Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ba5aa10de3 | ||
|
|
8c2797a308 | ||
|
|
03534e805d | ||
|
|
927b45938f | ||
|
|
382ee5915c | ||
|
|
53d1f52a94 | ||
|
|
1af43dbf90 | ||
|
|
16fed12dcc | ||
|
|
29825f2f8a | ||
|
|
efcee4b863 | ||
|
|
26edcab8b4 | ||
|
|
c626892adf | ||
|
|
3c66cdf2fe | ||
|
|
db31c36213 | ||
|
|
cafe3352f1 | ||
|
|
7a39ce34fa | ||
|
|
483702df77 | ||
|
|
206eb6a785 | ||
|
|
de9ec2bc73 | ||
|
|
1a66e517cd | ||
|
|
33e6f35ce9 | ||
|
|
e8896fe02d | ||
|
|
e89b053269 | ||
|
|
d052d481d8 | ||
|
|
fcbb494af7 | ||
|
|
2980a853e5 | ||
|
|
56de1465fa | ||
|
|
b500106fde |
No files matched your search
@@ -0,0 +1,222 @@
|
||||
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-13
|
||||
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[@]}" --verbose
|
||||
|
||||
- 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,8 +75,11 @@ npx t3
|
||||
- `bun run build` — Builds contracts, web app, and server through Turbo.
|
||||
- `bun run typecheck` — Strict TypeScript checks for all packages.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
|
||||
@@ -86,6 +89,12 @@ npx t3
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
### Running multiple dev instances
|
||||
|
||||
@@ -122,3 +131,6 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -266,6 +266,18 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
|
||||
expect(result.branches.some((branch) => branch.current)).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -370,6 +382,82 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists local branches first and remote branches last", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
|
||||
|
||||
const remoteOnlyBranch = "feature/remote-only";
|
||||
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
|
||||
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
|
||||
|
||||
expect(firstRemoteIndex).toBeGreaterThan(0);
|
||||
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
|
||||
).toBe(true);
|
||||
expect(
|
||||
result.branches.some(
|
||||
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
|
||||
),
|
||||
).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remoteName = "my-org/upstream";
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
yield* git(tmp, ["remote", "add", remoteName, remote]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
const remoteOnlyBranch = "feature/remote-with-remote-name";
|
||||
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
|
||||
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
|
||||
yield* git(tmp, ["checkout", defaultBranch]);
|
||||
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
|
||||
|
||||
const result = yield* listGitBranches({ cwd: tmp });
|
||||
const remoteBranch = result.branches.find(
|
||||
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
|
||||
);
|
||||
|
||||
expect(remoteBranch).toBeDefined();
|
||||
expect(remoteBranch?.isRemote).toBe(true);
|
||||
expect(remoteBranch?.remoteName).toBe(remoteName);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -592,6 +680,87 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"does not silently checkout a local branch when a remote ref no longer exists",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
yield* createGitBranch({ cwd: source, branch: "feature" });
|
||||
|
||||
const checkoutResult = yield* Effect.result(
|
||||
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
|
||||
);
|
||||
expect(checkoutResult._tag).toBe("Failure");
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const remoteName = "my-org/upstream";
|
||||
const featureBranch = "feature";
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", remoteName, remote]);
|
||||
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
|
||||
|
||||
yield* git(source, ["checkout", "-b", featureBranch]);
|
||||
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
|
||||
yield* git(source, ["add", "feature.txt"]);
|
||||
yield* git(source, ["commit", "-m", "feature commit"]);
|
||||
yield* git(source, ["push", "-u", remoteName, featureBranch]);
|
||||
yield* git(source, ["checkout", defaultBranch]);
|
||||
yield* git(source, ["branch", "-D", featureBranch]);
|
||||
|
||||
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
|
||||
|
||||
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"falls back to detached checkout when --track would conflict with an existing local branch",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
|
||||
yield* initRepoWithCommit(source);
|
||||
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", defaultBranch]);
|
||||
|
||||
// Keep local branch but remove tracking so `--track origin/<branch>`
|
||||
// would attempt to create an already-existing local branch.
|
||||
yield* git(source, ["branch", "--unset-upstream"]);
|
||||
|
||||
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
|
||||
|
||||
const core = yield* GitCore;
|
||||
const status = yield* core.statusDetails(source);
|
||||
expect(status.branch).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when checkout would overwrite uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -1153,5 +1322,54 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(didFailRecency).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
|
||||
const realGitService = yield* GitService;
|
||||
let didFailRemoteBranches = false;
|
||||
let didFailRemoteNames = false;
|
||||
const core = yield* makeIsolatedGitCore({
|
||||
execute: (input) => {
|
||||
if (input.args.join(" ") === "branch --no-color --remotes") {
|
||||
didFailRemoteBranches = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: "git.test.listBranchesRemoteBranches",
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "remote unavailable",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.args.join(" ") === "remote") {
|
||||
didFailRemoteNames = true;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: "git.test.listBranchesRemoteNames",
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "remote unavailable",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return realGitService.execute(input);
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* core.listBranches({ cwd: tmp });
|
||||
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThan(0);
|
||||
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
|
||||
expect(didFailRemoteBranches).toBe(true);
|
||||
expect(didFailRemoteNames).toBe(true);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -76,6 +76,87 @@ function parsePorcelainPath(line: string): string | null {
|
||||
return filePath.length > 0 ? filePath : null;
|
||||
}
|
||||
|
||||
function parseBranchLine(line: string): { name: string; current: boolean } | null {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const name = trimmed.replace(/^[*+]\s+/, "");
|
||||
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
|
||||
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
|
||||
if (name.includes(" -> ") || name.startsWith("(")) return null;
|
||||
|
||||
return {
|
||||
name,
|
||||
current: trimmed.startsWith("* "),
|
||||
};
|
||||
}
|
||||
|
||||
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.toSorted((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
function parseRemoteRefWithRemoteNames(
|
||||
branchName: string,
|
||||
remoteNames: ReadonlyArray<string>,
|
||||
): { remoteRef: string; remoteName: string; localBranch: string } | null {
|
||||
const trimmedBranchName = branchName.trim();
|
||||
if (trimmedBranchName.length === 0) return null;
|
||||
|
||||
for (const remoteName of remoteNames) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (!trimmedBranchName.startsWith(remotePrefix)) {
|
||||
continue;
|
||||
}
|
||||
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
|
||||
if (localBranch.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
remoteRef: trimmedBranchName,
|
||||
remoteName,
|
||||
localBranch,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTrackingBranchByUpstreamRef(
|
||||
stdout: string,
|
||||
upstreamRef: string,
|
||||
): string | null {
|
||||
for (const line of stdout.split("\n")) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
|
||||
const branchName = branchNameRaw?.trim() ?? "";
|
||||
const upstreamBranch = upstreamBranchRaw.trim();
|
||||
if (branchName.length === 0 || upstreamBranch.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (upstreamBranch === upstreamRef) {
|
||||
return branchName;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
|
||||
const separatorIndex = branchName.indexOf("/");
|
||||
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
|
||||
return null;
|
||||
}
|
||||
const localBranch = branchName.slice(separatorIndex + 1).trim();
|
||||
return localBranch.length > 0 ? localBranch : null;
|
||||
}
|
||||
|
||||
function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
@@ -264,7 +345,12 @@ const makeGitCore = Effect.gen(function* () {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitCore.readBranchRecency",
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
[
|
||||
"for-each-ref",
|
||||
"--format=%(refname:short)%09%(committerdate:unix)",
|
||||
"refs/heads",
|
||||
"refs/remotes",
|
||||
],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -564,7 +650,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
|
||||
Effect.catch(() => Effect.succeed(new Map<string, number>())),
|
||||
);
|
||||
const result = yield* executeGit(
|
||||
const localBranchResult = yield* executeGit(
|
||||
"GitCore.listBranches.branchNoColor",
|
||||
input.cwd,
|
||||
["branch", "--no-color"],
|
||||
@@ -574,8 +660,8 @@ const makeGitCore = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (localBranchResult.code !== 0) {
|
||||
const stderr = localBranchResult.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
@@ -587,7 +673,40 @@ const makeGitCore = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
|
||||
const remoteBranchResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteBranches",
|
||||
input.cwd,
|
||||
["branch", "--no-color", "--remotes"],
|
||||
{
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const remoteNamesResultEffect = executeGit(
|
||||
"GitCore.listBranches.remoteNames",
|
||||
input.cwd,
|
||||
["remote"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning(
|
||||
`GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
|
||||
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
|
||||
),
|
||||
);
|
||||
|
||||
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
|
||||
yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.listBranches.defaultRef",
|
||||
@@ -607,11 +726,25 @@ const makeGitCore = Effect.gen(function* () {
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
),
|
||||
remoteBranchResultEffect,
|
||||
remoteNamesResultEffect,
|
||||
branchRecencyPromise,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
|
||||
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
|
||||
);
|
||||
}
|
||||
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
|
||||
yield* Effect.logWarning(
|
||||
`GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
|
||||
);
|
||||
}
|
||||
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
@@ -636,19 +769,17 @@ const makeGitCore = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const branches = result.stdout
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => ({
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
@@ -660,6 +791,43 @@ const makeGitCore = Effect.gen(function* () {
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: branch.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const branches = [...localBranches, ...remoteBranches];
|
||||
|
||||
return { branches, isRepo: true };
|
||||
});
|
||||
|
||||
@@ -719,7 +887,75 @@ const makeGitCore = Effect.gen(function* () {
|
||||
|
||||
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
|
||||
const [localInputExists, remoteExists] = yield* Effect.all(
|
||||
[
|
||||
executeGit(
|
||||
"GitCore.checkoutBranch.localInputExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
executeGit(
|
||||
"GitCore.checkoutBranch.remoteExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const localTrackingBranch =
|
||||
remoteExists
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackingBranch",
|
||||
input.cwd,
|
||||
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.map((result) =>
|
||||
result.code === 0
|
||||
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
|
||||
: null,
|
||||
),
|
||||
)
|
||||
: null;
|
||||
|
||||
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
|
||||
const localTrackedBranchTargetExists =
|
||||
remoteExists && localTrackedBranchCandidate
|
||||
? yield* executeGit(
|
||||
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
|
||||
input.cwd,
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
|
||||
{
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.map((result) => result.code === 0))
|
||||
: false;
|
||||
|
||||
const checkoutArgs =
|
||||
localInputExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
|
||||
? ["checkout", input.branch]
|
||||
: remoteExists && !localTrackingBranch
|
||||
? ["checkout", "--track", input.branch]
|
||||
: remoteExists && localTrackingBranch
|
||||
? ["checkout", localTrackingBranch]
|
||||
: ["checkout", input.branch];
|
||||
|
||||
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
|
||||
@@ -101,7 +101,7 @@ export interface GitCoreShape {
|
||||
) => Effect.Effect<string | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branches and branch metadata.
|
||||
* List local + remote branches and branch metadata.
|
||||
*/
|
||||
readonly listBranches: (
|
||||
input: GitListBranchesInput,
|
||||
|
||||
@@ -22,12 +22,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
expect(
|
||||
normalizeCustomModelSlugs([
|
||||
" custom/internal-model ",
|
||||
"gpt-5.3-codex",
|
||||
"5.3",
|
||||
"custom/internal-model",
|
||||
"",
|
||||
null,
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions(["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
"custom/internal-model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions([], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
name: "custom/selected-model",
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { 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(
|
||||
@@ -14,8 +18,16 @@ 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({});
|
||||
|
||||
@@ -23,6 +35,76 @@ 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();
|
||||
@@ -35,7 +117,7 @@ function parsePersistedSettings(value: string | null): AppSettings {
|
||||
}
|
||||
|
||||
try {
|
||||
return Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value);
|
||||
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
@@ -96,10 +178,12 @@ export function useAppSettings() {
|
||||
);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
});
|
||||
const next = normalizeAppSettings(
|
||||
Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { ThreadId, type GitBranch } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
const branches: GitBranch[] = [
|
||||
{
|
||||
@@ -57,3 +61,124 @@ describe("deriveSyncedLocalBranch", () => {
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveLocalBranchNameFromRemoteRef", () => {
|
||||
it("strips the remote prefix from a remote ref", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
|
||||
});
|
||||
|
||||
it("supports remote names that contain slashes", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
|
||||
"upstream/feature/demo",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the original name when ref is malformed", () => {
|
||||
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
|
||||
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("dedupeRemoteBranchesWithLocalMatches", () => {
|
||||
it("hides remote refs when the matching local branch exists", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/demo",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/remote-only",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps all entries when no local match exists for a remote ref", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/local",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "origin/feature/remote-only",
|
||||
isRemote: true,
|
||||
remoteName: "origin",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/local",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes remote refs for remotes whose names contain slashes", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "feature/demo",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "my-org/upstream/feature/demo",
|
||||
isRemote: true,
|
||||
remoteName: "my-org/upstream",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"feature/demo",
|
||||
]);
|
||||
});
|
||||
|
||||
it("dedupes remote refs when git tracks with first-slash local naming", () => {
|
||||
const input: GitBranch[] = [
|
||||
{
|
||||
name: "upstream/feature",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
name: "my-org/upstream/feature",
|
||||
isRemote: true,
|
||||
remoteName: "my-org/upstream",
|
||||
current: false,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
|
||||
"upstream/feature",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,54 @@ interface DeriveSyncedLocalBranchInput {
|
||||
queryBranches: ReadonlyArray<GitBranch> | undefined;
|
||||
}
|
||||
|
||||
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
|
||||
const firstSeparatorIndex = branchName.indexOf("/");
|
||||
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
|
||||
return branchName;
|
||||
}
|
||||
return branchName.slice(firstSeparatorIndex + 1);
|
||||
}
|
||||
|
||||
function deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branchName: string,
|
||||
remoteName?: string,
|
||||
): ReadonlyArray<string> {
|
||||
const candidates = new Set<string>();
|
||||
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
|
||||
if (firstSlashCandidate.length > 0) {
|
||||
candidates.add(firstSlashCandidate);
|
||||
}
|
||||
|
||||
if (remoteName) {
|
||||
const remotePrefix = `${remoteName}/`;
|
||||
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
|
||||
candidates.add(branchName.slice(remotePrefix.length));
|
||||
}
|
||||
}
|
||||
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
export function dedupeRemoteBranchesWithLocalMatches(
|
||||
branches: ReadonlyArray<GitBranch>,
|
||||
): ReadonlyArray<GitBranch> {
|
||||
const localBranchNames = new Set(
|
||||
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
|
||||
);
|
||||
|
||||
return branches.filter((branch) => {
|
||||
if (!branch.isRemote) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
|
||||
branch.name,
|
||||
branch.remoteName,
|
||||
);
|
||||
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
export function deriveSyncedLocalBranch({
|
||||
activeThreadId,
|
||||
activeWorktreePath,
|
||||
|
||||
@@ -10,7 +10,11 @@ import {
|
||||
} from "../lib/gitReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useStore } from "../store";
|
||||
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
dedupeRemoteBranchesWithLocalMatches,
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
deriveSyncedLocalBranch,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
Combobox,
|
||||
@@ -55,7 +59,7 @@ export default function BranchToolbar({
|
||||
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
|
||||
|
||||
const branches = branchesQuery.data?.branches ?? [];
|
||||
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
|
||||
const branchNames = branches.map((branch) => branch.name);
|
||||
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
|
||||
const trimmedBranchQuery = branchQuery.trim();
|
||||
@@ -174,10 +178,21 @@ export default function BranchToolbar({
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedBranchName = branch.isRemote
|
||||
? deriveLocalBranchNameFromRemoteRef(branch.name)
|
||||
: branch.name;
|
||||
|
||||
checkoutMutation.mutate(branch.name, {
|
||||
onSuccess: () => {
|
||||
onSuccess: async () => {
|
||||
setThreadError(null);
|
||||
setThreadBranch(branch.name, activeWorktreePath);
|
||||
let nextBranchName = selectedBranchName;
|
||||
if (branch.isRemote) {
|
||||
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
|
||||
if (status?.branch) {
|
||||
nextBranchName = status.branch;
|
||||
}
|
||||
}
|
||||
setThreadBranch(nextBranchName, activeWorktreePath);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
},
|
||||
@@ -283,6 +298,15 @@ 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
|
||||
@@ -295,11 +319,7 @@ export default function BranchToolbar({
|
||||
>
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<span className="truncate">{itemValue}</span>
|
||||
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
||||
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
|
||||
</span>
|
||||
)}
|
||||
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
|
||||
</div>
|
||||
</ComboboxItem>
|
||||
);
|
||||
|
||||
@@ -1,18 +1,207 @@
|
||||
import { memo, useMemo } from "react";
|
||||
import {
|
||||
getSharedHighlighter,
|
||||
type DiffsHighlighter,
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import {
|
||||
Children,
|
||||
Suspense,
|
||||
isValidElement,
|
||||
use,
|
||||
useCallback,
|
||||
memo,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
interface ChatMarkdownProps {
|
||||
text: string;
|
||||
cwd: string | undefined;
|
||||
isStreaming?: boolean;
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
|
||||
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
|
||||
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
|
||||
const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_ENTRIES,
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
|
||||
function extractFenceLanguage(className: string | undefined): string {
|
||||
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
|
||||
return match?.[1] ?? "text";
|
||||
}
|
||||
|
||||
function nodeToPlainText(node: ReactNode): string {
|
||||
if (typeof node === "string" || typeof node === "number") {
|
||||
return String(node);
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
return node.map((child) => nodeToPlainText(child)).join("");
|
||||
}
|
||||
if (isValidElement<{ children?: ReactNode }>(node)) {
|
||||
return nodeToPlainText(node.props.children);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function extractCodeBlock(
|
||||
children: ReactNode,
|
||||
): { className: string | undefined; code: string } | null {
|
||||
const childNodes = Children.toArray(children);
|
||||
if (childNodes.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onlyChild = childNodes[0];
|
||||
if (
|
||||
!isValidElement<{ className?: string; children?: ReactNode }>(onlyChild) ||
|
||||
onlyChild.type !== "code"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
className: onlyChild.props.className,
|
||||
code: nodeToPlainText(onlyChild.props.children),
|
||||
};
|
||||
}
|
||||
|
||||
function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
|
||||
return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
|
||||
}
|
||||
|
||||
function estimateHighlightedSize(html: string, code: string): number {
|
||||
return Math.max(html.length * 2, code.length * 3);
|
||||
}
|
||||
|
||||
function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
const cached = highlighterPromiseCache.get(language);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = getSharedHighlighter({
|
||||
themes: [resolveDiffThemeName("dark"), resolveDiffThemeName("light")],
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
}
|
||||
void navigator.clipboard
|
||||
.writeText(code)
|
||||
.then(() => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
}
|
||||
setCopied(true);
|
||||
copiedTimerRef.current = setTimeout(() => {
|
||||
setCopied(false);
|
||||
copiedTimerRef.current = null;
|
||||
}, 1200);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [code]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimerRef.current != null) {
|
||||
clearTimeout(copiedTimerRef.current);
|
||||
copiedTimerRef.current = null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-codeblock">
|
||||
<button
|
||||
type="button"
|
||||
className="chat-markdown-copy-button"
|
||||
onClick={handleCopy}
|
||||
title={copied ? "Copied" : "Copy code"}
|
||||
aria-label={copied ? "Copied" : "Copy code"}
|
||||
>
|
||||
{copied ? <CheckIcon className="size-3" /> : <CopyIcon className="size-3" />}
|
||||
</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SuspenseShikiCodeBlockProps {
|
||||
className: string | undefined;
|
||||
code: string;
|
||||
themeName: DiffThemeName;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
function SuspenseShikiCodeBlock({
|
||||
className,
|
||||
code,
|
||||
themeName,
|
||||
isStreaming,
|
||||
}: SuspenseShikiCodeBlockProps) {
|
||||
const language = extractFenceLanguage(className);
|
||||
const cacheKey = createHighlightCacheKey(code, language, themeName);
|
||||
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
|
||||
|
||||
if (cachedHighlightedHtml != null) {
|
||||
return (
|
||||
<div
|
||||
className="chat-markdown-shiki"
|
||||
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(
|
||||
() => highlighter.codeToHtml(code, { lang: language, theme: themeName }),
|
||||
[code, highlighter, language, themeName],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isStreaming) {
|
||||
highlightedCodeCache.set(
|
||||
cacheKey,
|
||||
highlightedHtml,
|
||||
estimateHighlightedSize(highlightedHtml, code),
|
||||
);
|
||||
}
|
||||
}, [cacheKey, code, highlightedHtml, isStreaming]);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
|
||||
);
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
a({ node: _node, href, ...props }) {
|
||||
@@ -38,17 +227,32 @@ function ChatMarkdown({ text, cwd }: ChatMarkdownProps) {
|
||||
/>
|
||||
);
|
||||
},
|
||||
pre({ node: _node, children, ...props }) {
|
||||
const codeBlock = extractCodeBlock(children);
|
||||
if (!codeBlock) {
|
||||
return <pre {...props}>{children}</pre>;
|
||||
}
|
||||
|
||||
return (
|
||||
<MarkdownCodeBlock code={codeBlock.code}>
|
||||
<Suspense fallback={<pre {...props}>{children}</pre>}>
|
||||
<SuspenseShikiCodeBlock
|
||||
className={codeBlock.className}
|
||||
code={codeBlock.code}
|
||||
themeName={diffThemeName}
|
||||
isStreaming={isStreaming}
|
||||
/>
|
||||
</Suspense>
|
||||
</MarkdownCodeBlock>
|
||||
);
|
||||
},
|
||||
}),
|
||||
[cwd],
|
||||
[cwd, diffThemeName, isStreaming],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[[rehypeHighlight, { detect: true, ignoreMissing: true }]]}
|
||||
components={markdownComponents}
|
||||
>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
|
||||
{text}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
@@ -6,11 +6,9 @@ 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,
|
||||
@@ -112,7 +110,7 @@ import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import { clamp } from "effect/Number";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
@@ -129,12 +127,6 @@ 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;
|
||||
|
||||
@@ -216,7 +208,7 @@ type ComposerCommandItem =
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
@@ -438,6 +430,10 @@ 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";
|
||||
@@ -614,18 +610,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
];
|
||||
}
|
||||
|
||||
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]);
|
||||
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]);
|
||||
const composerMenuOpen = Boolean(composerTrigger);
|
||||
const activeComposerMenuItem = useMemo(
|
||||
() =>
|
||||
@@ -1660,7 +1664,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
|
||||
const onModelSelect = useCallback(
|
||||
(model: ModelSlug) => {
|
||||
(model: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!activeThread) return;
|
||||
if (api) {
|
||||
@@ -2012,7 +2016,11 @@ 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} onModelChange={onModelSelect} />
|
||||
<ModelPicker
|
||||
model={selectedModel}
|
||||
options={modelOptions}
|
||||
onModelChange={onModelSelect}
|
||||
/>
|
||||
|
||||
{/* Divider */}
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
@@ -2759,7 +2767,11 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown text={messageText} cwd={markdownCwd} />
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={markdownCwd}
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
/>
|
||||
{(() => {
|
||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
||||
if (!turnSummary) return null;
|
||||
@@ -2912,12 +2924,13 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
});
|
||||
|
||||
const ModelPicker = memo(function ModelPicker(props: {
|
||||
model: ModelSlug;
|
||||
onModelChange: (model: ModelSlug) => void;
|
||||
model: string;
|
||||
options: ReadonlyArray<{ slug: string; name: string }>;
|
||||
onModelChange: (model: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<Select
|
||||
items={MODEL_OPTIONS.map((option) => ({ label: option.name, value: option.slug }))}
|
||||
items={props.options.map((option) => ({ label: option.name, value: option.slug }))}
|
||||
value={props.model}
|
||||
onValueChange={(value) => (value ? props.onModelChange(value) : undefined)}
|
||||
>
|
||||
@@ -2925,7 +2938,7 @@ const ModelPicker = memo(function ModelPicker(props: {
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
{MODEL_OPTIONS.map(({ slug, name }) => (
|
||||
{props.options.map(({ slug, name }) => (
|
||||
<SelectItem key={slug} value={slug}>
|
||||
{name}
|
||||
</SelectItem>
|
||||
|
||||
@@ -7,10 +7,13 @@ 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";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -18,10 +21,62 @@ import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
type DiffThemeType = "light" | "dark";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-diffs-header],
|
||||
[data-diff],
|
||||
[data-file],
|
||||
[data-error-wrapper],
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-token-light-bg: transparent;
|
||||
--diffs-token-dark-bg: transparent;
|
||||
|
||||
--diffs-bg-context-override: color-mix(in srgb, var(--background) 97%, var(--foreground));
|
||||
--diffs-bg-hover-override: color-mix(in srgb, var(--background) 94%, var(--foreground));
|
||||
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
|
||||
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
|
||||
|
||||
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
|
||||
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
|
||||
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
|
||||
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
|
||||
|
||||
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
|
||||
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
|
||||
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
|
||||
--diffs-bg-deletion-emphasis-override: color-mix(
|
||||
in srgb,
|
||||
var(--background) 80%,
|
||||
var(--destructive)
|
||||
);
|
||||
|
||||
background-color: var(--diffs-bg) !important;
|
||||
}
|
||||
|
||||
[data-file-info] {
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-block-color: var(--border) !important;
|
||||
color: var(--foreground) !important;
|
||||
}
|
||||
|
||||
[data-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 =
|
||||
| {
|
||||
kind: "files";
|
||||
@@ -106,6 +161,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
|
||||
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
|
||||
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
@@ -226,6 +283,18 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
target?.scrollIntoView({ block: "nearest" });
|
||||
}, [selectedFilePath, renderableFiles]);
|
||||
|
||||
const openDiffFileInEditor = useCallback(
|
||||
(filePath: string) => {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
|
||||
console.warn("Failed to open diff file in editor.", error);
|
||||
});
|
||||
},
|
||||
[activeCwd],
|
||||
);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
if (!activeThread) return;
|
||||
void navigate({
|
||||
@@ -425,7 +494,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-card",
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
@@ -449,7 +518,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={patchViewportRef} className="min-h-0 min-w-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
ref={patchViewportRef}
|
||||
className="diff-panel-viewport min-h-0 min-w-0 flex-1 overflow-hidden"
|
||||
>
|
||||
{checkpointDiffError && !renderablePatch && (
|
||||
<div className="px-3">
|
||||
<p className="mb-2 text-[11px] text-red-500/80">{checkpointDiffError}</p>
|
||||
@@ -467,7 +539,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="h-full min-h-0 overflow-auto px-3 py-2"
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto p-2 "
|
||||
config={{
|
||||
overscrollSize: 600,
|
||||
intersectionObserverMargin: 1200,
|
||||
@@ -478,7 +550,21 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const fileKey = buildFileDiffRenderKey(fileDiff);
|
||||
const themedFileKey = `${fileKey}:${resolvedTheme}`;
|
||||
return (
|
||||
<div key={themedFileKey} data-diff-file-path={filePath} className="rounded-md">
|
||||
<div
|
||||
key={themedFileKey}
|
||||
data-diff-file-path={filePath}
|
||||
className="diff-render-file mb-2 rounded-md last:mb-0"
|
||||
onClickCapture={(event) => {
|
||||
const nativeEvent = event.nativeEvent as MouseEvent;
|
||||
const composedPath = nativeEvent.composedPath?.() ?? [];
|
||||
const clickedHeader = composedPath.some((node) => {
|
||||
if (!(node instanceof Element)) return false;
|
||||
return node.hasAttribute("data-title");
|
||||
});
|
||||
if (!clickedHeader) return;
|
||||
openDiffFileInEditor(filePath);
|
||||
}}
|
||||
>
|
||||
<FileDiff
|
||||
fileDiff={fileDiff}
|
||||
options={{
|
||||
@@ -486,6 +572,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
lineDiffType: "none",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
@@ -493,7 +580,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
})}
|
||||
</Virtualizer>
|
||||
) : (
|
||||
<div className="h-full overflow-auto px-3 py-2">
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
|
||||
@@ -2,12 +2,9 @@ import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function resolveDiffThemeName(theme: "light" | "dark") {
|
||||
return theme === "dark" ? "pierre-dark" : "pierre-light";
|
||||
}
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: "pierre-light" | "pierre-dark" }) {
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
const workerPool = useWorkerPool();
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -22,6 +22,7 @@ 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,
|
||||
@@ -67,9 +68,11 @@ interface TerminalStatusIndicator {
|
||||
interface PrStatusIndicator {
|
||||
label: "PR open" | "PR closed" | "PR merged";
|
||||
colorClass: string;
|
||||
tooltip: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
|
||||
type ThreadPr = GitStatusResult["pr"];
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
@@ -133,23 +136,31 @@ function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null
|
||||
};
|
||||
}
|
||||
|
||||
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
|
||||
if (prState === "open") {
|
||||
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
|
||||
if (!pr) return null;
|
||||
|
||||
if (pr.state === "open") {
|
||||
return {
|
||||
label: "PR open",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
tooltip: `#${pr.number} PR open: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (prState === "closed") {
|
||||
if (pr.state === "closed") {
|
||||
return {
|
||||
label: "PR closed",
|
||||
colorClass: "text-zinc-500 dark:text-zinc-400/80",
|
||||
tooltip: `#${pr.number} PR closed: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
if (prState === "merged") {
|
||||
if (pr.state === "merged") {
|
||||
return {
|
||||
label: "PR merged",
|
||||
colorClass: "text-violet-600 dark:text-violet-300/90",
|
||||
tooltip: `#${pr.number} PR merged: ${pr.title}`,
|
||||
url: pr.url,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
@@ -272,7 +283,7 @@ export default function Sidebar() {
|
||||
refetchInterval: 60_000,
|
||||
})),
|
||||
});
|
||||
const prStateByThreadId = useMemo(() => {
|
||||
const prByThreadId = useMemo(() => {
|
||||
const statusByCwd = new Map<string, GitStatusResult>();
|
||||
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
|
||||
const cwd = threadGitStatusCwds[index];
|
||||
@@ -283,16 +294,38 @@ export default function Sidebar() {
|
||||
}
|
||||
}
|
||||
|
||||
const map = new Map<ThreadId, ThreadPrState>();
|
||||
const map = new Map<ThreadId, ThreadPr>();
|
||||
for (const target of threadGitTargets) {
|
||||
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
|
||||
const branchMatches =
|
||||
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
|
||||
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
|
||||
map.set(target.threadId, branchMatches ? status?.pr ?? null : null);
|
||||
}
|
||||
return map;
|
||||
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
|
||||
|
||||
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Link opening is unavailable.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open PR link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
projectId: ProjectId,
|
||||
@@ -714,13 +747,13 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
|
||||
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
|
||||
return (
|
||||
<SidebarMenuSubItem key={thread.id} className="w-full">
|
||||
<SidebarMenuSubButton
|
||||
render={<button type="button" />}
|
||||
render={<div role="button" tabIndex={0} />}
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
|
||||
@@ -734,6 +767,14 @@ export default function Sidebar() {
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
void navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: thread.id },
|
||||
});
|
||||
}}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
void handleThreadContextMenu(thread.id, {
|
||||
@@ -743,6 +784,25 @@ export default function Sidebar() {
|
||||
}}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
|
||||
{prStatus && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label={prStatus.tooltip}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
|
||||
onClick={(event) => {
|
||||
openPrLink(event, prStatus.url);
|
||||
}}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
|
||||
@@ -760,16 +820,6 @@ export default function Sidebar() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{prStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={prStatus.label}
|
||||
title={prStatus.label}
|
||||
className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
|
||||
>
|
||||
<GitPullRequestIcon className="size-3" />
|
||||
</span>
|
||||
)}
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
|
||||
@@ -314,6 +314,52 @@ label:has(> select#reasoning-effort) select {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock {
|
||||
position: relative;
|
||||
margin: 0.65rem 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 1.5rem;
|
||||
width: 1.5rem;
|
||||
border-radius: 0.375rem;
|
||||
border: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--background) 82%, transparent);
|
||||
color: var(--muted-foreground);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
color 120ms ease,
|
||||
border-color 120ms ease;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-codeblock:hover .chat-markdown-copy-button,
|
||||
.chat-markdown .chat-markdown-codeblock:focus-within .chat-markdown-copy-button {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-copy-button:hover {
|
||||
color: var(--foreground);
|
||||
border-color: color-mix(in srgb, var(--border) 70%, var(--foreground));
|
||||
}
|
||||
|
||||
.chat-markdown .chat-markdown-shiki .shiki {
|
||||
background: color-mix(in srgb, var(--muted) 78%, var(--background)) !important;
|
||||
}
|
||||
|
||||
.chat-markdown table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
@@ -325,3 +371,15 @@ label:has(> select#reasoning-effort) select {
|
||||
padding: 0.35rem 0.45rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Diffs theme bridge (match diff surfaces to app palette) */
|
||||
.diff-panel-viewport {
|
||||
background: color-mix(in srgb, var(--background) 94%, var(--card));
|
||||
}
|
||||
|
||||
.diff-render-file {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.5rem;
|
||||
overflow: clip;
|
||||
background: color-mix(in srgb, var(--card) 92%, var(--background));
|
||||
}
|
||||
@@ -1,9 +1,24 @@
|
||||
export const DIFF_THEME_NAMES = {
|
||||
light: "pierre-light",
|
||||
dark: "pierre-dark",
|
||||
} as const;
|
||||
|
||||
export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
|
||||
|
||||
export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
|
||||
return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
|
||||
}
|
||||
|
||||
const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
|
||||
const FNV_PRIME_32 = 0x01000193;
|
||||
const SECONDARY_HASH_SEED = 0x9e3779b9;
|
||||
const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
|
||||
|
||||
function fnv1a32(input: string, seed: number, multiplier: number): number {
|
||||
export function fnv1a32(
|
||||
input: string,
|
||||
seed = FNV_OFFSET_BASIS_32,
|
||||
multiplier = FNV_PRIME_32,
|
||||
): number {
|
||||
let hash = seed >>> 0;
|
||||
for (let index = 0; index < input.length; index += 1) {
|
||||
hash ^= input.charCodeAt(index);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { LRUCache } from "./lruCache";
|
||||
|
||||
describe("LRUCache", () => {
|
||||
it("returns null for missing keys", () => {
|
||||
const cache = new LRUCache<string>(2, 100);
|
||||
expect(cache.get("missing")).toBeNull();
|
||||
});
|
||||
|
||||
it("evicts oldest by max entries", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("promotes on get and evicts least recently used", () => {
|
||||
const cache = new LRUCache<string>(2, 1_000);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
|
||||
cache.set("c", "C", 10);
|
||||
expect(cache.get("a")).toBe("A");
|
||||
expect(cache.get("b")).toBeNull();
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
|
||||
it("evicts by memory budget", () => {
|
||||
const cache = new LRUCache<string>(10, 25);
|
||||
cache.set("a", "A", 10);
|
||||
cache.set("b", "B", 10);
|
||||
cache.set("c", "C", 10);
|
||||
|
||||
expect(cache.get("a")).toBeNull();
|
||||
expect(cache.get("b")).toBe("B");
|
||||
expect(cache.get("c")).toBe("C");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
interface CacheEntry<T> {
|
||||
value: T;
|
||||
approximateSize: number;
|
||||
}
|
||||
|
||||
export class LRUCache<T> {
|
||||
private cache = new Map<string, CacheEntry<T>>();
|
||||
private totalSize = 0;
|
||||
|
||||
constructor(
|
||||
private readonly maxEntries: number,
|
||||
private readonly maxMemoryBytes: number,
|
||||
) {}
|
||||
|
||||
get(key: string): T | null {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
this.promote(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T, approximateSize: number): void {
|
||||
const existing = this.cache.get(key);
|
||||
if (existing) {
|
||||
this.totalSize -= existing.approximateSize;
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
this.evictIfNeeded(approximateSize);
|
||||
this.cache.set(key, { value, approximateSize });
|
||||
this.totalSize += approximateSize;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.cache.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
|
||||
private promote(key: string, entry: CacheEntry<T>): void {
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, entry);
|
||||
}
|
||||
|
||||
private evictIfNeeded(incomingSize: number): void {
|
||||
while (
|
||||
(this.cache.size >= this.maxEntries || this.totalSize + incomingSize > this.maxMemoryBytes) &&
|
||||
this.cache.size > 0
|
||||
) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (oldestKey === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
const oldestEntry = this.cache.get(oldestKey);
|
||||
if (oldestEntry) {
|
||||
this.totalSize -= oldestEntry.approximateSize;
|
||||
}
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { createHashHistory, createRouter, createBrowserHistory } from "@tanstack
|
||||
import { StoreProvider } from "./store";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import "highlight.js/styles/github-dark.css";
|
||||
import "./index.css";
|
||||
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
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 { useAppSettings } from "../appSettings";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
@@ -52,9 +53,12 @@ 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(() => {
|
||||
@@ -74,6 +78,42 @@ 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">
|
||||
@@ -193,6 +233,96 @@ 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,10 +153,9 @@ export function createWsNativeApi(): NativeApi {
|
||||
return;
|
||||
}
|
||||
|
||||
const popup = window.open(url, "_blank", "noopener,noreferrer");
|
||||
if (!popup) {
|
||||
throw new Error("Unable to open link. Allow popups and try again.");
|
||||
}
|
||||
// Some mobile browsers can return null here even when the tab opens.
|
||||
// Avoid false negatives and let the browser handle popup policy.
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
},
|
||||
},
|
||||
git: {
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
"": {
|
||||
"name": "@t3tools/monorepo",
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
@@ -71,12 +73,10 @@
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"effect": "catalog:",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.564.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"rehype-highlight": "^7.0.2",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
},
|
||||
@@ -863,20 +863,14 @@
|
||||
|
||||
"hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
|
||||
|
||||
"hast-util-is-element": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-Val9mnv2IWpLbNPqc/pUem+a7Ipj2aHacCwgNfTiK0vJKl0LF+4Ba4+v1oPHFpf3bLYmreq0/l3Gud9S5OH42g=="],
|
||||
|
||||
"hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
|
||||
|
||||
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
|
||||
|
||||
"hast-util-to-text": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "hast-util-is-element": "^3.0.0", "unist-util-find-after": "^5.0.0" } }, "sha512-KK6y/BN8lbaq654j7JgBydev7wuNMcID54lkRav1P0CaE1e47P72AWWPiGKXTJU271ooYzcvTAn/Zt0REnvc7A=="],
|
||||
|
||||
"hast-util-whitespace": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
|
||||
|
||||
"headers-polyfill": ["[email protected]", "", {}, "sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ=="],
|
||||
|
||||
"highlight.js": ["[email protected]", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
|
||||
|
||||
"hookable": ["[email protected]", "", {}, "sha512-uKGyY8BuzN/a5gvzvA+3FVWo0+wUjgtfSdnmjtrOVwQCZPHpHDH2WRO3VZSOeluYrHoDCiXFffZXs8Dj1ULWtw=="],
|
||||
|
||||
"html-url-attributes": ["[email protected]", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
|
||||
@@ -983,8 +977,6 @@
|
||||
|
||||
"lowercase-keys": ["[email protected]", "", {}, "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA=="],
|
||||
|
||||
"lowlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.0.0", "highlight.js": "~11.11.0" } }, "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ=="],
|
||||
|
||||
"lru-cache": ["[email protected]", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
|
||||
|
||||
"lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
|
||||
@@ -1197,8 +1189,6 @@
|
||||
|
||||
"regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
|
||||
|
||||
"rehype-highlight": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-to-text": "^4.0.0", "lowlight": "^3.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-k158pK7wdC2qL3M5NcZROZ2tR/l7zOzjxXd5VGdcfIyoijjQqpHd3JKtYSBDpDZ38UI2WJWuFAtkMDxmx5kstA=="],
|
||||
|
||||
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
|
||||
|
||||
"remark-parse": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
|
||||
@@ -1361,8 +1351,6 @@
|
||||
|
||||
"unified": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "bail": "^2.0.0", "devlop": "^1.0.0", "extend": "^3.0.0", "is-plain-obj": "^4.0.0", "trough": "^2.0.0", "vfile": "^6.0.0" } }, "sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA=="],
|
||||
|
||||
"unist-util-find-after": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-amQa0Ep2m6hE2g72AugUItjbuM8X8cGQnFoHk0pGfrFeT9GZhzN5SW8nRsiGKK7Aif4CrACPENkA6P/Lw6fHGQ=="],
|
||||
|
||||
"unist-util-is": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="],
|
||||
|
||||
"unist-util-position": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="],
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
# Release Checklist
|
||||
|
||||
This document covers how to run desktop releases from one tag, first without signing, then with signing.
|
||||
|
||||
## What the workflow does
|
||||
|
||||
- Trigger: push tag matching `v*.*.*`.
|
||||
- Runs quality gates first: lint, typecheck, test.
|
||||
- Builds four artifacts in parallel:
|
||||
- macOS `arm64` DMG
|
||||
- macOS `x64` DMG
|
||||
- Linux `x64` AppImage
|
||||
- Windows `x64` NSIS installer
|
||||
- Publishes one GitHub Release with all produced files.
|
||||
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
|
||||
- Signing is optional and auto-detected per platform from secrets.
|
||||
|
||||
## 0) npm OIDC trusted publishing setup (CLI)
|
||||
|
||||
The workflow publishes the CLI with `bun publish` from `apps/server` after bumping
|
||||
the package version to the release tag version.
|
||||
|
||||
Checklist:
|
||||
|
||||
1. Confirm npm org/user owns package `t3` (or rename package first if needed).
|
||||
2. In npm package settings, configure Trusted Publisher:
|
||||
- Provider: GitHub Actions
|
||||
- Repository: this repo
|
||||
- Workflow file: `.github/workflows/release.yml`
|
||||
- Environment (if used): match your npm trusted publishing config
|
||||
3. Ensure npm account and org policies allow trusted publishing for the package.
|
||||
4. Create release tag `vX.Y.Z` and push; workflow will:
|
||||
- set `apps/server/package.json` version to `X.Y.Z`
|
||||
- build web + server
|
||||
- run `bun publish --access public`
|
||||
|
||||
## 1) Dry-run release without signing
|
||||
|
||||
Use this first to validate the release pipeline.
|
||||
|
||||
1. Confirm no signing secrets are required for this test.
|
||||
2. Create a test tag:
|
||||
- `git tag v0.0.0-test.1`
|
||||
- `git push origin v0.0.0-test.1`
|
||||
3. Wait for `.github/workflows/release.yml` to finish.
|
||||
4. Verify the GitHub Release contains all platform artifacts.
|
||||
5. Download each artifact and sanity-check installation on each OS.
|
||||
|
||||
## 2) Apple signing + notarization setup (macOS)
|
||||
|
||||
Required secrets used by the workflow:
|
||||
|
||||
- `CSC_LINK`
|
||||
- `CSC_KEY_PASSWORD`
|
||||
- `APPLE_API_KEY`
|
||||
- `APPLE_API_KEY_ID`
|
||||
- `APPLE_API_ISSUER`
|
||||
|
||||
Checklist:
|
||||
|
||||
1. Apple Developer account access:
|
||||
- Team has rights to create Developer ID certificates.
|
||||
2. Create `Developer ID Application` certificate.
|
||||
3. Export certificate + private key as `.p12` from Keychain.
|
||||
4. Base64-encode the `.p12` and store as `CSC_LINK`.
|
||||
5. Store the `.p12` export password as `CSC_KEY_PASSWORD`.
|
||||
6. In App Store Connect, create an API key (Team key).
|
||||
7. Add API key values:
|
||||
- `APPLE_API_KEY`: contents of the downloaded `.p8`
|
||||
- `APPLE_API_KEY_ID`: Key ID
|
||||
- `APPLE_API_ISSUER`: Issuer ID
|
||||
8. Re-run a tag release and confirm macOS artifacts are signed/notarized.
|
||||
|
||||
Notes:
|
||||
|
||||
- `APPLE_API_KEY` is stored as raw key text in secrets.
|
||||
- The workflow writes it to a temporary `AuthKey_<id>.p8` file at runtime.
|
||||
|
||||
## 3) Azure Trusted Signing setup (Windows)
|
||||
|
||||
Required secrets used by the workflow:
|
||||
|
||||
- `AZURE_TENANT_ID`
|
||||
- `AZURE_CLIENT_ID`
|
||||
- `AZURE_CLIENT_SECRET`
|
||||
- `AZURE_TRUSTED_SIGNING_ENDPOINT`
|
||||
- `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`
|
||||
- `AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`
|
||||
- `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`
|
||||
|
||||
Checklist:
|
||||
|
||||
1. Create Azure Trusted Signing account and certificate profile.
|
||||
2. Record ATS values:
|
||||
- Endpoint
|
||||
- Account name
|
||||
- Certificate profile name
|
||||
- Publisher name
|
||||
3. Create/choose an Entra app registration (service principal).
|
||||
4. Grant service principal permissions required by Trusted Signing.
|
||||
5. Create a client secret for the service principal.
|
||||
6. Add Azure secrets listed above in GitHub Actions secrets.
|
||||
7. Re-run a tag release and confirm Windows installer is signed.
|
||||
|
||||
## 4) Ongoing release checklist
|
||||
|
||||
1. Ensure `main` is green in CI.
|
||||
2. Bump app version as needed.
|
||||
3. Create release tag: `vX.Y.Z`.
|
||||
4. Push tag.
|
||||
5. Verify workflow steps:
|
||||
- preflight passes
|
||||
- all matrix builds pass
|
||||
- release job uploads expected files
|
||||
6. Smoke test downloaded artifacts.
|
||||
|
||||
## 5) Troubleshooting
|
||||
|
||||
- macOS build unsigned when expected signed:
|
||||
- Check all Apple secrets are populated and non-empty.
|
||||
- Windows build unsigned when expected signed:
|
||||
- Check all Azure ATS and auth secrets are populated and non-empty.
|
||||
- Build fails with signing error:
|
||||
- Retry with secrets removed to confirm unsigned path still works.
|
||||
- Re-check certificate/profile names and tenant/client credentials.
|
||||
+8
-3
@@ -29,13 +29,18 @@
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"dist:desktop:dmg": "node scripts/build-desktop-dmg.mjs",
|
||||
"dist:desktop:dmg:arm64": "node scripts/build-desktop-dmg.mjs --arch arm64",
|
||||
"dist:desktop:dmg:x64": "node scripts/build-desktop-dmg.mjs --arch x64",
|
||||
"dist:desktop:artifact": "node scripts/build-desktop-artifact.ts",
|
||||
"dist:desktop:dmg": "node scripts/build-desktop-artifact.ts --platform mac --target dmg",
|
||||
"dist:desktop:dmg:arm64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch arm64",
|
||||
"dist:desktop:dmg:x64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch x64",
|
||||
"dist:desktop:linux": "node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64",
|
||||
"dist:desktop:win": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64",
|
||||
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
|
||||
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"oxfmt": "^0.35.0",
|
||||
"oxlint": "^1.50.0",
|
||||
"turbo": "^2.3.3",
|
||||
|
||||
@@ -23,6 +23,8 @@ export type GitStatusPrState = typeof GitStatusPrState.Type;
|
||||
|
||||
export const GitBranch = Schema.Struct({
|
||||
name: TrimmedNonEmptyStringSchema,
|
||||
isRemote: Schema.optional(Schema.Boolean),
|
||||
remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
current: Schema.Boolean,
|
||||
isDefault: Schema.Boolean,
|
||||
worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
|
||||
|
||||
@@ -22,9 +22,14 @@ describe("normalizeModelSlug", () => {
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default for missing and unknown models", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("gpt-4.1")).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");
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
|
||||
@@ -5,11 +5,12 @@ export const MODEL_OPTIONS = [
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
] as const;
|
||||
|
||||
export type ModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type BuiltInModelSlug = (typeof MODEL_OPTIONS)[number]["slug"];
|
||||
export type ModelSlug = string;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, ModelSlug> = {
|
||||
export const MODEL_SLUG_ALIASES: Record<string, BuiltInModelSlug> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
@@ -26,16 +27,12 @@ export function normalizeModelSlug(model: string | null | undefined): ModelSlug
|
||||
return null;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ModelSlug);
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined): ModelSlug {
|
||||
const normalized = normalizeModelSlug(model);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
return MODEL_OPTIONS.some((option) => option.slug === normalized) ? normalized : DEFAULT_MODEL;
|
||||
return normalized ?? DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
#!/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(flag, () => 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",
|
||||
cause: command,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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,
|
||||
};
|
||||
if (!options.signed) {
|
||||
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
|
||||
}
|
||||
|
||||
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 --bun electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
|
||||
);
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
if (!(yield* fs.exists(stageDistDir))) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but dist directory was not found at ${stageDistDir}`,
|
||||
});
|
||||
}
|
||||
|
||||
const stageEntries = yield* fs.readDirectory(stageDistDir);
|
||||
yield* fs.makeDirectory(options.outputDir, { recursive: true });
|
||||
|
||||
const copiedArtifacts: string[] = [];
|
||||
for (const entry of stageEntries) {
|
||||
const from = path.join(stageDistDir, entry);
|
||||
const stat = yield* fs.stat(from).pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!stat || stat.type !== "File") continue;
|
||||
|
||||
const to = path.join(options.outputDir, entry);
|
||||
yield* fs.copyFile(from, to);
|
||||
copiedArtifacts.push(to);
|
||||
}
|
||||
|
||||
if (copiedArtifacts.length === 0) {
|
||||
return yield* new BuildScriptError({
|
||||
message: `Build completed but no files were produced in ${stageDistDir}`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
|
||||
Effect.annotateLogs({ artifacts: copiedArtifacts }),
|
||||
);
|
||||
});
|
||||
|
||||
const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
|
||||
platform: Flag.choice("platform", BuildPlatform.literals).pipe(
|
||||
Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
|
||||
Flag.optional,
|
||||
),
|
||||
target: Flag.string("target").pipe(
|
||||
Flag.withDescription(
|
||||
"Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
arch: Flag.choice("arch", BuildArch.literals).pipe(
|
||||
Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
|
||||
Flag.optional,
|
||||
),
|
||||
buildVersion: Flag.string("build-version").pipe(
|
||||
Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),
|
||||
Flag.optional,
|
||||
),
|
||||
outputDir: Flag.string("output-dir").pipe(
|
||||
Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
|
||||
Flag.optional,
|
||||
),
|
||||
skipBuild: Flag.boolean("skip-build").pipe(
|
||||
Flag.withDescription(
|
||||
"Skip `bun run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
keepStage: Flag.boolean("keep-stage").pipe(
|
||||
Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
|
||||
Flag.optional,
|
||||
),
|
||||
signed: Flag.boolean("signed").pipe(
|
||||
Flag.withDescription(
|
||||
"Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
|
||||
),
|
||||
Flag.optional,
|
||||
),
|
||||
verbose: Flag.boolean("verbose").pipe(
|
||||
Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
|
||||
Flag.optional,
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Build a desktop artifact for T3 Code."),
|
||||
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
|
||||
);
|
||||
|
||||
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(Logger.layer([Logger.consolePretty()])),
|
||||
Effect.provide(NodeServices.layer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,392 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const PRODUCTION_ICON_SOURCE = path.join(repoRoot, "assets/macos-icon-1024.png");
|
||||
|
||||
const ARCH_CHOICES = new Set(["arm64", "x64", "universal"]);
|
||||
|
||||
function printUsage() {
|
||||
console.log(`Build a shareable macOS .dmg for T3 Code desktop.
|
||||
|
||||
Usage:
|
||||
node scripts/build-desktop-dmg.mjs [options]
|
||||
|
||||
Options:
|
||||
--arch <arm64|x64|universal> Target arch (default: host arch if supported)
|
||||
--version <semver> App version in DMG metadata (default: apps/server version)
|
||||
--output-dir <path> Output folder for final artifacts (default: release)
|
||||
--skip-build Skip 'bun run build:desktop' (requires existing dist artifacts)
|
||||
--keep-stage Keep temporary staging directory
|
||||
--signed Allow automatic code signing discovery
|
||||
--help Show this message
|
||||
`);
|
||||
}
|
||||
|
||||
function fail(message) {
|
||||
console.error(`[desktop-dmg] ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const defaultArch = process.arch === "arm64" || process.arch === "x64" ? process.arch : "arm64";
|
||||
const options = {
|
||||
arch: defaultArch,
|
||||
version: null,
|
||||
skipBuild: false,
|
||||
keepStage: false,
|
||||
signed: false,
|
||||
outputDir: path.join(repoRoot, "release"),
|
||||
};
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const arg = argv[i];
|
||||
if (arg === "--help") {
|
||||
options.help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--skip-build") {
|
||||
options.skipBuild = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--keep-stage") {
|
||||
options.keepStage = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--signed") {
|
||||
options.signed = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === "--arch" || arg === "--version" || arg === "--output-dir") {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.startsWith("--")) {
|
||||
fail(`Missing value for ${arg}`);
|
||||
}
|
||||
i += 1;
|
||||
if (arg === "--arch") options.arch = value;
|
||||
if (arg === "--version") options.version = value;
|
||||
if (arg === "--output-dir") options.outputDir = path.resolve(repoRoot, value);
|
||||
continue;
|
||||
}
|
||||
fail(`Unknown argument: ${arg}`);
|
||||
}
|
||||
|
||||
if (!ARCH_CHOICES.has(options.arch)) {
|
||||
fail(`Invalid arch '${options.arch}'. Expected one of: ${Array.from(ARCH_CHOICES).join(", ")}`);
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
async function readJson(filePath) {
|
||||
const raw = await fs.readFile(filePath, "utf8");
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
async function exists(filePath) {
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function run(command, args, { cwd, env = process.env, stdio = "inherit" } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd,
|
||||
env,
|
||||
stdio,
|
||||
});
|
||||
|
||||
child.on("error", reject);
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
reject(new Error(`${command} exited via signal ${signal}`));
|
||||
return;
|
||||
}
|
||||
if (code !== 0) {
|
||||
reject(new Error(`${command} exited with code ${code}`));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
|
||||
const iconsetDir = path.join(tmpRoot, "icon.iconset");
|
||||
await fs.mkdir(iconsetDir, { recursive: true });
|
||||
|
||||
const iconSizes = [16, 32, 128, 256, 512];
|
||||
for (const size of iconSizes) {
|
||||
await run(
|
||||
"sips",
|
||||
[
|
||||
"-z",
|
||||
String(size),
|
||||
String(size),
|
||||
sourcePng,
|
||||
"--out",
|
||||
path.join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
const retinaSize = size * 2;
|
||||
await run(
|
||||
"sips",
|
||||
[
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
sourcePng,
|
||||
"--out",
|
||||
path.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
],
|
||||
{ stdio: "ignore" },
|
||||
);
|
||||
}
|
||||
|
||||
await run("iconutil", ["-c", "icns", iconsetDir, "-o", targetIcns], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
async function stageProductionIcons(stageResourcesDir) {
|
||||
if (!(await exists(PRODUCTION_ICON_SOURCE))) {
|
||||
fail(`Production icon source is missing at ${PRODUCTION_ICON_SOURCE}`);
|
||||
}
|
||||
|
||||
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "t3code-icon-build-"));
|
||||
try {
|
||||
const iconPngPath = path.join(stageResourcesDir, "icon.png");
|
||||
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
|
||||
await run("sips", ["-z", "512", "512", PRODUCTION_ICON_SOURCE, "--out", iconPngPath], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
await generateMacIconSet(PRODUCTION_ICON_SOURCE, iconIcnsPath, tmpRoot);
|
||||
} finally {
|
||||
await fs.rm(tmpRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function validateBundledClientAssets(clientDir) {
|
||||
const indexPath = path.join(clientDir, "index.html");
|
||||
const indexHtml = await fs.readFile(indexPath, "utf8");
|
||||
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map((match) => match[1]);
|
||||
const missing = [];
|
||||
|
||||
for (const ref of refs) {
|
||||
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
|
||||
if (!normalizedRef) continue;
|
||||
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
|
||||
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
|
||||
|
||||
const ext = path.extname(normalizedRef);
|
||||
if (!ext) continue;
|
||||
|
||||
const relativePath = normalizedRef.replace(/^\/+/, "");
|
||||
const assetPath = path.join(clientDir, relativePath);
|
||||
if (!(await exists(assetPath))) {
|
||||
missing.push(normalizedRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
const preview = missing.slice(0, 6).join(", ");
|
||||
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
|
||||
fail(
|
||||
`Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function readWorkspaceCatalog(rootPackageJson) {
|
||||
const workspaces = rootPackageJson?.workspaces;
|
||||
if (!workspaces || typeof workspaces !== "object" || Array.isArray(workspaces)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const catalog = workspaces.catalog;
|
||||
if (!catalog || typeof catalog !== "object" || Array.isArray(catalog)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return catalog;
|
||||
}
|
||||
|
||||
function resolveCatalogDependencies(dependencies, catalog, dependencySourceLabel) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(dependencies).map(([dependencyName, spec]) => {
|
||||
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
|
||||
return [dependencyName, spec];
|
||||
}
|
||||
|
||||
const catalogKey = spec.slice("catalog:".length).trim();
|
||||
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
|
||||
const resolvedSpec = catalog[lookupKey];
|
||||
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
|
||||
fail(
|
||||
`Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. ` +
|
||||
`Expected key '${lookupKey}' in root workspace catalog.`,
|
||||
);
|
||||
}
|
||||
|
||||
return [dependencyName, resolvedSpec];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (options.help) {
|
||||
printUsage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (process.platform !== "darwin") {
|
||||
fail("This script only builds macOS .dmg artifacts and must run on macOS.");
|
||||
}
|
||||
|
||||
const rootPkg = await readJson(path.join(repoRoot, "package.json"));
|
||||
const desktopPkg = await readJson(path.join(repoRoot, "apps/desktop/package.json"));
|
||||
const serverPkg = await readJson(path.join(repoRoot, "apps/server/package.json"));
|
||||
|
||||
const electronVersion = desktopPkg.dependencies?.electron;
|
||||
if (typeof electronVersion !== "string" || electronVersion.length === 0) {
|
||||
fail("Could not resolve apps/desktop electron dependency version.");
|
||||
}
|
||||
|
||||
const dependencies = serverPkg.dependencies;
|
||||
if (!dependencies || Object.keys(dependencies).length === 0) {
|
||||
fail("Could not resolve production dependencies from apps/server/package.json.");
|
||||
}
|
||||
const resolvedDependencies = resolveCatalogDependencies(
|
||||
dependencies,
|
||||
readWorkspaceCatalog(rootPkg),
|
||||
"apps/server",
|
||||
);
|
||||
|
||||
const appVersion = options.version ?? serverPkg.version ?? "0.1.0";
|
||||
const stageRoot = path.join(os.tmpdir(), "t3code-desktop-dmg-stage");
|
||||
const stageAppDir = path.join(stageRoot, "app");
|
||||
const distDirs = {
|
||||
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
|
||||
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
|
||||
serverDist: path.join(repoRoot, "apps/server/dist"),
|
||||
};
|
||||
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
|
||||
|
||||
if (!options.skipBuild) {
|
||||
console.log("[desktop-dmg] Building desktop/server/web artifacts...");
|
||||
await run("bun", ["run", "build:desktop"], { cwd: repoRoot });
|
||||
}
|
||||
|
||||
for (const [label, dir] of Object.entries(distDirs)) {
|
||||
if (!(await exists(dir))) {
|
||||
fail(`Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`);
|
||||
}
|
||||
}
|
||||
if (!(await exists(bundledClientEntry))) {
|
||||
fail(
|
||||
`Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
|
||||
);
|
||||
}
|
||||
await validateBundledClientAssets(path.dirname(bundledClientEntry));
|
||||
|
||||
await fs.rm(stageRoot, { recursive: true, force: true });
|
||||
await fs.mkdir(path.join(stageAppDir, "apps/desktop"), { recursive: true });
|
||||
await fs.mkdir(path.join(stageAppDir, "apps/server"), { recursive: true });
|
||||
|
||||
console.log("[desktop-dmg] Staging release app...");
|
||||
await fs.cp(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"), {
|
||||
recursive: true,
|
||||
});
|
||||
await fs.cp(distDirs.desktopResources, path.join(stageAppDir, "apps/desktop/resources"), {
|
||||
recursive: true,
|
||||
});
|
||||
await fs.cp(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"), { recursive: true });
|
||||
await stageProductionIcons(path.join(stageAppDir, "apps/desktop/resources"));
|
||||
|
||||
const stagePackageJson = {
|
||||
name: "t3-code-desktop",
|
||||
version: appVersion,
|
||||
private: true,
|
||||
description: "T3 Code desktop build",
|
||||
author: "T3 Tools",
|
||||
main: "apps/desktop/dist-electron/main.js",
|
||||
build: {
|
||||
appId: "com.t3tools.t3code",
|
||||
productName: desktopPkg.productName ?? "T3 Code",
|
||||
artifactName: "T3-Code-${version}-${arch}.${ext}",
|
||||
directories: {
|
||||
buildResources: "apps/desktop/resources",
|
||||
},
|
||||
mac: {
|
||||
target: ["dmg"],
|
||||
icon: "icon.icns",
|
||||
category: "public.app-category.developer-tools",
|
||||
},
|
||||
},
|
||||
dependencies: resolvedDependencies,
|
||||
devDependencies: {
|
||||
electron: electronVersion,
|
||||
},
|
||||
};
|
||||
|
||||
await fs.writeFile(
|
||||
path.join(stageAppDir, "package.json"),
|
||||
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
console.log("[desktop-dmg] Installing staged production dependencies...");
|
||||
await run("bun", ["install", "--production"], { cwd: stageAppDir });
|
||||
|
||||
const buildEnv = {
|
||||
...process.env,
|
||||
};
|
||||
if (!options.signed) {
|
||||
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
|
||||
}
|
||||
|
||||
const buildArgs = ["--bun", "electron-builder", "--mac", "dmg", `--${options.arch}`];
|
||||
console.log(`[desktop-dmg] Building .dmg (arch=${options.arch}, version=${appVersion})...`);
|
||||
await run("bunx", buildArgs, { cwd: stageAppDir, env: buildEnv });
|
||||
|
||||
const stageDistDir = path.join(stageAppDir, "dist");
|
||||
const stageFiles = await fs.readdir(stageDistDir);
|
||||
const dmgFiles = stageFiles.filter((file) => file.endsWith(".dmg"));
|
||||
if (dmgFiles.length === 0) {
|
||||
fail(`Build completed but no .dmg found in ${stageDistDir}`);
|
||||
}
|
||||
|
||||
await fs.mkdir(options.outputDir, { recursive: true });
|
||||
const copiedArtifacts = [];
|
||||
for (const file of stageFiles) {
|
||||
if (!file.endsWith(".dmg") && !file.endsWith(".dmg.blockmap")) continue;
|
||||
const from = path.join(stageDistDir, file);
|
||||
const to = path.join(options.outputDir, file);
|
||||
await fs.copyFile(from, to);
|
||||
copiedArtifacts.push(to);
|
||||
}
|
||||
|
||||
if (!options.keepStage) {
|
||||
await fs.rm(stageRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
console.log("[desktop-dmg] Done. Artifacts:");
|
||||
for (const artifact of copiedArtifacts) {
|
||||
console.log(` - ${artifact}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
fail(message);
|
||||
});
|
||||
Reference in new issue
Block a user