Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0f8c29b96 | ||
|
|
9e994c1469 | ||
|
|
c832b7c860 | ||
|
|
8bfc45d29d | ||
|
|
5c16da6fba | ||
|
|
39eea0dcfd | ||
|
|
37f0951239 | ||
|
|
b2edc7e996 | ||
|
|
6b55b07089 |
No files matched your search
@@ -1,222 +0,0 @@
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.value }}
|
||||
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
|
||||
|
||||
- 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
|
||||
|
||||
- id: version
|
||||
name: Resolve release version
|
||||
run: echo "value=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
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
|
||||
|
||||
- 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: ${{ github.ref_name }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
files: release-assets/*
|
||||
fail_on_unmatched_files: true
|
||||
@@ -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.
|
||||
@@ -266,18 +266,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();
|
||||
@@ -382,82 +370,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 ──
|
||||
@@ -680,87 +592,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();
|
||||
@@ -1322,54 +1153,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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -76,87 +76,6 @@ 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(" ")}`;
|
||||
}
|
||||
@@ -345,12 +264,7 @@ const makeGitCore = 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,
|
||||
@@ -479,7 +393,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
pr: null,
|
||||
openPr: null,
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -650,7 +564,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"],
|
||||
@@ -660,8 +574,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 };
|
||||
}
|
||||
@@ -673,40 +587,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",
|
||||
@@ -726,25 +607,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\//, "")
|
||||
@@ -769,17 +636,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;
|
||||
@@ -791,43 +660,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 };
|
||||
});
|
||||
|
||||
@@ -887,75 +719,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",
|
||||
});
|
||||
|
||||
@@ -297,7 +297,7 @@ function makeManager(input?: {
|
||||
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
|
||||
|
||||
it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
it.effect("status includes PR metadata when branch already has an open PR", () =>
|
||||
it.effect("status includes open PR metadata when branch already has an open PR", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -324,103 +324,17 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.pr).toEqual({
|
||||
expect(status.openPr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns merged PR state when latest PR was merged", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-merged-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-merged-pr",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-30T10:00:00Z",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-merged-pr");
|
||||
expect(status.pr).toEqual({
|
||||
number: 22,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-merged-pr",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 45,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/45",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "MERGED",
|
||||
mergedAt: "2026-01-31T10:00:00Z",
|
||||
updatedAt: "2026-02-01T10:00:00Z",
|
||||
},
|
||||
{
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-over-merged",
|
||||
state: "OPEN",
|
||||
updatedAt: "2026-01-30T10:00:00Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-over-merged");
|
||||
expect(status.pr).toEqual({
|
||||
number: 46,
|
||||
title: "Open PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-over-merged",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
|
||||
it.effect("status is resilient to gh lookup failures and returns openPr null", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
@@ -440,7 +354,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.pr).toBeNull();
|
||||
expect(status.openPr).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -16,62 +16,6 @@ interface OpenPrInfo {
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
interface PullRequestInfo extends OpenPrInfo {
|
||||
state: "open" | "closed" | "merged";
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function gitManagerError(operation: string, detail: string, cause?: unknown): GitManagerError {
|
||||
return new GitManagerError({
|
||||
operation,
|
||||
@@ -135,13 +79,12 @@ function extractBranchFromRef(ref: string): string {
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
function toStatusPr(pr: PullRequestInfo): {
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
state: "open" | "closed" | "merged";
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
@@ -149,7 +92,6 @@ function toStatusPr(pr: PullRequestInfo): {
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
state: pr.state,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -181,56 +123,10 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
url: first.url,
|
||||
baseRefName: first.baseRefName,
|
||||
headRefName: first.headRefName,
|
||||
state: "open",
|
||||
updatedAt: null,
|
||||
} satisfies PullRequestInfo;
|
||||
} satisfies OpenPrInfo;
|
||||
}),
|
||||
);
|
||||
|
||||
const findLatestPr = (cwd: string, branch: string) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* gitHubCli
|
||||
.execute({
|
||||
cwd,
|
||||
args: [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"all",
|
||||
"--limit",
|
||||
"20",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt",
|
||||
],
|
||||
})
|
||||
.pipe(Effect.map((result) => result.stdout));
|
||||
|
||||
const raw = stdout.trim();
|
||||
if (raw.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
|
||||
const parsed = parsePullRequestList(parsedJson).toSorted((a, b) => {
|
||||
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
|
||||
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
|
||||
return right - left;
|
||||
});
|
||||
|
||||
const latestOpenPr = parsed.find((pr) => pr.state === "open");
|
||||
if (latestOpenPr) {
|
||||
return latestOpenPr;
|
||||
}
|
||||
return parsed[0] ?? null;
|
||||
});
|
||||
|
||||
const resolveBaseBranch = (cwd: string, branch: string, upstreamRef: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
|
||||
@@ -362,10 +258,10 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) {
|
||||
const details = yield* gitCore.statusDetails(input.cwd);
|
||||
|
||||
const pr =
|
||||
details.branch !== null
|
||||
? yield* findLatestPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((latest) => (latest ? toStatusPr(latest) : null)),
|
||||
const openPr =
|
||||
details.branch && details.hasUpstream
|
||||
? yield* findOpenPr(input.cwd, details.branch).pipe(
|
||||
Effect.map((pr) => (pr ? toStatusOpenPr(pr) : null)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
)
|
||||
: null;
|
||||
@@ -377,7 +273,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
pr,
|
||||
openPr,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ import type {
|
||||
|
||||
import type { GitCommandError } from "../Errors.ts";
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,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,
|
||||
|
||||
@@ -1521,7 +1521,7 @@ describe("WebSocket Server", () => {
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
openPr: null,
|
||||
};
|
||||
|
||||
const status = vi.fn(() => Effect.succeed(statusResult));
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
expect(
|
||||
normalizeCustomModelSlugs([
|
||||
" custom/internal-model ",
|
||||
"gpt-5.3-codex",
|
||||
"5.3",
|
||||
"custom/internal-model",
|
||||
"",
|
||||
null,
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions(["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
"custom/internal-model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions([], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
name: "custom/selected-model",
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,7 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
@@ -18,16 +14,8 @@ const AppSettingsSchema = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
isCustom: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
|
||||
@@ -35,76 +23,6 @@ let listeners: Array<() => void> = [];
|
||||
let cachedRawSettings: string | null | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
): AppSettings["customCodexModels"] {
|
||||
const normalizedModels: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const candidate of models) {
|
||||
const normalized = normalizeModelSlug(candidate);
|
||||
if (
|
||||
!normalized ||
|
||||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
|
||||
BUILT_IN_MODEL_SLUGS.has(normalized) ||
|
||||
seen.has(normalized)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(normalized);
|
||||
normalizedModels.push(normalized);
|
||||
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizedModels;
|
||||
}
|
||||
|
||||
function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
customModels: readonly string[],
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom: false,
|
||||
}));
|
||||
const seen = new Set(options.map((option) => option.slug));
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels)) {
|
||||
if (seen.has(slug)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
seen.add(slug);
|
||||
options.push({
|
||||
slug,
|
||||
name: slug,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel);
|
||||
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
name: normalizedSelectedModel,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
@@ -117,7 +35,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
@@ -178,12 +96,10 @@ export function useAppSettings() {
|
||||
);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = normalizeAppSettings(
|
||||
Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
});
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -10,11 +10,7 @@ import {
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -59,7 +55,7 @@ export default function BranchToolbar({
|
||||
|
||||
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();
|
||||
@@ -178,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?.();
|
||||
},
|
||||
@@ -298,15 +283,6 @@ 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
|
||||
@@ -319,7 +295,11 @@ export default function BranchToolbar({
|
||||
>
|
||||
<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>
|
||||
);
|
||||
|
||||
@@ -6,9 +6,11 @@ import {
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
type MessageId,
|
||||
MODEL_OPTIONS,
|
||||
type ProjectId,
|
||||
type ProjectEntry,
|
||||
type ProjectScript,
|
||||
ModelSlug,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
REASONING_OPTIONS,
|
||||
@@ -110,7 +112,7 @@ import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { clamp } from "effect/Number";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
@@ -127,6 +129,12 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SEARCHABLE_MODEL_OPTIONS = MODEL_OPTIONS.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
searchSlug: slug.toLowerCase(),
|
||||
searchName: name.toLowerCase(),
|
||||
}));
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
const SCRIPT_TERMINAL_ROWS = 30;
|
||||
|
||||
@@ -208,7 +216,7 @@ type ComposerCommandItem =
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
model: string;
|
||||
model: ModelSlug;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
@@ -430,10 +438,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const modelOptions = useMemo(
|
||||
() => getAppModelOptions(settings.customCodexModels, selectedModel),
|
||||
[selectedModel, settings.customCodexModels],
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isSendBusy = sendPhase !== "idle";
|
||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||
@@ -610,26 +614,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
];
|
||||
}
|
||||
|
||||
return modelOptions
|
||||
.map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
searchSlug: slug.toLowerCase(),
|
||||
searchName: name.toLowerCase(),
|
||||
}))
|
||||
.filter(({ searchSlug, searchName }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return searchSlug.includes(query) || searchName.includes(query);
|
||||
})
|
||||
.map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model" as const,
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, modelOptions, workspaceEntries]);
|
||||
return SEARCHABLE_MODEL_OPTIONS.filter(({ searchSlug, searchName }) => {
|
||||
const query = composerTrigger.query.trim().toLowerCase();
|
||||
if (!query) return true;
|
||||
return searchSlug.includes(query) || searchName.includes(query);
|
||||
}).map(({ slug, name }) => ({
|
||||
id: `model:${slug}`,
|
||||
type: "model",
|
||||
model: slug,
|
||||
label: name,
|
||||
description: slug,
|
||||
}));
|
||||
}, [composerTrigger, workspaceEntries]);
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
@@ -1664,7 +1660,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
const onModelSelect = useCallback(
|
||||
(model: string) => {
|
||||
(model: ModelSlug) => {
|
||||
const api = readNativeApi();
|
||||
if (!activeThread) return;
|
||||
if (api) {
|
||||
@@ -2016,11 +2012,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 px-2.5 pb-2.5 sm:flex-nowrap sm:gap-0 sm:px-3 sm:pb-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible">
|
||||
{/* Model picker */}
|
||||
<ModelPicker
|
||||
model={selectedModel}
|
||||
options={modelOptions}
|
||||
onModelChange={onModelSelect}
|
||||
/>
|
||||
<ModelPicker model={selectedModel} onModelChange={onModelSelect} />
|
||||
|
||||
{/* Divider */}
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
@@ -2924,13 +2916,12 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
});
|
||||
|
||||
const ModelPicker = memo(function ModelPicker(props: {
|
||||
model: string;
|
||||
options: ReadonlyArray<{ slug: string; name: string }>;
|
||||
onModelChange: (model: string) => void;
|
||||
model: ModelSlug;
|
||||
onModelChange: (model: ModelSlug) => void;
|
||||
}) {
|
||||
return (
|
||||
<Select
|
||||
items={props.options.map((option) => ({ label: option.name, value: option.slug }))}
|
||||
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
|
||||
value={props.model}
|
||||
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
||||
>
|
||||
@@ -2938,7 +2929,7 @@ const ModelPicker = memo(function ModelPicker(props: {
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{props.options.map(({ slug, name }) => (
|
||||
{MODEL_OPTIONS.map(({ slug, name }) => (
|
||||
<SelectItem key={slug} value={slug}>
|
||||
{name}
|
||||
</SelectItem>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -20,7 +20,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
|
||||
hasUpstream: true,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
openPr: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -29,13 +29,12 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("resolveQuickAction opens the existing PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 10,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/10",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -46,13 +45,12 @@ describe("when: branch is clean and has an open PR", () => {
|
||||
it("buildMenuItems disables commit/push and enables open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 11,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/11",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -149,13 +147,12 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
aheadCount: 3,
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 13,
|
||||
title: "Open PR",
|
||||
url: "https://example.com/pr/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -167,13 +164,12 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
const items = buildMenuItems(
|
||||
status({
|
||||
aheadCount: 2,
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 12,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/12",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -208,7 +204,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
|
||||
|
||||
describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
it("resolveQuickAction pushes and creates a PR", () => {
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
|
||||
const quick = resolveQuickAction(status({ aheadCount: 2, openPr: null }), false);
|
||||
assert.deepInclude(quick, {
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
@@ -217,7 +213,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems enables push and create PR, with commit disabled", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 2, pr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 2, openPr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -250,14 +246,14 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
|
||||
describe("when: branch is clean, up to date, and has no open PR", () => {
|
||||
it("resolveQuickAction returns disabled no-action state", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
|
||||
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, openPr: null }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
|
||||
});
|
||||
|
||||
it("buildMenuItems disables commit, push, and create PR", () => {
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, pr: null }), false);
|
||||
const items = buildMenuItems(status({ aheadCount: 0, behindCount: 0, openPr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -294,7 +290,7 @@ describe("when: branch is behind upstream", () => {
|
||||
});
|
||||
|
||||
it("buildMenuItems disables push and create PR", () => {
|
||||
const items = buildMenuItems(status({ behindCount: 1, pr: null }), false);
|
||||
const items = buildMenuItems(status({ behindCount: 1, openPr: null }), false);
|
||||
assert.deepEqual(items, [
|
||||
{
|
||||
id: "commit",
|
||||
@@ -350,13 +346,12 @@ describe("when: working tree has local changes", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({
|
||||
hasWorkingTreeChanges: true,
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 16,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/16",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -416,7 +411,7 @@ describe("when: on default branch without open PR", () => {
|
||||
|
||||
it("resolveQuickAction returns push when branch is ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ branch: "main", aheadCount: 2, pr: null }),
|
||||
status({ branch: "main", aheadCount: 2, openPr: null }),
|
||||
false,
|
||||
true,
|
||||
);
|
||||
@@ -516,7 +511,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
|
||||
describe("when: branch has no upstream configured", () => {
|
||||
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
|
||||
const quick = resolveQuickAction(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepInclude(quick, {
|
||||
@@ -531,13 +526,12 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 14,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -554,13 +548,12 @@ describe("when: branch has no upstream configured", () => {
|
||||
status({
|
||||
hasUpstream: false,
|
||||
aheadCount: 1,
|
||||
pr: {
|
||||
openPr: {
|
||||
number: 15,
|
||||
title: "Existing PR",
|
||||
url: "https://example.com/pr/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/test",
|
||||
state: "open",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
@@ -575,7 +568,7 @@ describe("when: branch has no upstream configured", () => {
|
||||
|
||||
it("buildMenuItems disables push and create PR when no commits are ahead", () => {
|
||||
const items = buildMenuItems(
|
||||
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
|
||||
status({ hasUpstream: false, openPr: null, aheadCount: 0 }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(items, [
|
||||
|
||||
@@ -108,7 +108,7 @@ export function buildMenuItems(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const canCommit = !isBusy && hasChanges;
|
||||
const canPush = !isBusy && hasBranch && !hasChanges && !isBehind && gitStatus.aheadCount > 0;
|
||||
@@ -178,7 +178,7 @@ export function resolveQuickAction(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
const isDiverged = isAhead && isBehind;
|
||||
|
||||
@@ -58,7 +58,7 @@ function getMenuActionDisabledReason(
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasOpenPr = gitStatus.pr?.state === "open";
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const isAhead = gitStatus.aheadCount > 0;
|
||||
const isBehind = gitStatus.behindCount > 0;
|
||||
|
||||
@@ -219,7 +219,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
return;
|
||||
}
|
||||
const prUrl = gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : null;
|
||||
const prUrl = gitStatusForActions?.openPr?.url ?? null;
|
||||
if (!prUrl) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
@@ -236,7 +236,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
}, [gitStatusForActions?.openPr?.url, threadToastData]);
|
||||
const runGitActionWithToast = useCallback(
|
||||
async ({
|
||||
action,
|
||||
@@ -295,9 +295,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
stopProgressUpdates();
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const existingOpenPrUrl =
|
||||
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
|
||||
const prUrl = result.pr.url ?? existingOpenPrUrl;
|
||||
const prUrl = result.pr.url ?? gitStatusForActions?.openPr?.url;
|
||||
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
|
||||
const shouldOfferOpenPrCta =
|
||||
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
|
||||
@@ -367,7 +365,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
[
|
||||
gitStatusForActions?.branch,
|
||||
gitStatusForActions?.hasWorkingTreeChanges,
|
||||
gitStatusForActions?.pr,
|
||||
gitStatusForActions?.openPr?.url,
|
||||
isDefaultBranch,
|
||||
maybeConfirmPushToDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
|
||||
import { ChevronRightIcon, FolderIcon, TerminalIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type GitStatusResult,
|
||||
type ResolvedKeybindingsConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
@@ -17,12 +16,11 @@ import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut } from "../keybindings";
|
||||
import { type Thread } from "../types";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import {
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
@@ -65,15 +63,6 @@ interface TerminalStatusIndicator {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
tooltip: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type ThreadPr = GitStatusResult["pr"];
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
@@ -136,36 +125,6 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
|
||||
if (pr.state === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
tooltip: `#${pr.number} PR open: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip: `#${pr.number} PR closed: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (pr.state === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
tooltip: `#${pr.number} PR merged: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
@@ -251,80 +210,6 @@ export default function Sidebar() {
|
||||
}
|
||||
return map;
|
||||
}, [state.threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[state.projects],
|
||||
);
|
||||
const threadGitTargets = useMemo(
|
||||
() =>
|
||||
state.threads.map((thread) => ({
|
||||
threadId: thread.id,
|
||||
branch: thread.branch,
|
||||
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
|
||||
})),
|
||||
[projectCwdById, state.threads],
|
||||
);
|
||||
const threadGitStatusCwds = useMemo(
|
||||
() =>
|
||||
[
|
||||
...new Set(
|
||||
threadGitTargets
|
||||
.filter((target) => target.branch !== null)
|
||||
.map((target) => target.cwd)
|
||||
.filter((cwd): cwd is string => cwd !== null),
|
||||
),
|
||||
],
|
||||
[threadGitTargets],
|
||||
);
|
||||
const threadGitStatusQueries = useQueries({
|
||||
queries: threadGitStatusCwds.map((cwd) => ({
|
||||
...gitStatusQueryOptions(cwd),
|
||||
staleTime: 30_000,
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
if (!cwd) continue;
|
||||
const status = threadGitStatusQueries[index]?.data;
|
||||
if (status) {
|
||||
statusByCwd.set(cwd, status);
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<ThreadId, ThreadPr>();
|
||||
for (const target of threadGitTargets) {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Link opening is unavailable.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
@@ -747,13 +632,12 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prByThreadId.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 ${
|
||||
@@ -767,14 +651,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, {
|
||||
@@ -784,25 +660,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}`}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useCallback, useState } from "react";
|
||||
import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
|
||||
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -53,12 +52,9 @@ function SettingsRouteView() {
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [customModelInput, setCustomModelInput] = useState("");
|
||||
const [customModelError, setCustomModelError] = useState<string | null>(null);
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const customCodexModels = settings.customCodexModels;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
@@ -78,42 +74,6 @@ function SettingsRouteView() {
|
||||
});
|
||||
}, [keybindingsConfigPath]);
|
||||
|
||||
const addCustomModel = useCallback(() => {
|
||||
const normalized = normalizeModelSlug(customModelInput);
|
||||
if (!normalized) {
|
||||
setCustomModelError("Enter a model slug.");
|
||||
return;
|
||||
}
|
||||
if (MODEL_OPTIONS.some((option) => option.slug === normalized)) {
|
||||
setCustomModelError("That model is already built in.");
|
||||
return;
|
||||
}
|
||||
if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {
|
||||
setCustomModelError(`Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`);
|
||||
return;
|
||||
}
|
||||
if (customCodexModels.includes(normalized)) {
|
||||
setCustomModelError("That custom model is already saved.");
|
||||
return;
|
||||
}
|
||||
|
||||
updateSettings({
|
||||
customCodexModels: [...customCodexModels, normalized],
|
||||
});
|
||||
setCustomModelInput("");
|
||||
setCustomModelError(null);
|
||||
}, [customCodexModels, customModelInput, updateSettings]);
|
||||
|
||||
const removeCustomModel = useCallback(
|
||||
(slug: string) => {
|
||||
updateSettings({
|
||||
customCodexModels: customCodexModels.filter((model) => model !== slug),
|
||||
});
|
||||
setCustomModelError(null);
|
||||
},
|
||||
[customCodexModels, updateSettings],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
@@ -233,96 +193,6 @@ function SettingsRouteView() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Models</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Save additional Codex model slugs so they appear in the chat model picker.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<form
|
||||
className="flex flex-col gap-3 sm:flex-row sm:items-start"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
addCustomModel();
|
||||
}}
|
||||
>
|
||||
<label className="block flex-1 space-y-1">
|
||||
<span className="text-xs font-medium text-foreground">Custom model slug</span>
|
||||
<Input
|
||||
value={customModelInput}
|
||||
onChange={(event) => {
|
||||
setCustomModelInput(event.target.value);
|
||||
if (customModelError) {
|
||||
setCustomModelError(null);
|
||||
}
|
||||
}}
|
||||
placeholder="your-model-slug"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Example: <code>gpt-6.7-codex-ultra-preview</code>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<Button className="sm:mt-6" type="submit">
|
||||
Add model
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{customModelError ? (
|
||||
<p className="text-xs text-destructive">{customModelError}</p>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<p>Saved custom models: {customCodexModels.length}</p>
|
||||
{customCodexModels.length > 0 ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
customCodexModels: defaults.customCodexModels,
|
||||
})
|
||||
}
|
||||
>
|
||||
Reset custom models
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{customCodexModels.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{customCodexModels.map((slug) => (
|
||||
<div
|
||||
key={slug}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-border bg-background px-3 py-2"
|
||||
>
|
||||
<code className="min-w-0 flex-1 truncate text-xs text-foreground">
|
||||
{slug}
|
||||
</code>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() => removeCustomModel(slug)}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border border-dashed border-border bg-background px-3 py-4 text-xs text-muted-foreground">
|
||||
No custom models saved yet.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-card p-5">
|
||||
<div className="mb-4">
|
||||
<h2 className="text-sm font-medium text-foreground">Runtime Mode</h2>
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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",
|
||||
|
||||
-125
@@ -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
-8
@@ -29,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",
|
||||
|
||||
@@ -18,13 +18,9 @@ export const GitPrStepStatus = Schema.Literals([
|
||||
"opened_existing",
|
||||
"skipped_not_requested",
|
||||
]);
|
||||
export const GitStatusPrState = Schema.Literals(["open", "closed", "merged"]);
|
||||
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),
|
||||
@@ -95,16 +91,6 @@ export type GitInitInput = typeof GitInitInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
export const GitStatusPr = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
state: GitStatusPrState,
|
||||
});
|
||||
export type GitStatusPr = typeof GitStatusPr.Type;
|
||||
|
||||
export const GitStatusResult = Schema.Struct({
|
||||
branch: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
hasWorkingTreeChanges: Schema.Boolean,
|
||||
@@ -122,7 +108,15 @@ export const GitStatusResult = Schema.Struct({
|
||||
hasUpstream: Schema.Boolean,
|
||||
aheadCount: NonNegativeInt,
|
||||
behindCount: NonNegativeInt,
|
||||
pr: Schema.NullOr(GitStatusPr),
|
||||
openPr: Schema.NullOr(
|
||||
Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
url: Schema.String,
|
||||
baseBranch: TrimmedNonEmptyStringSchema,
|
||||
headBranch: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type GitStatusResult = typeof GitStatusResult.Type;
|
||||
|
||||
|
||||
@@ -22,14 +22,9 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
it("returns default for missing and unknown models", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
|
||||
});
|
||||
|
||||
it("preserves unknown custom models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe("gpt-4.1");
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model");
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
|
||||
@@ -5,12 +5,11 @@ export const MODEL_OPTIONS = [
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
] as const;
|
||||
|
||||
export type BuiltInModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type ModelSlug = string;
|
||||
export type ModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, BuiltInModelSlug> = {
|
||||
export const MODEL_SLUG_ALIASES: Record<string, ModelSlug> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
@@ -27,12 +26,16 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
|
||||
return null;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model);
|
||||
return normalized ?? DEFAULT_MODEL;
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
|
||||
@@ -1,633 +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 private: true;
|
||||
readonly description: string;
|
||||
readonly author: string;
|
||||
readonly main: string;
|
||||
readonly build: Record<string, unknown>;
|
||||
readonly dependencies: Record<string, unknown>;
|
||||
readonly devDependencies: {
|
||||
readonly electron: string;
|
||||
};
|
||||
}
|
||||
|
||||
const AzureTrustedSigningOptionsConfig = Config.all({
|
||||
publisherName: Config.string("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
|
||||
endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
|
||||
certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
|
||||
codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
|
||||
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(
|
||||
Config.withDefault(() => "SHA256"),
|
||||
),
|
||||
timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
|
||||
Config.withDefault(() => "SHA256"),
|
||||
),
|
||||
timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
|
||||
Config.withDefault(() => "http://timestamp.acs.microsoft.com"),
|
||||
),
|
||||
});
|
||||
|
||||
const BuildEnvConfig = Config.all({
|
||||
platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
|
||||
target: Config.string("T3CODE_DESKTOP_TARGET").pipe(Config.option),
|
||||
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
|
||||
version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
|
||||
outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
|
||||
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(() => false)),
|
||||
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(() => false)),
|
||||
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(() => false)),
|
||||
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(() => false)),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
|
||||
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
|
||||
|
||||
const resolveBuildOptions = Effect.fn(function* (input: BuildCliInput) {
|
||||
const path = yield* Path.Path;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const env = yield* BuildEnvConfig.asEffect();
|
||||
|
||||
const platform = mergeOptions(
|
||||
input.platform,
|
||||
env.platform,
|
||||
detectHostBuildPlatform(process.platform),
|
||||
);
|
||||
|
||||
if (!platform) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Unsupported host platform '${process.platform}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
|
||||
const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform));
|
||||
const version = mergeOptions(input.buildVersion, env.version, undefined);
|
||||
const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release"));
|
||||
|
||||
const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
|
||||
const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
|
||||
const signed = resolveBooleanFlag(input.signed, env.signed);
|
||||
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
|
||||
|
||||
return {
|
||||
platform,
|
||||
target,
|
||||
arch,
|
||||
version,
|
||||
outputDir,
|
||||
skipBuild,
|
||||
keepStage,
|
||||
signed,
|
||||
verbose,
|
||||
} satisfies ResolvedBuildOptions;
|
||||
});
|
||||
|
||||
const commandOutputOptions = (verbose: boolean) =>
|
||||
({
|
||||
stdout: verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
}) as const;
|
||||
|
||||
const runCommand = Effect.fn(function* (command: ChildProcess.Command) {
|
||||
const exitCode = yield* ChildProcess.exitCode(command);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Command exited with non-zero exit code",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function generateMacIconSet(
|
||||
sourcePng: string,
|
||||
targetIcns: string,
|
||||
tmpRoot: string,
|
||||
path: Path.Path,
|
||||
verbose: boolean,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const iconsetDir = path.join(tmpRoot, "icon.iconset");
|
||||
yield* fs.makeDirectory(iconsetDir, { recursive: true });
|
||||
|
||||
const iconSizes = [16, 32, 128, 256, 512] as const;
|
||||
for (const size of iconSizes) {
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
|
||||
);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function stageMacIcons(stageResourcesDir: string, verbose: boolean) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const iconSource = yield* IconSource;
|
||||
if (!(yield* fs.exists(iconSource))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Production icon source is missing at ${iconSource}`,
|
||||
});
|
||||
}
|
||||
|
||||
const tmpRoot = yield* fs.makeTempDirectoryScoped({
|
||||
prefix: "t3code-icon-build-",
|
||||
});
|
||||
|
||||
const iconPngPath = path.join(stageResourcesDir, "icon.png");
|
||||
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
|
||||
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
...commandOutputOptions(verbose),
|
||||
})`sips -z 512 512 ${iconSource} --out ${iconPngPath}`,
|
||||
);
|
||||
|
||||
yield* generateMacIconSet(iconSource, iconIcnsPath, tmpRoot, path, verbose);
|
||||
});
|
||||
}
|
||||
|
||||
function validateBundledClientAssets(clientDir: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const indexPath = path.join(clientDir, "index.html");
|
||||
const indexHtml = yield* fs.readFileString(indexPath);
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
const missing: string[] = [];
|
||||
|
||||
for (const ref of refs) {
|
||||
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
|
||||
if (!normalizedRef) continue;
|
||||
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
|
||||
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
|
||||
|
||||
const ext = path.extname(normalizedRef);
|
||||
if (!ext) continue;
|
||||
|
||||
const relativePath = normalizedRef.replace(/^\/+/, "");
|
||||
const assetPath = path.join(clientDir, relativePath);
|
||||
if (!(yield* fs.exists(assetPath))) {
|
||||
missing.push(normalizedRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
const preview = missing.slice(0, 6).join(", ");
|
||||
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
|
||||
return yield* new BuildScriptError({
|
||||
message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function resolveCatalogDependencies(
|
||||
dependencies: Record<string, unknown>,
|
||||
catalog: Record<string, unknown>,
|
||||
dependencySourceLabel: string,
|
||||
): Record<string, unknown> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(dependencies).map(([dependencyName, spec]) => {
|
||||
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
|
||||
return [dependencyName, spec];
|
||||
}
|
||||
|
||||
const catalogKey = spec.slice("catalog:".length).trim();
|
||||
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
|
||||
const resolvedSpec = catalog[lookupKey];
|
||||
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
|
||||
throw new BuildScriptError({
|
||||
message: `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. Expected key '${lookupKey}' in root workspace catalog.`,
|
||||
});
|
||||
}
|
||||
|
||||
return [dependencyName, resolvedSpec];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const createBuildConfig = Effect.fn(function* (
|
||||
platform: typeof BuildPlatform.Type,
|
||||
target: string,
|
||||
productName: string,
|
||||
signed: boolean,
|
||||
) {
|
||||
const buildConfig: Record<string, unknown> = {
|
||||
appId: "com.t3tools.t3code",
|
||||
productName,
|
||||
artifactName: "T3-Code-${version}-${arch}.${ext}",
|
||||
directories: {
|
||||
buildResources: "apps/desktop/resources",
|
||||
},
|
||||
};
|
||||
|
||||
if (platform === "mac") {
|
||||
buildConfig.mac = {
|
||||
target: [target],
|
||||
icon: "icon.icns",
|
||||
category: "public.app-category.developer-tools",
|
||||
};
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
buildConfig.linux = {
|
||||
target: [target],
|
||||
icon: "icon.png",
|
||||
category: "Development",
|
||||
};
|
||||
}
|
||||
|
||||
if (platform === "win") {
|
||||
const winConfig: Record<string, unknown> = {
|
||||
target: [target],
|
||||
icon: "icon.ico",
|
||||
};
|
||||
if (signed) {
|
||||
winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
|
||||
}
|
||||
buildConfig.win = winConfig;
|
||||
}
|
||||
|
||||
return buildConfig;
|
||||
});
|
||||
|
||||
const assertPlatformBuildResources = Effect.fn(function* (
|
||||
platform: typeof BuildPlatform.Type,
|
||||
stageResourcesDir: string,
|
||||
verbose: boolean,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
if (platform === "mac") {
|
||||
yield* stageMacIcons(stageResourcesDir, verbose);
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform === "linux") {
|
||||
const iconPath = path.join(stageResourcesDir, "icon.png");
|
||||
if (!(yield* fs.exists(iconPath))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing Linux icon at ${iconPath}`,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform === "win") {
|
||||
const iconPath = path.join(stageResourcesDir, "icon.ico");
|
||||
if (!(yield* fs.exists(iconPath))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing Windows icon at ${iconPath}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions) {
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
const platformConfig = PLATFORM_CONFIG[options.platform];
|
||||
if (!platformConfig) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Unsupported platform '${options.platform}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const electronVersion = desktopPackageJson.dependencies.electron;
|
||||
|
||||
const dependencies = serverPackageJson.dependencies;
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
});
|
||||
}
|
||||
|
||||
const resolvedDependencies = yield* Effect.try({
|
||||
try: () =>
|
||||
resolveCatalogDependencies(dependencies, rootPackageJson.workspaces.catalog, "apps/server"),
|
||||
catch: (cause) =>
|
||||
new BuildScriptError({
|
||||
message: "Could not resolve production dependencies from apps/server/package.json.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const appVersion = options.version ?? serverPackageJson.version;
|
||||
const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
|
||||
const stageRoot = yield* mkdir({
|
||||
prefix: `t3code-desktop-${options.platform}-stage-`,
|
||||
});
|
||||
|
||||
const stageAppDir = path.join(stageRoot, "app");
|
||||
const stageResourcesDir = path.join(stageAppDir, "apps/desktop/resources");
|
||||
const distDirs = {
|
||||
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
|
||||
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
|
||||
serverDist: path.join(repoRoot, "apps/server/dist"),
|
||||
};
|
||||
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
|
||||
|
||||
if (!options.skipBuild) {
|
||||
yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: repoRoot,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bun run build:desktop`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const [label, dir] of Object.entries(distDirs)) {
|
||||
if (!(yield* fs.exists(dir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!(yield* fs.exists(bundledClientEntry))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* validateBundledClientAssets(path.dirname(bundledClientEntry));
|
||||
|
||||
yield* fs.makeDirectory(path.join(stageAppDir, "apps/desktop"), { recursive: true });
|
||||
yield* fs.makeDirectory(path.join(stageAppDir, "apps/server"), { recursive: true });
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Staging release app...");
|
||||
yield* fs.copy(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"));
|
||||
yield* fs.copy(distDirs.desktopResources, stageResourcesDir);
|
||||
yield* fs.copy(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"));
|
||||
|
||||
yield* assertPlatformBuildResources(options.platform, stageResourcesDir, options.verbose);
|
||||
|
||||
const stagePackageJson: StagePackageJson = {
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
main: "apps/desktop/dist-electron/main.js",
|
||||
build: yield* createBuildConfig(
|
||||
options.platform,
|
||||
options.target,
|
||||
desktopPackageJson.productName ?? "T3 Code",
|
||||
options.signed,
|
||||
),
|
||||
dependencies: resolvedDependencies,
|
||||
devDependencies: {
|
||||
electron: electronVersion,
|
||||
},
|
||||
};
|
||||
|
||||
yield* fs.writeFileString(
|
||||
path.join(stageAppDir, "package.json"),
|
||||
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
|
||||
);
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: stageAppDir,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bun install --production`,
|
||||
);
|
||||
|
||||
const buildEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
};
|
||||
for (const [key, value] of Object.entries(buildEnv)) {
|
||||
if (value === "") {
|
||||
delete buildEnv[key];
|
||||
}
|
||||
}
|
||||
if (!options.signed) {
|
||||
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
|
||||
delete buildEnv.CSC_LINK;
|
||||
delete buildEnv.CSC_KEY_PASSWORD;
|
||||
delete buildEnv.APPLE_API_KEY;
|
||||
delete buildEnv.APPLE_API_KEY_ID;
|
||||
delete buildEnv.APPLE_API_ISSUER;
|
||||
}
|
||||
|
||||
yield* Effect.log(
|
||||
`[desktop-artifact] Building ${options.platform}/${options.target} (arch=${options.arch}, version=${appVersion})...`,
|
||||
);
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: stageAppDir,
|
||||
env: buildEnv,
|
||||
...commandOutputOptions(options.verbose),
|
||||
})`bunx electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
|
||||
);
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
if (!(yield* fs.exists(stageDistDir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but dist directory was not found at ${stageDistDir}`,
|
||||
});
|
||||
}
|
||||
|
||||
const stageEntries = yield* fs.readDirectory(stageDistDir);
|
||||
yield* fs.makeDirectory(options.outputDir, { recursive: true });
|
||||
|
||||
const copiedArtifacts: string[] = [];
|
||||
for (const entry of stageEntries) {
|
||||
const from = path.join(stageDistDir, entry);
|
||||
const stat = yield* fs.stat(from).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!stat || stat.type !== "File") continue;
|
||||
|
||||
const to = path.join(options.outputDir, entry);
|
||||
yield* fs.copyFile(from, to);
|
||||
copiedArtifacts.push(to);
|
||||
}
|
||||
|
||||
if (copiedArtifacts.length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but no files were produced in ${stageDistDir}`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
|
||||
Effect.annotateLogs({ artifacts: copiedArtifacts }),
|
||||
);
|
||||
});
|
||||
|
||||
const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
|
||||
platform: Flag.choice("platform", BuildPlatform.literals).pipe(
|
||||
Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
|
||||
Flag.optional,
|
||||
),
|
||||
target: Flag.string("target").pipe(
|
||||
Flag.withDescription(
|
||||
"Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
arch: Flag.choice("arch", BuildArch.literals).pipe(
|
||||
Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
|
||||
Flag.optional,
|
||||
),
|
||||
buildVersion: Flag.string("build-version").pipe(
|
||||
Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),
|
||||
Flag.optional,
|
||||
),
|
||||
outputDir: Flag.string("output-dir").pipe(
|
||||
Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
|
||||
Flag.optional,
|
||||
),
|
||||
skipBuild: Flag.boolean("skip-build").pipe(
|
||||
Flag.withDescription(
|
||||
"Skip `bun run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
keepStage: Flag.boolean("keep-stage").pipe(
|
||||
Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
|
||||
Flag.optional,
|
||||
),
|
||||
signed: Flag.boolean("signed").pipe(
|
||||
Flag.withDescription(
|
||||
"Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
verbose: Flag.boolean("verbose").pipe(
|
||||
Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
|
||||
Flag.optional,
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Build a desktop artifact for T3 Code."),
|
||||
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
|
||||
);
|
||||
|
||||
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Logger.layer([Logger.consolePretty()])),
|
||||
Effect.provide(NodeServices.layer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user