Compare commits
75
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e99b8efdc | ||
|
|
4b4e3b1836 | ||
|
|
822d8dfc17 | ||
|
|
7c0b8bee70 | ||
|
|
39fd14b73e | ||
|
|
bd43372053 | ||
|
|
123eb96c52 | ||
|
|
ec18318e3c | ||
|
|
5a904fc8cc | ||
|
|
a74511e765 | ||
|
|
ac39b6fe05 | ||
|
|
696cbcc7fd | ||
|
|
3a5a14c6ed | ||
|
|
cadef14a84 | ||
|
|
10660f376c | ||
|
|
ae235f7155 | ||
|
|
a356cd0d0f | ||
|
|
58b932ffb8 | ||
|
|
d58af33fba | ||
|
|
a56418f8bc | ||
|
|
596e1590df | ||
|
|
70c9147c7f | ||
|
|
c0054cb56f | ||
|
|
41734dfbbf | ||
|
|
8f42d34db9 | ||
|
|
70857ce299 | ||
|
|
5e0ec38383 | ||
|
|
913d0409f6 | ||
|
|
ac0e720de1 | ||
|
|
5144d32b77 | ||
|
|
128cc21516 | ||
|
|
215ff36362 | ||
|
|
505b4d0bc3 | ||
|
|
343c0a9472 | ||
|
|
82681606d0 | ||
|
|
c91b79b6e2 | ||
|
|
5e55aa387f | ||
|
|
a21095bc9a | ||
|
|
ba03241df3 | ||
|
|
a8059dc2c0 | ||
|
|
be873bca3e | ||
|
|
e8bde958f1 | ||
|
|
95f21c1099 | ||
|
|
8cd92150b1 | ||
|
|
d0ab35931e | ||
|
|
882684a80c | ||
|
|
96efd1cef0 | ||
|
|
c8974ede6d | ||
|
|
0c637e3d5e | ||
|
|
0e2d50a620 | ||
|
|
f3b3c54859 | ||
|
|
02eca40c3b | ||
|
|
c6ee3aee9f | ||
|
|
586e0ecea9 | ||
|
|
dcd18413a2 | ||
|
|
73f296b4cf | ||
|
|
1419bf3989 | ||
|
|
dca85c402c | ||
|
|
56a3ad0f8b | ||
|
|
36f484c25a | ||
|
|
03c6685097 | ||
|
|
23afddfbf9 | ||
|
|
e3a2dfb9d0 | ||
|
|
3dd004c323 | ||
|
|
1af43dbf90 | ||
|
|
16fed12dcc | ||
|
|
29825f2f8a | ||
|
|
efcee4b863 | ||
|
|
26edcab8b4 | ||
|
|
c626892adf | ||
|
|
3c66cdf2fe | ||
|
|
db31c36213 | ||
|
|
cafe3352f1 | ||
|
|
7a39ce34fa | ||
|
|
483702df77 |
No files matched your search
@@ -0,0 +1,309 @@
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
ref: ${{ steps.release_ref.outputs.value }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${{ github.event.inputs.version }}"
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Update version strings
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
}
|
||||
'
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: bun install
|
||||
|
||||
- name: 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
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: bun run typecheck
|
||||
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: macos-14
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: macos-15-intel
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: ubuntu-24.04
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
CSC_LINK: ${{ secrets.CSC_LINK }}
|
||||
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
|
||||
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
|
||||
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
|
||||
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
|
||||
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
|
||||
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
|
||||
run: |
|
||||
args=(
|
||||
--platform "${{ matrix.platform }}"
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
)
|
||||
|
||||
has_all() {
|
||||
for value in "$@"; do
|
||||
if [[ -z "$value" ]]; then
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" ]]; then
|
||||
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
|
||||
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
|
||||
printf '%s' "$APPLE_API_KEY" > "$key_path"
|
||||
export APPLE_API_KEY="$key_path"
|
||||
echo "macOS signing enabled."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "macOS signing disabled (missing one or more Apple signing secrets)."
|
||||
fi
|
||||
elif [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
if has_all \
|
||||
"$AZURE_TENANT_ID" \
|
||||
"$AZURE_CLIENT_ID" \
|
||||
"$AZURE_CLIENT_SECRET" \
|
||||
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
|
||||
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
|
||||
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
|
||||
echo "Windows signing enabled (Azure Trusted Signing)."
|
||||
args+=(--signed)
|
||||
else
|
||||
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
|
||||
fi
|
||||
else
|
||||
echo "Signing disabled for ${{ matrix.platform }}."
|
||||
fi
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release/*
|
||||
if-no-files-found: error
|
||||
|
||||
# publish_cli:
|
||||
# name: Publish CLI to npm
|
||||
# needs: [preflight, build]
|
||||
# runs-on: ubuntu-24.04
|
||||
# steps:
|
||||
# - name: Checkout
|
||||
# uses: actions/checkout@v4
|
||||
|
||||
# - name: Setup Bun
|
||||
# uses: oven-sh/setup-bun@v2
|
||||
# with:
|
||||
# bun-version-file: package.json
|
||||
|
||||
# - name: Setup Node
|
||||
# uses: actions/setup-node@v4
|
||||
# with:
|
||||
# node-version-file: package.json
|
||||
# registry-url: https://registry.npmjs.org
|
||||
|
||||
# - name: Install dependencies
|
||||
# run: bun install --frozen-lockfile
|
||||
|
||||
# - name: Set CLI package version from release tag
|
||||
# env:
|
||||
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
# run: |
|
||||
# node --input-type=module -e '
|
||||
# import { readFileSync, writeFileSync } from "node:fs";
|
||||
# const packagePath = "apps/server/package.json";
|
||||
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
|
||||
# packageJson.version = process.env.RELEASE_VERSION;
|
||||
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
# '
|
||||
|
||||
# - name: Build CLI package
|
||||
# run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
# - name: Publish CLI package
|
||||
# run: bun --cwd apps/server publish --access public
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build]
|
||||
# needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: desktop-*
|
||||
merge-multiple: true
|
||||
path: release-assets
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
files: release-assets/*
|
||||
fail_on_unmatched_files: true
|
||||
@@ -1,5 +1,9 @@
|
||||
# CLAUDE.md
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
|
||||
@@ -18,7 +22,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
|
||||
@@ -75,8 +75,11 @@ npx t3
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
@@ -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.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
@@ -122,3 +131,6 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -23,6 +23,8 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/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 { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
@@ -54,6 +56,7 @@ import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { ServerConfig } from "../src/config.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -227,8 +230,17 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
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(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
@@ -240,6 +252,7 @@ export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -191,10 +191,7 @@ describe("sendTurn", () => {
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "error.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
dataUrl: "data:image/png;base64,AAAA",
|
||||
url: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3",
|
||||
@@ -242,10 +239,7 @@ describe("sendTurn", () => {
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 256,
|
||||
dataUrl: "data:image/png;base64,BBBB",
|
||||
url: "data:image/png;base64,BBBB",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
normalizeModelSlug,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
@@ -71,6 +70,14 @@ interface JsonRpcNotification {
|
||||
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 {
|
||||
id: ProviderTurnId;
|
||||
items: unknown[];
|
||||
@@ -290,7 +297,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
}
|
||||
|
||||
async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const context = this.requireSession(input.sessionId);
|
||||
if (!context.session.threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
@@ -310,7 +317,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
if (attachment.type === "image") {
|
||||
turnInput.push({
|
||||
type: "image",
|
||||
url: attachment.dataUrl,
|
||||
url: attachment.url,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,29 @@ export interface ServerConfigShape {
|
||||
*/
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {}
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, statedir: string) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
return {
|
||||
cwd,
|
||||
stateDir: statedir,
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
|
||||
@@ -3,10 +3,17 @@ import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "../Errors.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) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
@@ -21,13 +28,36 @@ function makeFakeCodexBinary(dir: string) {
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
"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',
|
||||
" shift",
|
||||
' output_path="$1"',
|
||||
" fi",
|
||||
" shift",
|
||||
"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',
|
||||
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
|
||||
"fi",
|
||||
@@ -48,6 +78,9 @@ function withFakeCodexEnv<A, E, R>(
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
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 previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
|
||||
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(() => {
|
||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||
@@ -76,6 +112,24 @@ function withFakeCodexEnv<A, E, R>(
|
||||
} else {
|
||||
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 {
|
||||
@@ -83,6 +137,9 @@ function withFakeCodexEnv<A, E, R>(
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
}),
|
||||
() => effect,
|
||||
@@ -107,14 +164,29 @@ function withFakeCodexEnv<A, E, R>(
|
||||
} else {
|
||||
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(
|
||||
CodexTextGenerationLive,
|
||||
NodeServices.layer,
|
||||
);
|
||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages", () =>
|
||||
@@ -170,6 +242,216 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates branch names and normalizes branch fragments", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: " Feat/Session ",
|
||||
}),
|
||||
stdinMustNotContain: "Image attachments supplied to the model",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Please update session handling.",
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("feat/session");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("omits attachment metadata section when no attachments are provided", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/session-timeout",
|
||||
}),
|
||||
stdinMustNotContain: "Attachment metadata:",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix timeout behavior.",
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/session-timeout");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("passes image attachments through as codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
stdinMustContain: "Attachment metadata:",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const attachmentId =
|
||||
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
|
||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() =>
|
||||
fs.stat(imagePath).pipe(
|
||||
Effect.map((fileInfo) => {
|
||||
expect(fileInfo.type).toBe("File");
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.ensuring(
|
||||
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
|
||||
),
|
||||
);
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores missing attachment ids for codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
|
||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: missingAttachmentId,
|
||||
name: "outside.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("missing --image input");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"fails with typed TextGenerationError when codex returns wrong branch payload shape",
|
||||
() =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
title: "This is not a branch payload",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix websocket reconnect flake",
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns typed TextGenerationError when codex exits non-zero", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
|
||||
@@ -3,8 +3,12 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
import {
|
||||
type BranchNameGenerationInput,
|
||||
type BranchNameGenerationResult,
|
||||
type CommitMessageGenerationResult,
|
||||
type PrContentGenerationResult,
|
||||
type TextGenerationShape,
|
||||
@@ -15,26 +19,6 @@ const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
|
||||
const COMMIT_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
subject: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["subject", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const PR_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["title", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
function normalizeCodexError(
|
||||
operation: string,
|
||||
error: unknown,
|
||||
@@ -71,32 +55,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 {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
@@ -124,10 +82,33 @@ function sanitizePrTitle(raw: string): string {
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
function sanitizeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"`]/g, "")
|
||||
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
||||
|
||||
const branchFragment = normalized
|
||||
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||
.slice(0, 64)
|
||||
.replace(/[./_-]+$/g, "");
|
||||
|
||||
return branchFragment.length > 0 ? branchFragment : "update";
|
||||
}
|
||||
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
|
||||
type MaterializedImageAttachments = {
|
||||
readonly imagePaths: ReadonlyArray<string>;
|
||||
};
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
@@ -171,24 +152,59 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
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,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
parse,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent";
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: object;
|
||||
parse: (raw: unknown) => T;
|
||||
}): Effect.Effect<T, TextGenerationError> =>
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(outputSchemaJson),
|
||||
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
@@ -208,6 +224,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
@@ -254,9 +271,12 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all([safeUnlink(schemaPath), safeUnlink(outputPath)], {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.asVoid);
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
@@ -273,7 +293,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const rawOutput = yield* fileSystem.readFileString(outputPath).pipe(
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
@@ -282,30 +302,17 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
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));
|
||||
});
|
||||
|
||||
@@ -331,8 +338,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parseCommitOutput(raw),
|
||||
outputSchemaJson: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -371,8 +380,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parsePrOutput(raw),
|
||||
outputSchemaJson: Schema.Struct({
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -384,9 +395,55 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
);
|
||||
};
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||
return Effect.gen(function* () {
|
||||
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) =>
|
||||
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
);
|
||||
|
||||
const promptSections = [
|
||||
"You generate concise git branch names.",
|
||||
"Return a JSON object with key: branch.",
|
||||
"Rules:",
|
||||
"- Branch should describe the requested work from the user message.",
|
||||
"- Keep it short and specific (2-6 words).",
|
||||
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
|
||||
"- If images are attached, use them as primary context for visual/UI issues.",
|
||||
"",
|
||||
"User message:",
|
||||
limitSection(input.message, 8_000),
|
||||
];
|
||||
if (attachmentLines.length > 0) {
|
||||
promptSections.push(
|
||||
"",
|
||||
"Attachment metadata:",
|
||||
limitSection(attachmentLines.join("\n"), 4_000),
|
||||
);
|
||||
}
|
||||
const prompt = promptSections.join("\n");
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchName(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -106,6 +106,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
||||
listBranches: (input) => core.listBranches(input),
|
||||
createWorktree: (input) => core.createWorktree(input),
|
||||
removeWorktree: (input) => core.removeWorktree(input),
|
||||
renameBranch: (input) => core.renameBranch(input),
|
||||
createBranch: (input) => core.createBranch(input),
|
||||
checkoutBranch: (input) => core.checkoutBranch(input),
|
||||
initRepo: (input) => core.initRepo(input),
|
||||
@@ -154,6 +155,13 @@ function removeGitWorktree(input: Parameters<GitCoreShape["removeWorktree"]>[0])
|
||||
});
|
||||
}
|
||||
|
||||
function renameGitBranch(input: Parameters<GitCoreShape["renameBranch"]>[0]) {
|
||||
return Effect.gen(function* () {
|
||||
const core = yield* GitCore;
|
||||
return yield* core.renameBranch(input);
|
||||
});
|
||||
}
|
||||
|
||||
function pullGitBranch({ cwd }: { cwd: string }) {
|
||||
return Effect.gen(function* () {
|
||||
const core = yield* GitCore;
|
||||
@@ -266,6 +274,18 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
|
||||
expect(result.branches.some((branch) => branch.current)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -370,6 +390,82 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists local branches first and remote branches last", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
|
||||
|
||||
const remoteOnlyBranch = "feature/remote-only";
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
|
||||
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
|
||||
|
||||
expect(firstRemoteIndex).toBeGreaterThan(0);
|
||||
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.branches.some(
|
||||
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remoteName = "my-org/upstream";
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
yield* git(tmp, ["remote", "add", remoteName, remote]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
const remoteOnlyBranch = "feature/remote-with-remote-name";
|
||||
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
const remoteBranch = result.branches.find(
|
||||
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
|
||||
);
|
||||
|
||||
expect(remoteBranch).toBeDefined();
|
||||
expect(remoteBranch?.isRemote).toBe(true);
|
||||
expect(remoteBranch?.remoteName).toBe(remoteName);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -592,6 +688,87 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"does not silently checkout a local branch when a remote ref no longer exists",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
yield* createGitBranch({ cwd: source, branch: "feature" });
|
||||
|
||||
const checkoutResult = yield* Effect.result(
|
||||
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
|
||||
);
|
||||
expect(checkoutResult._tag).toBe("Failure");
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", remoteName, remote]);
|
||||
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["push", "-u", remoteName, featureBranch]);
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
yield* git(source, ["branch", "-D", featureBranch]);
|
||||
|
||||
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
|
||||
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to detached checkout when --track would conflict with an existing local branch",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
// Keep local branch but remove tracking so `--track origin/<branch>`
|
||||
// would attempt to create an already-existing local branch.
|
||||
yield* git(source, ["branch", "--unset-upstream"]);
|
||||
|
||||
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
|
||||
|
||||
const core = yield* GitCore;
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when checkout would overwrite uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -650,6 +827,129 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
);
|
||||
});
|
||||
|
||||
// ── renameGitBranch ──
|
||||
|
||||
describe("renameGitBranch", () => {
|
||||
it.effect("renames the current branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||
|
||||
const renamed = yield* renameGitBranch({
|
||||
cwd: tmp,
|
||||
oldBranch: "feature/old-name",
|
||||
newBranch: "feature/new-name",
|
||||
});
|
||||
|
||||
expect(renamed.branch).toBe("feature/new-name");
|
||||
|
||||
const branches = yield* listGitBranches({ cwd: tmp });
|
||||
expect(branches.branches.some((branch) => branch.name === "feature/old-name")).toBe(false);
|
||||
const current = branches.branches.find((branch) => branch.current);
|
||||
expect(current?.name).toBe("feature/new-name");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns success without git invocation when old/new names match", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const current = (yield* listGitBranches({ cwd: tmp })).branches.find((b) => b.current)!;
|
||||
|
||||
const renamed = yield* renameGitBranch({
|
||||
cwd: tmp,
|
||||
oldBranch: current.name,
|
||||
newBranch: current.name,
|
||||
});
|
||||
|
||||
expect(renamed.branch).toBe(current.name);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("appends numeric suffix when target branch already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
|
||||
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||
|
||||
const renamed = yield* renameGitBranch({
|
||||
cwd: tmp,
|
||||
oldBranch: "t3code/tmp-working",
|
||||
newBranch: "t3code/feat/session",
|
||||
});
|
||||
|
||||
expect(renamed.branch).toBe("t3code/feat/session-1");
|
||||
const branches = yield* listGitBranches({ cwd: tmp });
|
||||
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(branches.branches.some((branch) => branch.name === "t3code/feat/session-1")).toBe(
|
||||
true,
|
||||
);
|
||||
const current = branches.branches.find((branch) => branch.current);
|
||||
expect(current?.name).toBe("t3code/feat/session-1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("increments suffix until it finds an available branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session" });
|
||||
yield* createGitBranch({ cwd: tmp, branch: "t3code/feat/session-1" });
|
||||
yield* createGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: "t3code/tmp-working" });
|
||||
|
||||
const renamed = yield* renameGitBranch({
|
||||
cwd: tmp,
|
||||
oldBranch: "t3code/tmp-working",
|
||||
newBranch: "t3code/feat/session",
|
||||
});
|
||||
|
||||
expect(renamed.branch).toBe("t3code/feat/session-2");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses '--' separator for branch rename arguments", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* createGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: "feature/old-name" });
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let renameArgs: ReadonlyArray<string> | null = null;
|
||||
const core = yield* makeIsolatedGitCore({
|
||||
execute: (input) => {
|
||||
if (input.args[0] === "branch" && input.args[1] === "-m") {
|
||||
renameArgs = [...input.args];
|
||||
}
|
||||
return realGitService.execute(input);
|
||||
},
|
||||
});
|
||||
|
||||
const renamed = yield* core.renameBranch({
|
||||
cwd: tmp,
|
||||
oldBranch: "feature/old-name",
|
||||
newBranch: "feature/new-name",
|
||||
});
|
||||
|
||||
expect(renamed.branch).toBe("feature/new-name");
|
||||
expect(renameArgs).toEqual([
|
||||
"branch",
|
||||
"-m",
|
||||
"--",
|
||||
"feature/old-name",
|
||||
"feature/new-name",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── createGitWorktree + removeGitWorktree ──
|
||||
|
||||
describe("createGitWorktree", () => {
|
||||
@@ -1282,5 +1582,54 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(didFailRecency).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let didFailRemoteBranches = false;
|
||||
let didFailRemoteNames = false;
|
||||
const core = yield* makeIsolatedGitCore({
|
||||
execute: (input) => {
|
||||
if (input.args.join(" ") === "branch --no-color --remotes") {
|
||||
didFailRemoteBranches = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: "git.test.listBranchesRemoteBranches",
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "remote unavailable",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.args.join(" ") === "remote") {
|
||||
didFailRemoteNames = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: "git.test.listBranchesRemoteNames",
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "remote unavailable",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return realGitService.execute(input);
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* core.listBranches({ cwd: tmp });
|
||||
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThan(0);
|
||||
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
|
||||
expect(didFailRemoteBranches).toBe(true);
|
||||
expect(didFailRemoteNames).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -77,6 +77,87 @@ function parsePorcelainPath(line: string): string | null {
|
||||
return filePath.length > 0 ? filePath : null;
|
||||
}
|
||||
|
||||
function parseBranchLine(line: string): { name: string; current: boolean } | null {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const name = trimmed.replace(/^[*+]\s+/, "");
|
||||
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
|
||||
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
|
||||
if (name.includes(" -> ") || name.startsWith("(")) return null;
|
||||
|
||||
return {
|
||||
name,
|
||||
current: trimmed.startsWith("* "),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.toSorted((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
function parseRemoteRefWithRemoteNames(
|
||||
branchName: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { remoteRef: string; remoteName: string; localBranch: string } | null {
|
||||
const trimmedBranchName = branchName.trim();
|
||||
if (trimmedBranchName.length === 0) return null;
|
||||
|
||||
for (const remoteName of remoteNames) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (!trimmedBranchName.startsWith(remotePrefix)) {
|
||||
continue;
|
||||
}
|
||||
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
|
||||
if (localBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
remoteRef: trimmedBranchName,
|
||||
remoteName,
|
||||
localBranch,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(
|
||||
stdout: string,
|
||||
upstreamRef: string,
|
||||
): string | null {
|
||||
for (const line of stdout.split("\n")) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
|
||||
const branchName = branchNameRaw?.trim() ?? "";
|
||||
const upstreamBranch = upstreamBranchRaw.trim();
|
||||
if (branchName.length === 0 || upstreamBranch.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (upstreamBranch === upstreamRef) {
|
||||
return branchName;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
|
||||
const separatorIndex = branchName.indexOf("/");
|
||||
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
|
||||
return null;
|
||||
}
|
||||
const localBranch = branchName.slice(separatorIndex + 1).trim();
|
||||
return localBranch.length > 0 ? localBranch : null;
|
||||
}
|
||||
|
||||
function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
@@ -169,6 +250,43 @@ const makeGitCore = Effect.gen(function* () {
|
||||
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 = (
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
@@ -282,11 +400,6 @@ const makeGitCore = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
executeGit("GitCore.branchExists", cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
|
||||
allowNonZeroExit: true,
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const remoteBranchExists = (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
@@ -377,7 +490,12 @@ const makeGitCore = Effect.gen(function* () {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitCore.readBranchRecency",
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
[
|
||||
"for-each-ref",
|
||||
"--format=%(refname:short)%09%(committerdate:unix)",
|
||||
"refs/heads",
|
||||
"refs/remotes",
|
||||
],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -713,7 +831,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
);
|
||||
const result = yield* executeGit(
|
||||
const localBranchResult = yield* executeGit(
|
||||
"GitCore.listBranches.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
@@ -723,8 +841,8 @@ const makeGitCore = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
@@ -736,7 +854,40 @@ const makeGitCore = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const remoteNamesResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteNames",
|
||||
input.cwd,
|
||||
["remote"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
@@ -756,11 +907,25 @@ const makeGitCore = Effect.gen(function* () {
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||
);
|
||||
}
|
||||
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
}
|
||||
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
@@ -785,19 +950,17 @@ const makeGitCore = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const branches = result.stdout
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => ({
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
@@ -809,6 +972,43 @@ const makeGitCore = Effect.gen(function* () {
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: branch.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const branches = [...localBranches, ...remoteBranches];
|
||||
|
||||
return { branches, isRepo: true };
|
||||
});
|
||||
|
||||
@@ -860,6 +1060,26 @@ const makeGitCore = Effect.gen(function* () {
|
||||
);
|
||||
});
|
||||
|
||||
const renameBranch: GitCoreShape["renameBranch"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.oldBranch === input.newBranch) {
|
||||
return { branch: input.newBranch };
|
||||
}
|
||||
const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);
|
||||
|
||||
yield* executeGit(
|
||||
"GitCore.renameBranch",
|
||||
input.cwd,
|
||||
["branch", "-m", "--", input.oldBranch, targetBranch],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch rename failed",
|
||||
},
|
||||
);
|
||||
|
||||
return { branch: targetBranch };
|
||||
});
|
||||
|
||||
const createBranch: GitCoreShape["createBranch"] = (input) =>
|
||||
executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
@@ -868,17 +1088,83 @@ const makeGitCore = Effect.gen(function* () {
|
||||
|
||||
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
|
||||
const [localInputExists, remoteExists] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.checkoutBranch.localInputExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
executeGit(
|
||||
"GitCore.checkoutBranch.remoteExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const localTrackingBranch =
|
||||
remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||
const localTrackedBranchTargetExists =
|
||||
remoteExists && localTrackedBranchCandidate
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
|
||||
const checkoutArgs =
|
||||
localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
// Refresh upstream refs in the background so checkout remains responsive.
|
||||
yield* Effect.sync(() => {
|
||||
void Effect.runPromise(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||
);
|
||||
});
|
||||
yield* Effect.forkDetach(
|
||||
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
|
||||
);
|
||||
});
|
||||
|
||||
const initRepo: GitCoreShape["initRepo"] = (input) =>
|
||||
@@ -899,6 +1185,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
listBranches,
|
||||
createWorktree,
|
||||
removeWorktree,
|
||||
renameBranch,
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
initRepo,
|
||||
|
||||
@@ -41,6 +41,10 @@ interface FakeGitTextGeneration {
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
generateBranchName: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||
}
|
||||
|
||||
function makeTempDir(
|
||||
@@ -110,6 +114,10 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
title: "Add stacked git actions",
|
||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||
}),
|
||||
generateBranchName: () =>
|
||||
Effect.succeed({
|
||||
branch: "update-workflow",
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
|
||||
@@ -136,6 +144,17 @@ function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): T
|
||||
}),
|
||||
),
|
||||
),
|
||||
generateBranchName: (input) =>
|
||||
implementation.generateBranchName(input).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "fake text generation failed",
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,16 @@ export interface GitRangeContext {
|
||||
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.
|
||||
*/
|
||||
@@ -101,7 +111,7 @@ export interface GitCoreShape {
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branches and branch metadata.
|
||||
* List local + remote branches and branch metadata.
|
||||
*/
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
@@ -124,6 +134,13 @@ export interface GitCoreShape {
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import type { TextGenerationError } from "../Errors.ts";
|
||||
|
||||
@@ -37,11 +38,22 @@ export interface PrContentGenerationResult {
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationInput {
|
||||
cwd: string;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationResult {
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult>;
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +73,13 @@ export interface TextGenerationShape {
|
||||
readonly generatePrContent: (
|
||||
input: PrContentGenerationInput,
|
||||
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Generate a concise branch name from a user message.
|
||||
*/
|
||||
readonly generateBranchName: (
|
||||
input: BranchNameGenerationInput,
|
||||
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
|
||||
|
||||
describe("imageMime", () => {
|
||||
it("parses base64 data URL with mime type", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("parses base64 data URL with mime parameters", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects non-base64 data URL", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing mime type", () => {
|
||||
expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull();
|
||||
});
|
||||
|
||||
it("parses base64 data URL with spaces in payload", () => {
|
||||
expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({
|
||||
mimeType: "image/png",
|
||||
base64: "SGVsbG8=",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not read inherited keys from mime extension map", () => {
|
||||
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
|
||||
export const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {
|
||||
"image/avif": ".avif",
|
||||
"image/bmp": ".bmp",
|
||||
"image/gif": ".gif",
|
||||
"image/heic": ".heic",
|
||||
"image/heif": ".heif",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/svg+xml": ".svg",
|
||||
"image/tiff": ".tiff",
|
||||
"image/webp": ".webp",
|
||||
};
|
||||
|
||||
export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".avif",
|
||||
".bmp",
|
||||
".gif",
|
||||
".heic",
|
||||
".heif",
|
||||
".ico",
|
||||
".jpeg",
|
||||
".jpg",
|
||||
".png",
|
||||
".svg",
|
||||
".tiff",
|
||||
".webp",
|
||||
]);
|
||||
|
||||
export function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const headerParts = (match[1] ?? "")
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
if (headerParts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
const trailingToken = headerParts.at(-1)?.toLowerCase();
|
||||
if (trailingToken !== "base64") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mimeType = headerParts[0]?.toLowerCase();
|
||||
const base64 = match[2]?.replace(/\s+/g, "");
|
||||
if (!mimeType || !base64) return null;
|
||||
|
||||
return { mimeType, base64 };
|
||||
}
|
||||
|
||||
export function inferImageExtension(input: { mimeType: string; fileName?: string }): string {
|
||||
const key = input.mimeType.toLowerCase();
|
||||
const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)
|
||||
? IMAGE_EXTENSION_BY_MIME_TYPE[key]
|
||||
: undefined;
|
||||
if (fromMime) {
|
||||
return fromMime;
|
||||
}
|
||||
|
||||
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||
if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
|
||||
return fromMimeExtension;
|
||||
}
|
||||
|
||||
const fileName = input.fileName?.trim() ?? "";
|
||||
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||
if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||
return fileNameExtension;
|
||||
}
|
||||
|
||||
return ".bin";
|
||||
}
|
||||
@@ -49,10 +49,21 @@ const testLayer = Layer.mergeAll(
|
||||
const runCli = (
|
||||
args: ReadonlyArray<string>,
|
||||
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
|
||||
) =>
|
||||
Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))),
|
||||
) => {
|
||||
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
|
||||
Effect.provide(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_STATE_DIR: uniqueStateDir,
|
||||
...env,
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
type ProviderServiceShape,
|
||||
} from "../../provider/Services/ProviderService.ts";
|
||||
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
@@ -238,6 +239,7 @@ describe("CheckpointReactor", () => {
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ import {
|
||||
OrchestrationProjectionPipeline,
|
||||
type OrchestrationProjectionPipelineShape,
|
||||
} 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 asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
@@ -37,6 +39,8 @@ async function createOrchestrationSystem() {
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(orchestrationLayer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
@@ -310,6 +314,8 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
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 {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
@@ -39,10 +38,11 @@ import {
|
||||
type OrchestrationProjectionPipelineShape,
|
||||
} from "../Services/ProjectionPipeline.ts";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
IMAGE_EXTENSION_BY_MIME_TYPE,
|
||||
SAFE_IMAGE_FILE_EXTENSIONS,
|
||||
} from "../../projectFaviconRoute.ts";
|
||||
attachmentRelativePath,
|
||||
parseAttachmentIdFromRelativePath,
|
||||
parseThreadSegmentFromAttachmentId,
|
||||
toSafeThreadAttachmentSegment,
|
||||
} from "../../attachmentStore.ts";
|
||||
|
||||
export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
@@ -66,115 +66,16 @@ interface ProjectorDefinition {
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
interface PendingAttachmentWrite {
|
||||
readonly absolutePath: string;
|
||||
readonly bytes: Uint8Array;
|
||||
}
|
||||
|
||||
interface AttachmentSideEffects {
|
||||
readonly writes: Array<PendingAttachmentWrite>;
|
||||
readonly deletedThreadIds: Set<string>;
|
||||
readonly prunedThreadRelativePaths: Map<string, Set<string>>;
|
||||
}
|
||||
|
||||
function toSafeThreadAttachmentSegment(threadId: string): string | null {
|
||||
const segment = encodeURIComponent(threadId);
|
||||
if (
|
||||
segment.length === 0 ||
|
||||
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 },
|
||||
);
|
||||
});
|
||||
const materializeAttachmentsForProjection = Effect.fn(
|
||||
(input: {
|
||||
readonly attachments: ReadonlyArray<ChatAttachment>;
|
||||
}) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
|
||||
);
|
||||
|
||||
function extractActivityRequestId(payload: unknown): ApprovalRequestId | 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(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
@@ -308,41 +197,31 @@ function collectThreadAttachmentRelativePaths(
|
||||
if (!threadSegment) {
|
||||
return new Set();
|
||||
}
|
||||
const threadPrefix = `${threadSegment}/`;
|
||||
const relativePaths = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
const relativePath = toAttachmentRelativePath(attachment.dataUrl);
|
||||
if (!relativePath || !relativePath.startsWith(threadPrefix)) {
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
continue;
|
||||
}
|
||||
const threadRelativePath = relativePath.slice(threadPrefix.length).replace(/^[/\\]+/, "");
|
||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||
continue;
|
||||
}
|
||||
relativePaths.add(threadRelativePath.replace(/\\/g, "/"));
|
||||
relativePaths.add(attachmentRelativePath(attachment));
|
||||
}
|
||||
}
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const runAttachmentSideEffects = Effect.fn(function* (input: {
|
||||
readonly sideEffects: AttachmentSideEffects;
|
||||
readonly fileSystem: FileSystem.FileSystem;
|
||||
readonly path: Path.Path;
|
||||
}) {
|
||||
const serverConfig = yield* Effect.serviceOption(ServerConfig);
|
||||
if (Option.isNone(serverConfig)) {
|
||||
return;
|
||||
}
|
||||
const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) {
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
|
||||
const path = yield* Effect.service(Path.Path);
|
||||
|
||||
const attachmentsRootDir = input.path.join(serverConfig.value.stateDir, "attachments");
|
||||
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.sideEffects.deletedThreadIds,
|
||||
sideEffects.deletedThreadIds,
|
||||
(threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const threadSegment = toSafeThreadAttachmentSegment(threadId);
|
||||
@@ -352,16 +231,39 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
||||
});
|
||||
return;
|
||||
}
|
||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||
yield* input.fileSystem.remove(threadDir, { recursive: true, force: true });
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
|
||||
return;
|
||||
}
|
||||
const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
return;
|
||||
}
|
||||
yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
|
||||
force: true,
|
||||
});
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.sideEffects.prunedThreadRelativePaths.entries(),
|
||||
sideEffects.prunedThreadRelativePaths.entries(),
|
||||
([threadId, keptThreadRelativePaths]) => {
|
||||
if (input.sideEffects.deletedThreadIds.has(threadId)) {
|
||||
if (sideEffects.deletedThreadIds.has(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
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 });
|
||||
return;
|
||||
}
|
||||
const threadDir = input.path.join(attachmentsRootDir, threadSegment);
|
||||
const entries = yield* input.fileSystem
|
||||
.readDirectory(threadDir, { recursive: true })
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(attachmentsRootDir, { recursive: false })
|
||||
.pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
|
||||
yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const threadRelativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (threadRelativePath.length === 0 || threadRelativePath.startsWith("..")) {
|
||||
const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
|
||||
if (relativePath.length === 0 || relativePath.includes("/")) {
|
||||
return;
|
||||
}
|
||||
const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
|
||||
if (!attachmentId) {
|
||||
return;
|
||||
}
|
||||
const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
|
||||
if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
|
||||
return;
|
||||
}
|
||||
|
||||
const absolutePath = input.path.join(threadDir, threadRelativePath);
|
||||
const fileInfo = yield* input.fileSystem
|
||||
const absolutePath = path.join(attachmentsRootDir, relativePath);
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(absolutePath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!keptThreadRelativePaths.has(threadRelativePath)) {
|
||||
yield* input.fileSystem.remove(absolutePath, { force: true });
|
||||
if (!keptThreadRelativePaths.has(relativePath)) {
|
||||
yield* fileSystem.remove(absolutePath, { force: true });
|
||||
}
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
@@ -402,22 +311,6 @@ const runAttachmentSideEffects = Effect.fn(function* (input: {
|
||||
{ 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* () {
|
||||
@@ -434,6 +327,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -634,13 +528,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const nextAttachments =
|
||||
event.payload.attachments !== undefined
|
||||
? yield* materializeAttachmentsForProjection({
|
||||
threadId: event.payload.threadId,
|
||||
messageId: event.payload.messageId,
|
||||
attachments: event.payload.attachments,
|
||||
stageFileWrite: (pendingWrite) => {
|
||||
attachmentSideEffects.writes.push(pendingWrite);
|
||||
},
|
||||
}).pipe(Effect.provideService(Path.Path, path))
|
||||
})
|
||||
: existingMessage?.attachments;
|
||||
yield* projectionThreadMessageRepository.upsert({
|
||||
messageId: event.payload.messageId,
|
||||
@@ -1131,7 +1020,6 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentSideEffects: AttachmentSideEffects = {
|
||||
writes: [],
|
||||
deletedThreadIds: new Set<string>(),
|
||||
prunedThreadRelativePaths: new Map<string, Set<string>>(),
|
||||
};
|
||||
@@ -1148,11 +1036,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
yield* runAttachmentSideEffects({
|
||||
sideEffects: attachmentSideEffects,
|
||||
fileSystem,
|
||||
path,
|
||||
}).pipe(
|
||||
yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to apply projected attachment side-effects", {
|
||||
projector: projector.name,
|
||||
@@ -1184,6 +1068,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
|
||||
concurrency: 1,
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.catchTag("SqlError", (sqlError) =>
|
||||
Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
|
||||
@@ -1195,6 +1082,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
bootstrapProjector,
|
||||
{ concurrency: 1 },
|
||||
).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(ServerConfig, serverConfig),
|
||||
Effect.asVoid,
|
||||
Effect.tap(() =>
|
||||
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 {
|
||||
ApprovalRequestId,
|
||||
@@ -13,6 +17,8 @@ import {
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
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 { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
@@ -20,11 +26,14 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} 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 { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
|
||||
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
@@ -56,6 +65,7 @@ describe("ProviderCommandReactor", () => {
|
||||
unknown
|
||||
> | null = null;
|
||||
let scope: Scope.Closeable | null = null;
|
||||
const createdStateDirs = new Set<string>();
|
||||
|
||||
afterEach(async () => {
|
||||
if (scope) {
|
||||
@@ -66,10 +76,16 @@ describe("ProviderCommandReactor", () => {
|
||||
await runtime.dispose();
|
||||
}
|
||||
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 stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
createdStateDirs.add(stateDir);
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
const startSession = vi.fn((_: unknown, __: unknown) => {
|
||||
@@ -92,6 +108,16 @@ describe("ProviderCommandReactor", () => {
|
||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||
const respondToRequest = 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 service: ProviderServiceShape = {
|
||||
@@ -115,8 +141,15 @@ describe("ProviderCommandReactor", () => {
|
||||
const layer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
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 reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
@@ -155,6 +188,9 @@ describe("ProviderCommandReactor", () => {
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
generateBranchName,
|
||||
stateDir,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -196,6 +232,247 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||
});
|
||||
|
||||
it("generates and renames temporary worktree branch on first turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/89abc123",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-rename"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-worktree-rename"),
|
||||
role: "user",
|
||||
text: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-rename",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
|
||||
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||
message: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-rename",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
|
||||
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||
oldBranch: "t3code/89abc123",
|
||||
newBranch: "t3code/generated-name",
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const readModel = Effect.runSync(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return thread?.branch === "t3code/generated-name";
|
||||
});
|
||||
});
|
||||
|
||||
it("passes persisted attachment references to branch generation and turn start", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-persisted"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/abcdef12",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-persisted-attachments"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-persisted-attachments"),
|
||||
role: "user",
|
||||
text: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-persisted",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||
cwd: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||
message: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-persisted",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-persisted",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("skips worktree branch generation after the first user turn", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/1234abcd",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-first"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-first"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-second"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-second"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.generateBranchName.mock.calls.length).toBe(1);
|
||||
expect(harness.renameBranch.mock.calls.length).toBe(1);
|
||||
});
|
||||
|
||||
it("skips worktree rename when branch-name generation fails", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
harness.generateBranchName.mockImplementationOnce(() =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "model returned invalid payload",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-null"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/0000abcd",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-0000abcd",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-null-branch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-null-branch"),
|
||||
role: "user",
|
||||
text: "Fix visual regression",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await Effect.runPromise(Effect.sleep("20 millis"));
|
||||
expect(harness.renameBranch.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.branch).toBe("t3code/0000abcd");
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -328,8 +605,8 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.startSession.mockImplementationOnce((_: unknown, __: unknown) =>
|
||||
Effect.fail(new Error("simulated restart failure")) as never,
|
||||
harness.startSession.mockImplementationOnce(
|
||||
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
|
||||
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 { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
@@ -66,10 +68,41 @@ const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
|
||||
function buildGeneratedWorktreeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^refs\/heads\//, "")
|
||||
.replace(/['"`]/g, "");
|
||||
|
||||
const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)
|
||||
? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)
|
||||
: normalized;
|
||||
|
||||
const branchFragment = withoutPrefix
|
||||
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||
.slice(0, 64)
|
||||
.replace(/[./_-]+$/g, "");
|
||||
|
||||
const safeFragment = branchFragment.length > 0 ? branchFragment : "update";
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;
|
||||
}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const git = yield* GitCore;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const handledTurnStartKeys = yield* Cache.make<string, true>({
|
||||
capacity: HANDLED_TURN_START_KEY_MAX,
|
||||
timeToLive: HANDLED_TURN_START_KEY_TTL,
|
||||
@@ -190,7 +223,8 @@ const make = Effect.gen(function* () {
|
||||
const existingSessionId = thread.session?.providerSessionId;
|
||||
if (existingSessionId) {
|
||||
const approvalPolicyChanged =
|
||||
options?.approvalPolicy !== undefined && options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||
options?.approvalPolicy !== undefined &&
|
||||
options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||
const sandboxModeChanged =
|
||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||
|
||||
@@ -198,7 +232,9 @@ const make = Effect.gen(function* () {
|
||||
return existingSessionId;
|
||||
}
|
||||
|
||||
const restartedSession = yield* startProviderSession(thread.session?.providerThreadId ?? null);
|
||||
const restartedSession = yield* startProviderSession(
|
||||
thread.session?.providerThreadId ?? null,
|
||||
);
|
||||
yield* bindSessionToThread(restartedSession);
|
||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||
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* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
|
||||
) {
|
||||
@@ -273,6 +377,15 @@ const make = Effect.gen(function* () {
|
||||
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({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
|
||||
@@ -28,11 +28,12 @@ import {
|
||||
type OrchestrationEngineShape,
|
||||
} from "../Services/OrchestrationEngine.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 asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId =>
|
||||
ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
@@ -122,6 +123,8 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const layer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(orchestrationLayer),
|
||||
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
@@ -255,7 +258,9 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
|
||||
|
||||
@@ -308,7 +313,9 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
expect(midThread?.session?.status).toBe("running");
|
||||
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
|
||||
|
||||
@@ -401,7 +408,9 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
|
||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||
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(
|
||||
false,
|
||||
);
|
||||
@@ -416,10 +425,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
itemId: asItemId("item-buffered"),
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some((message) => message.id === "assistant:item-buffered" && !message.streaming),
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-buffered" && !message.streaming,
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffered");
|
||||
expect(message?.text).toBe("buffer me");
|
||||
@@ -475,15 +484,13 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
delta: "hello live",
|
||||
});
|
||||
|
||||
const liveThread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message) =>
|
||||
message.id === "assistant:item-streaming-mode" &&
|
||||
message.streaming &&
|
||||
message.text === "hello live",
|
||||
),
|
||||
const liveThread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message) =>
|
||||
message.id === "assistant:item-streaming-mode" &&
|
||||
message.streaming &&
|
||||
message.text === "hello live",
|
||||
),
|
||||
);
|
||||
const liveMessage = liveThread.messages.find(
|
||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||
@@ -500,12 +507,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
itemId: asItemId("item-streaming-mode"),
|
||||
});
|
||||
|
||||
const finalThread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||
),
|
||||
const finalThread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-streaming-mode" && !message.streaming,
|
||||
),
|
||||
);
|
||||
const finalMessage = finalThread.messages.find(
|
||||
(entry) => entry.id === "assistant:item-streaming-mode",
|
||||
@@ -554,12 +559,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
itemId: asItemId("item-buffer-spill"),
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.engine,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||
),
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message) => message.id === "assistant:item-buffer-spill" && !message.streaming,
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find((entry) => entry.id === "assistant:item-buffer-spill");
|
||||
expect(message?.text.length).toBe(oversizedText.length);
|
||||
|
||||
@@ -21,10 +21,10 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
const persistedAttachments = [
|
||||
{
|
||||
type: "image" as const,
|
||||
id: "thread-preserve-attachments-att-1",
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "/attachments/thread-preserve-attachments/message-preserve-attachments/0.png",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -74,10 +74,10 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-clear-attachments-att-1",
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
dataUrl: "/attachments/thread-clear-attachments/message-clear-attachments/0.png",
|
||||
},
|
||||
],
|
||||
isStreaming: false,
|
||||
|
||||
@@ -2,32 +2,6 @@ import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
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> = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
ProviderItemId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
type ProviderSendTurnInput,
|
||||
ProviderSessionId,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
@@ -12,12 +11,17 @@ import {
|
||||
ProviderTurnId,
|
||||
type ProviderTurnStartResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { afterAll, assert, it, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Fiber, Stream } from "effect";
|
||||
import { Effect, Fiber, Layer, Stream } from "effect";
|
||||
|
||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
type CodexAppServerSendTurnInput,
|
||||
} from "../../codexAppServerManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ProviderAdapterValidationError } from "../Errors.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
|
||||
@@ -44,7 +48,7 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
);
|
||||
|
||||
public sendTurnImpl = vi.fn(
|
||||
async (_input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
||||
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
|
||||
threadId: ProviderThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
}),
|
||||
@@ -78,7 +82,7 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
return this.startSessionImpl(input);
|
||||
}
|
||||
|
||||
override sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
return this.sendTurnImpl(input);
|
||||
}
|
||||
|
||||
@@ -118,7 +122,12 @@ class FakeCodexManager extends CodexAppServerManager {
|
||||
}
|
||||
|
||||
const validationManager = new FakeCodexManager();
|
||||
const validationLayer = it.layer(makeCodexAdapterLive({ manager: validationManager }));
|
||||
const validationLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: validationManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
validationLayer("CodexAdapterLive validation", (it) => {
|
||||
it.effect("returns validation error for non-codex provider on startSession", () =>
|
||||
@@ -147,7 +156,12 @@ const sessionErrorManager = new FakeCodexManager();
|
||||
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
|
||||
throw new Error("Unknown session: sess-missing");
|
||||
});
|
||||
const sessionErrorLayer = it.layer(makeCodexAdapterLive({ manager: sessionErrorManager }));
|
||||
const sessionErrorLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
|
||||
@@ -178,7 +192,12 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
});
|
||||
|
||||
const lifecycleManager = new FakeCodexManager();
|
||||
const lifecycleLayer = it.layer(makeCodexAdapterLive({ manager: lifecycleManager }));
|
||||
const lifecycleLayer = it.layer(
|
||||
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
it.effect("maps completed agent message items to canonical message.completed events", () =>
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Queue, Schema, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Queue, Schema, Stream } from "effect";
|
||||
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
} from "../Errors.ts";
|
||||
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CodexAppServerManager } from "../../codexAppServerManager.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
@@ -426,6 +428,8 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
|
||||
const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverConfig = yield* Effect.service(ServerConfig);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogPath !== undefined
|
||||
? makeEventNdjsonLogger(options.nativeEventLogPath)
|
||||
@@ -475,9 +479,48 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
};
|
||||
|
||||
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.tryPromise({
|
||||
try: () => manager.sendTurn(input),
|
||||
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
|
||||
Effect.gen(function* () {
|
||||
const codexAttachments = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* Effect.fail(
|
||||
toRequestError(
|
||||
input.sessionId,
|
||||
"turn/start",
|
||||
new Error(`Invalid attachment id '${attachment.id}'.`),
|
||||
),
|
||||
);
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError((cause) => toRequestError(input.sessionId, "turn/start", cause)),
|
||||
);
|
||||
return {
|
||||
type: "image" as const,
|
||||
url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
|
||||
};
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => {
|
||||
const managerInput = {
|
||||
sessionId: input.sessionId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.effort !== undefined ? { effort: input.effort } : {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
};
|
||||
return manager.sendTurn(managerInput);
|
||||
},
|
||||
catch: (cause) => toRequestError(input.sessionId, "turn/start", cause),
|
||||
});
|
||||
});
|
||||
|
||||
const interruptTurn: CodexAdapterShape["interruptTurn"] = (sessionId, turnId) =>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from "node:path";
|
||||
|
||||
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 { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
|
||||
@@ -37,7 +37,7 @@ import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { stateDir } = yield* ServerConfig;
|
||||
@@ -56,6 +56,9 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
}
|
||||
|
||||
export function makeServerRuntimeServicesLayer() {
|
||||
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
||||
const textGenerationLayer = CodexTextGenerationLive;
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
@@ -78,6 +81,8 @@ export function makeServerRuntimeServicesLayer() {
|
||||
);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
@@ -92,12 +97,10 @@ export function makeServerRuntimeServicesLayer() {
|
||||
Layer.provide(typeof Bun !== "undefined" ? BunPtyAdapterLive : NodePtyAdapterLive),
|
||||
);
|
||||
|
||||
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
|
||||
|
||||
const gitManagerLayer = GitManagerLive.pipe(
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(GitHubCliLive),
|
||||
Layer.provideMerge(CodexTextGenerationLive),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
|
||||
return Layer.mergeAll(
|
||||
|
||||
@@ -369,7 +369,10 @@ describe("WebSocket Server", () => {
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
||||
gitCore?: Pick<
|
||||
GitCoreShape,
|
||||
"listBranches" | "initRepo" | "pullCurrentBranch"
|
||||
>;
|
||||
terminalManager?: TerminalManagerShape;
|
||||
} = {},
|
||||
): Promise<Http.Server> {
|
||||
@@ -417,6 +420,7 @@ describe("WebSocket Server", () => {
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
@@ -1507,6 +1511,7 @@ describe("WebSocket Server", () => {
|
||||
expect(pullResponse.result).toBeUndefined();
|
||||
expect(pullResponse.error?.message).toContain("No upstream configured");
|
||||
expect(pullCurrentBranch).toHaveBeenCalledWith("/repo/path");
|
||||
|
||||
});
|
||||
|
||||
it("supports git.status over websocket", async () => {
|
||||
|
||||
+114
-13
@@ -12,8 +12,11 @@ import type { Duplex } from "node:stream";
|
||||
import Mime from "@effect/platform-node/Mime";
|
||||
import {
|
||||
CommandId,
|
||||
type ClientOrchestrationCommand,
|
||||
type OrchestrationCommand,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TerminalEvent,
|
||||
@@ -54,7 +57,14 @@ import { clamp } from "effect/Number";
|
||||
import { Open } from "./open";
|
||||
import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { ATTACHMENTS_ROUTE_PREFIX, tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
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.
|
||||
@@ -230,6 +240,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
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const respond = (
|
||||
@@ -249,22 +341,30 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
}
|
||||
|
||||
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 normalizedRelativePath = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
|
||||
if (
|
||||
normalizedRelativePath.length === 0 ||
|
||||
normalizedRelativePath.startsWith("..") ||
|
||||
normalizedRelativePath.includes("\0")
|
||||
) {
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
|
||||
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
const isIdLookup =
|
||||
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
|
||||
const filePath = isIdLookup
|
||||
? resolveAttachmentPathById({
|
||||
stateDir: serverConfig.stateDir,
|
||||
attachmentId: normalizedRelativePath,
|
||||
})
|
||||
: resolveAttachmentRelativePath({
|
||||
stateDir: serverConfig.stateDir,
|
||||
relativePath: normalizedRelativePath,
|
||||
});
|
||||
if (!filePath) {
|
||||
respond(
|
||||
isIdLookup ? 404 : 400,
|
||||
{ "Content-Type": "text/plain" },
|
||||
isIdLookup ? "Not Found" : "Invalid attachment path",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -506,7 +606,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case ORCHESTRATION_WS_METHODS.dispatchCommand: {
|
||||
const { command } = request.body;
|
||||
return yield* orchestrationEngine.dispatch(command);
|
||||
const normalizedCommand = yield* normalizeDispatchCommand({ command });
|
||||
return yield* orchestrationEngine.dispatch(normalizedCommand);
|
||||
}
|
||||
|
||||
case ORCHESTRATION_WS_METHODS.getTurnDiff: {
|
||||
|
||||
@@ -27,7 +27,8 @@
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
@@ -57,3 +61,124 @@ describe("deriveSyncedLocalBranch", () => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
});
|
||||
|
||||
it("supports remote names that contain slashes", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
|
||||
"upstream/feature/demo",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the original name when ref is malformed", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
|
||||
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
it("hides remote refs when the matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/demo",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/remote-only",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps all entries when no local match exists for a remote ref", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/local",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/remote-only",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/local",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes remote refs for remotes whose names contain slashes", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "my-org/upstream/feature/demo",
|
||||
isRemote: true,
|
||||
remoteName: "my-org/upstream",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes remote refs when git tracks with first-slash local naming", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "upstream/feature",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "my-org/upstream/feature",
|
||||
isRemote: true,
|
||||
remoteName: "my-org/upstream",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"upstream/feature",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,54 @@ interface DeriveSyncedLocalBranchInput {
|
||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
||||
}
|
||||
|
||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
const firstSeparatorIndex = branchName.indexOf("/");
|
||||
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
|
||||
return branchName;
|
||||
}
|
||||
return branchName.slice(firstSeparatorIndex + 1);
|
||||
}
|
||||
|
||||
function deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branchName: string,
|
||||
remoteName?: string,
|
||||
): ReadonlyArray<string> {
|
||||
const candidates = new Set<string>();
|
||||
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
|
||||
if (firstSlashCandidate.length > 0) {
|
||||
candidates.add(firstSlashCandidate);
|
||||
}
|
||||
|
||||
if (remoteName) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
|
||||
candidates.add(branchName.slice(remotePrefix.length));
|
||||
}
|
||||
}
|
||||
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
export function dedupeRemoteBranchesWithLocalMatches(
|
||||
branches: ReadonlyArray<GitBranch>,
|
||||
): ReadonlyArray<GitBranch> {
|
||||
const localBranchNames = new Set(
|
||||
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
|
||||
);
|
||||
|
||||
return branches.filter((branch) => {
|
||||
if (!branch.isRemote) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branch.name,
|
||||
branch.remoteName,
|
||||
);
|
||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
|
||||
@@ -9,8 +9,13 @@ import {
|
||||
gitCreateBranchAndCheckoutMutationOptions,
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -39,27 +44,35 @@ export default function BranchToolbar({
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarProps) {
|
||||
const { state, dispatch } = useStore();
|
||||
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
|
||||
const activeThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeThreadId = activeThread?.id;
|
||||
const activeThreadBranch = activeThread?.branch ?? null;
|
||||
const activeWorktreePath = activeThread?.worktreePath ?? null;
|
||||
const serverThread = state.threads.find((thread) => thread.id === threadId);
|
||||
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
|
||||
const activeProject = state.projects.find((project) => project.id === activeProjectId);
|
||||
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
|
||||
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
|
||||
const hasServerThread = serverThread !== undefined;
|
||||
const effectiveEnvMode: "local" | "worktree" =
|
||||
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
|
||||
? "worktree"
|
||||
: envMode;
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
|
||||
const branches = branchesQuery.data?.branches ?? [];
|
||||
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
||||
const branchNames = branches.map((branch) => branch.name);
|
||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
|
||||
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
|
||||
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
@@ -84,14 +97,14 @@ export default function BranchToolbar({
|
||||
const syncedBranch = deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
envMode,
|
||||
envMode: effectiveEnvMode,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
});
|
||||
if (!activeThreadId || !syncedBranch) return;
|
||||
const api = readNativeApi();
|
||||
|
||||
if (api) {
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
@@ -100,13 +113,30 @@ export default function BranchToolbar({
|
||||
worktreePath: null,
|
||||
});
|
||||
}
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
if (hasServerThread) {
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: activeThreadId,
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
branch: syncedBranch,
|
||||
worktreePath: null,
|
||||
});
|
||||
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
|
||||
}, [
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
activeThreadBranch,
|
||||
queryBranches,
|
||||
effectiveEnvMode,
|
||||
dispatch,
|
||||
hasServerThread,
|
||||
setDraftThreadContext,
|
||||
threadId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isBranchMenuOpen) return;
|
||||
@@ -125,7 +155,7 @@ export default function BranchToolbar({
|
||||
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;
|
||||
const sessionId = serverThread?.session?.sessionId;
|
||||
if (sessionId && worktreePath !== activeWorktreePath && api) {
|
||||
void api.orchestration
|
||||
.dispatchCommand({
|
||||
@@ -136,7 +166,7 @@ export default function BranchToolbar({
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (api) {
|
||||
if (api && hasServerThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
@@ -145,7 +175,15 @@ export default function BranchToolbar({
|
||||
worktreePath,
|
||||
});
|
||||
}
|
||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
||||
if (hasServerThread) {
|
||||
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(threadId, {
|
||||
branch,
|
||||
worktreePath,
|
||||
envMode: effectiveEnvMode,
|
||||
});
|
||||
};
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
@@ -153,7 +191,7 @@ export default function BranchToolbar({
|
||||
if (!api || !activeThreadId || !branchCwd) return;
|
||||
|
||||
// For new worktree mode, selecting a branch picks the base branch.
|
||||
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
|
||||
setThreadError(null);
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
@@ -174,10 +212,21 @@ export default function BranchToolbar({
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
checkoutMutation.mutate(branch.name, {
|
||||
onSuccess: () => {
|
||||
onSuccess: async () => {
|
||||
setThreadError(null);
|
||||
setThreadBranch(branch.name, activeWorktreePath);
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
@@ -206,7 +255,7 @@ export default function BranchToolbar({
|
||||
});
|
||||
};
|
||||
|
||||
if (!activeThread || !activeProject) return null;
|
||||
if (!activeThreadId || !activeProject) return null;
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||
@@ -221,9 +270,11 @@ export default function BranchToolbar({
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
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>
|
||||
)}
|
||||
</div>
|
||||
@@ -233,7 +284,7 @@ export default function BranchToolbar({
|
||||
autoHighlight
|
||||
onOpenChange={(open) => setIsBranchMenuOpen(open)}
|
||||
open={isBranchMenuOpen}
|
||||
value={activeThread.branch}
|
||||
value={activeThreadBranch}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
render={<Button variant="ghost" size="xs" />}
|
||||
@@ -241,10 +292,10 @@ export default function BranchToolbar({
|
||||
disabled={branchesQuery.isLoading}
|
||||
>
|
||||
<span className="max-w-[240px] truncate">
|
||||
{activeThread.branch
|
||||
? envMode === "worktree" && !activeWorktreePath
|
||||
? `From ${activeThread.branch}`
|
||||
: activeThread.branch
|
||||
{activeThreadBranch
|
||||
? effectiveEnvMode === "worktree" && !activeWorktreePath
|
||||
? `From ${activeThreadBranch}`
|
||||
: activeThreadBranch
|
||||
: "Select branch"}
|
||||
</span>
|
||||
<ChevronDownIcon />
|
||||
@@ -283,23 +334,28 @@ export default function BranchToolbar({
|
||||
|
||||
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
|
||||
itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
|
||||
}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
||||
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
|
||||
</span>
|
||||
)}
|
||||
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlug,
|
||||
} from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -53,7 +54,7 @@ import {
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
type ChatMessage,
|
||||
type ChatImageAttachment,
|
||||
type Thread,
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
|
||||
@@ -111,6 +112,14 @@ import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
type DraftThreadState,
|
||||
type PersistedComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import { clamp } from "effect/Number";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
@@ -129,6 +138,7 @@ const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
function readLastInvokedScriptByProjectFromStorage(): Record<string, string> {
|
||||
const stored = localStorage.getItem(LAST_INVOKED_SCRIPT_BY_PROJECT_KEY);
|
||||
@@ -155,11 +165,6 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
return "text-muted-foreground/40";
|
||||
}
|
||||
|
||||
interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
|
||||
previewUrl: string;
|
||||
file: File;
|
||||
}
|
||||
|
||||
interface ExpandedImageItem {
|
||||
src: string;
|
||||
name: string;
|
||||
@@ -190,6 +195,62 @@ function buildExpandedImagePreview(
|
||||
};
|
||||
}
|
||||
|
||||
function buildLocalDraftThread(
|
||||
threadId: ThreadId,
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModel: string,
|
||||
error: string | null,
|
||||
): Thread {
|
||||
return {
|
||||
id: threadId,
|
||||
codexThreadId: null,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
model: fallbackModel,
|
||||
terminalOpen: false,
|
||||
terminalHeight: 280,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
error,
|
||||
createdAt: draftThread.createdAt,
|
||||
latestTurn: null,
|
||||
lastVisitedAt: draftThread.createdAt,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
};
|
||||
}
|
||||
|
||||
function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
|
||||
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
|
||||
return;
|
||||
}
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
|
||||
function revokeUserMessagePreviewUrls(message: ChatMessage): void {
|
||||
if (message.role !== "user" || !message.attachments) {
|
||||
return;
|
||||
}
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
revokeBlobPreviewUrl(attachment.previewUrl);
|
||||
}
|
||||
}
|
||||
|
||||
type ComposerCommandItem =
|
||||
| {
|
||||
id: string;
|
||||
@@ -232,6 +293,26 @@ function readFileAsDataUrl(file: File): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = crypto.randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
function cloneComposerImageForRetry(image: ComposerImageAttachment): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
}
|
||||
try {
|
||||
return {
|
||||
...image,
|
||||
previewUrl: URL.createObjectURL(image.file),
|
||||
};
|
||||
} catch {
|
||||
return image;
|
||||
}
|
||||
}
|
||||
|
||||
const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
@@ -365,23 +446,44 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
const prompt = composerDraft.prompt;
|
||||
const composerImages = composerDraft.images;
|
||||
const composerCursor = composerDraft.cursor;
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftCursor = useComposerDraftStore((store) => store.setCursor);
|
||||
const setComposerDraftModel = useComposerDraftStore((store) => store.setModel);
|
||||
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
|
||||
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
|
||||
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.clearPersistedAttachments,
|
||||
);
|
||||
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.syncPersistedAttachments,
|
||||
);
|
||||
const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
|
||||
const clearDraftThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const draftThread = useComposerDraftStore((store) => store.draftThreadsByThreadId[threadId] ?? null);
|
||||
const promptRef = useRef(prompt);
|
||||
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
||||
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
|
||||
Record<ThreadId, string | null>
|
||||
>({});
|
||||
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
||||
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
||||
const [envMode, setEnvMode] = useState<DraftThreadEnvMode>("local");
|
||||
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
const [composerCursor, setComposerCursor] = useState(0);
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useState<
|
||||
Record<string, string>
|
||||
@@ -395,7 +497,55 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const dragDepthRef = useRef(0);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
|
||||
const activeThread = state.threads.find((t) => t.id === threadId);
|
||||
const setPrompt = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
setComposerDraftPrompt(threadId, nextPrompt);
|
||||
},
|
||||
[setComposerDraftPrompt, threadId],
|
||||
);
|
||||
const setComposerCursor = useCallback(
|
||||
(nextCursor: number) => {
|
||||
setComposerDraftCursor(threadId, nextCursor);
|
||||
},
|
||||
[setComposerDraftCursor, threadId],
|
||||
);
|
||||
const addComposerImage = useCallback(
|
||||
(image: ComposerImageAttachment) => {
|
||||
addComposerDraftImage(threadId, image);
|
||||
},
|
||||
[addComposerDraftImage, threadId],
|
||||
);
|
||||
const addComposerImagesToDraft = useCallback(
|
||||
(images: ComposerImageAttachment[]) => {
|
||||
addComposerDraftImages(threadId, images);
|
||||
},
|
||||
[addComposerDraftImages, threadId],
|
||||
);
|
||||
const removeComposerImageFromDraft = useCallback(
|
||||
(imageId: string) => {
|
||||
removeComposerDraftImage(threadId, imageId);
|
||||
},
|
||||
[removeComposerDraftImage, threadId],
|
||||
);
|
||||
|
||||
const serverThread = state.threads.find((t) => t.id === threadId);
|
||||
const fallbackDraftProject = state.projects.find((project) => project.id === draftThread?.projectId);
|
||||
const localDraftError = localDraftErrorsByThreadId[threadId] ?? null;
|
||||
const localDraftThread = useMemo(
|
||||
() =>
|
||||
draftThread
|
||||
? buildLocalDraftThread(
|
||||
threadId,
|
||||
draftThread,
|
||||
fallbackDraftProject?.model ?? DEFAULT_MODEL,
|
||||
localDraftError,
|
||||
)
|
||||
: undefined,
|
||||
[draftThread, fallbackDraftProject?.model, localDraftError, threadId],
|
||||
);
|
||||
const activeThread = serverThread ?? localDraftThread;
|
||||
const isServerThread = serverThread !== undefined;
|
||||
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
|
||||
const diffSearch = useMemo(
|
||||
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
|
||||
[rawSearch],
|
||||
@@ -406,6 +556,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const activeProject = state.projects.find((p) => p.id === activeThread?.projectId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverThread) {
|
||||
return;
|
||||
}
|
||||
setLocalDraftErrorsByThreadId((existing) => {
|
||||
if (!(threadId in existing)) {
|
||||
return existing;
|
||||
}
|
||||
const { [threadId]: _removed, ...rest } = existing;
|
||||
return rest as Record<ThreadId, string | null>;
|
||||
});
|
||||
}, [serverThread, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
if (!latestTurnSettled) return;
|
||||
@@ -427,9 +590,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
dispatch,
|
||||
]);
|
||||
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const baseThreadModel = resolveModelSlug(activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL);
|
||||
const selectedModel = resolveModelSlug(composerDraft.model ?? baseThreadModel);
|
||||
const selectedEffort = composerDraft.effort ?? DEFAULT_REASONING;
|
||||
const modelOptions = useMemo(
|
||||
() => getAppModelOptions(settings.customCodexModels, selectedModel),
|
||||
[selectedModel, settings.customCodexModels],
|
||||
@@ -638,6 +801,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
null,
|
||||
[composerHighlightedItemId, composerMenuItems],
|
||||
);
|
||||
const nonPersistedComposerImageIdSet = useMemo(
|
||||
() => new Set(nonPersistedComposerImageIds),
|
||||
[nonPersistedComposerImageIds],
|
||||
);
|
||||
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
|
||||
const threadTerminalRuntimeEnv = useMemo(() => {
|
||||
if (!activeProject?.cwd) return {};
|
||||
@@ -686,12 +853,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const hasReachedTerminalLimit =
|
||||
(activeThread?.terminalIds.length ?? 0) >= MAX_THREAD_TERMINAL_COUNT;
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
if (!image.previewUrl) continue;
|
||||
URL.revokeObjectURL(image.previewUrl);
|
||||
}
|
||||
}, []);
|
||||
const focusComposer = useCallback(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
@@ -781,10 +942,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
worktreePath?: string | null;
|
||||
preferNewTerminal?: boolean;
|
||||
rememberAsLastInvoked?: boolean;
|
||||
allowLocalDraftThread?: boolean;
|
||||
},
|
||||
) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !activeProject || !activeThread) return;
|
||||
if (!isServerThread && !options?.allowLocalDraftThread) return;
|
||||
if (options?.rememberAsLastInvoked !== false) {
|
||||
setLastInvokedScriptByProjectId((current) => {
|
||||
if (current[activeProject.id] === script.id) return current;
|
||||
@@ -856,7 +1019,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}
|
||||
},
|
||||
[activeProject, activeThread, activeThreadId, dispatch, gitCwd],
|
||||
[activeProject, activeThread, activeThreadId, dispatch, gitCwd, isServerThread],
|
||||
);
|
||||
const persistProjectScripts = useCallback(
|
||||
async (input: {
|
||||
@@ -1067,7 +1230,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) {
|
||||
setOptimisticUserMessages([]);
|
||||
setOptimisticUserMessages((existing) => {
|
||||
for (const message of existing) {
|
||||
revokeUserMessagePreviewUrls(message);
|
||||
}
|
||||
return [];
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (activeThread.messages.length === 0) {
|
||||
@@ -1075,32 +1243,98 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
const serverIds = new Set(activeThread.messages.map((message) => message.id));
|
||||
setOptimisticUserMessages((existing) => {
|
||||
const removed = existing.filter((message) => serverIds.has(message.id));
|
||||
for (const message of removed) {
|
||||
revokeUserMessagePreviewUrls(message);
|
||||
}
|
||||
const next = existing.filter((message) => !serverIds.has(message.id));
|
||||
return next.length === existing.length ? existing : next;
|
||||
});
|
||||
}, [activeThread?.id, activeThread?.messages]);
|
||||
|
||||
useEffect(() => {
|
||||
setComposerImages((existing) => {
|
||||
revokePreviewUrls(existing);
|
||||
promptRef.current = prompt;
|
||||
}, [prompt]);
|
||||
|
||||
useEffect(() => {
|
||||
setOptimisticUserMessages((existing) => {
|
||||
for (const message of existing) {
|
||||
revokeUserMessagePreviewUrls(message);
|
||||
}
|
||||
return [];
|
||||
});
|
||||
setOptimisticUserMessages([]);
|
||||
setPrompt("");
|
||||
promptRef.current = "";
|
||||
setSendPhase("idle");
|
||||
setComposerCursor(0);
|
||||
setComposerHighlightedItemId(null);
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
setExpandedImage(null);
|
||||
}, [activeThread?.id, revokePreviewUrls]);
|
||||
}, [threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
if (composerImages.length === 0) {
|
||||
clearComposerDraftPersistedAttachments(threadId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const currentPersistedAttachments =
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
|
||||
const existingPersistedById = new Map(
|
||||
currentPersistedAttachments.map((attachment) => [attachment.id, attachment]),
|
||||
);
|
||||
const stagedAttachmentById = new Map<string, PersistedComposerImageAttachment>();
|
||||
await Promise.all(
|
||||
composerImages.map(async (image) => {
|
||||
try {
|
||||
const dataUrl = await readFileAsDataUrl(image.file);
|
||||
stagedAttachmentById.set(image.id, {
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl,
|
||||
});
|
||||
} catch {
|
||||
const existingPersisted = existingPersistedById.get(image.id);
|
||||
if (existingPersisted) {
|
||||
stagedAttachmentById.set(image.id, existingPersisted);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serialized = Array.from(stagedAttachmentById.values());
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
// Stage attachments in persisted draft state first so persist middleware can write them.
|
||||
syncComposerDraftPersistedAttachments(threadId, serialized);
|
||||
} catch {
|
||||
const currentImageIds = new Set(composerImages.map((image) => image.id));
|
||||
const fallbackPersistedAttachments =
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
|
||||
const fallbackPersistedIds = fallbackPersistedAttachments
|
||||
.map((attachment) => attachment.id)
|
||||
.filter((id) => currentImageIds.has(id));
|
||||
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
|
||||
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
|
||||
fallbackPersistedIdSet.has(attachment.id),
|
||||
);
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
syncComposerDraftPersistedAttachments(threadId, fallbackAttachments);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
revokePreviewUrls(composerImagesRef.current);
|
||||
cancelled = true;
|
||||
};
|
||||
}, [revokePreviewUrls]);
|
||||
}, [
|
||||
clearComposerDraftPersistedAttachments,
|
||||
composerImages,
|
||||
syncComposerDraftPersistedAttachments,
|
||||
threadId,
|
||||
]);
|
||||
|
||||
const closeExpandedImage = useCallback(() => {
|
||||
setExpandedImage(null);
|
||||
@@ -1154,8 +1388,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
setEnvMode(activeWorktreePath ? "worktree" : "local");
|
||||
}, [activeThread?.id, activeWorktreePath]);
|
||||
if (activeWorktreePath) {
|
||||
setEnvMode("worktree");
|
||||
return;
|
||||
}
|
||||
if (isLocalDraftThread) {
|
||||
setEnvMode(draftThread?.envMode ?? "local");
|
||||
return;
|
||||
}
|
||||
setEnvMode("local");
|
||||
}, [activeThread?.id, activeWorktreePath, draftThread?.envMode, isLocalDraftThread]);
|
||||
|
||||
// Auto-resize textarea
|
||||
useEffect(() => {
|
||||
@@ -1291,19 +1533,32 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setThreadError = useCallback(
|
||||
(threadId: ThreadId | null, error: string | null) => {
|
||||
if (!threadId) return;
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId,
|
||||
error,
|
||||
if (state.threads.some((thread) => thread.id === threadId)) {
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId,
|
||||
error,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setLocalDraftErrorsByThreadId((existing) => {
|
||||
if ((existing[threadId] ?? null) === error) {
|
||||
return existing;
|
||||
}
|
||||
return {
|
||||
...existing,
|
||||
[threadId]: error,
|
||||
};
|
||||
});
|
||||
},
|
||||
[dispatch],
|
||||
[dispatch, state.threads],
|
||||
);
|
||||
|
||||
const addComposerImages = (files: File[]) => {
|
||||
if (!activeThreadId || files.length === 0) return;
|
||||
|
||||
const nextImages = [...composerImagesRef.current];
|
||||
const nextImages: ComposerImageAttachment[] = [];
|
||||
let nextImageCount = composerImagesRef.current.length;
|
||||
let error: string | null = null;
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
@@ -1314,7 +1569,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
|
||||
continue;
|
||||
}
|
||||
if (nextImages.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
|
||||
break;
|
||||
}
|
||||
@@ -1329,20 +1584,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
previewUrl,
|
||||
file,
|
||||
});
|
||||
nextImageCount += 1;
|
||||
}
|
||||
|
||||
setComposerImages(nextImages);
|
||||
if (nextImages.length === 1 && nextImages[0]) {
|
||||
addComposerImage(nextImages[0]);
|
||||
} else if (nextImages.length > 1) {
|
||||
addComposerImagesToDraft(nextImages);
|
||||
}
|
||||
setThreadError(activeThreadId, error);
|
||||
};
|
||||
|
||||
const removeComposerImage = (imageId: string) => {
|
||||
setComposerImages((existing) => {
|
||||
const match = existing.find((image) => image.id === imageId);
|
||||
if (match?.previewUrl) {
|
||||
URL.revokeObjectURL(match.previewUrl);
|
||||
}
|
||||
return existing.filter((image) => image.id !== imageId);
|
||||
});
|
||||
removeComposerImageFromDraft(imageId);
|
||||
};
|
||||
|
||||
const onComposerPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
|
||||
@@ -1453,7 +1707,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (!trimmed && composerImages.length === 0) return;
|
||||
if (!activeProject) return;
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = activeThread.messages.length === 0;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
const baseBranchForWorktree =
|
||||
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
|
||||
? activeThread.branch
|
||||
@@ -1478,6 +1732,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const messageIdForSend = newMessageId();
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => ({
|
||||
type: "image" as const,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
})),
|
||||
);
|
||||
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
|
||||
type: "image" as const,
|
||||
id: image.id,
|
||||
@@ -1500,55 +1763,80 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
setThreadError(threadIdForSend, null);
|
||||
promptRef.current = "";
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
setComposerCursor(0);
|
||||
clearComposerDraftContent(threadIdForSend);
|
||||
setComposerHighlightedItemId(null);
|
||||
|
||||
let attemptedTurnStart = false;
|
||||
let createdServerThreadForLocalDraft = false;
|
||||
let turnStartSucceeded = false;
|
||||
let nextThreadBranch = activeThread.branch;
|
||||
let nextThreadWorktreePath = activeThread.worktreePath;
|
||||
try {
|
||||
// On first message: lock in branch + create worktree if needed.
|
||||
if (baseBranchForWorktree) {
|
||||
setSendPhase("preparing-worktree");
|
||||
const newBranch = `codething/${crypto.randomUUID().slice(0, 8)}`;
|
||||
const newBranch = buildTemporaryWorktreeBranchName();
|
||||
const result = await createWorktreeMutation.mutateAsync({
|
||||
cwd: activeProject.cwd,
|
||||
branch: baseBranchForWorktree,
|
||||
newBranch,
|
||||
});
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: threadIdForSend,
|
||||
branch: result.worktree.branch,
|
||||
worktreePath: result.worktree.path,
|
||||
});
|
||||
// Keep local thread state in sync immediately so terminal drawer opens
|
||||
// with the worktree cwd/env instead of briefly using the project root.
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: threadIdForSend,
|
||||
branch: result.worktree.branch,
|
||||
worktreePath: result.worktree.path,
|
||||
});
|
||||
const setupScript = setupProjectScript(activeProject.scripts);
|
||||
if (setupScript) {
|
||||
await runProjectScript(setupScript, {
|
||||
cwd: result.worktree.path,
|
||||
nextThreadBranch = result.worktree.branch;
|
||||
nextThreadWorktreePath = result.worktree.path;
|
||||
if (isServerThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: threadIdForSend,
|
||||
branch: result.worktree.branch,
|
||||
worktreePath: result.worktree.path,
|
||||
});
|
||||
// Keep local thread state in sync immediately so terminal drawer opens
|
||||
// with the worktree cwd/env instead of briefly using the project root.
|
||||
dispatch({
|
||||
type: "SET_THREAD_BRANCH",
|
||||
threadId: threadIdForSend,
|
||||
branch: result.worktree.branch,
|
||||
worktreePath: result.worktree.path,
|
||||
rememberAsLastInvoked: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const titleSeed =
|
||||
trimmed ||
|
||||
(composerImagesSnapshot.length > 0
|
||||
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
|
||||
: "New thread");
|
||||
const title = truncateTitle(titleSeed);
|
||||
|
||||
if (isLocalDraftThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.create",
|
||||
commandId: newCommandId(),
|
||||
threadId: threadIdForSend,
|
||||
projectId: activeProject.id,
|
||||
title,
|
||||
model: selectedModel ?? activeProject.model ?? DEFAULT_MODEL,
|
||||
branch: nextThreadBranch,
|
||||
worktreePath: nextThreadWorktreePath,
|
||||
createdAt: activeThread.createdAt,
|
||||
});
|
||||
createdServerThreadForLocalDraft = true;
|
||||
}
|
||||
|
||||
const setupScript = baseBranchForWorktree
|
||||
? setupProjectScript(activeProject.scripts)
|
||||
: null;
|
||||
if (setupScript && (isServerThread || createdServerThreadForLocalDraft)) {
|
||||
await runProjectScript(setupScript, {
|
||||
worktreePath: nextThreadWorktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
allowLocalDraftThread: createdServerThreadForLocalDraft,
|
||||
...(nextThreadWorktreePath ? { cwd: nextThreadWorktreePath } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-title from first message
|
||||
if (isFirstMessage) {
|
||||
const titleSeed =
|
||||
trimmed ||
|
||||
(composerImagesSnapshot.length > 0
|
||||
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
|
||||
: "New thread");
|
||||
const title = truncateTitle(titleSeed);
|
||||
if (isFirstMessage && isServerThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
@@ -1558,26 +1846,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
setSendPhase("sending-turn");
|
||||
const turnAttachments = await Promise.all(
|
||||
composerImagesSnapshot.map(
|
||||
async (
|
||||
image,
|
||||
): Promise<{
|
||||
type: "image";
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
dataUrl: string;
|
||||
}> => ({
|
||||
type: "image",
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
dataUrl: await readFileAsDataUrl(image.file),
|
||||
}),
|
||||
),
|
||||
);
|
||||
attemptedTurnStart = true;
|
||||
const turnAttachments = await turnAttachmentsPromise;
|
||||
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
|
||||
const sandboxMode =
|
||||
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
|
||||
@@ -1598,18 +1867,36 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
sandboxMode,
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
turnStartSucceeded = true;
|
||||
if (isFirstMessage) {
|
||||
clearDraftThread(threadIdForSend);
|
||||
}
|
||||
} catch (err) {
|
||||
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
|
||||
await api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
threadId: threadIdForSend,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
if (
|
||||
!attemptedTurnStart &&
|
||||
!turnStartSucceeded &&
|
||||
promptRef.current.length === 0 &&
|
||||
composerImagesRef.current.length === 0
|
||||
) {
|
||||
setOptimisticUserMessages((existing) =>
|
||||
existing.filter((message) => message.id !== messageIdForSend),
|
||||
);
|
||||
setOptimisticUserMessages((existing) => {
|
||||
const removed = existing.filter((message) => message.id === messageIdForSend);
|
||||
for (const message of removed) {
|
||||
revokeUserMessagePreviewUrls(message);
|
||||
}
|
||||
const next = existing.filter((message) => message.id !== messageIdForSend);
|
||||
return next.length === existing.length ? existing : next;
|
||||
});
|
||||
promptRef.current = trimmed;
|
||||
setPrompt(trimmed);
|
||||
setComposerImages(composerImagesSnapshot);
|
||||
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
|
||||
setComposerCursor(trimmed.length);
|
||||
}
|
||||
setThreadError(
|
||||
@@ -1665,33 +1952,45 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const onModelSelect = useCallback(
|
||||
(model: string) => {
|
||||
const normalizedModel = normalizeModelSlug(model);
|
||||
const resolvedModel = normalizedModel ?? baseThreadModel;
|
||||
setComposerDraftModel(threadId, resolvedModel === baseThreadModel ? null : resolvedModel);
|
||||
const api = readNativeApi();
|
||||
if (!activeThread) return;
|
||||
if (api) {
|
||||
if (api && isServerThread && activeThread) {
|
||||
void api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: activeThread.id,
|
||||
model: resolveModelSlug(model),
|
||||
model: resolvedModel,
|
||||
});
|
||||
}
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[activeThread, scheduleComposerFocus],
|
||||
[
|
||||
activeThread,
|
||||
baseThreadModel,
|
||||
isServerThread,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
threadId,
|
||||
],
|
||||
);
|
||||
const onEffortSelect = useCallback(
|
||||
(effort: ReasoningEffort) => {
|
||||
setSelectedEffort(effort);
|
||||
setComposerDraftEffort(threadId, effort);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus],
|
||||
[scheduleComposerFocus, setComposerDraftEffort, threadId],
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: "local" | "worktree") => {
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
setEnvMode(mode);
|
||||
if (isLocalDraftThread) {
|
||||
setDraftThreadContext(threadId, { envMode: mode });
|
||||
}
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus],
|
||||
[isLocalDraftThread, scheduleComposerFocus, setDraftThreadContext, threadId],
|
||||
);
|
||||
|
||||
const applyPromptReplacement = useCallback(
|
||||
@@ -1707,7 +2006,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerCursor(next.cursor);
|
||||
});
|
||||
},
|
||||
[],
|
||||
[setComposerCursor, setPrompt],
|
||||
);
|
||||
|
||||
const onSelectComposerItem = useCallback(
|
||||
@@ -1750,7 +2049,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
promptRef.current = nextPrompt;
|
||||
setPrompt(nextPrompt);
|
||||
setComposerCursor(nextCursor);
|
||||
}, []);
|
||||
}, [setComposerCursor, setPrompt]);
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (composerMenuOpen && composerMenuItems.length > 0) {
|
||||
@@ -1962,6 +2261,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-64 whitespace-normal leading-tight">
|
||||
Draft attachment could not be saved locally and may be lost on navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
|
||||
@@ -7,6 +7,8 @@ import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "luci
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -58,6 +60,29 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
[data-diffs-header] {
|
||||
position: sticky !important;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-bottom: 1px solid var(--border) !important;
|
||||
}
|
||||
|
||||
[data-title] {
|
||||
cursor: pointer;
|
||||
transition:
|
||||
color 120ms ease,
|
||||
text-decoration-color 120ms ease;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
[data-title]:hover {
|
||||
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
|
||||
text-decoration-color: currentColor;
|
||||
}
|
||||
`;
|
||||
|
||||
type RenderablePatch =
|
||||
@@ -144,6 +169,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -264,6 +291,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const openDiffFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
|
||||
console.warn("Failed to open diff file in editor.", error);
|
||||
});
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
@@ -508,7 +547,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -522,7 +561,17 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file rounded-md"
|
||||
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
const clickedHeader = composedPath.some((node) => {
|
||||
if (!(node instanceof Element)) return false;
|
||||
return node.hasAttribute("data-title");
|
||||
});
|
||||
if (!clickedHeader) return;
|
||||
openDiffFileInEditor(filePath);
|
||||
}}
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
@@ -539,7 +588,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
|
||||
@@ -20,8 +20,10 @@ import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
@@ -67,9 +69,11 @@ interface TerminalStatusIndicator {
|
||||
interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
tooltip: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
|
||||
type ThreadPr = GitStatusResult["pr"];
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
@@ -133,23 +137,31 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
|
||||
if (prState === "open") {
|
||||
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
|
||||
if (pr.state === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
tooltip: `#${pr.number} PR open: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (prState === "closed") {
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip: `#${pr.number} PR closed: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (prState === "merged") {
|
||||
if (pr.state === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
tooltip: `#${pr.number} PR merged: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
@@ -217,6 +229,19 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const clearProjectDraftThreadId = useComposerDraftStore(
|
||||
(store) => store.clearProjectDraftThreadId,
|
||||
);
|
||||
const clearProjectDraftThreadById = useComposerDraftStore(
|
||||
(store) => store.clearProjectDraftThreadById,
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const routeThreadId = useParams({
|
||||
@@ -254,15 +279,14 @@ export default function Sidebar() {
|
||||
[projectCwdById, state.threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
threadGitTargets
|
||||
.filter((target) => target.branch !== null)
|
||||
.map((target) => target.cwd)
|
||||
.filter((cwd): cwd is string => cwd !== null),
|
||||
),
|
||||
],
|
||||
() => [
|
||||
...new Set(
|
||||
threadGitTargets
|
||||
.filter((target) => target.branch !== null)
|
||||
.map((target) => target.cwd)
|
||||
.filter((cwd): cwd is string => cwd !== null),
|
||||
),
|
||||
],
|
||||
[threadGitTargets],
|
||||
);
|
||||
const threadGitStatusQueries = useQueries({
|
||||
@@ -272,7 +296,7 @@ export default function Sidebar() {
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prStateByThreadId = useMemo(() => {
|
||||
const prByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
@@ -283,58 +307,109 @@ export default function Sidebar() {
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<ThreadId, ThreadPrState>();
|
||||
const map = new Map<ThreadId, ThreadPr>();
|
||||
for (const target of threadGitTargets) {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
|
||||
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Link opening is unavailable.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
projectId: ProjectId,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode?: DraftThreadEnvMode;
|
||||
},
|
||||
): Promise<void> => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return Promise.resolve();
|
||||
const hasBranchOption = options?.branch !== undefined;
|
||||
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 createdAt = new Date().toISOString();
|
||||
const model =
|
||||
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
|
||||
return (async () => {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.create",
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model,
|
||||
setProjectDraftThreadId(projectId, threadId, {
|
||||
createdAt,
|
||||
branch: options?.branch ?? 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({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
});
|
||||
})();
|
||||
},
|
||||
[dispatch, navigate, state.projects],
|
||||
[
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThreadByProjectId,
|
||||
navigate,
|
||||
getDraftThread,
|
||||
routeThreadId,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
@@ -484,6 +559,8 @@ export default function Sidebar() {
|
||||
commandId: newCommandId(),
|
||||
threadId,
|
||||
});
|
||||
clearComposerDraftForThread(threadId);
|
||||
clearProjectDraftThreadById(thread.projectId, thread.id);
|
||||
if (shouldNavigateToFallback) {
|
||||
if (fallbackThreadId) {
|
||||
void navigate({
|
||||
@@ -523,6 +600,8 @@ export default function Sidebar() {
|
||||
},
|
||||
[
|
||||
appSettings.confirmThreadDelete,
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
dispatch,
|
||||
navigate,
|
||||
removeWorktreeMutation,
|
||||
@@ -558,6 +637,11 @@ export default function Sidebar() {
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
const projectDraftThread = getDraftThreadByProjectId(projectId);
|
||||
if (projectDraftThread) {
|
||||
clearComposerDraftForThread(projectDraftThread.threadId);
|
||||
}
|
||||
clearProjectDraftThreadId(projectId);
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "project.delete",
|
||||
commandId: newCommandId(),
|
||||
@@ -573,7 +657,13 @@ export default function Sidebar() {
|
||||
});
|
||||
}
|
||||
},
|
||||
[state.projects, state.threads],
|
||||
[
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThreadByProjectId,
|
||||
state.projects,
|
||||
state.threads,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -581,8 +671,10 @@ export default function Sidebar() {
|
||||
const activeThread = routeThreadId
|
||||
? state.threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId);
|
||||
@@ -590,12 +682,16 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
|
||||
envMode:
|
||||
activeDraftThread?.envMode ??
|
||||
(activeThread?.worktreePath ? "worktree" : "local"),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -603,7 +699,7 @@ export default function Sidebar() {
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
|
||||
|
||||
const onCreateThreadClick = () => {
|
||||
if (state.projects.length === 0) {
|
||||
@@ -660,7 +756,7 @@ export default function Sidebar() {
|
||||
<SidebarGroup className="px-2 py-2">
|
||||
<SidebarMenu>
|
||||
{state.projects.map((project) => {
|
||||
const threads = state.threads
|
||||
const visibleThreads = state.threads
|
||||
.filter((thread) => thread.projectId === project.id)
|
||||
.toSorted((a, b) => {
|
||||
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
@@ -703,24 +799,26 @@ export default function Sidebar() {
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
|
||||
<span className="text-[10px] text-muted-foreground/60">
|
||||
{visibleThreads.length}
|
||||
</span>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent>
|
||||
<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 threadStatus = threadStatusPill(
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
||||
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
|
||||
return (
|
||||
<SidebarMenuSubItem key={thread.id} className="w-full">
|
||||
<SidebarMenuSubButton
|
||||
render={<button type="button" />}
|
||||
render={<div role="button" tabIndex={0} />}
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||
@@ -734,6 +832,14 @@ export default function Sidebar() {
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
}}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
void handleThreadContextMenu(thread.id, {
|
||||
@@ -743,6 +849,25 @@ export default function Sidebar() {
|
||||
}}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
|
||||
{prStatus && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={prStatus.tooltip}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
|
||||
onClick={(event) => {
|
||||
openPrLink(event, prStatus.url);
|
||||
}}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
|
||||
@@ -760,16 +885,6 @@ export default function Sidebar() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{prStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={prStatus.label}
|
||||
title={prStatus.label}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
|
||||
@@ -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
@@ -3,6 +3,7 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
|
||||
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
|
||||
|
||||
import ChatView from "../components/ChatView";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useMediaQuery } from "../hooks/useMediaQuery";
|
||||
import { useStore } from "../store";
|
||||
@@ -139,6 +140,10 @@ function ChatThreadRouteView() {
|
||||
});
|
||||
const search = Route.useSearch();
|
||||
const threadExists = state.threads.some((thread) => thread.id === threadId);
|
||||
const draftThreadExists = useComposerDraftStore(
|
||||
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
|
||||
);
|
||||
const routeThreadExists = threadExists || draftThreadExists;
|
||||
const diffOpen = search.diff === "1";
|
||||
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
|
||||
const closeDiff = useCallback(() => {
|
||||
@@ -166,13 +171,13 @@ function ChatThreadRouteView() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!threadExists) {
|
||||
if (!routeThreadExists) {
|
||||
void navigate({ to: "/", replace: true });
|
||||
return;
|
||||
}
|
||||
}, [navigate, state.threadsHydrated, threadExists, threadId]);
|
||||
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
|
||||
|
||||
if (!state.threadsHydrated || !threadExists) {
|
||||
if (!state.threadsHydrated || !routeThreadExists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -229,6 +229,10 @@ function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||
return `/attachments/${encodeURIComponent(attachmentId)}`;
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
|
||||
@@ -487,13 +491,13 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
}
|
||||
: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const attachments = message.attachments?.map((attachment, index) => ({
|
||||
const attachments = message.attachments?.map((attachment) => ({
|
||||
type: "image" as const,
|
||||
id: `${message.id}:${index}`,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
previewUrl: toAttachmentPreviewUrl(attachment.dataUrl),
|
||||
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
|
||||
}));
|
||||
const normalizedMessage: ChatMessage = {
|
||||
id: message.id,
|
||||
|
||||
@@ -88,16 +88,16 @@ describe("getOrphanedWorktreePathForThread", () => {
|
||||
describe("formatWorktreePathForDisplay", () => {
|
||||
it("shows only the last path segment for unix-like paths", () => {
|
||||
const result = formatWorktreePathForDisplay(
|
||||
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
|
||||
"/Users/julius/.t3/worktrees/t3code-mvp/t3code-4e609bb8",
|
||||
);
|
||||
expect(result).toBe("codething-4e609bb8");
|
||||
expect(result).toBe("t3code-4e609bb8");
|
||||
});
|
||||
|
||||
it("normalizes windows separators before selecting the final segment", () => {
|
||||
const result = formatWorktreePathForDisplay(
|
||||
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
|
||||
"C:\\Users\\julius\\.t3\\worktrees\\t3code-mvp\\t3code-4e609bb8",
|
||||
);
|
||||
expect(result).toBe("codething-4e609bb8");
|
||||
expect(result).toBe("t3code-4e609bb8");
|
||||
});
|
||||
|
||||
it("uses the final segment even when outside ~/.t3/worktrees", () => {
|
||||
|
||||
@@ -153,10 +153,9 @@ export function createWsNativeApi(): NativeApi {
|
||||
return;
|
||||
}
|
||||
|
||||
const popup = window.open(url, "_blank", "noopener,noreferrer");
|
||||
if (!popup) {
|
||||
throw new Error("Unable to open link. Allow popups and try again.");
|
||||
}
|
||||
// Some mobile browsers can return null here even when the tab opens.
|
||||
// Avoid false negatives and let the browser handle popup policy.
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
},
|
||||
},
|
||||
git: {
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"": {
|
||||
"name": "@t3tools/monorepo",
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
@@ -77,6 +79,7 @@
|
||||
"react-markdown": "^10.1.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"zustand": "^5.0.11",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
@@ -1415,6 +1418,8 @@
|
||||
|
||||
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
|
||||
"zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg=="],
|
||||
|
||||
"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
|
||||
|
||||
"@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
# Release Checklist
|
||||
|
||||
This document covers how to run desktop releases from one tag, first without signing, then with signing.
|
||||
|
||||
## What the workflow does
|
||||
|
||||
- Trigger: push tag matching `v*.*.*`.
|
||||
- Runs quality gates first: lint, typecheck, test.
|
||||
- Builds four artifacts in parallel:
|
||||
- macOS `arm64` DMG
|
||||
- macOS `x64` DMG
|
||||
- Linux `x64` AppImage
|
||||
- Windows `x64` NSIS installer
|
||||
- Publishes one GitHub Release with all produced files.
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
|
||||
- Signing is optional and auto-detected per platform from secrets.
|
||||
|
||||
## 0) npm OIDC trusted publishing setup (CLI)
|
||||
|
||||
The workflow publishes the CLI with `bun publish` from `apps/server` after bumping
|
||||
the package version to the release tag version.
|
||||
|
||||
Checklist:
|
||||
|
||||
1. Confirm npm org/user owns package `t3` (or rename package first if needed).
|
||||
2. In npm package settings, configure Trusted Publisher:
|
||||
- Provider: GitHub Actions
|
||||
- Repository: this repo
|
||||
- Workflow file: `.github/workflows/release.yml`
|
||||
- Environment (if used): match your npm trusted publishing config
|
||||
3. Ensure npm account and org policies allow trusted publishing for the package.
|
||||
4. Create release tag `vX.Y.Z` and push; workflow will:
|
||||
- set `apps/server/package.json` version to `X.Y.Z`
|
||||
- build web + server
|
||||
- run `bun publish --access public`
|
||||
|
||||
## 1) Dry-run release without signing
|
||||
|
||||
Use this first to validate the release pipeline.
|
||||
|
||||
1. Confirm no signing secrets are required for this test.
|
||||
2. Create a test tag:
|
||||
- `git tag v0.0.0-test.1`
|
||||
- `git push origin v0.0.0-test.1`
|
||||
3. Wait for `.github/workflows/release.yml` to finish.
|
||||
4. Verify the GitHub Release contains all platform artifacts.
|
||||
5. Download each artifact and sanity-check installation on each OS.
|
||||
|
||||
## 2) Apple signing + notarization setup (macOS)
|
||||
|
||||
Required secrets used by the workflow:
|
||||
|
||||
- `CSC_LINK`
|
||||
- `CSC_KEY_PASSWORD`
|
||||
- `APPLE_API_KEY`
|
||||
- `APPLE_API_KEY_ID`
|
||||
- `APPLE_API_ISSUER`
|
||||
|
||||
Checklist:
|
||||
|
||||
1. Apple Developer account access:
|
||||
- Team has rights to create Developer ID certificates.
|
||||
2. Create `Developer ID Application` certificate.
|
||||
3. Export certificate + private key as `.p12` from Keychain.
|
||||
4. Base64-encode the `.p12` and store as `CSC_LINK`.
|
||||
5. Store the `.p12` export password as `CSC_KEY_PASSWORD`.
|
||||
6. In App Store Connect, create an API key (Team key).
|
||||
7. Add API key values:
|
||||
- `APPLE_API_KEY`: contents of the downloaded `.p8`
|
||||
- `APPLE_API_KEY_ID`: Key ID
|
||||
- `APPLE_API_ISSUER`: Issuer ID
|
||||
8. Re-run a tag release and confirm macOS artifacts are signed/notarized.
|
||||
|
||||
Notes:
|
||||
|
||||
- `APPLE_API_KEY` is stored as raw key text in secrets.
|
||||
- The workflow writes it to a temporary `AuthKey_<id>.p8` file at runtime.
|
||||
|
||||
## 3) Azure Trusted Signing setup (Windows)
|
||||
|
||||
Required secrets used by the workflow:
|
||||
|
||||
- `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`
|
||||
|
||||
Checklist:
|
||||
|
||||
1. Create Azure Trusted Signing account and certificate profile.
|
||||
2. Record ATS values:
|
||||
- Endpoint
|
||||
- Account name
|
||||
- Certificate profile name
|
||||
- Publisher name
|
||||
3. Create/choose an Entra app registration (service principal).
|
||||
4. Grant service principal permissions required by Trusted Signing.
|
||||
5. Create a client secret for the service principal.
|
||||
6. Add Azure secrets listed above in GitHub Actions secrets.
|
||||
7. Re-run a tag release and confirm Windows installer is signed.
|
||||
|
||||
## 4) Ongoing release checklist
|
||||
|
||||
1. Ensure `main` is green in CI.
|
||||
2. Bump app version as needed.
|
||||
3. Create release tag: `vX.Y.Z`.
|
||||
4. Push tag.
|
||||
5. Verify workflow steps:
|
||||
- preflight passes
|
||||
- all matrix builds pass
|
||||
- release job uploads expected files
|
||||
6. Smoke test downloaded artifacts.
|
||||
|
||||
## 5) Troubleshooting
|
||||
|
||||
- macOS build unsigned when expected signed:
|
||||
- Check all Apple secrets are populated and non-empty.
|
||||
- Windows build unsigned when expected signed:
|
||||
- Check all Azure ATS and auth secrets are populated and non-empty.
|
||||
- Build fails with signing error:
|
||||
- Retry with secrets removed to confirm unsigned path still works.
|
||||
- Re-check certificate/profile names and tenant/client credentials.
|
||||
+9
-3
@@ -14,6 +14,7 @@
|
||||
"@effect/language-service": "0.75.1"
|
||||
}
|
||||
},
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "bun run scripts/dev-runner.mjs dev",
|
||||
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
|
||||
@@ -29,13 +30,18 @@
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"dist:desktop:dmg": "node scripts/build-desktop-dmg.mjs",
|
||||
"dist:desktop:dmg:arm64": "node scripts/build-desktop-dmg.mjs --arch arm64",
|
||||
"dist:desktop:dmg:x64": "node scripts/build-desktop-dmg.mjs --arch x64",
|
||||
"dist:desktop:artifact": "node scripts/build-desktop-artifact.ts",
|
||||
"dist:desktop:dmg": "node scripts/build-desktop-artifact.ts --platform mac --target dmg",
|
||||
"dist:desktop:dmg:arm64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch arm64",
|
||||
"dist:desktop:dmg:x64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch x64",
|
||||
"dist:desktop:linux": "node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64",
|
||||
"dist:desktop:win": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
|
||||
@@ -23,6 +23,8 @@ export type GitStatusPrState = typeof GitStatusPrState.Type;
|
||||
|
||||
export const GitBranch = Schema.Struct({
|
||||
name: TrimmedNonEmptyStringSchema,
|
||||
isRemote: Schema.optional(Schema.Boolean),
|
||||
remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
current: Schema.Boolean,
|
||||
isDefault: Schema.Boolean,
|
||||
worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
|
||||
@@ -60,12 +60,28 @@ export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
|
||||
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
|
||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
|
||||
export const CHAT_ATTACHMENT_ID_MAX_CHARS = 128;
|
||||
|
||||
// Correlation id is command id by design in this model.
|
||||
export const CorrelationId = CommandId;
|
||||
export type CorrelationId = typeof CorrelationId.Type;
|
||||
|
||||
export const ChatAttachmentId = TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS),
|
||||
Schema.isPattern(/^[a-z0-9_-]+$/i),
|
||||
);
|
||||
export type ChatAttachmentId = typeof ChatAttachmentId.Type;
|
||||
|
||||
export const ChatImageAttachment = Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
id: ChatAttachmentId,
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
|
||||
sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),
|
||||
});
|
||||
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
|
||||
|
||||
export const UploadChatImageAttachment = Schema.Struct({
|
||||
type: Schema.Literal("image"),
|
||||
name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),
|
||||
mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\//i)),
|
||||
@@ -74,10 +90,12 @@ export const ChatImageAttachment = Schema.Struct({
|
||||
Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
|
||||
),
|
||||
});
|
||||
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
|
||||
export type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;
|
||||
|
||||
export const ChatAttachment = Schema.Union([ChatImageAttachment]);
|
||||
export type ChatAttachment = typeof ChatAttachment.Type;
|
||||
export const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);
|
||||
export type UploadChatAttachment = typeof UploadChatAttachment.Type;
|
||||
|
||||
export const ProjectScriptIcon = Schema.Literals([
|
||||
"play",
|
||||
@@ -307,6 +325,24 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ClientThreadTurnStartCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.turn.start"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
message: Schema.Struct({
|
||||
messageId: MessageId,
|
||||
role: Schema.Literal("user"),
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(UploadChatAttachment),
|
||||
}),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
effort: Schema.optional(TrimmedNonEmptyString),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
approvalPolicy: ProviderApprovalPolicy,
|
||||
sandboxMode: ProviderSandboxMode,
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ThreadTurnInterruptCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.turn.interrupt"),
|
||||
commandId: CommandId,
|
||||
@@ -339,7 +375,7 @@ export const ThreadSessionStopCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
export const ClientOrchestrationCommand = Schema.Union([
|
||||
export const DispatchableClientOrchestrationCommand = Schema.Union([
|
||||
ProjectCreateCommand,
|
||||
ProjectMetaUpdateCommand,
|
||||
ProjectDeleteCommand,
|
||||
@@ -352,6 +388,22 @@ export const ClientOrchestrationCommand = Schema.Union([
|
||||
ThreadCheckpointRevertCommand,
|
||||
ThreadSessionStopCommand,
|
||||
]);
|
||||
export type DispatchableClientOrchestrationCommand =
|
||||
typeof DispatchableClientOrchestrationCommand.Type;
|
||||
|
||||
export const ClientOrchestrationCommand = Schema.Union([
|
||||
ProjectCreateCommand,
|
||||
ProjectMetaUpdateCommand,
|
||||
ProjectDeleteCommand,
|
||||
ThreadCreateCommand,
|
||||
ThreadDeleteCommand,
|
||||
ThreadMetaUpdateCommand,
|
||||
ClientThreadTurnStartCommand,
|
||||
ThreadTurnInterruptCommand,
|
||||
ThreadApprovalRespondCommand,
|
||||
ThreadCheckpointRevertCommand,
|
||||
ThreadSessionStopCommand,
|
||||
]);
|
||||
export type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;
|
||||
|
||||
export const ThreadSessionSetCommand = Schema.Struct({
|
||||
@@ -422,7 +474,7 @@ export const InternalOrchestrationCommand = Schema.Union([
|
||||
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
|
||||
|
||||
export const OrchestrationCommand = Schema.Union([
|
||||
ClientOrchestrationCommand,
|
||||
DispatchableClientOrchestrationCommand,
|
||||
InternalOrchestrationCommand,
|
||||
]);
|
||||
export type OrchestrationCommand = typeof OrchestrationCommand.Type;
|
||||
|
||||
@@ -0,0 +1,633 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import rootPackageJson from "../package.json" with { type: "json" };
|
||||
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
|
||||
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Config, Data, Effect, FileSystem, Logger, Option, Path, Schema } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { ChildProcess } from "effect/unstable/process";
|
||||
|
||||
const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
|
||||
const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
|
||||
);
|
||||
const IconSource = Effect.zipWith(RepoRoot, Effect.service(Path.Path), (repoRoot, path) =>
|
||||
path.join(repoRoot, "assets/macos-icon-1024.png"),
|
||||
);
|
||||
|
||||
interface PlatformConfig {
|
||||
readonly cliFlag: "--mac" | "--linux" | "--win";
|
||||
readonly defaultTarget: string;
|
||||
readonly archChoices: ReadonlyArray<typeof BuildArch.Type>;
|
||||
}
|
||||
|
||||
const PLATFORM_CONFIG: Record<typeof BuildPlatform.Type, PlatformConfig> = {
|
||||
mac: {
|
||||
cliFlag: "--mac",
|
||||
defaultTarget: "dmg",
|
||||
archChoices: ["arm64", "x64", "universal"],
|
||||
},
|
||||
linux: {
|
||||
cliFlag: "--linux",
|
||||
defaultTarget: "AppImage",
|
||||
archChoices: ["x64", "arm64"],
|
||||
},
|
||||
win: {
|
||||
cliFlag: "--win",
|
||||
defaultTarget: "nsis",
|
||||
archChoices: ["x64", "arm64"],
|
||||
},
|
||||
};
|
||||
|
||||
interface BuildCliInput {
|
||||
readonly platform: Option.Option<typeof BuildPlatform.Type>;
|
||||
readonly target: Option.Option<string>;
|
||||
readonly arch: Option.Option<typeof BuildArch.Type>;
|
||||
readonly buildVersion: Option.Option<string>;
|
||||
readonly outputDir: Option.Option<string>;
|
||||
readonly skipBuild: Option.Option<boolean>;
|
||||
readonly keepStage: Option.Option<boolean>;
|
||||
readonly signed: Option.Option<boolean>;
|
||||
readonly verbose: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
|
||||
if (hostPlatform === "darwin") return "mac";
|
||||
if (hostPlatform === "linux") return "linux";
|
||||
if (hostPlatform === "win32") return "win";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getDefaultArch(platform: typeof BuildPlatform.Type): typeof BuildArch.Type {
|
||||
const config = PLATFORM_CONFIG[platform];
|
||||
if (!config) {
|
||||
return "x64";
|
||||
}
|
||||
|
||||
if (process.arch === "arm64" && config.archChoices.includes("arm64")) {
|
||||
return "arm64";
|
||||
}
|
||||
if (process.arch === "x64" && config.archChoices.includes("x64")) {
|
||||
return "x64";
|
||||
}
|
||||
|
||||
return config.archChoices[0] ?? "x64";
|
||||
}
|
||||
|
||||
class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
interface ResolvedBuildOptions {
|
||||
readonly platform: typeof BuildPlatform.Type;
|
||||
readonly target: string;
|
||||
readonly arch: typeof BuildArch.Type;
|
||||
readonly version: string | undefined;
|
||||
readonly outputDir: string;
|
||||
readonly skipBuild: boolean;
|
||||
readonly keepStage: boolean;
|
||||
readonly signed: boolean;
|
||||
readonly verbose: boolean;
|
||||
}
|
||||
|
||||
interface StagePackageJson {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
readonly private: true;
|
||||
readonly description: string;
|
||||
readonly author: string;
|
||||
readonly main: string;
|
||||
readonly build: Record<string, unknown>;
|
||||
readonly dependencies: Record<string, unknown>;
|
||||
readonly devDependencies: {
|
||||
readonly electron: string;
|
||||
};
|
||||
}
|
||||
|
||||
const AzureTrustedSigningOptionsConfig = Config.all({
|
||||
publisherName: Config.string("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
|
||||
endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
|
||||
certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
|
||||
codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
|
||||
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(
|
||||
Config.withDefault(() => "SHA256"),
|
||||
),
|
||||
timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
|
||||
Config.withDefault(() => "SHA256"),
|
||||
),
|
||||
timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
|
||||
Config.withDefault(() => "http://timestamp.acs.microsoft.com"),
|
||||
),
|
||||
});
|
||||
|
||||
const BuildEnvConfig = Config.all({
|
||||
platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
|
||||
target: Config.string("T3CODE_DESKTOP_TARGET").pipe(Config.option),
|
||||
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
|
||||
version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
|
||||
outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
|
||||
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(() => false)),
|
||||
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(() => false)),
|
||||
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(() => false)),
|
||||
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(() => false)),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
|
||||
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
|
||||
|
||||
const resolveBuildOptions = Effect.fn(function* (input: BuildCliInput) {
|
||||
const path = yield* Path.Path;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const env = yield* BuildEnvConfig.asEffect();
|
||||
|
||||
const platform = mergeOptions(
|
||||
input.platform,
|
||||
env.platform,
|
||||
detectHostBuildPlatform(process.platform),
|
||||
);
|
||||
|
||||
if (!platform) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Unsupported host platform '${process.platform}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
|
||||
const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform));
|
||||
const version = mergeOptions(input.buildVersion, env.version, undefined);
|
||||
const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release"));
|
||||
|
||||
const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
|
||||
const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
|
||||
const signed = resolveBooleanFlag(input.signed, env.signed);
|
||||
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
|
||||
|
||||
return {
|
||||
platform,
|
||||
target,
|
||||
arch,
|
||||
version,
|
||||
outputDir,
|
||||
skipBuild,
|
||||
keepStage,
|
||||
signed,
|
||||
verbose,
|
||||
} satisfies ResolvedBuildOptions;
|
||||
});
|
||||
|
||||
const commandOutputOptions = (verbose: boolean) =>
|
||||
({
|
||||
stdout: verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
}) as const;
|
||||
|
||||
const runCommand = Effect.fn(function* (command: ChildProcess.Command) {
|
||||
const exitCode = yield* ChildProcess.exitCode(command);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Command exited with non-zero exit code",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function generateMacIconSet(
|
||||
sourcePng: string,
|
||||
targetIcns: string,
|
||||
tmpRoot: string,
|
||||
path: Path.Path,
|
||||
verbose: boolean,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const iconsetDir = path.join(tmpRoot, "icon.iconset");
|
||||
yield* fs.makeDirectory(iconsetDir, { recursive: true });
|
||||
|
||||
const iconSizes = [16, 32, 128, 256, 512] as const;
|
||||
for (const size of iconSizes) {
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
|
||||
);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function stageMacIcons(stageResourcesDir: string, verbose: boolean) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const iconSource = yield* IconSource;
|
||||
if (!(yield* fs.exists(iconSource))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Production icon source is missing at ${iconSource}`,
|
||||
});
|
||||
}
|
||||
|
||||
const tmpRoot = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3code-icon-build-",
|
||||
});
|
||||
|
||||
const iconPngPath = path.join(stageResourcesDir, "icon.png");
|
||||
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
|
||||
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`sips -z 512 512 ${iconSource} --out ${iconPngPath}`,
|
||||
);
|
||||
|
||||
yield* generateMacIconSet(iconSource, iconIcnsPath, tmpRoot, path, verbose);
|
||||
});
|
||||
}
|
||||
|
||||
function validateBundledClientAssets(clientDir: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const indexPath = path.join(clientDir, "index.html");
|
||||
const indexHtml = yield* fs.readFileString(indexPath);
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const ref of refs) {
|
||||
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
|
||||
if (!normalizedRef) continue;
|
||||
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
|
||||
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
|
||||
|
||||
const ext = path.extname(normalizedRef);
|
||||
if (!ext) continue;
|
||||
|
||||
const relativePath = normalizedRef.replace(/^\/+/, "");
|
||||
const assetPath = path.join(clientDir, relativePath);
|
||||
if (!(yield* fs.exists(assetPath))) {
|
||||
missing.push(normalizedRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
const preview = missing.slice(0, 6).join(", ");
|
||||
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
|
||||
return yield* new BuildScriptError({
|
||||
message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function resolveCatalogDependencies(
|
||||
dependencies: Record<string, unknown>,
|
||||
catalog: Record<string, unknown>,
|
||||
dependencySourceLabel: string,
|
||||
): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(dependencies).map(([dependencyName, spec]) => {
|
||||
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
|
||||
return [dependencyName, spec];
|
||||
}
|
||||
|
||||
const catalogKey = spec.slice("catalog:".length).trim();
|
||||
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
|
||||
const resolvedSpec = catalog[lookupKey];
|
||||
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
|
||||
throw new BuildScriptError({
|
||||
message: `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. Expected key '${lookupKey}' in root workspace catalog.`,
|
||||
});
|
||||
}
|
||||
|
||||
return [dependencyName, resolvedSpec];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const createBuildConfig = Effect.fn(function* (
|
||||
platform: typeof BuildPlatform.Type,
|
||||
target: string,
|
||||
productName: string,
|
||||
signed: boolean,
|
||||
) {
|
||||
const buildConfig: Record<string, unknown> = {
|
||||
appId: "com.t3tools.t3code",
|
||||
productName,
|
||||
artifactName: "T3-Code-${version}-${arch}.${ext}",
|
||||
directories: {
|
||||
buildResources: "apps/desktop/resources",
|
||||
},
|
||||
};
|
||||
|
||||
if (platform === "mac") {
|
||||
buildConfig.mac = {
|
||||
target: [target],
|
||||
icon: "icon.icns",
|
||||
category: "public.app-category.developer-tools",
|
||||
};
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
buildConfig.linux = {
|
||||
target: [target],
|
||||
icon: "icon.png",
|
||||
category: "Development",
|
||||
};
|
||||
}
|
||||
|
||||
if (platform === "win") {
|
||||
const winConfig: Record<string, unknown> = {
|
||||
target: [target],
|
||||
icon: "icon.ico",
|
||||
};
|
||||
if (signed) {
|
||||
winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
|
||||
}
|
||||
buildConfig.win = winConfig;
|
||||
}
|
||||
|
||||
return buildConfig;
|
||||
});
|
||||
|
||||
const assertPlatformBuildResources = Effect.fn(function* (
|
||||
platform: typeof BuildPlatform.Type,
|
||||
stageResourcesDir: string,
|
||||
verbose: boolean,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
if (platform === "mac") {
|
||||
yield* stageMacIcons(stageResourcesDir, verbose);
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
const iconPath = path.join(stageResourcesDir, "icon.png");
|
||||
if (!(yield* fs.exists(iconPath))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing Linux icon at ${iconPath}`,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform === "win") {
|
||||
const iconPath = path.join(stageResourcesDir, "icon.ico");
|
||||
if (!(yield* fs.exists(iconPath))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing Windows icon at ${iconPath}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions) {
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
const platformConfig = PLATFORM_CONFIG[options.platform];
|
||||
if (!platformConfig) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Unsupported platform '${options.platform}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const electronVersion = desktopPackageJson.dependencies.electron;
|
||||
|
||||
const dependencies = serverPackageJson.dependencies;
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedDependencies = yield* Effect.try({
|
||||
try: () =>
|
||||
resolveCatalogDependencies(dependencies, rootPackageJson.workspaces.catalog, "apps/server"),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const appVersion = options.version ?? serverPackageJson.version;
|
||||
const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
|
||||
const stageRoot = yield* mkdir({
|
||||
prefix: `t3code-desktop-${options.platform}-stage-`,
|
||||
});
|
||||
|
||||
const stageAppDir = path.join(stageRoot, "app");
|
||||
const stageResourcesDir = path.join(stageAppDir, "apps/desktop/resources");
|
||||
const distDirs = {
|
||||
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
|
||||
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
|
||||
serverDist: path.join(repoRoot, "apps/server/dist"),
|
||||
};
|
||||
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
|
||||
|
||||
if (!options.skipBuild) {
|
||||
yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: repoRoot,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bun run build:desktop`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const [label, dir] of Object.entries(distDirs)) {
|
||||
if (!(yield* fs.exists(dir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!(yield* fs.exists(bundledClientEntry))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* validateBundledClientAssets(path.dirname(bundledClientEntry));
|
||||
|
||||
yield* fs.makeDirectory(path.join(stageAppDir, "apps/desktop"), { recursive: true });
|
||||
yield* fs.makeDirectory(path.join(stageAppDir, "apps/server"), { recursive: true });
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Staging release app...");
|
||||
yield* fs.copy(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"));
|
||||
yield* fs.copy(distDirs.desktopResources, stageResourcesDir);
|
||||
yield* fs.copy(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"));
|
||||
|
||||
yield* assertPlatformBuildResources(options.platform, stageResourcesDir, options.verbose);
|
||||
|
||||
const stagePackageJson: StagePackageJson = {
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
main: "apps/desktop/dist-electron/main.js",
|
||||
build: yield* createBuildConfig(
|
||||
options.platform,
|
||||
options.target,
|
||||
desktopPackageJson.productName ?? "T3 Code",
|
||||
options.signed,
|
||||
),
|
||||
dependencies: resolvedDependencies,
|
||||
devDependencies: {
|
||||
electron: electronVersion,
|
||||
},
|
||||
};
|
||||
|
||||
yield* fs.writeFileString(
|
||||
path.join(stageAppDir, "package.json"),
|
||||
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
|
||||
);
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: stageAppDir,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bun install --production`,
|
||||
);
|
||||
|
||||
const buildEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
};
|
||||
for (const [key, value] of Object.entries(buildEnv)) {
|
||||
if (value === "") {
|
||||
delete buildEnv[key];
|
||||
}
|
||||
}
|
||||
if (!options.signed) {
|
||||
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
|
||||
delete buildEnv.CSC_LINK;
|
||||
delete buildEnv.CSC_KEY_PASSWORD;
|
||||
delete buildEnv.APPLE_API_KEY;
|
||||
delete buildEnv.APPLE_API_KEY_ID;
|
||||
delete buildEnv.APPLE_API_ISSUER;
|
||||
}
|
||||
|
||||
yield* Effect.log(
|
||||
`[desktop-artifact] Building ${options.platform}/${options.target} (arch=${options.arch}, version=${appVersion})...`,
|
||||
);
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: stageAppDir,
|
||||
env: buildEnv,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bunx electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
|
||||
);
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
if (!(yield* fs.exists(stageDistDir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but dist directory was not found at ${stageDistDir}`,
|
||||
});
|
||||
}
|
||||
|
||||
const stageEntries = yield* fs.readDirectory(stageDistDir);
|
||||
yield* fs.makeDirectory(options.outputDir, { recursive: true });
|
||||
|
||||
const copiedArtifacts: string[] = [];
|
||||
for (const entry of stageEntries) {
|
||||
const from = path.join(stageDistDir, entry);
|
||||
const stat = yield* fs.stat(from).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!stat || stat.type !== "File") continue;
|
||||
|
||||
const to = path.join(options.outputDir, entry);
|
||||
yield* fs.copyFile(from, to);
|
||||
copiedArtifacts.push(to);
|
||||
}
|
||||
|
||||
if (copiedArtifacts.length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but no files were produced in ${stageDistDir}`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
|
||||
Effect.annotateLogs({ artifacts: copiedArtifacts }),
|
||||
);
|
||||
});
|
||||
|
||||
const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
|
||||
platform: Flag.choice("platform", BuildPlatform.literals).pipe(
|
||||
Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
|
||||
Flag.optional,
|
||||
),
|
||||
target: Flag.string("target").pipe(
|
||||
Flag.withDescription(
|
||||
"Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
arch: Flag.choice("arch", BuildArch.literals).pipe(
|
||||
Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
|
||||
Flag.optional,
|
||||
),
|
||||
buildVersion: Flag.string("build-version").pipe(
|
||||
Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),
|
||||
Flag.optional,
|
||||
),
|
||||
outputDir: Flag.string("output-dir").pipe(
|
||||
Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
|
||||
Flag.optional,
|
||||
),
|
||||
skipBuild: Flag.boolean("skip-build").pipe(
|
||||
Flag.withDescription(
|
||||
"Skip `bun run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
keepStage: Flag.boolean("keep-stage").pipe(
|
||||
Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
|
||||
Flag.optional,
|
||||
),
|
||||
signed: Flag.boolean("signed").pipe(
|
||||
Flag.withDescription(
|
||||
"Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
verbose: Flag.boolean("verbose").pipe(
|
||||
Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
|
||||
Flag.optional,
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Build a desktop artifact for T3 Code."),
|
||||
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
|
||||
);
|
||||
|
||||
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Logger.layer([Logger.consolePretty()])),
|
||||
Effect.provide(NodeServices.layer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,392 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const PRODUCTION_ICON_SOURCE = path.join(repoRoot, "assets/macos-icon-1024.png");
|
||||
|
||||
const ARCH_CHOICES = new Set(["arm64", "x64", "universal"]);
|
||||
|
||||
function printUsage() {
|
||||
console.log(`Build a shareable macOS .dmg for T3 Code desktop.
|
||||
|
||||
Usage:
|
||||
node scripts/build-desktop-dmg.mjs [options]
|
||||
|
||||
Options:
|
||||
--arch <arm64|x64|universal> Target arch (default: host arch if supported)
|
||||
--version <semver> App version in DMG metadata (default: apps/server version)
|
||||
--output-dir <path> Output folder for final artifacts (default: release)
|
||||
--skip-build Skip 'bun run build:desktop' (requires existing dist artifacts)
|
||||
--keep-stage Keep temporary staging directory
|
||||
--signed Allow automatic code signing discovery
|
||||
--help Show this message
|
||||
`);
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
console.error(`[desktop-dmg] ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const defaultArch = process.arch === "arm64" || process.arch === "x64" ? process.arch : "arm64";
|
||||
const options = {
|
||||
arch: defaultArch,
|
||||
version: null,
|
||||
skipBuild: false,
|
||||
keepStage: false,
|
||||
signed: false,
|
||||
outputDir: path.join(repoRoot, "release"),
|
||||
};
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === "--help") {
|
||||
options.help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--skip-build") {
|
||||
options.skipBuild = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--keep-stage") {
|
||||
options.keepStage = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--signed") {
|
||||
options.signed = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--arch" || arg === "--version" || arg === "--output-dir") {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.startsWith("--")) {
|
||||
fail(`Missing value for ${arg}`);
|
||||
}
|
||||
i += 1;
|
||||
if (arg === "--arch") options.arch = value;
|
||||
if (arg === "--version") options.version = value;
|
||||
if (arg === "--output-dir") options.outputDir = path.resolve(repoRoot, value);
|
||||
continue;
|
||||
}
|
||||
fail(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!ARCH_CHOICES.has(options.arch)) {
|
||||
fail(`Invalid arch '${options.arch}'. Expected one of: ${Array.from(ARCH_CHOICES).join(", ")}`);
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
async function readJson(filePath) {
|
||||
const raw = await fs.readFile(filePath, "utf8");
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
async function exists(filePath) {
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function run(command, args, { cwd, env = process.env, stdio = "inherit" } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd,
|
||||
env,
|
||||
stdio,
|
||||
});
|
||||
|
||||
child.on("error", reject);
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
reject(new Error(`${command} exited via signal ${signal}`));
|
||||
return;
|
||||
}
|
||||
if (code !== 0) {
|
||||
reject(new Error(`${command} exited with code ${code}`));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
|
||||
const iconsetDir = path.join(tmpRoot, "icon.iconset");
|
||||
await fs.mkdir(iconsetDir, { recursive: true });
|
||||
|
||||
const iconSizes = [16, 32, 128, 256, 512];
|
||||
for (const size of iconSizes) {
|
||||
await run(
|
||||
"sips",
|
||||
[
|
||||
"-z",
|
||||
String(size),
|
||||
String(size),
|
||||
sourcePng,
|
||||
"--out",
|
||||
path.join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
const retinaSize = size * 2;
|
||||
await run(
|
||||
"sips",
|
||||
[
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
sourcePng,
|
||||
"--out",
|
||||
path.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
}
|
||||
|
||||
await run("iconutil", ["-c", "icns", iconsetDir, "-o", targetIcns], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function stageProductionIcons(stageResourcesDir) {
|
||||
if (!(await exists(PRODUCTION_ICON_SOURCE))) {
|
||||
fail(`Production icon source is missing at ${PRODUCTION_ICON_SOURCE}`);
|
||||
}
|
||||
|
||||
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "t3code-icon-build-"));
|
||||
try {
|
||||
const iconPngPath = path.join(stageResourcesDir, "icon.png");
|
||||
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
|
||||
await run("sips", ["-z", "512", "512", PRODUCTION_ICON_SOURCE, "--out", iconPngPath], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
await generateMacIconSet(PRODUCTION_ICON_SOURCE, iconIcnsPath, tmpRoot);
|
||||
} finally {
|
||||
await fs.rm(tmpRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function validateBundledClientAssets(clientDir) {
|
||||
const indexPath = path.join(clientDir, "index.html");
|
||||
const indexHtml = await fs.readFile(indexPath, "utf8");
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map((match) => match[1]);
|
||||
const missing = [];
|
||||
|
||||
for (const ref of refs) {
|
||||
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
|
||||
if (!normalizedRef) continue;
|
||||
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
|
||||
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
|
||||
|
||||
const ext = path.extname(normalizedRef);
|
||||
if (!ext) continue;
|
||||
|
||||
const relativePath = normalizedRef.replace(/^\/+/, "");
|
||||
const assetPath = path.join(clientDir, relativePath);
|
||||
if (!(await exists(assetPath))) {
|
||||
missing.push(normalizedRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
const preview = missing.slice(0, 6).join(", ");
|
||||
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
|
||||
fail(
|
||||
`Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function readWorkspaceCatalog(rootPackageJson) {
|
||||
const workspaces = rootPackageJson?.workspaces;
|
||||
if (!workspaces || typeof workspaces !== "object" || Array.isArray(workspaces)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const catalog = workspaces.catalog;
|
||||
if (!catalog || typeof catalog !== "object" || Array.isArray(catalog)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return catalog;
|
||||
}
|
||||
|
||||
function resolveCatalogDependencies(dependencies, catalog, dependencySourceLabel) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(dependencies).map(([dependencyName, spec]) => {
|
||||
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
|
||||
return [dependencyName, spec];
|
||||
}
|
||||
|
||||
const catalogKey = spec.slice("catalog:".length).trim();
|
||||
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
|
||||
const resolvedSpec = catalog[lookupKey];
|
||||
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
|
||||
fail(
|
||||
`Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. ` +
|
||||
`Expected key '${lookupKey}' in root workspace catalog.`,
|
||||
);
|
||||
}
|
||||
|
||||
return [dependencyName, resolvedSpec];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
fail("This script only builds macOS .dmg artifacts and must run on macOS.");
|
||||
}
|
||||
|
||||
const rootPkg = await readJson(path.join(repoRoot, "package.json"));
|
||||
const desktopPkg = await readJson(path.join(repoRoot, "apps/desktop/package.json"));
|
||||
const serverPkg = await readJson(path.join(repoRoot, "apps/server/package.json"));
|
||||
|
||||
const electronVersion = desktopPkg.dependencies?.electron;
|
||||
if (typeof electronVersion !== "string" || electronVersion.length === 0) {
|
||||
fail("Could not resolve apps/desktop electron dependency version.");
|
||||
}
|
||||
|
||||
const dependencies = serverPkg.dependencies;
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
fail("Could not resolve production dependencies from apps/server/package.json.");
|
||||
}
|
||||
const resolvedDependencies = resolveCatalogDependencies(
|
||||
dependencies,
|
||||
readWorkspaceCatalog(rootPkg),
|
||||
"apps/server",
|
||||
);
|
||||
|
||||
const appVersion = options.version ?? serverPkg.version ?? "0.1.0";
|
||||
const stageRoot = path.join(os.tmpdir(), "t3code-desktop-dmg-stage");
|
||||
const stageAppDir = path.join(stageRoot, "app");
|
||||
const distDirs = {
|
||||
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
|
||||
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
|
||||
serverDist: path.join(repoRoot, "apps/server/dist"),
|
||||
};
|
||||
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
|
||||
|
||||
if (!options.skipBuild) {
|
||||
console.log("[desktop-dmg] Building desktop/server/web artifacts...");
|
||||
await run("bun", ["run", "build:desktop"], { cwd: repoRoot });
|
||||
}
|
||||
|
||||
for (const [label, dir] of Object.entries(distDirs)) {
|
||||
if (!(await exists(dir))) {
|
||||
fail(`Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`);
|
||||
}
|
||||
}
|
||||
if (!(await exists(bundledClientEntry))) {
|
||||
fail(
|
||||
`Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
|
||||
);
|
||||
}
|
||||
await validateBundledClientAssets(path.dirname(bundledClientEntry));
|
||||
|
||||
await fs.rm(stageRoot, { recursive: true, force: true });
|
||||
await fs.mkdir(path.join(stageAppDir, "apps/desktop"), { recursive: true });
|
||||
await fs.mkdir(path.join(stageAppDir, "apps/server"), { recursive: true });
|
||||
|
||||
console.log("[desktop-dmg] Staging release app...");
|
||||
await fs.cp(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"), {
|
||||
recursive: true,
|
||||
});
|
||||
await fs.cp(distDirs.desktopResources, path.join(stageAppDir, "apps/desktop/resources"), {
|
||||
recursive: true,
|
||||
});
|
||||
await fs.cp(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"), { recursive: true });
|
||||
await stageProductionIcons(path.join(stageAppDir, "apps/desktop/resources"));
|
||||
|
||||
const stagePackageJson = {
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
main: "apps/desktop/dist-electron/main.js",
|
||||
build: {
|
||||
appId: "com.t3tools.t3code",
|
||||
productName: desktopPkg.productName ?? "T3 Code",
|
||||
artifactName: "T3-Code-${version}-${arch}.${ext}",
|
||||
directories: {
|
||||
buildResources: "apps/desktop/resources",
|
||||
},
|
||||
mac: {
|
||||
target: ["dmg"],
|
||||
icon: "icon.icns",
|
||||
category: "public.app-category.developer-tools",
|
||||
},
|
||||
},
|
||||
dependencies: resolvedDependencies,
|
||||
devDependencies: {
|
||||
electron: electronVersion,
|
||||
},
|
||||
};
|
||||
|
||||
await fs.writeFile(
|
||||
path.join(stageAppDir, "package.json"),
|
||||
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
console.log("[desktop-dmg] Installing staged production dependencies...");
|
||||
await run("bun", ["install", "--production"], { cwd: stageAppDir });
|
||||
|
||||
const buildEnv = {
|
||||
...process.env,
|
||||
};
|
||||
if (!options.signed) {
|
||||
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
|
||||
}
|
||||
|
||||
const buildArgs = ["--bun", "electron-builder", "--mac", "dmg", `--${options.arch}`];
|
||||
console.log(`[desktop-dmg] Building .dmg (arch=${options.arch}, version=${appVersion})...`);
|
||||
await run("bunx", buildArgs, { cwd: stageAppDir, env: buildEnv });
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
const stageFiles = await fs.readdir(stageDistDir);
|
||||
const dmgFiles = stageFiles.filter((file) => file.endsWith(".dmg"));
|
||||
if (dmgFiles.length === 0) {
|
||||
fail(`Build completed but no .dmg found in ${stageDistDir}`);
|
||||
}
|
||||
|
||||
await fs.mkdir(options.outputDir, { recursive: true });
|
||||
const copiedArtifacts = [];
|
||||
for (const file of stageFiles) {
|
||||
if (!file.endsWith(".dmg") && !file.endsWith(".dmg.blockmap")) continue;
|
||||
const from = path.join(stageDistDir, file);
|
||||
const to = path.join(options.outputDir, file);
|
||||
await fs.copyFile(from, to);
|
||||
copiedArtifacts.push(to);
|
||||
}
|
||||
|
||||
if (!options.keepStage) {
|
||||
await fs.rm(stageRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
console.log("[desktop-dmg] Done. Artifacts:");
|
||||
for (const artifact of copiedArtifacts) {
|
||||
console.log(` - ${artifact}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
fail(message);
|
||||
});
|
||||
Reference in new issue
Block a user