Compare commits

..
Author SHA1 Message Date
Julius Marminge 150e171a88 Remove unused attachment route path helpers
- delete route-to-path conversion helpers from `attachmentPaths`
- remove unused `attachmentRoutePath` export and route prefix import
2026-03-01 19:49:26 -08:00
Julius Marminge 39f07869d9 Normalize attachment thread segments to lowercase
- Lowercase sanitized thread segments when creating attachment IDs
- Add coverage for mixed-case thread IDs in attachment store and projection pipeline tests
2026-03-01 19:18:41 -08:00
Julius Marminge afc0c78f0b Fix attachment cleanup to match exact thread segments
- Parse thread segments from attachment IDs using a UUID-aware pattern
- Prevent revert/delete cleanup from removing files belonging to similarly prefixed threads
- Add tests for prefix-collision cases in attachment store and projection pipeline
2026-03-01 19:01:47 -08:00
Julius Marminge dadda0d490 Reuse attachment thread segment sanitizer in projection pipeline
- export and reuse `toSafeThreadAttachmentSegment` from `attachmentStore`
- align projection attachment path logic with store-safe thread IDs
- update projection pipeline tests to cover thread IDs with spaces
2026-03-01 18:49:25 -08:00
Julius Marminge fb9274117c Read stdin before validating required image flag in codex test stub
- Move stdin capture earlier in fake codex script setup
- Ensure stdin-based assertions remain available even when image validation fails
2026-03-01 16:34:59 -08:00
Julius Marminge 88dc6c94aa Harden attachment ID resolution and missing-file handling
- Sanitize thread-derived attachment ID segments to safe, bounded tokens
- Resolve attachment IDs only when a matching file exists on disk
- Return 404 (not 400) for missing attachment IDs in the attachment route
- Add attachmentStore tests for ID sanitization and extension-based path lookup
2026-03-01 10:31:43 -08:00
Julius Marminge 585031572f Switch image attachments to persisted ID-based paths
- add attachment store helpers for IDs, route paths, and file resolution
- stop projection pipeline from mutating/storing data URLs; keep attachment metadata unchanged
- update Codex send/branch generation flows and tests to resolve images via attachment IDs
2026-03-01 01:42:02 -08:00
Julius Marmingeandcodex cd732a2b2e fix: address PR review feedback
Co-authored-by: codex <[email protected]>
2026-03-01 00:57:31 -08:00
Julius Marminge 875e6edcf2 Inject test ServerConfig across orchestration and git layers
- add `ServerConfig.layerTest(cwd, stateDir)` to standardize test wiring
- require `ServerConfig` in `CodexTextGeneration` attachment path resolution
- update orchestration/projection tests and harness to use managed runtimes with explicit config
2026-03-01 00:38:27 -08:00
Julius Marminge e1a8ee189a Handle parameterized base64 image data URLs
- accept `data:image/...;...;base64,...` headers while still rejecting invalid formats
- add `imageMime` tests for mime params, non-base64 URLs, and missing mime types
- fork branch-generation prompt effect at call site in `ProviderCommandReactor`
2026-02-28 23:53:19 -08:00
Julius Marminge e64ad4b2c7 Use Effect Schema to decode Codex structured outputs
- Replace manual JSON schema constants and parse helpers with `Schema.Struct` definitions
- Generate JSON Schema from Effect Schema and decode output via `Schema.fromJsonString`
- Map `SchemaError` to `TextGenerationError` for invalid Codex responses
- Update `ProviderCommandReactor` test mock typing for `generateBranchName`
2026-02-28 23:43:32 -08:00
Julius Marminge 0e146e22fb Handle branch-name generation failures as typed errors
- Make branch-name generation return a required string instead of nullable output
- Propagate invalid Codex branch payloads as `TextGenerationError` instead of silently falling back
- Update provider command reactor to catch generation failures, log warnings, and skip rename safely
2026-02-28 23:27:12 -08:00
Julius Marminge 700579bb3f fine there 2026-02-28 23:16:03 -08:00
Julius Marminge ad79b5a4a3 nit 2026-02-28 23:14:17 -08:00
Julius Marminge 4bc43a0e2b data uri for app server 2026-02-28 23:12:52 -08:00
Julius Marminge 44e409f9c6 nit 2026-02-28 23:05:58 -08:00
Julius Marminge d3d0a08237 Resolve persisted attachment paths across server pipelines
- add shared attachment path normalization and resolution helpers
- reuse persisted image files for turn start and branch name generation
- cover persisted attachment flow in text generation and reactor tests
2026-02-28 22:58:59 -08:00
Julius Marminge 9b0fe5efd0 Generate temporary worktree branch names from UUID tokens
- Remove message/time hashing for temporary branch names in `ChatView`
- Use an 8-char UUID token while preserving backend-detected suffix format
2026-02-28 22:39:56 -08:00
Julius Marminge 0df68cc73e Remove git.renameBranch RPC and harden branch rename args
- remove `git.renameBranch` from WS/contracts/native API surface and update server/web tests
- use `git branch -m -- ...` in GitCore to safely separate branch rename arguments
2026-02-28 22:35:09 -08:00
Julius Marminge 61e1babcc7 Scope upstream refresh in checkout effect lifecycle
- Replace fire-and-forget `Effect.runPromise` call with `Effect.forkScoped`
- Keep checkout responsive while tying upstream refresh to scoped effect management
2026-02-28 22:25:11 -08:00
Julius Marminge 06912c3222 Move worktree branch auto-rename into provider turn reactor
- Generate and rename temporary `t3code/*` worktree branches on first user turn in `ProviderCommandReactor`
- Remove websocket/client branch-generation RPCs and related contract/API surface
- Update Codex text-generation prompt to include attachment metadata only when attachments exist, with expanded tests
2026-02-28 22:16:24 -08:00
Julius Marminge 8416ecdb53 Add AI-generated worktree branch naming and safe branch rename
- add `git.generateBranchName`, `git.generateAndRenameBranch`, and `git.renameBranch` websocket flows
- pass image attachments into Codex branch-name generation and normalize/sanitize results
- add GitCore branch rename with collision-safe numeric suffixing
- extract shared image MIME/data-url helpers and expand server/web tests for new behavior
2026-02-28 22:01:48 -08:00
32 changed files with 793 additions and 5060 deletions

No files matched your search

-309
View File
@@ -1,309 +0,0 @@
name: Release Desktop
on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
inputs:
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: true
type: string
permissions:
contents: write
id-token: write
jobs:
preflight:
name: Preflight
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
ref: ${{ steps.release_ref.outputs.value }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Update version strings
if: github.event_name == 'workflow_dispatch'
env:
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
run: |
node --input-type=module -e '
import { readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
}
'
- name: Refresh lockfile
if: github.event_name == 'workflow_dispatch'
run: bun install
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
env:
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
run: |
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
echo "Tag $RELEASE_TAG already exists on origin." >&2
exit 1
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG" -m "Co-authored-by: codex <[email protected]>"
fi
git tag "$RELEASE_TAG"
git push origin "HEAD:${GITHUB_REF_NAME}"
git push origin "refs/tags/$RELEASE_TAG"
- id: release_ref
name: Resolve source ref
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.label }}
needs: preflight
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- label: macOS arm64
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
platform: win
target: nsis
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Build desktop artifact
shell: bash
env:
CSC_LINK: ${{ secrets.CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
args=(
--platform "${{ matrix.platform }}"
--target "${{ matrix.target }}"
--arch "${{ matrix.arch }}"
--build-version "${{ needs.preflight.outputs.version }}"
)
has_all() {
for value in "$@"; do
if [[ -z "$value" ]]; then
return 1
fi
done
return 0
}
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
echo "macOS signing enabled."
args+=(--signed)
else
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
"$AZURE_CLIENT_SECRET" \
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
echo "Windows signing enabled (Azure Trusted Signing)."
args+=(--signed)
else
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
fi
else
echo "Signing disabled for ${{ matrix.platform }}."
fi
bun run dist:desktop:artifact -- "${args[@]}"
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release/*
if-no-files-found: error
# publish_cli:
# name: Publish CLI to npm
# needs: [preflight, build]
# runs-on: ubuntu-24.04
# steps:
# - name: Checkout
# uses: actions/checkout@v4
# - name: Setup Bun
# uses: oven-sh/setup-bun@v2
# with:
# bun-version-file: package.json
# - name: Setup Node
# uses: actions/setup-node@v4
# with:
# node-version-file: package.json
# registry-url: https://registry.npmjs.org
# - name: Install dependencies
# run: bun install --frozen-lockfile
# - name: Set CLI package version from release tag
# env:
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
# run: |
# node --input-type=module -e '
# import { readFileSync, writeFileSync } from "node:fs";
# const packagePath = "apps/server/package.json";
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
# packageJson.version = process.env.RELEASE_VERSION;
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
# '
# - name: Build CLI package
# run: bun run build --filter=@t3tools/web --filter=t3
# - name: Publish CLI package
# run: bun --cwd apps/server publish --access public
release:
name: Publish GitHub Release
needs: [preflight, build]
# needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
path: release-assets
- name: Publish release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
files: release-assets/*
fail_on_unmatched_files: true
+1 -5
View File
@@ -1,9 +1,5 @@
# CLAUDE.md
## Task Completion Requirements
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
@@ -22,7 +18,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 effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex App Server (Important)
-12
View File
@@ -75,11 +75,8 @@ npx t3
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
### Desktop `.dmg` packaging notes
@@ -89,12 +86,6 @@ npx t3
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
### Running multiple dev instances
@@ -131,6 +122,3 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.0-alpha.4",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs"
},
-347
View File
@@ -274,18 +274,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
expect(result.branches.some((branch) => branch.current)).toBe(false);
}),
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -390,82 +378,6 @@ it.layer(TestLayer)("git integration", (it) => {
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
it.effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
const remoteOnlyBranch = "feature/remote-only";
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
);
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
).toBe(true);
expect(
result.branches.some(
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
),
).toBe(true);
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
const remoteName = "my-org/upstream";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", remoteName, remote]);
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
const remoteOnlyBranch = "feature/remote-with-remote-name";
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const remoteBranch = result.branches.find(
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
);
expect(remoteBranch).toBeDefined();
expect(remoteBranch?.isRemote).toBe(true);
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
});
// ── checkoutGitBranch ──
@@ -688,87 +600,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"does not silently checkout a local branch when a remote ref no longer exists",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["push", "-u", remoteName, featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
}),
);
it.effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
// Keep local branch but remove tracking so `--track origin/<branch>`
// would attempt to create an already-existing local branch.
yield* git(source, ["branch", "--unset-upstream"]);
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
const core = yield* GitCore;
const status = yield* core.statusDetails(source);
expect(status.branch).toBeNull();
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1272,135 +1103,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature commit"]);
const details = yield* core.statusDetails(tmp);
expect(details.branch).toBe("feature/no-upstream-ahead");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect(
"computes ahead count against origin/default when local default branch is missing",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of origin/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/remote-base-only");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("skipped_up_to_date");
expect(pushed.branch).toBe("feature/no-upstream-no-ahead");
expect(pushed.setUpstream).toBeUndefined();
}),
);
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(tmp, ["init", "--initial-branch=trunk"]);
yield* git(tmp, ["config", "user.email", "[email protected]"]);
yield* git(tmp, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
yield* git(tmp, ["add", "README.md"]);
yield* git(tmp, ["commit", "-m", "initial"]);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["checkout", "-b", "feature/no-base"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe("origin/feature/no-base");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/no-base",
);
}),
);
it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n");
yield* git(tmp, ["add", "default-ahead.txt"]);
yield* git(tmp, ["commit", "-m", "default ahead"]);
const featureBranch = "feature/publish-no-upstream";
yield* git(tmp, ["checkout", "-b", featureBranch]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`origin/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1582,54 +1284,5 @@ it.layer(TestLayer)("git integration", (it) => {
expect(didFailRecency).toBe(true);
}),
);
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
const realGitService = yield* GitService;
let didFailRemoteBranches = false;
let didFailRemoteNames = false;
const core = yield* makeIsolatedGitCore({
execute: (input) => {
if (input.args.join(" ") === "branch --no-color --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteBranches",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
if (input.args.join(" ") === "remote") {
didFailRemoteNames = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteNames",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
return realGitService.execute(input);
},
});
const result = yield* core.listBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
expect(didFailRemoteBranches).toBe(true);
expect(didFailRemoteNames).toBe(true);
}),
);
});
});
+24 -404
View File
@@ -7,7 +7,6 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
@@ -77,101 +76,10 @@ function parsePorcelainPath(line: string): string | null {
return filePath.length > 0 ? filePath : null;
}
function parseBranchLine(line: string): { name: string; current: boolean } | null {
const trimmed = line.trim();
if (trimmed.length === 0) return null;
const name = trimmed.replace(/^[*+]\s+/, "");
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
if (name.includes(" -> ") || name.startsWith("(")) return null;
return {
name,
current: trimmed.startsWith("* "),
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return null;
}
function parseTrackingBranchByUpstreamRef(
stdout: string,
upstreamRef: string,
): string | null {
for (const line of stdout.split("\n")) {
const trimmedLine = line.trim();
if (trimmedLine.length === 0) {
continue;
}
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
const branchName = branchNameRaw?.trim() ?? "";
const upstreamBranch = upstreamBranchRaw.trim();
if (branchName.length === 0 || upstreamBranch.length === 0) {
continue;
}
if (upstreamBranch === upstreamRef) {
return branchName;
}
}
return null;
}
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
const separatorIndex = branchName.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
return null;
}
const localBranch = branchName.slice(separatorIndex + 1).trim();
return localBranch.length > 0 ? localBranch : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
const trimmed = value.trim();
const prefix = "refs/remotes/origin/";
if (!trimmed.startsWith(prefix)) {
return null;
}
const branch = trimmed.slice(prefix.length).trim();
return branch.length > 0 ? branch : null;
}
function createGitCommandError(
operation: string,
cwd: string,
@@ -388,114 +296,12 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
allowNonZeroExit: true,
}).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
}),
);
const remoteBranchExists = (
cwd: string,
branch: string,
): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.remoteBranchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
{
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0));
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const resolveBaseBranchForNoUpstream = (
cwd: string,
branch: string,
): Effect.Effect<string | null, GitCommandError> =>
Effect.gen(function* () {
const configuredBaseBranch = yield* runGitStdout(
"GitCore.resolveBaseBranchForNoUpstream.config",
cwd,
["config", "--get", `branch.${branch}.gh-merge-base`],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const defaultBranch = yield* resolveDefaultBranchName(cwd);
const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch,
...DEFAULT_BASE_BRANCH_CANDIDATES,
];
for (const candidate of candidates) {
if (!candidate) {
continue;
}
const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length)
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue;
}
if (yield* branchExists(cwd, normalizedCandidate)) {
return normalizedCandidate;
}
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
return `origin/${normalizedCandidate}`;
}
}
return null;
});
const computeAheadCountAgainstBase = (
cwd: string,
branch: string,
): Effect.Effect<number, GitCommandError> =>
Effect.gen(function* () {
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
if (!baseBranch) {
return 0;
}
const result = yield* executeGit(
"GitCore.computeAheadCountAgainstBase",
cwd,
["rev-list", "--count", `${baseBranch}..HEAD`],
{ allowNonZeroExit: true },
);
if (result.code !== 0) {
return 0;
}
const parsed = Number.parseInt(result.stdout.trim(), 10);
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
});
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
Effect.gen(function* () {
const branchRecency = yield* executeGit(
"GitCore.readBranchRecency",
cwd,
[
"for-each-ref",
"--format=%(refname:short)%09%(committerdate:unix)",
"refs/heads",
"refs/remotes",
],
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
@@ -574,14 +380,6 @@ const makeGitCore = Effect.gen(function* () {
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
if (!upstreamRef && branch) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(0)),
);
behindCount = 0;
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
@@ -691,40 +489,12 @@ const makeGitCore = Effect.gen(function* () {
);
}
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
if (hasNoLocalDelta) {
if (details.hasUpstream) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (comparableBaseBranch) {
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (!hasOriginRemote) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (hasRemoteBranch) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
if (!details.hasUpstream) {
@@ -831,7 +601,7 @@ const makeGitCore = Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
);
const localBranchResult = yield* executeGit(
const result = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color"],
@@ -841,8 +611,8 @@ const makeGitCore = Effect.gen(function* () {
},
);
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
@@ -854,40 +624,7 @@ const makeGitCore = Effect.gen(function* () {
);
}
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const 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(
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
@@ -907,25 +644,11 @@ 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\//, "")
@@ -950,17 +673,19 @@ const makeGitCore = Effect.gen(function* () {
}
}
const localBranches = localBranchResult.stdout
const branches = result.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => ({
name: branch.name,
current: branch.current,
isRemote: false,
isDefault: branch.name === defaultBranch,
worktreePath: worktreeMap.get(branch.name) ?? null,
}))
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
@@ -972,43 +697,6 @@ const makeGitCore = Effect.gen(function* () {
return a.name.localeCompare(b.name);
});
const remoteBranches =
remoteBranchResult.code === 0
? remoteBranchResult.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => {
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
const remoteBranch: {
name: string;
current: boolean;
isRemote: boolean;
remoteName?: string;
isDefault: boolean;
worktreePath: string | null;
} = {
name: branch.name,
current: false,
isRemote: true,
isDefault: false,
worktreePath: null,
};
if (parsedRemoteRef) {
remoteBranch.remoteName = parsedRemoteRef.remoteName;
}
return remoteBranch;
})
.toSorted((a, b) => {
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
return a.name.localeCompare(b.name);
})
: [];
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true };
});
@@ -1088,75 +776,7 @@ const makeGitCore = Effect.gen(function* () {
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
Effect.gen(function* () {
const [localInputExists, remoteExists] = yield* Effect.all(
[
executeGit(
"GitCore.checkoutBranch.localInputExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
executeGit(
"GitCore.checkoutBranch.remoteExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
],
{ concurrency: "unbounded" },
);
const localTrackingBranch =
remoteExists
? yield* executeGit(
"GitCore.checkoutBranch.localTrackingBranch",
input.cwd,
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.map((result) =>
result.code === 0
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
: null,
),
)
: null;
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
const localTrackedBranchTargetExists =
remoteExists && localTrackedBranchCandidate
? yield* executeGit(
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0))
: false;
const checkoutArgs =
localInputExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch
? ["checkout", "--track", input.branch]
: remoteExists && localTrackingBranch
? ["checkout", localTrackingBranch]
: ["checkout", input.branch];
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
@@ -570,56 +570,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 77,
title: "Add no-upstream PR flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
baseRefName: "main",
headRefName: "feature/no-upstream-pr",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(result.pr.status).toBe("created");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("origin/feature/no-upstream-pr");
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/no-upstream-pr"),
),
).toBe(true);
}),
);
it.effect("skips push when branch is already up to date", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+1 -1
View File
@@ -111,7 +111,7 @@ export interface GitCoreShape {
) => Effect.Effect<string | null, GitCommandError>;
/**
* List local + remote branches and branch metadata.
* List local branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
@@ -27,8 +27,7 @@
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11"
"tailwind-merge": "^3.4.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -1,10 +1,6 @@
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
@@ -61,124 +57,3 @@ 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,54 +8,6 @@ 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,
+34 -90
View File
@@ -9,13 +9,8 @@ import {
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -44,35 +39,27 @@ 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 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 activeThread = state.threads.find((thread) => thread.id === threadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
const activeWorktreePath = activeThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode: "local" | "worktree" =
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
? "worktree"
: envMode;
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
const branches = branchesQuery.data?.branches ?? [];
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
@@ -97,14 +84,14 @@ export default function BranchToolbar({
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode: effectiveEnvMode,
envMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api && hasServerThread) {
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -113,30 +100,13 @@ export default function BranchToolbar({
worktreePath: null,
});
}
if (hasServerThread) {
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
return;
}
setDraftThreadContext(threadId, {
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}, [
activeThreadId,
activeWorktreePath,
activeThreadBranch,
queryBranches,
effectiveEnvMode,
dispatch,
hasServerThread,
setDraftThreadContext,
threadId,
]);
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
@@ -155,7 +125,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 = serverThread?.session?.sessionId;
const sessionId = activeThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
@@ -166,7 +136,7 @@ export default function BranchToolbar({
})
.catch(() => undefined);
}
if (api && hasServerThread) {
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -175,15 +145,7 @@ export default function BranchToolbar({
worktreePath,
});
}
if (hasServerThread) {
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
return;
}
setDraftThreadContext(threadId, {
branch,
worktreePath,
envMode: effectiveEnvMode,
});
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
const selectBranch = (branch: GitBranch) => {
@@ -191,7 +153,7 @@ export default function BranchToolbar({
if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
@@ -212,21 +174,10 @@ export default function BranchToolbar({
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
checkoutMutation.mutate(branch.name, {
onSuccess: async () => {
onSuccess: () => {
setThreadError(null);
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setThreadBranch(nextBranchName, activeWorktreePath);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
@@ -255,7 +206,7 @@ export default function BranchToolbar({
});
};
if (!activeThreadId || !activeProject) return null;
if (!activeThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
@@ -270,11 +221,9 @@ export default function BranchToolbar({
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={() =>
onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")
}
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
>
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
{envMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
@@ -284,7 +233,7 @@ export default function BranchToolbar({
autoHighlight
onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen}
value={activeThreadBranch}
value={activeThread.branch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
@@ -292,10 +241,10 @@ export default function BranchToolbar({
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate">
{activeThreadBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${activeThreadBranch}`
: activeThreadBranch
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<ChevronDownIcon />
@@ -334,28 +283,23 @@ 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 === activeThreadBranch ? "bg-accent text-foreground" : undefined
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</div>
</ComboboxItem>
);
+97 -416
View File
@@ -17,7 +17,6 @@ import {
type ProviderApprovalDecision,
type ThreadId,
type TurnId,
normalizeModelSlug,
resolveModelSlug,
} from "@t3tools/contracts";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
@@ -54,7 +53,7 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type Thread,
type ChatImageAttachment,
type TurnDiffSummary,
} from "../types";
import { basenameOfPath, getVscodeIconUrlForEntry } from "../vscode-icons";
@@ -112,14 +111,6 @@ 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 {
@@ -165,6 +156,11 @@ 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;
@@ -195,62 +191,6 @@ 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;
@@ -299,20 +239,6 @@ function buildTemporaryWorktreeBranchName(): string {
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";
@@ -446,44 +372,23 @@ export default function ChatView({ threadId }: ChatViewProps) {
const { resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
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 [prompt, setPrompt] = useState("");
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 [envMode, setEnvMode] = useState<DraftThreadEnvMode>("local");
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
const [envMode, setEnvMode] = useState<"local" | "worktree">("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>
@@ -497,55 +402,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const dragDepthRef = useRef(0);
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
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 activeThread = state.threads.find((t) => t.id === threadId);
const diffSearch = useMemo(
() => parseDiffRouteSearch(rawSearch as Record<string, unknown>),
[rawSearch],
@@ -556,19 +413,6 @@ 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;
@@ -590,9 +434,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
dispatch,
]);
const baseThreadModel = resolveModelSlug(activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL);
const selectedModel = resolveModelSlug(composerDraft.model ?? baseThreadModel);
const selectedEffort = composerDraft.effort ?? DEFAULT_REASONING;
const selectedModel = resolveModelSlug(
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
);
const modelOptions = useMemo(
() => getAppModelOptions(settings.customCodexModels, selectedModel),
[selectedModel, settings.customCodexModels],
@@ -801,10 +645,6 @@ 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 {};
@@ -853,6 +693,12 @@ 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;
@@ -942,12 +788,10 @@ 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;
@@ -1019,7 +863,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
},
[activeProject, activeThread, activeThreadId, dispatch, gitCwd, isServerThread],
[activeProject, activeThread, activeThreadId, dispatch, gitCwd],
);
const persistProjectScripts = useCallback(
async (input: {
@@ -1230,12 +1074,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThread?.id) {
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
}
return [];
});
setOptimisticUserMessages([]);
return;
}
if (activeThread.messages.length === 0) {
@@ -1243,98 +1082,32 @@ 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(() => {
promptRef.current = prompt;
}, [prompt]);
useEffect(() => {
setOptimisticUserMessages((existing) => {
for (const message of existing) {
revokeUserMessagePreviewUrls(message);
}
setComposerImages((existing) => {
revokePreviewUrls(existing);
return [];
});
setOptimisticUserMessages([]);
setPrompt("");
promptRef.current = "";
setSendPhase("idle");
setComposerCursor(0);
setComposerHighlightedItemId(null);
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [threadId]);
}, [activeThread?.id, revokePreviewUrls]);
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 () => {
cancelled = true;
revokePreviewUrls(composerImagesRef.current);
};
}, [
clearComposerDraftPersistedAttachments,
composerImages,
syncComposerDraftPersistedAttachments,
threadId,
]);
}, [revokePreviewUrls]);
const closeExpandedImage = useCallback(() => {
setExpandedImage(null);
@@ -1388,16 +1161,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
useEffect(() => {
if (!activeThread?.id) return;
if (activeWorktreePath) {
setEnvMode("worktree");
return;
}
if (isLocalDraftThread) {
setEnvMode(draftThread?.envMode ?? "local");
return;
}
setEnvMode("local");
}, [activeThread?.id, activeWorktreePath, draftThread?.envMode, isLocalDraftThread]);
setEnvMode(activeWorktreePath ? "worktree" : "local");
}, [activeThread?.id, activeWorktreePath]);
// Auto-resize textarea
useEffect(() => {
@@ -1533,32 +1298,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(threadId: ThreadId | null, error: string | null) => {
if (!threadId) return;
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({
type: "SET_ERROR",
threadId,
error,
});
},
[dispatch, state.threads],
[dispatch],
);
const addComposerImages = (files: File[]) => {
if (!activeThreadId || files.length === 0) return;
const nextImages: ComposerImageAttachment[] = [];
let nextImageCount = composerImagesRef.current.length;
const nextImages = [...composerImagesRef.current];
let error: string | null = null;
for (const file of files) {
if (!file.type.startsWith("image/")) {
@@ -1569,7 +1321,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
continue;
}
if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
if (nextImages.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
break;
}
@@ -1584,19 +1336,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
previewUrl,
file,
});
nextImageCount += 1;
}
if (nextImages.length === 1 && nextImages[0]) {
addComposerImage(nextImages[0]);
} else if (nextImages.length > 1) {
addComposerImagesToDraft(nextImages);
}
setComposerImages(nextImages);
setThreadError(activeThreadId, error);
};
const removeComposerImage = (imageId: string) => {
removeComposerImageFromDraft(imageId);
setComposerImages((existing) => {
const match = existing.find((image) => image.id === imageId);
if (match?.previewUrl) {
URL.revokeObjectURL(match.previewUrl);
}
return existing.filter((image) => image.id !== imageId);
});
};
const onComposerPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
@@ -1707,7 +1460,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
if (!trimmed && composerImages.length === 0) return;
if (!activeProject) return;
const threadIdForSend = activeThread.id;
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
const isFirstMessage = activeThread.messages.length === 0;
const baseBranchForWorktree =
isFirstMessage && envMode === "worktree" && !activeThread.worktreePath
? activeThread.branch
@@ -1763,13 +1516,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
setThreadError(threadIdForSend, null);
promptRef.current = "";
clearComposerDraftContent(threadIdForSend);
setPrompt("");
setComposerImages([]);
setComposerCursor(0);
setComposerHighlightedItemId(null);
let createdServerThreadForLocalDraft = false;
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
let attemptedTurnStart = false;
try {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
@@ -1780,63 +1532,39 @@ export default function ChatView({ threadId }: ChatViewProps) {
branch: baseBranchForWorktree,
newBranch,
});
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,
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,
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 && isServerThread) {
if (isFirstMessage) {
const titleSeed =
trimmed ||
(composerImagesSnapshot.length > 0
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
: "New thread");
const title = truncateTitle(titleSeed);
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -1847,6 +1575,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setSendPhase("sending-turn");
const turnAttachments = await turnAttachmentsPromise;
attemptedTurnStart = true;
const approvalPolicy = state.runtimeMode === "full-access" ? "never" : "on-request";
const sandboxMode =
state.runtimeMode === "full-access" ? "danger-full-access" : "workspace-write";
@@ -1867,36 +1596,18 @@ 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 (
!turnStartSucceeded &&
!attemptedTurnStart &&
promptRef.current.length === 0 &&
composerImagesRef.current.length === 0
) {
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;
});
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
promptRef.current = trimmed;
setPrompt(trimmed);
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
setComposerImages(composerImagesSnapshot);
setComposerCursor(trimmed.length);
}
setThreadError(
@@ -1952,45 +1663,33 @@ 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 (api && isServerThread && activeThread) {
if (!activeThread) return;
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThread.id,
model: resolvedModel,
model: resolveModelSlug(model),
});
}
scheduleComposerFocus();
},
[
activeThread,
baseThreadModel,
isServerThread,
scheduleComposerFocus,
setComposerDraftModel,
threadId,
],
[activeThread, scheduleComposerFocus],
);
const onEffortSelect = useCallback(
(effort: ReasoningEffort) => {
setComposerDraftEffort(threadId, effort);
setSelectedEffort(effort);
scheduleComposerFocus();
},
[scheduleComposerFocus, setComposerDraftEffort, threadId],
[scheduleComposerFocus],
);
const onEnvModeChange = useCallback(
(mode: DraftThreadEnvMode) => {
(mode: "local" | "worktree") => {
setEnvMode(mode);
if (isLocalDraftThread) {
setDraftThreadContext(threadId, { envMode: mode });
}
scheduleComposerFocus();
},
[isLocalDraftThread, scheduleComposerFocus, setDraftThreadContext, threadId],
[scheduleComposerFocus],
);
const applyPromptReplacement = useCallback(
@@ -2006,7 +1705,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
setComposerCursor(next.cursor);
});
},
[setComposerCursor, setPrompt],
[],
);
const onSelectComposerItem = useCallback(
@@ -2049,7 +1748,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) {
@@ -2261,24 +1960,6 @@ 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"
+3 -52
View File
@@ -7,8 +7,6 @@ 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";
@@ -60,29 +58,6 @@ const DIFF_PANEL_UNSAFE_CSS = `
border-block-color: var(--border) !important;
color: var(--foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-bottom: 1px solid var(--border) !important;
}
[data-title] {
cursor: pointer;
transition:
color 120ms ease,
text-decoration-color 120ms ease;
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
}
[data-title]:hover {
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
`;
type RenderablePatch =
@@ -169,8 +144,6 @@ 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(
@@ -291,18 +264,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
target?.scrollIntoView({ block: "nearest" });
}, [selectedFilePath, renderableFiles]);
const openDiffFileInEditor = useCallback(
(filePath: string) => {
const api = readNativeApi();
if (!api) return;
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
console.warn("Failed to open diff file in editor.", error);
});
},
[activeCwd],
);
const selectTurn = (turnId: TurnId) => {
if (!activeThread) return;
void navigate({
@@ -547,7 +508,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
) : renderablePatch.kind === "files" ? (
<Virtualizer
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
@@ -561,17 +522,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div
key={themedFileKey}
data-diff-file-path={filePath}
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
onClickCapture={(event) => {
const nativeEvent = event.nativeEvent as MouseEvent;
const composedPath = nativeEvent.composedPath?.() ?? [];
const clickedHeader = composedPath.some((node) => {
if (!(node instanceof Element)) return false;
return node.hasAttribute("data-title");
});
if (!clickedHeader) return;
openDiffFileInEditor(filePath);
}}
className="diff-render-file rounded-md"
>
<FileDiff
fileDiff={fileDiff}
@@ -588,7 +539,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
})}
</Virtualizer>
) : (
<div className="h-full overflow-auto p-2">
<div className="h-full overflow-auto px-3 py-2">
<div className="space-y-2">
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
@@ -4,8 +4,6 @@ import {
buildGitActionProgressStages,
buildMenuItems,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -516,20 +514,19 @@ describe("when: HEAD is detached and there are no local changes", () => {
});
describe("when: branch has no upstream configured", () => {
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
const quick = resolveQuickAction(
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
false,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Push",
hint: "No local commits to push.",
label: "Commit",
disabled: true,
});
});
it("resolveQuickAction opens PR when clean, no upstream, no local commits are ahead, and PR exists", () => {
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
@@ -546,9 +543,9 @@ describe("when: branch has no upstream configured", () => {
false,
);
assert.deepInclude(quick, {
kind: "open_pr",
label: "Open PR",
disabled: false,
kind: "show_hint",
label: "Commit",
disabled: true,
});
});
@@ -608,132 +605,6 @@ describe("when: branch has no upstream configured", () => {
},
]);
});
it("resolveQuickAction runs push and create PR when no upstream and commits are ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
aheadCount: 2,
pr: null,
}),
false,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Push & create PR",
disabled: false,
});
});
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: false,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
hasUpstream: false,
aheadCount: 0,
pr: null,
}),
false,
true,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Push",
hint: "No local commits to push.",
disabled: true,
});
});
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
hasUpstream: false,
aheadCount: 1,
pr: null,
}),
false,
true,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Push",
disabled: false,
});
});
it("buildMenuItems still disables push and create PR when branch is behind", () => {
const items = buildMenuItems(
status({
hasUpstream: false,
behindCount: 1,
aheadCount: 0,
pr: null,
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("requiresDefaultBranchConfirmation", () => {
@@ -745,53 +616,6 @@ describe("requiresDefaultBranchConfirmation", () => {
});
});
describe("resolveDefaultBranchActionDialogCopy", () => {
it("uses push-only copy when pushing without a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push",
branchName: "main",
includesCommit: false,
});
assert.deepEqual(copy, {
title: "Push to default branch?",
description:
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Push to main",
});
});
it("uses push-and-pr copy when creating a PR without a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push_pr",
branchName: "main",
includesCommit: false,
});
assert.deepEqual(copy, {
title: "Push & create PR from default branch?",
description:
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Push & create PR",
});
});
it("keeps commit copy when the action includes a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push_pr",
branchName: "main",
includesCommit: true,
});
assert.deepEqual(copy, {
title: "Commit, push & create PR from default branch?",
description:
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Commit, push & create PR",
});
});
});
describe("buildGitActionProgressStages", () => {
it("shows only push progress when push-only is forced", () => {
const stages = buildGitActionProgressStages({
@@ -908,20 +732,3 @@ describe("summarizeGitResult", () => {
});
});
});
describe("resolveAutoFeatureBranchName", () => {
const day = new Date("2026-03-01T12:00:00.000Z");
it("returns the base auto feature branch name when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
assert.equal(branch, "feature/stacked-20260301");
});
it("increments suffix when the base name already exists", () => {
const branch = resolveAutoFeatureBranchName(
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
day,
);
assert.equal(branch, "feature/stacked-20260301-3");
});
});
@@ -25,17 +25,8 @@ export interface GitQuickAction {
hint?: string;
}
export interface DefaultBranchActionDialogCopy {
title: string;
description: string;
continueLabel: string;
}
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
@@ -127,6 +118,7 @@ export function buildMenuItems(
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
gitStatus.hasUpstream &&
!isBehind;
const canOpenPr = !isBusy && hasOpenPr;
@@ -212,29 +204,6 @@ export function resolveQuickAction(
};
}
if (!gitStatus.hasUpstream) {
if (!isAhead) {
if (hasOpenPr) {
return { label: "Open PR", disabled: false, kind: "open_pr" };
}
return {
label: "Push",
disabled: true,
kind: "show_hint",
hint: "No local commits to push.",
};
}
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
};
}
if (isDiverged) {
return {
label: "Sync branch",
@@ -283,67 +252,3 @@ export function requiresDefaultBranchConfirmation(
if (!isDefaultBranch) return false;
return action === "commit_push" || action === "commit_push_pr";
}
export function resolveDefaultBranchActionDialogCopy(input: {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
}): DefaultBranchActionDialogCopy {
const branchLabel = input.branchName;
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
if (input.action === "commit_push") {
if (input.includesCommit) {
return {
title: "Commit & push to default branch?",
description: `This action will commit and push changes${suffix}`,
continueLabel: `Commit & push to ${branchLabel}`,
};
}
return {
title: "Push to default branch?",
description: `This action will push local commits${suffix}`,
continueLabel: `Push to ${branchLabel}`,
};
}
if (input.includesCommit) {
return {
title: "Commit, push & create PR from default branch?",
description: `This action will commit, push, and create a PR${suffix}`,
continueLabel: `Commit, push & create PR`,
};
}
return {
title: "Push & create PR from default branch?",
description: `This action will push local commits and create a PR${suffix}`,
continueLabel: "Push & create PR",
};
}
function formatDateForBranch(now: Date): string {
const year = now.getUTCFullYear();
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
const day = String(now.getUTCDate()).padStart(2, "0");
return `${year}${month}${day}`;
}
export function resolveAutoFeatureBranchName(
existingBranchNames: readonly string[],
now = new Date(),
): string {
const daySlug = formatDateForBranch(now);
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
const existingNames = new Set(existingBranchNames);
if (!existingNames.has(base)) {
return base;
}
let suffix = 2;
while (existingNames.has(`${base}-${suffix}`)) {
suffix += 1;
}
return `${base}-${suffix}`;
}
+141 -271
View File
@@ -8,11 +8,9 @@ import {
buildMenuItems,
type GitActionIconName,
type GitActionMenuItem,
type GitDialogAction,
type GitQuickAction,
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -34,7 +32,6 @@ import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitCreateBranchAndCheckoutMutationOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
@@ -50,17 +47,6 @@ interface GitActionsControlProps {
activeThreadId: ThreadId | null;
}
interface PendingDefaultBranchAction {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
commitMessage?: string;
forcePushOnlyProgress: boolean;
onConfirmed?: () => void;
}
type GitActionToastId = ReturnType<typeof toastManager.add>;
function getMenuActionDisabledReason(
item: GitActionMenuItem,
gitStatus: GitStatusResult | null,
@@ -111,15 +97,26 @@ function getMenuActionDisabledReason(
if (!isAhead) {
return "No local commits to include in a PR.";
}
if (!gitStatus.hasUpstream) {
return "Set an upstream branch before creating a PR.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before creating a PR.";
}
return "Create PR is currently unavailable.";
}
const COMMIT_DIALOG_TITLE = "Commit changes";
const COMMIT_DIALOG_DESCRIPTION =
"Review and confirm your commit. Leave the message blank to auto-generate one.";
const DIALOG_TITLE_BY_ACTION = {
commit: "Commit changes",
push: "Push branch",
create_pr: "Create pull request",
};
const DIALOG_DESCRIPTION_BY_ACTION = {
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
push: "Push this branch now.",
create_pr: "Create a pull request using generated title/body content.",
};
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
if (icon === "commit") return <GitCommitIcon />;
@@ -146,10 +143,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[activeThreadId],
);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
@@ -172,18 +167,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
);
const createBranchAndCheckoutMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isRunStackedActionRunning =
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isCreateBranchAndCheckoutRunning =
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning =
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -202,13 +191,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
? resolveDefaultBranchActionDialogCopy({
action: pendingDefaultBranchAction.action,
branchName: pendingDefaultBranchAction.branchName,
includesCommit: pendingDefaultBranchAction.includesCommit,
})
: null;
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
const api = readNativeApi();
if (!api) return false;
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
!gitStatusForActions?.branch
) {
return true;
}
return api.dialogs.confirm(
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[gitStatusForActions?.branch, isDefaultBranch],
);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
@@ -238,82 +237,43 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
});
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
isDefaultBranchOverride,
progressToastId,
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
}) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
const actionBranch = actionStatus?.branch ?? null;
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
if (
!skipDefaultBranchPrompt &&
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
actionBranch
) {
if (action !== "commit_push" && action !== "commit_push_pr") {
return;
}
setPendingDefaultBranchAction({
action,
branchName: actionBranch,
includesCommit,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
});
return;
}
const confirmed = await maybeConfirmPushToDefaultBranch(action);
if (!confirmed) return;
onConfirmed?.();
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
const pushTarget = gitStatusForActions?.branch
? `origin/${gitStatusForActions.branch}`
: undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
...(pushTarget ? { pushTarget } : {}),
});
const resolvedProgressToastId =
progressToastId ??
toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
if (progressToastId) {
toastManager.update(progressToastId, {
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
}
const progressToastId = toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(resolvedProgressToastId, {
toastManager.update(progressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
@@ -335,23 +295,19 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const existingOpenPrUrl =
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
const prUrl = result.pr.url ?? existingOpenPrUrl;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") &&
!!prUrl &&
!actionIsDefaultBranch;
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
const shouldOfferCreatePrCta =
action === "commit_push" &&
!prUrl &&
result.push.status === "pushed" &&
!actionIsDefaultBranch;
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
const closeResultToast = () => {
toastManager.close(resolvedProgressToastId);
toastManager.close(progressToastId);
};
toastManager.update(resolvedProgressToastId, {
toastManager.update(progressToastId, {
type: "success",
title: resultToast.title,
description: resultToast.description,
@@ -369,8 +325,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
@@ -393,11 +347,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
children: "Create PR",
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: "commit_push_pr",
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
setActiveDialogAction("create_pr");
},
},
}
@@ -405,7 +355,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
} catch (err) {
stopProgressUpdates();
toastManager.update(resolvedProgressToastId, {
toastManager.update(progressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
@@ -415,109 +365,17 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
},
[
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.pr,
isDefaultBranch,
maybeConfirmPushToDefaultBranch,
runImmediateGitActionMutation,
setPendingDefaultBranchAction,
threadToastData,
gitStatusForActions,
],
);
const continuePendingDefaultBranchAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction, runGitActionWithToast]);
const checkoutNewBranchAndRunAction = useCallback(
(actionParams: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
}) => {
const branchName = resolveAutoFeatureBranchName(
branchList?.branches.map((branch) => branch.name) ?? [],
);
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
const checkoutToastId = toastManager.add({
type: "loading",
title: `Creating ${branchName}...`,
timeout: 0,
data: threadToastData,
});
void checkoutPromise
.then(() => {
const statusOverride = gitStatusForActions
? {
...gitStatusForActions,
branch: branchName,
pr: null,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
}
: null;
return runGitActionWithToast({
...actionParams,
skipDefaultBranchPrompt: true,
statusOverride,
isDefaultBranchOverride: false,
progressToastId: checkoutToastId,
});
})
.catch((error) => {
toastManager.update(checkoutToastId, {
type: "error",
title: "Failed to checkout feature branch",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[
branchList?.branches,
createBranchAndCheckoutMutation,
gitStatusForActions,
runGitActionWithToast,
setActiveDialogAction,
threadToastData,
],
);
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
checkoutNewBranchAndRunAction({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
});
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
const runDialogActionOnNewBranch = useCallback(() => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
checkoutNewBranchAndRunAction({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
});
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
@@ -569,31 +427,30 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "commit_push_pr" });
return;
if (item.dialogAction) {
setActiveDialogAction(item.dialogAction);
}
setIsCommitDialogOpen(true);
},
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
[openExistingPr, runGitActionWithToast],
);
const runDialogAction = useCallback(() => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
if (!activeDialogAction) return;
const action: GitStackedAction =
activeDialogAction === "commit"
? "commit"
: activeDialogAction === "push"
? "commit_push"
: "commit_push_pr";
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
const forcePushOnlyProgress = activeDialogAction === "push";
setActiveDialogAction(null);
void runGitActionWithToast({
action: "commit",
action,
...(commitMessage ? { commitMessage } : {}),
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
});
}, [
dialogCommitMessage,
isCommitDialogOpen,
runGitActionWithToast,
setDialogCommitMessage,
setIsCommitDialogOpen,
]);
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
const openChangedFileInEditor = useCallback(
(filePath: string) => {
@@ -749,29 +606,68 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
)}
<Dialog
open={isCommitDialogOpen}
open={activeDialogAction !== null}
onOpenChange={(open) => {
if (!open) {
setIsCommitDialogOpen(false);
setActiveDialogAction(null);
setDialogCommitMessage("");
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
<DialogDescription>
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="flex items-center justify-between gap-2">
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
{isDefaultBranch && (
<span className="text-right text-warning text-xs">Warning: default branch</span>
)}
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
</span>
{activeDialogAction !== "commit" && (
<>
<span className="text-muted-foreground">Upstream</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasUpstream
? "No upstream configured"
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 &&
gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
: `Behind by ${gitStatusForActions.behindCount}`}
</span>
<span className="text-muted-foreground">Working tree</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
? "Clean"
: `${gitStatusForActions.workingTree.files.length} file(s)`}
</span>
<span className="text-muted-foreground">Diff</span>
<span className="font-mono">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
"none"
) : (
<>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</>
)}
</span>
</>
)}
</div>
<div className="space-y-1">
<p className="text-muted-foreground">Files</p>
@@ -811,61 +707,35 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
)}
</div>
</div>
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
{activeDialogAction === "commit" && (
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
)}
</DialogPanel>
<DialogFooter>
<Button
variant="outline"
size="sm"
onClick={() => {
setIsCommitDialogOpen(false);
setActiveDialogAction(null);
setDialogCommitMessage("");
}}
>
Cancel
</Button>
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
Commit on new branch
</Button>
<Button size="sm" onClick={runDialogAction}>
Commit
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<Dialog
open={pendingDefaultBranchAction !== null}
onOpenChange={(open) => {
if (!open) {
setPendingDefaultBranchAction(null);
}
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
</DialogTitle>
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
Abort
</Button>
<Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
</Button>
<Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
Checkout feature branch & continue
{activeDialogAction === "commit"
? "Commit"
: activeDialogAction === "push"
? "Push"
: "Create PR"}
</Button>
</DialogFooter>
</DialogPopup>
+59 -174
View File
@@ -20,10 +20,8 @@ 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,
@@ -69,11 +67,9 @@ interface TerminalStatusIndicator {
interface PrStatusIndicator {
label: "PR open" | "PR closed" | "PR merged";
colorClass: string;
tooltip: string;
url: string;
}
type ThreadPr = GitStatusResult["pr"];
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurn?.completedAt) return false;
@@ -137,31 +133,23 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
};
}
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
if (!pr) return null;
if (pr.state === "open") {
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
if (prState === "open") {
return {
label: "PR open",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
tooltip: `#${pr.number} PR open: ${pr.title}`,
url: pr.url,
};
}
if (pr.state === "closed") {
if (prState === "closed") {
return {
label: "PR closed",
colorClass: "text-zinc-500 dark:text-zinc-400/80",
tooltip: `#${pr.number} PR closed: ${pr.title}`,
url: pr.url,
};
}
if (pr.state === "merged") {
if (prState === "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;
@@ -229,19 +217,6 @@ 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({
@@ -279,14 +254,15 @@ 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({
@@ -296,7 +272,7 @@ export default function Sidebar() {
refetchInterval: 60_000,
})),
});
const prByThreadId = useMemo(() => {
const prStateByThreadId = useMemo(() => {
const statusByCwd = new Map<string, GitStatusResult>();
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
const cwd = threadGitStatusCwds[index];
@@ -307,109 +283,58 @@ export default function Sidebar() {
}
}
const map = new Map<ThreadId, ThreadPr>();
const map = new Map<ThreadId, ThreadPrState>();
for (const target of threadGitTargets) {
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
const branchMatches =
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
map.set(target.threadId, branchMatches ? status?.pr?.state ?? 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 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 api = readNativeApi();
if (!api) 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 () => {
setProjectDraftThreadId(projectId, threadId, {
createdAt,
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId,
projectId,
title: "New thread",
model,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
envMode: options?.envMode ?? "local",
createdAt,
});
// 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 },
});
})();
},
[
clearProjectDraftThreadId,
getDraftThreadByProjectId,
navigate,
getDraftThread,
routeThreadId,
setDraftThreadContext,
setProjectDraftThreadId,
],
[dispatch, navigate, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
@@ -559,8 +484,6 @@ export default function Sidebar() {
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
@@ -600,8 +523,6 @@ export default function Sidebar() {
},
[
appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
dispatch,
navigate,
removeWorktreeMutation,
@@ -637,11 +558,6 @@ 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(),
@@ -657,13 +573,7 @@ export default function Sidebar() {
});
}
},
[
clearComposerDraftForThread,
clearProjectDraftThreadId,
getDraftThreadByProjectId,
state.projects,
state.threads,
],
[state.projects, state.threads],
);
useEffect(() => {
@@ -671,10 +581,8 @@ 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 ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId);
@@ -682,16 +590,12 @@ export default function Sidebar() {
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? state.projects[0]?.id;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ??
(activeThread?.worktreePath ? "worktree" : "local"),
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
};
@@ -699,7 +603,7 @@ export default function Sidebar() {
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [getDraftThread, handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
const onCreateThreadClick = () => {
if (state.projects.length === 0) {
@@ -756,7 +660,7 @@ export default function Sidebar() {
<SidebarGroup className="px-2 py-2">
<SidebarMenu>
{state.projects.map((project) => {
const visibleThreads = state.threads
const threads = state.threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
@@ -799,26 +703,24 @@ 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">
{visibleThreads.length}
</span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
{visibleThreads.map((thread) => {
{threads.map((thread) => {
const isActive = routeThreadId === thread.id;
const threadStatus = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusIndicator(thread);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
render={<button type="button" />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
@@ -832,14 +734,6 @@ 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, {
@@ -849,25 +743,6 @@ 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}`}
@@ -885,6 +760,16 @@ 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"
-350
View File
@@ -1,350 +0,0 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
function makeImage(input: {
id: string;
previewUrl: string;
name?: string;
mimeType?: string;
sizeBytes?: number;
lastModified?: number;
}): ComposerImageAttachment {
const name = input.name ?? "image.png";
const mimeType = input.mimeType ?? "image/png";
const sizeBytes = input.sizeBytes ?? 4;
const lastModified = input.lastModified ?? 1_700_000_000_000;
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
type: mimeType,
lastModified,
});
return {
type: "image",
id: input.id,
name,
mimeType,
sizeBytes: file.size,
previewUrl: input.previewUrl,
file,
};
}
describe("composerDraftStore addImages", () => {
const threadId = ThreadId.makeUnsafe("thread-dedupe");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("deduplicates identical images in one batch by file signature", () => {
const first = makeImage({
id: "img-1",
previewUrl: "blob:first",
name: "same.png",
mimeType: "image/png",
sizeBytes: 12,
lastModified: 12345,
});
const duplicate = makeImage({
id: "img-2",
previewUrl: "blob:duplicate",
name: "same.png",
mimeType: "image/png",
sizeBytes: 12,
lastModified: 12345,
});
useComposerDraftStore.getState().addImages(threadId, [first, duplicate]);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-1"]);
expect(revokeSpy).toHaveBeenCalledWith("blob:duplicate");
});
it("deduplicates against existing images across calls by file signature", () => {
const first = makeImage({
id: "img-a",
previewUrl: "blob:a",
name: "same.png",
mimeType: "image/png",
sizeBytes: 9,
lastModified: 777,
});
const duplicateLater = makeImage({
id: "img-b",
previewUrl: "blob:b",
name: "same.png",
mimeType: "image/png",
sizeBytes: 9,
lastModified: 999,
});
useComposerDraftStore.getState().addImage(threadId, first);
useComposerDraftStore.getState().addImage(threadId, duplicateLater);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-a"]);
expect(revokeSpy).toHaveBeenCalledWith("blob:b");
});
it("does not revoke blob URLs that are still used by an accepted duplicate image", () => {
const first = makeImage({
id: "img-shared",
previewUrl: "blob:shared",
});
const duplicateSameUrl = makeImage({
id: "img-shared",
previewUrl: "blob:shared",
});
useComposerDraftStore.getState().addImages(threadId, [first, duplicateSameUrl]);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-shared"]);
expect(revokeSpy).not.toHaveBeenCalledWith("blob:shared");
});
});
describe("composerDraftStore clearComposerContent", () => {
const threadId = ThreadId.makeUnsafe("thread-clear");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("does not revoke blob preview URLs when clearing composer content", () => {
const first = makeImage({
id: "img-optimistic",
previewUrl: "blob:optimistic",
});
useComposerDraftStore.getState().addImage(threadId, first);
useComposerDraftStore.getState().clearComposerContent(threadId);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft).toBeUndefined();
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
});
});
describe("composerDraftStore project draft thread mapping", () => {
const projectId = ProjectId.makeUnsafe("project-a");
const otherProjectId = ProjectId.makeUnsafe("project-b");
const threadId = ThreadId.makeUnsafe("thread-a");
const otherThreadId = ThreadId.makeUnsafe("thread-b");
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("stores and reads project draft thread ids via actions", () => {
const store = useComposerDraftStore.getState();
expect(store.getDraftThreadByProjectId(projectId)).toBeNull();
expect(store.getDraftThread(threadId)).toBeNull();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toEqual({
threadId,
projectId,
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toEqual({
projectId,
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
createdAt: "2026-01-01T00:00:00.000Z",
});
});
it("clears only matching project draft mapping entries", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "hello");
store.clearProjectDraftThreadById(projectId, otherThreadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
threadId,
);
store.clearProjectDraftThreadById(projectId, threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears project draft mapping by project id", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "hello");
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears orphaned composer drafts when remapping a project to a new draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "orphan me");
store.setProjectDraftThreadId(projectId, otherThreadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
otherThreadId,
);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("keeps composer drafts when the thread is still mapped by another project", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setProjectDraftThreadId(otherProjectId, threadId);
store.setPrompt(threadId, "keep me");
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId).toBe(
threadId,
);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("clears draft registration independently", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.clearDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
});
it("updates branch context on an existing draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "main",
worktreePath: null,
});
store.setDraftThreadContext(threadId, {
branch: "feature/next",
worktreePath: "/tmp/feature-next",
});
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
threadId,
);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "feature/next",
worktreePath: "/tmp/feature-next",
envMode: "worktree",
});
});
it("preserves existing branch and worktree when setProjectDraftThreadId receives undefined", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "main",
worktreePath: "/tmp/main-worktree",
});
const runtimeUndefinedOptions = {
branch: undefined,
worktreePath: undefined,
} as unknown as {
branch?: string | null;
worktreePath?: string | null;
};
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "main",
worktreePath: "/tmp/main-worktree",
envMode: "worktree",
});
});
it("preserves worktree env mode without a worktree path", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "feature/base",
worktreePath: null,
envMode: "worktree",
});
const runtimeUndefinedOptions = {
branch: undefined,
worktreePath: undefined,
envMode: undefined,
} as unknown as {
branch?: string | null;
worktreePath?: string | null;
envMode?: "local" | "worktree";
};
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "feature/base",
worktreePath: null,
envMode: "worktree",
});
});
});
describe("composerDraftStore setModel", () => {
const threadId = ThreadId.makeUnsafe("thread-model");
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
const store = useComposerDraftStore.getState();
store.setModel(threadId, "gpt-5.3-codex");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe("gpt-5.3-codex");
});
});
File diff suppressed because it is too large. Load diff
+3 -8
View File
@@ -3,7 +3,6 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
import ChatView from "../components/ChatView";
import { useComposerDraftStore } from "../composerDraftStore";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
@@ -140,10 +139,6 @@ 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(() => {
@@ -171,13 +166,13 @@ function ChatThreadRouteView() {
return;
}
if (!routeThreadExists) {
if (!threadExists) {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, routeThreadExists, state.threadsHydrated, threadId]);
}, [navigate, state.threadsHydrated, threadExists, threadId]);
if (!state.threadsHydrated || !routeThreadExists) {
if (!state.threadsHydrated || !threadExists) {
return null;
}
+4 -3
View File
@@ -153,9 +153,10 @@ export function createWsNativeApi(): NativeApi {
return;
}
// 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");
const popup = window.open(url, "_blank", "noopener,noreferrer");
if (!popup) {
throw new Error("Unable to open link. Allow popups and try again.");
}
},
},
git: {
+4 -9
View File
@@ -5,8 +5,6 @@
"": {
"name": "@t3tools/monorepo",
"devDependencies": {
"@effect/platform-node": "catalog:",
"effect": "catalog:",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"turbo": "^2.3.3",
@@ -16,7 +14,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"dependencies": {
"electron": "40.6.0",
},
@@ -32,7 +30,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.0-alpha.4",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -60,7 +58,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@pierre/diffs": "^1.1.0-beta.16",
@@ -79,7 +77,6 @@
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11",
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -96,7 +93,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"dependencies": {
"effect": "catalog:",
},
@@ -1418,8 +1415,6 @@
"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
View File
@@ -1,125 +0,0 @@
# 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.
+3 -9
View File
@@ -14,7 +14,6 @@
"@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",
@@ -30,18 +29,13 @@
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
"build:contracts": "turbo run build --filter=@t3tools/contracts",
"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",
"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",
"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",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"private": true,
"files": [
"dist"
-2
View File
@@ -23,8 +23,6 @@ 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),
-635
View File
@@ -1,635 +0,0 @@
#!/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 buildVersion: 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,
buildVersion: 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,
);
+392
View File
@@ -0,0 +1,392 @@
#!/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);
});
+14 -165
View File
@@ -1,5 +1,4 @@
import { spawn } from "node:child_process";
import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -7,7 +6,6 @@ import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
@@ -211,133 +209,7 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
return output;
}
function portPairForOffset(offset) {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
async function canListenOnHost(port, host) {
return await new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", (error) => {
const code = error?.code;
if (code === "EADDRNOTAVAIL") {
// Host family unavailable on this machine (for example, no IPv6 loopback).
resolve(true);
return;
}
resolve(false);
});
server.once("listening", () => {
server.close(() => {
resolve(true);
});
});
server.listen({ host, port });
});
}
async function isPortAvailable(port) {
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
// so we don't pick a port that fails later on one address family.
const [ipv4, ipv6] = await Promise.all([
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
]);
return ipv4 && ipv6;
}
const defaultCheckPortAvailability = isPortAvailable;
export async function findFirstAvailableOffset({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability = defaultCheckPortAvailability,
}) {
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks = [];
if (requireServerPort) {
checks.push(checkPortAvailability(serverPort));
}
if (requireWebPort) {
checks.push(checkPortAvailability(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = await Promise.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
throw new Error(
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
);
}
export async function resolveModePortOffsets({
mode,
startOffset,
envOverrides,
checkPortAvailability,
}) {
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
}
export async function runDevRunner(argv = process.argv) {
export function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
@@ -346,49 +218,24 @@ export async function runDevRunner(argv = process.argv) {
}
const { offset, source } = resolveOffset();
const { serverOffset, webOffset } = await resolveModePortOffsets({
mode,
startOffset: offset,
envOverrides: parsedArgs.envOverrides,
});
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
const { webPort } = portPairForOffset(webOffset);
mergedEnvOverrides.PORT = String(webPort);
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
if (serverPort > 65535 || webPort > 65535) {
throw new Error(
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
);
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset: serverOffset,
envOverrides: mergedEnvOverrides,
offset,
envOverrides: parsedArgs.envOverrides,
});
const parsedServerPort = Number(env.T3CODE_PORT);
const parsedWebPort = Number(env.PORT);
if (
!Number.isInteger(parsedServerPort) ||
parsedServerPort < 1 ||
parsedServerPort > MAX_PORT ||
!Number.isInteger(parsedWebPort) ||
parsedWebPort < 1 ||
parsedWebPort > MAX_PORT
) {
throw new Error(
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
);
}
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
console.info(
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (parsedArgs.isDryRun) {
@@ -418,8 +265,10 @@ export async function runDevRunner(argv = process.argv) {
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
runDevRunner().catch((error) => {
try {
runDevRunner();
} catch (error) {
console.error("[dev-runner]", error);
process.exit(1);
});
}
}
-98
View File
@@ -3,9 +3,7 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
findFirstAvailableOffset,
parseDevRunnerArgs,
resolveModePortOffsets,
} from "./dev-runner.mjs";
describe("parseDevRunnerArgs", () => {
@@ -125,99 +123,3 @@ describe("createDevRunnerEnv", () => {
).toThrow("Invalid T3CODE_PORT override");
});
});
describe("findFirstAvailableOffset", () => {
it("returns the starting offset when required ports are available", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async () => true,
});
expect(offset).toBe(0);
});
it("advances until all required ports are available", async () => {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offset).toBe(2);
});
it("allows offsets where only non-required ports exceed max", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: async () => true,
});
expect(offset).toBe(59_803);
});
});
describe("resolveModePortOffsets", () => {
it("uses a shared fallback offset for dev mode", async () => {
const taken = new Set([3773, 5733]);
const offsets = await resolveModePortOffsets({
mode: "dev",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
const taken = new Set([5733]);
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
});
it("shifts only server offset for dev:server", async () => {
const taken = new Set([3773]);
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("respects explicit dev-url override for dev:web", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
it("respects explicit server port override for dev:server", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: { T3CODE_PORT: "4888" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
});