Compare commits
209
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04ffe3b247 | ||
|
|
df5009c70b | ||
|
|
454d97f0cf | ||
|
|
4acb6e91ca | ||
|
|
45745a247a | ||
|
|
b175d6b2a3 | ||
|
|
c5c12aa738 | ||
|
|
7241400edd | ||
|
|
310fd0b187 | ||
|
|
db94743220 | ||
|
|
07aaf37fd4 | ||
|
|
65a808808f | ||
|
|
cca1aa1588 | ||
|
|
c9d4b773c9 | ||
|
|
e23f3102f4 | ||
|
|
ec89587c37 | ||
|
|
32d89806d7 | ||
|
|
2fd4e06b34 | ||
|
|
3cffdce1c1 | ||
|
|
6d2f4f4cdf | ||
|
|
865d7bd684 | ||
|
|
392d63231c | ||
|
|
7559f5ad70 | ||
|
|
605e8143e0 | ||
|
|
5b056cd337 | ||
|
|
6c350489b1 | ||
|
|
2ae63f4aa2 | ||
|
|
3d0233e3b0 | ||
|
|
64f2c3a465 | ||
|
|
0a12333448 | ||
|
|
9db54c9b19 | ||
|
|
34430e3514 | ||
|
|
99e44f2c23 | ||
|
|
7a0f2d9b30 | ||
|
|
4bf310f7ca | ||
|
|
8b9fbe701d | ||
|
|
0c5be023e4 | ||
|
|
86e87a8789 | ||
|
|
404e78a506 | ||
|
|
73563c7c25 | ||
|
|
326595b148 | ||
|
|
41a8468b08 | ||
|
|
ced2ecb6ba | ||
|
|
2d746b3a7e | ||
|
|
e6ac39de75 | ||
|
|
b76a0a6c91 | ||
|
|
9fdec3c2c8 | ||
|
|
760fe643e8 | ||
|
|
93af851dc5 | ||
|
|
fabb3e0734 | ||
|
|
9ca9a862a5 | ||
|
|
827dc9ff9f | ||
|
|
09b32ac9dd | ||
|
|
253684e280 | ||
|
|
f6d40ce841 | ||
|
|
36fb1bb7e4 | ||
|
|
4a82c1608f | ||
|
|
3efb3da007 | ||
|
|
11606fd9c6 | ||
|
|
a935db07ef | ||
|
|
98860a9549 | ||
|
|
7688742b2a | ||
|
|
b2efe4f83c | ||
|
|
f934b435fa | ||
|
|
3c121585da | ||
|
|
40acfbd2df | ||
|
|
0af61bf6ba | ||
|
|
7b2968f2ff | ||
|
|
a1c7b98f98 | ||
|
|
99ea16a969 | ||
|
|
ebe44d03a5 | ||
|
|
dcd2d50768 | ||
|
|
f11764c517 | ||
|
|
77c81b7468 | ||
|
|
7a5ccd3310 | ||
|
|
e4df6fcf8e | ||
|
|
b2be7f4e4f | ||
|
|
94beb21a43 | ||
|
|
30e05538b7 | ||
|
|
c884947ea8 | ||
|
|
61289a152d | ||
|
|
906550f9af | ||
|
|
c2aaa89b57 | ||
|
|
dde48e9414 | ||
|
|
b1608f41ad | ||
|
|
78d89e3d35 | ||
|
|
1309495218 | ||
|
|
c34a4c69e5 | ||
|
|
2f6cac0cf0 | ||
|
|
5c26df3a4f | ||
|
|
302323a64b | ||
|
|
b981fad920 | ||
|
|
8a2f2a5c2b | ||
|
|
e319735ed1 | ||
|
|
e7790490f1 | ||
|
|
a638978b75 | ||
|
|
4a08686e74 | ||
|
|
b3de2bd926 | ||
|
|
b81ec02984 | ||
|
|
de61c0c42b | ||
|
|
ecb4a1efa4 | ||
|
|
1b0093a483 | ||
|
|
06fc364ee1 | ||
|
|
094859bbc7 | ||
|
|
5e78386cdc | ||
|
|
c378afeff8 | ||
|
|
bf7002209e | ||
|
|
a3aa4bd189 | ||
|
|
5a0006f7ef | ||
|
|
9e2e73c070 | ||
|
|
c530e5d50f | ||
|
|
674720c6cd | ||
|
|
58c9e4b96d | ||
|
|
feb286379c | ||
|
|
cefe641586 | ||
|
|
664451c296 | ||
|
|
fd4ff8ca46 | ||
|
|
1bcfbdf287 | ||
|
|
4e45c1a6ab | ||
|
|
32fe80d164 | ||
|
|
6e93d42023 | ||
|
|
6f50867aa1 | ||
|
|
4fca60469d | ||
|
|
afcd824ae9 | ||
|
|
f84f279738 | ||
|
|
246624ad3c | ||
|
|
410444aead | ||
|
|
7522d3bde3 | ||
|
|
ed26b84177 | ||
|
|
ad4d12cf94 | ||
|
|
f6fd760e4e | ||
|
|
506a5260dc | ||
|
|
d4c90d696d | ||
|
|
be4d26a1b3 | ||
|
|
5c09614319 | ||
|
|
4c846332c5 | ||
|
|
a3a0cbf0f8 | ||
|
|
2c7101092a | ||
|
|
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 |
No files matched your search
@@ -0,0 +1,330 @@
|
|||||||
|
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 }}"
|
||||||
|
--verbose
|
||||||
|
)
|
||||||
|
|
||||||
|
has_all() {
|
||||||
|
for value in "$@"; do
|
||||||
|
if [[ -z "$value" ]]; then
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||||
|
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||||
|
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||||
|
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||||
|
export APPLE_API_KEY="$key_path"
|
||||||
|
echo "macOS signing enabled."
|
||||||
|
args+=(--signed)
|
||||||
|
else
|
||||||
|
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||||
|
fi
|
||||||
|
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||||
|
if has_all \
|
||||||
|
"$AZURE_TENANT_ID" \
|
||||||
|
"$AZURE_CLIENT_ID" \
|
||||||
|
"$AZURE_CLIENT_SECRET" \
|
||||||
|
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
|
||||||
|
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
|
||||||
|
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
|
||||||
|
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
|
||||||
|
echo "Windows signing enabled (Azure Trusted Signing)."
|
||||||
|
args+=(--signed)
|
||||||
|
else
|
||||||
|
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "Signing disabled for ${{ matrix.platform }}."
|
||||||
|
fi
|
||||||
|
|
||||||
|
bun run dist:desktop:artifact -- "${args[@]}"
|
||||||
|
|
||||||
|
- name: Collect release assets
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
mkdir -p release-publish
|
||||||
|
|
||||||
|
shopt -s nullglob
|
||||||
|
for pattern in \
|
||||||
|
"release/*.dmg" \
|
||||||
|
"release/*.zip" \
|
||||||
|
"release/*.AppImage" \
|
||||||
|
"release/*.exe" \
|
||||||
|
"release/*.blockmap" \
|
||||||
|
"release/latest*.yml"; do
|
||||||
|
for file in $pattern; do
|
||||||
|
cp "$file" release-publish/
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||||
|
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||||
|
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Upload build artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||||
|
path: release-publish/*
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
publish_cli:
|
||||||
|
name: Publish CLI to npm
|
||||||
|
needs: [preflight, build]
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ needs.preflight.outputs.ref }}
|
||||||
|
|
||||||
|
- name: Setup Bun
|
||||||
|
uses: oven-sh/setup-bun@v2
|
||||||
|
with:
|
||||||
|
bun-version-file: package.json
|
||||||
|
|
||||||
|
- name: Setup Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version-file: package.json
|
||||||
|
registry-url: https://registry.npmjs.org
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Build CLI package
|
||||||
|
run: bun run build --filter=@t3tools/web --filter=t3
|
||||||
|
|
||||||
|
- name: Publish CLI package
|
||||||
|
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||||
|
|
||||||
|
release:
|
||||||
|
name: Publish GitHub Release
|
||||||
|
needs: [preflight, build, publish_cli]
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- name: Download all desktop artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
pattern: desktop-*
|
||||||
|
merge-multiple: true
|
||||||
|
path: release-assets
|
||||||
|
|
||||||
|
- name: Publish release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||||
|
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||||
|
generate_release_notes: true
|
||||||
|
files: |
|
||||||
|
release-assets/*.dmg
|
||||||
|
release-assets/*.zip
|
||||||
|
release-assets/*.AppImage
|
||||||
|
release-assets/*.exe
|
||||||
|
release-assets/*.blockmap
|
||||||
|
release-assets/latest*.yml
|
||||||
|
fail_on_unmatched_files: true
|
||||||
@@ -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).
|
||||||
@@ -14,11 +18,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
|
|||||||
|
|
||||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||||
|
|
||||||
|
## Maintainability
|
||||||
|
|
||||||
|
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||||
|
|
||||||
## Package Roles
|
## Package Roles
|
||||||
|
|
||||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
- `apps/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. Keep this package schema-only — no runtime logic.
|
||||||
|
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||||
|
|
||||||
## 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,6 +89,12 @@ 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
|
||||||
|
|
||||||
@@ -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.18",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -14,15 +14,17 @@
|
|||||||
"smoke-test": "node scripts/smoke-test.mjs"
|
"smoke-test": "node scripts/smoke-test.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"electron": "40.6.0"
|
"effect": "catalog:",
|
||||||
|
"electron": "40.6.0",
|
||||||
|
"electron-updater": "^6.6.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
"@types/node": "^22.10.2",
|
"@t3tools/shared": "workspace:*",
|
||||||
"electronmon": "^2.0.2",
|
"@types/node": "catalog:",
|
||||||
"tsdown": "^0.20.3",
|
"tsdown": "catalog:",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "catalog:",
|
||||||
"vitest": "^4.0.0",
|
"vitest": "catalog:",
|
||||||
"wait-on": "^8.0.2"
|
"wait-on": "^8.0.2"
|
||||||
},
|
},
|
||||||
"productName": "T3 Code (Alpha)"
|
"productName": "T3 Code (Alpha)"
|
||||||
|
|||||||
@@ -1,43 +1,171 @@
|
|||||||
import { spawnSync } from "node:child_process";
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
|
import { watch } from "node:fs";
|
||||||
import electronmon from "electronmon";
|
import { join } from "node:path";
|
||||||
import waitOn from "wait-on";
|
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 ?? 5733);
|
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
|
||||||
const devServerUrl = `http://localhost:${port}`;
|
const devServerUrl = `http://localhost:${port}`;
|
||||||
|
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
|
||||||
|
const watchedDirectories = [
|
||||||
|
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||||
|
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||||
|
];
|
||||||
|
const forcedShutdownTimeoutMs = 1_500;
|
||||||
|
const restartDebounceMs = 120;
|
||||||
|
const childTreeGracePeriodMs = 1_200;
|
||||||
|
|
||||||
await waitOn({
|
await waitOn({
|
||||||
resources: [
|
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||||
`tcp:${port}`,
|
|
||||||
"file:dist-electron/main.js",
|
|
||||||
"file:dist-electron/preload.js",
|
|
||||||
"file:../server/dist/index.mjs",
|
|
||||||
],
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const childEnv = { ...process.env };
|
const childEnv = { ...process.env };
|
||||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||||
|
|
||||||
const monitor = await electronmon({
|
|
||||||
cwd: desktopDir,
|
|
||||||
args: ["dist-electron/main.js"],
|
|
||||||
env: {
|
|
||||||
...childEnv,
|
|
||||||
VITE_DEV_SERVER_URL: devServerUrl,
|
|
||||||
},
|
|
||||||
electronPath: resolveElectronPath(),
|
|
||||||
});
|
|
||||||
|
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
|
let restartTimer = null;
|
||||||
|
let currentApp = null;
|
||||||
|
let restartQueue = Promise.resolve();
|
||||||
|
const expectedExits = new WeakSet();
|
||||||
|
const watchers = [];
|
||||||
|
|
||||||
|
function killChildTreeByPid(pid, signal) {
|
||||||
|
if (process.platform === "win32" || typeof pid !== "number") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupStaleDevApps() {
|
||||||
|
if (process.platform === "win32") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||||
|
}
|
||||||
|
|
||||||
|
function startApp() {
|
||||||
|
if (shuttingDown || currentApp !== null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const app = spawn(
|
||||||
|
resolveElectronPath(),
|
||||||
|
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||||
|
{
|
||||||
|
cwd: desktopDir,
|
||||||
|
env: {
|
||||||
|
...childEnv,
|
||||||
|
VITE_DEV_SERVER_URL: devServerUrl,
|
||||||
|
},
|
||||||
|
stdio: "inherit",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
currentApp = app;
|
||||||
|
|
||||||
|
app.once("error", () => {
|
||||||
|
if (currentApp === app) {
|
||||||
|
currentApp = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shuttingDown) {
|
||||||
|
scheduleRestart();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.once("exit", () => {
|
||||||
|
if (currentApp === app) {
|
||||||
|
currentApp = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!shuttingDown && !expectedExits.has(app)) {
|
||||||
|
scheduleRestart();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopApp() {
|
||||||
|
const app = currentApp;
|
||||||
|
if (!app) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentApp = null;
|
||||||
|
expectedExits.add(app);
|
||||||
|
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
let settled = false;
|
||||||
|
|
||||||
|
const finish = () => {
|
||||||
|
if (settled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
settled = true;
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
app.once("exit", finish);
|
||||||
|
app.kill("SIGTERM");
|
||||||
|
killChildTreeByPid(app.pid, "TERM");
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (settled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
app.kill("SIGKILL");
|
||||||
|
killChildTreeByPid(app.pid, "KILL");
|
||||||
|
finish();
|
||||||
|
}, forcedShutdownTimeoutMs).unref();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleRestart() {
|
||||||
|
if (shuttingDown) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (restartTimer) {
|
||||||
|
clearTimeout(restartTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
restartTimer = setTimeout(() => {
|
||||||
|
restartTimer = null;
|
||||||
|
restartQueue = restartQueue
|
||||||
|
.catch(() => undefined)
|
||||||
|
.then(async () => {
|
||||||
|
await stopApp();
|
||||||
|
if (!shuttingDown) {
|
||||||
|
startApp();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, restartDebounceMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startWatchers() {
|
||||||
|
for (const { directory, files } of watchedDirectories) {
|
||||||
|
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
|
||||||
|
if (typeof filename !== "string" || !files.has(filename)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleRestart();
|
||||||
|
});
|
||||||
|
|
||||||
|
watchers.push(watcher);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function killChildTree(signal) {
|
function killChildTree(signal) {
|
||||||
if (process.platform === "win32") {
|
if (process.platform === "win32") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,20 +173,29 @@ async function shutdown(exitCode) {
|
|||||||
if (shuttingDown) return;
|
if (shuttingDown) return;
|
||||||
shuttingDown = true;
|
shuttingDown = true;
|
||||||
|
|
||||||
try {
|
if (restartTimer) {
|
||||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
clearTimeout(restartTimer);
|
||||||
} catch {
|
restartTimer = null;
|
||||||
// Best effort only; fallback process kill below handles stubborn children.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const watcher of watchers) {
|
||||||
|
watcher.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
await stopApp();
|
||||||
killChildTree("TERM");
|
killChildTree("TERM");
|
||||||
setTimeout(() => {
|
await new Promise((resolve) => {
|
||||||
killChildTree("KILL");
|
setTimeout(resolve, childTreeGracePeriodMs);
|
||||||
}, 1_200).unref();
|
});
|
||||||
|
killChildTree("KILL");
|
||||||
|
|
||||||
process.exit(exitCode);
|
process.exit(exitCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
startWatchers();
|
||||||
|
cleanupStaleDevApps();
|
||||||
|
startApp();
|
||||||
|
|
||||||
process.once("SIGINT", () => {
|
process.once("SIGINT", () => {
|
||||||
void shutdown(130);
|
void shutdown(130);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { execFileSync } from "node:child_process";
|
import * as ChildProcess from "node:child_process";
|
||||||
|
|
||||||
export function fixPath(): void {
|
export function fixPath(): void {
|
||||||
if (process.platform !== "darwin") return;
|
if (process.platform !== "darwin") return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||||
encoding: "utf8",
|
encoding: "utf8",
|
||||||
timeout: 5000,
|
timeout: 5000,
|
||||||
});
|
});
|
||||||
|
|||||||
+749
-79
File diff suppressed because it is too large.
Load diff
@@ -6,13 +6,17 @@ const CONFIRM_CHANNEL = "desktop:confirm";
|
|||||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||||
|
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||||
|
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||||
|
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||||
|
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||||
|
|
||||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||||
getWsUrl: () => wsUrl,
|
getWsUrl: () => wsUrl,
|
||||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||||
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
|
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||||
onMenuAction: (listener) => {
|
onMenuAction: (listener) => {
|
||||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||||
@@ -25,4 +29,18 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
|||||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||||
|
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||||
|
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||||
|
onUpdateState: (listener) => {
|
||||||
|
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||||
|
if (typeof state !== "object" || state === null) return;
|
||||||
|
listener(state as Parameters<typeof listener>[0]);
|
||||||
|
};
|
||||||
|
|
||||||
|
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||||
|
return () => {
|
||||||
|
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||||
|
};
|
||||||
|
},
|
||||||
} satisfies DesktopBridge);
|
} satisfies DesktopBridge);
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||||
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
const tempRoots: string[] = [];
|
||||||
|
|
||||||
|
function makeTempDir(): string {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
|
||||||
|
tempRoots.push(dir);
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const dir of tempRoots.splice(0)) {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("RotatingFileSink", () => {
|
||||||
|
it("rotates when writes exceed max bytes", () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
const logPath = path.join(dir, "desktop-main.log");
|
||||||
|
const sink = new RotatingFileSink({
|
||||||
|
filePath: logPath,
|
||||||
|
maxBytes: 10,
|
||||||
|
maxFiles: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
sink.write("12345");
|
||||||
|
sink.write("67890");
|
||||||
|
sink.write("abc");
|
||||||
|
|
||||||
|
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
|
||||||
|
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retains only maxFiles backups", () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
const logPath = path.join(dir, "server-child.log");
|
||||||
|
const sink = new RotatingFileSink({
|
||||||
|
filePath: logPath,
|
||||||
|
maxBytes: 4,
|
||||||
|
maxFiles: 2,
|
||||||
|
});
|
||||||
|
|
||||||
|
sink.write("aaaa");
|
||||||
|
sink.write("bbbb");
|
||||||
|
sink.write("cccc");
|
||||||
|
sink.write("dddd");
|
||||||
|
|
||||||
|
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
|
||||||
|
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
|
||||||
|
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("prunes stale backups above maxFiles on startup", () => {
|
||||||
|
const dir = makeTempDir();
|
||||||
|
const logPath = path.join(dir, "desktop-main.log");
|
||||||
|
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
|
||||||
|
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
|
||||||
|
|
||||||
|
const sink = new RotatingFileSink({
|
||||||
|
filePath: logPath,
|
||||||
|
maxBytes: 16,
|
||||||
|
maxFiles: 2,
|
||||||
|
});
|
||||||
|
sink.write("hello");
|
||||||
|
|
||||||
|
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
createInitialDesktopUpdateState,
|
||||||
|
reduceDesktopUpdateStateOnCheckFailure,
|
||||||
|
reduceDesktopUpdateStateOnCheckStart,
|
||||||
|
reduceDesktopUpdateStateOnDownloadComplete,
|
||||||
|
reduceDesktopUpdateStateOnDownloadFailure,
|
||||||
|
reduceDesktopUpdateStateOnDownloadProgress,
|
||||||
|
reduceDesktopUpdateStateOnDownloadStart,
|
||||||
|
reduceDesktopUpdateStateOnInstallFailure,
|
||||||
|
reduceDesktopUpdateStateOnNoUpdate,
|
||||||
|
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||||
|
} from "./updateMachine";
|
||||||
|
|
||||||
|
describe("updateMachine", () => {
|
||||||
|
it("clears transient errors when a check starts", () => {
|
||||||
|
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||||
|
{
|
||||||
|
...createInitialDesktopUpdateState("1.0.0"),
|
||||||
|
enabled: true,
|
||||||
|
status: "error",
|
||||||
|
message: "network",
|
||||||
|
errorContext: "check",
|
||||||
|
canRetry: true,
|
||||||
|
},
|
||||||
|
"2026-03-04T00:00:00.000Z",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.status).toBe("checking");
|
||||||
|
expect(state.message).toBeNull();
|
||||||
|
expect(state.errorContext).toBeNull();
|
||||||
|
expect(state.canRetry).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("records a check failure without exposing an action", () => {
|
||||||
|
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||||
|
{
|
||||||
|
...createInitialDesktopUpdateState("1.0.0"),
|
||||||
|
enabled: true,
|
||||||
|
status: "checking",
|
||||||
|
},
|
||||||
|
"network unavailable",
|
||||||
|
"2026-03-04T00:00:00.000Z",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.status).toBe("error");
|
||||||
|
expect(state.errorContext).toBe("check");
|
||||||
|
expect(state.canRetry).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves available version on download failure for retry", () => {
|
||||||
|
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||||
|
{
|
||||||
|
...createInitialDesktopUpdateState("1.0.0"),
|
||||||
|
enabled: true,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
downloadPercent: 43,
|
||||||
|
},
|
||||||
|
"checksum mismatch",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.status).toBe("available");
|
||||||
|
expect(state.availableVersion).toBe("1.1.0");
|
||||||
|
expect(state.errorContext).toBe("download");
|
||||||
|
expect(state.canRetry).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("transitions to downloaded and then preserves install retry state", () => {
|
||||||
|
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||||
|
{
|
||||||
|
...createInitialDesktopUpdateState("1.0.0"),
|
||||||
|
enabled: true,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
},
|
||||||
|
"1.1.0",
|
||||||
|
);
|
||||||
|
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
|
||||||
|
|
||||||
|
expect(downloaded.status).toBe("downloaded");
|
||||||
|
expect(downloaded.downloadedVersion).toBe("1.1.0");
|
||||||
|
expect(failedInstall.status).toBe("downloaded");
|
||||||
|
expect(failedInstall.errorContext).toBe("install");
|
||||||
|
expect(failedInstall.canRetry).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears stale download state when no update is available", () => {
|
||||||
|
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||||
|
{
|
||||||
|
...createInitialDesktopUpdateState("1.0.0"),
|
||||||
|
enabled: true,
|
||||||
|
status: "error",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
downloadedVersion: "1.1.0",
|
||||||
|
message: "old failure",
|
||||||
|
errorContext: "download",
|
||||||
|
canRetry: true,
|
||||||
|
},
|
||||||
|
"2026-03-04T00:00:00.000Z",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(state.status).toBe("up-to-date");
|
||||||
|
expect(state.availableVersion).toBeNull();
|
||||||
|
expect(state.downloadedVersion).toBeNull();
|
||||||
|
expect(state.message).toBeNull();
|
||||||
|
expect(state.errorContext).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tracks available, download start, and progress cleanly", () => {
|
||||||
|
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||||
|
{
|
||||||
|
...createInitialDesktopUpdateState("1.0.0"),
|
||||||
|
enabled: true,
|
||||||
|
status: "checking",
|
||||||
|
},
|
||||||
|
"1.1.0",
|
||||||
|
"2026-03-04T00:00:00.000Z",
|
||||||
|
);
|
||||||
|
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||||
|
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||||
|
|
||||||
|
expect(available.status).toBe("available");
|
||||||
|
expect(downloading.status).toBe("downloading");
|
||||||
|
expect(downloading.downloadPercent).toBe(0);
|
||||||
|
expect(progress.downloadPercent).toBe(55.5);
|
||||||
|
expect(progress.errorContext).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||||
|
|
||||||
|
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
enabled: false,
|
||||||
|
status: "disabled",
|
||||||
|
currentVersion,
|
||||||
|
availableVersion: null,
|
||||||
|
downloadedVersion: null,
|
||||||
|
downloadPercent: null,
|
||||||
|
checkedAt: null,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnCheckStart(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
checkedAt: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "checking",
|
||||||
|
checkedAt,
|
||||||
|
message: null,
|
||||||
|
downloadPercent: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnCheckFailure(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
message: string,
|
||||||
|
checkedAt: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "error",
|
||||||
|
message,
|
||||||
|
checkedAt,
|
||||||
|
downloadPercent: null,
|
||||||
|
errorContext: "check",
|
||||||
|
canRetry: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
version: string,
|
||||||
|
checkedAt: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "available",
|
||||||
|
availableVersion: version,
|
||||||
|
downloadedVersion: null,
|
||||||
|
downloadPercent: null,
|
||||||
|
checkedAt,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnNoUpdate(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
checkedAt: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "up-to-date",
|
||||||
|
availableVersion: null,
|
||||||
|
downloadedVersion: null,
|
||||||
|
downloadPercent: null,
|
||||||
|
checkedAt,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnDownloadStart(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "downloading",
|
||||||
|
downloadPercent: 0,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnDownloadFailure(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
message: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: nextStatusAfterDownloadFailure(state),
|
||||||
|
message,
|
||||||
|
downloadPercent: null,
|
||||||
|
errorContext: "download",
|
||||||
|
canRetry: getCanRetryAfterDownloadFailure(state),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnDownloadProgress(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
percent: number,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "downloading",
|
||||||
|
downloadPercent: percent,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnDownloadComplete(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
version: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "downloaded",
|
||||||
|
availableVersion: version,
|
||||||
|
downloadedVersion: version,
|
||||||
|
downloadPercent: 100,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reduceDesktopUpdateStateOnInstallFailure(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
message: string,
|
||||||
|
): DesktopUpdateState {
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
status: "downloaded",
|
||||||
|
message,
|
||||||
|
errorContext: "install",
|
||||||
|
canRetry: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import {
|
||||||
|
getCanRetryAfterDownloadFailure,
|
||||||
|
getAutoUpdateDisabledReason,
|
||||||
|
nextStatusAfterDownloadFailure,
|
||||||
|
shouldBroadcastDownloadProgress,
|
||||||
|
} from "./updateState";
|
||||||
|
|
||||||
|
const baseState: DesktopUpdateState = {
|
||||||
|
enabled: true,
|
||||||
|
status: "idle",
|
||||||
|
currentVersion: "1.0.0",
|
||||||
|
availableVersion: null,
|
||||||
|
downloadedVersion: null,
|
||||||
|
downloadPercent: null,
|
||||||
|
checkedAt: null,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("shouldBroadcastDownloadProgress", () => {
|
||||||
|
it("broadcasts the first downloading progress update", () => {
|
||||||
|
expect(
|
||||||
|
shouldBroadcastDownloadProgress(
|
||||||
|
{ ...baseState, status: "downloading", downloadPercent: null },
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("skips progress updates within the same 10% bucket", () => {
|
||||||
|
expect(
|
||||||
|
shouldBroadcastDownloadProgress(
|
||||||
|
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
|
||||||
|
18.7,
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("broadcasts progress updates when a new 10% bucket is reached", () => {
|
||||||
|
expect(
|
||||||
|
shouldBroadcastDownloadProgress(
|
||||||
|
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
|
||||||
|
20.1,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("broadcasts progress updates when a retry resets the download percentage", () => {
|
||||||
|
expect(
|
||||||
|
shouldBroadcastDownloadProgress(
|
||||||
|
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
|
||||||
|
0.2,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getAutoUpdateDisabledReason", () => {
|
||||||
|
it("reports development builds as disabled", () => {
|
||||||
|
expect(
|
||||||
|
getAutoUpdateDisabledReason({
|
||||||
|
isDevelopment: true,
|
||||||
|
isPackaged: false,
|
||||||
|
platform: "darwin",
|
||||||
|
appImage: undefined,
|
||||||
|
disabledByEnv: false,
|
||||||
|
}),
|
||||||
|
).toContain("packaged production builds");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports env-disabled auto updates", () => {
|
||||||
|
expect(
|
||||||
|
getAutoUpdateDisabledReason({
|
||||||
|
isDevelopment: false,
|
||||||
|
isPackaged: true,
|
||||||
|
platform: "darwin",
|
||||||
|
appImage: undefined,
|
||||||
|
disabledByEnv: true,
|
||||||
|
}),
|
||||||
|
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports linux non-AppImage builds as disabled", () => {
|
||||||
|
expect(
|
||||||
|
getAutoUpdateDisabledReason({
|
||||||
|
isDevelopment: false,
|
||||||
|
isPackaged: true,
|
||||||
|
platform: "linux",
|
||||||
|
appImage: undefined,
|
||||||
|
disabledByEnv: false,
|
||||||
|
}),
|
||||||
|
).toContain("AppImage");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("nextStatusAfterDownloadFailure", () => {
|
||||||
|
it("returns available when an update version is still known", () => {
|
||||||
|
expect(
|
||||||
|
nextStatusAfterDownloadFailure({
|
||||||
|
...baseState,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
}),
|
||||||
|
).toBe("available");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns error when no update version can be retried", () => {
|
||||||
|
expect(
|
||||||
|
nextStatusAfterDownloadFailure({
|
||||||
|
...baseState,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: null,
|
||||||
|
}),
|
||||||
|
).toBe("error");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getCanRetryAfterDownloadFailure", () => {
|
||||||
|
it("returns true when an available version is still present", () => {
|
||||||
|
expect(
|
||||||
|
getCanRetryAfterDownloadFailure({
|
||||||
|
...baseState,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when no version is available to retry", () => {
|
||||||
|
expect(
|
||||||
|
getCanRetryAfterDownloadFailure({
|
||||||
|
...baseState,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: null,
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
export function shouldBroadcastDownloadProgress(
|
||||||
|
currentState: DesktopUpdateState,
|
||||||
|
nextPercent: number,
|
||||||
|
): boolean {
|
||||||
|
if (currentState.status !== "downloading") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentPercent = currentState.downloadPercent;
|
||||||
|
if (currentPercent === null) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousStep = Math.floor(currentPercent / 10);
|
||||||
|
const nextStep = Math.floor(nextPercent / 10);
|
||||||
|
return nextStep !== previousStep || nextPercent === 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function nextStatusAfterDownloadFailure(
|
||||||
|
currentState: DesktopUpdateState,
|
||||||
|
): DesktopUpdateState["status"] {
|
||||||
|
return currentState.availableVersion ? "available" : "error";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
|
||||||
|
return currentState.availableVersion !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAutoUpdateDisabledReason(args: {
|
||||||
|
isDevelopment: boolean;
|
||||||
|
isPackaged: boolean;
|
||||||
|
platform: NodeJS.Platform;
|
||||||
|
appImage?: string | undefined;
|
||||||
|
disabledByEnv: boolean;
|
||||||
|
}): string | null {
|
||||||
|
if (args.isDevelopment || !args.isPackaged) {
|
||||||
|
return "Automatic updates are only available in packaged production builds.";
|
||||||
|
}
|
||||||
|
if (args.disabledByEnv) {
|
||||||
|
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
|
||||||
|
}
|
||||||
|
if (args.platform === "linux" && !args.appImage) {
|
||||||
|
return "Automatic updates on Linux require running the AppImage build.";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
|||||||
...shared,
|
...shared,
|
||||||
entry: ["src/main.ts"],
|
entry: ["src/main.ts"],
|
||||||
clean: true,
|
clean: true,
|
||||||
noExternal: ["@t3tools/contracts"],
|
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
...shared,
|
...shared,
|
||||||
|
|||||||
@@ -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, {
|
||||||
@@ -227,8 +230,17 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
|||||||
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),
|
||||||
@@ -240,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),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
+13
-10
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "t3",
|
"name": "t3",
|
||||||
"version": "0.1.0",
|
"version": "0.0.0-alpha.18",
|
||||||
"bin": {
|
"bin": {
|
||||||
"t3": "./dist/index.mjs"
|
"t3": "./dist/index.mjs"
|
||||||
},
|
},
|
||||||
@@ -8,10 +8,9 @@
|
|||||||
"dist"
|
"dist"
|
||||||
],
|
],
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.mjs",
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
"dev": "bun run src/index.ts",
|
||||||
"build": "tsdown && node scripts/bundle-client.ts",
|
"build": "node scripts/cli.ts build",
|
||||||
"start": "node dist/index.mjs",
|
"start": "node dist/index.mjs",
|
||||||
"prepare": "effect-language-service patch",
|
"prepare": "effect-language-service patch",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
@@ -27,15 +26,19 @@
|
|||||||
"ws": "^8.18.0"
|
"ws": "^8.18.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@effect/language-service": "0.75.1",
|
"@effect/language-service": "catalog:",
|
||||||
"@effect/vitest": "catalog:",
|
"@effect/vitest": "catalog:",
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
|
"@t3tools/shared": "workspace:*",
|
||||||
"@t3tools/web": "workspace:*",
|
"@t3tools/web": "workspace:*",
|
||||||
"@types/bun": "^1.3.9",
|
"@types/bun": "catalog:",
|
||||||
"@types/node": "^22.10.2",
|
"@types/node": "catalog:",
|
||||||
"@types/ws": "^8.5.13",
|
"@types/ws": "^8.5.13",
|
||||||
"tsdown": "^0.20.3",
|
"tsdown": "catalog:",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "catalog:",
|
||||||
"vitest": "^4.0.0"
|
"vitest": "catalog:"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^22.13 || ^23.4 || >=24.10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
/**
|
|
||||||
* Copies the built web app into dist/client/ so the published npm package
|
|
||||||
* includes the web UI. This runs as a post-build step.
|
|
||||||
*/
|
|
||||||
import * as fs from "node:fs";
|
|
||||||
import * as path from "node:path";
|
|
||||||
|
|
||||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
|
||||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
|
||||||
|
|
||||||
if (!fs.existsSync(webDist)) {
|
|
||||||
console.log(
|
|
||||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
|
||||||
);
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.cpSync(webDist, target, { recursive: true });
|
|
||||||
console.log("✓ Bundled web app into dist/client");
|
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
|
||||||
|
import { Command, Flag } from "effect/unstable/cli";
|
||||||
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
|
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||||
|
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||||
|
import serverPackageJson from "../package.json" with { type: "json" };
|
||||||
|
|
||||||
|
class CliError extends Data.TaggedError("CliError")<{
|
||||||
|
readonly message: string;
|
||||||
|
readonly cause?: unknown;
|
||||||
|
}> {}
|
||||||
|
|
||||||
|
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||||
|
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||||
|
);
|
||||||
|
|
||||||
|
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||||
|
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const child = yield* spawner.spawn(command);
|
||||||
|
const exitCode = yield* child.exitCode;
|
||||||
|
|
||||||
|
if (exitCode !== 0) {
|
||||||
|
return yield* new CliError({
|
||||||
|
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// build subcommand
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const buildCmd = Command.make(
|
||||||
|
"build",
|
||||||
|
{
|
||||||
|
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||||
|
},
|
||||||
|
(config) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const repoRoot = yield* RepoRoot;
|
||||||
|
const serverDir = path.join(repoRoot, "apps/server");
|
||||||
|
|
||||||
|
yield* Effect.log("[cli] Running tsdown...");
|
||||||
|
yield* runCommand(
|
||||||
|
ChildProcess.make({
|
||||||
|
cwd: serverDir,
|
||||||
|
stdout: config.verbose ? "inherit" : "ignore",
|
||||||
|
stderr: "inherit",
|
||||||
|
})`bun tsdown`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||||
|
const clientTarget = path.join(serverDir, "dist/client");
|
||||||
|
|
||||||
|
if (yield* fs.exists(webDist)) {
|
||||||
|
yield* fs.copy(webDist, clientTarget);
|
||||||
|
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||||
|
} else {
|
||||||
|
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// publish subcommand
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const publishCmd = Command.make(
|
||||||
|
"publish",
|
||||||
|
{
|
||||||
|
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
|
||||||
|
access: Flag.string("access").pipe(Flag.withDefault("public")),
|
||||||
|
appVersion: Flag.string("app-version").pipe(Flag.optional),
|
||||||
|
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
|
||||||
|
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||||
|
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||||
|
},
|
||||||
|
(config) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const path = yield* Path.Path;
|
||||||
|
const fs = yield* FileSystem.FileSystem;
|
||||||
|
const repoRoot = yield* RepoRoot;
|
||||||
|
const serverDir = path.join(repoRoot, "apps/server");
|
||||||
|
const packageJsonPath = path.join(serverDir, "package.json");
|
||||||
|
const backupPath = `${packageJsonPath}.bak`;
|
||||||
|
|
||||||
|
// Assert build assets exist
|
||||||
|
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||||
|
const abs = path.join(serverDir, relPath);
|
||||||
|
if (!(yield* fs.exists(abs))) {
|
||||||
|
return yield* new CliError({
|
||||||
|
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* Effect.acquireUseRelease(
|
||||||
|
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const original = yield* fs.readFileString(packageJsonPath);
|
||||||
|
yield* fs.writeFileString(backupPath, original);
|
||||||
|
|
||||||
|
// Build package.json for publish
|
||||||
|
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||||
|
const pkg = {
|
||||||
|
name: serverPackageJson.name,
|
||||||
|
type: serverPackageJson.type,
|
||||||
|
version,
|
||||||
|
engines: serverPackageJson.engines,
|
||||||
|
files: serverPackageJson.files,
|
||||||
|
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Resolve catalog: entries in production dependencies
|
||||||
|
pkg.dependencies = resolveCatalogDependencies(
|
||||||
|
pkg.dependencies,
|
||||||
|
rootPackageJson.workspaces.catalog,
|
||||||
|
"apps/server dependencies",
|
||||||
|
);
|
||||||
|
|
||||||
|
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||||
|
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||||
|
}),
|
||||||
|
// Use: npm publish
|
||||||
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||||
|
if (config.provenance) args.push("--provenance");
|
||||||
|
if (config.dryRun) args.push("--dry-run");
|
||||||
|
|
||||||
|
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||||
|
yield* runCommand(
|
||||||
|
ChildProcess.make("npm", [...args], {
|
||||||
|
cwd: serverDir,
|
||||||
|
stdout: config.verbose ? "inherit" : "ignore",
|
||||||
|
stderr: "inherit",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
// Release: restore
|
||||||
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* fs.rename(backupPath, packageJsonPath);
|
||||||
|
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// root command
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const cli = Command.make("cli").pipe(
|
||||||
|
Command.withDescription("T3 server build & publish CLI."),
|
||||||
|
Command.withSubcommands([buildCmd, publishCmd]),
|
||||||
|
);
|
||||||
|
|
||||||
|
Command.run(cli, { version: "0.0.0" }).pipe(
|
||||||
|
Effect.scoped,
|
||||||
|
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
|
||||||
|
NodeRuntime.runMain,
|
||||||
|
);
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,17 +1,44 @@
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { Cause } from "effect";
|
||||||
|
import { ManagedRuntime, ServiceMap } from "effect";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { ProviderSessionId } from "@t3tools/contracts";
|
import { ProviderSessionId } from "@t3tools/contracts";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
CodexAppServerManager,
|
CodexAppServerManager,
|
||||||
classifyCodexStderrLine,
|
classifyCodexStderrLine,
|
||||||
isRecoverableThreadResumeError,
|
isRecoverableThreadResumeError,
|
||||||
|
messageFromCodexProcessCause,
|
||||||
normalizeCodexModelSlug,
|
normalizeCodexModelSlug,
|
||||||
} from "./codexAppServerManager";
|
} from "./codexAppServerManager";
|
||||||
|
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
|
|
||||||
|
let runtime: ManagedRuntime.ManagedRuntime<NodeServices.NodeServices, never> | null = null;
|
||||||
|
let services: ServiceMap.ServiceMap<NodeServices.NodeServices> | null = null;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
runtime = ManagedRuntime.make(NodeServices.layer);
|
||||||
|
services = await runtime.services();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
services = null;
|
||||||
|
if (runtime) {
|
||||||
|
await runtime.dispose();
|
||||||
|
}
|
||||||
|
runtime = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
function createManager() {
|
||||||
|
if (!services) {
|
||||||
|
throw new Error("Test runtime services not initialized.");
|
||||||
|
}
|
||||||
|
return new CodexAppServerManager(services);
|
||||||
|
}
|
||||||
|
|
||||||
function createSendTurnHarness() {
|
function createSendTurnHarness() {
|
||||||
const manager = new CodexAppServerManager();
|
const manager = createManager();
|
||||||
const context = {
|
const context = {
|
||||||
session: {
|
session: {
|
||||||
sessionId: "sess_1",
|
sessionId: "sess_1",
|
||||||
@@ -47,7 +74,7 @@ function createSendTurnHarness() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createThreadControlHarness() {
|
function createThreadControlHarness() {
|
||||||
const manager = new CodexAppServerManager();
|
const manager = createManager();
|
||||||
const context = {
|
const context = {
|
||||||
session: {
|
session: {
|
||||||
sessionId: "sess_1",
|
sessionId: "sess_1",
|
||||||
@@ -146,9 +173,15 @@ describe("isRecoverableThreadResumeError", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("messageFromCodexProcessCause", () => {
|
||||||
|
it("extracts the underlying error message from an effect cause", () => {
|
||||||
|
expect(messageFromCodexProcessCause(Cause.fail(new Error("boom")))).toBe("boom");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("startSession", () => {
|
describe("startSession", () => {
|
||||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||||
const manager = new CodexAppServerManager();
|
const manager = createManager();
|
||||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||||
manager.on("event", (event) => {
|
manager.on("event", (event) => {
|
||||||
events.push({
|
events.push({
|
||||||
@@ -191,10 +224,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 +272,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",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
|
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import readline from "node:readline";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
@@ -14,11 +12,14 @@ 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,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
|
import type * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
import { Cause, Effect, Exit, ServiceMap, Scope, Stream } from "effect";
|
||||||
|
import type { ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
import { makeRuntimeCommand, spawnManagedCommand } from "./processRunner";
|
||||||
|
|
||||||
type PendingRequestKey = string;
|
type PendingRequestKey = string;
|
||||||
|
|
||||||
@@ -41,8 +42,8 @@ interface PendingApprovalRequest {
|
|||||||
|
|
||||||
interface CodexSessionContext {
|
interface CodexSessionContext {
|
||||||
session: ProviderSession;
|
session: ProviderSession;
|
||||||
child: ChildProcessWithoutNullStreams;
|
child: ChildProcessSpawner.ChildProcessHandle;
|
||||||
output: readline.Interface;
|
scope: Scope.Closeable;
|
||||||
pending: Map<PendingRequestKey, PendingRequest>;
|
pending: Map<PendingRequestKey, PendingRequest>;
|
||||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||||
nextRequestId: number;
|
nextRequestId: number;
|
||||||
@@ -71,6 +72,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[];
|
||||||
@@ -144,12 +153,32 @@ export function isRecoverableThreadResumeError(error: unknown): boolean {
|
|||||||
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
|
return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function messageFromCodexProcessCause(cause: Cause.Cause<unknown>): string {
|
||||||
|
const squashed = Cause.squash(cause);
|
||||||
|
return squashed instanceof Error ? squashed.message : "codex app-server process errored.";
|
||||||
|
}
|
||||||
|
|
||||||
export interface CodexAppServerManagerEvents {
|
export interface CodexAppServerManagerEvents {
|
||||||
event: [event: ProviderEvent];
|
event: [event: ProviderEvent];
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
|
||||||
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
|
private readonly sessions = new Map<ProviderSessionId, CodexSessionContext>();
|
||||||
|
private readonly runPromise: <A, E>(
|
||||||
|
effect: Effect.Effect<A, E, NodeServices.NodeServices>,
|
||||||
|
options?: Effect.RunOptions | undefined,
|
||||||
|
) => Promise<A>;
|
||||||
|
|
||||||
|
constructor(services?: ServiceMap.ServiceMap<NodeServices.NodeServices>) {
|
||||||
|
super();
|
||||||
|
this.runPromise = services
|
||||||
|
? Effect.runPromiseWith(services)
|
||||||
|
: ((effect, options) =>
|
||||||
|
Effect.runPromise(
|
||||||
|
effect as unknown as Effect.Effect<unknown, never>,
|
||||||
|
options,
|
||||||
|
)) as typeof this.runPromise;
|
||||||
|
}
|
||||||
|
|
||||||
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
async startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
|
||||||
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
const sessionId = ProviderSessionId.makeUnsafe(randomUUID());
|
||||||
@@ -171,20 +200,23 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
|
|
||||||
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
const codexBinaryPath = input.codexBinaryPath ?? "codex";
|
||||||
const codexHomePath = input.codexHomePath;
|
const codexHomePath = input.codexHomePath;
|
||||||
const child = spawn(codexBinaryPath, ["app-server"], {
|
const managedProcess = await this.runPromise(
|
||||||
cwd: resolvedCwd,
|
spawnManagedCommand(
|
||||||
env: {
|
makeRuntimeCommand(codexBinaryPath, ["app-server"], {
|
||||||
...process.env,
|
cwd: resolvedCwd,
|
||||||
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
env: {
|
||||||
},
|
...process.env,
|
||||||
stdio: ["pipe", "pipe", "pipe"],
|
...(codexHomePath ? { CODEX_HOME: codexHomePath } : {}),
|
||||||
});
|
},
|
||||||
const output = readline.createInterface({ input: child.stdout });
|
extendEnv: false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
context = {
|
context = {
|
||||||
session,
|
session,
|
||||||
child,
|
child: managedProcess.handle,
|
||||||
output,
|
scope: managedProcess.scope,
|
||||||
pending: new Map(),
|
pending: new Map(),
|
||||||
pendingApprovals: new Map(),
|
pendingApprovals: new Map(),
|
||||||
nextRequestId: 1,
|
nextRequestId: 1,
|
||||||
@@ -192,7 +224,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.sessions.set(sessionId, context);
|
this.sessions.set(sessionId, context);
|
||||||
this.attachProcessListeners(context);
|
await this.attachProcessListeners(context);
|
||||||
|
|
||||||
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
|
||||||
|
|
||||||
@@ -207,7 +239,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
this.writeMessage(context, { method: "initialized" });
|
await this.writeMessage(context, { method: "initialized" });
|
||||||
|
|
||||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||||
const sessionOverrides = {
|
const sessionOverrides = {
|
||||||
@@ -290,7 +322,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 +342,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,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -423,7 +455,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
context.pendingApprovals.delete(requestId);
|
context.pendingApprovals.delete(requestId);
|
||||||
this.writeMessage(context, {
|
await this.writeMessage(context, {
|
||||||
id: pendingRequest.jsonRpcId,
|
id: pendingRequest.jsonRpcId,
|
||||||
result: {
|
result: {
|
||||||
decision,
|
decision,
|
||||||
@@ -464,12 +496,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
context.pending.clear();
|
context.pending.clear();
|
||||||
context.pendingApprovals.clear();
|
context.pendingApprovals.clear();
|
||||||
|
void this.runPromise(Scope.close(context.scope, Exit.void)).catch(() => undefined);
|
||||||
context.output.close();
|
|
||||||
|
|
||||||
if (!context.child.killed) {
|
|
||||||
context.child.kill();
|
|
||||||
}
|
|
||||||
|
|
||||||
this.updateSession(context, {
|
this.updateSession(context, {
|
||||||
status: "closed",
|
status: "closed",
|
||||||
@@ -508,47 +535,71 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
private attachProcessListeners(context: CodexSessionContext): void {
|
private async attachProcessListeners(context: CodexSessionContext): Promise<void> {
|
||||||
context.output.on("line", (line) => {
|
await this.runPromise(
|
||||||
this.handleStdoutLine(context, line);
|
Effect.gen(
|
||||||
});
|
function* (this: CodexAppServerManager) {
|
||||||
|
yield* Effect.forkScoped(
|
||||||
|
Stream.runForEach(Stream.splitLines(Stream.decodeText(context.child.stdout)), (line) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
this.handleStdoutLine(context, line);
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
context.child.stderr.on("data", (chunk: Buffer) => {
|
yield* Effect.forkScoped(
|
||||||
const raw = chunk.toString();
|
Stream.runForEach(Stream.decodeText(context.child.stderr), (raw) =>
|
||||||
const lines = raw.split(/\r?\n/g);
|
Effect.sync(() => {
|
||||||
for (const rawLine of lines) {
|
const lines = raw.split(/\r?\n/g);
|
||||||
const classified = classifyCodexStderrLine(rawLine);
|
for (const rawLine of lines) {
|
||||||
if (!classified) {
|
const classified = classifyCodexStderrLine(rawLine);
|
||||||
continue;
|
if (!classified) {
|
||||||
}
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
this.emitErrorEvent(context, "process/stderr", classified.message);
|
this.emitErrorEvent(context, "process/stderr", classified.message);
|
||||||
}
|
}
|
||||||
});
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
context.child.on("error", (error) => {
|
yield* Effect.forkScoped(
|
||||||
const message = error.message || "codex app-server process errored.";
|
Effect.matchCauseEffect(context.child.exitCode, {
|
||||||
this.updateSession(context, {
|
onFailure: (cause) =>
|
||||||
status: "error",
|
Effect.sync(() => {
|
||||||
lastError: message,
|
if (context.stopping) {
|
||||||
});
|
return;
|
||||||
this.emitErrorEvent(context, "process/error", message);
|
}
|
||||||
});
|
|
||||||
|
|
||||||
context.child.on("exit", (code, signal) => {
|
const message = messageFromCodexProcessCause(cause);
|
||||||
if (context.stopping) {
|
this.updateSession(context, {
|
||||||
return;
|
status: "error",
|
||||||
}
|
activeTurnId: undefined,
|
||||||
|
lastError: message,
|
||||||
|
});
|
||||||
|
this.emitErrorEvent(context, "process/error", message);
|
||||||
|
this.sessions.delete(context.session.sessionId);
|
||||||
|
}),
|
||||||
|
onSuccess: (code) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
if (context.stopping) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const message = `codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`;
|
const message = `codex app-server exited (code=${code}).`;
|
||||||
this.updateSession(context, {
|
this.updateSession(context, {
|
||||||
status: "closed",
|
status: "closed",
|
||||||
activeTurnId: undefined,
|
activeTurnId: undefined,
|
||||||
lastError: code === 0 ? context.session.lastError : message,
|
lastError: code === 0 ? context.session.lastError : message,
|
||||||
});
|
});
|
||||||
this.emitLifecycleEvent(context, "session/exited", message);
|
this.emitLifecycleEvent(context, "session/exited", message);
|
||||||
this.sessions.delete(context.session.sessionId);
|
this.sessions.delete(context.session.sessionId);
|
||||||
});
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}.bind(this),
|
||||||
|
).pipe(Scope.provide(context.scope)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
private handleStdoutLine(context: CodexSessionContext, line: string): void {
|
||||||
@@ -704,19 +755,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (request.method === "item/tool/requestUserInput") {
|
if (request.method === "item/tool/requestUserInput") {
|
||||||
this.writeMessage(context, {
|
void this.writeMessage(context, {
|
||||||
id: request.id,
|
id: request.id,
|
||||||
result: { answers: {} },
|
result: { answers: {} },
|
||||||
|
}).catch((error) => {
|
||||||
|
this.emitErrorEvent(
|
||||||
|
context,
|
||||||
|
"protocol/writeError",
|
||||||
|
error instanceof Error ? error.message : String(error),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.writeMessage(context, {
|
void this.writeMessage(context, {
|
||||||
id: request.id,
|
id: request.id,
|
||||||
error: {
|
error: {
|
||||||
code: -32601,
|
code: -32601,
|
||||||
message: `Unsupported server request: ${request.method}`,
|
message: `Unsupported server request: ${request.method}`,
|
||||||
},
|
},
|
||||||
|
}).catch((error) => {
|
||||||
|
this.emitErrorEvent(
|
||||||
|
context,
|
||||||
|
"protocol/writeError",
|
||||||
|
error instanceof Error ? error.message : String(error),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -759,23 +822,30 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
|||||||
resolve,
|
resolve,
|
||||||
reject,
|
reject,
|
||||||
});
|
});
|
||||||
this.writeMessage(context, {
|
void this.writeMessage(context, {
|
||||||
method,
|
method,
|
||||||
id,
|
id,
|
||||||
params,
|
params,
|
||||||
|
}).catch((error) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
context.pending.delete(String(id));
|
||||||
|
reject(error instanceof Error ? error : new Error(String(error)));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
return result as TResponse;
|
return result as TResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
private writeMessage(context: CodexSessionContext, message: unknown): void {
|
private async writeMessage(context: CodexSessionContext, message: unknown): Promise<void> {
|
||||||
const encoded = JSON.stringify(message);
|
const encoded = JSON.stringify(message);
|
||||||
if (!context.child.stdin.writable) {
|
if (context.stopping) {
|
||||||
throw new Error("Cannot write to codex app-server stdin.");
|
throw new Error("Cannot write to codex app-server stdin.");
|
||||||
}
|
}
|
||||||
|
await this.runPromise(
|
||||||
context.child.stdin.write(`${encoded}\n`);
|
Stream.run(context.child.stdin)(Stream.make(new TextEncoder().encode(`${encoded}\n`))).pipe(
|
||||||
|
Scope.provide(context.scope),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||||
|
|||||||
+22
-63
@@ -1,13 +1,12 @@
|
|||||||
/**
|
/**
|
||||||
* ServerConfig and NetService - Runtime configuration services.
|
* ServerConfig - Runtime configuration services.
|
||||||
*
|
*
|
||||||
* Defines process-level server configuration and networking helpers used by
|
* Defines process-level server configuration and networking helpers used by
|
||||||
* startup and runtime layers.
|
* startup and runtime layers.
|
||||||
*
|
*
|
||||||
* @module ServerConfig
|
* @module ServerConfig
|
||||||
*/
|
*/
|
||||||
import * as Net from "node:net";
|
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||||
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
|
||||||
|
|
||||||
export const DEFAULT_PORT = 3773;
|
export const DEFAULT_PORT = 3773;
|
||||||
|
|
||||||
@@ -36,68 +35,28 @@ 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",
|
||||||
) {}
|
|
||||||
|
|
||||||
// Helpers
|
|
||||||
|
|
||||||
export class NetError extends Data.TaggedError("NetError")<{
|
|
||||||
readonly message: string;
|
|
||||||
readonly cause?: unknown;
|
|
||||||
}> {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* NetServiceShape - Networking helper operations used during startup.
|
|
||||||
*/
|
|
||||||
export interface NetServiceShape {
|
|
||||||
/**
|
|
||||||
* Resolve an available listening port, preferring the provided port first.
|
|
||||||
*
|
|
||||||
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
|
|
||||||
*/
|
|
||||||
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* NetService - Service tag for startup networking helpers.
|
|
||||||
*/
|
|
||||||
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
|
|
||||||
"t3/config/NetService",
|
|
||||||
) {
|
) {
|
||||||
static readonly layer = Layer.succeed(NetService, {
|
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||||
findAvailablePort: (preferred) =>
|
Layer.effect(
|
||||||
Effect.callback<number, NetError>((resume) => {
|
ServerConfig,
|
||||||
let fallbackServer: Net.Server | null = null;
|
Effect.gen(function* () {
|
||||||
const server = Net.createServer();
|
const path = yield* Path.Path;
|
||||||
server.listen(preferred, () => {
|
return {
|
||||||
server.close(() => resume(Effect.succeed(preferred)));
|
cwd,
|
||||||
});
|
stateDir: statedir,
|
||||||
server.on("error", () => {
|
mode: "web",
|
||||||
const fallback = Net.createServer();
|
autoBootstrapProjectFromCwd: false,
|
||||||
fallback.listen(0, () => {
|
logWebSocketEvents: false,
|
||||||
const addr = fallback.address();
|
port: 0,
|
||||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
host: undefined,
|
||||||
fallback.close(() => {
|
authToken: undefined,
|
||||||
resume(
|
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||||
port > 0
|
staticDir: undefined,
|
||||||
? Effect.succeed(port)
|
devUrl: undefined,
|
||||||
: Effect.fail(new NetError({ message: "Could not find an available port." })),
|
noBrowser: false,
|
||||||
);
|
};
|
||||||
});
|
|
||||||
});
|
|
||||||
fallback.on("error", (cause) => {
|
|
||||||
resume(
|
|
||||||
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
fallbackServer = fallback;
|
|
||||||
});
|
|
||||||
|
|
||||||
return Effect.sync(() => {
|
|
||||||
server.close();
|
|
||||||
fallbackServer?.close();
|
|
||||||
});
|
|
||||||
}),
|
}),
|
||||||
});
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const resolveStaticDir = Effect.fn(function* () {
|
export const resolveStaticDir = Effect.fn(function* () {
|
||||||
|
|||||||
@@ -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,17 +164,32 @@ 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 without branch by default", () =>
|
||||||
withFakeCodexEnv(
|
withFakeCodexEnv(
|
||||||
{
|
{
|
||||||
output: JSON.stringify({
|
output: JSON.stringify({
|
||||||
@@ -125,6 +197,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
|
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
|
||||||
body: "\n- added migration\n- updated tests\n",
|
body: "\n- added migration\n- updated tests\n",
|
||||||
}),
|
}),
|
||||||
|
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||||
},
|
},
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const textGeneration = yield* TextGeneration;
|
const textGeneration = yield* TextGeneration;
|
||||||
@@ -139,6 +212,34 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
|||||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||||
expect(generated.subject.endsWith(".")).toBe(false);
|
expect(generated.subject.endsWith(".")).toBe(false);
|
||||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||||
|
expect(generated.branch).toBeUndefined();
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||||
|
withFakeCodexEnv(
|
||||||
|
{
|
||||||
|
output: JSON.stringify({
|
||||||
|
subject: "Add important change",
|
||||||
|
body: "",
|
||||||
|
branch: "fix/important-system-change",
|
||||||
|
}),
|
||||||
|
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||||
|
},
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const textGeneration = yield* TextGeneration;
|
||||||
|
|
||||||
|
const generated = yield* textGeneration.generateCommitMessage({
|
||||||
|
cwd: process.cwd(),
|
||||||
|
branch: "feature/codex-effect",
|
||||||
|
stagedSummary: "M README.md",
|
||||||
|
stagedPatch: "diff --git a/README.md b/README.md",
|
||||||
|
includeBranch: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(generated.subject).toBe("Add important change");
|
||||||
|
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -170,6 +271,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(
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
import { Effect, FileSystem, Layer, Path, Schema } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
|
||||||
|
|
||||||
|
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { runProcess } from "../../processRunner.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 +21,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 +68,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);
|
||||||
@@ -127,25 +98,11 @@ function sanitizePrTitle(raw: string): string {
|
|||||||
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 serverConfig = yield* Effect.service(ServerConfig);
|
||||||
|
|
||||||
const readStreamAsString = <E>(
|
type MaterializedImageAttachments = {
|
||||||
operation: string,
|
readonly imagePaths: ReadonlyArray<string>;
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
};
|
||||||
): Effect.Effect<string, TextGenerationError> =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
let text = "";
|
|
||||||
yield* Stream.runForEach(stream, (chunk) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
text += Buffer.from(chunk).toString("utf8");
|
|
||||||
}),
|
|
||||||
).pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCodexError(operation, cause, "Failed to collect process output"),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return text;
|
|
||||||
});
|
|
||||||
|
|
||||||
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
|
||||||
|
|
||||||
@@ -171,109 +128,128 @@ 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", "");
|
||||||
|
|
||||||
const runCodexCommand = Effect.gen(function* () {
|
const runCodexCommand = Effect.tryPromise({
|
||||||
const command = ChildProcess.make(
|
try: async () => {
|
||||||
"codex",
|
const result = await runProcess(
|
||||||
[
|
"codex",
|
||||||
"exec",
|
[
|
||||||
"--ephemeral",
|
"exec",
|
||||||
"-s",
|
"--ephemeral",
|
||||||
"read-only",
|
"-s",
|
||||||
"--model",
|
"read-only",
|
||||||
CODEX_MODEL,
|
"--model",
|
||||||
"--config",
|
CODEX_MODEL,
|
||||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
"--config",
|
||||||
"--output-schema",
|
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||||
schemaPath,
|
"--output-schema",
|
||||||
"--output-last-message",
|
schemaPath,
|
||||||
outputPath,
|
"--output-last-message",
|
||||||
"-",
|
outputPath,
|
||||||
],
|
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||||
{
|
"-",
|
||||||
cwd,
|
],
|
||||||
stdin: {
|
{
|
||||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
cwd,
|
||||||
|
stdin: prompt,
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
timeoutMs: CODEX_TIMEOUT_MS,
|
||||||
|
maxBufferBytes: 1_000_000,
|
||||||
|
outputMode: "truncate",
|
||||||
},
|
},
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const child = yield* commandSpawner
|
|
||||||
.spawn(command)
|
|
||||||
.pipe(
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
if (result.timedOut) {
|
||||||
[
|
throw new TextGenerationError({ operation, detail: "Codex CLI request timed out." });
|
||||||
readStreamAsString(operation, child.stdout),
|
}
|
||||||
readStreamAsString(operation, child.stderr),
|
|
||||||
child.exitCode.pipe(
|
|
||||||
Effect.map((value) => Number(value)),
|
|
||||||
Effect.mapError((cause) =>
|
|
||||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
);
|
|
||||||
|
|
||||||
if (exitCode !== 0) {
|
const stdout = result.stdout;
|
||||||
const stderrDetail = stderr.trim();
|
const stderr = result.stderr;
|
||||||
const stdoutDetail = stdout.trim();
|
const exitCode = result.code ?? 0;
|
||||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
|
||||||
return yield* new TextGenerationError({
|
if (exitCode !== 0) {
|
||||||
operation,
|
const stderrDetail = stderr.trim();
|
||||||
detail:
|
const stdoutDetail = stdout.trim();
|
||||||
detail.length > 0
|
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||||
? `Codex CLI command failed: ${detail}`
|
throw new TextGenerationError({
|
||||||
: `Codex CLI command failed with code ${exitCode}.`,
|
operation,
|
||||||
});
|
detail:
|
||||||
}
|
detail.length > 0
|
||||||
|
? `Codex CLI command failed: ${detail}`
|
||||||
|
: `Codex CLI command failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
catch: (error) =>
|
||||||
|
normalizeCodexError(operation, error, "Failed to execute Codex CLI process"),
|
||||||
});
|
});
|
||||||
|
|
||||||
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;
|
||||||
Effect.scoped,
|
|
||||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
|
||||||
Effect.flatMap(
|
|
||||||
Option.match({
|
|
||||||
onNone: () =>
|
|
||||||
Effect.fail(
|
|
||||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
|
||||||
),
|
|
||||||
onSome: () => Effect.void,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
|
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||||
Effect.mapError(
|
Effect.mapError(
|
||||||
(cause) =>
|
(cause) =>
|
||||||
new TextGenerationError({
|
new TextGenerationError({
|
||||||
@@ -282,40 +258,34 @@ 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));
|
||||||
});
|
});
|
||||||
|
|
||||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||||
|
const wantsBranch = input.includeBranch === true;
|
||||||
|
|
||||||
const prompt = [
|
const prompt = [
|
||||||
"You write concise git commit messages.",
|
"You write concise git commit messages.",
|
||||||
"Return a JSON object with keys: subject, body.",
|
wantsBranch
|
||||||
|
? "Return a JSON object with keys: subject, body, branch."
|
||||||
|
: "Return a JSON object with keys: subject, body.",
|
||||||
"Rules:",
|
"Rules:",
|
||||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||||
"- body can be empty string or short bullet points",
|
"- body can be empty string or short bullet points",
|
||||||
|
...(wantsBranch
|
||||||
|
? ["- branch must be a short semantic git branch fragment for this change"]
|
||||||
|
: []),
|
||||||
"- capture the primary user-visible or developer-visible change",
|
"- capture the primary user-visible or developer-visible change",
|
||||||
"",
|
"",
|
||||||
`Branch: ${input.branch ?? "(detached)"}`,
|
`Branch: ${input.branch ?? "(detached)"}`,
|
||||||
@@ -327,18 +297,31 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
|||||||
limitSection(input.stagedPatch, 40_000),
|
limitSection(input.stagedPatch, 40_000),
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|
||||||
|
const outputSchemaJson = wantsBranch
|
||||||
|
? Schema.Struct({
|
||||||
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
branch: Schema.String,
|
||||||
|
})
|
||||||
|
: Schema.Struct({
|
||||||
|
subject: Schema.String,
|
||||||
|
body: Schema.String,
|
||||||
|
});
|
||||||
|
|
||||||
return runCodexJson({
|
return runCodexJson({
|
||||||
operation: "generateCommitMessage",
|
operation: "generateCommitMessage",
|
||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
prompt,
|
prompt,
|
||||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
outputSchemaJson,
|
||||||
parse: (raw) => parseCommitOutput(raw),
|
|
||||||
}).pipe(
|
}).pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(generated) =>
|
(generated) =>
|
||||||
({
|
({
|
||||||
subject: sanitizeCommitSubject(generated.subject),
|
subject: sanitizeCommitSubject(generated.subject),
|
||||||
body: generated.body.trim(),
|
body: generated.body.trim(),
|
||||||
|
...("branch" in generated && typeof generated.branch === "string"
|
||||||
|
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||||
|
: {}),
|
||||||
}) satisfies CommitMessageGenerationResult,
|
}) satisfies CommitMessageGenerationResult,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -371,8 +354,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 +369,58 @@ 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: sanitizeBranchFragment(generated.branch),
|
||||||
|
} satisfies BranchNameGenerationResult;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
generateCommitMessage,
|
generateCommitMessage,
|
||||||
generatePrContent,
|
generatePrContent,
|
||||||
|
generateBranchName,
|
||||||
} satisfies TextGenerationShape;
|
} satisfies TextGenerationShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -106,9 +106,11 @@ 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),
|
||||||
|
listLocalBranchNames: (cwd) => core.listLocalBranchNames(cwd),
|
||||||
} satisfies GitCoreShape;
|
} satisfies GitCoreShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -154,6 +156,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;
|
||||||
@@ -819,6 +828,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", () => {
|
||||||
@@ -1141,6 +1273,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();
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -125,10 +126,7 @@ function parseRemoteRefWithRemoteNames(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseTrackingBranchByUpstreamRef(
|
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
|
||||||
stdout: string,
|
|
||||||
upstreamRef: string,
|
|
||||||
): string | null {
|
|
||||||
for (const line of stdout.split("\n")) {
|
for (const line of stdout.split("\n")) {
|
||||||
const trimmedLine = line.trim();
|
const trimmedLine = line.trim();
|
||||||
if (trimmedLine.length === 0) {
|
if (trimmedLine.length === 0) {
|
||||||
@@ -161,6 +159,16 @@ 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,
|
||||||
@@ -239,6 +247,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<
|
||||||
@@ -340,6 +385,106 @@ 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(
|
||||||
@@ -429,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 }>();
|
||||||
@@ -538,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) {
|
||||||
@@ -707,33 +888,34 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
|
|
||||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||||
yield* Effect.all(
|
yield* Effect.all(
|
||||||
[
|
[
|
||||||
executeGit(
|
executeGit(
|
||||||
"GitCore.listBranches.defaultRef",
|
"GitCore.listBranches.defaultRef",
|
||||||
input.cwd,
|
input.cwd,
|
||||||
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
["symbolic-ref", "refs/remotes/origin/HEAD"],
|
||||||
{
|
{
|
||||||
timeoutMs: 5_000,
|
timeoutMs: 5_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
executeGit(
|
executeGit(
|
||||||
"GitCore.listBranches.worktreeList",
|
"GitCore.listBranches.worktreeList",
|
||||||
input.cwd,
|
input.cwd,
|
||||||
["worktree", "list", "--porcelain"],
|
["worktree", "list", "--porcelain"],
|
||||||
{
|
{
|
||||||
timeoutMs: 5_000,
|
timeoutMs: 5_000,
|
||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
remoteBranchResultEffect,
|
remoteBranchResultEffect,
|
||||||
remoteNamesResultEffect,
|
remoteNamesResultEffect,
|
||||||
branchRecencyPromise,
|
branchRecencyPromise,
|
||||||
],
|
],
|
||||||
{ concurrency: "unbounded" },
|
{ concurrency: "unbounded" },
|
||||||
);
|
);
|
||||||
|
|
||||||
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
const remoteNames =
|
||||||
|
remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||||
yield* Effect.logWarning(
|
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.`,
|
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||||
@@ -879,6 +1061,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,
|
||||||
@@ -911,24 +1113,23 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
{ concurrency: "unbounded" },
|
{ concurrency: "unbounded" },
|
||||||
);
|
);
|
||||||
|
|
||||||
const localTrackingBranch =
|
const localTrackingBranch = remoteExists
|
||||||
remoteExists
|
? yield* executeGit(
|
||||||
? yield* executeGit(
|
"GitCore.checkoutBranch.localTrackingBranch",
|
||||||
"GitCore.checkoutBranch.localTrackingBranch",
|
input.cwd,
|
||||||
input.cwd,
|
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
{
|
||||||
{
|
timeoutMs: 5_000,
|
||||||
timeoutMs: 5_000,
|
allowNonZeroExit: true,
|
||||||
allowNonZeroExit: true,
|
},
|
||||||
},
|
).pipe(
|
||||||
).pipe(
|
Effect.map((result) =>
|
||||||
Effect.map((result) =>
|
result.code === 0
|
||||||
result.code === 0
|
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
: null,
|
||||||
: null,
|
),
|
||||||
),
|
)
|
||||||
)
|
: null;
|
||||||
: null;
|
|
||||||
|
|
||||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||||
const localTrackedBranchTargetExists =
|
const localTrackedBranchTargetExists =
|
||||||
@@ -944,16 +1145,15 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
).pipe(Effect.map((result) => result.code === 0))
|
).pipe(Effect.map((result) => result.code === 0))
|
||||||
: false;
|
: false;
|
||||||
|
|
||||||
const checkoutArgs =
|
const checkoutArgs = localInputExists
|
||||||
localInputExists
|
? ["checkout", input.branch]
|
||||||
? ["checkout", input.branch]
|
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
|
||||||
? ["checkout", input.branch]
|
? ["checkout", input.branch]
|
||||||
: remoteExists && !localTrackingBranch
|
: remoteExists && !localTrackingBranch
|
||||||
? ["checkout", "--track", input.branch]
|
? ["checkout", "--track", input.branch]
|
||||||
: remoteExists && localTrackingBranch
|
: remoteExists && localTrackingBranch
|
||||||
? ["checkout", localTrackingBranch]
|
? ["checkout", localTrackingBranch]
|
||||||
: ["checkout", input.branch];
|
: ["checkout", input.branch];
|
||||||
|
|
||||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||||
timeoutMs: 10_000,
|
timeoutMs: 10_000,
|
||||||
@@ -961,11 +1161,9 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 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) =>
|
||||||
@@ -974,6 +1172,20 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
fallbackErrorMessage: "git init failed",
|
fallbackErrorMessage: "git init failed",
|
||||||
}).pipe(Effect.asVoid);
|
}).pipe(Effect.asVoid);
|
||||||
|
|
||||||
|
const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) =>
|
||||||
|
runGitStdout("GitCore.listLocalBranchNames", cwd, [
|
||||||
|
"branch",
|
||||||
|
"--list",
|
||||||
|
"--format=%(refname:short)",
|
||||||
|
]).pipe(
|
||||||
|
Effect.map((stdout) =>
|
||||||
|
stdout
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter((line) => line.length > 0),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
status,
|
status,
|
||||||
statusDetails,
|
statusDetails,
|
||||||
@@ -986,9 +1198,11 @@ const makeGitCore = Effect.gen(function* () {
|
|||||||
listBranches,
|
listBranches,
|
||||||
createWorktree,
|
createWorktree,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
|
renameBranch,
|
||||||
createBranch,
|
createBranch,
|
||||||
checkoutBranch,
|
checkoutBranch,
|
||||||
initRepo,
|
initRepo,
|
||||||
|
listLocalBranchNames,
|
||||||
} satisfies GitCoreShape;
|
} satisfies GitCoreShape;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,11 @@ interface FakeGitTextGeneration {
|
|||||||
branch: string | null;
|
branch: string | null;
|
||||||
stagedSummary: string;
|
stagedSummary: string;
|
||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
includeBranch?: boolean;
|
||||||
|
}) => Effect.Effect<
|
||||||
|
{ subject: string; body: string; branch?: string | undefined },
|
||||||
|
TextGenerationError
|
||||||
|
>;
|
||||||
generatePrContent: (input: {
|
generatePrContent: (input: {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
baseBranch: string;
|
baseBranch: string;
|
||||||
@@ -41,6 +45,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(
|
||||||
@@ -100,16 +108,23 @@ function createBareRemote(): Effect.Effect<
|
|||||||
|
|
||||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||||
const implementation: FakeGitTextGeneration = {
|
const implementation: FakeGitTextGeneration = {
|
||||||
generateCommitMessage: () =>
|
generateCommitMessage: (input) =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
subject: "Implement stacked git actions",
|
subject: "Implement stacked git actions",
|
||||||
body: "",
|
body: "",
|
||||||
|
...(input.includeBranch
|
||||||
|
? { branch: "feature/implement-stacked-git-actions" }
|
||||||
|
: {}),
|
||||||
}),
|
}),
|
||||||
generatePrContent: () =>
|
generatePrContent: () =>
|
||||||
Effect.succeed({
|
Effect.succeed({
|
||||||
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 +151,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 } : {}),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,6 +290,7 @@ function runStackedAction(
|
|||||||
cwd: string;
|
cwd: string;
|
||||||
action: "commit" | "commit_push" | "commit_push_pr";
|
action: "commit" | "commit_push" | "commit_push_pr";
|
||||||
commitMessage?: string;
|
commitMessage?: string;
|
||||||
|
featureBranch?: boolean;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
return manager.runStackedAction(input);
|
return manager.runStackedAction(input);
|
||||||
@@ -456,6 +483,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit",
|
action: "commit",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.commit.status).toBe("created");
|
expect(result.commit.status).toBe("created");
|
||||||
expect(result.push.status).toBe("skipped_not_requested");
|
expect(result.push.status).toBe("skipped_not_requested");
|
||||||
expect(result.pr.status).toBe("skipped_not_requested");
|
expect(result.pr.status).toBe("skipped_not_requested");
|
||||||
@@ -476,12 +504,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
|
|
||||||
const { manager } = yield* makeManager({
|
const { manager } = yield* makeManager({
|
||||||
textGeneration: {
|
textGeneration: {
|
||||||
generateCommitMessage: () =>
|
generateCommitMessage: (input) =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
generatedCount += 1;
|
generatedCount += 1;
|
||||||
return {
|
return {
|
||||||
subject: "this should not be used",
|
subject: "this should not be used",
|
||||||
body: "",
|
body: "",
|
||||||
|
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
@@ -492,6 +521,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.commit.status).toBe("created");
|
expect(result.commit.status).toBe("created");
|
||||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||||
expect(generatedCount).toBe(0);
|
expect(generatedCount).toBe(0);
|
||||||
@@ -508,6 +538,101 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
yield* initRepo(repoDir);
|
||||||
|
const remoteDir = yield* createBareRemote();
|
||||||
|
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||||
|
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||||
|
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
|
||||||
|
let generatedCount = 0;
|
||||||
|
|
||||||
|
const { manager } = yield* makeManager({
|
||||||
|
textGeneration: {
|
||||||
|
generateCommitMessage: (input) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
generatedCount += 1;
|
||||||
|
return {
|
||||||
|
subject: "Implement stacked git actions",
|
||||||
|
body: "",
|
||||||
|
...(input.includeBranch
|
||||||
|
? { branch: "feature/implement-stacked-git-actions" }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = yield* runStackedAction(manager, {
|
||||||
|
cwd: repoDir,
|
||||||
|
action: "commit_push",
|
||||||
|
featureBranch: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("created");
|
||||||
|
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
|
||||||
|
expect(result.commit.status).toBe("created");
|
||||||
|
expect(result.push.status).toBe("pushed");
|
||||||
|
expect(
|
||||||
|
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
|
||||||
|
Effect.map((result) => result.stdout.trim()),
|
||||||
|
),
|
||||||
|
).toBe("feature/implement-stacked-git-actions");
|
||||||
|
|
||||||
|
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||||
|
Effect.map((r) => r.stdout.trim()),
|
||||||
|
);
|
||||||
|
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
|
||||||
|
Effect.map((r) => r.stdout.trim()),
|
||||||
|
);
|
||||||
|
expect(mergeBase).toBe(mainSha);
|
||||||
|
expect(generatedCount).toBe(1);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
yield* initRepo(repoDir);
|
||||||
|
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
|
||||||
|
let generatedCount = 0;
|
||||||
|
|
||||||
|
const { manager } = yield* makeManager({
|
||||||
|
textGeneration: {
|
||||||
|
generateCommitMessage: (input) =>
|
||||||
|
Effect.sync(() => {
|
||||||
|
generatedCount += 1;
|
||||||
|
return {
|
||||||
|
subject: "unused",
|
||||||
|
body: "",
|
||||||
|
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const result = yield* runStackedAction(manager, {
|
||||||
|
cwd: repoDir,
|
||||||
|
action: "commit",
|
||||||
|
featureBranch: true,
|
||||||
|
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("created");
|
||||||
|
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
|
||||||
|
expect(result.commit.status).toBe("created");
|
||||||
|
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||||
|
expect(generatedCount).toBe(0);
|
||||||
|
|
||||||
|
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||||
|
Effect.map((r) => r.stdout.trim()),
|
||||||
|
);
|
||||||
|
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
|
||||||
|
Effect.map((r) => r.stdout.trim()),
|
||||||
|
);
|
||||||
|
expect(mergeBase).toBe(mainSha);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("skips commit when there are no uncommitted changes", () =>
|
it.effect("skips commit when there are no uncommitted changes", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -519,12 +644,32 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit",
|
action: "commit",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.commit.status).toBe("skipped_no_changes");
|
expect(result.commit.status).toBe("skipped_no_changes");
|
||||||
expect(result.push.status).toBe("skipped_not_requested");
|
expect(result.push.status).toBe("skipped_not_requested");
|
||||||
expect(result.pr.status).toBe("skipped_not_requested");
|
expect(result.pr.status).toBe("skipped_not_requested");
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("featureBranch returns error when worktree is clean", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
yield* initRepo(repoDir);
|
||||||
|
|
||||||
|
const { manager } = yield* makeManager();
|
||||||
|
const errorMessage = yield* runStackedAction(manager, {
|
||||||
|
cwd: repoDir,
|
||||||
|
action: "commit",
|
||||||
|
featureBranch: true,
|
||||||
|
}).pipe(
|
||||||
|
Effect.flip,
|
||||||
|
Effect.map((error) => error.message),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(errorMessage).toContain("no changes to commit");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
@@ -540,6 +685,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push",
|
action: "commit_push",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.commit.status).toBe("created");
|
expect(result.commit.status).toBe("created");
|
||||||
expect(result.push.status).toBe("pushed");
|
expect(result.push.status).toBe("pushed");
|
||||||
expect(result.push.setUpstream).toBe(true);
|
expect(result.push.setUpstream).toBe(true);
|
||||||
@@ -551,6 +697,57 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect(
|
||||||
|
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
|
||||||
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||||
|
yield* initRepo(repoDir);
|
||||||
|
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
|
||||||
|
const remoteDir = yield* createBareRemote();
|
||||||
|
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||||
|
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||||
|
|
||||||
|
const { manager, ghCalls } = yield* makeManager({
|
||||||
|
ghScenario: {
|
||||||
|
prListSequence: [
|
||||||
|
"[]",
|
||||||
|
JSON.stringify([
|
||||||
|
{
|
||||||
|
number: 77,
|
||||||
|
title: "Add no-upstream PR flow",
|
||||||
|
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
|
||||||
|
baseRefName: "main",
|
||||||
|
headRefName: "feature/no-upstream-pr",
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = yield* runStackedAction(manager, {
|
||||||
|
cwd: repoDir,
|
||||||
|
action: "commit_push_pr",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
|
expect(result.commit.status).toBe("created");
|
||||||
|
expect(result.push.status).toBe("pushed");
|
||||||
|
expect(result.push.setUpstream).toBe(true);
|
||||||
|
expect(result.pr.status).toBe("created");
|
||||||
|
expect(
|
||||||
|
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
|
||||||
|
Effect.map((result) => result.stdout.trim()),
|
||||||
|
),
|
||||||
|
).toBe("origin/feature/no-upstream-pr");
|
||||||
|
expect(
|
||||||
|
ghCalls.some((call) =>
|
||||||
|
call.includes("pr create --base main --head feature/no-upstream-pr"),
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
it.effect("skips push when branch is already up to date", () =>
|
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-");
|
||||||
@@ -566,6 +763,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push",
|
action: "commit_push",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.commit.status).toBe("skipped_no_changes");
|
expect(result.commit.status).toBe("skipped_no_changes");
|
||||||
expect(result.push.status).toBe("skipped_up_to_date");
|
expect(result.push.status).toBe("skipped_up_to_date");
|
||||||
}),
|
}),
|
||||||
@@ -600,6 +798,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.pr.status).toBe("opened_existing");
|
expect(result.pr.status).toBe("opened_existing");
|
||||||
expect(result.pr.number).toBe(42);
|
expect(result.pr.number).toBe(42);
|
||||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||||
@@ -640,6 +839,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
|||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
expect(result.branch.status).toBe("skipped_not_requested");
|
||||||
expect(result.pr.status).toBe("created");
|
expect(result.pr.status).toBe("created");
|
||||||
expect(result.pr.number).toBe(88);
|
expect(result.pr.number).toBe(88);
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||||
|
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||||
|
|
||||||
import { GitManagerError } from "../Errors.ts";
|
import { GitManagerError } from "../Errors.ts";
|
||||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||||
@@ -85,9 +86,14 @@ function limitContext(value: string, maxChars: number): string {
|
|||||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
function sanitizeCommitMessage(generated: {
|
||||||
subject: string;
|
subject: string;
|
||||||
body: string;
|
body: string;
|
||||||
|
branch?: string | undefined;
|
||||||
|
}): {
|
||||||
|
subject: string;
|
||||||
|
body: string;
|
||||||
|
branch?: string | undefined;
|
||||||
} {
|
} {
|
||||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||||
@@ -95,9 +101,25 @@ function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
|||||||
return {
|
return {
|
||||||
subject: safeSubject,
|
subject: safeSubject,
|
||||||
body: generated.body.trim(),
|
body: generated.body.trim(),
|
||||||
|
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface CommitAndBranchSuggestion {
|
||||||
|
subject: string;
|
||||||
|
body: string;
|
||||||
|
branch?: string | undefined;
|
||||||
|
commitMessage: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCommitMessage(subject: string, body: string): string {
|
||||||
|
const trimmedBody = body.trim();
|
||||||
|
if (trimmedBody.length === 0) {
|
||||||
|
return subject;
|
||||||
|
}
|
||||||
|
return `${subject}\n\n${trimmedBody}`;
|
||||||
|
}
|
||||||
|
|
||||||
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
|
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
|
||||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||||
if (normalized.length === 0) {
|
if (normalized.length === 0) {
|
||||||
@@ -253,30 +275,72 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
return "main";
|
return "main";
|
||||||
});
|
});
|
||||||
|
|
||||||
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
const resolveCommitAndBranchSuggestion = (input: {
|
||||||
|
cwd: string;
|
||||||
|
branch: string | null;
|
||||||
|
commitMessage?: string;
|
||||||
|
/** When true, also produce a semantic feature branch name. */
|
||||||
|
includeBranch?: boolean;
|
||||||
|
}) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const context = yield* gitCore.prepareCommitContext(cwd);
|
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||||
if (!context) {
|
if (!context) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
|
||||||
|
if (customCommit) {
|
||||||
|
return {
|
||||||
|
subject: customCommit.subject,
|
||||||
|
body: customCommit.body,
|
||||||
|
...(input.includeBranch
|
||||||
|
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
|
||||||
|
: {}),
|
||||||
|
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = yield* textGeneration
|
||||||
|
.generateCommitMessage({
|
||||||
|
cwd: input.cwd,
|
||||||
|
branch: input.branch,
|
||||||
|
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||||
|
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||||
|
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||||
|
})
|
||||||
|
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||||
|
|
||||||
|
return {
|
||||||
|
subject: generated.subject,
|
||||||
|
body: generated.body,
|
||||||
|
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||||
|
commitMessage: formatCommitMessage(generated.subject, generated.body),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const runCommitStep = (
|
||||||
|
cwd: string,
|
||||||
|
branch: string | null,
|
||||||
|
commitMessage?: string,
|
||||||
|
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||||
|
) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const suggestion =
|
||||||
|
preResolvedSuggestion ??
|
||||||
|
(yield* resolveCommitAndBranchSuggestion({
|
||||||
|
cwd,
|
||||||
|
branch,
|
||||||
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
}));
|
||||||
|
if (!suggestion) {
|
||||||
return { status: "skipped_no_changes" as const };
|
return { status: "skipped_no_changes" as const };
|
||||||
}
|
}
|
||||||
|
|
||||||
let generated = parseCustomCommitMessage(commitMessage ?? "");
|
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||||
if (!generated) {
|
|
||||||
generated = yield* textGeneration
|
|
||||||
.generateCommitMessage({
|
|
||||||
cwd,
|
|
||||||
branch,
|
|
||||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
|
||||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
|
||||||
})
|
|
||||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
|
||||||
}
|
|
||||||
|
|
||||||
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
|
|
||||||
return {
|
return {
|
||||||
status: "created" as const,
|
status: "created" as const,
|
||||||
commitSha,
|
commitSha,
|
||||||
subject: generated.subject,
|
subject: suggestion.subject,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -381,34 +445,88 @@ export const makeGitManager = Effect.gen(function* () {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||||
|
cwd,
|
||||||
|
branch,
|
||||||
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
includeBranch: true,
|
||||||
|
});
|
||||||
|
if (!suggestion) {
|
||||||
|
return yield* gitManagerError(
|
||||||
|
"runFeatureBranchStep",
|
||||||
|
"Cannot create a feature branch because there are no changes to commit.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
|
||||||
|
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||||
|
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||||
|
|
||||||
|
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||||
|
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||||
|
|
||||||
|
return {
|
||||||
|
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||||
|
resolvedCommitMessage: suggestion.commitMessage,
|
||||||
|
resolvedCommitSuggestion: suggestion,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||||
function* (input) {
|
function* (input) {
|
||||||
const wantsPush = input.action !== "commit";
|
const wantsPush = input.action !== "commit";
|
||||||
const wantsPr = input.action === "commit_push_pr";
|
const wantsPr = input.action === "commit_push_pr";
|
||||||
|
|
||||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||||
if (wantsPush && !initialStatus.branch) {
|
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||||
}
|
}
|
||||||
if (wantsPr && !initialStatus.branch) {
|
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||||
return yield* gitManagerError(
|
return yield* gitManagerError(
|
||||||
"runStackedAction",
|
"runStackedAction",
|
||||||
"Cannot create a pull request from detached HEAD.",
|
"Cannot create a pull request from detached HEAD.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||||
|
let commitMessageForStep = input.commitMessage;
|
||||||
|
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||||
|
|
||||||
|
if (input.featureBranch) {
|
||||||
|
const result = yield* runFeatureBranchStep(
|
||||||
|
input.cwd,
|
||||||
|
initialStatus.branch,
|
||||||
|
input.commitMessage,
|
||||||
|
);
|
||||||
|
branchStep = result.branchStep;
|
||||||
|
commitMessageForStep = result.resolvedCommitMessage;
|
||||||
|
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||||
|
} else {
|
||||||
|
branchStep = { status: "skipped_not_requested" as const };
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||||
|
|
||||||
|
const commit = yield* runCommitStep(
|
||||||
|
input.cwd,
|
||||||
|
currentBranch,
|
||||||
|
commitMessageForStep,
|
||||||
|
preResolvedCommitSuggestion,
|
||||||
|
);
|
||||||
|
|
||||||
const push = wantsPush
|
const push = wantsPush
|
||||||
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||||
: { status: "skipped_not_requested" as const };
|
: { status: "skipped_not_requested" as const };
|
||||||
|
|
||||||
const pr = wantsPr
|
const pr = wantsPr
|
||||||
? yield* runPrStep(input.cwd, initialStatus.branch)
|
? yield* runPrStep(input.cwd, currentBranch)
|
||||||
: { status: "skipped_not_requested" as const };
|
: { status: "skipped_not_requested" as const };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
action: input.action,
|
action: input.action,
|
||||||
|
branch: branchStep,
|
||||||
commit,
|
commit,
|
||||||
push,
|
push,
|
||||||
pr,
|
pr,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { it, assert } from "@effect/vitest";
|
|||||||
import { Effect, Layer, Schema } from "effect";
|
import { Effect, Layer, Schema } from "effect";
|
||||||
|
|
||||||
import { GitCommandError } from "../Errors.ts";
|
import { GitCommandError } from "../Errors.ts";
|
||||||
import { GitServiceLive } from "./GitService.ts";
|
import { GitServiceLive, normalizeGitProcessResult } from "./GitService.ts";
|
||||||
import { GitService } from "../Services/GitService.ts";
|
import { GitService } from "../Services/GitService.ts";
|
||||||
|
|
||||||
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
|
||||||
@@ -56,4 +56,31 @@ layer("GitServiceLive", (it) => {
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it("normalizeGitProcessResult fails when git exits without a code", () => {
|
||||||
|
try {
|
||||||
|
void normalizeGitProcessResult(
|
||||||
|
{
|
||||||
|
operation: "GitProcess.test.signal",
|
||||||
|
cwd: process.cwd(),
|
||||||
|
args: ["status"],
|
||||||
|
},
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
code: null,
|
||||||
|
signal: "SIGTERM",
|
||||||
|
stdout: "",
|
||||||
|
stderr: "",
|
||||||
|
timedOut: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert.fail("Expected normalizeGitProcessResult to throw.");
|
||||||
|
} catch (error) {
|
||||||
|
assert.equal(Schema.is(GitCommandError)(error), true);
|
||||||
|
if (!Schema.is(GitCommandError)(error)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert.equal(error.detail, "git status terminated by signal SIGTERM.");
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* Git process helpers - Effect-native git execution with typed errors.
|
* Git process helpers - runtime-aware git execution with typed errors.
|
||||||
*
|
*
|
||||||
* Centralizes child-process git invocation for server modules. This module
|
* Centralizes child-process git invocation for server modules. This module
|
||||||
* only executes git commands and reports structured failures.
|
* only executes git commands and reports structured failures.
|
||||||
*
|
*
|
||||||
* @module GitServiceLive
|
* @module GitServiceLive
|
||||||
*/
|
*/
|
||||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
import { Effect, Layer, Schema } from "effect";
|
||||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
import { runProcess } from "../../processRunner.ts";
|
||||||
import { GitCommandError } from "../Errors.ts";
|
import { GitCommandError } from "../Errors.ts";
|
||||||
import {
|
import {
|
||||||
ExecuteGitInput,
|
ExecuteGitInput,
|
||||||
@@ -39,37 +39,60 @@ function toGitCommandError(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const collectOutput = Effect.fn(function* <E>(
|
export function normalizeGitProcessResult(
|
||||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
commandInput: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||||
stream: Stream.Stream<Uint8Array, E>,
|
input: Pick<ExecuteGitInput, "allowNonZeroExit">,
|
||||||
maxOutputBytes: number,
|
result: {
|
||||||
): Effect.fn.Return<string, GitCommandError> {
|
readonly stdout: string;
|
||||||
const decoder = new TextDecoder();
|
readonly stderr: string;
|
||||||
let bytes = 0;
|
readonly code: number | null;
|
||||||
let text = "";
|
readonly signal: NodeJS.Signals | null;
|
||||||
|
readonly timedOut: boolean;
|
||||||
|
},
|
||||||
|
): ExecuteGitResult {
|
||||||
|
if (result.timedOut) {
|
||||||
|
throw new GitCommandError({
|
||||||
|
operation: commandInput.operation,
|
||||||
|
command: quoteGitCommand(commandInput.args),
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
yield* Stream.runForEach(stream, (chunk) =>
|
if (result.code === null) {
|
||||||
Effect.gen(function* () {
|
throw new GitCommandError({
|
||||||
bytes += chunk.byteLength;
|
operation: commandInput.operation,
|
||||||
if (bytes > maxOutputBytes) {
|
command: quoteGitCommand(commandInput.args),
|
||||||
return yield* new GitCommandError({
|
cwd: commandInput.cwd,
|
||||||
operation: input.operation,
|
detail:
|
||||||
command: quoteGitCommand(input.args),
|
result.signal !== null
|
||||||
cwd: input.cwd,
|
? `${quoteGitCommand(commandInput.args)} terminated by signal ${result.signal}.`
|
||||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
: `${quoteGitCommand(commandInput.args)} terminated before reporting an exit code.`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
text += decoder.decode(chunk, { stream: true });
|
|
||||||
}),
|
|
||||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
|
||||||
|
|
||||||
text += decoder.decode();
|
const exitCode = result.code;
|
||||||
return text;
|
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||||
});
|
const trimmedStderr = result.stderr.trim();
|
||||||
|
throw new GitCommandError({
|
||||||
|
operation: commandInput.operation,
|
||||||
|
command: quoteGitCommand(commandInput.args),
|
||||||
|
cwd: commandInput.cwd,
|
||||||
|
detail:
|
||||||
|
trimmedStderr.length > 0
|
||||||
|
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
||||||
|
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const makeGitService = Effect.gen(function* () {
|
return {
|
||||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
code: exitCode,
|
||||||
|
stdout: result.stdout,
|
||||||
|
stderr: result.stderr,
|
||||||
|
} satisfies ExecuteGitResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
const makeGitService = Effect.sync(() => {
|
||||||
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
|
||||||
const commandInput = {
|
const commandInput = {
|
||||||
...input,
|
...input,
|
||||||
@@ -78,62 +101,21 @@ const makeGitService = Effect.gen(function* () {
|
|||||||
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||||
|
|
||||||
const commandEffect = Effect.gen(function* () {
|
return yield* Effect.tryPromise({
|
||||||
const child = yield* commandSpawner
|
try: async () => {
|
||||||
.spawn(
|
const result = await runProcess("git", commandInput.args, {
|
||||||
ChildProcess.make("git", commandInput.args, {
|
|
||||||
cwd: commandInput.cwd,
|
|
||||||
...(input.env ? { env: input.env } : {}),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
|
|
||||||
|
|
||||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
|
||||||
[
|
|
||||||
collectOutput(commandInput, child.stdout, maxOutputBytes),
|
|
||||||
collectOutput(commandInput, child.stderr, maxOutputBytes),
|
|
||||||
child.exitCode.pipe(
|
|
||||||
Effect.map((value) => Number(value)),
|
|
||||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
{ concurrency: "unbounded" },
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
|
||||||
const trimmedStderr = stderr.trim();
|
|
||||||
return yield* new GitCommandError({
|
|
||||||
operation: commandInput.operation,
|
|
||||||
command: quoteGitCommand(commandInput.args),
|
|
||||||
cwd: commandInput.cwd,
|
cwd: commandInput.cwd,
|
||||||
detail:
|
...(input.env ? { env: input.env } : {}),
|
||||||
trimmedStderr.length > 0
|
timeoutMs,
|
||||||
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
|
allowNonZeroExit: true,
|
||||||
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
|
maxBufferBytes: maxOutputBytes,
|
||||||
|
outputMode: "error",
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
|
||||||
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
|
return normalizeGitProcessResult(commandInput, input, result);
|
||||||
|
},
|
||||||
|
catch: toGitCommandError(commandInput, "failed to run."),
|
||||||
});
|
});
|
||||||
|
|
||||||
return yield* commandEffect.pipe(
|
|
||||||
Effect.scoped,
|
|
||||||
Effect.timeoutOption(timeoutMs),
|
|
||||||
Effect.flatMap((result) =>
|
|
||||||
Option.match(result, {
|
|
||||||
onNone: () =>
|
|
||||||
Effect.fail(
|
|
||||||
new GitCommandError({
|
|
||||||
operation: commandInput.operation,
|
|
||||||
command: quoteGitCommand(commandInput.args),
|
|
||||||
cwd: commandInput.cwd,
|
|
||||||
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
onSome: Effect.succeed,
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
* @module GitCore
|
* @module GitCore
|
||||||
*/
|
*/
|
||||||
import { ServiceMap } from "effect";
|
import { ServiceMap } from "effect";
|
||||||
import type { Effect } from "effect";
|
import type { Effect, Scope } from "effect";
|
||||||
import type {
|
import type {
|
||||||
GitCheckoutInput,
|
GitCheckoutInput,
|
||||||
GitCreateBranchInput,
|
GitCreateBranchInput,
|
||||||
@@ -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.
|
||||||
*/
|
*/
|
||||||
@@ -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.
|
||||||
*/
|
*/
|
||||||
@@ -132,12 +149,19 @@ export interface GitCoreShape {
|
|||||||
/**
|
/**
|
||||||
* Checkout an existing branch and refresh its upstream metadata in background.
|
* Checkout an existing branch and refresh its upstream metadata in background.
|
||||||
*/
|
*/
|
||||||
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
|
readonly checkoutBranch: (
|
||||||
|
input: GitCheckoutInput,
|
||||||
|
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize a repository in the provided directory.
|
* Initialize a repository in the provided directory.
|
||||||
*/
|
*/
|
||||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List local branch names (short format).
|
||||||
|
*/
|
||||||
|
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ export interface GitManagerShape {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
|
||||||
|
* When `featureBranch` is set, creates and checks out a feature branch first.
|
||||||
*/
|
*/
|
||||||
readonly runStackedAction: (
|
readonly runStackedAction: (
|
||||||
input: GitRunStackedActionInput,
|
input: GitRunStackedActionInput,
|
||||||
|
|||||||
@@ -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";
|
||||||
|
|
||||||
@@ -16,11 +17,15 @@ export interface CommitMessageGenerationInput {
|
|||||||
branch: string | null;
|
branch: string | null;
|
||||||
stagedSummary: string;
|
stagedSummary: string;
|
||||||
stagedPatch: string;
|
stagedPatch: string;
|
||||||
|
/** When true, the model also returns a semantic branch name for the change. */
|
||||||
|
includeBranch?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CommitMessageGenerationResult {
|
export interface CommitMessageGenerationResult {
|
||||||
subject: string;
|
subject: string;
|
||||||
body: string;
|
body: string;
|
||||||
|
/** Only present when `includeBranch` was set on the input. */
|
||||||
|
branch?: string | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PrContentGenerationInput {
|
export interface PrContentGenerationInput {
|
||||||
@@ -37,11 +42,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 +77,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";
|
||||||
|
}
|
||||||
@@ -8,7 +8,7 @@ import { OpenLive } from "./open";
|
|||||||
import { Command } from "effect/unstable/cli";
|
import { Command } from "effect/unstable/cli";
|
||||||
import { version } from "../package.json" with { type: "json" };
|
import { version } from "../package.json" with { type: "json" };
|
||||||
import { ServerLive } from "./wsServer";
|
import { ServerLive } from "./wsServer";
|
||||||
import { NetService } from "./config";
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
|
||||||
const RuntimeLayer = Layer.empty.pipe(
|
const RuntimeLayer = Layer.empty.pipe(
|
||||||
Layer.provideMerge(CliConfig.layer),
|
Layer.provideMerge(CliConfig.layer),
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ import * as Effect from "effect/Effect";
|
|||||||
import * as Layer from "effect/Layer";
|
import * as Layer from "effect/Layer";
|
||||||
import * as Command from "effect/unstable/cli/Command";
|
import * as Command from "effect/unstable/cli/Command";
|
||||||
import { beforeEach } from "vitest";
|
import { beforeEach } from "vitest";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
|
||||||
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
||||||
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
|
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||||
import { Open, type OpenShape } from "./open";
|
import { Open, type OpenShape } from "./open";
|
||||||
import { Server, type ServerShape } from "./wsServer";
|
import { Server, type ServerShape } from "./wsServer";
|
||||||
|
|
||||||
@@ -33,6 +34,9 @@ const testLayer = Layer.mergeAll(
|
|||||||
resolveStaticDir: Effect.undefined,
|
resolveStaticDir: Effect.undefined,
|
||||||
} satisfies CliConfigShape),
|
} satisfies CliConfigShape),
|
||||||
Layer.succeed(NetService, {
|
Layer.succeed(NetService, {
|
||||||
|
canListenOnHost: () => Effect.succeed(true),
|
||||||
|
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||||
|
reserveLoopbackPort: () => Effect.succeed(0),
|
||||||
findAvailablePort,
|
findAvailablePort,
|
||||||
}),
|
}),
|
||||||
Layer.succeed(Server, {
|
Layer.succeed(Server, {
|
||||||
@@ -49,10 +53,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();
|
||||||
|
|||||||
@@ -8,10 +8,10 @@
|
|||||||
*/
|
*/
|
||||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||||
import { Command, Flag } from "effect/unstable/cli";
|
import { Command, Flag } from "effect/unstable/cli";
|
||||||
|
import { NetService } from "@t3tools/shared/Net";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_PORT,
|
DEFAULT_PORT,
|
||||||
NetService,
|
|
||||||
resolveStaticDir,
|
resolveStaticDir,
|
||||||
ServerConfig,
|
ServerConfig,
|
||||||
type RuntimeMode,
|
type RuntimeMode,
|
||||||
@@ -21,6 +21,7 @@ import { fixPath, resolveStateDir } from "./os-jank";
|
|||||||
import { Open } from "./open";
|
import { Open } from "./open";
|
||||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||||
|
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||||
import { Server } from "./wsServer";
|
import { Server } from "./wsServer";
|
||||||
|
|
||||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||||
@@ -197,6 +198,7 @@ const LayerLive = (input: CliInput) =>
|
|||||||
Layer.empty.pipe(
|
Layer.empty.pipe(
|
||||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||||
Layer.provideMerge(makeServerProviderLayer()),
|
Layer.provideMerge(makeServerProviderLayer()),
|
||||||
|
Layer.provideMerge(ProviderHealthLive),
|
||||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||||
Layer.provideMerge(ServerConfigLive(input)),
|
Layer.provideMerge(ServerConfigLive(input)),
|
||||||
);
|
);
|
||||||
|
|||||||
+326
-11
@@ -1,28 +1,56 @@
|
|||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
import { assert, describe, it } from "@effect/vitest";
|
import { assert, describe, it } from "@effect/vitest";
|
||||||
|
|
||||||
import { launchDetached, resolveEditorLaunch } from "./open";
|
import {
|
||||||
|
isCommandAvailable,
|
||||||
|
launchDetached,
|
||||||
|
resolveBrowserLaunch,
|
||||||
|
resolveAvailableEditors,
|
||||||
|
resolveEditorLaunch,
|
||||||
|
} from "./open";
|
||||||
import { Effect } from "effect";
|
import { Effect } from "effect";
|
||||||
import { assertSuccess } from "@effect/vitest/utils";
|
import { assertSuccess } from "@effect/vitest/utils";
|
||||||
|
|
||||||
describe("resolveEditorLaunch", () => {
|
describe("resolveEditorLaunch", () => {
|
||||||
it.effect("returns cursor command for cursor editor", () =>
|
it.effect("returns commands for command-based editors", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const launch = yield* resolveEditorLaunch(
|
const cursorLaunch = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace", editor: "cursor" },
|
{ cwd: "/tmp/workspace", editor: "cursor" },
|
||||||
"darwin",
|
{ platform: "darwin" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(launch, {
|
assert.deepEqual(cursorLaunch, {
|
||||||
command: "cursor",
|
command: "cursor",
|
||||||
args: ["/tmp/workspace"],
|
args: ["/tmp/workspace"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||||
|
{ platform: "darwin" },
|
||||||
|
);
|
||||||
|
assert.deepEqual(vscodeLaunch, {
|
||||||
|
command: "code",
|
||||||
|
args: ["/tmp/workspace"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const zedLaunch = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||||
|
{ platform: "darwin" },
|
||||||
|
);
|
||||||
|
assert.deepEqual(zedLaunch, {
|
||||||
|
command: "zed",
|
||||||
|
args: ["/tmp/workspace"],
|
||||||
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
|
it.effect("uses --goto when editor supports line/column suffixes", () =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const lineOnly = yield* resolveEditorLaunch(
|
const lineOnly = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
|
||||||
"darwin",
|
{ platform: "darwin" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(lineOnly, {
|
assert.deepEqual(lineOnly, {
|
||||||
command: "cursor",
|
command: "cursor",
|
||||||
@@ -31,12 +59,30 @@ describe("resolveEditorLaunch", () => {
|
|||||||
|
|
||||||
const lineAndColumn = yield* resolveEditorLaunch(
|
const lineAndColumn = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
|
||||||
"darwin",
|
{ platform: "darwin" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(lineAndColumn, {
|
assert.deepEqual(lineAndColumn, {
|
||||||
command: "cursor",
|
command: "cursor",
|
||||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||||
|
{ platform: "darwin" },
|
||||||
|
);
|
||||||
|
assert.deepEqual(vscodeLineAndColumn, {
|
||||||
|
command: "code",
|
||||||
|
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||||
|
{ platform: "darwin" },
|
||||||
|
);
|
||||||
|
assert.deepEqual(zedLineAndColumn, {
|
||||||
|
command: "zed",
|
||||||
|
args: ["/tmp/workspace/src/open.ts:71:5"],
|
||||||
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -44,7 +90,7 @@ describe("resolveEditorLaunch", () => {
|
|||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const launch1 = yield* resolveEditorLaunch(
|
const launch1 = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||||
"darwin",
|
{ platform: "darwin" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(launch1, {
|
assert.deepEqual(launch1, {
|
||||||
command: "open",
|
command: "open",
|
||||||
@@ -53,7 +99,7 @@ describe("resolveEditorLaunch", () => {
|
|||||||
|
|
||||||
const launch2 = yield* resolveEditorLaunch(
|
const launch2 = yield* resolveEditorLaunch(
|
||||||
{ cwd: "C:\\workspace", editor: "file-manager" },
|
{ cwd: "C:\\workspace", editor: "file-manager" },
|
||||||
"win32",
|
{ platform: "win32" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(launch2, {
|
assert.deepEqual(launch2, {
|
||||||
command: "explorer",
|
command: "explorer",
|
||||||
@@ -62,7 +108,7 @@ describe("resolveEditorLaunch", () => {
|
|||||||
|
|
||||||
const launch3 = yield* resolveEditorLaunch(
|
const launch3 = yield* resolveEditorLaunch(
|
||||||
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
{ cwd: "/tmp/workspace", editor: "file-manager" },
|
||||||
"linux",
|
{ platform: "linux" },
|
||||||
);
|
);
|
||||||
assert.deepEqual(launch3, {
|
assert.deepEqual(launch3, {
|
||||||
command: "xdg-open",
|
command: "xdg-open",
|
||||||
@@ -70,6 +116,112 @@ describe("resolveEditorLaunch", () => {
|
|||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
it.effect("prefers linux editor shims in wsl-hosted mode when available", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-linux-editor-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "code"), "#!/bin/sh\n", { mode: 0o755 });
|
||||||
|
const launch = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||||
|
{
|
||||||
|
platform: "linux",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert.deepEqual(launch, {
|
||||||
|
command: "code",
|
||||||
|
args: ["--goto", "/home/julius/project/src/open.ts:71:5"],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("falls back to windows editor executables in wsl-hosted mode", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-win-editor-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||||
|
const launch = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "vscode" },
|
||||||
|
{
|
||||||
|
platform: "linux",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
},
|
||||||
|
translateWslPathToWindows: (target) =>
|
||||||
|
target.replace(
|
||||||
|
"/home/julius/project",
|
||||||
|
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||||
|
),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert.deepEqual(launch, {
|
||||||
|
command: "code.exe",
|
||||||
|
args: [
|
||||||
|
"--goto",
|
||||||
|
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts:71:5",
|
||||||
|
],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("translates file-manager targets for wsl-hosted mode", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-wsl-file-manager-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||||
|
const launch = yield* resolveEditorLaunch(
|
||||||
|
{ cwd: "/home/julius/project/src/open.ts:71:5", editor: "file-manager" },
|
||||||
|
{
|
||||||
|
platform: "linux",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
},
|
||||||
|
translateWslPathToWindows: (target) =>
|
||||||
|
target.replace(
|
||||||
|
"/home/julius/project",
|
||||||
|
"\\\\wsl.localhost\\Ubuntu\\home\\julius\\project",
|
||||||
|
),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert.deepEqual(launch, {
|
||||||
|
command: "explorer.exe",
|
||||||
|
args: ["\\\\wsl.localhost\\Ubuntu\\home\\julius\\project/src/open.ts"],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("launchDetached", () => {
|
describe("launchDetached", () => {
|
||||||
@@ -93,3 +245,166 @@ describe("launchDetached", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("isCommandAvailable", () => {
|
||||||
|
function withTempDir(run: (dir: string) => void): void {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
|
||||||
|
try {
|
||||||
|
run(dir);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it("resolves win32 commands with PATHEXT", () => {
|
||||||
|
withTempDir((dir) => {
|
||||||
|
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||||
|
const env = {
|
||||||
|
PATH: dir,
|
||||||
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
|
} satisfies NodeJS.ProcessEnv;
|
||||||
|
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when a command is not on PATH", () => {
|
||||||
|
const env = {
|
||||||
|
PATH: "",
|
||||||
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
|
} satisfies NodeJS.ProcessEnv;
|
||||||
|
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not treat bare files without executable extension as available on win32", () => {
|
||||||
|
withTempDir((dir) => {
|
||||||
|
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
|
||||||
|
const env = {
|
||||||
|
PATH: dir,
|
||||||
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
|
} satisfies NodeJS.ProcessEnv;
|
||||||
|
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
|
||||||
|
withTempDir((dir) => {
|
||||||
|
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
|
||||||
|
const env = {
|
||||||
|
PATH: dir,
|
||||||
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
|
} satisfies NodeJS.ProcessEnv;
|
||||||
|
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses platform-specific PATH delimiter for platform overrides", () => {
|
||||||
|
withTempDir((firstDir) => {
|
||||||
|
withTempDir((secondDir) => {
|
||||||
|
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
|
||||||
|
const env = {
|
||||||
|
PATH: `${firstDir};${secondDir}`,
|
||||||
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
|
} satisfies NodeJS.ProcessEnv;
|
||||||
|
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveAvailableEditors", () => {
|
||||||
|
it("returns only editors whose launch commands are available", () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
|
||||||
|
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
|
||||||
|
const editors = resolveAvailableEditors({
|
||||||
|
platform: "win32",
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("accepts windows editor executables in wsl-hosted mode", () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-wsl-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "code.exe"), "MZ", { mode: 0o755 });
|
||||||
|
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||||
|
const editors = resolveAvailableEditors({
|
||||||
|
platform: "linux",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(editors, ["vscode", "file-manager"]);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("resolveBrowserLaunch", () => {
|
||||||
|
it("prefers wslview in wsl-hosted mode", () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "wslview"), "#!/bin/sh\n", { mode: 0o755 });
|
||||||
|
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||||
|
platform: "linux",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(launch, {
|
||||||
|
command: "wslview",
|
||||||
|
args: ["http://localhost:3773"],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to explorer.exe in wsl-hosted mode", () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-browser-wsl-explorer-"));
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(dir, "explorer.exe"), "MZ", { mode: 0o755 });
|
||||||
|
const launch = resolveBrowserLaunch("http://localhost:3773", {
|
||||||
|
platform: "linux",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
},
|
||||||
|
env: {
|
||||||
|
PATH: dir,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.deepEqual(launch, {
|
||||||
|
command: "explorer.exe",
|
||||||
|
args: ["http://localhost:3773"],
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
+371
-38
@@ -6,10 +6,13 @@
|
|||||||
*
|
*
|
||||||
* @module Open
|
* @module Open
|
||||||
*/
|
*/
|
||||||
import { spawn } from "node:child_process";
|
import { accessSync, constants, statSync } from "node:fs";
|
||||||
|
import { extname, join } from "node:path";
|
||||||
|
|
||||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
import { EDITORS, type EditorId, type ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||||
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
import { ServiceMap, Schema, Effect, Layer } from "effect";
|
||||||
|
import { spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||||
|
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||||
|
|
||||||
// ==============================
|
// ==============================
|
||||||
// Definitions
|
// Definitions
|
||||||
@@ -30,10 +33,170 @@ interface EditorLaunch {
|
|||||||
readonly args: ReadonlyArray<string>;
|
readonly args: ReadonlyArray<string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface CommandAvailabilityOptions {
|
||||||
|
readonly platform?: NodeJS.Platform;
|
||||||
|
readonly env?: NodeJS.ProcessEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ResolveOpenOptions extends CommandAvailabilityOptions {
|
||||||
|
readonly runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||||
|
readonly translateWslPathToWindows?: (target: string) => string;
|
||||||
|
}
|
||||||
|
|
||||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||||
|
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||||
|
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||||
|
|
||||||
|
function detectRuntimeEnvironment(options: ResolveOpenOptions): ServerRuntimeEnvironment {
|
||||||
|
return (
|
||||||
|
options.runtimeEnvironment ??
|
||||||
|
detectServerRuntimeEnvironment({
|
||||||
|
...(options.platform !== undefined ? { platform: options.platform } : {}),
|
||||||
|
...(options.env !== undefined ? { env: options.env } : {}),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||||
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||||
|
switch (platform) {
|
||||||
|
case "darwin":
|
||||||
|
return "open";
|
||||||
|
case "win32":
|
||||||
|
return "explorer";
|
||||||
|
default:
|
||||||
|
return "xdg-open";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripWrappingQuotes(value: string): string {
|
||||||
|
return value.replace(/^"+|"+$/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||||
|
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||||
|
const rawValue = env.PATHEXT;
|
||||||
|
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||||
|
if (!rawValue) return fallback;
|
||||||
|
|
||||||
|
const parsed = rawValue
|
||||||
|
.split(";")
|
||||||
|
.map((entry) => entry.trim())
|
||||||
|
.filter((entry) => entry.length > 0)
|
||||||
|
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||||
|
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveCommandCandidates(
|
||||||
|
command: string,
|
||||||
|
platform: NodeJS.Platform,
|
||||||
|
windowsPathExtensions: ReadonlyArray<string>,
|
||||||
|
): ReadonlyArray<string> {
|
||||||
|
if (platform !== "win32") return [command];
|
||||||
|
const extension = extname(command);
|
||||||
|
const normalizedExtension = extension.toUpperCase();
|
||||||
|
|
||||||
|
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||||
|
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||||
|
return Array.from(
|
||||||
|
new Set([
|
||||||
|
command,
|
||||||
|
`${commandWithoutExtension}${normalizedExtension}`,
|
||||||
|
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidates: string[] = [];
|
||||||
|
for (const extension of windowsPathExtensions) {
|
||||||
|
candidates.push(`${command}${extension}`);
|
||||||
|
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||||
|
}
|
||||||
|
return Array.from(new Set(candidates));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExecutableFile(
|
||||||
|
filePath: string,
|
||||||
|
platform: NodeJS.Platform,
|
||||||
|
windowsPathExtensions: ReadonlyArray<string>,
|
||||||
|
): boolean {
|
||||||
|
try {
|
||||||
|
const stat = statSync(filePath);
|
||||||
|
if (!stat.isFile()) return false;
|
||||||
|
if (platform === "win32") {
|
||||||
|
const extension = extname(filePath);
|
||||||
|
if (extension.length === 0) return false;
|
||||||
|
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||||
|
}
|
||||||
|
accessSync(filePath, constants.X_OK);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||||
|
return platform === "win32" ? ";" : ":";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isCommandAvailable(
|
||||||
|
command: string,
|
||||||
|
options: CommandAvailabilityOptions = {},
|
||||||
|
): boolean {
|
||||||
|
const platform = options.platform ?? process.platform;
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||||
|
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||||
|
|
||||||
|
if (command.includes("/") || command.includes("\\")) {
|
||||||
|
return commandCandidates.some((candidate) =>
|
||||||
|
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pathValue = resolvePathEnvironmentVariable(env);
|
||||||
|
if (pathValue.length === 0) return false;
|
||||||
|
const pathEntries = pathValue
|
||||||
|
.split(resolvePathDelimiter(platform))
|
||||||
|
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||||
|
.filter((entry) => entry.length > 0);
|
||||||
|
|
||||||
|
for (const pathEntry of pathEntries) {
|
||||||
|
for (const candidate of commandCandidates) {
|
||||||
|
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveAvailableEditors(
|
||||||
|
options: ResolveOpenOptions = {},
|
||||||
|
): ReadonlyArray<EditorId> {
|
||||||
|
const platform = options.platform ?? process.platform;
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||||
|
const available: EditorId[] = [];
|
||||||
|
|
||||||
|
for (const editor of EDITORS) {
|
||||||
|
const launch = resolveOpenCommand(editor.id, {
|
||||||
|
platform,
|
||||||
|
env,
|
||||||
|
runtimeEnvironment,
|
||||||
|
});
|
||||||
|
if (launch.some((entry) => isCommandAvailable(entry, { platform, env }))) {
|
||||||
|
available.push(editor.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return available;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -62,58 +225,223 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
|||||||
// Implementations
|
// Implementations
|
||||||
// ==============================
|
// ==============================
|
||||||
|
|
||||||
|
function splitPathAndPosition(value: string): {
|
||||||
|
path: string;
|
||||||
|
line: string | undefined;
|
||||||
|
column: string | undefined;
|
||||||
|
} {
|
||||||
|
let path = value;
|
||||||
|
let column: string | undefined;
|
||||||
|
let line: string | undefined;
|
||||||
|
|
||||||
|
const columnMatch = path.match(/:(\d+)$/);
|
||||||
|
if (!columnMatch?.[1]) {
|
||||||
|
return { path, line: undefined, column: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
column = columnMatch[1];
|
||||||
|
path = path.slice(0, -columnMatch[0].length);
|
||||||
|
|
||||||
|
const lineMatch = path.match(/:(\d+)$/);
|
||||||
|
if (lineMatch?.[1]) {
|
||||||
|
line = lineMatch[1];
|
||||||
|
path = path.slice(0, -lineMatch[0].length);
|
||||||
|
} else {
|
||||||
|
line = column;
|
||||||
|
column = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { path, line, column };
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripLineColumnSuffix(value: string): string {
|
||||||
|
const { path } = splitPathAndPosition(value);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPathWithPosition(input: {
|
||||||
|
readonly path: string;
|
||||||
|
readonly line?: string;
|
||||||
|
readonly column?: string;
|
||||||
|
}): string {
|
||||||
|
if (!input.line) {
|
||||||
|
return input.path;
|
||||||
|
}
|
||||||
|
return `${input.path}:${input.line}${input.column ? `:${input.column}` : ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWindowsPath(value: string): boolean {
|
||||||
|
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultTranslateWslPathToWindows(target: string): string {
|
||||||
|
const parsed = splitPathAndPosition(target);
|
||||||
|
if (parsed.path.length === 0 || !parsed.path.startsWith("/") || isWindowsPath(parsed.path)) {
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = spawnProcessSync("wslpath", ["-w", parsed.path], {
|
||||||
|
encoding: "utf8",
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
if (result.error) {
|
||||||
|
throw result.error;
|
||||||
|
}
|
||||||
|
if (result.status !== 0) {
|
||||||
|
const detail = result.stderr.trim() || result.stdout.trim() || "wslpath failed";
|
||||||
|
throw new Error(detail);
|
||||||
|
}
|
||||||
|
|
||||||
|
const translatedPath = result.stdout.trim();
|
||||||
|
if (translatedPath.length === 0) {
|
||||||
|
throw new Error("wslpath returned an empty path");
|
||||||
|
}
|
||||||
|
|
||||||
|
return formatPathWithPosition({
|
||||||
|
path: translatedPath,
|
||||||
|
...(parsed.line ? { line: parsed.line } : {}),
|
||||||
|
...(parsed.column ? { column: parsed.column } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveOpenCommand(
|
||||||
|
editorId: EditorId,
|
||||||
|
options: ResolveOpenOptions,
|
||||||
|
): ReadonlyArray<string> {
|
||||||
|
const platform = options.platform ?? process.platform;
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||||
|
const editorDef = EDITORS.find((editor) => editor.id === editorId);
|
||||||
|
if (!editorDef) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (editorId === "file-manager") {
|
||||||
|
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||||
|
return ["explorer.exe", "xdg-open"];
|
||||||
|
}
|
||||||
|
return [fileManagerCommandForPlatform(platform)];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!editorDef.command) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||||
|
return [editorDef.command, `${editorDef.command}.exe`];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [editorDef.command];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveBrowserLaunch(
|
||||||
|
target: string,
|
||||||
|
options: ResolveOpenOptions = {},
|
||||||
|
): EditorLaunch | null {
|
||||||
|
const platform = options.platform ?? process.platform;
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||||
|
|
||||||
|
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted") {
|
||||||
|
if (isCommandAvailable("wslview", { platform, env })) {
|
||||||
|
return { command: "wslview", args: [target] };
|
||||||
|
}
|
||||||
|
if (isCommandAvailable("explorer.exe", { platform, env })) {
|
||||||
|
return { command: "explorer.exe", args: [target] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||||
input: OpenInEditorInput,
|
input: OpenInEditorInput,
|
||||||
platform: NodeJS.Platform = process.platform,
|
options: ResolveOpenOptions = {},
|
||||||
): Effect.fn.Return<EditorLaunch, OpenError> {
|
): Effect.fn.Return<EditorLaunch, OpenError> {
|
||||||
|
const platform = options.platform ?? process.platform;
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const runtimeEnvironment = detectRuntimeEnvironment({ ...options, platform, env });
|
||||||
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
|
||||||
if (!editorDef) {
|
if (!editorDef) {
|
||||||
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const translateWslPathToWindows = options.translateWslPathToWindows ?? defaultTranslateWslPathToWindows;
|
||||||
|
|
||||||
if (editorDef.command) {
|
if (editorDef.command) {
|
||||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
platform,
|
||||||
: { command: editorDef.command, args: [input.cwd] };
|
env,
|
||||||
|
runtimeEnvironment,
|
||||||
|
});
|
||||||
|
const command =
|
||||||
|
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||||
|
candidateCommands[0];
|
||||||
|
if (!command) {
|
||||||
|
return yield* new OpenError({ message: `Editor command not found: ${editorDef.command}` });
|
||||||
|
}
|
||||||
|
|
||||||
|
const usesWindowsPath = runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command.endsWith(".exe");
|
||||||
|
const target = usesWindowsPath
|
||||||
|
? yield* Effect.try({
|
||||||
|
try: () => translateWslPathToWindows(input.cwd),
|
||||||
|
catch: (cause) =>
|
||||||
|
new OpenError({
|
||||||
|
message: "Failed to translate WSL path for Windows editor launch",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
: input.cwd;
|
||||||
|
|
||||||
|
return shouldUseGotoFlag(editorDef.id, target)
|
||||||
|
? { command, args: ["--goto", target] }
|
||||||
|
: { command, args: [target] };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (editorDef.id !== "file-manager") {
|
if (editorDef.id !== "file-manager") {
|
||||||
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (platform) {
|
const candidateCommands = resolveOpenCommand(editorDef.id, {
|
||||||
case "darwin":
|
platform,
|
||||||
return { command: "open", args: [input.cwd] };
|
env,
|
||||||
case "win32":
|
runtimeEnvironment,
|
||||||
return { command: "explorer", args: [input.cwd] };
|
});
|
||||||
default:
|
const command =
|
||||||
return { command: "xdg-open", args: [input.cwd] };
|
candidateCommands.find((entry) => isCommandAvailable(entry, { platform, env })) ??
|
||||||
|
candidateCommands[0];
|
||||||
|
if (!command) {
|
||||||
|
return yield* new OpenError({ message: "Editor command not found: file-manager" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let target = stripLineColumnSuffix(input.cwd);
|
||||||
|
if (runtimeEnvironment.windowsInteropMode === "wsl-hosted" && command === "explorer.exe") {
|
||||||
|
target = yield* Effect.try({
|
||||||
|
try: () => stripLineColumnSuffix(translateWslPathToWindows(target)),
|
||||||
|
catch: (cause) =>
|
||||||
|
new OpenError({
|
||||||
|
message: "Failed to translate WSL path for Windows file manager launch",
|
||||||
|
cause,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { command, args: [target] };
|
||||||
});
|
});
|
||||||
|
|
||||||
export const launchDetached = (launch: EditorLaunch) =>
|
export const launchDetached = (launch: EditorLaunch) =>
|
||||||
Effect.callback<void, OpenError>((resume) => {
|
Effect.tryPromise({
|
||||||
let child;
|
try: async () => {
|
||||||
try {
|
if (!isCommandAvailable(launch.command)) {
|
||||||
child = spawn(launch.command, [...launch.args], {
|
throw new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||||
detached: true,
|
}
|
||||||
stdio: "ignore",
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
return resume(
|
|
||||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleSpawn = () => {
|
await spawnDetachedProcess(launch.command, [...launch.args]);
|
||||||
child.unref();
|
},
|
||||||
resume(Effect.void);
|
catch: (cause) =>
|
||||||
};
|
Schema.is(OpenError)(cause)
|
||||||
|
? cause
|
||||||
child.once("spawn", handleSpawn);
|
: new OpenError({ message: "failed to spawn detached process", cause }),
|
||||||
child.once("error", (cause) =>
|
|
||||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const make = Effect.gen(function* () {
|
const make = Effect.gen(function* () {
|
||||||
@@ -123,11 +451,16 @@ const make = Effect.gen(function* () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
openBrowser: (target) =>
|
openBrowser: (target) => {
|
||||||
Effect.tryPromise({
|
const launch = resolveBrowserLaunch(target);
|
||||||
|
if (launch) {
|
||||||
|
return launchDetached(launch);
|
||||||
|
}
|
||||||
|
return Effect.tryPromise({
|
||||||
try: () => open.default(target),
|
try: () => open.default(target),
|
||||||
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
|
||||||
}),
|
});
|
||||||
|
},
|
||||||
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
|
||||||
} satisfies OpenShape;
|
} satisfies OpenShape;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ 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);
|
||||||
@@ -238,6 +239,7 @@ describe("CheckpointReactor", () => {
|
|||||||
Layer.provideMerge(orchestrationLayer),
|
Layer.provideMerge(orchestrationLayer),
|
||||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||||
Layer.provideMerge(CheckpointStoreLive),
|
Layer.provideMerge(CheckpointStoreLive),
|
||||||
|
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||||
Layer.provideMerge(NodeServices.layer),
|
Layer.provideMerge(NodeServices.layer),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -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));
|
||||||
@@ -310,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));
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,3 @@
|
|||||||
import Mime from "@effect/platform-node/Mime";
|
|
||||||
import {
|
import {
|
||||||
ApprovalRequestId,
|
ApprovalRequestId,
|
||||||
type ChatAttachment,
|
type ChatAttachment,
|
||||||
@@ -39,10 +38,11 @@ import {
|
|||||||
type OrchestrationProjectionPipelineShape,
|
type OrchestrationProjectionPipelineShape,
|
||||||
} from "../Services/ProjectionPipeline.ts";
|
} from "../Services/ProjectionPipeline.ts";
|
||||||
import {
|
import {
|
||||||
ATTACHMENTS_ROUTE_PREFIX,
|
attachmentRelativePath,
|
||||||
IMAGE_EXTENSION_BY_MIME_TYPE,
|
parseAttachmentIdFromRelativePath,
|
||||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
parseThreadSegmentFromAttachmentId,
|
||||||
} from "../../projectFaviconRoute.ts";
|
toSafeThreadAttachmentSegment,
|
||||||
|
} from "../../attachmentStore.ts";
|
||||||
|
|
||||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||||
projects: "projection.projects",
|
projects: "projection.projects",
|
||||||
@@ -66,115 +66,16 @@ interface ProjectorDefinition {
|
|||||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PendingAttachmentWrite {
|
|
||||||
readonly absolutePath: string;
|
|
||||||
readonly bytes: Uint8Array;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AttachmentSideEffects {
|
interface AttachmentSideEffects {
|
||||||
readonly writes: Array<PendingAttachmentWrite>;
|
|
||||||
readonly deletedThreadIds: Set<string>;
|
readonly deletedThreadIds: Set<string>;
|
||||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
const materializeAttachmentsForProjection = Effect.fn(
|
||||||
const segment = encodeURIComponent(threadId);
|
(input: {
|
||||||
if (
|
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||||
segment.length === 0 ||
|
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||||
segment === "." ||
|
);
|
||||||
segment === ".." ||
|
|
||||||
segment.includes("/") ||
|
|
||||||
segment.includes("\\") ||
|
|
||||||
segment.includes("\0")
|
|
||||||
) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return segment;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseBase64DataUrl(
|
|
||||||
dataUrl: string,
|
|
||||||
): { readonly mimeType: string; readonly base64: string } | null {
|
|
||||||
const match = /^data:([^;,]+);base64,([a-z0-9+/=\r\n]+)$/i.exec(dataUrl.trim());
|
|
||||||
if (!match) return null;
|
|
||||||
|
|
||||||
const mimeType = match[1]?.trim().toLowerCase();
|
|
||||||
const base64 = match[2]?.replace(/\s+/g, "");
|
|
||||||
if (!mimeType || !base64) return null;
|
|
||||||
|
|
||||||
return { mimeType, base64 };
|
|
||||||
}
|
|
||||||
|
|
||||||
function inferImageExtension(attachment: Extract<ChatAttachment, { type: "image" }>): string {
|
|
||||||
const normalizedMimeType = attachment.mimeType.toLowerCase();
|
|
||||||
if (normalizedMimeType.startsWith("image/")) {
|
|
||||||
const fromMime = IMAGE_EXTENSION_BY_MIME_TYPE[normalizedMimeType];
|
|
||||||
if (fromMime) return fromMime;
|
|
||||||
}
|
|
||||||
const ext = Mime.getExtension(attachment.mimeType);
|
|
||||||
if (ext && SAFE_IMAGE_FILE_EXTENSIONS.has(ext)) return ext;
|
|
||||||
return ".bin";
|
|
||||||
}
|
|
||||||
|
|
||||||
const materializeAttachmentsForProjection = Effect.fn(function* (input: {
|
|
||||||
readonly threadId: string;
|
|
||||||
readonly messageId: string;
|
|
||||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
|
||||||
readonly stageFileWrite: (pendingWrite: PendingAttachmentWrite) => void;
|
|
||||||
}) {
|
|
||||||
if (input.attachments.length === 0) return [];
|
|
||||||
|
|
||||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
|
||||||
if (Option.isNone(serverConfig)) return input.attachments;
|
|
||||||
|
|
||||||
const path = yield* Path.Path;
|
|
||||||
const attachmentsRootDir = path.join(serverConfig.value.stateDir, "attachments");
|
|
||||||
const threadSegment = toSafeThreadAttachmentSegment(input.threadId);
|
|
||||||
if (!threadSegment) {
|
|
||||||
yield* Effect.logWarning("skipping attachment materialization for unsafe thread id", {
|
|
||||||
threadId: input.threadId,
|
|
||||||
messageId: input.messageId,
|
|
||||||
});
|
|
||||||
return input.attachments;
|
|
||||||
}
|
|
||||||
const messageSegment = encodeURIComponent(input.messageId);
|
|
||||||
|
|
||||||
return yield* Effect.forEach(
|
|
||||||
input.attachments,
|
|
||||||
(attachment, index) =>
|
|
||||||
Effect.sync(() => {
|
|
||||||
if (attachment.type !== "image" || !attachment.dataUrl.startsWith("data:")) {
|
|
||||||
return attachment;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
|
||||||
if (!parsed) {
|
|
||||||
return attachment;
|
|
||||||
}
|
|
||||||
if (!parsed.mimeType.startsWith("image/")) {
|
|
||||||
return attachment;
|
|
||||||
}
|
|
||||||
|
|
||||||
const bytes = Buffer.from(parsed.base64, "base64");
|
|
||||||
if (bytes.byteLength === 0) return attachment;
|
|
||||||
|
|
||||||
const fileName = `${index}${inferImageExtension({
|
|
||||||
...attachment,
|
|
||||||
mimeType: parsed.mimeType,
|
|
||||||
})}`;
|
|
||||||
const uniqueFileName = `${messageSegment}-${fileName}`;
|
|
||||||
const relativePath = `${threadSegment}/${uniqueFileName}`;
|
|
||||||
const absolutePath = path.join(attachmentsRootDir, threadSegment, uniqueFileName);
|
|
||||||
input.stageFileWrite({ absolutePath, bytes });
|
|
||||||
|
|
||||||
return {
|
|
||||||
...attachment,
|
|
||||||
dataUrl: `${ATTACHMENTS_ROUTE_PREFIX}/${relativePath}`,
|
|
||||||
} satisfies ChatAttachment;
|
|
||||||
}),
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||||
if (typeof payload !== "object" || payload === null) {
|
if (typeof payload !== "object" || payload === null) {
|
||||||
@@ -288,18 +189,6 @@ function retainProjectionActivitiesAfterRevert(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toAttachmentRelativePath(dataUrl: string): string | null {
|
|
||||||
const prefix = `${ATTACHMENTS_ROUTE_PREFIX}/`;
|
|
||||||
if (!dataUrl.startsWith(prefix)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const relativePath = dataUrl.slice(prefix.length).replace(/^[/\\]+/, "");
|
|
||||||
if (relativePath.length === 0 || relativePath.startsWith("..")) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return relativePath.replace(/\\/g, "/");
|
|
||||||
}
|
|
||||||
|
|
||||||
function collectThreadAttachmentRelativePaths(
|
function collectThreadAttachmentRelativePaths(
|
||||||
threadId: string,
|
threadId: string,
|
||||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||||
@@ -308,41 +197,31 @@ function collectThreadAttachmentRelativePaths(
|
|||||||
if (!threadSegment) {
|
if (!threadSegment) {
|
||||||
return new Set();
|
return new Set();
|
||||||
}
|
}
|
||||||
const threadPrefix = `${threadSegment}/`;
|
|
||||||
const relativePaths = new Set<string>();
|
const relativePaths = new Set<string>();
|
||||||
for (const message of messages) {
|
for (const message of messages) {
|
||||||
for (const attachment of message.attachments ?? []) {
|
for (const attachment of message.attachments ?? []) {
|
||||||
if (attachment.type !== "image") {
|
if (attachment.type !== "image") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const relativePath = toAttachmentRelativePath(attachment.dataUrl);
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
|
||||||
if (!relativePath || !relativePath.startsWith(threadPrefix)) {
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");
|
relativePaths.add(attachmentRelativePath(attachment));
|
||||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
relativePaths.add(threadRelativePath.replace(/\\/g, "/"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return relativePaths;
|
return relativePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
const runAttachmentSideEffects = Effect.fn(function* (input: {
|
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
|
||||||
readonly sideEffects: AttachmentSideEffects;
|
const serverConfig = yield* Effect.service(ServerConfig);
|
||||||
readonly fileSystem: FileSystem.FileSystem;
|
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||||
readonly path: Path.Path;
|
const path = yield* Effect.service(Path.Path);
|
||||||
}) {
|
|
||||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
|
||||||
if (Option.isNone(serverConfig)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const attachmentsRootDir = input.path.join(serverConfig.value.stateDir, "attachments");
|
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.sideEffects.deletedThreadIds,
|
sideEffects.deletedThreadIds,
|
||||||
(threadId) =>
|
(threadId) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||||
@@ -352,16 +231,39 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
const entries = yield* fileSystem
|
||||||
yield* input.fileSystem.remove(threadDir, { recursive: true, force: true });
|
.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 },
|
{ concurrency: 1 },
|
||||||
);
|
);
|
||||||
|
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
input.sideEffects.prunedThreadRelativePaths.entries(),
|
sideEffects.prunedThreadRelativePaths.entries(),
|
||||||
([threadId, keptThreadRelativePaths]) => {
|
([threadId, keptThreadRelativePaths]) => {
|
||||||
if (input.sideEffects.deletedThreadIds.has(threadId)) {
|
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||||
return Effect.void;
|
return Effect.void;
|
||||||
}
|
}
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
@@ -370,29 +272,36 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
|||||||
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
const entries = yield* fileSystem
|
||||||
const entries = yield* input.fileSystem
|
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||||
.readDirectory(threadDir, { recursive: true })
|
|
||||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||||
yield* Effect.forEach(
|
yield* Effect.forEach(
|
||||||
entries,
|
entries,
|
||||||
(entry) =>
|
(entry) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const threadRelativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||||
|
if (!attachmentId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||||
|
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const absolutePath = input.path.join(threadDir, threadRelativePath);
|
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||||
const fileInfo = yield* input.fileSystem
|
const fileInfo = yield* fileSystem
|
||||||
.stat(absolutePath)
|
.stat(absolutePath)
|
||||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||||
if (!fileInfo || fileInfo.type !== "File") {
|
if (!fileInfo || fileInfo.type !== "File") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!keptThreadRelativePaths.has(threadRelativePath)) {
|
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||||
yield* input.fileSystem.remove(absolutePath, { force: true });
|
yield* fileSystem.remove(absolutePath, { force: true });
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
@@ -402,22 +311,6 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
|||||||
{ concurrency: 1 },
|
{ concurrency: 1 },
|
||||||
);
|
);
|
||||||
|
|
||||||
const writesByPath = new Map<string, Uint8Array>();
|
|
||||||
for (const pendingWrite of input.sideEffects.writes) {
|
|
||||||
// Last write wins for a path so updated attachment contents replace stale bytes.
|
|
||||||
writesByPath.set(pendingWrite.absolutePath, pendingWrite.bytes);
|
|
||||||
}
|
|
||||||
yield* Effect.forEach(
|
|
||||||
writesByPath.entries(),
|
|
||||||
([absolutePath, bytes]) =>
|
|
||||||
Effect.gen(function* () {
|
|
||||||
yield* input.fileSystem.makeDirectory(input.path.dirname(absolutePath), {
|
|
||||||
recursive: true,
|
|
||||||
});
|
|
||||||
yield* input.fileSystem.writeFile(absolutePath, bytes);
|
|
||||||
}),
|
|
||||||
{ concurrency: 1 },
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||||
@@ -434,6 +327,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
|
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
|
const serverConfig = yield* ServerConfig;
|
||||||
|
|
||||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
@@ -634,13 +528,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const nextAttachments =
|
const nextAttachments =
|
||||||
event.payload.attachments !== undefined
|
event.payload.attachments !== undefined
|
||||||
? yield* materializeAttachmentsForProjection({
|
? yield* materializeAttachmentsForProjection({
|
||||||
threadId: event.payload.threadId,
|
|
||||||
messageId: event.payload.messageId,
|
|
||||||
attachments: event.payload.attachments,
|
attachments: event.payload.attachments,
|
||||||
stageFileWrite: (pendingWrite) => {
|
})
|
||||||
attachmentSideEffects.writes.push(pendingWrite);
|
|
||||||
},
|
|
||||||
}).pipe(Effect.provideService(Path.Path, path))
|
|
||||||
: existingMessage?.attachments;
|
: existingMessage?.attachments;
|
||||||
yield* projectionThreadMessageRepository.upsert({
|
yield* projectionThreadMessageRepository.upsert({
|
||||||
messageId: event.payload.messageId,
|
messageId: event.payload.messageId,
|
||||||
@@ -1131,7 +1020,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const attachmentSideEffects: AttachmentSideEffects = {
|
const attachmentSideEffects: AttachmentSideEffects = {
|
||||||
writes: [],
|
|
||||||
deletedThreadIds: new Set<string>(),
|
deletedThreadIds: new Set<string>(),
|
||||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||||
};
|
};
|
||||||
@@ -1148,11 +1036,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
yield* runAttachmentSideEffects({
|
yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
|
||||||
sideEffects: attachmentSideEffects,
|
|
||||||
fileSystem,
|
|
||||||
path,
|
|
||||||
}).pipe(
|
|
||||||
Effect.catch((cause) =>
|
Effect.catch((cause) =>
|
||||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||||
projector: projector.name,
|
projector: projector.name,
|
||||||
@@ -1184,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)),
|
||||||
@@ -1195,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(
|
||||||
|
|||||||
@@ -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,10 +76,16 @@ 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>());
|
||||||
let nextSessionIndex = 1;
|
let nextSessionIndex = 1;
|
||||||
const startSession = vi.fn((_: unknown, __: unknown) => {
|
const startSession = vi.fn((_: unknown, __: unknown) => {
|
||||||
@@ -92,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 = {
|
||||||
@@ -115,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"));
|
||||||
@@ -155,6 +188,9 @@ describe("ProviderCommandReactor", () => {
|
|||||||
interruptTurn,
|
interruptTurn,
|
||||||
respondToRequest,
|
respondToRequest,
|
||||||
stopSession,
|
stopSession,
|
||||||
|
renameBranch,
|
||||||
|
generateBranchName,
|
||||||
|
stateDir,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,6 +232,247 @@ describe("ProviderCommandReactor", () => {
|
|||||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
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 () => {
|
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||||
const harness = await createHarness();
|
const harness = await createHarness();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -328,8 +605,8 @@ describe("ProviderCommandReactor", () => {
|
|||||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||||
|
|
||||||
harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
|
harness.startSession.mockImplementationOnce(
|
||||||
Effect.fail(new Error("simulated restart failure")) as never,
|
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
await Effect.runPromise(
|
await Effect.runPromise(
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import {
|
|||||||
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 {
|
||||||
@@ -66,10 +68,41 @@ 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_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
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,
|
||||||
@@ -190,7 +223,8 @@ const make = Effect.gen(function* () {
|
|||||||
const existingSessionId = thread.session?.providerSessionId;
|
const existingSessionId = thread.session?.providerSessionId;
|
||||||
if (existingSessionId) {
|
if (existingSessionId) {
|
||||||
const approvalPolicyChanged =
|
const approvalPolicyChanged =
|
||||||
options?.approvalPolicy !== undefined && options.approvalPolicy !== thread.session?.approvalPolicy;
|
options?.approvalPolicy !== undefined &&
|
||||||
|
options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||||
const sandboxModeChanged =
|
const sandboxModeChanged =
|
||||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||||
|
|
||||||
@@ -198,7 +232,9 @@ const make = Effect.gen(function* () {
|
|||||||
return existingSessionId;
|
return existingSessionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
const restartedSession = yield* startProviderSession(thread.session?.providerThreadId ?? null);
|
const restartedSession = yield* startProviderSession(
|
||||||
|
thread.session?.providerThreadId ?? null,
|
||||||
|
);
|
||||||
yield* bindSessionToThread(restartedSession);
|
yield* bindSessionToThread(restartedSession);
|
||||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||||
Effect.catchCause((cause) =>
|
Effect.catchCause((cause) =>
|
||||||
@@ -247,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" }>,
|
||||||
) {
|
) {
|
||||||
@@ -273,6 +377,15 @@ 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,
|
||||||
|
|||||||
@@ -28,11 +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 =>
|
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||||
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);
|
||||||
@@ -122,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));
|
||||||
@@ -255,7 +258,9 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
await Effect.runPromise(Effect.sleep("40 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?.session?.status).toBe("running");
|
expect(midThread?.session?.status).toBe("running");
|
||||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||||
|
|
||||||
@@ -308,7 +313,9 @@ describe("ProviderRuntimeIngestion", () => {
|
|||||||
|
|
||||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
await Effect.runPromise(Effect.sleep("40 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?.session?.status).toBe("running");
|
expect(midThread?.session?.status).toBe("running");
|
||||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||||
|
|
||||||
@@ -401,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,
|
||||||
);
|
);
|
||||||
@@ -416,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");
|
||||||
@@ -475,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",
|
||||||
@@ -500,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",
|
||||||
@@ -554,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);
|
||||||
|
|||||||
@@ -415,8 +415,7 @@ const make = Effect.gen(function* () {
|
|||||||
: event.threadId !== undefined
|
: event.threadId !== undefined
|
||||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||||
: null;
|
: null;
|
||||||
const providerThreadId =
|
const providerThreadId = providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
||||||
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
|
|
||||||
const status =
|
const status =
|
||||||
event.type === "turn.started"
|
event.type === "turn.started"
|
||||||
? "running"
|
? "running"
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
|||||||
const persistedAttachments = [
|
const persistedAttachments = [
|
||||||
{
|
{
|
||||||
type: "image" as const,
|
type: "image" as const,
|
||||||
|
id: "thread-preserve-attachments-att-1",
|
||||||
name: "example.png",
|
name: "example.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
dataUrl: "/attachments/thread-preserve-attachments/message-preserve-attachments/0.png",
|
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -74,10 +74,10 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
|||||||
attachments: [
|
attachments: [
|
||||||
{
|
{
|
||||||
type: "image",
|
type: "image",
|
||||||
|
id: "thread-clear-attachments-att-1",
|
||||||
name: "example.png",
|
name: "example.png",
|
||||||
mimeType: "image/png",
|
mimeType: "image/png",
|
||||||
sizeBytes: 5,
|
sizeBytes: 5,
|
||||||
dataUrl: "/attachments/thread-clear-attachments/message-clear-attachments/0.png",
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
isStreaming: false,
|
isStreaming: false,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { runProcess } from "./processRunner";
|
import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner";
|
||||||
|
|
||||||
describe("runProcess", () => {
|
describe("runProcess", () => {
|
||||||
it("fails when output exceeds max buffer in default mode", async () => {
|
it("fails when output exceeds max buffer in default mode", async () => {
|
||||||
@@ -20,4 +20,20 @@ describe("runProcess", () => {
|
|||||||
expect(result.stdoutTruncated).toBe(true);
|
expect(result.stdoutTruncated).toBe(true);
|
||||||
expect(result.stderrTruncated).toBe(false);
|
expect(result.stderrTruncated).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("runs sync commands through the shared spawn strategy", () => {
|
||||||
|
const result = spawnProcessSync("node", ["-e", "process.stdout.write('ok')"], {
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.error).toBeUndefined();
|
||||||
|
expect(result.status).toBe(0);
|
||||||
|
expect(result.stdout).toBe("ok");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("spawns detached commands through the shared spawn strategy", async () => {
|
||||||
|
await expect(
|
||||||
|
spawnDetachedProcess(process.execPath, ["-e", "process.exit(0)"]),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,4 +1,44 @@
|
|||||||
import { spawn } from "node:child_process";
|
import {
|
||||||
|
type ChildProcess as ChildProcessHandle,
|
||||||
|
type ChildProcessWithoutNullStreams,
|
||||||
|
spawn,
|
||||||
|
spawnSync,
|
||||||
|
type StdioOptions,
|
||||||
|
} from "node:child_process";
|
||||||
|
|
||||||
|
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||||
|
import { Effect, Exit, Scope } from "effect";
|
||||||
|
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||||
|
|
||||||
|
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||||
|
|
||||||
|
interface ProcessSpawnBaseOptions {
|
||||||
|
cwd?: string | undefined;
|
||||||
|
env?: NodeJS.ProcessEnv | undefined;
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||||
|
shell?: boolean | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RuntimeShellOptions {
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||||
|
shell?: boolean | string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProcessSpawnOptions extends ProcessSpawnBaseOptions {
|
||||||
|
stdio?: StdioOptions | undefined;
|
||||||
|
detached?: boolean | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RuntimeCommandOptions extends ChildProcess.CommandOptions {
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ProcessSpawnSyncOptions extends ProcessSpawnBaseOptions {
|
||||||
|
stdio?: StdioOptions | undefined;
|
||||||
|
detached?: boolean | undefined;
|
||||||
|
encoding?: BufferEncoding | undefined;
|
||||||
|
input?: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ProcessRunOptions {
|
export interface ProcessRunOptions {
|
||||||
cwd?: string | undefined;
|
cwd?: string | undefined;
|
||||||
@@ -8,6 +48,8 @@ export interface ProcessRunOptions {
|
|||||||
allowNonZeroExit?: boolean | undefined;
|
allowNonZeroExit?: boolean | undefined;
|
||||||
maxBufferBytes?: number | undefined;
|
maxBufferBytes?: number | undefined;
|
||||||
outputMode?: "error" | "truncate" | undefined;
|
outputMode?: "error" | "truncate" | undefined;
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||||
|
shell?: boolean | undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProcessRunResult {
|
export interface ProcessRunResult {
|
||||||
@@ -24,6 +66,127 @@ function commandLabel(command: string, args: readonly string[]): string {
|
|||||||
return [command, ...args].join(" ");
|
return [command, ...args].join(" ");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveRuntimeEnvironment(
|
||||||
|
runtimeEnvironment: ServerRuntimeEnvironment | undefined,
|
||||||
|
): ServerRuntimeEnvironment {
|
||||||
|
return runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||||
|
}
|
||||||
|
|
||||||
|
function shouldUseShell(options: RuntimeShellOptions): boolean | string {
|
||||||
|
if (options.shell !== undefined) {
|
||||||
|
return options.shell;
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows";
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSpawnOptions(options: ProcessSpawnOptions) {
|
||||||
|
return {
|
||||||
|
cwd: options.cwd,
|
||||||
|
env: options.env,
|
||||||
|
shell: shouldUseShell(options),
|
||||||
|
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||||
|
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toRuntimeCommandOptions(
|
||||||
|
options: RuntimeCommandOptions = {},
|
||||||
|
): ChildProcess.CommandOptions {
|
||||||
|
const { runtimeEnvironment: _, ...rest } = options;
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
shell: options.shell ?? shouldUseShell(options),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeRuntimeCommand(
|
||||||
|
command: string,
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
options: RuntimeCommandOptions = {},
|
||||||
|
): ChildProcess.StandardCommand {
|
||||||
|
return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ManagedChildProcess {
|
||||||
|
readonly scope: Scope.Closeable;
|
||||||
|
readonly handle: ChildProcessSpawner.ChildProcessHandle;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const spawnManagedCommand = (command: ChildProcess.Command) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const scope = yield* Scope.make("sequential");
|
||||||
|
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||||
|
const handle = yield* spawner.spawn(command).pipe(
|
||||||
|
Scope.provide(scope),
|
||||||
|
Effect.tapError(() => Scope.close(scope, Exit.void)),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
scope,
|
||||||
|
handle,
|
||||||
|
} satisfies ManagedChildProcess;
|
||||||
|
});
|
||||||
|
|
||||||
|
function spawnProcess(
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
options: ProcessSpawnOptions = {},
|
||||||
|
): ChildProcessHandle {
|
||||||
|
return spawn(command, args, toSpawnOptions(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnPipedProcess(
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||||
|
): ChildProcessWithoutNullStreams {
|
||||||
|
return spawnProcess(command, args, {
|
||||||
|
...options,
|
||||||
|
stdio: "pipe",
|
||||||
|
}) as ChildProcessWithoutNullStreams;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function spawnProcessSync(
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
options: ProcessSpawnSyncOptions = {},
|
||||||
|
) {
|
||||||
|
return spawnSync(command, args, {
|
||||||
|
cwd: options.cwd,
|
||||||
|
env: options.env,
|
||||||
|
shell: shouldUseShell(options),
|
||||||
|
encoding: options.encoding ?? "utf8",
|
||||||
|
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
|
||||||
|
...(options.detached !== undefined ? { detached: options.detached } : {}),
|
||||||
|
...(options.input !== undefined ? { input: options.input } : {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function spawnDetachedProcess(
|
||||||
|
command: string,
|
||||||
|
args: readonly string[],
|
||||||
|
options: Omit<ProcessSpawnOptions, "stdio" | "detached"> = {},
|
||||||
|
): Promise<void> {
|
||||||
|
return new Promise<void>((resolve, reject) => {
|
||||||
|
const child = spawnProcess(command, args, {
|
||||||
|
...options,
|
||||||
|
detached: true,
|
||||||
|
stdio: "ignore",
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSpawn = () => {
|
||||||
|
child.unref();
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
child.once("spawn", handleSpawn);
|
||||||
|
child.once("error", (error) => {
|
||||||
|
reject(normalizeSpawnError(command, args, error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
|
||||||
if (!(error instanceof Error)) {
|
if (!(error instanceof Error)) {
|
||||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||||
@@ -37,11 +200,26 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
|||||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isWindowsCommandNotFound(
|
||||||
|
code: number | null,
|
||||||
|
stderr: string,
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||||
|
): boolean {
|
||||||
|
if (resolveRuntimeEnvironment(runtimeEnvironment).platform !== "windows") return false;
|
||||||
|
if (code === 9009) return true;
|
||||||
|
return /is not recognized as an internal or external command/i.test(stderr);
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeExitError(
|
function normalizeExitError(
|
||||||
command: string,
|
command: string,
|
||||||
args: readonly string[],
|
args: readonly string[],
|
||||||
result: ProcessRunResult,
|
result: ProcessRunResult,
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment,
|
||||||
): Error {
|
): Error {
|
||||||
|
if (isWindowsCommandNotFound(result.code, result.stderr, runtimeEnvironment)) {
|
||||||
|
return new Error(`Command not found: ${command}`);
|
||||||
|
}
|
||||||
|
|
||||||
const reason = result.timedOut
|
const reason = result.timedOut
|
||||||
? "timed out"
|
? "timed out"
|
||||||
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
||||||
@@ -70,6 +248,42 @@ function normalizeBufferError(
|
|||||||
|
|
||||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||||
|
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||||
|
* entire process tree instead.
|
||||||
|
*/
|
||||||
|
function killProcessTree(
|
||||||
|
child: ChildProcessHandle,
|
||||||
|
options: {
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment | undefined;
|
||||||
|
signal?: NodeJS.Signals | undefined;
|
||||||
|
} = {},
|
||||||
|
): void {
|
||||||
|
const signal = options.signal ?? "SIGTERM";
|
||||||
|
if (
|
||||||
|
resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows" &&
|
||||||
|
child.pid !== undefined
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const result = spawnProcessSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
||||||
|
stdio: "ignore",
|
||||||
|
shell: false,
|
||||||
|
runtimeEnvironment: options.runtimeEnvironment,
|
||||||
|
});
|
||||||
|
if (!result.error && result.status === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (result.error) {
|
||||||
|
throw result.error;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// fallback to direct kill
|
||||||
|
}
|
||||||
|
}
|
||||||
|
child.kill(signal);
|
||||||
|
}
|
||||||
|
|
||||||
function appendChunkWithinLimit(
|
function appendChunkWithinLimit(
|
||||||
target: string,
|
target: string,
|
||||||
currentBytes: number,
|
currentBytes: number,
|
||||||
@@ -108,11 +322,7 @@ export async function runProcess(
|
|||||||
const outputMode = options.outputMode ?? "error";
|
const outputMode = options.outputMode ?? "error";
|
||||||
|
|
||||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||||
const child = spawn(command, args, {
|
const child = spawnPipedProcess(command, args, options);
|
||||||
cwd: options.cwd,
|
|
||||||
env: options.env,
|
|
||||||
stdio: "pipe",
|
|
||||||
});
|
|
||||||
|
|
||||||
let stdout = "";
|
let stdout = "";
|
||||||
let stderr = "";
|
let stderr = "";
|
||||||
@@ -126,9 +336,15 @@ export async function runProcess(
|
|||||||
|
|
||||||
const timeoutTimer = setTimeout(() => {
|
const timeoutTimer = setTimeout(() => {
|
||||||
timedOut = true;
|
timedOut = true;
|
||||||
child.kill("SIGTERM");
|
killProcessTree(child, {
|
||||||
|
runtimeEnvironment: options.runtimeEnvironment,
|
||||||
|
signal: "SIGTERM",
|
||||||
|
});
|
||||||
forceKillTimer = setTimeout(() => {
|
forceKillTimer = setTimeout(() => {
|
||||||
child.kill("SIGKILL");
|
killProcessTree(child, {
|
||||||
|
runtimeEnvironment: options.runtimeEnvironment,
|
||||||
|
signal: "SIGKILL",
|
||||||
|
});
|
||||||
}, 1_000);
|
}, 1_000);
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
@@ -143,7 +359,10 @@ export async function runProcess(
|
|||||||
};
|
};
|
||||||
|
|
||||||
const fail = (error: Error): void => {
|
const fail = (error: Error): void => {
|
||||||
child.kill("SIGTERM");
|
killProcessTree(child, {
|
||||||
|
runtimeEnvironment: options.runtimeEnvironment,
|
||||||
|
signal: "SIGTERM",
|
||||||
|
});
|
||||||
finalize(() => {
|
finalize(() => {
|
||||||
reject(error);
|
reject(error);
|
||||||
});
|
});
|
||||||
@@ -216,7 +435,7 @@ export async function runProcess(
|
|||||||
|
|
||||||
finalize(() => {
|
finalize(() => {
|
||||||
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
|
||||||
reject(normalizeExitError(command, args, result));
|
reject(normalizeExitError(command, args, result, options.runtimeEnvironment));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
resolve(result);
|
resolve(result);
|
||||||
|
|||||||
@@ -152,4 +152,16 @@ describe("tryHandleProjectFaviconRequest", () => {
|
|||||||
expect(response.body).toBe("<svg>brand-obj-order</svg>");
|
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"');
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -2,32 +2,6 @@ import fs from "node:fs";
|
|||||||
import http from "node:http";
|
import http from "node:http";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
|
||||||
|
|
||||||
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
|
||||||
"image/png": ".png",
|
|
||||||
"image/jpeg": ".jpg",
|
|
||||||
"image/jpg": ".jpg",
|
|
||||||
"image/gif": ".gif",
|
|
||||||
"image/webp": ".webp",
|
|
||||||
"image/svg+xml": ".svg",
|
|
||||||
"image/bmp": ".bmp",
|
|
||||||
"image/tiff": ".tiff",
|
|
||||||
"image/heic": ".heic",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
|
||||||
".jpg",
|
|
||||||
".jpeg",
|
|
||||||
".png",
|
|
||||||
".gif",
|
|
||||||
".webp",
|
|
||||||
".bmp",
|
|
||||||
".tiff",
|
|
||||||
".svg",
|
|
||||||
".ico",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const FAVICON_MIME_TYPES: Record<string, string> = {
|
const FAVICON_MIME_TYPES: Record<string, string> = {
|
||||||
".png": "image/png",
|
".png": "image/png",
|
||||||
".jpg": "image/jpeg",
|
".jpg": "image/jpeg",
|
||||||
@@ -35,6 +9,8 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
|
|||||||
".ico": "image/x-icon",
|
".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.
|
// Well-known favicon paths checked in order.
|
||||||
const FAVICON_CANDIDATES = [
|
const FAVICON_CANDIDATES = [
|
||||||
"favicon.svg",
|
"favicon.svg",
|
||||||
@@ -111,6 +87,14 @@ function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function serveFallbackFavicon(res: http.ServerResponse): void {
|
||||||
|
res.writeHead(200, {
|
||||||
|
"Content-Type": "image/svg+xml",
|
||||||
|
"Cache-Control": "public, max-age=3600",
|
||||||
|
});
|
||||||
|
res.end(FALLBACK_FAVICON_SVG);
|
||||||
|
}
|
||||||
|
|
||||||
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
|
||||||
if (url.pathname !== "/api/project-favicon") {
|
if (url.pathname !== "/api/project-favicon") {
|
||||||
return false;
|
return false;
|
||||||
@@ -144,8 +128,7 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
|
|||||||
|
|
||||||
const trySourceFiles = (index: number): void => {
|
const trySourceFiles = (index: number): void => {
|
||||||
if (index >= ICON_SOURCE_FILES.length) {
|
if (index >= ICON_SOURCE_FILES.length) {
|
||||||
res.writeHead(404, { "Content-Type": "text/plain" });
|
serveFallbackFavicon(res);
|
||||||
res.end("No favicon found");
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
|
||||||
|
|||||||
@@ -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,14 +11,20 @@ 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, Option, 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 { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||||
|
|
||||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||||
@@ -44,7 +49,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 +83,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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,8 +122,24 @@ class FakeCodexManager extends CodexAppServerManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||||
|
upsert: () => Effect.void,
|
||||||
|
getProvider: () =>
|
||||||
|
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||||
|
getBinding: () => Effect.succeed(Option.none()),
|
||||||
|
getThreadId: () => Effect.succeed(Option.none()),
|
||||||
|
remove: () => Effect.void,
|
||||||
|
listSessionIds: () => Effect.succeed([]),
|
||||||
|
});
|
||||||
|
|
||||||
const validationManager = new FakeCodexManager();
|
const 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(providerSessionDirectoryTestLayer),
|
||||||
|
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 +168,13 @@ 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(providerSessionDirectoryTestLayer),
|
||||||
|
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 +205,13 @@ 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(providerSessionDirectoryTestLayer),
|
||||||
|
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, Option, Queue, Schema, Stream } from "effect";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ProviderAdapterProcessError,
|
ProviderAdapterProcessError,
|
||||||
@@ -28,8 +28,12 @@ import {
|
|||||||
type ProviderAdapterError,
|
type ProviderAdapterError,
|
||||||
} from "../Errors.ts";
|
} from "../Errors.ts";
|
||||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||||
|
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||||
|
import { ServerConfig } from "../../config.ts";
|
||||||
|
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||||
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||||
|
|
||||||
const PROVIDER = "codex" as const;
|
const PROVIDER = "codex" as const;
|
||||||
|
|
||||||
@@ -37,6 +41,7 @@ export interface CodexAdapterLiveOptions {
|
|||||||
readonly manager?: CodexAppServerManager;
|
readonly manager?: CodexAppServerManager;
|
||||||
readonly makeManager?: () => CodexAppServerManager;
|
readonly makeManager?: () => CodexAppServerManager;
|
||||||
readonly nativeEventLogPath?: string;
|
readonly nativeEventLogPath?: string;
|
||||||
|
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toMessage(cause: unknown, fallback: string): string {
|
function toMessage(cause: unknown, fallback: string): string {
|
||||||
@@ -426,10 +431,17 @@ 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 directory = yield* ProviderSessionDirectory;
|
||||||
|
const services = yield* Effect.services<NodeServices.NodeServices>();
|
||||||
const nativeEventLogger =
|
const nativeEventLogger =
|
||||||
options?.nativeEventLogPath !== undefined
|
options?.nativeEventLogger ??
|
||||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
(options?.nativeEventLogPath !== undefined
|
||||||
: undefined;
|
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||||
|
stream: "native",
|
||||||
|
})
|
||||||
|
: undefined);
|
||||||
|
|
||||||
const manager = yield* Effect.acquireRelease(
|
const manager = yield* Effect.acquireRelease(
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
@@ -439,7 +451,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
|||||||
if (options?.makeManager) {
|
if (options?.makeManager) {
|
||||||
return options.makeManager();
|
return options.makeManager();
|
||||||
}
|
}
|
||||||
return new CodexAppServerManager();
|
return new CodexAppServerManager(services);
|
||||||
}),
|
}),
|
||||||
(manager) =>
|
(manager) =>
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
@@ -475,9 +487,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* 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) =>
|
||||||
@@ -539,13 +590,29 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
|||||||
|
|
||||||
yield* Effect.acquireRelease(
|
yield* Effect.acquireRelease(
|
||||||
Effect.sync(() => {
|
Effect.sync(() => {
|
||||||
const listener = (event: ProviderEvent) => {
|
const writeNativeEvent = (event: ProviderEvent) =>
|
||||||
nativeEventLogger?.write({
|
Effect.gen(function* () {
|
||||||
observedAt: new Date().toISOString(),
|
if (!nativeEventLogger) {
|
||||||
event,
|
return;
|
||||||
|
}
|
||||||
|
const orchestrationThreadId = yield* Effect.catch(
|
||||||
|
directory
|
||||||
|
.getThreadId(event.sessionId)
|
||||||
|
.pipe(
|
||||||
|
Effect.map((threadIdOption) =>
|
||||||
|
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
() => Effect.succeed(null),
|
||||||
|
);
|
||||||
|
yield* nativeEventLogger.write(event, orchestrationThreadId);
|
||||||
});
|
});
|
||||||
Queue.offerAllUnsafe(runtimeEventQueue, mapToRuntimeEvents(event));
|
|
||||||
};
|
const listener = (event: ProviderEvent) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
yield* writeNativeEvent(event);
|
||||||
|
yield* Queue.offerAll(runtimeEventQueue, mapToRuntimeEvents(event));
|
||||||
|
}).pipe(Effect.runPromiseWith(services));
|
||||||
manager.on("event", listener);
|
manager.on("event", listener);
|
||||||
return listener;
|
return listener;
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -2,36 +2,165 @@ 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 { describe, expect, it } from "vitest";
|
import { ThreadId } from "@t3tools/contracts";
|
||||||
|
import { assert, describe, it } from "@effect/vitest";
|
||||||
|
import { Effect } from "effect";
|
||||||
|
|
||||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||||
|
|
||||||
|
function parseLogLine(line: string) {
|
||||||
|
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
|
||||||
|
assert.notEqual(match, null);
|
||||||
|
if (!match) {
|
||||||
|
throw new Error(`invalid log line: ${line}`);
|
||||||
|
}
|
||||||
|
const observedAt = match[1];
|
||||||
|
const stream = match[2];
|
||||||
|
const payload = match[3];
|
||||||
|
if (!observedAt || !stream || payload === undefined) {
|
||||||
|
throw new Error(`invalid log line: ${line}`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
observedAt,
|
||||||
|
stream,
|
||||||
|
payload,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
describe("EventNdjsonLogger", () => {
|
describe("EventNdjsonLogger", () => {
|
||||||
it("writes NDJSON records to disk", () => {
|
it.effect("writes effect-style lines to thread-scoped files", () =>
|
||||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
Effect.gen(function* () {
|
||||||
const filePath = path.join(tempDir, "provider-native.ndjson");
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||||
|
const basePath = path.join(tempDir, "provider-native.ndjson");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const logger = makeEventNdjsonLogger(filePath);
|
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
|
||||||
expect(logger).toBeDefined();
|
assert.notEqual(logger, undefined);
|
||||||
if (!logger) {
|
if (!logger) {
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield* logger.write(
|
||||||
|
{ threadId: "provider-thread-1", id: "evt-1" },
|
||||||
|
ThreadId.makeUnsafe("thread-1"),
|
||||||
|
);
|
||||||
|
yield* logger.write(
|
||||||
|
{ type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
|
||||||
|
ThreadId.makeUnsafe("thread-2"),
|
||||||
|
);
|
||||||
|
yield* logger.close();
|
||||||
|
|
||||||
|
const threadOnePath = path.join(tempDir, "thread-1.log");
|
||||||
|
const threadTwoPath = path.join(tempDir, "thread-2.log");
|
||||||
|
assert.equal(fs.existsSync(threadOnePath), true);
|
||||||
|
assert.equal(fs.existsSync(threadTwoPath), true);
|
||||||
|
|
||||||
|
const first = parseLogLine(fs.readFileSync(threadOnePath, "utf8").trim());
|
||||||
|
const second = parseLogLine(fs.readFileSync(threadTwoPath, "utf8").trim());
|
||||||
|
|
||||||
|
assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
|
||||||
|
assert.equal(first.stream, "NTIVE");
|
||||||
|
assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
|
||||||
|
|
||||||
|
assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
|
||||||
|
assert.equal(second.stream, "NTIVE");
|
||||||
|
assert.equal(
|
||||||
|
second.payload,
|
||||||
|
'{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
logger.write({ type: "native", payload: { id: "evt-1" } });
|
it.effect(
|
||||||
logger.write({ type: "canonical", payload: { id: "evt-2" } });
|
"falls back to a global segment when orchestration thread id is missing or invalid",
|
||||||
logger.close();
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||||
|
const basePath = path.join(tempDir, "provider-canonical.ndjson");
|
||||||
|
|
||||||
const raw = fs.readFileSync(filePath, "utf8").trim();
|
try {
|
||||||
const lines = raw.split("\n");
|
const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
|
||||||
expect(lines.length).toBe(2);
|
assert.notEqual(logger, undefined);
|
||||||
|
if (!logger) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const first = JSON.parse(lines[0] ?? "{}");
|
yield* logger.write({ id: "evt-no-thread" }, null);
|
||||||
const second = JSON.parse(lines[1] ?? "{}");
|
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
|
||||||
expect(first).toEqual({ type: "native", payload: { id: "evt-1" } });
|
yield* logger.close();
|
||||||
expect(second).toEqual({ type: "canonical", payload: { id: "evt-2" } });
|
|
||||||
} finally {
|
const globalPath = path.join(tempDir, "_global.log");
|
||||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
assert.equal(fs.existsSync(globalPath), true);
|
||||||
}
|
const lines = fs
|
||||||
});
|
.readFileSync(globalPath, "utf8")
|
||||||
|
.trim()
|
||||||
|
.split("\n")
|
||||||
|
.map((line) => parseLogLine(line));
|
||||||
|
assert.equal(lines.length, 2);
|
||||||
|
assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
|
||||||
|
assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
|
||||||
|
assert.equal(lines[0]?.stream, "CANON");
|
||||||
|
assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
|
||||||
|
assert.equal(lines[1]?.stream, "CANON");
|
||||||
|
assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("rotates per-thread files when max size is exceeded", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
|
||||||
|
const basePath = path.join(tempDir, "provider-native.ndjson");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const logger = yield* makeEventNdjsonLogger(basePath, {
|
||||||
|
stream: "native",
|
||||||
|
maxBytes: 120,
|
||||||
|
maxFiles: 2,
|
||||||
|
});
|
||||||
|
assert.notEqual(logger, undefined);
|
||||||
|
if (!logger) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let index = 0; index < 10; index += 1) {
|
||||||
|
yield* logger.write(
|
||||||
|
{
|
||||||
|
threadId: "provider-thread-rotate",
|
||||||
|
id: `evt-${index}`,
|
||||||
|
payload: "x".repeat(40),
|
||||||
|
},
|
||||||
|
ThreadId.makeUnsafe("thread-rotate"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
yield* logger.close();
|
||||||
|
|
||||||
|
const fileStem = "thread-rotate.log";
|
||||||
|
const matchingFiles = fs
|
||||||
|
.readdirSync(tempDir)
|
||||||
|
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
|
||||||
|
.toSorted();
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
matchingFiles.some((entry) => entry === `${fileStem}.1`),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
matchingFiles.some((entry) => entry === `${fileStem}.3`),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
@@ -1,66 +1,257 @@
|
|||||||
/**
|
/**
|
||||||
* Provider event NDJSON logger helper.
|
* Provider event logger helper.
|
||||||
*
|
*
|
||||||
* Best-effort writer for observability logs. Failures are downgraded to warnings
|
* Best-effort writer for observability logs. Each record is formatted as a
|
||||||
* so provider runtime behavior is unaffected.
|
* single effect-style text line in a thread-scoped file. Failures are
|
||||||
|
* downgraded to warnings so provider runtime behavior is unaffected.
|
||||||
*/
|
*/
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
|
|
||||||
import { createLogger } from "../../logger.ts";
|
import type { ThreadId } from "@t3tools/contracts";
|
||||||
|
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||||
|
import { Effect, Exit, Logger, Scope } from "effect";
|
||||||
|
|
||||||
const logger = createLogger("provider-observability");
|
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
|
||||||
|
|
||||||
|
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
||||||
|
const DEFAULT_MAX_FILES = 10;
|
||||||
|
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||||
|
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||||
|
const LOG_SCOPE = "provider-observability";
|
||||||
|
|
||||||
|
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||||
|
|
||||||
export interface EventNdjsonLogger {
|
export interface EventNdjsonLogger {
|
||||||
readonly filePath: string;
|
readonly filePath: string;
|
||||||
write: (record: unknown) => void;
|
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
|
||||||
close: () => void;
|
close: () => Effect.Effect<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function stringifyRecord(record: unknown): string | undefined {
|
export interface EventNdjsonLoggerOptions {
|
||||||
try {
|
readonly stream: EventNdjsonStream;
|
||||||
return JSON.stringify(record);
|
readonly maxBytes?: number;
|
||||||
} catch (error) {
|
readonly maxFiles?: number;
|
||||||
logger.warn("failed to serialize provider event log record", { error });
|
readonly batchWindowMs?: number;
|
||||||
return undefined;
|
}
|
||||||
|
|
||||||
|
interface ThreadWriter {
|
||||||
|
writeMessage: (message: string) => Effect.Effect<void>;
|
||||||
|
close: () => Effect.Effect<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
|
||||||
|
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveThreadSegment(raw: string | null | undefined): string {
|
||||||
|
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
|
||||||
|
return normalized ?? GLOBAL_THREAD_SEGMENT;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatLoggerMessage(message: unknown): string {
|
||||||
|
if (Array.isArray(message)) {
|
||||||
|
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
|
||||||
|
}
|
||||||
|
return typeof message === "string" ? message : String(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
|
||||||
|
return Logger.make(
|
||||||
|
({ date, message }) =>
|
||||||
|
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||||
|
switch (stream) {
|
||||||
|
case "native":
|
||||||
|
return "NTIVE";
|
||||||
|
case "canonical":
|
||||||
|
case "orchestration":
|
||||||
|
default:
|
||||||
|
return "CANON";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function makeEventNdjsonLogger(filePath: string): EventNdjsonLogger | undefined {
|
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
|
||||||
try {
|
return Effect.gen(function* () {
|
||||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
const serialized = yield* Effect.sync(() => {
|
||||||
fs.appendFileSync(filePath, "", { encoding: "utf8", flag: "a" });
|
try {
|
||||||
} catch (error) {
|
return { ok: true as const, value: JSON.stringify(event) };
|
||||||
logger.warn("failed to create provider event log directory", { filePath, error });
|
} catch (error) {
|
||||||
return undefined;
|
return { ok: false as const, error };
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
if (!serialized.ok) {
|
||||||
let broken = false;
|
yield* logWarning("failed to serialize provider event log record", {
|
||||||
|
error: serialized.error,
|
||||||
|
});
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof serialized.value !== "string") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return serialized.value;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeThreadWriter(input: {
|
||||||
|
readonly filePath: string;
|
||||||
|
readonly maxBytes: number;
|
||||||
|
readonly maxFiles: number;
|
||||||
|
readonly batchWindowMs: number;
|
||||||
|
readonly streamLabel: string;
|
||||||
|
}): Effect.Effect<ThreadWriter | undefined> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const sinkResult = yield* Effect.sync(() => {
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
ok: true as const,
|
||||||
|
sink: new RotatingFileSink({
|
||||||
|
filePath: input.filePath,
|
||||||
|
maxBytes: input.maxBytes,
|
||||||
|
maxFiles: input.maxFiles,
|
||||||
|
throwOnError: true,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sinkResult.ok) {
|
||||||
|
yield* logWarning("failed to initialize provider thread log file", {
|
||||||
|
filePath: input.filePath,
|
||||||
|
error: sinkResult.error,
|
||||||
|
});
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sink = sinkResult.sink;
|
||||||
|
const scope = yield* Scope.make();
|
||||||
|
const lineLogger = makeLineLogger(input.streamLabel);
|
||||||
|
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||||
|
window: input.batchWindowMs,
|
||||||
|
flush: (messages) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const flushResult = yield* Effect.sync(() => {
|
||||||
|
try {
|
||||||
|
for (const message of messages) {
|
||||||
|
sink.write(message);
|
||||||
|
}
|
||||||
|
return { ok: true as const };
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!flushResult.ok) {
|
||||||
|
yield* logWarning("provider event log batch flush failed", {
|
||||||
|
filePath: input.filePath,
|
||||||
|
error: flushResult.error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||||
|
|
||||||
|
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||||
|
|
||||||
|
return {
|
||||||
|
writeMessage(message: string) {
|
||||||
|
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||||
|
},
|
||||||
|
close() {
|
||||||
|
return Scope.close(scope, Exit.void);
|
||||||
|
},
|
||||||
|
} satisfies ThreadWriter;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeEventNdjsonLogger(
|
||||||
|
filePath: string,
|
||||||
|
options: EventNdjsonLoggerOptions,
|
||||||
|
): Effect.Effect<EventNdjsonLogger | undefined> {
|
||||||
|
return Effect.gen(function* () {
|
||||||
|
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||||
|
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||||
|
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||||
|
const streamLabel = resolveStreamLabel(options.stream);
|
||||||
|
|
||||||
|
const directoryReady = yield* Effect.sync(() => {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
return { ok: false as const, error };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (directoryReady !== true) {
|
||||||
|
yield* logWarning("failed to create provider event log directory", {
|
||||||
|
filePath,
|
||||||
|
error: directoryReady.error,
|
||||||
|
});
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const threadWriters = new Map<string, ThreadWriter>();
|
||||||
|
const failedSegments = new Set<string>();
|
||||||
|
|
||||||
|
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
if (failedSegments.has(threadSegment)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const existing = threadWriters.get(threadSegment);
|
||||||
|
if (existing) {
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
const writer = yield* makeThreadWriter({
|
||||||
|
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||||
|
maxBytes,
|
||||||
|
maxFiles,
|
||||||
|
batchWindowMs,
|
||||||
|
streamLabel,
|
||||||
|
});
|
||||||
|
if (!writer) {
|
||||||
|
failedSegments.add(threadSegment);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
threadWriters.set(threadSegment, writer);
|
||||||
|
return writer;
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
filePath,
|
filePath,
|
||||||
write(record: unknown) {
|
write(event: unknown, threadId: ThreadId | null) {
|
||||||
if (broken) {
|
return Effect.gen(function* () {
|
||||||
return;
|
const threadSegment = resolveThreadSegment(threadId);
|
||||||
}
|
const message = yield* toLogMessage(event);
|
||||||
const serialized = stringifyRecord(record);
|
if (!message) {
|
||||||
if (!serialized) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
try {
|
const writer = yield* resolveThreadWriter(threadSegment);
|
||||||
fs.appendFileSync(filePath, `${serialized}\n`, { encoding: "utf8", flag: "a" });
|
if (!writer) {
|
||||||
} catch (error) {
|
return;
|
||||||
broken = true;
|
}
|
||||||
logger.warn("provider event log write failed", { filePath, error });
|
|
||||||
}
|
yield* writer.writeMessage(message);
|
||||||
|
});
|
||||||
},
|
},
|
||||||
close() {
|
close() {
|
||||||
// no-op for sync append logger
|
return Effect.gen(function* () {
|
||||||
|
for (const writer of threadWriters.values()) {
|
||||||
|
yield* writer.close();
|
||||||
|
}
|
||||||
|
threadWriters.clear();
|
||||||
|
});
|
||||||
},
|
},
|
||||||
};
|
} satisfies EventNdjsonLogger;
|
||||||
} catch (error) {
|
});
|
||||||
logger.warn("failed to create provider event log file", { filePath, error });
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { it } from "@effect/vitest";
|
||||||
|
import { Effect } from "effect";
|
||||||
|
|
||||||
|
import { checkCodexProviderStatus, parseAuthStatusFromOutput } from "./ProviderHealth";
|
||||||
|
|
||||||
|
// ── Test helpers ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function mockRunner(
|
||||||
|
handler: (args: ReadonlyArray<string>) => {
|
||||||
|
stdout: string;
|
||||||
|
stderr: string;
|
||||||
|
code: number | null;
|
||||||
|
timedOut?: boolean;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
return (args: ReadonlyArray<string>) => Promise.resolve(handler(args));
|
||||||
|
}
|
||||||
|
|
||||||
|
function failingRunner(description: string) {
|
||||||
|
return () => Promise.reject(new Error(description));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Tests ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
it.effect("returns ready when codex is installed and authenticated", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const status = yield* checkCodexProviderStatus(
|
||||||
|
mockRunner((args) => {
|
||||||
|
const joined = args.join(" ");
|
||||||
|
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||||
|
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||||
|
throw new Error(`Unexpected args: ${joined}`);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.strictEqual(status.provider, "codex");
|
||||||
|
assert.strictEqual(status.status, "ready");
|
||||||
|
assert.strictEqual(status.available, true);
|
||||||
|
assert.strictEqual(status.authStatus, "authenticated");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns unavailable when codex is missing", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const status = yield* checkCodexProviderStatus(failingRunner("spawn codex ENOENT"));
|
||||||
|
assert.strictEqual(status.provider, "codex");
|
||||||
|
assert.strictEqual(status.status, "error");
|
||||||
|
assert.strictEqual(status.available, false);
|
||||||
|
assert.strictEqual(status.authStatus, "unknown");
|
||||||
|
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns unauthenticated when auth probe reports login required", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const status = yield* checkCodexProviderStatus(
|
||||||
|
mockRunner((args) => {
|
||||||
|
const joined = args.join(" ");
|
||||||
|
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||||
|
if (joined === "login status") {
|
||||||
|
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected args: ${joined}`);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.strictEqual(status.provider, "codex");
|
||||||
|
assert.strictEqual(status.status, "error");
|
||||||
|
assert.strictEqual(status.available, true);
|
||||||
|
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||||
|
assert.strictEqual(
|
||||||
|
status.message,
|
||||||
|
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect(
|
||||||
|
"returns unauthenticated when login status output includes 'not logged in'",
|
||||||
|
() =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const status = yield* checkCodexProviderStatus(
|
||||||
|
mockRunner((args) => {
|
||||||
|
const joined = args.join(" ");
|
||||||
|
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||||
|
if (joined === "login status")
|
||||||
|
return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||||
|
throw new Error(`Unexpected args: ${joined}`);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.strictEqual(status.provider, "codex");
|
||||||
|
assert.strictEqual(status.status, "error");
|
||||||
|
assert.strictEqual(status.available, true);
|
||||||
|
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||||
|
assert.strictEqual(
|
||||||
|
status.message,
|
||||||
|
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns warning when login status command is unsupported", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const status = yield* checkCodexProviderStatus(
|
||||||
|
mockRunner((args) => {
|
||||||
|
const joined = args.join(" ");
|
||||||
|
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
|
||||||
|
if (joined === "login status") {
|
||||||
|
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected args: ${joined}`);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.strictEqual(status.provider, "codex");
|
||||||
|
assert.strictEqual(status.status, "warning");
|
||||||
|
assert.strictEqual(status.available, true);
|
||||||
|
assert.strictEqual(status.authStatus, "unknown");
|
||||||
|
assert.strictEqual(
|
||||||
|
status.message,
|
||||||
|
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it.effect("returns unavailable when codex version probe times out", () =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const status = yield* checkCodexProviderStatus(
|
||||||
|
mockRunner((args) => {
|
||||||
|
const joined = args.join(" ");
|
||||||
|
if (joined === "--version") {
|
||||||
|
return { stdout: "", stderr: "", code: null, timedOut: true };
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected args: ${joined}`);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert.strictEqual(status.provider, "codex");
|
||||||
|
assert.strictEqual(status.status, "error");
|
||||||
|
assert.strictEqual(status.available, false);
|
||||||
|
assert.strictEqual(status.authStatus, "unknown");
|
||||||
|
assert.strictEqual(status.message, "Codex CLI is installed but failed to run. Timed out while running command.");
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
it("parseAuthStatusFromOutput: timed out auth check is warning", () => {
|
||||||
|
const parsed = parseAuthStatusFromOutput({ stdout: "", stderr: "", code: null, timedOut: true });
|
||||||
|
assert.strictEqual(parsed.status, "warning");
|
||||||
|
assert.strictEqual(parsed.authStatus, "unknown");
|
||||||
|
assert.strictEqual(parsed.message, "Timed out while checking Codex authentication status.");
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Pure function tests ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
it("parseAuthStatusFromOutput: exit code 0 with no auth markers is ready", () => {
|
||||||
|
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||||
|
assert.strictEqual(parsed.status, "ready");
|
||||||
|
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parseAuthStatusFromOutput: JSON with authenticated=false is unauthenticated", () => {
|
||||||
|
const parsed = parseAuthStatusFromOutput({
|
||||||
|
stdout: '[{"authenticated":false}]\n',
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
});
|
||||||
|
assert.strictEqual(parsed.status, "error");
|
||||||
|
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("parseAuthStatusFromOutput: JSON without auth marker is warning", () => {
|
||||||
|
const parsed = parseAuthStatusFromOutput({
|
||||||
|
stdout: '[{"ok":true}]\n',
|
||||||
|
stderr: "",
|
||||||
|
code: 0,
|
||||||
|
});
|
||||||
|
assert.strictEqual(parsed.status, "warning");
|
||||||
|
assert.strictEqual(parsed.authStatus, "unknown");
|
||||||
|
});
|
||||||
@@ -0,0 +1,311 @@
|
|||||||
|
/**
|
||||||
|
* ProviderHealthLive - Startup-time provider health checks.
|
||||||
|
*
|
||||||
|
* Performs one-time provider readiness probes when the server starts and
|
||||||
|
* keeps the resulting snapshot in memory for `server.getConfig`.
|
||||||
|
*
|
||||||
|
* Uses the shared process runner to run CLI probes natively.
|
||||||
|
*
|
||||||
|
* @module ProviderHealthLive
|
||||||
|
*/
|
||||||
|
import type {
|
||||||
|
ServerProviderAuthStatus,
|
||||||
|
ServerProviderStatus,
|
||||||
|
ServerProviderStatusState,
|
||||||
|
} from "@t3tools/contracts";
|
||||||
|
import { Data, Effect, Layer, Result } from "effect";
|
||||||
|
|
||||||
|
import { runProcess } from "../../processRunner";
|
||||||
|
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
|
||||||
|
|
||||||
|
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||||
|
const CODEX_PROVIDER = "codex" as const;
|
||||||
|
|
||||||
|
class ProviderHealthCommandError extends Data.TaggedError("ProviderHealthCommandError")<{
|
||||||
|
readonly message: string;
|
||||||
|
readonly cause?: unknown;
|
||||||
|
}> {}
|
||||||
|
|
||||||
|
// ── Pure helpers ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface CommandResult {
|
||||||
|
readonly stdout: string;
|
||||||
|
readonly stderr: string;
|
||||||
|
readonly code: number | null;
|
||||||
|
readonly timedOut?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(error: unknown): string {
|
||||||
|
if (error instanceof Error) {
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
error &&
|
||||||
|
typeof error === "object" &&
|
||||||
|
"message" in error &&
|
||||||
|
typeof (error as { message?: unknown }).message === "string"
|
||||||
|
) {
|
||||||
|
return (error as { message: string }).message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||||
|
if (!value) return undefined;
|
||||||
|
const trimmed = value.trim();
|
||||||
|
return trimmed.length > 0 ? trimmed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCommandMissingCause(error: unknown): boolean {
|
||||||
|
const lower = errorMessage(error).toLowerCase();
|
||||||
|
return (
|
||||||
|
lower.includes("command not found: codex") ||
|
||||||
|
lower.includes("spawn codex enoent") ||
|
||||||
|
lower.includes("enoent") ||
|
||||||
|
lower.includes("notfound")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function detailFromResult(
|
||||||
|
result: CommandResult & { readonly timedOut?: boolean },
|
||||||
|
): string | undefined {
|
||||||
|
if (result.timedOut) return "Timed out while running command.";
|
||||||
|
const stderr = nonEmptyTrimmed(result.stderr);
|
||||||
|
if (stderr) return stderr;
|
||||||
|
const stdout = nonEmptyTrimmed(result.stdout);
|
||||||
|
if (stdout) return stdout;
|
||||||
|
if (result.code === null) {
|
||||||
|
return "Command was terminated before reporting an exit code.";
|
||||||
|
}
|
||||||
|
if (result.code !== 0) {
|
||||||
|
return `Command exited with code ${result.code}.`;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractAuthBoolean(value: unknown): boolean | undefined {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
for (const entry of value) {
|
||||||
|
const nested = extractAuthBoolean(entry);
|
||||||
|
if (nested !== undefined) return nested;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!value || typeof value !== "object") return undefined;
|
||||||
|
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
|
||||||
|
if (typeof record[key] === "boolean") return record[key];
|
||||||
|
}
|
||||||
|
for (const key of ["auth", "status", "session", "account"] as const) {
|
||||||
|
const nested = extractAuthBoolean(record[key]);
|
||||||
|
if (nested !== undefined) return nested;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||||
|
readonly status: ServerProviderStatusState;
|
||||||
|
readonly authStatus: ServerProviderAuthStatus;
|
||||||
|
readonly message?: string;
|
||||||
|
} {
|
||||||
|
if (result.timedOut) {
|
||||||
|
return {
|
||||||
|
status: "warning",
|
||||||
|
authStatus: "unknown",
|
||||||
|
message: "Timed out while checking Codex authentication status.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||||
|
|
||||||
|
if (
|
||||||
|
lowerOutput.includes("unknown command") ||
|
||||||
|
lowerOutput.includes("unrecognized command") ||
|
||||||
|
lowerOutput.includes("unexpected argument")
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
status: "warning",
|
||||||
|
authStatus: "unknown",
|
||||||
|
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
lowerOutput.includes("not logged in") ||
|
||||||
|
lowerOutput.includes("login required") ||
|
||||||
|
lowerOutput.includes("authentication required") ||
|
||||||
|
lowerOutput.includes("run `codex login`") ||
|
||||||
|
lowerOutput.includes("run codex login")
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
status: "error",
|
||||||
|
authStatus: "unauthenticated",
|
||||||
|
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsedAuth = (() => {
|
||||||
|
const trimmed = result.stdout.trim();
|
||||||
|
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||||
|
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
attemptedJsonParse: true as const,
|
||||||
|
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (parsedAuth.auth === true) {
|
||||||
|
return { status: "ready", authStatus: "authenticated" };
|
||||||
|
}
|
||||||
|
if (parsedAuth.auth === false) {
|
||||||
|
return {
|
||||||
|
status: "error",
|
||||||
|
authStatus: "unauthenticated",
|
||||||
|
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (parsedAuth.attemptedJsonParse) {
|
||||||
|
return {
|
||||||
|
status: "warning",
|
||||||
|
authStatus: "unknown",
|
||||||
|
message:
|
||||||
|
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (result.code === 0) {
|
||||||
|
return { status: "ready", authStatus: "authenticated" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const detail = detailFromResult(result);
|
||||||
|
return {
|
||||||
|
status: "warning",
|
||||||
|
authStatus: "unknown",
|
||||||
|
message: detail
|
||||||
|
? `Could not verify Codex authentication status. ${detail}`
|
||||||
|
: "Could not verify Codex authentication status.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RunProviderHealthCommand = (
|
||||||
|
args: ReadonlyArray<string>,
|
||||||
|
) => Promise<CommandResult>;
|
||||||
|
|
||||||
|
const defaultRunCodexCommand: RunProviderHealthCommand = async (args) => {
|
||||||
|
const result = await runProcess("codex", [...args], {
|
||||||
|
allowNonZeroExit: true,
|
||||||
|
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||||
|
maxBufferBytes: 262_144,
|
||||||
|
outputMode: "truncate",
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
stdout: result.stdout,
|
||||||
|
stderr: result.stderr,
|
||||||
|
code: result.code,
|
||||||
|
timedOut: result.timedOut,
|
||||||
|
} satisfies CommandResult;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ── Health check ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const checkCodexProviderStatus = (
|
||||||
|
runCodexCommand: RunProviderHealthCommand = defaultRunCodexCommand,
|
||||||
|
): Effect.Effect<ServerProviderStatus> =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const checkedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
// Probe 1: `codex --version` — is the CLI reachable?
|
||||||
|
const versionProbe = yield* Effect.tryPromise({
|
||||||
|
try: () => runCodexCommand(["--version"]),
|
||||||
|
catch: (error) =>
|
||||||
|
new ProviderHealthCommandError({
|
||||||
|
message: errorMessage(error),
|
||||||
|
...(error !== undefined ? { cause: error } : {}),
|
||||||
|
}),
|
||||||
|
}).pipe(Effect.result);
|
||||||
|
|
||||||
|
if (Result.isFailure(versionProbe)) {
|
||||||
|
const error = versionProbe.failure;
|
||||||
|
return {
|
||||||
|
provider: CODEX_PROVIDER,
|
||||||
|
status: "error" as const,
|
||||||
|
available: false,
|
||||||
|
authStatus: "unknown" as const,
|
||||||
|
checkedAt,
|
||||||
|
message: isCommandMissingCause(error)
|
||||||
|
? "Codex CLI (`codex`) is not installed or not on PATH."
|
||||||
|
: `Failed to execute Codex CLI health check: ${errorMessage(error)}.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const version = versionProbe.success;
|
||||||
|
if (version.timedOut || version.code !== 0) {
|
||||||
|
const detail = detailFromResult(version);
|
||||||
|
return {
|
||||||
|
provider: CODEX_PROVIDER,
|
||||||
|
status: "error" as const,
|
||||||
|
available: false,
|
||||||
|
authStatus: "unknown" as const,
|
||||||
|
checkedAt,
|
||||||
|
message: detail
|
||||||
|
? `Codex CLI is installed but failed to run. ${detail}`
|
||||||
|
: "Codex CLI is installed but failed to run.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Probe 2: `codex login status` — is the user authenticated?
|
||||||
|
const authProbe = yield* Effect.tryPromise({
|
||||||
|
try: () => runCodexCommand(["login", "status"]),
|
||||||
|
catch: (error) =>
|
||||||
|
new ProviderHealthCommandError({
|
||||||
|
message: errorMessage(error),
|
||||||
|
...(error !== undefined ? { cause: error } : {}),
|
||||||
|
}),
|
||||||
|
}).pipe(Effect.result);
|
||||||
|
|
||||||
|
if (Result.isFailure(authProbe)) {
|
||||||
|
const error = authProbe.failure;
|
||||||
|
return {
|
||||||
|
provider: CODEX_PROVIDER,
|
||||||
|
status: "warning" as const,
|
||||||
|
available: true,
|
||||||
|
authStatus: "unknown" as const,
|
||||||
|
checkedAt,
|
||||||
|
message:
|
||||||
|
errorMessage(error).length > 0
|
||||||
|
? `Could not verify Codex authentication status: ${errorMessage(error)}.`
|
||||||
|
: "Could not verify Codex authentication status.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseAuthStatusFromOutput(authProbe.success);
|
||||||
|
return {
|
||||||
|
provider: CODEX_PROVIDER,
|
||||||
|
status: parsed.status,
|
||||||
|
available: true,
|
||||||
|
authStatus: parsed.authStatus,
|
||||||
|
checkedAt,
|
||||||
|
...(parsed.message ? { message: parsed.message } : {}),
|
||||||
|
} satisfies ServerProviderStatus;
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── Layer ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export const ProviderHealthLive = Layer.effect(
|
||||||
|
ProviderHealth,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const codexStatus = yield* checkCodexProviderStatus();
|
||||||
|
return {
|
||||||
|
getStatuses: Effect.succeed([codexStatus]),
|
||||||
|
} satisfies ProviderHealthShape;
|
||||||
|
}),
|
||||||
|
);
|
||||||
@@ -30,10 +30,11 @@ import {
|
|||||||
ProviderSessionDirectory,
|
ProviderSessionDirectory,
|
||||||
type ProviderSessionBinding,
|
type ProviderSessionBinding,
|
||||||
} from "../Services/ProviderSessionDirectory.ts";
|
} from "../Services/ProviderSessionDirectory.ts";
|
||||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||||
|
|
||||||
export interface ProviderServiceLiveOptions {
|
export interface ProviderServiceLiveOptions {
|
||||||
readonly canonicalEventLogPath?: string;
|
readonly canonicalEventLogPath?: string;
|
||||||
|
readonly canonicalEventLogger?: EventNdjsonLogger;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ProviderRollbackConversationInput = Schema.Struct({
|
const ProviderRollbackConversationInput = Schema.Struct({
|
||||||
@@ -108,9 +109,12 @@ function readPersistedCwd(
|
|||||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const canonicalEventLogger =
|
const canonicalEventLogger =
|
||||||
options?.canonicalEventLogPath !== undefined
|
options?.canonicalEventLogger ??
|
||||||
? makeEventNdjsonLogger(options.canonicalEventLogPath)
|
(options?.canonicalEventLogPath !== undefined
|
||||||
: undefined;
|
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
|
||||||
|
stream: "canonical",
|
||||||
|
})
|
||||||
|
: undefined);
|
||||||
|
|
||||||
const registry = yield* ProviderAdapterRegistry;
|
const registry = yield* ProviderAdapterRegistry;
|
||||||
const directory = yield* ProviderSessionDirectory;
|
const directory = yield* ProviderSessionDirectory;
|
||||||
@@ -140,12 +144,20 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
|||||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||||
canonicalizeRuntimeEventSession(event).pipe(
|
canonicalizeRuntimeEventSession(event).pipe(
|
||||||
Effect.tap((canonicalEvent) =>
|
Effect.tap((canonicalEvent) =>
|
||||||
Effect.sync(() => {
|
canonicalEventLogger
|
||||||
canonicalEventLogger?.write({
|
? Effect.flatMap(
|
||||||
observedAt: new Date().toISOString(),
|
Effect.catch(
|
||||||
event: canonicalEvent,
|
directory.getThreadId(canonicalEvent.sessionId).pipe(
|
||||||
});
|
Effect.map((threadIdOption) =>
|
||||||
}),
|
Option.isSome(threadIdOption) ? threadIdOption.value : null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
() => Effect.succeed<ThreadId | null>(null),
|
||||||
|
),
|
||||||
|
(orchestrationThreadId) =>
|
||||||
|
canonicalEventLogger.write(canonicalEvent, orchestrationThreadId),
|
||||||
|
)
|
||||||
|
: Effect.void,
|
||||||
),
|
),
|
||||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||||
Effect.asVoid,
|
Effect.asVoid,
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/**
|
||||||
|
* ProviderHealth - Provider readiness snapshot service.
|
||||||
|
*
|
||||||
|
* Owns startup-time provider health checks (install/auth reachability) and
|
||||||
|
* exposes the cached results to transport layers.
|
||||||
|
*
|
||||||
|
* @module ProviderHealth
|
||||||
|
*/
|
||||||
|
import type { ServerProviderStatus } from "@t3tools/contracts";
|
||||||
|
import { ServiceMap } from "effect";
|
||||||
|
import type { Effect } from "effect";
|
||||||
|
|
||||||
|
export interface ProviderHealthShape {
|
||||||
|
/**
|
||||||
|
* Read provider health statuses computed at server startup.
|
||||||
|
*/
|
||||||
|
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
|
||||||
|
"t3/provider/Services/ProviderHealth",
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||||
|
|
||||||
|
describe("detectServerRuntimeEnvironment", () => {
|
||||||
|
it("detects native windows mode", () => {
|
||||||
|
expect(
|
||||||
|
detectServerRuntimeEnvironment({
|
||||||
|
platform: "win32",
|
||||||
|
env: {},
|
||||||
|
osRelease: "10.0.26100",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
platform: "windows",
|
||||||
|
pathStyle: "windows",
|
||||||
|
isWsl: false,
|
||||||
|
windowsInteropMode: "windows-native",
|
||||||
|
wslDistroName: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects wsl-hosted mode from environment variables", () => {
|
||||||
|
expect(
|
||||||
|
detectServerRuntimeEnvironment({
|
||||||
|
platform: "linux",
|
||||||
|
env: {
|
||||||
|
WSL_DISTRO_NAME: "Ubuntu-24.04",
|
||||||
|
WSL_INTEROP: "/run/WSL/123_interop",
|
||||||
|
},
|
||||||
|
osRelease: "6.6.87.2-microsoft-standard-WSL2",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu-24.04",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("detects wsl-hosted mode from os release when env is unavailable", () => {
|
||||||
|
expect(
|
||||||
|
detectServerRuntimeEnvironment({
|
||||||
|
platform: "linux",
|
||||||
|
env: {},
|
||||||
|
osRelease: "5.15.167.4-microsoft-standard-WSL2",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves non-wsl posix hosts outside the windows interop modes", () => {
|
||||||
|
expect(
|
||||||
|
detectServerRuntimeEnvironment({
|
||||||
|
platform: "darwin",
|
||||||
|
env: {},
|
||||||
|
osRelease: "24.3.0",
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
platform: "macos",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: false,
|
||||||
|
windowsInteropMode: null,
|
||||||
|
wslDistroName: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import os from "node:os";
|
||||||
|
|
||||||
|
import type { ServerRuntimeEnvironment } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
interface DetectServerRuntimeEnvironmentOptions {
|
||||||
|
readonly platform?: NodeJS.Platform;
|
||||||
|
readonly env?: NodeJS.ProcessEnv;
|
||||||
|
readonly osRelease?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePlatform(platform: NodeJS.Platform): ServerRuntimeEnvironment["platform"] {
|
||||||
|
switch (platform) {
|
||||||
|
case "win32":
|
||||||
|
return "windows";
|
||||||
|
case "darwin":
|
||||||
|
return "macos";
|
||||||
|
default:
|
||||||
|
return "linux";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectWsl(options: {
|
||||||
|
readonly platform: NodeJS.Platform;
|
||||||
|
readonly env: NodeJS.ProcessEnv;
|
||||||
|
readonly osRelease: string;
|
||||||
|
}): boolean {
|
||||||
|
if (options.platform !== "linux") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.env.WSL_DISTRO_NAME || options.env.WSL_INTEROP) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return options.osRelease.toLowerCase().includes("microsoft");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectServerRuntimeEnvironment(
|
||||||
|
options: DetectServerRuntimeEnvironmentOptions = {},
|
||||||
|
): ServerRuntimeEnvironment {
|
||||||
|
const platform = options.platform ?? process.platform;
|
||||||
|
const env = options.env ?? process.env;
|
||||||
|
const osRelease = options.osRelease ?? os.release();
|
||||||
|
const normalizedPlatform = normalizePlatform(platform);
|
||||||
|
const isWsl = detectWsl({ platform, env, osRelease });
|
||||||
|
|
||||||
|
return {
|
||||||
|
platform: normalizedPlatform,
|
||||||
|
pathStyle: normalizedPlatform === "windows" ? "windows" : "posix",
|
||||||
|
isWsl,
|
||||||
|
windowsInteropMode: normalizedPlatform === "windows" ? "windows-native" : isWsl ? "wsl-hosted" : null,
|
||||||
|
wslDistroName: isWsl ? env.WSL_DISTRO_NAME?.trim() || null : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -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";
|
||||||
@@ -23,6 +23,7 @@ import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRe
|
|||||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||||
import { ProviderService } from "./provider/Services/ProviderService";
|
import { ProviderService } from "./provider/Services/ProviderService";
|
||||||
|
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
|
||||||
|
|
||||||
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
import { TerminalManagerLive } from "./terminal/Layers/Manager";
|
||||||
import { KeybindingsLive } from "./keybindings";
|
import { KeybindingsLive } from "./keybindings";
|
||||||
@@ -37,25 +38,38 @@ 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 | NodeServices.NodeServices
|
||||||
> {
|
> {
|
||||||
return Effect.gen(function* () {
|
return Effect.gen(function* () {
|
||||||
const { stateDir } = yield* ServerConfig;
|
const { stateDir } = yield* ServerConfig;
|
||||||
const providerLogsDir = path.join(stateDir, "logs", "providers");
|
const providerLogsDir = path.join(stateDir, "logs", "provider");
|
||||||
const codexAdapterLayer = makeCodexAdapterLive({
|
const providerEventLogPath = path.join(providerLogsDir, "events.log");
|
||||||
nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"),
|
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||||
|
stream: "native",
|
||||||
|
});
|
||||||
|
const canonicalEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||||
|
stream: "canonical",
|
||||||
});
|
});
|
||||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer));
|
|
||||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||||
);
|
);
|
||||||
return makeProviderServiceLive({
|
const codexAdapterLayer = makeCodexAdapterLive(
|
||||||
canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"),
|
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||||
}).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
);
|
||||||
|
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||||
|
Layer.provide(codexAdapterLayer),
|
||||||
|
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||||
|
);
|
||||||
|
return makeProviderServiceLive(
|
||||||
|
canonicalEventLogger ? { canonicalEventLogger } : undefined,
|
||||||
|
).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer));
|
||||||
}).pipe(Layer.unwrap);
|
}).pipe(Layer.unwrap);
|
||||||
}
|
}
|
||||||
|
|
||||||
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),
|
||||||
@@ -78,6 +92,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),
|
||||||
@@ -89,15 +105,17 @@ export function makeServerRuntimeServicesLayer() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const terminalLayer = TerminalManagerLive.pipe(
|
const terminalLayer = TerminalManagerLive.pipe(
|
||||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
Layer.provide(
|
||||||
|
typeof Bun !== "undefined" && process.platform !== "win32"
|
||||||
|
? 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(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import path from "node:path";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_TERMINAL_ID,
|
DEFAULT_TERMINAL_ID,
|
||||||
|
type ServerRuntimeEnvironment,
|
||||||
type TerminalEvent,
|
type TerminalEvent,
|
||||||
type TerminalOpenInput,
|
type TerminalOpenInput,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
@@ -16,7 +17,11 @@ import {
|
|||||||
type PtyProcess,
|
type PtyProcess,
|
||||||
type PtySpawnInput,
|
type PtySpawnInput,
|
||||||
} from "../Services/PTY";
|
} from "../Services/PTY";
|
||||||
import { TerminalManagerRuntime } from "./Manager";
|
import {
|
||||||
|
resolveShellCandidates,
|
||||||
|
TerminalManagerRuntime,
|
||||||
|
validateTerminalCwdForRuntime,
|
||||||
|
} from "./Manager";
|
||||||
import { Effect, Encoding } from "effect";
|
import { Effect, Encoding } from "effect";
|
||||||
|
|
||||||
class FakePtyProcess implements PtyProcess {
|
class FakePtyProcess implements PtyProcess {
|
||||||
@@ -172,6 +177,7 @@ describe("TerminalManager", () => {
|
|||||||
options: {
|
options: {
|
||||||
shellResolver?: () => string;
|
shellResolver?: () => string;
|
||||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||||
subprocessPollIntervalMs?: number;
|
subprocessPollIntervalMs?: number;
|
||||||
processKillGraceMs?: number;
|
processKillGraceMs?: number;
|
||||||
maxRetainedInactiveSessions?: number;
|
maxRetainedInactiveSessions?: number;
|
||||||
@@ -186,6 +192,7 @@ describe("TerminalManager", () => {
|
|||||||
ptyAdapter,
|
ptyAdapter,
|
||||||
historyLineLimit,
|
historyLineLimit,
|
||||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||||
|
...(options.runtimeEnvironment ? { runtimeEnvironment: options.runtimeEnvironment } : {}),
|
||||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||||
...(options.subprocessPollIntervalMs
|
...(options.subprocessPollIntervalMs
|
||||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||||
@@ -669,4 +676,93 @@ describe("TerminalManager", () => {
|
|||||||
|
|
||||||
manager.dispose();
|
manager.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("resolves Windows shell candidates from runtime environment instead of host assumptions", () => {
|
||||||
|
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||||
|
platform: "windows",
|
||||||
|
pathStyle: "windows",
|
||||||
|
isWsl: false,
|
||||||
|
windowsInteropMode: "windows-native",
|
||||||
|
wslDistroName: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const candidates = resolveShellCandidates(() => "/bin/bash -l", runtimeEnvironment);
|
||||||
|
|
||||||
|
expect(candidates.map((candidate) => candidate.shell)).toContain("cmd.exe");
|
||||||
|
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||||
|
expect(candidates.map((candidate) => candidate.shell)).not.toContain("/bin/sh");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolves POSIX shell candidates for wsl-hosted runtime even when the requested shell is Windows-style", () => {
|
||||||
|
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
};
|
||||||
|
|
||||||
|
const candidates = resolveShellCandidates(() => "powershell.exe", runtimeEnvironment);
|
||||||
|
|
||||||
|
expect(candidates.map((candidate) => candidate.shell)).toContain("powershell.exe");
|
||||||
|
expect(candidates.map((candidate) => candidate.shell)).toContain("/bin/bash");
|
||||||
|
expect(candidates.map((candidate) => candidate.shell)).toContain("sh");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects POSIX cwd values for windows-native terminal runtimes", async () => {
|
||||||
|
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||||
|
platform: "windows",
|
||||||
|
pathStyle: "windows",
|
||||||
|
isWsl: false,
|
||||||
|
windowsInteropMode: "windows-native",
|
||||||
|
wslDistroName: null,
|
||||||
|
};
|
||||||
|
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||||
|
|
||||||
|
await expect(manager.open(openInput({ cwd: "/home/julius/project" }))).rejects.toThrow(
|
||||||
|
"Terminal cwd does not match Windows runtime path style",
|
||||||
|
);
|
||||||
|
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||||
|
|
||||||
|
manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects Windows cwd values for wsl-hosted terminal runtimes", async () => {
|
||||||
|
const runtimeEnvironment: ServerRuntimeEnvironment = {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
};
|
||||||
|
const { manager, ptyAdapter } = makeManager(5, { runtimeEnvironment });
|
||||||
|
|
||||||
|
await expect(manager.open(openInput({ cwd: "C:\\Users\\julius\\project" }))).rejects.toThrow(
|
||||||
|
"Terminal cwd does not match POSIX runtime path style",
|
||||||
|
);
|
||||||
|
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||||
|
|
||||||
|
manager.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates cwd compatibility as a pure runtime helper", () => {
|
||||||
|
expect(
|
||||||
|
validateTerminalCwdForRuntime("/repo", {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
}),
|
||||||
|
).toBeNull();
|
||||||
|
expect(
|
||||||
|
validateTerminalCwdForRuntime("\\\\wsl.localhost\\Ubuntu\\repo", {
|
||||||
|
platform: "linux",
|
||||||
|
pathStyle: "posix",
|
||||||
|
isWsl: true,
|
||||||
|
windowsInteropMode: "wsl-hosted",
|
||||||
|
wslDistroName: "Ubuntu",
|
||||||
|
}),
|
||||||
|
).toContain("POSIX runtime path style");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -9,12 +9,14 @@ import {
|
|||||||
TerminalOpenInput,
|
TerminalOpenInput,
|
||||||
TerminalResizeInput,
|
TerminalResizeInput,
|
||||||
TerminalWriteInput,
|
TerminalWriteInput,
|
||||||
|
type ServerRuntimeEnvironment,
|
||||||
type TerminalEvent,
|
type TerminalEvent,
|
||||||
type TerminalSessionSnapshot,
|
type TerminalSessionSnapshot,
|
||||||
} from "@t3tools/contracts";
|
} from "@t3tools/contracts";
|
||||||
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
import { Effect, Encoding, Layer, Path, Schema } from "effect";
|
||||||
|
|
||||||
import { createLogger } from "../../logger";
|
import { createLogger } from "../../logger";
|
||||||
|
import { detectServerRuntimeEnvironment } from "../../runtimeEnvironment";
|
||||||
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
|
||||||
import { runProcess } from "../../processRunner";
|
import { runProcess } from "../../processRunner";
|
||||||
import { ServerConfig } from "../../config";
|
import { ServerConfig } from "../../config";
|
||||||
@@ -35,6 +37,8 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
|||||||
const DEFAULT_OPEN_COLS = 120;
|
const DEFAULT_OPEN_COLS = 120;
|
||||||
const DEFAULT_OPEN_ROWS = 30;
|
const DEFAULT_OPEN_ROWS = 30;
|
||||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||||
|
const WINDOWS_ABSOLUTE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
|
||||||
|
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
|
||||||
|
|
||||||
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
|
const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput);
|
||||||
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
|
const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput);
|
||||||
@@ -44,19 +48,22 @@ const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput);
|
|||||||
|
|
||||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||||
|
|
||||||
function defaultShellResolver(): string {
|
function defaultShellResolver(runtimeEnvironment: ServerRuntimeEnvironment): string {
|
||||||
if (process.platform === "win32") {
|
if (runtimeEnvironment.platform === "windows") {
|
||||||
return process.env.ComSpec ?? "cmd.exe";
|
return process.env.ComSpec ?? "cmd.exe";
|
||||||
}
|
}
|
||||||
return process.env.SHELL ?? "bash";
|
return process.env.SHELL ?? "bash";
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeShellCommand(value: string | undefined): string | null {
|
function normalizeShellCommand(
|
||||||
|
value: string | undefined,
|
||||||
|
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||||
|
): string | null {
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
const trimmed = value.trim();
|
const trimmed = value.trim();
|
||||||
if (trimmed.length === 0) return null;
|
if (trimmed.length === 0) return null;
|
||||||
|
|
||||||
if (process.platform === "win32") {
|
if (runtimeEnvironment.platform === "windows") {
|
||||||
return trimmed;
|
return trimmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,10 +72,13 @@ function normalizeShellCommand(value: string | undefined): string | null {
|
|||||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
|
function shellCandidateFromCommand(
|
||||||
|
command: string | null,
|
||||||
|
runtimeEnvironment: ServerRuntimeEnvironment,
|
||||||
|
): ShellCandidate | null {
|
||||||
if (!command || command.length === 0) return null;
|
if (!command || command.length === 0) return null;
|
||||||
const shellName = path.basename(command).toLowerCase();
|
const shellName = path.basename(command).toLowerCase();
|
||||||
if (process.platform !== "win32" && shellName === "zsh") {
|
if (runtimeEnvironment.platform !== "windows" && shellName === "zsh") {
|
||||||
return { shell: command, args: ["-o", "nopromptsp"] };
|
return { shell: command, args: ["-o", "nopromptsp"] };
|
||||||
}
|
}
|
||||||
return { shell: command };
|
return { shell: command };
|
||||||
@@ -92,27 +102,36 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
|
|||||||
return ordered;
|
return ordered;
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
|
export function resolveShellCandidates(
|
||||||
const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
|
shellResolver: () => string,
|
||||||
|
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||||
|
): ShellCandidate[] {
|
||||||
|
const requested = shellCandidateFromCommand(
|
||||||
|
normalizeShellCommand(shellResolver(), runtimeEnvironment),
|
||||||
|
runtimeEnvironment,
|
||||||
|
);
|
||||||
|
|
||||||
if (process.platform === "win32") {
|
if (runtimeEnvironment.platform === "windows") {
|
||||||
return uniqueShellCandidates([
|
return uniqueShellCandidates([
|
||||||
requested,
|
requested,
|
||||||
shellCandidateFromCommand(process.env.ComSpec ?? null),
|
shellCandidateFromCommand(process.env.ComSpec ?? null, runtimeEnvironment),
|
||||||
shellCandidateFromCommand("powershell.exe"),
|
shellCandidateFromCommand("powershell.exe", runtimeEnvironment),
|
||||||
shellCandidateFromCommand("cmd.exe"),
|
shellCandidateFromCommand("cmd.exe", runtimeEnvironment),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return uniqueShellCandidates([
|
return uniqueShellCandidates([
|
||||||
requested,
|
requested,
|
||||||
shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
|
shellCandidateFromCommand(
|
||||||
shellCandidateFromCommand("/bin/zsh"),
|
normalizeShellCommand(process.env.SHELL, runtimeEnvironment),
|
||||||
shellCandidateFromCommand("/bin/bash"),
|
runtimeEnvironment,
|
||||||
shellCandidateFromCommand("/bin/sh"),
|
),
|
||||||
shellCandidateFromCommand("zsh"),
|
shellCandidateFromCommand("/bin/zsh", runtimeEnvironment),
|
||||||
shellCandidateFromCommand("bash"),
|
shellCandidateFromCommand("/bin/bash", runtimeEnvironment),
|
||||||
shellCandidateFromCommand("sh"),
|
shellCandidateFromCommand("/bin/sh", runtimeEnvironment),
|
||||||
|
shellCandidateFromCommand("zsh", runtimeEnvironment),
|
||||||
|
shellCandidateFromCommand("bash", runtimeEnvironment),
|
||||||
|
shellCandidateFromCommand("sh", runtimeEnvironment),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,6 +197,13 @@ async function checkWindowsSubprocessActivity(terminalPid: number): Promise<bool
|
|||||||
allowNonZeroExit: true,
|
allowNonZeroExit: true,
|
||||||
maxBufferBytes: 32_768,
|
maxBufferBytes: 32_768,
|
||||||
outputMode: "truncate",
|
outputMode: "truncate",
|
||||||
|
runtimeEnvironment: {
|
||||||
|
platform: "windows",
|
||||||
|
pathStyle: "windows",
|
||||||
|
isWsl: false,
|
||||||
|
windowsInteropMode: "windows-native",
|
||||||
|
wslDistroName: null,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
return result.code === 0;
|
return result.code === 0;
|
||||||
@@ -230,14 +256,37 @@ async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolea
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
function createDefaultSubprocessChecker(runtimeEnvironment: ServerRuntimeEnvironment) {
|
||||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
return async (terminalPid: number): Promise<boolean> => {
|
||||||
return false;
|
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (runtimeEnvironment.platform === "windows") {
|
||||||
|
return checkWindowsSubprocessActivity(terminalPid);
|
||||||
|
}
|
||||||
|
return checkPosixSubprocessActivity(terminalPid);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWindowsPath(value: string): boolean {
|
||||||
|
return WINDOWS_ABSOLUTE_PATH_PATTERN.test(value) || WINDOWS_UNC_PATH_PATTERN.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateTerminalCwdForRuntime(
|
||||||
|
cwd: string,
|
||||||
|
runtimeEnvironment: ServerRuntimeEnvironment = detectServerRuntimeEnvironment(),
|
||||||
|
): string | null {
|
||||||
|
if (runtimeEnvironment.pathStyle === "windows") {
|
||||||
|
if (cwd.startsWith("/")) {
|
||||||
|
return `Terminal cwd does not match Windows runtime path style: ${cwd}`;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
if (process.platform === "win32") {
|
|
||||||
return checkWindowsSubprocessActivity(terminalPid);
|
if (isWindowsPath(cwd)) {
|
||||||
|
return `Terminal cwd does not match POSIX runtime path style: ${cwd}`;
|
||||||
}
|
}
|
||||||
return checkPosixSubprocessActivity(terminalPid);
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function capHistory(history: string, maxLines: number): string {
|
function capHistory(history: string, maxLines: number): string {
|
||||||
@@ -316,6 +365,7 @@ interface TerminalManagerOptions {
|
|||||||
ptyAdapter: PtyAdapterShape;
|
ptyAdapter: PtyAdapterShape;
|
||||||
shellResolver?: () => string;
|
shellResolver?: () => string;
|
||||||
subprocessChecker?: TerminalSubprocessChecker;
|
subprocessChecker?: TerminalSubprocessChecker;
|
||||||
|
runtimeEnvironment?: ServerRuntimeEnvironment;
|
||||||
subprocessPollIntervalMs?: number;
|
subprocessPollIntervalMs?: number;
|
||||||
processKillGraceMs?: number;
|
processKillGraceMs?: number;
|
||||||
maxRetainedInactiveSessions?: number;
|
maxRetainedInactiveSessions?: number;
|
||||||
@@ -333,6 +383,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
|||||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||||
private readonly persistDebounceMs: number;
|
private readonly persistDebounceMs: number;
|
||||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||||
|
private readonly runtimeEnvironment: ServerRuntimeEnvironment;
|
||||||
private readonly subprocessPollIntervalMs: number;
|
private readonly subprocessPollIntervalMs: number;
|
||||||
private readonly processKillGraceMs: number;
|
private readonly processKillGraceMs: number;
|
||||||
private readonly maxRetainedInactiveSessions: number;
|
private readonly maxRetainedInactiveSessions: number;
|
||||||
@@ -343,12 +394,15 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
|||||||
|
|
||||||
constructor(options: TerminalManagerOptions) {
|
constructor(options: TerminalManagerOptions) {
|
||||||
super();
|
super();
|
||||||
|
this.runtimeEnvironment = options.runtimeEnvironment ?? detectServerRuntimeEnvironment();
|
||||||
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
|
this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
|
||||||
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
|
||||||
this.ptyAdapter = options.ptyAdapter;
|
this.ptyAdapter = options.ptyAdapter;
|
||||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
this.shellResolver =
|
||||||
|
options.shellResolver ?? (() => defaultShellResolver(this.runtimeEnvironment));
|
||||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
this.subprocessChecker =
|
||||||
|
options.subprocessChecker ?? createDefaultSubprocessChecker(this.runtimeEnvironment);
|
||||||
this.subprocessPollIntervalMs =
|
this.subprocessPollIntervalMs =
|
||||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||||
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||||
@@ -589,7 +643,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
|||||||
let ptyProcess: PtyProcess | null = null;
|
let ptyProcess: PtyProcess | null = null;
|
||||||
let startedShell: string | null = null;
|
let startedShell: string | null = null;
|
||||||
try {
|
try {
|
||||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
const shellCandidates = resolveShellCandidates(this.shellResolver, this.runtimeEnvironment);
|
||||||
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
|
||||||
let lastSpawnError: unknown = null;
|
let lastSpawnError: unknown = null;
|
||||||
|
|
||||||
@@ -1051,6 +1105,11 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async assertValidCwd(cwd: string): Promise<void> {
|
private async assertValidCwd(cwd: string): Promise<void> {
|
||||||
|
const runtimePathError = validateTerminalCwdForRuntime(cwd, this.runtimeEnvironment);
|
||||||
|
if (runtimePathError) {
|
||||||
|
throw new Error(runtimePathError);
|
||||||
|
}
|
||||||
|
|
||||||
let stats: fs.Stats;
|
let stats: fs.Stats;
|
||||||
try {
|
try {
|
||||||
stats = await fs.promises.stat(cwd);
|
stats = await fs.promises.stat(cwd);
|
||||||
@@ -1173,10 +1232,11 @@ export const TerminalManagerLive = Layer.effect(
|
|||||||
const { stateDir } = yield* ServerConfig;
|
const { stateDir } = yield* ServerConfig;
|
||||||
const { join } = yield* Path.Path;
|
const { join } = yield* Path.Path;
|
||||||
const logsDir = join(stateDir, "logs", "terminals");
|
const logsDir = join(stateDir, "logs", "terminals");
|
||||||
|
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||||
|
|
||||||
const ptyAdapter = yield* PtyAdapter;
|
const ptyAdapter = yield* PtyAdapter;
|
||||||
const runtime = yield* Effect.acquireRelease(
|
const runtime = yield* Effect.acquireRelease(
|
||||||
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
|
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter, runtimeEnvironment })),
|
||||||
(r) => Effect.sync(() => r.dispose()),
|
(r) => Effect.sync(() => r.dispose()),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_TERMINAL_ID,
|
DEFAULT_TERMINAL_ID,
|
||||||
|
EDITORS,
|
||||||
EventId,
|
EventId,
|
||||||
ORCHESTRATION_WS_CHANNELS,
|
ORCHESTRATION_WS_CHANNELS,
|
||||||
ORCHESTRATION_WS_METHODS,
|
ORCHESTRATION_WS_METHODS,
|
||||||
@@ -24,6 +25,7 @@ import {
|
|||||||
WS_METHODS,
|
WS_METHODS,
|
||||||
type WebSocketResponse,
|
type WebSocketResponse,
|
||||||
type ProviderRuntimeEvent,
|
type ProviderRuntimeEvent,
|
||||||
|
type ServerProviderStatus,
|
||||||
type KeybindingsConfig,
|
type KeybindingsConfig,
|
||||||
type ResolvedKeybindingsConfig,
|
type ResolvedKeybindingsConfig,
|
||||||
type WsPush,
|
type WsPush,
|
||||||
@@ -42,12 +44,14 @@ import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/
|
|||||||
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
|
||||||
import { SqlClient, SqlError } 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 { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
|
||||||
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";
|
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||||
|
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||||
|
|
||||||
interface PendingMessages {
|
interface PendingMessages {
|
||||||
queue: unknown[];
|
queue: unknown[];
|
||||||
@@ -68,6 +72,22 @@ const defaultOpenService: OpenShape = {
|
|||||||
openInEditor: () => Effect.void,
|
openInEditor: () => Effect.void,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
|
||||||
|
{
|
||||||
|
provider: "codex",
|
||||||
|
status: "ready",
|
||||||
|
available: true,
|
||||||
|
authStatus: "authenticated",
|
||||||
|
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const defaultProviderHealthService: ProviderHealthShape = {
|
||||||
|
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultRuntimeEnvironment = detectServerRuntimeEnvironment();
|
||||||
|
|
||||||
class MockTerminalManager implements TerminalManagerShape {
|
class MockTerminalManager implements TerminalManagerShape {
|
||||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||||
@@ -340,6 +360,15 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
|
|||||||
}
|
}
|
||||||
|
|
||||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
|
||||||
|
const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id));
|
||||||
|
|
||||||
|
function expectAvailableEditors(value: unknown): void {
|
||||||
|
expect(Array.isArray(value)).toBe(true);
|
||||||
|
for (const editorId of value as unknown[]) {
|
||||||
|
expect(typeof editorId).toBe("string");
|
||||||
|
expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
describe("WebSocket Server", () => {
|
describe("WebSocket Server", () => {
|
||||||
let server: Http.Server | null = null;
|
let server: Http.Server | null = null;
|
||||||
@@ -367,9 +396,13 @@ describe("WebSocket Server", () => {
|
|||||||
stateDir?: string;
|
stateDir?: string;
|
||||||
staticDir?: string;
|
staticDir?: string;
|
||||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||||
|
providerHealth?: ProviderHealthShape;
|
||||||
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> {
|
||||||
@@ -381,6 +414,10 @@ describe("WebSocket Server", () => {
|
|||||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||||
|
const providerHealthLayer = Layer.succeed(
|
||||||
|
ProviderHealth,
|
||||||
|
options.providerHealth ?? defaultProviderHealthService,
|
||||||
|
);
|
||||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||||
mode: "web",
|
mode: "web",
|
||||||
@@ -415,8 +452,10 @@ describe("WebSocket Server", () => {
|
|||||||
);
|
);
|
||||||
const dependenciesLayer = Layer.empty.pipe(
|
const dependenciesLayer = Layer.empty.pipe(
|
||||||
Layer.provideMerge(runtimeLayer),
|
Layer.provideMerge(runtimeLayer),
|
||||||
|
Layer.provideMerge(providerHealthLayer),
|
||||||
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)),
|
||||||
@@ -722,7 +761,11 @@ describe("WebSocket Server", () => {
|
|||||||
keybindingsConfigPath: keybindingsPath,
|
keybindingsConfigPath: keybindingsPath,
|
||||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||||
issues: [],
|
issues: [],
|
||||||
|
providers: defaultProviderStatuses,
|
||||||
|
availableEditors: expect.any(Array),
|
||||||
|
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||||
});
|
});
|
||||||
|
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("bootstraps default keybindings file when missing", async () => {
|
it("bootstraps default keybindings file when missing", async () => {
|
||||||
@@ -745,7 +788,11 @@ describe("WebSocket Server", () => {
|
|||||||
keybindingsConfigPath: keybindingsPath,
|
keybindingsConfigPath: keybindingsPath,
|
||||||
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
|
||||||
issues: [],
|
issues: [],
|
||||||
|
providers: defaultProviderStatuses,
|
||||||
|
availableEditors: expect.any(Array),
|
||||||
|
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||||
});
|
});
|
||||||
|
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||||
|
|
||||||
const persistedConfig = JSON.parse(
|
const persistedConfig = JSON.parse(
|
||||||
fs.readFileSync(keybindingsPath, "utf8"),
|
fs.readFileSync(keybindingsPath, "utf8"),
|
||||||
@@ -778,7 +825,11 @@ describe("WebSocket Server", () => {
|
|||||||
message: expect.stringContaining("expected JSON array"),
|
message: expect.stringContaining("expected JSON array"),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
providers: defaultProviderStatuses,
|
||||||
|
availableEditors: expect.any(Array),
|
||||||
|
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||||
});
|
});
|
||||||
|
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -810,6 +861,9 @@ describe("WebSocket Server", () => {
|
|||||||
keybindingsConfigPath: string;
|
keybindingsConfigPath: string;
|
||||||
keybindings: ResolvedKeybindingsConfig;
|
keybindings: ResolvedKeybindingsConfig;
|
||||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||||
|
providers: ReadonlyArray<ServerProviderStatus>;
|
||||||
|
availableEditors: unknown;
|
||||||
|
runtimeEnvironment: unknown;
|
||||||
};
|
};
|
||||||
expect(result.cwd).toBe("/my/workspace");
|
expect(result.cwd).toBe("/my/workspace");
|
||||||
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
|
||||||
@@ -828,6 +882,9 @@ describe("WebSocket Server", () => {
|
|||||||
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
|
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
|
||||||
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
|
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
|
||||||
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
|
||||||
|
expect(result.providers).toEqual(defaultProviderStatuses);
|
||||||
|
expectAvailableEditors(result.availableEditors);
|
||||||
|
expect(result.runtimeEnvironment).toEqual(defaultRuntimeEnvironment);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
it("pushes server.configUpdated issues when keybindings file changes", async () => {
|
||||||
@@ -855,6 +912,7 @@ describe("WebSocket Server", () => {
|
|||||||
);
|
);
|
||||||
expect(malformedPush.data).toEqual({
|
expect(malformedPush.data).toEqual({
|
||||||
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
||||||
|
providers: defaultProviderStatuses,
|
||||||
});
|
});
|
||||||
|
|
||||||
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
fs.writeFileSync(keybindingsPath, "[]", "utf8");
|
||||||
@@ -865,7 +923,7 @@ describe("WebSocket Server", () => {
|
|||||||
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
|
Array.isArray((push.data as { issues?: unknown[] }).issues) &&
|
||||||
(push.data as { issues: unknown[] }).issues.length === 0,
|
(push.data as { issues: unknown[] }).issues.length === 0,
|
||||||
);
|
);
|
||||||
expect(successPush.data).toEqual({ issues: [] });
|
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("routes shell.openInEditor through the injected open service", async () => {
|
it("routes shell.openInEditor through the injected open service", async () => {
|
||||||
@@ -925,7 +983,11 @@ describe("WebSocket Server", () => {
|
|||||||
keybindingsConfigPath: keybindingsPath,
|
keybindingsConfigPath: keybindingsPath,
|
||||||
keybindings: compileKeybindings(persistedConfig),
|
keybindings: compileKeybindings(persistedConfig),
|
||||||
issues: [],
|
issues: [],
|
||||||
|
providers: defaultProviderStatuses,
|
||||||
|
availableEditors: expect.any(Array),
|
||||||
|
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||||
});
|
});
|
||||||
|
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("upserts keybinding rules and updates cached server config", async () => {
|
it("upserts keybinding rules and updates cached server config", async () => {
|
||||||
@@ -970,7 +1032,13 @@ describe("WebSocket Server", () => {
|
|||||||
keybindingsConfigPath: keybindingsPath,
|
keybindingsConfigPath: keybindingsPath,
|
||||||
keybindings: compileKeybindings(persistedConfig),
|
keybindings: compileKeybindings(persistedConfig),
|
||||||
issues: [],
|
issues: [],
|
||||||
|
providers: defaultProviderStatuses,
|
||||||
|
availableEditors: expect.any(Array),
|
||||||
|
runtimeEnvironment: defaultRuntimeEnvironment,
|
||||||
});
|
});
|
||||||
|
expectAvailableEditors(
|
||||||
|
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns error for unknown methods", async () => {
|
it("returns error for unknown methods", async () => {
|
||||||
@@ -1507,6 +1575,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 () => {
|
||||||
|
|||||||
+136
-17
@@ -12,8 +12,11 @@ import type { Duplex } from "node:stream";
|
|||||||
import Mime from "@effect/platform-node/Mime";
|
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,
|
ThreadId,
|
||||||
TerminalEvent,
|
TerminalEvent,
|
||||||
@@ -49,12 +52,25 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
|
|||||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||||
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
|
||||||
import { ProviderService } from "./provider/Services/ProviderService";
|
import { ProviderService } from "./provider/Services/ProviderService";
|
||||||
|
import { ProviderHealth } from "./provider/Services/ProviderHealth";
|
||||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||||
import { clamp } from "effect/Number";
|
import { clamp } from "effect/Number";
|
||||||
import { Open } from "./open";
|
import { Open, resolveAvailableEditors } 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 { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||||
|
import { detectServerRuntimeEnvironment } from "./runtimeEnvironment";
|
||||||
|
import {
|
||||||
|
ATTACHMENTS_ROUTE_PREFIX,
|
||||||
|
normalizeAttachmentRelativePath,
|
||||||
|
resolveAttachmentRelativePath,
|
||||||
|
} from "./attachmentPaths";
|
||||||
|
import {
|
||||||
|
createAttachmentId,
|
||||||
|
resolveAttachmentPath,
|
||||||
|
resolveAttachmentPathById,
|
||||||
|
} from "./attachmentStore.ts";
|
||||||
|
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ServerShape - Service API for server lifecycle control.
|
* ServerShape - Service API for server lifecycle control.
|
||||||
@@ -140,7 +156,8 @@ export type ServerCoreRuntimeServices =
|
|||||||
| ProjectionSnapshotQuery
|
| ProjectionSnapshotQuery
|
||||||
| CheckpointDiffQuery
|
| CheckpointDiffQuery
|
||||||
| OrchestrationReactor
|
| OrchestrationReactor
|
||||||
| ProviderService;
|
| ProviderService
|
||||||
|
| ProviderHealth;
|
||||||
|
|
||||||
export type ServerRuntimeServices =
|
export type ServerRuntimeServices =
|
||||||
| ServerCoreRuntimeServices
|
| ServerCoreRuntimeServices
|
||||||
@@ -179,10 +196,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
logWebSocketEvents,
|
logWebSocketEvents,
|
||||||
autoBootstrapProjectFromCwd,
|
autoBootstrapProjectFromCwd,
|
||||||
} = serverConfig;
|
} = serverConfig;
|
||||||
|
const availableEditors = resolveAvailableEditors();
|
||||||
|
const runtimeEnvironment = detectServerRuntimeEnvironment();
|
||||||
|
|
||||||
const gitManager = yield* GitManager;
|
const gitManager = yield* GitManager;
|
||||||
const terminalManager = yield* TerminalManager;
|
const terminalManager = yield* TerminalManager;
|
||||||
const keybindingsManager = yield* Keybindings;
|
const keybindingsManager = yield* Keybindings;
|
||||||
|
const providerHealth = yield* ProviderHealth;
|
||||||
const git = yield* GitCore;
|
const git = yield* GitCore;
|
||||||
const fileSystem = yield* FileSystem.FileSystem;
|
const fileSystem = yield* FileSystem.FileSystem;
|
||||||
const path = yield* Path.Path;
|
const path = yield* Path.Path;
|
||||||
@@ -197,6 +217,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const providerStatuses = yield* providerHealth.getStatuses;
|
||||||
|
|
||||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||||
const logger = createLogger("ws");
|
const logger = createLogger("ws");
|
||||||
|
|
||||||
@@ -230,6 +252,88 @@ 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) => {
|
||||||
const respond = (
|
const respond = (
|
||||||
@@ -249,22 +353,30 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||||
const attachmentsRoot = path.resolve(path.join(serverConfig.stateDir, "attachments"));
|
|
||||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||||
const normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||||
|
if (!normalizedRelativePath) {
|
||||||
if (
|
|
||||||
normalizedRelativePath.length === 0 ||
|
|
||||||
normalizedRelativePath.startsWith("..") ||
|
|
||||||
normalizedRelativePath.includes("\0")
|
|
||||||
) {
|
|
||||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
const isIdLookup =
|
||||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -432,7 +544,10 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
broadcastPush({
|
broadcastPush({
|
||||||
type: "push",
|
type: "push",
|
||||||
channel: WS_CHANNELS.serverConfigUpdated,
|
channel: WS_CHANNELS.serverConfigUpdated,
|
||||||
data: event,
|
data: {
|
||||||
|
issues: event.issues,
|
||||||
|
providers: providerStatuses,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
).pipe(Effect.forkIn(subscriptionsScope));
|
).pipe(Effect.forkIn(subscriptionsScope));
|
||||||
|
|
||||||
@@ -506,7 +621,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: {
|
||||||
@@ -584,7 +700,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
|
|
||||||
case WS_METHODS.gitCheckout: {
|
case WS_METHODS.gitCheckout: {
|
||||||
const body = stripRequestTag(request.body);
|
const body = stripRequestTag(request.body);
|
||||||
return yield* git.checkoutBranch(body);
|
return yield* Effect.scoped(git.checkoutBranch(body));
|
||||||
}
|
}
|
||||||
|
|
||||||
case WS_METHODS.gitInit: {
|
case WS_METHODS.gitInit: {
|
||||||
@@ -629,6 +745,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
|||||||
keybindingsConfigPath,
|
keybindingsConfigPath,
|
||||||
keybindings: keybindingsConfig.keybindings,
|
keybindings: keybindingsConfig.keybindings,
|
||||||
issues: keybindingsConfig.issues,
|
issues: keybindingsConfig.issues,
|
||||||
|
providers: providerStatuses,
|
||||||
|
availableEditors,
|
||||||
|
runtimeEnvironment,
|
||||||
};
|
};
|
||||||
|
|
||||||
case WS_METHODS.serverUpsertKeybinding: {
|
case WS_METHODS.serverUpsertKeybinding: {
|
||||||
|
|||||||
@@ -21,5 +21,5 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"include": ["src", "tsdown.config.ts", "scripts", "integration"]
|
"include": ["src", "tsdown.config.ts", "scripts", "integration", "../../scripts/lib"]
|
||||||
}
|
}
|
||||||
@@ -3,10 +3,13 @@ import { defineConfig } from "tsdown";
|
|||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
entry: ["src/index.ts"],
|
entry: ["src/index.ts"],
|
||||||
format: ["esm", "cjs"],
|
format: ["esm", "cjs"],
|
||||||
|
checks: {
|
||||||
|
legacyCjs: false,
|
||||||
|
},
|
||||||
outDir: "dist",
|
outDir: "dist",
|
||||||
sourcemap: true,
|
sourcemap: true,
|
||||||
clean: true,
|
clean: true,
|
||||||
noExternal: ["@t3tools/contracts"],
|
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||||
inlineOnly: false,
|
inlineOnly: false,
|
||||||
banner: {
|
banner: {
|
||||||
js: "#!/usr/bin/env node\n",
|
js: "#!/usr/bin/env node\n",
|
||||||
|
|||||||
+10
-4
@@ -1,19 +1,22 @@
|
|||||||
{
|
{
|
||||||
"name": "@t3tools/web",
|
"name": "@t3tools/web",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0-alpha.18",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
|
"prepare": "effect-language-service patch",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run --passWithNoTests"
|
"test": "vitest run --passWithNoTests"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@base-ui/react": "^1.2.0",
|
"@base-ui/react": "^1.2.0",
|
||||||
|
"@lexical/react": "^0.41.0",
|
||||||
"@pierre/diffs": "^1.1.0-beta.16",
|
"@pierre/diffs": "^1.1.0-beta.16",
|
||||||
"@t3tools/contracts": "workspace:*",
|
"@t3tools/contracts": "workspace:*",
|
||||||
|
"@t3tools/shared": "workspace:*",
|
||||||
"@tanstack/react-pacer": "^0.19.4",
|
"@tanstack/react-pacer": "^0.19.4",
|
||||||
"@tanstack/react-query": "^5.90.0",
|
"@tanstack/react-query": "^5.90.0",
|
||||||
"@tanstack/react-router": "^1.160.2",
|
"@tanstack/react-router": "^1.160.2",
|
||||||
@@ -22,12 +25,14 @@
|
|||||||
"@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:",
|
||||||
|
"lexical": "^0.41.0",
|
||||||
"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",
|
||||||
"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:",
|
||||||
@@ -38,7 +43,8 @@
|
|||||||
"@vitejs/plugin-react": "^5.1.4",
|
"@vitejs/plugin-react": "^5.1.4",
|
||||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||||
"tailwindcss": "^4.0.0",
|
"tailwindcss": "^4.0.0",
|
||||||
"typescript": "^5.7.3",
|
"typescript": "catalog:",
|
||||||
"vite": "^8.0.0-beta.12"
|
"vite": "^8.0.0-beta.12",
|
||||||
|
"vitest": "catalog:"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||||
|
|
||||||
describe("normalizeCustomModelSlugs", () => {
|
describe("normalizeCustomModelSlugs", () => {
|
||||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||||
@@ -40,3 +40,17 @@ describe("getAppModelOptions", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("getSlashModelOptions", () => {
|
||||||
|
it("includes saved custom model slugs for /model command suggestions", () => {
|
||||||
|
const options = getSlashModelOptions(["custom/internal-model"], "", "gpt-5.3-codex");
|
||||||
|
|
||||||
|
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("filters slash-model suggestions across built-in and custom model names", () => {
|
||||||
|
const options = getSlashModelOptions(["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
|
||||||
|
|
||||||
|
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -105,6 +105,24 @@ export function getAppModelOptions(
|
|||||||
return options;
|
return options;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getSlashModelOptions(
|
||||||
|
customModels: readonly string[],
|
||||||
|
query: string,
|
||||||
|
selectedModel?: string | null,
|
||||||
|
): AppModelOption[] {
|
||||||
|
const normalizedQuery = query.trim().toLowerCase();
|
||||||
|
const options = getAppModelOptions(customModels, selectedModel);
|
||||||
|
if (!normalizedQuery) {
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
return options.filter((option) => {
|
||||||
|
const searchSlug = option.slug.toLowerCase();
|
||||||
|
const searchName = option.name.toLowerCase();
|
||||||
|
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function emitChange(): void {
|
function emitChange(): void {
|
||||||
for (const listener of listeners) {
|
for (const listener of listeners) {
|
||||||
listener();
|
listener();
|
||||||
|
|||||||
@@ -1,64 +1,76 @@
|
|||||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
import type { GitBranch } from "@t3tools/contracts";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
dedupeRemoteBranchesWithLocalMatches,
|
dedupeRemoteBranchesWithLocalMatches,
|
||||||
deriveLocalBranchNameFromRemoteRef,
|
deriveLocalBranchNameFromRemoteRef,
|
||||||
deriveSyncedLocalBranch,
|
resolveDraftEnvModeAfterBranchChange,
|
||||||
|
resolveBranchToolbarValue,
|
||||||
} from "./BranchToolbar.logic";
|
} from "./BranchToolbar.logic";
|
||||||
|
|
||||||
const branches: GitBranch[] = [
|
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||||
{
|
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
|
||||||
name: "main",
|
expect(
|
||||||
current: true,
|
resolveDraftEnvModeAfterBranchChange({
|
||||||
isDefault: true,
|
nextWorktreePath: null,
|
||||||
worktreePath: null,
|
currentWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||||
},
|
effectiveEnvMode: "worktree",
|
||||||
{
|
}),
|
||||||
name: "feature/demo",
|
).toBe("local");
|
||||||
current: false,
|
|
||||||
isDefault: false,
|
|
||||||
worktreePath: null,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
describe("deriveSyncedLocalBranch", () => {
|
|
||||||
it("syncs to git current branch in local mode", () => {
|
|
||||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
|
||||||
const result = deriveSyncedLocalBranch({
|
|
||||||
activeThreadId: threadId,
|
|
||||||
activeWorktreePath: null,
|
|
||||||
envMode: "local",
|
|
||||||
activeThreadBranch: "feature/demo",
|
|
||||||
queryBranches: branches,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toBe("main");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not sync when creating a new worktree", () => {
|
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
|
||||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
expect(
|
||||||
const result = deriveSyncedLocalBranch({
|
resolveDraftEnvModeAfterBranchChange({
|
||||||
activeThreadId: threadId,
|
nextWorktreePath: null,
|
||||||
activeWorktreePath: null,
|
currentWorktreePath: null,
|
||||||
envMode: "worktree",
|
effectiveEnvMode: "worktree",
|
||||||
activeThreadBranch: "feature/demo",
|
}),
|
||||||
queryBranches: branches,
|
).toBe("worktree");
|
||||||
});
|
|
||||||
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not sync when thread already targets a worktree path", () => {
|
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
|
||||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
expect(
|
||||||
const result = deriveSyncedLocalBranch({
|
resolveDraftEnvModeAfterBranchChange({
|
||||||
activeThreadId: threadId,
|
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
|
||||||
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
|
currentWorktreePath: null,
|
||||||
envMode: "local",
|
effectiveEnvMode: "local",
|
||||||
activeThreadBranch: "feature/demo",
|
}),
|
||||||
queryBranches: branches,
|
).toBe("worktree");
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
expect(result).toBeNull();
|
describe("resolveBranchToolbarValue", () => {
|
||||||
|
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
|
||||||
|
expect(
|
||||||
|
resolveBranchToolbarValue({
|
||||||
|
envMode: "worktree",
|
||||||
|
activeWorktreePath: null,
|
||||||
|
activeThreadBranch: null,
|
||||||
|
currentGitBranch: "main",
|
||||||
|
}),
|
||||||
|
).toBe("main");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps an explicitly selected worktree base branch", () => {
|
||||||
|
expect(
|
||||||
|
resolveBranchToolbarValue({
|
||||||
|
envMode: "worktree",
|
||||||
|
activeWorktreePath: null,
|
||||||
|
activeThreadBranch: "feature/base",
|
||||||
|
currentGitBranch: "main",
|
||||||
|
}),
|
||||||
|
).toBe("feature/base");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
|
||||||
|
expect(
|
||||||
|
resolveBranchToolbarValue({
|
||||||
|
envMode: "local",
|
||||||
|
activeWorktreePath: null,
|
||||||
|
activeThreadBranch: "feature/base",
|
||||||
|
currentGitBranch: "main",
|
||||||
|
}),
|
||||||
|
).toBe("main");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,44 @@
|
|||||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
import type { GitBranch } from "@t3tools/contracts";
|
||||||
|
|
||||||
interface DeriveSyncedLocalBranchInput {
|
export type EnvMode = "local" | "worktree";
|
||||||
activeThreadId: ThreadId | undefined;
|
|
||||||
|
export function resolveEffectiveEnvMode(input: {
|
||||||
|
activeWorktreePath: string | null;
|
||||||
|
hasServerThread: boolean;
|
||||||
|
draftThreadEnvMode: EnvMode | undefined;
|
||||||
|
}): EnvMode {
|
||||||
|
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
|
||||||
|
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
|
||||||
|
? "worktree"
|
||||||
|
: "local";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveDraftEnvModeAfterBranchChange(input: {
|
||||||
|
nextWorktreePath: string | null;
|
||||||
|
currentWorktreePath: string | null;
|
||||||
|
effectiveEnvMode: EnvMode;
|
||||||
|
}): EnvMode {
|
||||||
|
const { nextWorktreePath, currentWorktreePath, effectiveEnvMode } = input;
|
||||||
|
if (nextWorktreePath) {
|
||||||
|
return "worktree";
|
||||||
|
}
|
||||||
|
if (effectiveEnvMode === "worktree" && !currentWorktreePath) {
|
||||||
|
return "worktree";
|
||||||
|
}
|
||||||
|
return "local";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveBranchToolbarValue(input: {
|
||||||
|
envMode: EnvMode;
|
||||||
activeWorktreePath: string | null;
|
activeWorktreePath: string | null;
|
||||||
envMode: "local" | "worktree";
|
|
||||||
activeThreadBranch: string | null;
|
activeThreadBranch: string | null;
|
||||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
currentGitBranch: string | null;
|
||||||
|
}): string | null {
|
||||||
|
const { envMode, activeWorktreePath, activeThreadBranch, currentGitBranch } = input;
|
||||||
|
if (envMode === "worktree" && !activeWorktreePath) {
|
||||||
|
return activeThreadBranch ?? currentGitBranch;
|
||||||
|
}
|
||||||
|
return currentGitBranch ?? activeThreadBranch;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||||
@@ -55,22 +88,3 @@ export function dedupeRemoteBranchesWithLocalMatches(
|
|||||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deriveSyncedLocalBranch({
|
|
||||||
activeThreadId,
|
|
||||||
activeWorktreePath,
|
|
||||||
envMode,
|
|
||||||
activeThreadBranch,
|
|
||||||
queryBranches,
|
|
||||||
}: DeriveSyncedLocalBranchInput): string | null {
|
|
||||||
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentBranch = queryBranches?.find((branch) => branch.current);
|
|
||||||
if (!currentBranch || currentBranch.name === activeThreadBranch) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return currentBranch.name;
|
|
||||||
}
|
|
||||||
@@ -1,227 +1,105 @@
|
|||||||
import type { GitBranch, ThreadId } from "@t3tools/contracts";
|
import type { ThreadId } from "@t3tools/contracts";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useCallback } from "react";
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
|
|
||||||
import { newCommandId } from "../lib/utils";
|
import { newCommandId } from "../lib/utils";
|
||||||
import {
|
|
||||||
gitBranchesQueryOptions,
|
|
||||||
gitCheckoutMutationOptions,
|
|
||||||
gitCreateBranchAndCheckoutMutationOptions,
|
|
||||||
} from "../lib/gitReactQuery";
|
|
||||||
import { readNativeApi } from "../nativeApi";
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import { useComposerDraftStore } from "../composerDraftStore";
|
||||||
import { useStore } from "../store";
|
import { useStore } from "../store";
|
||||||
import {
|
import {
|
||||||
dedupeRemoteBranchesWithLocalMatches,
|
EnvMode,
|
||||||
deriveLocalBranchNameFromRemoteRef,
|
resolveDraftEnvModeAfterBranchChange,
|
||||||
deriveSyncedLocalBranch,
|
resolveEffectiveEnvMode,
|
||||||
} from "./BranchToolbar.logic";
|
} from "./BranchToolbar.logic";
|
||||||
|
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||||
import { Button } from "./ui/button";
|
import { Button } from "./ui/button";
|
||||||
import {
|
|
||||||
Combobox,
|
|
||||||
ComboboxEmpty,
|
|
||||||
ComboboxInput,
|
|
||||||
ComboboxItem,
|
|
||||||
ComboboxList,
|
|
||||||
ComboboxPopup,
|
|
||||||
ComboboxTrigger,
|
|
||||||
} from "./ui/combobox";
|
|
||||||
import { ChevronDownIcon } from "lucide-react";
|
|
||||||
|
|
||||||
interface BranchToolbarProps {
|
interface BranchToolbarProps {
|
||||||
threadId: ThreadId;
|
threadId: ThreadId;
|
||||||
envMode: "local" | "worktree";
|
onEnvModeChange: (mode: EnvMode) => void;
|
||||||
onEnvModeChange: (mode: "local" | "worktree") => void;
|
|
||||||
envLocked: boolean;
|
envLocked: boolean;
|
||||||
onComposerFocusRequest?: () => void;
|
onComposerFocusRequest?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function BranchToolbar({
|
export default function BranchToolbar({
|
||||||
threadId,
|
threadId,
|
||||||
envMode,
|
|
||||||
onEnvModeChange,
|
onEnvModeChange,
|
||||||
envLocked,
|
envLocked,
|
||||||
onComposerFocusRequest,
|
onComposerFocusRequest,
|
||||||
}: BranchToolbarProps) {
|
}: BranchToolbarProps) {
|
||||||
const { state, dispatch } = useStore();
|
const threads = useStore((store) => store.threads);
|
||||||
const queryClient = useQueryClient();
|
const projects = useStore((store) => store.projects);
|
||||||
|
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
|
||||||
|
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||||
|
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||||
|
|
||||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
const serverThread = threads.find((thread) => thread.id === threadId);
|
||||||
const [branchQuery, setBranchQuery] = useState("");
|
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||||
|
const activeProject = projects.find((project) => project.id === activeProjectId);
|
||||||
const activeThread = state.threads.find((thread) => thread.id === threadId);
|
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||||
const activeThreadId = activeThread?.id;
|
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||||
const activeThreadBranch = activeThread?.branch ?? null;
|
|
||||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
|
||||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
||||||
|
const hasServerThread = serverThread !== undefined;
|
||||||
|
const effectiveEnvMode = resolveEffectiveEnvMode({
|
||||||
|
activeWorktreePath,
|
||||||
|
hasServerThread,
|
||||||
|
draftThreadEnvMode: draftThread?.envMode,
|
||||||
|
});
|
||||||
|
|
||||||
// ── Queries ───────────────────────────────────────────────────────────
|
const setThreadBranch = useCallback(
|
||||||
|
(branch: string | null, worktreePath: string | null) => {
|
||||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
if (!activeThreadId) return;
|
||||||
|
const api = readNativeApi();
|
||||||
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
// If the effective cwd is about to change, stop the running session so the
|
||||||
const branchNames = branches.map((branch) => branch.name);
|
// next message creates a new one with the correct cwd.
|
||||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
const sessionId = serverThread?.session?.sessionId;
|
||||||
const trimmedBranchQuery = branchQuery.trim();
|
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||||
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
|
void api.orchestration
|
||||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
.dispatchCommand({
|
||||||
const createBranchItemValue = canCreateBranch
|
type: "thread.session.stop",
|
||||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
commandId: newCommandId(),
|
||||||
: null;
|
threadId: activeThreadId,
|
||||||
const branchPickerItems =
|
createdAt: new Date().toISOString(),
|
||||||
createBranchItemValue && !hasExactBranchMatch
|
})
|
||||||
? [...branchNames, createBranchItemValue]
|
.catch(() => undefined);
|
||||||
: branchNames;
|
}
|
||||||
// ── Mutations ─────────────────────────────────────────────────────────
|
if (api && hasServerThread) {
|
||||||
|
void api.orchestration.dispatchCommand({
|
||||||
const checkoutMutation = useMutation(gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }));
|
type: "thread.meta.update",
|
||||||
|
|
||||||
const createBranchMutation = useMutation(
|
|
||||||
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
|
|
||||||
);
|
|
||||||
|
|
||||||
// ── Effects ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
// Keep thread branch synced to git current branch for local threads.
|
|
||||||
const queryBranches = branchesQuery.data?.branches;
|
|
||||||
useEffect(() => {
|
|
||||||
const syncedBranch = deriveSyncedLocalBranch({
|
|
||||||
activeThreadId,
|
|
||||||
activeWorktreePath,
|
|
||||||
envMode,
|
|
||||||
activeThreadBranch,
|
|
||||||
queryBranches,
|
|
||||||
});
|
|
||||||
if (!activeThreadId || !syncedBranch) return;
|
|
||||||
const api = readNativeApi();
|
|
||||||
|
|
||||||
if (api) {
|
|
||||||
void api.orchestration.dispatchCommand({
|
|
||||||
type: "thread.meta.update",
|
|
||||||
commandId: newCommandId(),
|
|
||||||
threadId: activeThreadId,
|
|
||||||
branch: syncedBranch,
|
|
||||||
worktreePath: null,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
dispatch({
|
|
||||||
type: "SET_THREAD_BRANCH",
|
|
||||||
threadId: activeThreadId,
|
|
||||||
branch: syncedBranch,
|
|
||||||
worktreePath: null,
|
|
||||||
});
|
|
||||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isBranchMenuOpen) return;
|
|
||||||
setBranchQuery("");
|
|
||||||
}, [isBranchMenuOpen]);
|
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const setThreadError = (error: string | null) => {
|
|
||||||
if (!activeThreadId) return;
|
|
||||||
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
|
|
||||||
};
|
|
||||||
|
|
||||||
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
|
|
||||||
if (!activeThreadId) return;
|
|
||||||
const api = readNativeApi();
|
|
||||||
// If the effective cwd is about to change, stop the running session so the
|
|
||||||
// next message creates a new one with the correct cwd.
|
|
||||||
const sessionId = activeThread?.session?.sessionId;
|
|
||||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
|
||||||
void api.orchestration
|
|
||||||
.dispatchCommand({
|
|
||||||
type: "thread.session.stop",
|
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
threadId: activeThreadId,
|
threadId: activeThreadId,
|
||||||
createdAt: new Date().toISOString(),
|
branch,
|
||||||
})
|
worktreePath,
|
||||||
.catch(() => undefined);
|
});
|
||||||
}
|
}
|
||||||
if (api) {
|
if (hasServerThread) {
|
||||||
void api.orchestration.dispatchCommand({
|
setThreadBranchAction(activeThreadId, branch, worktreePath);
|
||||||
type: "thread.meta.update",
|
return;
|
||||||
commandId: newCommandId(),
|
}
|
||||||
threadId: activeThreadId,
|
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
|
||||||
|
nextWorktreePath: worktreePath,
|
||||||
|
currentWorktreePath: activeWorktreePath,
|
||||||
|
effectiveEnvMode,
|
||||||
|
});
|
||||||
|
setDraftThreadContext(threadId, {
|
||||||
branch,
|
branch,
|
||||||
worktreePath,
|
worktreePath,
|
||||||
|
envMode: nextDraftEnvMode,
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
[
|
||||||
};
|
activeThreadId,
|
||||||
|
serverThread?.session?.sessionId,
|
||||||
|
activeWorktreePath,
|
||||||
|
hasServerThread,
|
||||||
|
setThreadBranchAction,
|
||||||
|
setDraftThreadContext,
|
||||||
|
threadId,
|
||||||
|
effectiveEnvMode,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const selectBranch = (branch: GitBranch) => {
|
if (!activeThreadId || !activeProject) return null;
|
||||||
const api = readNativeApi();
|
|
||||||
if (!api || !activeThreadId || !branchCwd) return;
|
|
||||||
|
|
||||||
// For new worktree mode, selecting a branch picks the base branch.
|
|
||||||
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
|
|
||||||
setThreadError(null);
|
|
||||||
setThreadBranch(branch.name, null);
|
|
||||||
setIsBranchMenuOpen(false);
|
|
||||||
onComposerFocusRequest?.();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the branch already lives in a worktree, redirect there instead of
|
|
||||||
// trying to checkout (which git would reject with "already used by worktree").
|
|
||||||
if (branch.worktreePath) {
|
|
||||||
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
|
|
||||||
setThreadError(null);
|
|
||||||
// Main worktree → switch back to local (project cwd, worktreePath=null).
|
|
||||||
// Secondary worktree → point the thread at that worktree path.
|
|
||||||
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
|
||||||
setIsBranchMenuOpen(false);
|
|
||||||
onComposerFocusRequest?.();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const selectedBranchName = branch.isRemote
|
|
||||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
|
||||||
: branch.name;
|
|
||||||
|
|
||||||
checkoutMutation.mutate(branch.name, {
|
|
||||||
onSuccess: async () => {
|
|
||||||
setThreadError(null);
|
|
||||||
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);
|
|
||||||
onComposerFocusRequest?.();
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
|
|
||||||
setIsBranchMenuOpen(true);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const createBranch = (rawName: string) => {
|
|
||||||
const name = rawName.trim();
|
|
||||||
const api = readNativeApi();
|
|
||||||
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
|
|
||||||
createBranchMutation.mutate(name, {
|
|
||||||
onSuccess: () => {
|
|
||||||
setThreadError(null);
|
|
||||||
setThreadBranch(name, activeWorktreePath);
|
|
||||||
setBranchQuery("");
|
|
||||||
setIsBranchMenuOpen(false);
|
|
||||||
onComposerFocusRequest?.();
|
|
||||||
},
|
|
||||||
onError: (error) => {
|
|
||||||
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
|
|
||||||
},
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!activeThread || !activeProject) return null;
|
|
||||||
|
|
||||||
return (
|
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">
|
||||||
@@ -236,97 +114,23 @@ 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>
|
||||||
|
|
||||||
<Combobox
|
<BranchToolbarBranchSelector
|
||||||
items={branchPickerItems}
|
activeProjectCwd={activeProject.cwd}
|
||||||
autoHighlight
|
activeThreadBranch={activeThreadBranch}
|
||||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
activeWorktreePath={activeWorktreePath}
|
||||||
open={isBranchMenuOpen}
|
branchCwd={branchCwd}
|
||||||
value={activeThread.branch}
|
effectiveEnvMode={effectiveEnvMode}
|
||||||
>
|
envLocked={envLocked}
|
||||||
<ComboboxTrigger
|
onSetThreadBranch={setThreadBranch}
|
||||||
render={<Button variant="ghost" size="xs" />}
|
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
/>
|
||||||
disabled={branchesQuery.isLoading}
|
|
||||||
>
|
|
||||||
<span className="max-w-[240px] truncate">
|
|
||||||
{activeThread.branch
|
|
||||||
? envMode === "worktree" && !activeWorktreePath
|
|
||||||
? `From ${activeThread.branch}`
|
|
||||||
: activeThread.branch
|
|
||||||
: "Select branch"}
|
|
||||||
</span>
|
|
||||||
<ChevronDownIcon />
|
|
||||||
</ComboboxTrigger>
|
|
||||||
<ComboboxPopup align="end" side="top" className="w-64">
|
|
||||||
<div className="border-b p-1">
|
|
||||||
<ComboboxInput
|
|
||||||
className="[&_input]:font-sans rounded-md"
|
|
||||||
inputClassName="ring-0"
|
|
||||||
placeholder="Search branches..."
|
|
||||||
showTrigger={false}
|
|
||||||
size="sm"
|
|
||||||
value={branchQuery}
|
|
||||||
onChange={(event) => setBranchQuery(event.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
|
||||||
|
|
||||||
<ComboboxList className="max-h-56">
|
|
||||||
{(itemValue) => {
|
|
||||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
|
||||||
return (
|
|
||||||
<ComboboxItem
|
|
||||||
hideIndicator
|
|
||||||
key={itemValue}
|
|
||||||
value={itemValue}
|
|
||||||
onClick={() => createBranch(trimmedBranchQuery)}
|
|
||||||
>
|
|
||||||
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
|
||||||
</ComboboxItem>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const branch = branchByName.get(itemValue);
|
|
||||||
if (!branch) return null;
|
|
||||||
|
|
||||||
const hasSecondaryWorktree =
|
|
||||||
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
|
|
||||||
const badge = branch.current
|
|
||||||
? "current"
|
|
||||||
: hasSecondaryWorktree
|
|
||||||
? "worktree"
|
|
||||||
: branch.isRemote
|
|
||||||
? "remote"
|
|
||||||
: branch.isDefault
|
|
||||||
? "default"
|
|
||||||
: null;
|
|
||||||
return (
|
|
||||||
<ComboboxItem
|
|
||||||
hideIndicator
|
|
||||||
key={itemValue}
|
|
||||||
value={itemValue}
|
|
||||||
className={
|
|
||||||
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
|
|
||||||
}
|
|
||||||
onClick={() => selectBranch(branch)}
|
|
||||||
>
|
|
||||||
<div className="flex w-full items-center justify-between gap-2">
|
|
||||||
<span className="truncate">{itemValue}</span>
|
|
||||||
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
|
|
||||||
</div>
|
|
||||||
</ComboboxItem>
|
|
||||||
);
|
|
||||||
}}
|
|
||||||
</ComboboxList>
|
|
||||||
</ComboboxPopup>
|
|
||||||
</Combobox>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,408 @@
|
|||||||
|
import type { GitBranch } from "@t3tools/contracts";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||||
|
import { ChevronDownIcon } from "lucide-react";
|
||||||
|
import {
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useOptimistic,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
useTransition,
|
||||||
|
} from "react";
|
||||||
|
|
||||||
|
import { gitBranchesQueryOptions, gitQueryKeys, invalidateGitQueries } from "../lib/gitReactQuery";
|
||||||
|
import { readNativeApi } from "../nativeApi";
|
||||||
|
import {
|
||||||
|
dedupeRemoteBranchesWithLocalMatches,
|
||||||
|
deriveLocalBranchNameFromRemoteRef,
|
||||||
|
EnvMode,
|
||||||
|
resolveBranchToolbarValue,
|
||||||
|
} from "./BranchToolbar.logic";
|
||||||
|
import { Button } from "./ui/button";
|
||||||
|
import {
|
||||||
|
Combobox,
|
||||||
|
ComboboxEmpty,
|
||||||
|
ComboboxInput,
|
||||||
|
ComboboxItem,
|
||||||
|
ComboboxList,
|
||||||
|
ComboboxPopup,
|
||||||
|
ComboboxTrigger,
|
||||||
|
} from "./ui/combobox";
|
||||||
|
import { toastManager } from "./ui/toast";
|
||||||
|
|
||||||
|
interface BranchToolbarBranchSelectorProps {
|
||||||
|
activeProjectCwd: string;
|
||||||
|
activeThreadBranch: string | null;
|
||||||
|
activeWorktreePath: string | null;
|
||||||
|
branchCwd: string | null;
|
||||||
|
effectiveEnvMode: EnvMode;
|
||||||
|
envLocked: boolean;
|
||||||
|
onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void;
|
||||||
|
onComposerFocusRequest?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBranchActionErrorMessage(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : "An error occurred.";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getBranchTriggerLabel(input: {
|
||||||
|
activeWorktreePath: string | null;
|
||||||
|
effectiveEnvMode: EnvMode;
|
||||||
|
resolvedActiveBranch: string | null;
|
||||||
|
}): string {
|
||||||
|
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||||
|
if (!resolvedActiveBranch) {
|
||||||
|
return "Select branch";
|
||||||
|
}
|
||||||
|
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||||
|
return `From ${resolvedActiveBranch}`;
|
||||||
|
}
|
||||||
|
return resolvedActiveBranch;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BranchToolbarBranchSelector({
|
||||||
|
activeProjectCwd,
|
||||||
|
activeThreadBranch,
|
||||||
|
activeWorktreePath,
|
||||||
|
branchCwd,
|
||||||
|
effectiveEnvMode,
|
||||||
|
envLocked,
|
||||||
|
onSetThreadBranch,
|
||||||
|
onComposerFocusRequest,
|
||||||
|
}: BranchToolbarBranchSelectorProps) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||||
|
const [branchQuery, setBranchQuery] = useState("");
|
||||||
|
|
||||||
|
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||||
|
const branches = useMemo(
|
||||||
|
() => dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []),
|
||||||
|
[branchesQuery.data?.branches],
|
||||||
|
);
|
||||||
|
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
|
||||||
|
const canonicalActiveBranch = resolveBranchToolbarValue({
|
||||||
|
envMode: effectiveEnvMode,
|
||||||
|
activeWorktreePath,
|
||||||
|
activeThreadBranch,
|
||||||
|
currentGitBranch,
|
||||||
|
});
|
||||||
|
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||||
|
const branchByName = useMemo(
|
||||||
|
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||||
|
[branches],
|
||||||
|
);
|
||||||
|
const trimmedBranchQuery = branchQuery.trim();
|
||||||
|
const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
|
||||||
|
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
|
||||||
|
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||||
|
const createBranchItemValue = canCreateBranch
|
||||||
|
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||||
|
: null;
|
||||||
|
const branchPickerItems = useMemo(
|
||||||
|
() =>
|
||||||
|
createBranchItemValue && !hasExactBranchMatch
|
||||||
|
? [...branchNames, createBranchItemValue]
|
||||||
|
: branchNames,
|
||||||
|
[branchNames, createBranchItemValue, hasExactBranchMatch],
|
||||||
|
);
|
||||||
|
const filteredBranchPickerItems = useMemo(
|
||||||
|
() =>
|
||||||
|
normalizedBranchQuery.length === 0
|
||||||
|
? branchPickerItems
|
||||||
|
: branchPickerItems.filter((itemValue) => {
|
||||||
|
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
|
||||||
|
return itemValue.toLowerCase().includes(normalizedBranchQuery);
|
||||||
|
}),
|
||||||
|
[branchPickerItems, createBranchItemValue, normalizedBranchQuery],
|
||||||
|
);
|
||||||
|
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||||
|
canonicalActiveBranch,
|
||||||
|
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||||
|
);
|
||||||
|
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||||
|
|
||||||
|
const runBranchAction = (action: () => Promise<void>) => {
|
||||||
|
startBranchActionTransition(async () => {
|
||||||
|
await action().catch(() => undefined);
|
||||||
|
await invalidateGitQueries(queryClient).catch(() => undefined);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectBranch = (branch: GitBranch) => {
|
||||||
|
const api = readNativeApi();
|
||||||
|
if (!api || !branchCwd || isBranchActionPending) return;
|
||||||
|
|
||||||
|
// In new-worktree mode, selecting a branch sets the base branch.
|
||||||
|
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||||
|
onSetThreadBranch(branch.name, null);
|
||||||
|
setIsBranchMenuOpen(false);
|
||||||
|
onComposerFocusRequest?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the branch already lives in a worktree, point the thread there.
|
||||||
|
if (branch.worktreePath) {
|
||||||
|
const isMainWorktree = branch.worktreePath === activeProjectCwd;
|
||||||
|
onSetThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
|
||||||
|
setIsBranchMenuOpen(false);
|
||||||
|
onComposerFocusRequest?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectedBranchName = branch.isRemote
|
||||||
|
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||||
|
: branch.name;
|
||||||
|
|
||||||
|
setIsBranchMenuOpen(false);
|
||||||
|
onComposerFocusRequest?.();
|
||||||
|
|
||||||
|
runBranchAction(async () => {
|
||||||
|
setOptimisticBranch(selectedBranchName);
|
||||||
|
try {
|
||||||
|
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
|
||||||
|
await invalidateGitQueries(queryClient);
|
||||||
|
} catch (error) {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Failed to checkout branch.",
|
||||||
|
description: toBranchActionErrorMessage(error),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextBranchName = selectedBranchName;
|
||||||
|
if (branch.isRemote) {
|
||||||
|
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||||
|
if (status?.branch) {
|
||||||
|
nextBranchName = status.branch;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setOptimisticBranch(nextBranchName);
|
||||||
|
onSetThreadBranch(nextBranchName, activeWorktreePath);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const createBranch = (rawName: string) => {
|
||||||
|
const name = rawName.trim();
|
||||||
|
const api = readNativeApi();
|
||||||
|
if (!api || !branchCwd || !name || isBranchActionPending) return;
|
||||||
|
|
||||||
|
setIsBranchMenuOpen(false);
|
||||||
|
onComposerFocusRequest?.();
|
||||||
|
|
||||||
|
runBranchAction(async () => {
|
||||||
|
setOptimisticBranch(name);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api.git.createBranch({ cwd: branchCwd, branch: name });
|
||||||
|
try {
|
||||||
|
await api.git.checkout({ cwd: branchCwd, branch: name });
|
||||||
|
} catch (error) {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Failed to checkout branch.",
|
||||||
|
description: toBranchActionErrorMessage(error),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Failed to create branch.",
|
||||||
|
description: toBranchActionErrorMessage(error),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setOptimisticBranch(name);
|
||||||
|
onSetThreadBranch(name, activeWorktreePath);
|
||||||
|
setBranchQuery("");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
effectiveEnvMode !== "worktree" ||
|
||||||
|
activeWorktreePath ||
|
||||||
|
activeThreadBranch ||
|
||||||
|
!currentGitBranch
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSetThreadBranch(currentGitBranch, null);
|
||||||
|
}, [
|
||||||
|
activeThreadBranch,
|
||||||
|
activeWorktreePath,
|
||||||
|
currentGitBranch,
|
||||||
|
effectiveEnvMode,
|
||||||
|
onSetThreadBranch,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const handleOpenChange = useCallback(
|
||||||
|
(open: boolean) => {
|
||||||
|
setIsBranchMenuOpen(open);
|
||||||
|
if (!open) {
|
||||||
|
setBranchQuery("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void queryClient.invalidateQueries({
|
||||||
|
queryKey: gitQueryKeys.branches(branchCwd),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[branchCwd, queryClient],
|
||||||
|
);
|
||||||
|
|
||||||
|
const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const branchListVirtualizer = useVirtualizer({
|
||||||
|
count: filteredBranchPickerItems.length,
|
||||||
|
estimateSize: () => 28,
|
||||||
|
getScrollElement: () => branchListScrollElementRef.current,
|
||||||
|
overscan: 12,
|
||||||
|
enabled: isBranchMenuOpen,
|
||||||
|
initialRect: {
|
||||||
|
height: 224,
|
||||||
|
width: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const virtualBranchRows = branchListVirtualizer.getVirtualItems();
|
||||||
|
const setBranchListRef = useCallback(
|
||||||
|
(element: HTMLDivElement | null) => {
|
||||||
|
branchListScrollElementRef.current =
|
||||||
|
(element?.parentElement as HTMLDivElement | null) ?? null;
|
||||||
|
if (element) {
|
||||||
|
branchListVirtualizer.measure();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[branchListVirtualizer],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isBranchMenuOpen) return;
|
||||||
|
queueMicrotask(() => {
|
||||||
|
branchListVirtualizer.measure();
|
||||||
|
});
|
||||||
|
}, [branchListVirtualizer, filteredBranchPickerItems.length, isBranchMenuOpen]);
|
||||||
|
|
||||||
|
const triggerLabel = getBranchTriggerLabel({
|
||||||
|
activeWorktreePath,
|
||||||
|
effectiveEnvMode,
|
||||||
|
resolvedActiveBranch,
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Combobox
|
||||||
|
items={branchPickerItems}
|
||||||
|
filteredItems={filteredBranchPickerItems}
|
||||||
|
autoHighlight
|
||||||
|
virtualized
|
||||||
|
onItemHighlighted={(_value, eventDetails) => {
|
||||||
|
if (!isBranchMenuOpen || eventDetails.index < 0) return;
|
||||||
|
branchListVirtualizer.scrollToIndex(eventDetails.index, { align: "auto" });
|
||||||
|
}}
|
||||||
|
onOpenChange={handleOpenChange}
|
||||||
|
open={isBranchMenuOpen}
|
||||||
|
value={resolvedActiveBranch}
|
||||||
|
>
|
||||||
|
<ComboboxTrigger
|
||||||
|
render={<Button variant="ghost" size="xs" />}
|
||||||
|
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||||
|
disabled={branchesQuery.isLoading || isBranchActionPending}
|
||||||
|
>
|
||||||
|
<span className="max-w-[240px] truncate">{triggerLabel}</span>
|
||||||
|
<ChevronDownIcon />
|
||||||
|
</ComboboxTrigger>
|
||||||
|
<ComboboxPopup align="end" side="top" className="w-64">
|
||||||
|
<div className="border-b p-1">
|
||||||
|
<ComboboxInput
|
||||||
|
className="[&_input]:font-sans rounded-md"
|
||||||
|
inputClassName="ring-0"
|
||||||
|
placeholder="Search branches..."
|
||||||
|
showTrigger={false}
|
||||||
|
size="sm"
|
||||||
|
value={branchQuery}
|
||||||
|
onChange={(event) => setBranchQuery(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||||
|
|
||||||
|
<ComboboxList ref={setBranchListRef} className="max-h-56">
|
||||||
|
<div
|
||||||
|
className="relative"
|
||||||
|
style={{
|
||||||
|
height: `${branchListVirtualizer.getTotalSize()}px`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{virtualBranchRows.map((virtualRow) => {
|
||||||
|
const itemValue = filteredBranchPickerItems[virtualRow.index];
|
||||||
|
if (!itemValue) return null;
|
||||||
|
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||||
|
return (
|
||||||
|
<ComboboxItem
|
||||||
|
hideIndicator
|
||||||
|
key={itemValue}
|
||||||
|
index={virtualRow.index}
|
||||||
|
value={itemValue}
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100%",
|
||||||
|
transform: `translateY(${virtualRow.start}px)`,
|
||||||
|
}}
|
||||||
|
onClick={() => createBranch(trimmedBranchQuery)}
|
||||||
|
>
|
||||||
|
<span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
|
||||||
|
</ComboboxItem>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const branch = branchByName.get(itemValue);
|
||||||
|
if (!branch) return null;
|
||||||
|
|
||||||
|
const hasSecondaryWorktree =
|
||||||
|
branch.worktreePath && branch.worktreePath !== activeProjectCwd;
|
||||||
|
const badge = branch.current
|
||||||
|
? "current"
|
||||||
|
: hasSecondaryWorktree
|
||||||
|
? "worktree"
|
||||||
|
: branch.isRemote
|
||||||
|
? "remote"
|
||||||
|
: branch.isDefault
|
||||||
|
? "default"
|
||||||
|
: null;
|
||||||
|
return (
|
||||||
|
<ComboboxItem
|
||||||
|
hideIndicator
|
||||||
|
key={itemValue}
|
||||||
|
index={virtualRow.index}
|
||||||
|
value={itemValue}
|
||||||
|
className={
|
||||||
|
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
|
||||||
|
}
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100%",
|
||||||
|
transform: `translateY(${virtualRow.start}px)`,
|
||||||
|
}}
|
||||||
|
onClick={() => selectBranch(branch)}
|
||||||
|
>
|
||||||
|
<div className="flex w-full items-center justify-between gap-2">
|
||||||
|
<span className="truncate">{itemValue}</span>
|
||||||
|
{badge && (
|
||||||
|
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ComboboxItem>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</ComboboxList>
|
||||||
|
</ComboboxPopup>
|
||||||
|
</Combobox>
|
||||||
|
);
|
||||||
|
}
|
||||||
+1284
-519
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,813 @@
|
|||||||
|
import {
|
||||||
|
LexicalComposer,
|
||||||
|
type InitialConfigType,
|
||||||
|
} from "@lexical/react/LexicalComposer";
|
||||||
|
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
|
||||||
|
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
|
||||||
|
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
|
||||||
|
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
|
||||||
|
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
|
||||||
|
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
|
||||||
|
import {
|
||||||
|
$applyNodeReplacement,
|
||||||
|
$createRangeSelection,
|
||||||
|
$getSelection,
|
||||||
|
$setSelection,
|
||||||
|
$isElementNode,
|
||||||
|
$isLineBreakNode,
|
||||||
|
$isRangeSelection,
|
||||||
|
$isTextNode,
|
||||||
|
$createLineBreakNode,
|
||||||
|
$createParagraphNode,
|
||||||
|
$createTextNode,
|
||||||
|
KEY_ARROW_DOWN_COMMAND,
|
||||||
|
KEY_ARROW_LEFT_COMMAND,
|
||||||
|
KEY_ARROW_RIGHT_COMMAND,
|
||||||
|
KEY_ARROW_UP_COMMAND,
|
||||||
|
KEY_ENTER_COMMAND,
|
||||||
|
KEY_TAB_COMMAND,
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
KEY_BACKSPACE_COMMAND,
|
||||||
|
$getRoot,
|
||||||
|
type ElementNode,
|
||||||
|
type LexicalNode,
|
||||||
|
TextNode,
|
||||||
|
type EditorConfig,
|
||||||
|
type EditorState,
|
||||||
|
type NodeKey,
|
||||||
|
type SerializedTextNode,
|
||||||
|
type Spread,
|
||||||
|
} from "lexical";
|
||||||
|
import {
|
||||||
|
forwardRef,
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useImperativeHandle,
|
||||||
|
useLayoutEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
type ClipboardEventHandler,
|
||||||
|
type Ref,
|
||||||
|
} from "react";
|
||||||
|
|
||||||
|
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||||
|
import { cn } from "~/lib/utils";
|
||||||
|
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||||
|
|
||||||
|
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||||
|
|
||||||
|
type SerializedComposerMentionNode = Spread<
|
||||||
|
{
|
||||||
|
path: string;
|
||||||
|
type: "composer-mention";
|
||||||
|
version: 1;
|
||||||
|
},
|
||||||
|
SerializedTextNode
|
||||||
|
>;
|
||||||
|
|
||||||
|
class ComposerMentionNode extends TextNode {
|
||||||
|
__path: string;
|
||||||
|
|
||||||
|
static override getType(): string {
|
||||||
|
return "composer-mention";
|
||||||
|
}
|
||||||
|
|
||||||
|
static override clone(node: ComposerMentionNode): ComposerMentionNode {
|
||||||
|
return new ComposerMentionNode(node.__path, node.__key);
|
||||||
|
}
|
||||||
|
|
||||||
|
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
|
||||||
|
return $createComposerMentionNode(serializedNode.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(path: string, key?: NodeKey) {
|
||||||
|
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
|
||||||
|
super(`@${normalizedPath}`, key);
|
||||||
|
this.__path = normalizedPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
override exportJSON(): SerializedComposerMentionNode {
|
||||||
|
return {
|
||||||
|
...super.exportJSON(),
|
||||||
|
path: this.__path,
|
||||||
|
type: "composer-mention",
|
||||||
|
version: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
override createDOM(_config: EditorConfig): HTMLElement {
|
||||||
|
const dom = document.createElement("span");
|
||||||
|
dom.className =
|
||||||
|
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||||
|
dom.contentEditable = "false";
|
||||||
|
dom.setAttribute("spellcheck", "false");
|
||||||
|
renderMentionChipDom(dom, this.__path);
|
||||||
|
return dom;
|
||||||
|
}
|
||||||
|
|
||||||
|
override updateDOM(
|
||||||
|
prevNode: ComposerMentionNode,
|
||||||
|
dom: HTMLElement,
|
||||||
|
_config: EditorConfig,
|
||||||
|
): boolean {
|
||||||
|
dom.contentEditable = "false";
|
||||||
|
if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
|
||||||
|
renderMentionChipDom(dom, this.__path);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
override canInsertTextBefore(): false {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
override canInsertTextAfter(): false {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
override isTextEntity(): true {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
override isToken(): true {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||||
|
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||||
|
const base = basenameOfPath(pathValue);
|
||||||
|
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||||
|
return "directory";
|
||||||
|
}
|
||||||
|
if (base.includes(".")) {
|
||||||
|
return "file";
|
||||||
|
}
|
||||||
|
return "directory";
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvedThemeFromDocument(): "light" | "dark" {
|
||||||
|
return document.documentElement.classList.contains("dark") ? "dark" : "light";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||||
|
container.textContent = "";
|
||||||
|
container.style.setProperty("user-select", "none");
|
||||||
|
container.style.setProperty("-webkit-user-select", "none");
|
||||||
|
|
||||||
|
const theme = resolvedThemeFromDocument();
|
||||||
|
const icon = document.createElement("img");
|
||||||
|
icon.alt = "";
|
||||||
|
icon.ariaHidden = "true";
|
||||||
|
icon.className = "size-3.5 shrink-0 opacity-85";
|
||||||
|
icon.loading = "lazy";
|
||||||
|
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||||
|
|
||||||
|
const label = document.createElement("span");
|
||||||
|
label.className = "truncate select-none leading-tight";
|
||||||
|
label.textContent = basenameOfPath(pathValue);
|
||||||
|
|
||||||
|
container.append(icon, label);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampCursor(value: string, cursor: number): number {
|
||||||
|
if (!Number.isFinite(cursor)) return value.length;
|
||||||
|
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getComposerNodeTextLength(node: LexicalNode): number {
|
||||||
|
if (node instanceof ComposerMentionNode) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if ($isTextNode(node)) {
|
||||||
|
return node.getTextContentSize();
|
||||||
|
}
|
||||||
|
if ($isLineBreakNode(node)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if ($isElementNode(node)) {
|
||||||
|
return node.getChildren().reduce((total, child) => total + getComposerNodeTextLength(child), 0);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
|
||||||
|
let offset = 0;
|
||||||
|
let current: LexicalNode | null = node;
|
||||||
|
|
||||||
|
while (current) {
|
||||||
|
const nextParent = current.getParent() as LexicalNode | null;
|
||||||
|
if (!nextParent || !$isElementNode(nextParent)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const siblings = nextParent.getChildren();
|
||||||
|
const index = current.getIndexWithinParent();
|
||||||
|
for (let i = 0; i < index; i += 1) {
|
||||||
|
const sibling = siblings[i];
|
||||||
|
if (!sibling) continue;
|
||||||
|
offset += getComposerNodeTextLength(sibling);
|
||||||
|
}
|
||||||
|
current = nextParent;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isTextNode(node)) {
|
||||||
|
if (node instanceof ComposerMentionNode) {
|
||||||
|
return offset + (pointOffset > 0 ? 1 : 0);
|
||||||
|
}
|
||||||
|
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isLineBreakNode(node)) {
|
||||||
|
return offset + Math.min(pointOffset, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isElementNode(node)) {
|
||||||
|
const children = node.getChildren();
|
||||||
|
const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
|
||||||
|
for (let i = 0; i < clampedOffset; i += 1) {
|
||||||
|
const child = children[i];
|
||||||
|
if (!child) continue;
|
||||||
|
offset += getComposerNodeTextLength(child);
|
||||||
|
}
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findSelectionPointAtOffset(
|
||||||
|
node: LexicalNode,
|
||||||
|
remainingRef: { value: number },
|
||||||
|
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||||
|
if (node instanceof ComposerMentionNode) {
|
||||||
|
const parent = node.getParent();
|
||||||
|
if (!parent || !$isElementNode(parent)) return null;
|
||||||
|
const index = node.getIndexWithinParent();
|
||||||
|
if (remainingRef.value === 0) {
|
||||||
|
return {
|
||||||
|
key: parent.getKey(),
|
||||||
|
offset: index,
|
||||||
|
type: "element",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (remainingRef.value === 1) {
|
||||||
|
return {
|
||||||
|
key: parent.getKey(),
|
||||||
|
offset: index + 1,
|
||||||
|
type: "element",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
remainingRef.value -= 1;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isTextNode(node)) {
|
||||||
|
const size = node.getTextContentSize();
|
||||||
|
if (remainingRef.value <= size) {
|
||||||
|
return {
|
||||||
|
key: node.getKey(),
|
||||||
|
offset: remainingRef.value,
|
||||||
|
type: "text",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
remainingRef.value -= size;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isLineBreakNode(node)) {
|
||||||
|
const parent = node.getParent();
|
||||||
|
if (!parent) return null;
|
||||||
|
const index = node.getIndexWithinParent();
|
||||||
|
if (remainingRef.value === 0) {
|
||||||
|
return {
|
||||||
|
key: parent.getKey(),
|
||||||
|
offset: index,
|
||||||
|
type: "element",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (remainingRef.value === 1) {
|
||||||
|
return {
|
||||||
|
key: parent.getKey(),
|
||||||
|
offset: index + 1,
|
||||||
|
type: "element",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
remainingRef.value -= 1;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isElementNode(node)) {
|
||||||
|
const children = node.getChildren();
|
||||||
|
for (const child of children) {
|
||||||
|
const point = findSelectionPointAtOffset(child, remainingRef);
|
||||||
|
if (point) {
|
||||||
|
return point;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (remainingRef.value === 0) {
|
||||||
|
return {
|
||||||
|
key: node.getKey(),
|
||||||
|
offset: children.length,
|
||||||
|
type: "element",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function $getComposerRootLength(): number {
|
||||||
|
const root = $getRoot();
|
||||||
|
const children = root.getChildren();
|
||||||
|
return children.reduce((sum, child) => sum + getComposerNodeTextLength(child), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function $setSelectionAtComposerOffset(nextOffset: number): void {
|
||||||
|
const root = $getRoot();
|
||||||
|
const composerLength = $getComposerRootLength();
|
||||||
|
const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
|
||||||
|
const remainingRef = { value: boundedOffset };
|
||||||
|
const point =
|
||||||
|
findSelectionPointAtOffset(root, remainingRef) ?? {
|
||||||
|
key: root.getKey(),
|
||||||
|
offset: root.getChildren().length,
|
||||||
|
type: "element" as const,
|
||||||
|
};
|
||||||
|
const selection = $createRangeSelection();
|
||||||
|
selection.anchor.set(point.key, point.offset, point.type);
|
||||||
|
selection.focus.set(point.key, point.offset, point.type);
|
||||||
|
$setSelection(selection);
|
||||||
|
}
|
||||||
|
|
||||||
|
function $readSelectionOffsetFromEditorState(fallback: number): number {
|
||||||
|
const selection = $getSelection();
|
||||||
|
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
const anchorNode = selection.anchor.getNode();
|
||||||
|
const offset = getAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
|
||||||
|
const composerLength = $getComposerRootLength();
|
||||||
|
return Math.max(0, Math.min(offset, composerLength));
|
||||||
|
}
|
||||||
|
|
||||||
|
function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||||
|
const lines = text.split("\n");
|
||||||
|
for (let index = 0; index < lines.length; index += 1) {
|
||||||
|
const line = lines[index] ?? "";
|
||||||
|
if (line.length > 0) {
|
||||||
|
parent.append($createTextNode(line));
|
||||||
|
}
|
||||||
|
if (index < lines.length - 1) {
|
||||||
|
parent.append($createLineBreakNode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function $setComposerEditorPrompt(prompt: string): void {
|
||||||
|
const root = $getRoot();
|
||||||
|
root.clear();
|
||||||
|
const paragraph = $createParagraphNode();
|
||||||
|
root.append(paragraph);
|
||||||
|
|
||||||
|
const segments = splitPromptIntoComposerSegments(prompt);
|
||||||
|
for (const segment of segments) {
|
||||||
|
if (segment.type === "mention") {
|
||||||
|
paragraph.append($createComposerMentionNode(segment.path));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$appendTextWithLineBreaks(paragraph, segment.text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ComposerPromptEditorHandle {
|
||||||
|
focus: () => void;
|
||||||
|
focusAt: (cursor: number) => void;
|
||||||
|
focusAtEnd: () => void;
|
||||||
|
readSnapshot: () => { value: string; cursor: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ComposerPromptEditorProps {
|
||||||
|
value: string;
|
||||||
|
cursor: number;
|
||||||
|
disabled: boolean;
|
||||||
|
placeholder: string;
|
||||||
|
className?: string;
|
||||||
|
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
|
||||||
|
onCommandKeyDown?: (
|
||||||
|
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||||
|
event: KeyboardEvent,
|
||||||
|
) => boolean;
|
||||||
|
onPaste: ClipboardEventHandler<HTMLElement>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
|
||||||
|
editorRef: Ref<ComposerPromptEditorHandle>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ComposerCommandKeyPlugin(props: {
|
||||||
|
onCommandKeyDown?: (
|
||||||
|
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||||
|
event: KeyboardEvent,
|
||||||
|
) => boolean;
|
||||||
|
}) {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleCommand = (
|
||||||
|
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||||
|
event: KeyboardEvent | null,
|
||||||
|
): boolean => {
|
||||||
|
if (!props.onCommandKeyDown || !event) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const handled = props.onCommandKeyDown(key, event);
|
||||||
|
if (handled) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
return handled;
|
||||||
|
};
|
||||||
|
|
||||||
|
const unregisterArrowDown = editor.registerCommand(
|
||||||
|
KEY_ARROW_DOWN_COMMAND,
|
||||||
|
(event) => handleCommand("ArrowDown", event),
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
const unregisterArrowUp = editor.registerCommand(
|
||||||
|
KEY_ARROW_UP_COMMAND,
|
||||||
|
(event) => handleCommand("ArrowUp", event),
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
const unregisterEnter = editor.registerCommand(
|
||||||
|
KEY_ENTER_COMMAND,
|
||||||
|
(event) => handleCommand("Enter", event),
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
const unregisterTab = editor.registerCommand(
|
||||||
|
KEY_TAB_COMMAND,
|
||||||
|
(event) => handleCommand("Tab", event),
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unregisterArrowDown();
|
||||||
|
unregisterArrowUp();
|
||||||
|
unregisterEnter();
|
||||||
|
unregisterTab();
|
||||||
|
};
|
||||||
|
}, [editor, props]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ComposerMentionArrowPlugin() {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const unregisterLeft = editor.registerCommand(
|
||||||
|
KEY_ARROW_LEFT_COMMAND,
|
||||||
|
() => {
|
||||||
|
let currentOffset = -1;
|
||||||
|
editor.getEditorState().read(() => {
|
||||||
|
const selection = $getSelection();
|
||||||
|
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||||
|
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||||
|
});
|
||||||
|
if (currentOffset <= 0) return false;
|
||||||
|
editor.update(() => {
|
||||||
|
$setSelectionAtComposerOffset(currentOffset - 1);
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
const unregisterRight = editor.registerCommand(
|
||||||
|
KEY_ARROW_RIGHT_COMMAND,
|
||||||
|
() => {
|
||||||
|
let currentOffset = -1;
|
||||||
|
let composerLength = 0;
|
||||||
|
editor.getEditorState().read(() => {
|
||||||
|
const selection = $getSelection();
|
||||||
|
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||||
|
composerLength = $getComposerRootLength();
|
||||||
|
currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||||
|
});
|
||||||
|
if (currentOffset < 0 || currentOffset >= composerLength) return false;
|
||||||
|
editor.update(() => {
|
||||||
|
$setSelectionAtComposerOffset(currentOffset + 1);
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
unregisterLeft();
|
||||||
|
unregisterRight();
|
||||||
|
};
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ComposerMentionSelectionNormalizePlugin() {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return editor.registerUpdateListener(({ editorState }) => {
|
||||||
|
let afterOffset: number | null = null;
|
||||||
|
editorState.read(() => {
|
||||||
|
const selection = $getSelection();
|
||||||
|
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||||
|
const anchorNode = selection.anchor.getNode();
|
||||||
|
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||||
|
if (selection.anchor.offset === 0) return;
|
||||||
|
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||||
|
afterOffset = beforeOffset + 1;
|
||||||
|
});
|
||||||
|
if (afterOffset !== null) {
|
||||||
|
queueMicrotask(() => {
|
||||||
|
editor.update(() => {
|
||||||
|
$setSelectionAtComposerOffset(afterOffset!);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function $isCursorAdjacentToMention(): boolean {
|
||||||
|
const selection = $getSelection();
|
||||||
|
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
|
||||||
|
const anchorNode = selection.anchor.getNode();
|
||||||
|
|
||||||
|
if (anchorNode instanceof ComposerMentionNode) return true;
|
||||||
|
|
||||||
|
if ($isElementNode(anchorNode)) {
|
||||||
|
const childIndex = selection.anchor.offset - 1;
|
||||||
|
if (childIndex >= 0) {
|
||||||
|
const child = anchorNode.getChildAtIndex(childIndex);
|
||||||
|
if (child instanceof ComposerMentionNode) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isTextNode(anchorNode) && selection.anchor.offset === 0) {
|
||||||
|
const prev = anchorNode.getPreviousSibling();
|
||||||
|
if (prev instanceof ComposerMentionNode) return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ComposerMentionBackspacePlugin() {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return editor.registerCommand(
|
||||||
|
KEY_BACKSPACE_COMMAND,
|
||||||
|
(event) => {
|
||||||
|
const selection = $getSelection();
|
||||||
|
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const anchorNode = selection.anchor.getNode();
|
||||||
|
const removeMentionNode = (candidate: unknown): boolean => {
|
||||||
|
if (!(candidate instanceof ComposerMentionNode)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||||
|
candidate.remove();
|
||||||
|
$setSelectionAtComposerOffset(mentionStart);
|
||||||
|
event?.preventDefault();
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (removeMentionNode(anchorNode)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isTextNode(anchorNode)) {
|
||||||
|
if (selection.anchor.offset > 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const parent = anchorNode.getParent();
|
||||||
|
if ($isElementNode(parent)) {
|
||||||
|
const index = anchorNode.getIndexWithinParent();
|
||||||
|
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isElementNode(anchorNode)) {
|
||||||
|
const childIndex = selection.anchor.offset - 1;
|
||||||
|
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ComposerPromptEditorInner({
|
||||||
|
value,
|
||||||
|
cursor,
|
||||||
|
disabled,
|
||||||
|
placeholder,
|
||||||
|
className,
|
||||||
|
onChange,
|
||||||
|
onCommandKeyDown,
|
||||||
|
onPaste,
|
||||||
|
editorRef,
|
||||||
|
}: ComposerPromptEditorInnerProps) {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
const onChangeRef = useRef(onChange);
|
||||||
|
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onChangeRef.current = onChange;
|
||||||
|
}, [onChange]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
editor.setEditable(!disabled);
|
||||||
|
}, [disabled, editor]);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const normalizedCursor = clampCursor(value, cursor);
|
||||||
|
const previousSnapshot = snapshotRef.current;
|
||||||
|
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previousSnapshot.value !== value) {
|
||||||
|
editor.update(() => {
|
||||||
|
$setComposerEditorPrompt(value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshotRef.current = { value, cursor: normalizedCursor };
|
||||||
|
|
||||||
|
const rootElement = editor.getRootElement();
|
||||||
|
if (!rootElement || document.activeElement !== rootElement) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
editor.update(() => {
|
||||||
|
$setSelectionAtComposerOffset(normalizedCursor);
|
||||||
|
});
|
||||||
|
}, [cursor, editor, value]);
|
||||||
|
|
||||||
|
const focusAt = useCallback(
|
||||||
|
(nextCursor: number) => {
|
||||||
|
const rootElement = editor.getRootElement();
|
||||||
|
if (!rootElement) return;
|
||||||
|
const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
|
||||||
|
rootElement.focus();
|
||||||
|
editor.update(() => {
|
||||||
|
$setSelectionAtComposerOffset(boundedCursor);
|
||||||
|
});
|
||||||
|
snapshotRef.current = {
|
||||||
|
value: snapshotRef.current.value,
|
||||||
|
cursor: boundedCursor,
|
||||||
|
};
|
||||||
|
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
|
||||||
|
},
|
||||||
|
[editor],
|
||||||
|
);
|
||||||
|
|
||||||
|
const readSnapshot = useCallback((): { value: string; cursor: number } => {
|
||||||
|
let snapshot = snapshotRef.current;
|
||||||
|
editor.getEditorState().read(() => {
|
||||||
|
const nextValue = $getRoot().getTextContent();
|
||||||
|
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||||
|
const nextCursor = clampCursor(
|
||||||
|
nextValue,
|
||||||
|
$readSelectionOffsetFromEditorState(fallbackCursor),
|
||||||
|
);
|
||||||
|
snapshot = {
|
||||||
|
value: nextValue,
|
||||||
|
cursor: nextCursor,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
snapshotRef.current = snapshot;
|
||||||
|
return snapshot;
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
useImperativeHandle(
|
||||||
|
editorRef,
|
||||||
|
() => ({
|
||||||
|
focus: () => {
|
||||||
|
focusAt(snapshotRef.current.cursor);
|
||||||
|
},
|
||||||
|
focusAt: (nextCursor: number) => {
|
||||||
|
focusAt(nextCursor);
|
||||||
|
},
|
||||||
|
focusAtEnd: () => {
|
||||||
|
focusAt(snapshotRef.current.value.length);
|
||||||
|
},
|
||||||
|
readSnapshot,
|
||||||
|
}),
|
||||||
|
[focusAt, readSnapshot],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleEditorChange = useCallback((editorState: EditorState) => {
|
||||||
|
editorState.read(() => {
|
||||||
|
const nextValue = $getRoot().getTextContent();
|
||||||
|
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||||
|
const nextCursor = clampCursor(nextValue, $readSelectionOffsetFromEditorState(fallbackCursor));
|
||||||
|
const previousSnapshot = snapshotRef.current;
|
||||||
|
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
snapshotRef.current = {
|
||||||
|
value: nextValue,
|
||||||
|
cursor: nextCursor,
|
||||||
|
};
|
||||||
|
onChangeRef.current(nextValue, nextCursor, $isCursorAdjacentToMention());
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative">
|
||||||
|
<PlainTextPlugin
|
||||||
|
contentEditable={
|
||||||
|
<ContentEditable
|
||||||
|
className={cn(
|
||||||
|
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
aria-placeholder={placeholder}
|
||||||
|
placeholder={<span />}
|
||||||
|
onPaste={onPaste}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
placeholder={
|
||||||
|
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||||
|
{placeholder}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
ErrorBoundary={LexicalErrorBoundary}
|
||||||
|
/>
|
||||||
|
<OnChangePlugin onChange={handleEditorChange} />
|
||||||
|
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||||
|
<ComposerMentionArrowPlugin />
|
||||||
|
<ComposerMentionSelectionNormalizePlugin />
|
||||||
|
<ComposerMentionBackspacePlugin />
|
||||||
|
<HistoryPlugin />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ComposerPromptEditor = forwardRef<ComposerPromptEditorHandle, ComposerPromptEditorProps>(
|
||||||
|
function ComposerPromptEditor(
|
||||||
|
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const initialValueRef = useRef(value);
|
||||||
|
const initialConfig = useMemo<InitialConfigType>(
|
||||||
|
() => ({
|
||||||
|
namespace: "t3tools-composer-editor",
|
||||||
|
editable: true,
|
||||||
|
nodes: [ComposerMentionNode],
|
||||||
|
editorState: () => {
|
||||||
|
$setComposerEditorPrompt(initialValueRef.current);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
throw error;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
|
||||||
|
<ComposerPromptEditorInner
|
||||||
|
value={value}
|
||||||
|
cursor={cursor}
|
||||||
|
disabled={disabled}
|
||||||
|
placeholder={placeholder}
|
||||||
|
onChange={onChange}
|
||||||
|
onPaste={onPaste}
|
||||||
|
editorRef={ref}
|
||||||
|
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
|
||||||
|
{...(className ? { className } : {})}
|
||||||
|
/>
|
||||||
|
</LexicalComposer>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -4,7 +4,7 @@ import { useQuery } from "@tanstack/react-query";
|
|||||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { type WheelEvent as ReactWheelEvent, 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 { readNativeApi } from "../nativeApi";
|
||||||
@@ -156,7 +156,6 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
|||||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { resolvedTheme } = useTheme();
|
const { resolvedTheme } = useTheme();
|
||||||
const { state } = useStore();
|
|
||||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -168,8 +167,13 @@ 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 = useStore((store) =>
|
||||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||||
|
);
|
||||||
|
const activeProjectId = activeThread?.projectId ?? null;
|
||||||
|
const activeProject = useStore((store) =>
|
||||||
|
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
|
||||||
|
);
|
||||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||||
useTurnDiffSummaries(activeThread);
|
useTurnDiffSummaries(activeThread);
|
||||||
@@ -342,7 +346,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
if (!element) return;
|
if (!element) return;
|
||||||
element.scrollBy({ left: offset, behavior: "smooth" });
|
element.scrollBy({ left: offset, behavior: "smooth" });
|
||||||
}, []);
|
}, []);
|
||||||
const onTurnStripWheel = useCallback((event: WheelEvent) => {
|
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
|
||||||
const element = turnStripRef.current;
|
const element = turnStripRef.current;
|
||||||
if (!element) return;
|
if (!element) return;
|
||||||
if (element.scrollWidth <= element.clientWidth + 1) return;
|
if (element.scrollWidth <= element.clientWidth + 1) return;
|
||||||
@@ -356,24 +360,26 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
const element = turnStripRef.current;
|
const element = turnStripRef.current;
|
||||||
if (!element) return;
|
if (!element) return;
|
||||||
|
|
||||||
updateTurnStripScrollState();
|
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||||
const onScroll = () => updateTurnStripScrollState();
|
const onScroll = () => updateTurnStripScrollState();
|
||||||
|
|
||||||
element.addEventListener("scroll", onScroll, { passive: true });
|
element.addEventListener("scroll", onScroll, { passive: true });
|
||||||
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
|
|
||||||
|
|
||||||
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
|
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
|
||||||
resizeObserver.observe(element);
|
resizeObserver.observe(element);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
window.cancelAnimationFrame(frameId);
|
||||||
element.removeEventListener("scroll", onScroll);
|
element.removeEventListener("scroll", onScroll);
|
||||||
element.removeEventListener("wheel", onTurnStripWheel);
|
|
||||||
resizeObserver.disconnect();
|
resizeObserver.disconnect();
|
||||||
};
|
};
|
||||||
}, [updateTurnStripScrollState, onTurnStripWheel]);
|
}, [updateTurnStripScrollState]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
updateTurnStripScrollState();
|
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
|
||||||
|
return () => {
|
||||||
|
window.cancelAnimationFrame(frameId);
|
||||||
|
};
|
||||||
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -422,7 +428,11 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
|||||||
>
|
>
|
||||||
<ChevronRightIcon className="size-3.5" />
|
<ChevronRightIcon className="size-3.5" />
|
||||||
</button>
|
</button>
|
||||||
<div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
|
<div
|
||||||
|
ref={turnStripRef}
|
||||||
|
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
|
||||||
|
onWheel={onTurnStripWheel}
|
||||||
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="shrink-0 rounded-md"
|
className="shrink-0 rounded-md"
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import {
|
|||||||
buildGitActionProgressStages,
|
buildGitActionProgressStages,
|
||||||
buildMenuItems,
|
buildMenuItems,
|
||||||
requiresDefaultBranchConfirmation,
|
requiresDefaultBranchConfirmation,
|
||||||
|
resolveAutoFeatureBranchName,
|
||||||
|
resolveDefaultBranchActionDialogCopy,
|
||||||
resolveQuickAction,
|
resolveQuickAction,
|
||||||
summarizeGitResult,
|
summarizeGitResult,
|
||||||
} from "./GitActionsControl.logic";
|
} from "./GitActionsControl.logic";
|
||||||
@@ -514,19 +516,20 @@ 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, pr: 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,
|
||||||
@@ -543,9 +546,9 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
assert.deepInclude(quick, {
|
assert.deepInclude(quick, {
|
||||||
kind: "show_hint",
|
kind: "open_pr",
|
||||||
label: "Commit",
|
label: "Open PR",
|
||||||
disabled: true,
|
disabled: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -605,10 +608,136 @@ describe("when: branch has no upstream configured", () => {
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("resolveQuickAction runs push and create PR when no upstream and commits are ahead", () => {
|
||||||
|
const quick = resolveQuickAction(
|
||||||
|
status({
|
||||||
|
hasUpstream: false,
|
||||||
|
aheadCount: 2,
|
||||||
|
pr: null,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.deepInclude(quick, {
|
||||||
|
kind: "run_action",
|
||||||
|
action: "commit_push_pr",
|
||||||
|
label: "Push & create PR",
|
||||||
|
disabled: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
|
||||||
|
const items = buildMenuItems(
|
||||||
|
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.deepEqual(items, [
|
||||||
|
{
|
||||||
|
id: "commit",
|
||||||
|
label: "Commit",
|
||||||
|
disabled: true,
|
||||||
|
icon: "commit",
|
||||||
|
kind: "open_dialog",
|
||||||
|
dialogAction: "commit",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "push",
|
||||||
|
label: "Push",
|
||||||
|
disabled: false,
|
||||||
|
icon: "push",
|
||||||
|
kind: "open_dialog",
|
||||||
|
dialogAction: "push",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "pr",
|
||||||
|
label: "Create PR",
|
||||||
|
disabled: false,
|
||||||
|
icon: "pr",
|
||||||
|
kind: "open_dialog",
|
||||||
|
dialogAction: "create_pr",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
|
||||||
|
const quick = resolveQuickAction(
|
||||||
|
status({
|
||||||
|
branch: "main",
|
||||||
|
hasUpstream: false,
|
||||||
|
aheadCount: 0,
|
||||||
|
pr: null,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.deepInclude(quick, {
|
||||||
|
kind: "show_hint",
|
||||||
|
label: "Push",
|
||||||
|
hint: "No local commits to push.",
|
||||||
|
disabled: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
|
||||||
|
const quick = resolveQuickAction(
|
||||||
|
status({
|
||||||
|
branch: "main",
|
||||||
|
hasUpstream: false,
|
||||||
|
aheadCount: 1,
|
||||||
|
pr: null,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.deepInclude(quick, {
|
||||||
|
kind: "run_action",
|
||||||
|
action: "commit_push",
|
||||||
|
label: "Push",
|
||||||
|
disabled: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("buildMenuItems still disables push and create PR when branch is behind", () => {
|
||||||
|
const items = buildMenuItems(
|
||||||
|
status({
|
||||||
|
hasUpstream: false,
|
||||||
|
behindCount: 1,
|
||||||
|
aheadCount: 0,
|
||||||
|
pr: null,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.deepEqual(items, [
|
||||||
|
{
|
||||||
|
id: "commit",
|
||||||
|
label: "Commit",
|
||||||
|
disabled: true,
|
||||||
|
icon: "commit",
|
||||||
|
kind: "open_dialog",
|
||||||
|
dialogAction: "commit",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "push",
|
||||||
|
label: "Push",
|
||||||
|
disabled: true,
|
||||||
|
icon: "push",
|
||||||
|
kind: "open_dialog",
|
||||||
|
dialogAction: "push",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "pr",
|
||||||
|
label: "Create PR",
|
||||||
|
disabled: true,
|
||||||
|
icon: "pr",
|
||||||
|
kind: "open_dialog",
|
||||||
|
dialogAction: "create_pr",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("requiresDefaultBranchConfirmation", () => {
|
describe("requiresDefaultBranchConfirmation", () => {
|
||||||
it("requires confirmation only for push actions on default branch", () => {
|
it("requires confirmation for push actions on default branch", () => {
|
||||||
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
|
||||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
|
assert.isTrue(requiresDefaultBranchConfirmation("commit_push", true));
|
||||||
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
|
assert.isTrue(requiresDefaultBranchConfirmation("commit_push_pr", true));
|
||||||
@@ -616,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({
|
||||||
@@ -628,6 +804,17 @@ describe("buildGitActionProgressStages", () => {
|
|||||||
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
|
assert.deepEqual(stages, ["Pushing to origin/feature/test..."]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("skips commit stages for create-pr flow when push-only is forced", () => {
|
||||||
|
const stages = buildGitActionProgressStages({
|
||||||
|
action: "commit_push_pr",
|
||||||
|
hasCustomCommitMessage: false,
|
||||||
|
hasWorkingTreeChanges: true,
|
||||||
|
forcePushOnly: true,
|
||||||
|
pushTarget: "origin/feature/test",
|
||||||
|
});
|
||||||
|
assert.deepEqual(stages, ["Pushing to origin/feature/test...", "Creating PR..."]);
|
||||||
|
});
|
||||||
|
|
||||||
it("includes commit stages for commit+push when working tree is dirty", () => {
|
it("includes commit stages for commit+push when working tree is dirty", () => {
|
||||||
const stages = buildGitActionProgressStages({
|
const stages = buildGitActionProgressStages({
|
||||||
action: "commit_push",
|
action: "commit_push",
|
||||||
@@ -647,6 +834,7 @@ describe("summarizeGitResult", () => {
|
|||||||
it("returns commit-focused toast for commit action", () => {
|
it("returns commit-focused toast for commit action", () => {
|
||||||
const result = summarizeGitResult({
|
const result = summarizeGitResult({
|
||||||
action: "commit",
|
action: "commit",
|
||||||
|
branch: { status: "skipped_not_requested" },
|
||||||
commit: {
|
commit: {
|
||||||
status: "created",
|
status: "created",
|
||||||
commitSha: "0123456789abcdef",
|
commitSha: "0123456789abcdef",
|
||||||
@@ -665,6 +853,7 @@ describe("summarizeGitResult", () => {
|
|||||||
it("returns push-focused toast for push action", () => {
|
it("returns push-focused toast for push action", () => {
|
||||||
const result = summarizeGitResult({
|
const result = summarizeGitResult({
|
||||||
action: "commit_push",
|
action: "commit_push",
|
||||||
|
branch: { status: "skipped_not_requested" },
|
||||||
commit: {
|
commit: {
|
||||||
status: "created",
|
status: "created",
|
||||||
commitSha: "abcdef0123456789",
|
commitSha: "abcdef0123456789",
|
||||||
@@ -687,6 +876,7 @@ describe("summarizeGitResult", () => {
|
|||||||
it("returns PR-focused toast for created PR action", () => {
|
it("returns PR-focused toast for created PR action", () => {
|
||||||
const result = summarizeGitResult({
|
const result = summarizeGitResult({
|
||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
|
branch: { status: "skipped_not_requested" },
|
||||||
commit: {
|
commit: {
|
||||||
status: "created",
|
status: "created",
|
||||||
commitSha: "89abcdef01234567",
|
commitSha: "89abcdef01234567",
|
||||||
@@ -712,6 +902,7 @@ describe("summarizeGitResult", () => {
|
|||||||
it("truncates long description text", () => {
|
it("truncates long description text", () => {
|
||||||
const result = summarizeGitResult({
|
const result = summarizeGitResult({
|
||||||
action: "commit_push_pr",
|
action: "commit_push_pr",
|
||||||
|
branch: { status: "skipped_not_requested" },
|
||||||
commit: {
|
commit: {
|
||||||
status: "created",
|
status: "created",
|
||||||
commitSha: "89abcdef01234567",
|
commitSha: "89abcdef01234567",
|
||||||
@@ -732,3 +923,33 @@ describe("summarizeGitResult", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("resolveAutoFeatureBranchName", () => {
|
||||||
|
it("uses semantic preferred branch names when available", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
|
||||||
|
assert.equal(branch, "feature/fix-toast-copy");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("normalizes preferred names that already include a branch namespace", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
|
||||||
|
assert.equal(branch, "feature/refine-toolbar-actions");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("increments suffix when the preferred branch name already exists", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(
|
||||||
|
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
|
||||||
|
"fix toast copy",
|
||||||
|
);
|
||||||
|
assert.equal(branch, "feature/fix-toast-copy-3");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats existing branch names as case-insensitive for collision checks", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
|
||||||
|
assert.equal(branch, "feature/ticket-1-2");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to feature/update when no preferred name is provided", () => {
|
||||||
|
const branch = resolveAutoFeatureBranchName(["main"]);
|
||||||
|
assert.equal(branch, "feature/update");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -25,6 +25,14 @@ 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;
|
||||||
|
|
||||||
@@ -49,7 +57,9 @@ export function buildGitActionProgressStages(input: {
|
|||||||
hasWorkingTreeChanges: boolean;
|
hasWorkingTreeChanges: boolean;
|
||||||
forcePushOnly?: boolean;
|
forcePushOnly?: boolean;
|
||||||
pushTarget?: string;
|
pushTarget?: string;
|
||||||
|
featureBranch?: boolean;
|
||||||
}): string[] {
|
}): string[] {
|
||||||
|
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
|
||||||
const shouldIncludeCommitStages =
|
const shouldIncludeCommitStages =
|
||||||
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
|
!input.forcePushOnly && (input.action === "commit" || input.hasWorkingTreeChanges);
|
||||||
const commitStages = !shouldIncludeCommitStages
|
const commitStages = !shouldIncludeCommitStages
|
||||||
@@ -59,12 +69,12 @@ export function buildGitActionProgressStages(input: {
|
|||||||
: ["Generating commit message...", "Committing..."];
|
: ["Generating commit message...", "Committing..."];
|
||||||
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
|
||||||
if (input.action === "commit") {
|
if (input.action === "commit") {
|
||||||
return commitStages;
|
return [...branchStages, ...commitStages];
|
||||||
}
|
}
|
||||||
if (input.action === "commit_push") {
|
if (input.action === "commit_push") {
|
||||||
return [...commitStages, pushStage];
|
return [...branchStages, ...commitStages, pushStage];
|
||||||
}
|
}
|
||||||
return [...commitStages, pushStage, "Creating PR..."];
|
return [...branchStages, ...commitStages, pushStage, "Creating PR..."];
|
||||||
}
|
}
|
||||||
|
|
||||||
const withDescription = (title: string, description: string | undefined) =>
|
const withDescription = (title: string, description: string | undefined) =>
|
||||||
@@ -118,7 +128,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;
|
||||||
|
|
||||||
@@ -204,6 +213,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 +284,43 @@ 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",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-export from shared for backwards compatibility in this module's exports
|
||||||
|
export { resolveAutoFeatureBranchName } from "@t3tools/shared/git";
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { type GitStatusResult, type GitStackedAction, type ThreadId } from "@t3tools/contracts";
|
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
|
||||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||||
@@ -8,9 +8,10 @@ import {
|
|||||||
buildMenuItems,
|
buildMenuItems,
|
||||||
type GitActionIconName,
|
type GitActionIconName,
|
||||||
type GitActionMenuItem,
|
type GitActionMenuItem,
|
||||||
type GitDialogAction,
|
|
||||||
type GitQuickAction,
|
type GitQuickAction,
|
||||||
|
type DefaultBranchConfirmableAction,
|
||||||
requiresDefaultBranchConfirmation,
|
requiresDefaultBranchConfirmation,
|
||||||
|
resolveDefaultBranchActionDialogCopy,
|
||||||
resolveQuickAction,
|
resolveQuickAction,
|
||||||
summarizeGitResult,
|
summarizeGitResult,
|
||||||
} from "./GitActionsControl.logic";
|
} from "./GitActionsControl.logic";
|
||||||
@@ -47,6 +48,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,
|
||||||
@@ -97,26 +109,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 +144,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));
|
||||||
|
|
||||||
@@ -191,23 +194,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();
|
||||||
@@ -237,43 +230,85 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.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,
|
||||||
|
featureBranch = false,
|
||||||
|
isDefaultBranchOverride,
|
||||||
|
progressToastId,
|
||||||
}: {
|
}: {
|
||||||
action: GitStackedAction;
|
action: GitStackedAction;
|
||||||
commitMessage?: string;
|
commitMessage?: string;
|
||||||
forcePushOnlyProgress?: boolean;
|
forcePushOnlyProgress?: boolean;
|
||||||
onConfirmed?: () => void;
|
onConfirmed?: () => void;
|
||||||
|
skipDefaultBranchPrompt?: boolean;
|
||||||
|
statusOverride?: GitStatusResult | null;
|
||||||
|
featureBranch?: boolean;
|
||||||
|
isDefaultBranchOverride?: boolean;
|
||||||
|
progressToastId?: GitActionToastId;
|
||||||
}) => {
|
}) => {
|
||||||
const confirmed = await maybeConfirmPushToDefaultBranch(action);
|
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||||
if (!confirmed) return;
|
const actionBranch = actionStatus?.branch ?? null;
|
||||||
|
const actionIsDefaultBranch = isDefaultBranchOverride ?? (featureBranch ? false : isDefaultBranch);
|
||||||
|
const includesCommit =
|
||||||
|
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
|
||||||
|
if (
|
||||||
|
!skipDefaultBranchPrompt &&
|
||||||
|
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
|
||||||
|
actionBranch
|
||||||
|
) {
|
||||||
|
if (action !== "commit_push" && action !== "commit_push_pr") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPendingDefaultBranchAction({
|
||||||
|
action,
|
||||||
|
branchName: actionBranch,
|
||||||
|
includesCommit,
|
||||||
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
forcePushOnlyProgress,
|
||||||
|
...(onConfirmed ? { onConfirmed } : {}),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
onConfirmed?.();
|
onConfirmed?.();
|
||||||
|
|
||||||
const pushTarget = gitStatusForActions?.branch
|
const pushTarget = !featureBranch && 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,
|
||||||
|
featureBranch,
|
||||||
...(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,
|
||||||
@@ -288,6 +323,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||||
action,
|
action,
|
||||||
...(commitMessage ? { commitMessage } : {}),
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
...(featureBranch ? { featureBranch } : {}),
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -295,19 +331,25 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
stopProgressUpdates();
|
stopProgressUpdates();
|
||||||
const resultToast = summarizeGitResult(result);
|
const resultToast = summarizeGitResult(result);
|
||||||
|
|
||||||
const existingOpenPrUrl =
|
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
|
||||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
|
||||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
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 ||
|
||||||
|
result.pr.status === "created" ||
|
||||||
|
result.pr.status === "opened_existing");
|
||||||
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,
|
||||||
@@ -325,6 +367,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,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -347,7 +391,12 @@ 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",
|
||||||
|
forcePushOnlyProgress: true,
|
||||||
|
statusOverride: actionStatus,
|
||||||
|
isDefaultBranchOverride: actionIsDefaultBranch,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -355,7 +404,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.",
|
||||||
@@ -365,17 +414,68 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
|||||||
},
|
},
|
||||||
|
|
||||||
[
|
[
|
||||||
gitStatusForActions?.branch,
|
|
||||||
gitStatusForActions?.hasWorkingTreeChanges,
|
|
||||||
gitStatusForActions?.pr,
|
|
||||||
isDefaultBranch,
|
isDefaultBranch,
|
||||||
maybeConfirmPushToDefaultBranch,
|
|
||||||
runImmediateGitActionMutation,
|
runImmediateGitActionMutation,
|
||||||
setActiveDialogAction,
|
setPendingDefaultBranchAction,
|
||||||
threadToastData,
|
threadToastData,
|
||||||
|
gitStatusForActions,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const continuePendingDefaultBranchAction = useCallback(() => {
|
||||||
|
if (!pendingDefaultBranchAction) return;
|
||||||
|
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
|
||||||
|
setPendingDefaultBranchAction(null);
|
||||||
|
void runGitActionWithToast({
|
||||||
|
action,
|
||||||
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
forcePushOnlyProgress,
|
||||||
|
...(onConfirmed ? { onConfirmed } : {}),
|
||||||
|
skipDefaultBranchPrompt: true,
|
||||||
|
});
|
||||||
|
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||||
|
|
||||||
|
const checkoutNewBranchAndRunAction = useCallback(
|
||||||
|
(actionParams: {
|
||||||
|
action: GitStackedAction;
|
||||||
|
commitMessage?: string;
|
||||||
|
forcePushOnlyProgress?: boolean;
|
||||||
|
onConfirmed?: () => void;
|
||||||
|
}) => {
|
||||||
|
void runGitActionWithToast({
|
||||||
|
...actionParams,
|
||||||
|
featureBranch: true,
|
||||||
|
skipDefaultBranchPrompt: true,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[runGitActionWithToast],
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||||
|
if (!pendingDefaultBranchAction) return;
|
||||||
|
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
|
||||||
|
setPendingDefaultBranchAction(null);
|
||||||
|
checkoutNewBranchAndRunAction({
|
||||||
|
action,
|
||||||
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
forcePushOnlyProgress,
|
||||||
|
...(onConfirmed ? { onConfirmed } : {}),
|
||||||
|
});
|
||||||
|
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||||
|
|
||||||
|
const runDialogActionOnNewBranch = useCallback(() => {
|
||||||
|
if (!isCommitDialogOpen) return;
|
||||||
|
const commitMessage = dialogCommitMessage.trim();
|
||||||
|
|
||||||
|
setIsCommitDialogOpen(false);
|
||||||
|
setDialogCommitMessage("");
|
||||||
|
|
||||||
|
checkoutNewBranchAndRunAction({
|
||||||
|
action: "commit",
|
||||||
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
});
|
||||||
|
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
|
||||||
|
|
||||||
const runQuickAction = useCallback(() => {
|
const runQuickAction = useCallback(() => {
|
||||||
if (quickAction.kind === "open_pr") {
|
if (quickAction.kind === "open_pr") {
|
||||||
void openExistingPr();
|
void openExistingPr();
|
||||||
@@ -427,30 +527,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) => {
|
||||||
@@ -606,68 +707,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>
|
||||||
@@ -707,35 +769,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,4 +1,4 @@
|
|||||||
import type { SVGProps } from "react";
|
import { type SVGProps, useId } from "react";
|
||||||
|
|
||||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||||
|
|
||||||
@@ -19,3 +19,126 @@ export const CursorIcon: Icon = (props) => (
|
|||||||
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
|
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const VisualStudioCode: Icon = (props) => {
|
||||||
|
const id = useId();
|
||||||
|
const maskId = `${id}-vscode-a`;
|
||||||
|
const topShadowFilterId = `${id}-vscode-b`;
|
||||||
|
const sideShadowFilterId = `${id}-vscode-c`;
|
||||||
|
const overlayGradientId = `${id}-vscode-d`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<svg {...props} fill="none" viewBox="0 0 100 100">
|
||||||
|
<mask id={maskId} width="100" height="100" x="0" y="0" maskUnits="userSpaceOnUse">
|
||||||
|
<path
|
||||||
|
fill="#fff"
|
||||||
|
fillRule="evenodd"
|
||||||
|
d="M70.912 99.317a6.223 6.223 0 0 0 4.96-.19l20.589-9.907A6.25 6.25 0 0 0 100 83.587V16.413a6.25 6.25 0 0 0-3.54-5.632L75.874.874a6.226 6.226 0 0 0-7.104 1.21L29.355 38.04 12.187 25.01a4.162 4.162 0 0 0-5.318.236l-5.506 5.009a4.168 4.168 0 0 0-.004 6.162L16.247 50 1.36 63.583a4.168 4.168 0 0 0 .004 6.162l5.506 5.01a4.162 4.162 0 0 0 5.318.236l17.168-13.032L68.77 97.917a6.217 6.217 0 0 0 2.143 1.4ZM75.015 27.3 45.11 50l29.906 22.701V27.3Z"
|
||||||
|
clipRule="evenodd"
|
||||||
|
/>
|
||||||
|
</mask>
|
||||||
|
<g mask={`url(#${maskId})`}>
|
||||||
|
<path
|
||||||
|
fill="#0065A9"
|
||||||
|
d="M96.461 10.796 75.857.876a6.23 6.23 0 0 0-7.107 1.207l-67.451 61.5a4.167 4.167 0 0 0 .004 6.162l5.51 5.009a4.167 4.167 0 0 0 5.32.236l81.228-61.62c2.725-2.067 6.639-.124 6.639 3.297v-.24a6.25 6.25 0 0 0-3.539-5.63Z"
|
||||||
|
/>
|
||||||
|
<g filter={`url(#${topShadowFilterId})`}>
|
||||||
|
<path
|
||||||
|
fill="#007ACC"
|
||||||
|
d="m96.461 89.204-20.604 9.92a6.229 6.229 0 0 1-7.107-1.207l-67.451-61.5a4.167 4.167 0 0 1 .004-6.162l5.51-5.009a4.167 4.167 0 0 1 5.32-.236l81.228 61.62c2.725 2.067 6.639.124 6.639-3.297v.24a6.25 6.25 0 0 1-3.539 5.63Z"
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
<g filter={`url(#${sideShadowFilterId})`}>
|
||||||
|
<path
|
||||||
|
fill="#1F9CF0"
|
||||||
|
d="M75.858 99.126a6.232 6.232 0 0 1-7.108-1.21c2.306 2.307 6.25.674 6.25-2.588V4.672c0-3.262-3.944-4.895-6.25-2.589a6.232 6.232 0 0 1 7.108-1.21l20.6 9.908A6.25 6.25 0 0 1 100 16.413v67.174a6.25 6.25 0 0 1-3.541 5.633l-20.601 9.906Z"
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
<path
|
||||||
|
fill={`url(#${overlayGradientId})`}
|
||||||
|
fillRule="evenodd"
|
||||||
|
d="M70.851 99.317a6.224 6.224 0 0 0 4.96-.19L96.4 89.22a6.25 6.25 0 0 0 3.54-5.633V16.413a6.25 6.25 0 0 0-3.54-5.632L75.812.874a6.226 6.226 0 0 0-7.104 1.21L29.294 38.04 12.126 25.01a4.162 4.162 0 0 0-5.317.236l-5.507 5.009a4.168 4.168 0 0 0-.004 6.162L16.186 50 1.298 63.583a4.168 4.168 0 0 0 .004 6.162l5.507 5.009a4.162 4.162 0 0 0 5.317.236L29.294 61.96l39.414 35.958a6.218 6.218 0 0 0 2.143 1.4ZM74.954 27.3 45.048 50l29.906 22.701V27.3Z"
|
||||||
|
clipRule="evenodd"
|
||||||
|
opacity=".25"
|
||||||
|
style={{ mixBlendMode: "overlay" }}
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
<defs>
|
||||||
|
<filter
|
||||||
|
id={topShadowFilterId}
|
||||||
|
width="116.727"
|
||||||
|
height="92.246"
|
||||||
|
x="-8.394"
|
||||||
|
y="15.829"
|
||||||
|
colorInterpolationFilters="sRGB"
|
||||||
|
filterUnits="userSpaceOnUse"
|
||||||
|
>
|
||||||
|
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||||
|
<feColorMatrix
|
||||||
|
in="SourceAlpha"
|
||||||
|
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||||
|
/>
|
||||||
|
<feOffset />
|
||||||
|
<feGaussianBlur stdDeviation="4.167" />
|
||||||
|
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||||
|
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||||
|
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||||
|
</filter>
|
||||||
|
<filter
|
||||||
|
id={sideShadowFilterId}
|
||||||
|
width="47.917"
|
||||||
|
height="116.151"
|
||||||
|
x="60.417"
|
||||||
|
y="-8.076"
|
||||||
|
colorInterpolationFilters="sRGB"
|
||||||
|
filterUnits="userSpaceOnUse"
|
||||||
|
>
|
||||||
|
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
||||||
|
<feColorMatrix
|
||||||
|
in="SourceAlpha"
|
||||||
|
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
|
||||||
|
/>
|
||||||
|
<feOffset />
|
||||||
|
<feGaussianBlur stdDeviation="4.167" />
|
||||||
|
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
|
||||||
|
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
|
||||||
|
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
|
||||||
|
</filter>
|
||||||
|
<linearGradient
|
||||||
|
id={overlayGradientId}
|
||||||
|
x1="49.939"
|
||||||
|
x2="49.939"
|
||||||
|
y1=".258"
|
||||||
|
y2="99.742"
|
||||||
|
gradientUnits="userSpaceOnUse"
|
||||||
|
>
|
||||||
|
<stop stopColor="#fff" />
|
||||||
|
<stop offset="1" stopColor="#fff" stopOpacity="0" />
|
||||||
|
</linearGradient>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Zed: Icon = (props) => {
|
||||||
|
const id = useId();
|
||||||
|
const clipPathId = `${id}-zed-logo-a`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<svg {...props} fill="none" viewBox="0 0 96 96">
|
||||||
|
<g clipPath={`url(#${clipPathId})`}>
|
||||||
|
<path
|
||||||
|
fill="currentColor"
|
||||||
|
fillRule="evenodd"
|
||||||
|
d="M9 6a3 3 0 0 0-3 3v66H0V9a9 9 0 0 1 9-9h80.379c4.009 0 6.016 4.847 3.182 7.682L43.055 57.187H57V51h6v7.688a4.5 4.5 0 0 1-4.5 4.5H37.055L26.743 73.5H73.5V36h6v37.5a6 6 0 0 1-6 6H20.743L10.243 90H87a3 3 0 0 0 3-3V21h6v66a9 9 0 0 1-9 9H6.621c-4.009 0-6.016-4.847-3.182-7.682L52.757 39H39v6h-6v-7.5a4.5 4.5 0 0 1 4.5-4.5h21.257l10.5-10.5H22.5V60h-6V22.5a6 6 0 0 1 6-6h52.757L85.757 6H9Z"
|
||||||
|
clipRule="evenodd"
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
<defs>
|
||||||
|
<clipPath id={clipPathId}>
|
||||||
|
<path fill="#fff" d="M0 0h96v96H0z" />
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
+439
-108
@@ -1,7 +1,14 @@
|
|||||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
import {
|
||||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
ChevronRightIcon,
|
||||||
|
FolderIcon,
|
||||||
|
GitPullRequestIcon,
|
||||||
|
RocketIcon,
|
||||||
|
TerminalIcon,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import {
|
import {
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
|
type DesktopUpdateState,
|
||||||
ProjectId,
|
ProjectId,
|
||||||
ThreadId,
|
ThreadId,
|
||||||
type GitStatusResult,
|
type GitStatusResult,
|
||||||
@@ -20,7 +27,18 @@ import { derivePendingApprovals } from "../session-logic";
|
|||||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
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 { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||||
import { toastManager } from "./ui/toast";
|
import { toastManager } from "./ui/toast";
|
||||||
|
import {
|
||||||
|
getDesktopUpdateActionError,
|
||||||
|
getDesktopUpdateButtonTooltip,
|
||||||
|
isDesktopUpdateButtonDisabled,
|
||||||
|
resolveDesktopUpdateButtonAction,
|
||||||
|
shouldHighlightDesktopUpdateError,
|
||||||
|
shouldShowDesktopUpdateButton,
|
||||||
|
shouldToastDesktopUpdateActionResult,
|
||||||
|
} from "./desktopUpdate.logic";
|
||||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||||
import {
|
import {
|
||||||
@@ -125,8 +143,10 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
|
function terminalStatusFromRunningIds(
|
||||||
if (thread.runningTerminalIds.length === 0) {
|
runningTerminalIds: string[],
|
||||||
|
): TerminalStatusIndicator | null {
|
||||||
|
if (runningTerminalIds.length === 0) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@@ -170,7 +190,7 @@ 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"
|
||||||
>
|
>
|
||||||
@@ -227,7 +247,25 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function Sidebar() {
|
export default function Sidebar() {
|
||||||
const { state, dispatch } = useStore();
|
const projects = useStore((store) => store.projects);
|
||||||
|
const threads = useStore((store) => store.threads);
|
||||||
|
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||||
|
const toggleProject = useStore((store) => store.toggleProject);
|
||||||
|
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||||
|
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||||
|
(store) => store.getDraftThreadByProjectId,
|
||||||
|
);
|
||||||
|
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||||
|
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
|
||||||
|
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||||
|
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({
|
||||||
@@ -244,36 +282,40 @@ 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 [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
|
||||||
|
const [renamingTitle, setRenamingTitle] = useState("");
|
||||||
|
const renamingCommittedRef = useRef(false);
|
||||||
|
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
|
||||||
const pendingApprovalByThreadId = useMemo(() => {
|
const pendingApprovalByThreadId = useMemo(() => {
|
||||||
const map = new Map<ThreadId, boolean>();
|
const map = new Map<ThreadId, boolean>();
|
||||||
for (const thread of state.threads) {
|
for (const thread of threads) {
|
||||||
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}, [state.threads]);
|
}, [threads]);
|
||||||
const projectCwdById = useMemo(
|
const projectCwdById = useMemo(
|
||||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
|
||||||
[state.projects],
|
[projects],
|
||||||
);
|
);
|
||||||
const threadGitTargets = useMemo(
|
const threadGitTargets = useMemo(
|
||||||
() =>
|
() =>
|
||||||
state.threads.map((thread) => ({
|
threads.map((thread) => ({
|
||||||
threadId: thread.id,
|
threadId: thread.id,
|
||||||
branch: thread.branch,
|
branch: thread.branch,
|
||||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||||
})),
|
})),
|
||||||
[projectCwdById, state.threads],
|
[projectCwdById, threads],
|
||||||
);
|
);
|
||||||
const threadGitStatusCwds = useMemo(
|
const threadGitStatusCwds = useMemo(
|
||||||
() =>
|
() => [
|
||||||
[
|
...new Set(
|
||||||
...new Set(
|
threadGitTargets
|
||||||
threadGitTargets
|
.filter((target) => target.branch !== null)
|
||||||
.filter((target) => target.branch !== null)
|
.map((target) => target.cwd)
|
||||||
.map((target) => target.cwd)
|
.filter((cwd): cwd is string => cwd !== null),
|
||||||
.filter((cwd): cwd is string => cwd !== null),
|
),
|
||||||
),
|
],
|
||||||
],
|
|
||||||
[threadGitTargets],
|
[threadGitTargets],
|
||||||
);
|
);
|
||||||
const threadGitStatusQueries = useQueries({
|
const threadGitStatusQueries = useQueries({
|
||||||
@@ -299,7 +341,7 @@ export default function Sidebar() {
|
|||||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||||
const branchMatches =
|
const branchMatches =
|
||||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||||
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
|
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||||
@@ -332,47 +374,76 @@ 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(
|
||||||
(projectId: ProjectId) => {
|
(projectId: ProjectId) => {
|
||||||
const latestThread = state.threads
|
const latestThread = threads
|
||||||
.filter((thread) => thread.projectId === projectId)
|
.filter((thread) => thread.projectId === projectId)
|
||||||
.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();
|
||||||
@@ -386,7 +457,7 @@ export default function Sidebar() {
|
|||||||
params: { threadId: latestThread.id },
|
params: { threadId: latestThread.id },
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[navigate, state.threads],
|
[navigate, threads],
|
||||||
);
|
);
|
||||||
|
|
||||||
const addProjectFromPath = useCallback(
|
const addProjectFromPath = useCallback(
|
||||||
@@ -394,20 +465,27 @@ export default function Sidebar() {
|
|||||||
const cwd = rawCwd.trim();
|
const cwd = rawCwd.trim();
|
||||||
if (!cwd || isAddingProject) return;
|
if (!cwd || isAddingProject) return;
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
|
if (!api) return;
|
||||||
|
|
||||||
setIsAddingProject(true);
|
setIsAddingProject(true);
|
||||||
try {
|
const finishAddingProject = () => {
|
||||||
if (!api) return;
|
setIsAddingProject(false);
|
||||||
const existing = state.projects.find((project) => project.cwd === cwd);
|
setNewCwd("");
|
||||||
if (existing) {
|
setAddingProject(false);
|
||||||
focusMostRecentThreadForProject(existing.id);
|
};
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectId = newProjectId();
|
const existing = projects.find((project) => project.cwd === cwd);
|
||||||
const createdAt = new Date().toISOString();
|
if (existing) {
|
||||||
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
focusMostRecentThreadForProject(existing.id);
|
||||||
await api.orchestration.dispatchCommand({
|
finishAddingProject();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const projectId = newProjectId();
|
||||||
|
const createdAt = new Date().toISOString();
|
||||||
|
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
|
||||||
|
const projectCreated = await api.orchestration
|
||||||
|
.dispatchCommand({
|
||||||
type: "project.create",
|
type: "project.create",
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
projectId,
|
projectId,
|
||||||
@@ -415,15 +493,15 @@ export default function Sidebar() {
|
|||||||
workspaceRoot: cwd,
|
workspaceRoot: cwd,
|
||||||
defaultModel: DEFAULT_MODEL,
|
defaultModel: DEFAULT_MODEL,
|
||||||
createdAt,
|
createdAt,
|
||||||
});
|
})
|
||||||
await handleNewThread(projectId);
|
.then(() => true)
|
||||||
} finally {
|
.catch(() => false);
|
||||||
setIsAddingProject(false);
|
if (projectCreated) {
|
||||||
setNewCwd("");
|
await handleNewThread(projectId).catch(() => undefined);
|
||||||
setAddingProject(false);
|
|
||||||
}
|
}
|
||||||
|
finishAddingProject();
|
||||||
},
|
},
|
||||||
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
|
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleAddProject = () => {
|
const handleAddProject = () => {
|
||||||
@@ -434,34 +512,94 @@ export default function Sidebar() {
|
|||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api || isPickingFolder) return;
|
if (!api || isPickingFolder) return;
|
||||||
setIsPickingFolder(true);
|
setIsPickingFolder(true);
|
||||||
|
let pickedPath: string | null = null;
|
||||||
try {
|
try {
|
||||||
const pickedPath = await api.dialogs.pickFolder();
|
pickedPath = await api.dialogs.pickFolder();
|
||||||
if (!pickedPath) return;
|
} catch {
|
||||||
await addProjectFromPath(pickedPath);
|
// Ignore picker failures and leave the current thread selection unchanged.
|
||||||
} finally {
|
|
||||||
setIsPickingFolder(false);
|
|
||||||
}
|
}
|
||||||
|
if (pickedPath) {
|
||||||
|
await addProjectFromPath(pickedPath);
|
||||||
|
}
|
||||||
|
setIsPickingFolder(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const cancelRename = useCallback(() => {
|
||||||
|
setRenamingThreadId(null);
|
||||||
|
renamingInputRef.current = null;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const commitRename = useCallback(
|
||||||
|
async (threadId: ThreadId, newTitle: string, originalTitle: string) => {
|
||||||
|
const finishRename = () => {
|
||||||
|
setRenamingThreadId((current) => {
|
||||||
|
if (current !== threadId) return current;
|
||||||
|
renamingInputRef.current = null;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const trimmed = newTitle.trim();
|
||||||
|
if (trimmed.length === 0) {
|
||||||
|
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
|
||||||
|
finishRename();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (trimmed === originalTitle) {
|
||||||
|
finishRename();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const api = readNativeApi();
|
||||||
|
if (!api) {
|
||||||
|
finishRename();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await api.orchestration.dispatchCommand({
|
||||||
|
type: "thread.meta.update",
|
||||||
|
commandId: newCommandId(),
|
||||||
|
threadId,
|
||||||
|
title: trimmed,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Failed to rename thread",
|
||||||
|
description: error instanceof Error ? error.message : "An error occurred.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
finishRename();
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
const handleThreadContextMenu = useCallback(
|
const handleThreadContextMenu = useCallback(
|
||||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api) return;
|
if (!api) return;
|
||||||
const clicked = await api.contextMenu.show(
|
const clicked = await api.contextMenu.show(
|
||||||
[
|
[
|
||||||
|
{ id: "rename", label: "Rename thread" },
|
||||||
{ id: "mark-unread", label: "Mark unread" },
|
{ id: "mark-unread", label: "Mark unread" },
|
||||||
{ id: "delete", label: "Delete" },
|
{ id: "delete", label: "Delete", destructive: true },
|
||||||
],
|
],
|
||||||
position,
|
position,
|
||||||
);
|
);
|
||||||
|
const thread = threads.find((t) => t.id === threadId);
|
||||||
|
if (!thread) return;
|
||||||
|
|
||||||
|
if (clicked === "rename") {
|
||||||
|
setRenamingThreadId(threadId);
|
||||||
|
setRenamingTitle(thread.title);
|
||||||
|
renamingCommittedRef.current = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (clicked === "mark-unread") {
|
if (clicked === "mark-unread") {
|
||||||
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
|
markThreadUnread(threadId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (clicked !== "delete") return;
|
if (clicked !== "delete") return;
|
||||||
|
|
||||||
const thread = state.threads.find((t) => t.id === threadId);
|
|
||||||
if (!thread) return;
|
|
||||||
if (appSettings.confirmThreadDelete) {
|
if (appSettings.confirmThreadDelete) {
|
||||||
const confirmed = await api.dialogs.confirm(
|
const confirmed = await api.dialogs.confirm(
|
||||||
[
|
[
|
||||||
@@ -473,8 +611,8 @@ export default function Sidebar() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
const threadProject = projects.find((project) => project.id === thread.projectId);
|
||||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
|
||||||
const displayWorktreePath = orphanedWorktreePath
|
const displayWorktreePath = orphanedWorktreePath
|
||||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
||||||
: null;
|
: null;
|
||||||
@@ -511,12 +649,15 @@ export default function Sidebar() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||||
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
|
||||||
await api.orchestration.dispatchCommand({
|
await api.orchestration.dispatchCommand({
|
||||||
type: "thread.delete",
|
type: "thread.delete",
|
||||||
commandId: newCommandId(),
|
commandId: newCommandId(),
|
||||||
threadId,
|
threadId,
|
||||||
});
|
});
|
||||||
|
clearComposerDraftForThread(threadId);
|
||||||
|
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||||
|
clearTerminalState(threadId);
|
||||||
if (shouldNavigateToFallback) {
|
if (shouldNavigateToFallback) {
|
||||||
if (fallbackThreadId) {
|
if (fallbackThreadId) {
|
||||||
void navigate({
|
void navigate({
|
||||||
@@ -556,12 +697,15 @@ export default function Sidebar() {
|
|||||||
},
|
},
|
||||||
[
|
[
|
||||||
appSettings.confirmThreadDelete,
|
appSettings.confirmThreadDelete,
|
||||||
dispatch,
|
clearComposerDraftForThread,
|
||||||
|
clearProjectDraftThreadById,
|
||||||
|
clearTerminalState,
|
||||||
|
markThreadUnread,
|
||||||
navigate,
|
navigate,
|
||||||
|
projects,
|
||||||
removeWorktreeMutation,
|
removeWorktreeMutation,
|
||||||
routeThreadId,
|
routeThreadId,
|
||||||
state.projects,
|
threads,
|
||||||
state.threads,
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -569,13 +713,16 @@ export default function Sidebar() {
|
|||||||
async (projectId: ProjectId, position: { x: number; y: number }) => {
|
async (projectId: ProjectId, position: { x: number; y: number }) => {
|
||||||
const api = readNativeApi();
|
const api = readNativeApi();
|
||||||
if (!api) return;
|
if (!api) return;
|
||||||
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
|
const clicked = await api.contextMenu.show(
|
||||||
|
[{ id: "delete", label: "Delete", destructive: true }],
|
||||||
|
position,
|
||||||
|
);
|
||||||
if (clicked !== "delete") return;
|
if (clicked !== "delete") return;
|
||||||
|
|
||||||
const project = state.projects.find((entry) => entry.id === projectId);
|
const project = projects.find((entry) => entry.id === projectId);
|
||||||
if (!project) return;
|
if (!project) return;
|
||||||
|
|
||||||
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
|
const projectThreads = threads.filter((thread) => thread.projectId === projectId);
|
||||||
if (projectThreads.length > 0) {
|
if (projectThreads.length > 0) {
|
||||||
toastManager.add({
|
toastManager.add({
|
||||||
type: "warning",
|
type: "warning",
|
||||||
@@ -591,6 +738,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(),
|
||||||
@@ -606,16 +758,24 @@ export default function Sidebar() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[state.projects, state.threads],
|
[
|
||||||
|
clearComposerDraftForThread,
|
||||||
|
clearProjectDraftThreadId,
|
||||||
|
getDraftThreadByProjectId,
|
||||||
|
projects,
|
||||||
|
threads,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||||
const activeThread = routeThreadId
|
const activeThread = routeThreadId
|
||||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
? 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 ?? projects[0]?.id;
|
||||||
if (!projectId) return;
|
if (!projectId) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
void handleNewThread(projectId);
|
void handleNewThread(projectId);
|
||||||
@@ -623,12 +783,13 @@ 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 ?? 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"),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -636,26 +797,139 @@ export default function Sidebar() {
|
|||||||
return () => {
|
return () => {
|
||||||
window.removeEventListener("keydown", onWindowKeyDown);
|
window.removeEventListener("keydown", onWindowKeyDown);
|
||||||
};
|
};
|
||||||
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isElectron) return;
|
||||||
|
const bridge = window.desktopBridge;
|
||||||
|
if (
|
||||||
|
!bridge ||
|
||||||
|
typeof bridge.getUpdateState !== "function" ||
|
||||||
|
typeof bridge.onUpdateState !== "function"
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let disposed = false;
|
||||||
|
let receivedSubscriptionUpdate = false;
|
||||||
|
const unsubscribe = bridge.onUpdateState((nextState) => {
|
||||||
|
if (disposed) return;
|
||||||
|
receivedSubscriptionUpdate = true;
|
||||||
|
setDesktopUpdateState(nextState);
|
||||||
|
});
|
||||||
|
|
||||||
|
void bridge
|
||||||
|
.getUpdateState()
|
||||||
|
.then((nextState) => {
|
||||||
|
if (disposed || receivedSubscriptionUpdate) return;
|
||||||
|
setDesktopUpdateState(nextState);
|
||||||
|
})
|
||||||
|
.catch(() => undefined);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
disposed = true;
|
||||||
|
unsubscribe();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const onCreateThreadClick = () => {
|
const onCreateThreadClick = () => {
|
||||||
if (state.projects.length === 0) {
|
if (projects.length === 0) {
|
||||||
setAddingProject(true);
|
setAddingProject(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const firstProject = state.projects[0];
|
const firstProject = projects[0];
|
||||||
if (firstProject) void handleNewThread(firstProject.id);
|
if (firstProject) void handleNewThread(firstProject.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState);
|
||||||
|
|
||||||
|
const desktopUpdateTooltip = desktopUpdateState
|
||||||
|
? getDesktopUpdateButtonTooltip(desktopUpdateState)
|
||||||
|
: "Update available";
|
||||||
|
|
||||||
|
const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState);
|
||||||
|
const desktopUpdateButtonAction = desktopUpdateState
|
||||||
|
? resolveDesktopUpdateButtonAction(desktopUpdateState)
|
||||||
|
: "none";
|
||||||
|
const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled
|
||||||
|
? "cursor-not-allowed opacity-60"
|
||||||
|
: "hover:bg-accent hover:text-foreground";
|
||||||
|
const desktopUpdateButtonClasses =
|
||||||
|
desktopUpdateState?.status === "downloaded"
|
||||||
|
? "text-emerald-500"
|
||||||
|
: desktopUpdateState?.status === "downloading"
|
||||||
|
? "text-sky-400"
|
||||||
|
: shouldHighlightDesktopUpdateError(desktopUpdateState)
|
||||||
|
? "text-rose-500 animate-pulse"
|
||||||
|
: "text-amber-500 animate-pulse";
|
||||||
|
|
||||||
|
const handleDesktopUpdateButtonClick = useCallback(() => {
|
||||||
|
const bridge = window.desktopBridge;
|
||||||
|
if (!bridge || !desktopUpdateState) return;
|
||||||
|
if (desktopUpdateButtonDisabled || desktopUpdateButtonAction === "none") return;
|
||||||
|
|
||||||
|
if (desktopUpdateButtonAction === "download") {
|
||||||
|
void bridge
|
||||||
|
.downloadUpdate()
|
||||||
|
.then((result) => {
|
||||||
|
if (result.completed) {
|
||||||
|
toastManager.add({
|
||||||
|
type: "success",
|
||||||
|
title: "Update downloaded",
|
||||||
|
description: "Restart the app from the update button to install it.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||||
|
const actionError = getDesktopUpdateActionError(result);
|
||||||
|
if (!actionError) return;
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Could not download update",
|
||||||
|
description: actionError,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Could not start update download",
|
||||||
|
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (desktopUpdateButtonAction === "install") {
|
||||||
|
void bridge
|
||||||
|
.installUpdate()
|
||||||
|
.then((result) => {
|
||||||
|
if (!shouldToastDesktopUpdateActionResult(result)) return;
|
||||||
|
const actionError = getDesktopUpdateActionError(result);
|
||||||
|
if (!actionError) return;
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Could not install update",
|
||||||
|
description: actionError,
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
toastManager.add({
|
||||||
|
type: "error",
|
||||||
|
title: "Could not install update",
|
||||||
|
description: error instanceof Error ? error.message : "An unexpected error occurred.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [desktopUpdateButtonAction, desktopUpdateButtonDisabled, desktopUpdateState]);
|
||||||
|
|
||||||
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>
|
||||||
@@ -677,10 +951,29 @@ 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}
|
||||||
|
{showDesktopUpdateButton && (
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger
|
||||||
|
render={
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={desktopUpdateTooltip}
|
||||||
|
aria-disabled={desktopUpdateButtonDisabled || undefined}
|
||||||
|
disabled={desktopUpdateButtonDisabled}
|
||||||
|
className={`inline-flex size-7 ml-auto mt-2 items-center justify-center rounded-md text-muted-foreground transition-colors ${desktopUpdateButtonInteractivityClasses} ${desktopUpdateButtonClasses}`}
|
||||||
|
onClick={handleDesktopUpdateButtonClick}
|
||||||
|
>
|
||||||
|
<RocketIcon className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<TooltipPopup side="bottom">{desktopUpdateTooltip}</TooltipPopup>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
</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">
|
||||||
@@ -692,8 +985,8 @@ export default function Sidebar() {
|
|||||||
<SidebarContent className="gap-0">
|
<SidebarContent className="gap-0">
|
||||||
<SidebarGroup className="px-2 py-2">
|
<SidebarGroup className="px-2 py-2">
|
||||||
<SidebarMenu>
|
<SidebarMenu>
|
||||||
{state.projects.map((project) => {
|
{projects.map((project) => {
|
||||||
const threads = state.threads
|
const visibleThreads = 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();
|
||||||
@@ -708,7 +1001,7 @@ export default function Sidebar() {
|
|||||||
open={project.expanded}
|
open={project.expanded}
|
||||||
onOpenChange={(open) => {
|
onOpenChange={(open) => {
|
||||||
if (open === project.expanded) return;
|
if (open === project.expanded) return;
|
||||||
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
|
toggleProject(project.id);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<SidebarMenuItem>
|
<SidebarMenuItem>
|
||||||
@@ -736,19 +1029,24 @@ export default function Sidebar() {
|
|||||||
<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 prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||||
const terminalStatus = terminalStatusIndicator(thread);
|
const terminalStatus = terminalStatusFromRunningIds(
|
||||||
|
selectThreadTerminalState(terminalStateByThreadId, thread.id)
|
||||||
|
.runningTerminalIds,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarMenuSubItem key={thread.id} className="w-full">
|
<SidebarMenuSubItem key={thread.id} className="w-full">
|
||||||
@@ -756,7 +1054,7 @@ export default function Sidebar() {
|
|||||||
render={<div role="button" tabIndex={0} />}
|
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 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||||
isActive
|
isActive
|
||||||
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
|
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
|
||||||
: "text-muted-foreground"
|
: "text-muted-foreground"
|
||||||
@@ -815,9 +1113,42 @@ export default function Sidebar() {
|
|||||||
<span className="hidden md:inline">{threadStatus.label}</span>
|
<span className="hidden md:inline">{threadStatus.label}</span>
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<span className="min-w-0 flex-1 truncate text-xs">
|
{renamingThreadId === thread.id ? (
|
||||||
{thread.title}
|
<input
|
||||||
</span>
|
ref={(el) => {
|
||||||
|
if (el && renamingInputRef.current !== el) {
|
||||||
|
renamingInputRef.current = el;
|
||||||
|
el.focus();
|
||||||
|
el.select();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
|
||||||
|
value={renamingTitle}
|
||||||
|
onChange={(e) => setRenamingTitle(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
renamingCommittedRef.current = true;
|
||||||
|
void commitRename(thread.id, renamingTitle, thread.title);
|
||||||
|
} else if (e.key === "Escape") {
|
||||||
|
e.preventDefault();
|
||||||
|
renamingCommittedRef.current = true;
|
||||||
|
cancelRename();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onBlur={() => {
|
||||||
|
if (!renamingCommittedRef.current) {
|
||||||
|
void commitRename(thread.id, renamingTitle, thread.title);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span className="min-w-0 flex-1 truncate text-xs">
|
||||||
|
{thread.title}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||||
{terminalStatus && (
|
{terminalStatus && (
|
||||||
@@ -866,7 +1197,7 @@ export default function Sidebar() {
|
|||||||
})}
|
})}
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
|
|
||||||
{state.projects.length === 0 && !addingProject && (
|
{projects.length === 0 && !addingProject && (
|
||||||
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
|
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
|
||||||
No projects yet.
|
No projects yet.
|
||||||
<br />
|
<br />
|
||||||
|
|||||||
@@ -389,6 +389,9 @@ function TerminalViewport({
|
|||||||
fitAddonRef.current = null;
|
fitAddonRef.current = null;
|
||||||
terminal.dispose();
|
terminal.dispose();
|
||||||
};
|
};
|
||||||
|
// autoFocus is intentionally omitted;
|
||||||
|
// it is only read at mount time and must not trigger terminal teardown/recreation.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [cwd, runtimeEnv, terminalId, threadId]);
|
}, [cwd, runtimeEnv, terminalId, threadId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import {
|
||||||
|
getDesktopUpdateActionError,
|
||||||
|
getDesktopUpdateButtonTooltip,
|
||||||
|
isDesktopUpdateButtonDisabled,
|
||||||
|
resolveDesktopUpdateButtonAction,
|
||||||
|
shouldHighlightDesktopUpdateError,
|
||||||
|
shouldShowDesktopUpdateButton,
|
||||||
|
shouldToastDesktopUpdateActionResult,
|
||||||
|
} from "./desktopUpdate.logic";
|
||||||
|
|
||||||
|
const baseState: DesktopUpdateState = {
|
||||||
|
enabled: true,
|
||||||
|
status: "idle",
|
||||||
|
currentVersion: "1.0.0",
|
||||||
|
availableVersion: null,
|
||||||
|
downloadedVersion: null,
|
||||||
|
downloadPercent: null,
|
||||||
|
checkedAt: null,
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("desktop update button state", () => {
|
||||||
|
it("shows a download action when an update is available", () => {
|
||||||
|
const state: DesktopUpdateState = { ...baseState, status: "available", availableVersion: "1.1.0" };
|
||||||
|
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||||
|
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps retry action available after a download error", () => {
|
||||||
|
const state: DesktopUpdateState = {
|
||||||
|
...baseState,
|
||||||
|
status: "error",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
message: "network timeout",
|
||||||
|
errorContext: "download",
|
||||||
|
canRetry: true,
|
||||||
|
};
|
||||||
|
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||||
|
expect(resolveDesktopUpdateButtonAction(state)).toBe("download");
|
||||||
|
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps install action available after an install error", () => {
|
||||||
|
const state: DesktopUpdateState = {
|
||||||
|
...baseState,
|
||||||
|
status: "error",
|
||||||
|
downloadedVersion: "1.1.0",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
message: "shutdown timeout",
|
||||||
|
errorContext: "install",
|
||||||
|
canRetry: true,
|
||||||
|
};
|
||||||
|
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||||
|
expect(resolveDesktopUpdateButtonAction(state)).toBe("install");
|
||||||
|
expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hides the button for non-actionable check errors", () => {
|
||||||
|
const state: DesktopUpdateState = {
|
||||||
|
...baseState,
|
||||||
|
status: "error",
|
||||||
|
message: "network unavailable",
|
||||||
|
errorContext: "check",
|
||||||
|
canRetry: true,
|
||||||
|
};
|
||||||
|
expect(shouldShowDesktopUpdateButton(state)).toBe(false);
|
||||||
|
expect(resolveDesktopUpdateButtonAction(state)).toBe("none");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("disables the button while downloading", () => {
|
||||||
|
const state: DesktopUpdateState = {
|
||||||
|
...baseState,
|
||||||
|
status: "downloading",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
downloadPercent: 42.5,
|
||||||
|
};
|
||||||
|
expect(shouldShowDesktopUpdateButton(state)).toBe(true);
|
||||||
|
expect(isDesktopUpdateButtonDisabled(state)).toBe(true);
|
||||||
|
expect(getDesktopUpdateButtonTooltip(state)).toContain("42%");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getDesktopUpdateActionError", () => {
|
||||||
|
it("returns user-visible message for accepted failed attempts", () => {
|
||||||
|
const result: DesktopUpdateActionResult = {
|
||||||
|
accepted: true,
|
||||||
|
completed: false,
|
||||||
|
state: {
|
||||||
|
...baseState,
|
||||||
|
status: "available",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
message: "checksum mismatch",
|
||||||
|
errorContext: "download",
|
||||||
|
canRetry: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(getDesktopUpdateActionError(result)).toBe("checksum mismatch");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores messages for non-accepted attempts", () => {
|
||||||
|
const result: DesktopUpdateActionResult = {
|
||||||
|
accepted: false,
|
||||||
|
completed: false,
|
||||||
|
state: {
|
||||||
|
...baseState,
|
||||||
|
status: "error",
|
||||||
|
message: "background failure",
|
||||||
|
errorContext: "check",
|
||||||
|
canRetry: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(getDesktopUpdateActionError(result)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores messages for successful attempts", () => {
|
||||||
|
const result: DesktopUpdateActionResult = {
|
||||||
|
accepted: true,
|
||||||
|
completed: true,
|
||||||
|
state: {
|
||||||
|
...baseState,
|
||||||
|
status: "downloaded",
|
||||||
|
downloadedVersion: "1.1.0",
|
||||||
|
availableVersion: "1.1.0",
|
||||||
|
message: null,
|
||||||
|
errorContext: null,
|
||||||
|
canRetry: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(getDesktopUpdateActionError(result)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("desktop update UI helpers", () => {
|
||||||
|
it("toasts only for accepted incomplete actions", () => {
|
||||||
|
expect(
|
||||||
|
shouldToastDesktopUpdateActionResult({
|
||||||
|
accepted: true,
|
||||||
|
completed: false,
|
||||||
|
state: baseState,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
shouldToastDesktopUpdateActionResult({
|
||||||
|
accepted: true,
|
||||||
|
completed: true,
|
||||||
|
state: baseState,
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("highlights only actionable updater errors", () => {
|
||||||
|
expect(
|
||||||
|
shouldHighlightDesktopUpdateError({
|
||||||
|
...baseState,
|
||||||
|
status: "error",
|
||||||
|
errorContext: "download",
|
||||||
|
canRetry: true,
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
shouldHighlightDesktopUpdateError({
|
||||||
|
...baseState,
|
||||||
|
status: "error",
|
||||||
|
errorContext: "check",
|
||||||
|
canRetry: true,
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
export type DesktopUpdateButtonAction = "download" | "install" | "none";
|
||||||
|
|
||||||
|
export function resolveDesktopUpdateButtonAction(
|
||||||
|
state: DesktopUpdateState,
|
||||||
|
): DesktopUpdateButtonAction {
|
||||||
|
if (state.status === "available") {
|
||||||
|
return "download";
|
||||||
|
}
|
||||||
|
if (state.status === "downloaded") {
|
||||||
|
return "install";
|
||||||
|
}
|
||||||
|
if (state.status === "error") {
|
||||||
|
if (state.errorContext === "install" && state.downloadedVersion) {
|
||||||
|
return "install";
|
||||||
|
}
|
||||||
|
if (state.errorContext === "download" && state.availableVersion) {
|
||||||
|
return "download";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldShowDesktopUpdateButton(state: DesktopUpdateState | null): boolean {
|
||||||
|
if (!state || !state.enabled) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (state.status === "downloading") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return resolveDesktopUpdateButtonAction(state) !== "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDesktopUpdateButtonDisabled(state: DesktopUpdateState | null): boolean {
|
||||||
|
return state?.status === "downloading";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {
|
||||||
|
if (state.status === "available") {
|
||||||
|
return `Update ${state.availableVersion ?? "available"} ready to download`;
|
||||||
|
}
|
||||||
|
if (state.status === "downloading") {
|
||||||
|
const progress =
|
||||||
|
typeof state.downloadPercent === "number" ? ` (${Math.floor(state.downloadPercent)}%)` : "";
|
||||||
|
return `Downloading update${progress}`;
|
||||||
|
}
|
||||||
|
if (state.status === "downloaded") {
|
||||||
|
return `Update ${state.downloadedVersion ?? state.availableVersion ?? "ready"} downloaded. Click to restart and install.`;
|
||||||
|
}
|
||||||
|
if (state.status === "error") {
|
||||||
|
if (state.errorContext === "download" && state.availableVersion) {
|
||||||
|
return `Download failed for ${state.availableVersion}. Click to retry.`;
|
||||||
|
}
|
||||||
|
if (state.errorContext === "install" && state.downloadedVersion) {
|
||||||
|
return `Install failed for ${state.downloadedVersion}. Click to retry.`;
|
||||||
|
}
|
||||||
|
return state.message ?? "Update failed";
|
||||||
|
}
|
||||||
|
return "Update available";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {
|
||||||
|
if (!result.accepted || result.completed) return null;
|
||||||
|
if (typeof result.state.message !== "string") return null;
|
||||||
|
const message = result.state.message.trim();
|
||||||
|
return message.length > 0 ? message : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean {
|
||||||
|
return result.accepted && !result.completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | null): boolean {
|
||||||
|
if (!state || state.status !== "error") return false;
|
||||||
|
return state.errorContext === "download" || state.errorContext === "install";
|
||||||
|
}
|
||||||
@@ -20,10 +20,9 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
|
|||||||
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
|
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
|
||||||
) {
|
) {
|
||||||
const chipsRef = React.useRef<Element | null>(null);
|
const chipsRef = React.useRef<Element | null>(null);
|
||||||
|
const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
|
||||||
return (
|
return (
|
||||||
<ComboboxContext.Provider
|
<ComboboxContext.Provider value={value}>
|
||||||
value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
|
|
||||||
>
|
|
||||||
<ComboboxPrimitive.Root {...props} />
|
<ComboboxPrimitive.Root {...props} />
|
||||||
</ComboboxContext.Provider>
|
</ComboboxContext.Provider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ function ToggleGroup({
|
|||||||
children,
|
children,
|
||||||
...props
|
...props
|
||||||
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
|
||||||
|
const value = React.useMemo(() => ({ size, variant }), [size, variant]);
|
||||||
return (
|
return (
|
||||||
<ToggleGroupPrimitive
|
<ToggleGroupPrimitive
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -42,11 +43,7 @@ function ToggleGroup({
|
|||||||
orientation={orientation}
|
orientation={orientation}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ToggleGroupContext.Provider
|
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
|
||||||
value={React.useMemo(() => ({ size, variant }), [size, variant])}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</ToggleGroupContext.Provider>
|
|
||||||
</ToggleGroupPrimitive>
|
</ToggleGroupPrimitive>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||||
|
|
||||||
|
describe("splitPromptIntoComposerSegments", () => {
|
||||||
|
it("splits mention tokens followed by whitespace into mention segments", () => {
|
||||||
|
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md please")).toEqual([
|
||||||
|
{ type: "text", text: "Inspect " },
|
||||||
|
{ type: "mention", path: "AGENTS.md" },
|
||||||
|
{ type: "text", text: " please" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not convert an incomplete trailing mention token", () => {
|
||||||
|
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md")).toEqual([
|
||||||
|
{ type: "text", text: "Inspect @AGENTS.md" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps newlines around mention tokens", () => {
|
||||||
|
expect(splitPromptIntoComposerSegments("one\n@src/index.ts \ntwo")).toEqual([
|
||||||
|
{ type: "text", text: "one\n" },
|
||||||
|
{ type: "mention", path: "src/index.ts" },
|
||||||
|
{ type: "text", text: " \ntwo" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
export type ComposerPromptSegment =
|
||||||
|
| {
|
||||||
|
type: "text";
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
type: "mention";
|
||||||
|
path: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
|
||||||
|
|
||||||
|
function pushTextSegment(segments: ComposerPromptSegment[], text: string): void {
|
||||||
|
if (!text) return;
|
||||||
|
const last = segments[segments.length - 1];
|
||||||
|
if (last && last.type === "text") {
|
||||||
|
last.text += text;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
segments.push({ type: "text", text });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
|
||||||
|
const segments: ComposerPromptSegment[] = [];
|
||||||
|
if (!prompt) {
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
|
let cursor = 0;
|
||||||
|
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
|
||||||
|
const fullMatch = match[0];
|
||||||
|
const prefix = match[1] ?? "";
|
||||||
|
const path = match[2] ?? "";
|
||||||
|
const matchIndex = match.index ?? 0;
|
||||||
|
const mentionStart = matchIndex + prefix.length;
|
||||||
|
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
|
||||||
|
|
||||||
|
if (mentionStart > cursor) {
|
||||||
|
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (path.length > 0) {
|
||||||
|
segments.push({ type: "mention", path });
|
||||||
|
} else {
|
||||||
|
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = mentionEnd;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cursor < prompt.length) {
|
||||||
|
pushTextSegment(segments, prompt.slice(cursor));
|
||||||
|
}
|
||||||
|
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
|
import {
|
||||||
|
detectComposerTrigger,
|
||||||
|
expandCollapsedComposerCursor,
|
||||||
|
replaceTextRange,
|
||||||
|
} from "./composer-logic";
|
||||||
|
|
||||||
describe("detectComposerTrigger", () => {
|
describe("detectComposerTrigger", () => {
|
||||||
it("detects @path trigger at cursor", () => {
|
it("detects @path trigger at cursor", () => {
|
||||||
@@ -49,3 +53,27 @@ describe("replaceTextRange", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("expandCollapsedComposerCursor", () => {
|
||||||
|
it("keeps cursor unchanged when no mention segment is present", () => {
|
||||||
|
expect(expandCollapsedComposerCursor("plain text", 5)).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps collapsed mention cursor to expanded text cursor", () => {
|
||||||
|
const text = "what's in my @AGENTS.md fsfdas";
|
||||||
|
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||||
|
const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
|
||||||
|
|
||||||
|
expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
|
||||||
|
expandedCursorAfterMention,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows path trigger detection to close after selecting a mention", () => {
|
||||||
|
const text = "what's in my @AGENTS.md ";
|
||||||
|
const collapsedCursorAfterMention = "what's in my ".length + 2;
|
||||||
|
const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
|
||||||
|
|
||||||
|
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
|
||||||
|
|
||||||
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
|
||||||
|
|
||||||
export interface ComposerTrigger {
|
export interface ComposerTrigger {
|
||||||
@@ -24,6 +26,38 @@ function tokenStartForCursor(text: string, cursor: number): number {
|
|||||||
return index + 1;
|
return index + 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function expandCollapsedComposerCursor(text: string, cursorInput: number): number {
|
||||||
|
const collapsedCursor = clampCursor(text, cursorInput);
|
||||||
|
const segments = splitPromptIntoComposerSegments(text);
|
||||||
|
if (segments.length === 0) {
|
||||||
|
return collapsedCursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
let remaining = collapsedCursor;
|
||||||
|
let expandedCursor = 0;
|
||||||
|
|
||||||
|
for (const segment of segments) {
|
||||||
|
if (segment.type === "mention") {
|
||||||
|
const expandedLength = segment.path.length + 1;
|
||||||
|
if (remaining <= 1) {
|
||||||
|
return expandedCursor + (remaining === 0 ? 0 : expandedLength);
|
||||||
|
}
|
||||||
|
remaining -= 1;
|
||||||
|
expandedCursor += expandedLength;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const segmentLength = segment.text.length;
|
||||||
|
if (remaining <= segmentLength) {
|
||||||
|
return expandedCursor + remaining;
|
||||||
|
}
|
||||||
|
remaining -= segmentLength;
|
||||||
|
expandedCursor += segmentLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
return expandedCursor;
|
||||||
|
}
|
||||||
|
|
||||||
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
|
||||||
const cursor = clampCursor(text, cursorInput);
|
const cursor = clampCursor(text, cursorInput);
|
||||||
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
|
||||||
|
|||||||
@@ -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,10 +1,12 @@
|
|||||||
|
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Imperative DOM-based context menu for non-Electron environments.
|
* Imperative DOM-based context menu for non-Electron environments.
|
||||||
* Shows a positioned dropdown and returns a promise that resolves
|
* Shows a positioned dropdown and returns a promise that resolves
|
||||||
* with the clicked item id, or null if dismissed.
|
* with the clicked item id, or null if dismissed.
|
||||||
*/
|
*/
|
||||||
export function showContextMenuFallback<T extends string>(
|
export function showContextMenuFallback<T extends string>(
|
||||||
items: readonly { id: T; label: string }[],
|
items: readonly ContextMenuItem<T>[],
|
||||||
position?: { x: number; y: number },
|
position?: { x: number; y: number },
|
||||||
): Promise<T | null> {
|
): Promise<T | null> {
|
||||||
return new Promise<T | null>((resolve) => {
|
return new Promise<T | null>((resolve) => {
|
||||||
@@ -41,8 +43,8 @@ export function showContextMenuFallback<T extends string>(
|
|||||||
const btn = document.createElement("button");
|
const btn = document.createElement("button");
|
||||||
btn.type = "button";
|
btn.type = "button";
|
||||||
btn.textContent = item.label;
|
btn.textContent = item.label;
|
||||||
const isDeleteAction = item.id === "delete";
|
const isDestructiveAction = item.destructive === true || item.id === "delete";
|
||||||
btn.className = isDeleteAction
|
btn.className = isDestructiveAction
|
||||||
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
|
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
|
||||||
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
|
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
|
||||||
btn.addEventListener("click", () => cleanup(item.id));
|
btn.addEventListener("click", () => cleanup(item.id));
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ export const gitQueryKeys = {
|
|||||||
export const gitMutationKeys = {
|
export const gitMutationKeys = {
|
||||||
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
init: (cwd: string | null) => ["git", "mutation", "init", cwd] as const,
|
||||||
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
checkout: (cwd: string | null) => ["git", "mutation", "checkout", cwd] as const,
|
||||||
createBranchAndCheckout: (cwd: string | null) =>
|
|
||||||
["git", "mutation", "create-branch-and-checkout", cwd] as const,
|
|
||||||
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
runStackedAction: (cwd: string | null) => ["git", "mutation", "run-stacked-action", cwd] as const,
|
||||||
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
pull: (cwd: string | null) => ["git", "mutation", "pull", cwd] as const,
|
||||||
};
|
};
|
||||||
@@ -89,24 +87,6 @@ export function gitCheckoutMutationOptions(input: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function gitCreateBranchAndCheckoutMutationOptions(input: {
|
|
||||||
cwd: string | null;
|
|
||||||
queryClient: QueryClient;
|
|
||||||
}) {
|
|
||||||
return mutationOptions({
|
|
||||||
mutationKey: gitMutationKeys.createBranchAndCheckout(input.cwd),
|
|
||||||
mutationFn: async (branch: string) => {
|
|
||||||
const api = ensureNativeApi();
|
|
||||||
if (!input.cwd) throw new Error("Git branch creation is unavailable.");
|
|
||||||
await api.git.createBranch({ cwd: input.cwd, branch });
|
|
||||||
return api.git.checkout({ cwd: input.cwd, branch });
|
|
||||||
},
|
|
||||||
onSuccess: async () => {
|
|
||||||
await invalidateGitQueries(input.queryClient);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gitRunStackedActionMutationOptions(input: {
|
export function gitRunStackedActionMutationOptions(input: {
|
||||||
cwd: string | null;
|
cwd: string | null;
|
||||||
queryClient: QueryClient;
|
queryClient: QueryClient;
|
||||||
@@ -116,9 +96,11 @@ export function gitRunStackedActionMutationOptions(input: {
|
|||||||
mutationFn: async ({
|
mutationFn: async ({
|
||||||
action,
|
action,
|
||||||
commitMessage,
|
commitMessage,
|
||||||
|
featureBranch,
|
||||||
}: {
|
}: {
|
||||||
action: GitStackedAction;
|
action: GitStackedAction;
|
||||||
commitMessage?: string;
|
commitMessage?: string;
|
||||||
|
featureBranch?: boolean;
|
||||||
}) => {
|
}) => {
|
||||||
const api = ensureNativeApi();
|
const api = ensureNativeApi();
|
||||||
if (!input.cwd) throw new Error("Git action is unavailable.");
|
if (!input.cwd) throw new Error("Git action is unavailable.");
|
||||||
@@ -126,6 +108,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
|||||||
cwd: input.cwd,
|
cwd: input.cwd,
|
||||||
action,
|
action,
|
||||||
...(commitMessage ? { commitMessage } : {}),
|
...(commitMessage ? { commitMessage } : {}),
|
||||||
|
...(featureBranch ? { featureBranch } : {}),
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onSettled: async () => {
|
onSettled: async () => {
|
||||||
|
|||||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user