Compare commits

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

No files matched your search

-309
View File
@@ -1,309 +0,0 @@
name: Release Desktop
on:
push:
tags:
- "v*.*.*"
workflow_dispatch:
inputs:
version:
description: "Release version (for example 1.2.3 or v1.2.3)"
required: true
type: string
permissions:
contents: write
id-token: write
jobs:
preflight:
name: Preflight
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.release_meta.outputs.version }}
tag: ${{ steps.release_meta.outputs.tag }}
ref: ${{ steps.release_ref.outputs.value }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- id: release_meta
name: Resolve release version
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
raw="${{ github.event.inputs.version }}"
else
raw="${GITHUB_REF_NAME}"
fi
version="${raw#v}"
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
echo "Invalid release version: $raw" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
echo "tag=v$version" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Update version strings
if: github.event_name == 'workflow_dispatch'
env:
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
run: |
node --input-type=module -e '
import { readFileSync, writeFileSync } from "node:fs";
const files = [
"apps/server/package.json",
"apps/desktop/package.json",
"apps/web/package.json",
"packages/contracts/package.json",
];
for (const file of files) {
const packageJson = JSON.parse(readFileSync(file, "utf8"));
packageJson.version = process.env.RELEASE_VERSION;
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
}
'
- name: Refresh lockfile
if: github.event_name == 'workflow_dispatch'
run: bun install
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- name: Test
run: bun run test
- name: Commit and push release version + tag
if: github.event_name == 'workflow_dispatch'
shell: bash
env:
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
run: |
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
echo "Tag $RELEASE_TAG already exists on origin." >&2
exit 1
fi
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG" -m "Co-authored-by: codex <[email protected]>"
fi
git tag "$RELEASE_TAG"
git push origin "HEAD:${GITHUB_REF_NAME}"
git push origin "refs/tags/$RELEASE_TAG"
- id: release_ref
name: Resolve source ref
shell: bash
run: |
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
else
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.label }}
needs: preflight
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- label: macOS arm64
runner: macos-14
platform: mac
target: dmg
arch: arm64
- label: macOS x64
runner: macos-15-intel
platform: mac
target: dmg
arch: x64
- label: Linux x64
runner: ubuntu-24.04
platform: linux
target: AppImage
arch: x64
- label: Windows x64
runner: windows-2022
platform: win
target: nsis
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Build desktop artifact
shell: bash
env:
CSC_LINK: ${{ secrets.CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
args=(
--platform "${{ matrix.platform }}"
--target "${{ matrix.target }}"
--arch "${{ matrix.arch }}"
--build-version "${{ needs.preflight.outputs.version }}"
)
has_all() {
for value in "$@"; do
if [[ -z "$value" ]]; then
return 1
fi
done
return 0
}
if [[ "${{ matrix.platform }}" == "mac" ]]; then
if has_all "$CSC_LINK" "$CSC_KEY_PASSWORD" "$APPLE_API_KEY" "$APPLE_API_KEY_ID" "$APPLE_API_ISSUER"; then
key_path="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"
printf '%s' "$APPLE_API_KEY" > "$key_path"
export APPLE_API_KEY="$key_path"
echo "macOS signing enabled."
args+=(--signed)
else
echo "macOS signing disabled (missing one or more Apple signing secrets)."
fi
elif [[ "${{ matrix.platform }}" == "win" ]]; then
if has_all \
"$AZURE_TENANT_ID" \
"$AZURE_CLIENT_ID" \
"$AZURE_CLIENT_SECRET" \
"$AZURE_TRUSTED_SIGNING_ENDPOINT" \
"$AZURE_TRUSTED_SIGNING_ACCOUNT_NAME" \
"$AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME" \
"$AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"; then
echo "Windows signing enabled (Azure Trusted Signing)."
args+=(--signed)
else
echo "Windows signing disabled (missing one or more Azure Trusted Signing secrets)."
fi
else
echo "Signing disabled for ${{ matrix.platform }}."
fi
bun run dist:desktop:artifact -- "${args[@]}"
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release/*
if-no-files-found: error
# publish_cli:
# name: Publish CLI to npm
# needs: [preflight, build]
# runs-on: ubuntu-24.04
# steps:
# - name: Checkout
# uses: actions/checkout@v4
# - name: Setup Bun
# uses: oven-sh/setup-bun@v2
# with:
# bun-version-file: package.json
# - name: Setup Node
# uses: actions/setup-node@v4
# with:
# node-version-file: package.json
# registry-url: https://registry.npmjs.org
# - name: Install dependencies
# run: bun install --frozen-lockfile
# - name: Set CLI package version from release tag
# env:
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
# run: |
# node --input-type=module -e '
# import { readFileSync, writeFileSync } from "node:fs";
# const packagePath = "apps/server/package.json";
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
# packageJson.version = process.env.RELEASE_VERSION;
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
# '
# - name: Build CLI package
# run: bun run build --filter=@t3tools/web --filter=t3
# - name: Publish CLI package
# run: bun --cwd apps/server publish --access public
release:
name: Publish GitHub Release
needs: [preflight, build]
# needs: [preflight, build, publish_cli]
runs-on: ubuntu-24.04
steps:
- name: Download all desktop artifacts
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
path: release-assets
- name: Publish release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.preflight.outputs.tag }}
name: T3 Code v${{ needs.preflight.outputs.version }}
generate_release_notes: true
files: release-assets/*
fail_on_unmatched_files: true
+1 -8
View File
@@ -1,9 +1,5 @@
# CLAUDE.md
## Task Completion Requirements
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
## Project Snapshot
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
@@ -22,7 +18,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
- `packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
## Codex App Server (Important)
@@ -45,6 +41,3 @@ Docs:
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
<!-- Dummy change: placeholder note for testing edits. -->
<!-- Dummy change: second placeholder note for edit validation. -->
-12
View File
@@ -75,11 +75,8 @@ npx t3
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
### Desktop `.dmg` packaging notes
@@ -89,12 +86,6 @@ npx t3
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
- Windows `--signed` uses Azure Trusted Signing and expects:
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
- Azure authentication env vars are also required (for example service principal with secret):
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
### Running multiple dev instances
@@ -131,6 +122,3 @@ Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI
## CI quality gates
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
- See `docs/release.md` for full release/signing setup checklist.
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -18,7 +18,7 @@
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@types/node": "^24.10.13",
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
+16 -138
View File
@@ -5,10 +5,9 @@ import net from "node:net";
import os from "node:os";
import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import type { ContextMenuItem } from "@t3tools/contracts";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
@@ -26,8 +25,6 @@ const ROOT_DIR = path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
const COMMIT_HASH_DISPLAY_LENGTH = 12;
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess | null = null;
@@ -38,32 +35,6 @@ let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
let desktopProtocolRegistered = false;
let aboutCommitHashCache: string | null | undefined;
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
if (process.platform !== "darwin") return undefined;
if (destructiveMenuIconCache !== undefined) {
return destructiveMenuIconCache ?? undefined;
}
try {
const icon = nativeImage.createFromNamedImage("trash").resize({
width: 14,
height: 14,
});
if (icon.isEmpty()) {
destructiveMenuIconCache = null;
return undefined;
}
icon.setTemplateImage(true);
destructiveMenuIconCache = icon;
return icon;
} catch {
destructiveMenuIconCache = null;
return undefined;
}
}
protocol.registerSchemesAsPrivileged([
{
@@ -84,54 +55,6 @@ function resolveAppRoot(): string {
return app.getAppPath();
}
function normalizeCommitHash(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
if (!COMMIT_HASH_PATTERN.test(trimmed)) {
return null;
}
return trimmed.slice(0, COMMIT_HASH_DISPLAY_LENGTH).toLowerCase();
}
function resolveEmbeddedCommitHash(): string | null {
const packageJsonPath = path.join(resolveAppRoot(), "package.json");
if (!fs.existsSync(packageJsonPath)) {
return null;
}
try {
const raw = fs.readFileSync(packageJsonPath, "utf8");
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
return normalizeCommitHash(parsed.t3codeCommitHash);
} catch {
return null;
}
}
function resolveAboutCommitHash(): string | null {
if (aboutCommitHashCache !== undefined) {
return aboutCommitHashCache;
}
const envCommitHash = normalizeCommitHash(process.env.T3CODE_COMMIT_HASH);
if (envCommitHash) {
aboutCommitHashCache = envCommitHash;
return aboutCommitHashCache;
}
// Only packaged builds are required to expose commit metadata.
if (!app.isPackaged) {
aboutCommitHashCache = null;
return aboutCommitHashCache;
}
aboutCommitHashCache = resolveEmbeddedCommitHash();
return aboutCommitHashCache;
}
function resolveBackendEntry(): string {
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
@@ -328,11 +251,8 @@ function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
function configureAppIdentity(): void {
app.setName(APP_DISPLAY_NAME);
const commitHash = resolveAboutCommitHash();
app.setAboutPanelOptions({
applicationName: APP_DISPLAY_NAME,
applicationVersion: app.getVersion(),
version: commitHash ?? "unknown",
});
if (process.platform === "win32") {
@@ -477,65 +397,23 @@ function registerIpcHandlers(): void {
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
id: item.id,
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
if (!window) return null;
return new Promise<string | null>((resolve) => {
const menu = Menu.buildFromTemplate(
items.map((item) => ({
label: item.label,
destructive: item.destructive === true,
}));
if (normalizedItems.length === 0) {
return null;
}
const popupPosition =
position &&
Number.isFinite(position.x) &&
Number.isFinite(position.y) &&
position.x >= 0 &&
position.y >= 0
? {
x: Math.floor(position.x),
y: Math.floor(position.y),
}
: null;
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
if (!window) return null;
return new Promise<string | null>((resolve) => {
const template: MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
for (const item of normalizedItems) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
hasInsertedDestructiveSeparator = true;
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
click: () => resolve(item.id),
};
if (item.destructive) {
const destructiveIcon = getDestructiveMenuIcon();
if (destructiveIcon) {
itemOption.icon = destructiveIcon;
}
}
template.push(itemOption);
}
const menu = Menu.buildFromTemplate(template);
menu.popup({
window,
...popupPosition,
callback: () => resolve(null),
});
click: () => resolve(item.id),
})),
);
menu.popup({
window,
callback: () => resolve(null),
});
},
);
});
});
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
+1 -1
View File
@@ -12,7 +12,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
showContextMenu: (items) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.0-alpha.4",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs"
},
@@ -32,7 +32,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
@@ -19,17 +19,6 @@ const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return {
...document.schema,
$defs: document.definitions,
};
}
return document.schema;
}
function normalizeCodexError(
operation: string,
error: unknown,
@@ -215,7 +204,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
JSON.stringify(Schema.toJsonSchemaDocument(outputSchemaJson).schema),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
-347
View File
@@ -274,18 +274,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
expect(result.branches.some((branch) => branch.current)).toBe(false);
}),
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -390,82 +378,6 @@ it.layer(TestLayer)("git integration", (it) => {
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
it.effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
const remoteOnlyBranch = "feature/remote-only";
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
);
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
).toBe(true);
expect(
result.branches.some(
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
),
).toBe(true);
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
const remoteName = "my-org/upstream";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", remoteName, remote]);
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
const remoteOnlyBranch = "feature/remote-with-remote-name";
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const remoteBranch = result.branches.find(
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
);
expect(remoteBranch).toBeDefined();
expect(remoteBranch?.isRemote).toBe(true);
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
});
// ── checkoutGitBranch ──
@@ -688,87 +600,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"does not silently checkout a local branch when a remote ref no longer exists",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["push", "-u", remoteName, featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
}),
);
it.effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
// Keep local branch but remove tracking so `--track origin/<branch>`
// would attempt to create an already-existing local branch.
yield* git(source, ["branch", "--unset-upstream"]);
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
const core = yield* GitCore;
const status = yield* core.statusDetails(source);
expect(status.branch).toBeNull();
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1272,135 +1103,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature commit"]);
const details = yield* core.statusDetails(tmp);
expect(details.branch).toBe("feature/no-upstream-ahead");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect(
"computes ahead count against origin/default when local default branch is missing",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of origin/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/remote-base-only");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("skipped_up_to_date");
expect(pushed.branch).toBe("feature/no-upstream-no-ahead");
expect(pushed.setUpstream).toBeUndefined();
}),
);
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(tmp, ["init", "--initial-branch=trunk"]);
yield* git(tmp, ["config", "user.email", "[email protected]"]);
yield* git(tmp, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
yield* git(tmp, ["add", "README.md"]);
yield* git(tmp, ["commit", "-m", "initial"]);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["checkout", "-b", "feature/no-base"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe("origin/feature/no-base");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/no-base",
);
}),
);
it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n");
yield* git(tmp, ["add", "default-ahead.txt"]);
yield* git(tmp, ["commit", "-m", "default ahead"]);
const featureBranch = "feature/publish-no-upstream";
yield* git(tmp, ["checkout", "-b", featureBranch]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`origin/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1582,54 +1284,5 @@ it.layer(TestLayer)("git integration", (it) => {
expect(didFailRecency).toBe(true);
}),
);
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
const realGitService = yield* GitService;
let didFailRemoteBranches = false;
let didFailRemoteNames = false;
const core = yield* makeIsolatedGitCore({
execute: (input) => {
if (input.args.join(" ") === "branch --no-color --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteBranches",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
if (input.args.join(" ") === "remote") {
didFailRemoteNames = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteNames",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
return realGitService.execute(input);
},
});
const result = yield* core.listBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
expect(didFailRemoteBranches).toBe(true);
expect(didFailRemoteNames).toBe(true);
}),
);
});
});
+47 -426
View File
@@ -7,7 +7,6 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
@@ -77,98 +76,10 @@ function parsePorcelainPath(line: string): string | null {
return filePath.length > 0 ? filePath : null;
}
function parseBranchLine(line: string): { name: string; current: boolean } | null {
const trimmed = line.trim();
if (trimmed.length === 0) return null;
const name = trimmed.replace(/^[*+]\s+/, "");
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
if (name.includes(" -> ") || name.startsWith("(")) return null;
return {
name,
current: trimmed.startsWith("* "),
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return null;
}
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
for (const line of stdout.split("\n")) {
const trimmedLine = line.trim();
if (trimmedLine.length === 0) {
continue;
}
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
const branchName = branchNameRaw?.trim() ?? "";
const upstreamBranch = upstreamBranchRaw.trim();
if (branchName.length === 0 || upstreamBranch.length === 0) {
continue;
}
if (upstreamBranch === upstreamRef) {
return branchName;
}
}
return null;
}
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
const separatorIndex = branchName.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
return null;
}
const localBranch = branchName.slice(separatorIndex + 1).trim();
return localBranch.length > 0 ? localBranch : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
const trimmed = value.trim();
const prefix = "refs/remotes/origin/";
if (!trimmed.startsWith(prefix)) {
return null;
}
const branch = trimmed.slice(prefix.length).trim();
return branch.length > 0 ? branch : null;
}
function createGitCommandError(
operation: string,
cwd: string,
@@ -385,117 +296,12 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
executeGit(
"GitCore.resolveDefaultBranchName",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{ allowNonZeroExit: true },
).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
}),
);
const remoteBranchExists = (
cwd: string,
branch: string,
): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.remoteBranchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
{
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0));
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const resolveBaseBranchForNoUpstream = (
cwd: string,
branch: string,
): Effect.Effect<string | null, GitCommandError> =>
Effect.gen(function* () {
const configuredBaseBranch = yield* runGitStdout(
"GitCore.resolveBaseBranchForNoUpstream.config",
cwd,
["config", "--get", `branch.${branch}.gh-merge-base`],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const defaultBranch = yield* resolveDefaultBranchName(cwd);
const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch,
...DEFAULT_BASE_BRANCH_CANDIDATES,
];
for (const candidate of candidates) {
if (!candidate) {
continue;
}
const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length)
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue;
}
if (yield* branchExists(cwd, normalizedCandidate)) {
return normalizedCandidate;
}
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
return `origin/${normalizedCandidate}`;
}
}
return null;
});
const computeAheadCountAgainstBase = (
cwd: string,
branch: string,
): Effect.Effect<number, GitCommandError> =>
Effect.gen(function* () {
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
if (!baseBranch) {
return 0;
}
const result = yield* executeGit(
"GitCore.computeAheadCountAgainstBase",
cwd,
["rev-list", "--count", `${baseBranch}..HEAD`],
{ allowNonZeroExit: true },
);
if (result.code !== 0) {
return 0;
}
const parsed = Number.parseInt(result.stdout.trim(), 10);
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
});
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
Effect.gen(function* () {
const branchRecency = yield* executeGit(
"GitCore.readBranchRecency",
cwd,
[
"for-each-ref",
"--format=%(refname:short)%09%(committerdate:unix)",
"refs/heads",
"refs/remotes",
],
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
@@ -574,14 +380,6 @@ const makeGitCore = Effect.gen(function* () {
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
if (!upstreamRef && branch) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(0)),
);
behindCount = 0;
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
@@ -691,40 +489,12 @@ const makeGitCore = Effect.gen(function* () {
);
}
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
if (hasNoLocalDelta) {
if (details.hasUpstream) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (comparableBaseBranch) {
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (!hasOriginRemote) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (hasRemoteBranch) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
if (!details.hasUpstream) {
@@ -831,7 +601,7 @@ const makeGitCore = Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
);
const localBranchResult = yield* executeGit(
const result = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color"],
@@ -841,8 +611,8 @@ const makeGitCore = Effect.gen(function* () {
},
);
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
@@ -854,79 +624,31 @@ const makeGitCore = Effect.gen(function* () {
);
}
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
input.cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
executeGit(
"GitCore.listBranches.worktreeList",
input.cwd,
["worktree", "list", "--porcelain"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
branchRecencyPromise,
],
{ concurrency: "unbounded" },
);
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",
input.cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
),
executeGit(
"GitCore.listBranches.worktreeList",
input.cwd,
["worktree", "list", "--porcelain"],
{
timeoutMs: 5_000,
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\//, "")
@@ -951,17 +673,19 @@ const makeGitCore = Effect.gen(function* () {
}
}
const localBranches = localBranchResult.stdout
const branches = result.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => ({
name: branch.name,
current: branch.current,
isRemote: false,
isDefault: branch.name === defaultBranch,
worktreePath: worktreeMap.get(branch.name) ?? null,
}))
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
@@ -973,43 +697,6 @@ const makeGitCore = Effect.gen(function* () {
return a.name.localeCompare(b.name);
});
const remoteBranches =
remoteBranchResult.code === 0
? remoteBranchResult.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => {
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
const remoteBranch: {
name: string;
current: boolean;
isRemote: boolean;
remoteName?: string;
isDefault: boolean;
worktreePath: string | null;
} = {
name: branch.name,
current: false,
isRemote: true,
isDefault: false,
worktreePath: null,
};
if (parsedRemoteRef) {
remoteBranch.remoteName = parsedRemoteRef.remoteName;
}
return remoteBranch;
})
.toSorted((a, b) => {
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
return a.name.localeCompare(b.name);
})
: [];
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true };
});
@@ -1089,79 +776,13 @@ const makeGitCore = Effect.gen(function* () {
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
Effect.gen(function* () {
const [localInputExists, remoteExists] = yield* Effect.all(
[
executeGit(
"GitCore.checkoutBranch.localInputExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
executeGit(
"GitCore.checkoutBranch.remoteExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
],
{ concurrency: "unbounded" },
);
const localTrackingBranch = remoteExists
? yield* executeGit(
"GitCore.checkoutBranch.localTrackingBranch",
input.cwd,
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.map((result) =>
result.code === 0
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
: null,
),
)
: null;
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
const localTrackedBranchTargetExists =
remoteExists && localTrackedBranchCandidate
? yield* executeGit(
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0))
: false;
const checkoutArgs = localInputExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch
? ["checkout", "--track", input.branch]
: remoteExists && localTrackingBranch
? ["checkout", localTrackingBranch]
: ["checkout", input.branch];
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkScoped(
yield* Effect.forkDetach(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.catch(() => Effect.void)),
);
});
@@ -570,56 +570,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 77,
title: "Add no-upstream PR flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
baseRefName: "main",
headRefName: "feature/no-upstream-pr",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(result.pr.status).toBe("created");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("origin/feature/no-upstream-pr");
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/no-upstream-pr"),
),
).toBe(true);
}),
);
it.effect("skips push when branch is already up to date", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
+3 -5
View File
@@ -7,7 +7,7 @@
* @module GitCore
*/
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
GitCreateBranchInput,
@@ -111,7 +111,7 @@ export interface GitCoreShape {
) => Effect.Effect<string | null, GitCommandError>;
/**
* List local + remote branches and branch metadata.
* List local branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
@@ -149,9 +149,7 @@ export interface GitCoreShape {
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<void, GitCommandError, Scope.Scope>;
readonly checkoutBranch: (input: GitCheckoutInput) => Effect.Effect<void, GitCommandError>;
/**
* Initialize a repository in the provided directory.
+5 -132
View File
@@ -1,51 +1,24 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
isCommandAvailable,
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { launchDetached, resolveEditorLaunch } from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
describe("resolveEditorLaunch", () => {
it.effect("returns commands for command-based editors", () =>
it.effect("returns cursor command for cursor editor", () =>
Effect.gen(function* () {
const cursorLaunch = yield* resolveEditorLaunch(
const launch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
);
assert.deepEqual(cursorLaunch, {
assert.deepEqual(launch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
it.effect("uses --goto when editor supports line/column suffixes", () =>
it.effect("uses --goto when cursor target includes line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
@@ -64,24 +37,6 @@ describe("resolveEditorLaunch", () => {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
);
@@ -138,85 +93,3 @@ describe("launchDetached", () => {
}),
);
});
describe("isCommandAvailable", () => {
function withTempDir(run: (dir: string) => void): void {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-open-"));
try {
run(dir);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}
it("resolves win32 commands with PATHEXT", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
});
});
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it("does not treat bare files without executable extension as available on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "npm"), "echo nope\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
});
});
it("appends PATHEXT for commands with non-executable extensions on win32", () => {
withTempDir((dir) => {
fs.writeFileSync(path.join(dir, "my.tool.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
});
});
it("uses platform-specific PATH delimiter for platform overrides", () => {
withTempDir((firstDir) => {
withTempDir((secondDir) => {
fs.writeFileSync(path.join(secondDir, "code.CMD"), "@echo off\r\n", "utf8");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
});
});
});
});
describe("resolveAvailableEditors", () => {
it("returns only editors whose launch commands are available", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-editors-"));
try {
fs.writeFileSync(path.join(dir, "cursor.CMD"), "@echo off\r\n", "utf8");
fs.writeFileSync(path.join(dir, "explorer.EXE"), "MZ", "utf8");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["cursor", "file-manager"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
+9 -141
View File
@@ -7,8 +7,6 @@
* @module Open
*/
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
@@ -32,147 +30,10 @@ interface EditorLaunch {
readonly args: ReadonlyArray<string>;
}
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
return (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
return env.PATH ?? env.Path ?? env.path ?? "";
}
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
const rawValue = env.PATHEXT;
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
if (!rawValue) return fallback;
const parsed = rawValue
.split(";")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveCommandCandidates(
command: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
command,
`${commandWithoutExtension}${normalizedExtension}`,
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
]),
);
}
const candidates: string[] = [];
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
export function isCommandAvailable(
command: string,
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
const command = editor.command ?? fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
}
return available;
return editorId === "cursor" && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
/**
@@ -220,7 +81,14 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
switch (platform) {
case "darwin":
return { command: "open", args: [input.cwd] };
case "win32":
return { command: "explorer", args: [input.cwd] };
default:
return { command: "xdg-open", args: [input.cwd] };
}
});
export const launchDetached = (launch: EditorLaunch) =>
@@ -415,7 +415,8 @@ const make = Effect.gen(function* () {
: event.threadId !== undefined
? ProviderThreadId.makeUnsafe(event.threadId)
: null;
const providerThreadId = providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
const providerThreadId =
providerThreadIdFromEvent ?? sessionProviderThreadId ?? null;
const status =
event.type === "turn.started"
? "running"
@@ -152,16 +152,4 @@ describe("tryHandleProjectFaviconRequest", () => {
expect(response.body).toBe("<svg>brand-obj-order</svg>");
});
});
it("serves a fallback favicon when no icon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toContain('data-fallback="project-favicon"');
});
});
});
+2 -11
View File
@@ -9,8 +9,6 @@ const FAVICON_MIME_TYPES: Record<string, string> = {
".ico": "image/x-icon",
};
const FALLBACK_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
@@ -87,14 +85,6 @@ function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
});
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
@@ -128,7 +118,8 @@ export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerRespons
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("No favicon found");
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
@@ -489,10 +489,12 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
attachment,
});
if (!attachmentPath) {
return yield* toRequestError(
input.sessionId,
"turn/start",
new Error(`Invalid attachment id '${attachment.id}'.`),
return yield* Effect.fail(
toRequestError(
input.sessionId,
"turn/start",
new Error(`Invalid attachment id '${attachment.id}'.`),
),
);
}
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
-24
View File
@@ -13,7 +13,6 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
import {
DEFAULT_TERMINAL_ID,
EDITORS,
EventId,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
@@ -341,15 +340,6 @@ function compileKeybindings(bindings: KeybindingsConfig): ResolvedKeybindingsCon
}
const DEFAULT_RESOLVED_KEYBINDINGS = compileKeybindings([...DEFAULT_KEYBINDINGS]);
const VALID_EDITOR_IDS = new Set(EDITORS.map((editor) => editor.id));
function expectAvailableEditors(value: unknown): void {
expect(Array.isArray(value)).toBe(true);
for (const editorId of value as unknown[]) {
expect(typeof editorId).toBe("string");
expect(VALID_EDITOR_IDS.has(editorId as (typeof EDITORS)[number]["id"])).toBe(true);
}
}
describe("WebSocket Server", () => {
let server: Http.Server | null = null;
@@ -736,9 +726,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
});
it("bootstraps default keybindings file when missing", async () => {
@@ -761,9 +749,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
issues: [],
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
const persistedConfig = JSON.parse(
fs.readFileSync(keybindingsPath, "utf8"),
@@ -796,9 +782,7 @@ describe("WebSocket Server", () => {
message: expect.stringContaining("expected JSON array"),
},
],
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
});
@@ -830,7 +814,6 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: string;
keybindings: ResolvedKeybindingsConfig;
issues: Array<{ kind: string; index?: number; message: string }>;
availableEditors: unknown;
};
expect(result.cwd).toBe("/my/workspace");
expect(result.keybindingsConfigPath).toBe(keybindingsPath);
@@ -849,7 +832,6 @@ describe("WebSocket Server", () => {
expect(result.keybindings).toHaveLength(DEFAULT_RESOLVED_KEYBINDINGS.length);
expect(result.keybindings.some((entry) => entry.command === "terminal.toggle")).toBe(true);
expect(result.keybindings.some((entry) => entry.command === "terminal.new")).toBe(true);
expectAvailableEditors(result.availableEditors);
});
it("pushes server.configUpdated issues when keybindings file changes", async () => {
@@ -947,9 +929,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
availableEditors: expect.any(Array),
});
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
});
it("upserts keybinding rules and updates cached server config", async () => {
@@ -994,11 +974,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: keybindingsPath,
keybindings: compileKeybindings(persistedConfig),
issues: [],
availableEditors: expect.any(Array),
});
expectAvailableEditors(
(configResponse.result as { availableEditors: unknown }).availableEditors,
);
});
it("returns error for unknown methods", async () => {
+3 -9
View File
@@ -54,7 +54,7 @@ import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReac
import { ProviderService } from "./provider/Services/ProviderService";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
import { Open } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
@@ -63,11 +63,7 @@ import {
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths";
import {
createAttachmentId,
resolveAttachmentPath,
resolveAttachmentPathById,
} from "./attachmentStore.ts";
import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
import { parseBase64DataUrl } from "./imageMime.ts";
/**
@@ -193,7 +189,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const availableEditors = resolveAvailableEditors();
const gitManager = yield* GitManager;
const terminalManager = yield* TerminalManager;
@@ -690,7 +685,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitCheckout: {
const body = stripRequestTag(request.body);
return yield* Effect.scoped(git.checkoutBranch(body));
return yield* git.checkoutBranch(body);
}
case WS_METHODS.gitInit: {
@@ -735,7 +730,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
availableEditors,
};
case WS_METHODS.serverUpsertKeybinding: {
+2 -5
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
@@ -12,7 +12,6 @@
},
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
@@ -23,14 +22,12 @@
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"lexical": "^0.41.0",
"lucide-react": "^0.564.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11"
"tailwind-merge": "^3.4.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -1,127 +1,59 @@
import type { GitBranch } from "@t3tools/contracts";
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "./BranchToolbar.logic";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
const branches: GitBranch[] = [
{
name: "main",
current: true,
isDefault: true,
worktreePath: null,
},
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
];
describe("deriveSyncedLocalBranch", () => {
it("syncs to git current branch in local mode", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: threadId,
activeWorktreePath: null,
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBe("main");
});
it("supports remote names that contain slashes", () => {
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
"upstream/feature/demo",
);
it("does not sync when creating a new worktree", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: threadId,
activeWorktreePath: null,
envMode: "worktree",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
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",
]);
it("does not sync when thread already targets a worktree path", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const result = deriveSyncedLocalBranch({
activeThreadId: threadId,
activeWorktreePath: "/tmp/repo/worktrees/feature-demo",
envMode: "local",
activeThreadBranch: "feature/demo",
queryBranches: branches,
});
expect(result).toBeNull();
});
});
+20 -41
View File
@@ -1,49 +1,28 @@
import type { GitBranch } from "@t3tools/contracts";
import type { GitBranch, ThreadId } from "@t3tools/contracts";
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
interface DeriveSyncedLocalBranchInput {
activeThreadId: ThreadId | undefined;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
queryBranches: ReadonlyArray<GitBranch> | undefined;
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
}: DeriveSyncedLocalBranchInput): string | null {
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
return null;
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
const currentBranch = queryBranches?.find((branch) => branch.current);
if (!currentBranch || currentBranch.name === activeThreadBranch) {
return null;
}
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));
});
return currentBranch.name;
}
+107 -149
View File
@@ -1,16 +1,16 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useOptimistic, useState, useTransition } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { newCommandId } from "../lib/utils";
import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
} from "./BranchToolbar.logic";
gitBranchesQueryOptions,
gitCheckoutMutationOptions,
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -22,7 +22,6 @@ import {
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
import { toastManager } from "./ui/toast";
interface BranchToolbarProps {
threadId: ThreadId;
@@ -39,44 +38,28 @@ export default function BranchToolbar({
envLocked,
onComposerFocusRequest,
}: BranchToolbarProps) {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const setThreadBranchAction = useStore((store) => store.setThreadBranch);
const setThreadErrorAction = useStore((store) => store.setError);
const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const { state, dispatch } = useStore();
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
const [branchQuery, setBranchQuery] = useState("");
const serverThread = threads.find((thread) => thread.id === threadId);
const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
const activeProject = projects.find((project) => project.id === activeProjectId);
const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
const activeThread = state.threads.find((thread) => thread.id === threadId);
const activeProject = state.projects.find((project) => project.id === activeThread?.projectId);
const activeThreadId = activeThread?.id;
const activeThreadBranch = activeThread?.branch ?? null;
const activeWorktreePath = activeThread?.worktreePath ?? null;
const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
const hasServerThread = serverThread !== undefined;
const effectiveEnvMode: "local" | "worktree" =
activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
? "worktree"
: envMode;
// ── Queries ───────────────────────────────────────────────────────────
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
const canonicalActiveBranch =
effectiveEnvMode === "worktree" && !activeWorktreePath
? activeThreadBranch
: (currentGitBranch ?? activeThreadBranch);
const branches = branchesQuery.data?.branches ?? [];
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
const canCreateBranch = envMode === "local" && trimmedBranchQuery.length > 0;
const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
const createBranchItemValue = canCreateBranch
? `__create_new_branch__:${trimmedBranchQuery}`
@@ -85,24 +68,56 @@ export default function BranchToolbar({
createBranchItemValue && !hasExactBranchMatch
? [...branchNames, createBranchItemValue]
: branchNames;
// ── Mutations ─────────────────────────────────────────────────────────
const checkoutMutation = useMutation(gitCheckoutMutationOptions({ cwd: branchCwd, queryClient }));
const createBranchMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
);
// ── Effects ───────────────────────────────────────────────────────────
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}
dispatch({
type: "SET_THREAD_BRANCH",
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}, [activeThreadId, activeWorktreePath, activeThreadBranch, queryBranches, envMode, dispatch]);
useEffect(() => {
if (isBranchMenuOpen) return;
setBranchQuery("");
}, [isBranchMenuOpen]);
// ── Helpers ───────────────────────────────────────────────────────────
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
canonicalActiveBranch,
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
);
const [isBranchActionPending, startBranchActionTransition] = useTransition();
const runBranchAction = (action: () => Promise<void>) => {
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await invalidateGitQueries(queryClient).catch(() => undefined);
});
};
const setThreadError = (error: string | null) => {
if (!activeThreadId) return;
setThreadErrorAction(activeThreadId, error);
dispatch({ type: "SET_ERROR", threadId: activeThreadId, error });
};
const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
@@ -110,7 +125,7 @@ export default function BranchToolbar({
const api = readNativeApi();
// If the effective cwd is about to change, stop the running session so the
// next message creates a new one with the correct cwd.
const sessionId = serverThread?.session?.sessionId;
const sessionId = activeThread?.session?.sessionId;
if (sessionId && worktreePath !== activeWorktreePath && api) {
void api.orchestration
.dispatchCommand({
@@ -121,7 +136,7 @@ export default function BranchToolbar({
})
.catch(() => undefined);
}
if (api && hasServerThread) {
if (api) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
@@ -130,23 +145,16 @@ export default function BranchToolbar({
worktreePath,
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, branch, worktreePath);
return;
}
setDraftThreadContext(threadId, {
branch,
worktreePath,
envMode: effectiveEnvMode,
});
dispatch({ type: "SET_THREAD_BRANCH", threadId: activeThreadId, branch, worktreePath });
};
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || isBranchActionPending) return;
if (!api || !activeThreadId || !branchCwd) return;
// For new worktree mode, selecting a branch picks the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
if (envMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
@@ -157,6 +165,7 @@ export default function BranchToolbar({
// trying to checkout (which git would reject with "already used by worktree").
if (branch.worktreePath) {
const isMainWorktree = branch.worktreePath === activeProject?.cwd;
setThreadError(null);
// Main worktree → switch back to local (project cwd, worktreePath=null).
// Secondary worktree → point the thread at that worktree path.
setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
@@ -165,79 +174,39 @@ export default function BranchToolbar({
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(selectedBranchName);
try {
await api.git.checkout({ cwd: branchCwd, branch: branch.name });
await invalidateGitQueries(queryClient);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, activeWorktreePath);
checkoutMutation.mutate(branch.name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
setIsBranchMenuOpen(true);
},
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd || !name || isBranchActionPending) return;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
runBranchAction(async () => {
setOptimisticBranch(name);
try {
await api.git.createBranch({ cwd: branchCwd, branch: name });
try {
await api.git.checkout({ cwd: branchCwd, branch: name });
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to checkout branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to create branch.",
description: error instanceof Error ? error.message : "An error occurred.",
});
return;
}
setOptimisticBranch(name);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
if (!api || !activeThreadId || !branchCwd || !name || createBranchMutation.isPending) return;
createBranchMutation.mutate(name, {
onSuccess: () => {
setThreadError(null);
setThreadBranch(name, activeWorktreePath);
setBranchQuery("");
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to create branch.");
},
});
};
if (!activeThreadId || !activeProject) return null;
if (!activeThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
@@ -252,9 +221,9 @@ export default function BranchToolbar({
variant="ghost"
className="text-muted-foreground/70 hover:text-foreground/80"
size="xs"
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
onClick={() => onEnvModeChange(envMode === "local" ? "worktree" : "local")}
>
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
{envMode === "worktree" ? "New worktree" : "Local"}
</Button>
)}
</div>
@@ -262,24 +231,20 @@ export default function BranchToolbar({
<Combobox
items={branchPickerItems}
autoHighlight
onOpenChange={(open) => {
setIsBranchMenuOpen(open);
if (!open) setBranchQuery("");
else void invalidateGitQueries(queryClient);
}}
onOpenChange={(open) => setIsBranchMenuOpen(open)}
open={isBranchMenuOpen}
value={resolvedActiveBranch}
value={activeThread.branch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading || isBranchActionPending}
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate">
{resolvedActiveBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${resolvedActiveBranch}`
: resolvedActiveBranch
{activeThread.branch
? envMode === "worktree" && !activeWorktreePath
? `From ${activeThread.branch}`
: activeThread.branch
: "Select branch"}
</span>
<ChevronDownIcon />
@@ -318,29 +283,22 @@ export default function BranchToolbar({
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
key={itemValue}
value={itemValue}
className={
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
itemValue === activeThread.branch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{badge && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
</div>
</ComboboxItem>
File diff suppressed because it is too large. Load diff
@@ -1,813 +0,0 @@
import {
LexicalComposer,
type InitialConfigType,
} from "@lexical/react/LexicalComposer";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { ContentEditable } from "@lexical/react/LexicalContentEditable";
import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
import {
$applyNodeReplacement,
$createRangeSelection,
$getSelection,
$setSelection,
$isElementNode,
$isLineBreakNode,
$isRangeSelection,
$isTextNode,
$createLineBreakNode,
$createParagraphNode,
$createTextNode,
KEY_ARROW_DOWN_COMMAND,
KEY_ARROW_LEFT_COMMAND,
KEY_ARROW_RIGHT_COMMAND,
KEY_ARROW_UP_COMMAND,
KEY_ENTER_COMMAND,
KEY_TAB_COMMAND,
COMMAND_PRIORITY_HIGH,
KEY_BACKSPACE_COMMAND,
$getRoot,
type ElementNode,
type LexicalNode,
TextNode,
type EditorConfig,
type EditorState,
type NodeKey,
type SerializedTextNode,
type Spread,
} from "lexical";
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
type ClipboardEventHandler,
type Ref,
} from "react";
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
import { cn } from "~/lib/utils";
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
type SerializedComposerMentionNode = Spread<
{
path: string;
type: "composer-mention";
version: 1;
},
SerializedTextNode
>;
class ComposerMentionNode extends TextNode {
__path: string;
static override getType(): string {
return "composer-mention";
}
static override clone(node: ComposerMentionNode): ComposerMentionNode {
return new ComposerMentionNode(node.__path, node.__key);
}
static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
return $createComposerMentionNode(serializedNode.path);
}
constructor(path: string, key?: NodeKey) {
const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
super(`@${normalizedPath}`, key);
this.__path = normalizedPath;
}
override exportJSON(): SerializedComposerMentionNode {
return {
...super.exportJSON(),
path: this.__path,
type: "composer-mention",
version: 1,
};
}
override createDOM(_config: EditorConfig): HTMLElement {
const dom = document.createElement("span");
dom.className =
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
dom.contentEditable = "false";
dom.setAttribute("spellcheck", "false");
renderMentionChipDom(dom, this.__path);
return dom;
}
override updateDOM(
prevNode: ComposerMentionNode,
dom: HTMLElement,
_config: EditorConfig,
): boolean {
dom.contentEditable = "false";
if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
renderMentionChipDom(dom, this.__path);
}
return false;
}
override canInsertTextBefore(): false {
return false;
}
override canInsertTextAfter(): false {
return false;
}
override isTextEntity(): true {
return true;
}
override isToken(): true {
return true;
}
}
function $createComposerMentionNode(path: string): ComposerMentionNode {
return $applyNodeReplacement(new ComposerMentionNode(path));
}
function inferMentionPathKind(pathValue: string): "file" | "directory" {
const base = basenameOfPath(pathValue);
if (base.startsWith(".") && !base.slice(1).includes(".")) {
return "directory";
}
if (base.includes(".")) {
return "file";
}
return "directory";
}
function resolvedThemeFromDocument(): "light" | "dark" {
return document.documentElement.classList.contains("dark") ? "dark" : "light";
}
function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
container.textContent = "";
container.style.setProperty("user-select", "none");
container.style.setProperty("-webkit-user-select", "none");
const theme = resolvedThemeFromDocument();
const icon = document.createElement("img");
icon.alt = "";
icon.ariaHidden = "true";
icon.className = "size-3.5 shrink-0 opacity-85";
icon.loading = "lazy";
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
const label = document.createElement("span");
label.className = "truncate select-none leading-tight";
label.textContent = basenameOfPath(pathValue);
container.append(icon, label);
}
function clampCursor(value: string, cursor: number): number {
if (!Number.isFinite(cursor)) return value.length;
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
}
function getComposerNodeTextLength(node: LexicalNode): number {
if (node instanceof ComposerMentionNode) {
return 1;
}
if ($isTextNode(node)) {
return node.getTextContentSize();
}
if ($isLineBreakNode(node)) {
return 1;
}
if ($isElementNode(node)) {
return node.getChildren().reduce((total, child) => total + getComposerNodeTextLength(child), 0);
}
return 0;
}
function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
let offset = 0;
let current: LexicalNode | null = node;
while (current) {
const nextParent = current.getParent() as LexicalNode | null;
if (!nextParent || !$isElementNode(nextParent)) {
break;
}
const siblings = nextParent.getChildren();
const index = current.getIndexWithinParent();
for (let i = 0; i < index; i += 1) {
const sibling = siblings[i];
if (!sibling) continue;
offset += getComposerNodeTextLength(sibling);
}
current = nextParent;
}
if ($isTextNode(node)) {
if (node instanceof ComposerMentionNode) {
return offset + (pointOffset > 0 ? 1 : 0);
}
return offset + Math.min(pointOffset, node.getTextContentSize());
}
if ($isLineBreakNode(node)) {
return offset + Math.min(pointOffset, 1);
}
if ($isElementNode(node)) {
const children = node.getChildren();
const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
for (let i = 0; i < clampedOffset; i += 1) {
const child = children[i];
if (!child) continue;
offset += getComposerNodeTextLength(child);
}
return offset;
}
return offset;
}
function findSelectionPointAtOffset(
node: LexicalNode,
remainingRef: { value: number },
): { key: string; offset: number; type: "text" | "element" } | null {
if (node instanceof ComposerMentionNode) {
const parent = node.getParent();
if (!parent || !$isElementNode(parent)) return null;
const index = node.getIndexWithinParent();
if (remainingRef.value === 0) {
return {
key: parent.getKey(),
offset: index,
type: "element",
};
}
if (remainingRef.value === 1) {
return {
key: parent.getKey(),
offset: index + 1,
type: "element",
};
}
remainingRef.value -= 1;
return null;
}
if ($isTextNode(node)) {
const size = node.getTextContentSize();
if (remainingRef.value <= size) {
return {
key: node.getKey(),
offset: remainingRef.value,
type: "text",
};
}
remainingRef.value -= size;
return null;
}
if ($isLineBreakNode(node)) {
const parent = node.getParent();
if (!parent) return null;
const index = node.getIndexWithinParent();
if (remainingRef.value === 0) {
return {
key: parent.getKey(),
offset: index,
type: "element",
};
}
if (remainingRef.value === 1) {
return {
key: parent.getKey(),
offset: index + 1,
type: "element",
};
}
remainingRef.value -= 1;
return null;
}
if ($isElementNode(node)) {
const children = node.getChildren();
for (const child of children) {
const point = findSelectionPointAtOffset(child, remainingRef);
if (point) {
return point;
}
}
if (remainingRef.value === 0) {
return {
key: node.getKey(),
offset: children.length,
type: "element",
};
}
}
return null;
}
function $getComposerRootLength(): number {
const root = $getRoot();
const children = root.getChildren();
return children.reduce((sum, child) => sum + getComposerNodeTextLength(child), 0);
}
function $setSelectionAtComposerOffset(nextOffset: number): void {
const root = $getRoot();
const composerLength = $getComposerRootLength();
const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
const remainingRef = { value: boundedOffset };
const point =
findSelectionPointAtOffset(root, remainingRef) ?? {
key: root.getKey(),
offset: root.getChildren().length,
type: "element" as const,
};
const selection = $createRangeSelection();
selection.anchor.set(point.key, point.offset, point.type);
selection.focus.set(point.key, point.offset, point.type);
$setSelection(selection);
}
function $readSelectionOffsetFromEditorState(fallback: number): number {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
return fallback;
}
const anchorNode = selection.anchor.getNode();
const offset = getAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
const composerLength = $getComposerRootLength();
return Math.max(0, Math.min(offset, composerLength));
}
function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
const lines = text.split("\n");
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index] ?? "";
if (line.length > 0) {
parent.append($createTextNode(line));
}
if (index < lines.length - 1) {
parent.append($createLineBreakNode());
}
}
}
function $setComposerEditorPrompt(prompt: string): void {
const root = $getRoot();
root.clear();
const paragraph = $createParagraphNode();
root.append(paragraph);
const segments = splitPromptIntoComposerSegments(prompt);
for (const segment of segments) {
if (segment.type === "mention") {
paragraph.append($createComposerMentionNode(segment.path));
continue;
}
$appendTextWithLineBreaks(paragraph, segment.text);
}
}
export interface ComposerPromptEditorHandle {
focus: () => void;
focusAt: (cursor: number) => void;
focusAtEnd: () => void;
readSnapshot: () => { value: string; cursor: number };
}
interface ComposerPromptEditorProps {
value: string;
cursor: number;
disabled: boolean;
placeholder: string;
className?: string;
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
onCommandKeyDown?: (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent,
) => boolean;
onPaste: ClipboardEventHandler<HTMLElement>;
}
interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
editorRef: Ref<ComposerPromptEditorHandle>;
}
function ComposerCommandKeyPlugin(props: {
onCommandKeyDown?: (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent,
) => boolean;
}) {
const [editor] = useLexicalComposerContext();
useEffect(() => {
const handleCommand = (
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
event: KeyboardEvent | null,
): boolean => {
if (!props.onCommandKeyDown || !event) {
return false;
}
const handled = props.onCommandKeyDown(key, event);
if (handled) {
event.preventDefault();
event.stopPropagation();
}
return handled;
};
const unregisterArrowDown = editor.registerCommand(
KEY_ARROW_DOWN_COMMAND,
(event) => handleCommand("ArrowDown", event),
COMMAND_PRIORITY_HIGH,
);
const unregisterArrowUp = editor.registerCommand(
KEY_ARROW_UP_COMMAND,
(event) => handleCommand("ArrowUp", event),
COMMAND_PRIORITY_HIGH,
);
const unregisterEnter = editor.registerCommand(
KEY_ENTER_COMMAND,
(event) => handleCommand("Enter", event),
COMMAND_PRIORITY_HIGH,
);
const unregisterTab = editor.registerCommand(
KEY_TAB_COMMAND,
(event) => handleCommand("Tab", event),
COMMAND_PRIORITY_HIGH,
);
return () => {
unregisterArrowDown();
unregisterArrowUp();
unregisterEnter();
unregisterTab();
};
}, [editor, props]);
return null;
}
function ComposerMentionArrowPlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
const unregisterLeft = editor.registerCommand(
KEY_ARROW_LEFT_COMMAND,
() => {
let currentOffset = -1;
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
currentOffset = $readSelectionOffsetFromEditorState(0);
});
if (currentOffset <= 0) return false;
editor.update(() => {
$setSelectionAtComposerOffset(currentOffset - 1);
});
return true;
},
COMMAND_PRIORITY_HIGH,
);
const unregisterRight = editor.registerCommand(
KEY_ARROW_RIGHT_COMMAND,
() => {
let currentOffset = -1;
let composerLength = 0;
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
composerLength = $getComposerRootLength();
currentOffset = $readSelectionOffsetFromEditorState(0);
});
if (currentOffset < 0 || currentOffset >= composerLength) return false;
editor.update(() => {
$setSelectionAtComposerOffset(currentOffset + 1);
});
return true;
},
COMMAND_PRIORITY_HIGH,
);
return () => {
unregisterLeft();
unregisterRight();
};
}, [editor]);
return null;
}
function ComposerMentionSelectionNormalizePlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return editor.registerUpdateListener(({ editorState }) => {
let afterOffset: number | null = null;
editorState.read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
const anchorNode = selection.anchor.getNode();
if (!(anchorNode instanceof ComposerMentionNode)) return;
if (selection.anchor.offset === 0) return;
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
afterOffset = beforeOffset + 1;
});
if (afterOffset !== null) {
queueMicrotask(() => {
editor.update(() => {
$setSelectionAtComposerOffset(afterOffset!);
});
});
}
});
}, [editor]);
return null;
}
function $isCursorAdjacentToMention(): boolean {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
const anchorNode = selection.anchor.getNode();
if (anchorNode instanceof ComposerMentionNode) return true;
if ($isElementNode(anchorNode)) {
const childIndex = selection.anchor.offset - 1;
if (childIndex >= 0) {
const child = anchorNode.getChildAtIndex(childIndex);
if (child instanceof ComposerMentionNode) return true;
}
}
if ($isTextNode(anchorNode) && selection.anchor.offset === 0) {
const prev = anchorNode.getPreviousSibling();
if (prev instanceof ComposerMentionNode) return true;
}
return false;
}
function ComposerMentionBackspacePlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return editor.registerCommand(
KEY_BACKSPACE_COMMAND,
(event) => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
return false;
}
const anchorNode = selection.anchor.getNode();
const removeMentionNode = (candidate: unknown): boolean => {
if (!(candidate instanceof ComposerMentionNode)) {
return false;
}
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
candidate.remove();
$setSelectionAtComposerOffset(mentionStart);
event?.preventDefault();
return true;
};
if (removeMentionNode(anchorNode)) {
return true;
}
if ($isTextNode(anchorNode)) {
if (selection.anchor.offset > 0) {
return false;
}
if (removeMentionNode(anchorNode.getPreviousSibling())) {
return true;
}
const parent = anchorNode.getParent();
if ($isElementNode(parent)) {
const index = anchorNode.getIndexWithinParent();
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
return true;
}
}
return false;
}
if ($isElementNode(anchorNode)) {
const childIndex = selection.anchor.offset - 1;
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
return true;
}
}
return false;
},
COMMAND_PRIORITY_HIGH,
);
}, [editor]);
return null;
}
function ComposerPromptEditorInner({
value,
cursor,
disabled,
placeholder,
className,
onChange,
onCommandKeyDown,
onPaste,
editorRef,
}: ComposerPromptEditorInnerProps) {
const [editor] = useLexicalComposerContext();
const onChangeRef = useRef(onChange);
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
useEffect(() => {
onChangeRef.current = onChange;
}, [onChange]);
useEffect(() => {
editor.setEditable(!disabled);
}, [disabled, editor]);
useLayoutEffect(() => {
const normalizedCursor = clampCursor(value, cursor);
const previousSnapshot = snapshotRef.current;
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
return;
}
if (previousSnapshot.value !== value) {
editor.update(() => {
$setComposerEditorPrompt(value);
});
}
snapshotRef.current = { value, cursor: normalizedCursor };
const rootElement = editor.getRootElement();
if (!rootElement || document.activeElement !== rootElement) {
return;
}
editor.update(() => {
$setSelectionAtComposerOffset(normalizedCursor);
});
}, [cursor, editor, value]);
const focusAt = useCallback(
(nextCursor: number) => {
const rootElement = editor.getRootElement();
if (!rootElement) return;
const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
rootElement.focus();
editor.update(() => {
$setSelectionAtComposerOffset(boundedCursor);
});
snapshotRef.current = {
value: snapshotRef.current.value,
cursor: boundedCursor,
};
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
},
[editor],
);
const readSnapshot = useCallback((): { value: string; cursor: number } => {
let snapshot = snapshotRef.current;
editor.getEditorState().read(() => {
const nextValue = $getRoot().getTextContent();
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCursor(
nextValue,
$readSelectionOffsetFromEditorState(fallbackCursor),
);
snapshot = {
value: nextValue,
cursor: nextCursor,
};
});
snapshotRef.current = snapshot;
return snapshot;
}, [editor]);
useImperativeHandle(
editorRef,
() => ({
focus: () => {
focusAt(snapshotRef.current.cursor);
},
focusAt: (nextCursor: number) => {
focusAt(nextCursor);
},
focusAtEnd: () => {
focusAt(snapshotRef.current.value.length);
},
readSnapshot,
}),
[focusAt, readSnapshot],
);
const handleEditorChange = useCallback((editorState: EditorState) => {
editorState.read(() => {
const nextValue = $getRoot().getTextContent();
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
const nextCursor = clampCursor(nextValue, $readSelectionOffsetFromEditorState(fallbackCursor));
const previousSnapshot = snapshotRef.current;
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
return;
}
snapshotRef.current = {
value: nextValue,
cursor: nextCursor,
};
onChangeRef.current(nextValue, nextCursor, $isCursorAdjacentToMention());
});
}, []);
return (
<div className="relative">
<PlainTextPlugin
contentEditable={
<ContentEditable
className={cn(
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
className,
)}
aria-placeholder={placeholder}
placeholder={<span />}
onPaste={onPaste}
/>
}
placeholder={
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
{placeholder}
</div>
}
ErrorBoundary={LexicalErrorBoundary}
/>
<OnChangePlugin onChange={handleEditorChange} />
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
<ComposerMentionArrowPlugin />
<ComposerMentionSelectionNormalizePlugin />
<ComposerMentionBackspacePlugin />
<HistoryPlugin />
</div>
);
}
export const ComposerPromptEditor = forwardRef<ComposerPromptEditorHandle, ComposerPromptEditorProps>(
function ComposerPromptEditor(
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
ref,
) {
const initialValueRef = useRef(value);
const initialConfig = useMemo<InitialConfigType>(
() => ({
namespace: "t3tools-composer-editor",
editable: true,
nodes: [ComposerMentionNode],
editorState: () => {
$setComposerEditorPrompt(initialValueRef.current);
},
onError: (error) => {
throw error;
},
}),
[],
);
return (
<LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
<ComposerPromptEditorInner
value={value}
cursor={cursor}
disabled={disabled}
placeholder={placeholder}
onChange={onChange}
onPaste={onPaste}
editorRef={ref}
{...(onCommandKeyDown ? { onCommandKeyDown } : {})}
{...(className ? { className } : {})}
/>
</LexicalComposer>
);
},
);
+13 -72
View File
@@ -4,11 +4,9 @@ import { useQuery } from "@tanstack/react-query";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ThreadId, type TurnId } from "@t3tools/contracts";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { type WheelEvent as ReactWheelEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { isElectron } from "../env";
import { useTheme } from "../hooks/useTheme";
@@ -60,29 +58,6 @@ const DIFF_PANEL_UNSAFE_CSS = `
border-block-color: var(--border) !important;
color: var(--foreground) !important;
}
[data-diffs-header] {
position: sticky !important;
top: 0;
z-index: 4;
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
border-bottom: 1px solid var(--border) !important;
}
[data-title] {
cursor: pointer;
transition:
color 120ms ease,
text-decoration-color 120ms ease;
text-decoration: underline;
text-decoration-color: transparent;
text-underline-offset: 2px;
}
[data-title]:hover {
color: color-mix(in srgb, var(--foreground) 84%, var(--primary)) !important;
text-decoration-color: currentColor;
}
`;
type RenderablePatch =
@@ -156,6 +131,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { state } = useStore();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
@@ -167,14 +143,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
});
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
const activeThreadId = routeThreadId;
const activeThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
);
const activeProjectId = activeThread?.projectId ?? null;
const activeProject = useStore((store) =>
activeProjectId ? store.projects.find((project) => project.id === activeProjectId) : undefined,
);
const activeCwd = activeThread?.worktreePath ?? activeProject?.cwd;
const activeThread = state.threads.find((thread) => thread.id === activeThreadId);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -295,18 +264,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
target?.scrollIntoView({ block: "nearest" });
}, [selectedFilePath, renderableFiles]);
const openDiffFileInEditor = useCallback(
(filePath: string) => {
const api = readNativeApi();
if (!api) return;
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
console.warn("Failed to open diff file in editor.", error);
});
},
[activeCwd],
);
const selectTurn = (turnId: TurnId) => {
if (!activeThread) return;
void navigate({
@@ -346,7 +303,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
if (!element) return;
element.scrollBy({ left: offset, behavior: "smooth" });
}, []);
const onTurnStripWheel = useCallback((event: ReactWheelEvent<HTMLDivElement>) => {
const onTurnStripWheel = useCallback((event: WheelEvent) => {
const element = turnStripRef.current;
if (!element) return;
if (element.scrollWidth <= element.clientWidth + 1) return;
@@ -360,26 +317,24 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const element = turnStripRef.current;
if (!element) return;
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
updateTurnStripScrollState();
const onScroll = () => updateTurnStripScrollState();
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
resizeObserver.observe(element);
return () => {
window.cancelAnimationFrame(frameId);
element.removeEventListener("scroll", onScroll);
element.removeEventListener("wheel", onTurnStripWheel);
resizeObserver.disconnect();
};
}, [updateTurnStripScrollState]);
}, [updateTurnStripScrollState, onTurnStripWheel]);
useEffect(() => {
const frameId = window.requestAnimationFrame(() => updateTurnStripScrollState());
return () => {
window.cancelAnimationFrame(frameId);
};
updateTurnStripScrollState();
}, [orderedTurnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
useEffect(() => {
@@ -428,11 +383,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
>
<ChevronRightIcon className="size-3.5" />
</button>
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
onWheel={onTurnStripWheel}
>
<div ref={turnStripRef} className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5">
<button
type="button"
className="shrink-0 rounded-md"
@@ -557,7 +508,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
</div>
) : renderablePatch.kind === "files" ? (
<Virtualizer
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
className="diff-render-surface h-full min-h-0 overflow-auto px-3 py-2"
config={{
overscrollSize: 600,
intersectionObserverMargin: 1200,
@@ -571,17 +522,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div
key={themedFileKey}
data-diff-file-path={filePath}
className="diff-render-file mb-2 rounded-md first:mt-2 last:mb-0"
onClickCapture={(event) => {
const nativeEvent = event.nativeEvent as MouseEvent;
const composedPath = nativeEvent.composedPath?.() ?? [];
const clickedHeader = composedPath.some((node) => {
if (!(node instanceof Element)) return false;
return node.hasAttribute("data-title");
});
if (!clickedHeader) return;
openDiffFileInEditor(filePath);
}}
className="diff-render-file rounded-md"
>
<FileDiff
fileDiff={fileDiff}
@@ -598,7 +539,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
})}
</Virtualizer>
) : (
<div className="h-full overflow-auto p-2">
<div className="h-full overflow-auto px-3 py-2">
<div className="space-y-2">
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
@@ -4,8 +4,6 @@ import {
buildGitActionProgressStages,
buildMenuItems,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -516,20 +514,19 @@ describe("when: HEAD is detached and there are no local changes", () => {
});
describe("when: branch has no upstream configured", () => {
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
const quick = resolveQuickAction(
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
false,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Push",
hint: "No local commits to push.",
label: "Commit",
disabled: true,
});
});
it("resolveQuickAction opens PR when clean, no upstream, no local commits are ahead, and PR exists", () => {
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
@@ -546,9 +543,9 @@ describe("when: branch has no upstream configured", () => {
false,
);
assert.deepInclude(quick, {
kind: "open_pr",
label: "Open PR",
disabled: false,
kind: "show_hint",
label: "Commit",
disabled: true,
});
});
@@ -608,132 +605,6 @@ describe("when: branch has no upstream configured", () => {
},
]);
});
it("resolveQuickAction runs push and create PR when no upstream and commits are ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
aheadCount: 2,
pr: null,
}),
false,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Push & create PR",
disabled: false,
});
});
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: false,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
hasUpstream: false,
aheadCount: 0,
pr: null,
}),
false,
true,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Push",
hint: "No local commits to push.",
disabled: true,
});
});
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
hasUpstream: false,
aheadCount: 1,
pr: null,
}),
false,
true,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Push",
disabled: false,
});
});
it("buildMenuItems still disables push and create PR when branch is behind", () => {
const items = buildMenuItems(
status({
hasUpstream: false,
behindCount: 1,
aheadCount: 0,
pr: null,
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("requiresDefaultBranchConfirmation", () => {
@@ -745,53 +616,6 @@ describe("requiresDefaultBranchConfirmation", () => {
});
});
describe("resolveDefaultBranchActionDialogCopy", () => {
it("uses push-only copy when pushing without a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push",
branchName: "main",
includesCommit: false,
});
assert.deepEqual(copy, {
title: "Push to default branch?",
description:
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Push to main",
});
});
it("uses push-and-pr copy when creating a PR without a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push_pr",
branchName: "main",
includesCommit: false,
});
assert.deepEqual(copy, {
title: "Push & create PR from default branch?",
description:
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Push & create PR",
});
});
it("keeps commit copy when the action includes a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push_pr",
branchName: "main",
includesCommit: true,
});
assert.deepEqual(copy, {
title: "Commit, push & create PR from default branch?",
description:
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Commit, push & create PR",
});
});
});
describe("buildGitActionProgressStages", () => {
it("shows only push progress when push-only is forced", () => {
const stages = buildGitActionProgressStages({
@@ -908,20 +732,3 @@ describe("summarizeGitResult", () => {
});
});
});
describe("resolveAutoFeatureBranchName", () => {
const day = new Date("2026-03-01T12:00:00.000Z");
it("returns the base auto feature branch name when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
assert.equal(branch, "feature/stacked-20260301");
});
it("increments suffix when the base name already exists", () => {
const branch = resolveAutoFeatureBranchName(
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
day,
);
assert.equal(branch, "feature/stacked-20260301-3");
});
});
@@ -25,17 +25,8 @@ export interface GitQuickAction {
hint?: string;
}
export interface DefaultBranchActionDialogCopy {
title: string;
description: string;
continueLabel: string;
}
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
@@ -127,6 +118,7 @@ export function buildMenuItems(
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
gitStatus.hasUpstream &&
!isBehind;
const canOpenPr = !isBusy && hasOpenPr;
@@ -212,29 +204,6 @@ export function resolveQuickAction(
};
}
if (!gitStatus.hasUpstream) {
if (!isAhead) {
if (hasOpenPr) {
return { label: "Open PR", disabled: false, kind: "open_pr" };
}
return {
label: "Push",
disabled: true,
kind: "show_hint",
hint: "No local commits to push.",
};
}
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
};
}
if (isDiverged) {
return {
label: "Sync branch",
@@ -283,67 +252,3 @@ export function requiresDefaultBranchConfirmation(
if (!isDefaultBranch) return false;
return action === "commit_push" || action === "commit_push_pr";
}
export function resolveDefaultBranchActionDialogCopy(input: {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
}): DefaultBranchActionDialogCopy {
const branchLabel = input.branchName;
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
if (input.action === "commit_push") {
if (input.includesCommit) {
return {
title: "Commit & push to default branch?",
description: `This action will commit and push changes${suffix}`,
continueLabel: `Commit & push to ${branchLabel}`,
};
}
return {
title: "Push to default branch?",
description: `This action will push local commits${suffix}`,
continueLabel: `Push to ${branchLabel}`,
};
}
if (input.includesCommit) {
return {
title: "Commit, push & create PR from default branch?",
description: `This action will commit, push, and create a PR${suffix}`,
continueLabel: `Commit, push & create PR`,
};
}
return {
title: "Push & create PR from default branch?",
description: `This action will push local commits and create a PR${suffix}`,
continueLabel: "Push & create PR",
};
}
function formatDateForBranch(now: Date): string {
const year = now.getUTCFullYear();
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
const day = String(now.getUTCDate()).padStart(2, "0");
return `${year}${month}${day}`;
}
export function resolveAutoFeatureBranchName(
existingBranchNames: readonly string[],
now = new Date(),
): string {
const daySlug = formatDateForBranch(now);
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
const existingNames = new Set(existingBranchNames);
if (!existingNames.has(base)) {
return base;
}
let suffix = 2;
while (existingNames.has(`${base}-${suffix}`)) {
suffix += 1;
}
return `${base}-${suffix}`;
}
+141 -271
View File
@@ -8,11 +8,9 @@ import {
buildMenuItems,
type GitActionIconName,
type GitActionMenuItem,
type GitDialogAction,
type GitQuickAction,
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -34,7 +32,6 @@ import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitCreateBranchAndCheckoutMutationOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
@@ -50,17 +47,6 @@ interface GitActionsControlProps {
activeThreadId: ThreadId | null;
}
interface PendingDefaultBranchAction {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
commitMessage?: string;
forcePushOnlyProgress: boolean;
onConfirmed?: () => void;
}
type GitActionToastId = ReturnType<typeof toastManager.add>;
function getMenuActionDisabledReason(
item: GitActionMenuItem,
gitStatus: GitStatusResult | null,
@@ -111,15 +97,26 @@ function getMenuActionDisabledReason(
if (!isAhead) {
return "No local commits to include in a PR.";
}
if (!gitStatus.hasUpstream) {
return "Set an upstream branch before creating a PR.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before creating a PR.";
}
return "Create PR is currently unavailable.";
}
const COMMIT_DIALOG_TITLE = "Commit changes";
const COMMIT_DIALOG_DESCRIPTION =
"Review and confirm your commit. Leave the message blank to auto-generate one.";
const DIALOG_TITLE_BY_ACTION = {
commit: "Commit changes",
push: "Push branch",
create_pr: "Create pull request",
};
const DIALOG_DESCRIPTION_BY_ACTION = {
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
push: "Push this branch now.",
create_pr: "Create a pull request using generated title/body content.",
};
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
if (icon === "commit") return <GitCommitIcon />;
@@ -146,10 +143,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[activeThreadId],
);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
@@ -172,18 +167,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
);
const createBranchAndCheckoutMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isRunStackedActionRunning =
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isCreateBranchAndCheckoutRunning =
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning =
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -202,13 +191,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
? resolveDefaultBranchActionDialogCopy({
action: pendingDefaultBranchAction.action,
branchName: pendingDefaultBranchAction.branchName,
includesCommit: pendingDefaultBranchAction.includesCommit,
})
: null;
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
const api = readNativeApi();
if (!api) return false;
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
!gitStatusForActions?.branch
) {
return true;
}
return api.dialogs.confirm(
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[gitStatusForActions?.branch, isDefaultBranch],
);
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
@@ -238,82 +237,43 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
});
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
isDefaultBranchOverride,
progressToastId,
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
}) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
const actionBranch = actionStatus?.branch ?? null;
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
if (
!skipDefaultBranchPrompt &&
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
actionBranch
) {
if (action !== "commit_push" && action !== "commit_push_pr") {
return;
}
setPendingDefaultBranchAction({
action,
branchName: actionBranch,
includesCommit,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
});
return;
}
const confirmed = await maybeConfirmPushToDefaultBranch(action);
if (!confirmed) return;
onConfirmed?.();
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
const pushTarget = gitStatusForActions?.branch
? `origin/${gitStatusForActions.branch}`
: undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
...(pushTarget ? { pushTarget } : {}),
});
const resolvedProgressToastId =
progressToastId ??
toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
if (progressToastId) {
toastManager.update(progressToastId, {
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
}
const progressToastId = toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(resolvedProgressToastId, {
toastManager.update(progressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
@@ -335,23 +295,19 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const existingOpenPrUrl =
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
const prUrl = result.pr.url ?? existingOpenPrUrl;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") &&
!!prUrl &&
!actionIsDefaultBranch;
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
const shouldOfferCreatePrCta =
action === "commit_push" &&
!prUrl &&
result.push.status === "pushed" &&
!actionIsDefaultBranch;
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
const closeResultToast = () => {
toastManager.close(resolvedProgressToastId);
toastManager.close(progressToastId);
};
toastManager.update(resolvedProgressToastId, {
toastManager.update(progressToastId, {
type: "success",
title: resultToast.title,
description: resultToast.description,
@@ -369,8 +325,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
@@ -393,11 +347,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
children: "Create PR",
onClick: () => {
closeResultToast();
void runGitActionWithToast({
action: "commit_push_pr",
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
setActiveDialogAction("create_pr");
},
},
}
@@ -405,7 +355,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
} catch (err) {
stopProgressUpdates();
toastManager.update(resolvedProgressToastId, {
toastManager.update(progressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
@@ -415,109 +365,17 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
},
[
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.pr,
isDefaultBranch,
maybeConfirmPushToDefaultBranch,
runImmediateGitActionMutation,
setPendingDefaultBranchAction,
threadToastData,
gitStatusForActions,
],
);
const continuePendingDefaultBranchAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction, runGitActionWithToast]);
const checkoutNewBranchAndRunAction = useCallback(
(actionParams: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
}) => {
const branchName = resolveAutoFeatureBranchName(
branchList?.branches.map((branch) => branch.name) ?? [],
);
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
const checkoutToastId = toastManager.add({
type: "loading",
title: `Creating ${branchName}...`,
timeout: 0,
data: threadToastData,
});
void checkoutPromise
.then(() => {
const statusOverride = gitStatusForActions
? {
...gitStatusForActions,
branch: branchName,
pr: null,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
}
: null;
return runGitActionWithToast({
...actionParams,
skipDefaultBranchPrompt: true,
statusOverride,
isDefaultBranchOverride: false,
progressToastId: checkoutToastId,
});
})
.catch((error) => {
toastManager.update(checkoutToastId, {
type: "error",
title: "Failed to checkout feature branch",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[
branchList?.branches,
createBranchAndCheckoutMutation,
gitStatusForActions,
runGitActionWithToast,
setActiveDialogAction,
threadToastData,
],
);
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
checkoutNewBranchAndRunAction({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
});
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
const runDialogActionOnNewBranch = useCallback(() => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
checkoutNewBranchAndRunAction({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
});
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
@@ -569,31 +427,30 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "commit_push_pr" });
return;
if (item.dialogAction) {
setActiveDialogAction(item.dialogAction);
}
setIsCommitDialogOpen(true);
},
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
[openExistingPr, runGitActionWithToast],
);
const runDialogAction = useCallback(() => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
if (!activeDialogAction) return;
const action: GitStackedAction =
activeDialogAction === "commit"
? "commit"
: activeDialogAction === "push"
? "commit_push"
: "commit_push_pr";
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
const forcePushOnlyProgress = activeDialogAction === "push";
setActiveDialogAction(null);
void runGitActionWithToast({
action: "commit",
action,
...(commitMessage ? { commitMessage } : {}),
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
});
}, [
dialogCommitMessage,
isCommitDialogOpen,
runGitActionWithToast,
setDialogCommitMessage,
setIsCommitDialogOpen,
]);
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
const openChangedFileInEditor = useCallback(
(filePath: string) => {
@@ -749,29 +606,68 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
)}
<Dialog
open={isCommitDialogOpen}
open={activeDialogAction !== null}
onOpenChange={(open) => {
if (!open) {
setIsCommitDialogOpen(false);
setActiveDialogAction(null);
setDialogCommitMessage("");
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
<DialogDescription>
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="flex items-center justify-between gap-2">
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
{isDefaultBranch && (
<span className="text-right text-warning text-xs">Warning: default branch</span>
)}
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
</span>
{activeDialogAction !== "commit" && (
<>
<span className="text-muted-foreground">Upstream</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasUpstream
? "No upstream configured"
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 &&
gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
: `Behind by ${gitStatusForActions.behindCount}`}
</span>
<span className="text-muted-foreground">Working tree</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
? "Clean"
: `${gitStatusForActions.workingTree.files.length} file(s)`}
</span>
<span className="text-muted-foreground">Diff</span>
<span className="font-mono">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
"none"
) : (
<>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</>
)}
</span>
</>
)}
</div>
<div className="space-y-1">
<p className="text-muted-foreground">Files</p>
@@ -811,61 +707,35 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
)}
</div>
</div>
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
{activeDialogAction === "commit" && (
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
)}
</DialogPanel>
<DialogFooter>
<Button
variant="outline"
size="sm"
onClick={() => {
setIsCommitDialogOpen(false);
setActiveDialogAction(null);
setDialogCommitMessage("");
}}
>
Cancel
</Button>
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
Commit on new branch
</Button>
<Button size="sm" onClick={runDialogAction}>
Commit
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<Dialog
open={pendingDefaultBranchAction !== null}
onOpenChange={(open) => {
if (!open) {
setPendingDefaultBranchAction(null);
}
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
</DialogTitle>
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
Abort
</Button>
<Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
</Button>
<Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
Checkout feature branch & continue
{activeDialogAction === "commit"
? "Commit"
: activeDialogAction === "push"
? "Push"
: "Create PR"}
</Button>
</DialogFooter>
</DialogPopup>
+1 -124
View File
@@ -1,4 +1,4 @@
import { type SVGProps, useId } from "react";
import type { SVGProps } from "react";
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
@@ -19,126 +19,3 @@ export const CursorIcon: Icon = (props) => (
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
</svg>
);
export const VisualStudioCode: Icon = (props) => {
const id = useId();
const maskId = `${id}-vscode-a`;
const topShadowFilterId = `${id}-vscode-b`;
const sideShadowFilterId = `${id}-vscode-c`;
const overlayGradientId = `${id}-vscode-d`;
return (
<svg {...props} fill="none" viewBox="0 0 100 100">
<mask id={maskId} width="100" height="100" x="0" y="0" maskUnits="userSpaceOnUse">
<path
fill="#fff"
fillRule="evenodd"
d="M70.912 99.317a6.223 6.223 0 0 0 4.96-.19l20.589-9.907A6.25 6.25 0 0 0 100 83.587V16.413a6.25 6.25 0 0 0-3.54-5.632L75.874.874a6.226 6.226 0 0 0-7.104 1.21L29.355 38.04 12.187 25.01a4.162 4.162 0 0 0-5.318.236l-5.506 5.009a4.168 4.168 0 0 0-.004 6.162L16.247 50 1.36 63.583a4.168 4.168 0 0 0 .004 6.162l5.506 5.01a4.162 4.162 0 0 0 5.318.236l17.168-13.032L68.77 97.917a6.217 6.217 0 0 0 2.143 1.4ZM75.015 27.3 45.11 50l29.906 22.701V27.3Z"
clipRule="evenodd"
/>
</mask>
<g mask={`url(#${maskId})`}>
<path
fill="#0065A9"
d="M96.461 10.796 75.857.876a6.23 6.23 0 0 0-7.107 1.207l-67.451 61.5a4.167 4.167 0 0 0 .004 6.162l5.51 5.009a4.167 4.167 0 0 0 5.32.236l81.228-61.62c2.725-2.067 6.639-.124 6.639 3.297v-.24a6.25 6.25 0 0 0-3.539-5.63Z"
/>
<g filter={`url(#${topShadowFilterId})`}>
<path
fill="#007ACC"
d="m96.461 89.204-20.604 9.92a6.229 6.229 0 0 1-7.107-1.207l-67.451-61.5a4.167 4.167 0 0 1 .004-6.162l5.51-5.009a4.167 4.167 0 0 1 5.32-.236l81.228 61.62c2.725 2.067 6.639.124 6.639-3.297v.24a6.25 6.25 0 0 1-3.539 5.63Z"
/>
</g>
<g filter={`url(#${sideShadowFilterId})`}>
<path
fill="#1F9CF0"
d="M75.858 99.126a6.232 6.232 0 0 1-7.108-1.21c2.306 2.307 6.25.674 6.25-2.588V4.672c0-3.262-3.944-4.895-6.25-2.589a6.232 6.232 0 0 1 7.108-1.21l20.6 9.908A6.25 6.25 0 0 1 100 16.413v67.174a6.25 6.25 0 0 1-3.541 5.633l-20.601 9.906Z"
/>
</g>
<path
fill={`url(#${overlayGradientId})`}
fillRule="evenodd"
d="M70.851 99.317a6.224 6.224 0 0 0 4.96-.19L96.4 89.22a6.25 6.25 0 0 0 3.54-5.633V16.413a6.25 6.25 0 0 0-3.54-5.632L75.812.874a6.226 6.226 0 0 0-7.104 1.21L29.294 38.04 12.126 25.01a4.162 4.162 0 0 0-5.317.236l-5.507 5.009a4.168 4.168 0 0 0-.004 6.162L16.186 50 1.298 63.583a4.168 4.168 0 0 0 .004 6.162l5.507 5.009a4.162 4.162 0 0 0 5.317.236L29.294 61.96l39.414 35.958a6.218 6.218 0 0 0 2.143 1.4ZM74.954 27.3 45.048 50l29.906 22.701V27.3Z"
clipRule="evenodd"
opacity=".25"
style={{ mixBlendMode: "overlay" }}
/>
</g>
<defs>
<filter
id={topShadowFilterId}
width="116.727"
height="92.246"
x="-8.394"
y="15.829"
colorInterpolationFilters="sRGB"
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
/>
<feOffset />
<feGaussianBlur stdDeviation="4.167" />
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
</filter>
<filter
id={sideShadowFilterId}
width="47.917"
height="116.151"
x="60.417"
y="-8.076"
colorInterpolationFilters="sRGB"
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
/>
<feOffset />
<feGaussianBlur stdDeviation="4.167" />
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
<feBlend in2="BackgroundImageFix" mode="overlay" result="effect1_dropShadow" />
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
</filter>
<linearGradient
id={overlayGradientId}
x1="49.939"
x2="49.939"
y1=".258"
y2="99.742"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#fff" />
<stop offset="1" stopColor="#fff" stopOpacity="0" />
</linearGradient>
</defs>
</svg>
);
};
export const Zed: Icon = (props) => {
const id = useId();
const clipPathId = `${id}-zed-logo-a`;
return (
<svg {...props} fill="none" viewBox="0 0 96 96">
<g clipPath={`url(#${clipPathId})`}>
<path
fill="currentColor"
fillRule="evenodd"
d="M9 6a3 3 0 0 0-3 3v66H0V9a9 9 0 0 1 9-9h80.379c4.009 0 6.016 4.847 3.182 7.682L43.055 57.187H57V51h6v7.688a4.5 4.5 0 0 1-4.5 4.5H37.055L26.743 73.5H73.5V36h6v37.5a6 6 0 0 1-6 6H20.743L10.243 90H87a3 3 0 0 0 3-3V21h6v66a9 9 0 0 1-9 9H6.621c-4.009 0-6.016-4.847-3.182-7.682L52.757 39H39v6h-6v-7.5a4.5 4.5 0 0 1 4.5-4.5h21.257l10.5-10.5H22.5V60h-6V22.5a6 6 0 0 1 6-6h52.757L85.757 6H9Z"
clipRule="evenodd"
/>
</g>
<defs>
<clipPath id={clipPathId}>
<path fill="#fff" d="M0 0h96v96H0z" />
</clipPath>
</defs>
</svg>
);
};
+125 -358
View File
@@ -1,5 +1,5 @@
import { ChevronRightIcon, FolderIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
DEFAULT_MODEL,
ProjectId,
@@ -20,11 +20,8 @@ import { derivePendingApprovals } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import {
SidebarContent,
SidebarFooter,
@@ -70,11 +67,9 @@ interface TerminalStatusIndicator {
interface PrStatusIndicator {
label: "PR open" | "PR closed" | "PR merged";
colorClass: string;
tooltip: string;
url: string;
}
type ThreadPr = GitStatusResult["pr"];
type ThreadPrState = NonNullable<GitStatusResult["pr"]>["state"] | null;
function hasUnseenCompletion(thread: Thread): boolean {
if (!thread.latestTurn?.completedAt) return false;
@@ -127,10 +122,8 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
return null;
}
function terminalStatusFromRunningIds(
runningTerminalIds: string[],
): TerminalStatusIndicator | null {
if (runningTerminalIds.length === 0) {
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
if (thread.runningTerminalIds.length === 0) {
return null;
}
return {
@@ -140,31 +133,23 @@ function terminalStatusFromRunningIds(
};
}
function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
if (!pr) return null;
if (pr.state === "open") {
function prStatusIndicator(prState: ThreadPrState): PrStatusIndicator | null {
if (prState === "open") {
return {
label: "PR open",
colorClass: "text-emerald-600 dark:text-emerald-300/90",
tooltip: `#${pr.number} PR open: ${pr.title}`,
url: pr.url,
};
}
if (pr.state === "closed") {
if (prState === "closed") {
return {
label: "PR closed",
colorClass: "text-zinc-500 dark:text-zinc-400/80",
tooltip: `#${pr.number} PR closed: ${pr.title}`,
url: pr.url,
};
}
if (pr.state === "merged") {
if (prState === "merged") {
return {
label: "PR merged",
colorClass: "text-violet-600 dark:text-violet-300/90",
tooltip: `#${pr.number} PR merged: ${pr.title}`,
url: pr.url,
};
}
return null;
@@ -174,7 +159,7 @@ function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-2.5 w-auto shrink-0 text-foreground"
className="h-3 w-auto shrink-0 text-foreground"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
@@ -231,25 +216,7 @@ function ProjectFavicon({ cwd }: { cwd: string }) {
}
export default function Sidebar() {
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const markThreadUnread = useStore((store) => store.markThreadUnread);
const toggleProject = useStore((store) => store.toggleProject);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearThreadDraft);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const clearProjectDraftThreadId = useComposerDraftStore(
(store) => store.clearProjectDraftThreadId,
);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
);
const { state, dispatch } = useStore();
const navigate = useNavigate();
const { settings: appSettings } = useAppSettings();
const routeThreadId = useParams({
@@ -266,39 +233,36 @@ export default function Sidebar() {
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
const [isAddingProject, setIsAddingProject] = useState(false);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const renamingCommittedRef = useRef(false);
const renamingInputRef = useRef<HTMLInputElement | null>(null);
const pendingApprovalByThreadId = useMemo(() => {
const map = new Map<ThreadId, boolean>();
for (const thread of threads) {
for (const thread of state.threads) {
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
}
return map;
}, [threads]);
}, [state.threads]);
const projectCwdById = useMemo(
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
[projects],
() => new Map(state.projects.map((project) => [project.id, project.cwd] as const)),
[state.projects],
);
const threadGitTargets = useMemo(
() =>
threads.map((thread) => ({
state.threads.map((thread) => ({
threadId: thread.id,
branch: thread.branch,
cwd: thread.worktreePath ?? projectCwdById.get(thread.projectId) ?? null,
})),
[projectCwdById, threads],
[projectCwdById, state.threads],
);
const threadGitStatusCwds = useMemo(
() => [
...new Set(
threadGitTargets
.filter((target) => target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
],
() =>
[
...new Set(
threadGitTargets
.filter((target) => target.branch !== null)
.map((target) => target.cwd)
.filter((cwd): cwd is string => cwd !== null),
),
],
[threadGitTargets],
);
const threadGitStatusQueries = useQueries({
@@ -308,7 +272,7 @@ export default function Sidebar() {
refetchInterval: 60_000,
})),
});
const prByThreadId = useMemo(() => {
const prStateByThreadId = useMemo(() => {
const statusByCwd = new Map<string, GitStatusResult>();
for (let index = 0; index < threadGitStatusCwds.length; index += 1) {
const cwd = threadGitStatusCwds[index];
@@ -319,114 +283,63 @@ export default function Sidebar() {
}
}
const map = new Map<ThreadId, ThreadPr>();
const map = new Map<ThreadId, ThreadPrState>();
for (const target of threadGitTargets) {
const status = target.cwd ? statusByCwd.get(target.cwd) : undefined;
const branchMatches =
target.branch !== null && status?.branch !== null && status?.branch === target.branch;
map.set(target.threadId, branchMatches ? (status?.pr ?? null) : null);
map.set(target.threadId, branchMatches ? status?.pr?.state ?? null : null);
}
return map;
}, [threadGitStatusCwds, threadGitStatusQueries, threadGitTargets]);
const openPrLink = useCallback((event: React.MouseEvent<HTMLElement>, prUrl: string) => {
event.preventDefault();
event.stopPropagation();
const api = readNativeApi();
if (!api) {
toastManager.add({
type: "error",
title: "Link opening is unavailable.",
});
return;
}
void api.shell.openExternal(prUrl).catch((error) => {
toastManager.add({
type: "error",
title: "Unable to open PR link",
description: error instanceof Error ? error.message : "An error occurred.",
});
});
}, []);
const handleNewThread = useCallback(
(
projectId: ProjectId,
options?: {
branch?: string | null;
worktreePath?: string | null;
envMode?: DraftThreadEnvMode;
},
): Promise<void> => {
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
const hasEnvModeOption = options?.envMode !== undefined;
const storedDraftThread = getDraftThreadByProjectId(projectId);
if (storedDraftThread) {
return (async () => {
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
setDraftThreadContext(storedDraftThread.threadId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
}
setProjectDraftThreadId(projectId, storedDraftThread.threadId);
if (routeThreadId === storedDraftThread.threadId) {
return;
}
await navigate({
to: "/$threadId",
params: { threadId: storedDraftThread.threadId },
});
})();
}
clearProjectDraftThreadId(projectId);
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
if (activeDraftThread && routeThreadId && activeDraftThread.projectId === projectId) {
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
setDraftThreadContext(routeThreadId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
}
setProjectDraftThreadId(projectId, routeThreadId);
return Promise.resolve();
}
const api = readNativeApi();
if (!api) return Promise.resolve();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const model =
state.projects.find((project) => project.id === projectId)?.model ?? DEFAULT_MODEL;
return (async () => {
setProjectDraftThreadId(projectId, threadId, {
createdAt,
await api.orchestration.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId,
projectId,
title: "New thread",
model,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
envMode: options?.envMode ?? "local",
createdAt,
});
// Ensure route guards can see the new thread before navigating.
try {
const snapshot = await api.orchestration.getSnapshot();
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
} catch {
// Event stream can still hydrate the thread shortly after dispatch.
}
await navigate({
to: "/$threadId",
params: { threadId },
});
})();
},
[
clearProjectDraftThreadId,
getDraftThreadByProjectId,
navigate,
getDraftThread,
routeThreadId,
setDraftThreadContext,
setProjectDraftThreadId,
],
[dispatch, navigate, state.projects],
);
const focusMostRecentThreadForProject = useCallback(
(projectId: ProjectId) => {
const latestThread = threads
const latestThread = state.threads
.filter((thread) => thread.projectId === projectId)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
@@ -440,7 +353,7 @@ export default function Sidebar() {
params: { threadId: latestThread.id },
});
},
[navigate, threads],
[navigate, state.threads],
);
const addProjectFromPath = useCallback(
@@ -448,27 +361,20 @@ export default function Sidebar() {
const cwd = rawCwd.trim();
if (!cwd || isAddingProject) return;
const api = readNativeApi();
if (!api) return;
setIsAddingProject(true);
const finishAddingProject = () => {
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
};
try {
if (!api) return;
const existing = state.projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
return;
}
const existing = projects.find((project) => project.cwd === cwd);
if (existing) {
focusMostRecentThreadForProject(existing.id);
finishAddingProject();
return;
}
const projectId = newProjectId();
const createdAt = new Date().toISOString();
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
const projectCreated = await api.orchestration
.dispatchCommand({
const projectId = newProjectId();
const createdAt = new Date().toISOString();
const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: newCommandId(),
projectId,
@@ -476,15 +382,15 @@ export default function Sidebar() {
workspaceRoot: cwd,
defaultModel: DEFAULT_MODEL,
createdAt,
})
.then(() => true)
.catch(() => false);
if (projectCreated) {
await handleNewThread(projectId).catch(() => undefined);
});
await handleNewThread(projectId);
} finally {
setIsAddingProject(false);
setNewCwd("");
setAddingProject(false);
}
finishAddingProject();
},
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, state.projects],
);
const handleAddProject = () => {
@@ -495,94 +401,34 @@ export default function Sidebar() {
const api = readNativeApi();
if (!api || isPickingFolder) return;
setIsPickingFolder(true);
let pickedPath: string | null = null;
try {
pickedPath = await api.dialogs.pickFolder();
} catch {
// Ignore picker failures and leave the current thread selection unchanged.
}
if (pickedPath) {
const pickedPath = await api.dialogs.pickFolder();
if (!pickedPath) return;
await addProjectFromPath(pickedPath);
} finally {
setIsPickingFolder(false);
}
setIsPickingFolder(false);
};
const cancelRename = useCallback(() => {
setRenamingThreadId(null);
renamingInputRef.current = null;
}, []);
const commitRename = useCallback(
async (threadId: ThreadId, newTitle: string, originalTitle: string) => {
const finishRename = () => {
setRenamingThreadId((current) => {
if (current !== threadId) return current;
renamingInputRef.current = null;
return null;
});
};
const trimmed = newTitle.trim();
if (trimmed.length === 0) {
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
finishRename();
return;
}
if (trimmed === originalTitle) {
finishRename();
return;
}
const api = readNativeApi();
if (!api) {
finishRename();
return;
}
try {
await api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId,
title: trimmed,
});
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to rename thread",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
finishRename();
},
[],
);
const handleThreadContextMenu = useCallback(
async (threadId: ThreadId, position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const clicked = await api.contextMenu.show(
[
{ id: "rename", label: "Rename thread" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "delete", label: "Delete", destructive: true },
{ id: "delete", label: "Delete" },
],
position,
);
const thread = threads.find((t) => t.id === threadId);
if (!thread) return;
if (clicked === "rename") {
setRenamingThreadId(threadId);
setRenamingTitle(thread.title);
renamingCommittedRef.current = false;
return;
}
if (clicked === "mark-unread") {
markThreadUnread(threadId);
dispatch({ type: "MARK_THREAD_UNREAD", threadId });
return;
}
if (clicked !== "delete") return;
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
@@ -594,8 +440,8 @@ export default function Sidebar() {
return;
}
}
const threadProject = projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
@@ -632,15 +478,12 @@ export default function Sidebar() {
}
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
const fallbackThreadId = state.threads.find((entry) => entry.id !== threadId)?.id ?? null;
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
@@ -680,15 +523,12 @@ export default function Sidebar() {
},
[
appSettings.confirmThreadDelete,
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
markThreadUnread,
dispatch,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
state.projects,
state.threads,
],
);
@@ -696,16 +536,13 @@ export default function Sidebar() {
async (projectId: ProjectId, position: { x: number; y: number }) => {
const api = readNativeApi();
if (!api) return;
const clicked = await api.contextMenu.show(
[{ id: "delete", label: "Delete", destructive: true }],
position,
);
const clicked = await api.contextMenu.show([{ id: "delete", label: "Delete" }], position);
if (clicked !== "delete") return;
const project = projects.find((entry) => entry.id === projectId);
const project = state.projects.find((entry) => entry.id === projectId);
if (!project) return;
const projectThreads = threads.filter((thread) => thread.projectId === projectId);
const projectThreads = state.threads.filter((thread) => thread.projectId === projectId);
if (projectThreads.length > 0) {
toastManager.add({
type: "warning",
@@ -721,11 +558,6 @@ export default function Sidebar() {
if (!confirmed) return;
try {
const projectDraftThread = getDraftThreadByProjectId(projectId);
if (projectDraftThread) {
clearComposerDraftForThread(projectDraftThread.threadId);
}
clearProjectDraftThreadId(projectId);
await api.orchestration.dispatchCommand({
type: "project.delete",
commandId: newCommandId(),
@@ -741,24 +573,16 @@ export default function Sidebar() {
});
}
},
[
clearComposerDraftForThread,
clearProjectDraftThreadId,
getDraftThreadByProjectId,
projects,
threads,
],
[state.projects, state.threads],
);
useEffect(() => {
const onWindowKeyDown = (event: KeyboardEvent) => {
const activeThread = routeThreadId
? threads.find((thread) => thread.id === routeThreadId)
? state.threads.find((thread) => thread.id === routeThreadId)
: undefined;
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
if (isChatNewLocalShortcut(event, keybindings)) {
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId);
@@ -766,14 +590,12 @@ export default function Sidebar() {
}
if (!isChatNewShortcut(event, keybindings)) return;
const projectId =
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
if (!projectId) return;
event.preventDefault();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
branch: activeThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? null,
});
};
@@ -781,26 +603,26 @@ export default function Sidebar() {
return () => {
window.removeEventListener("keydown", onWindowKeyDown);
};
}, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
}, [handleNewThread, keybindings, routeThreadId, state.projects, state.threads]);
const onCreateThreadClick = () => {
if (projects.length === 0) {
if (state.projects.length === 0) {
setAddingProject(true);
return;
}
const firstProject = projects[0];
const firstProject = state.projects[0];
if (firstProject) void handleNewThread(firstProject.id);
};
const wordmark = (
<div className="flex items-center gap-2">
<div className={`flex items-center gap-2 ${isElectron ? "-translate-y-px" : ""}`}>
<SidebarTrigger className="shrink-0 md:hidden" />
<div className="flex min-w-0 flex-1 items-center gap-1 mt-2 ml-1">
<div className="flex min-w-0 flex-1 items-center gap-1">
<T3Wordmark />
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
<span className="truncate text-base font-medium tracking-tight text-muted-foreground">
Code
</span>
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[9px] font-medium uppercase tracking-widest text-muted-foreground/60">
{APP_STAGE_LABEL}
</span>
</div>
@@ -822,10 +644,10 @@ export default function Sidebar() {
<>
{isElectron ? (
<>
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[82px]">
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[88px]">
{wordmark}
</SidebarHeader>
<div className="px-4 py-2">{newThreadButton}</div>
<div className="px-4 pb-2">{newThreadButton}</div>
</>
) : (
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">
@@ -837,8 +659,8 @@ export default function Sidebar() {
<SidebarContent className="gap-0">
<SidebarGroup className="px-2 py-2">
<SidebarMenu>
{projects.map((project) => {
const visibleThreads = threads
{state.projects.map((project) => {
const threads = state.threads
.filter((thread) => thread.projectId === project.id)
.toSorted((a, b) => {
const byDate = new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
@@ -853,7 +675,7 @@ export default function Sidebar() {
open={project.expanded}
onOpenChange={(open) => {
if (open === project.expanded) return;
toggleProject(project.id);
dispatch({ type: "TOGGLE_PROJECT", projectId: project.id });
}}
>
<SidebarMenuItem>
@@ -881,32 +703,27 @@ export default function Sidebar() {
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
{project.name}
</span>
<span className="text-[10px] text-muted-foreground/60">
{visibleThreads.length}
</span>
<span className="text-[10px] text-muted-foreground/60">{threads.length}</span>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
{visibleThreads.map((thread) => {
{threads.map((thread) => {
const isActive = routeThreadId === thread.id;
const threadStatus = threadStatusPill(
thread,
pendingApprovalByThreadId.get(thread.id) === true,
);
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusFromRunningIds(
selectThreadTerminalState(terminalStateByThreadId, thread.id)
.runningTerminalIds,
);
const prStatus = prStatusIndicator(prStateByThreadId.get(thread.id) ?? null);
const terminalStatus = terminalStatusIndicator(thread);
return (
<SidebarMenuSubItem key={thread.id} className="w-full">
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
render={<button type="button" />}
size="sm"
isActive={isActive}
className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
className={`h-7 w-full translate-x-0 justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
isActive
? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
: "text-muted-foreground"
@@ -917,14 +734,6 @@ export default function Sidebar() {
params: { threadId: thread.id },
});
}}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
void navigate({
to: "/$threadId",
params: { threadId: thread.id },
});
}}
onContextMenu={(event) => {
event.preventDefault();
void handleThreadContextMenu(thread.id, {
@@ -934,25 +743,6 @@ export default function Sidebar() {
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{prStatus && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={prStatus.tooltip}
className={`inline-flex items-center justify-center ${prStatus.colorClass} cursor-pointer rounded-sm outline-hidden focus-visible:ring-1 focus-visible:ring-ring`}
onClick={(event) => {
openPrLink(event, prStatus.url);
}}
>
<GitPullRequestIcon className="size-3" />
</button>
}
/>
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
@@ -965,44 +755,21 @@ export default function Sidebar() {
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
if (el && renamingInputRef.current !== el) {
renamingInputRef.current = el;
el.focus();
el.select();
}
}}
className="min-w-0 flex-1 truncate text-xs bg-transparent outline-none border border-ring rounded px-0.5"
value={renamingTitle}
onChange={(e) => setRenamingTitle(e.target.value)}
onKeyDown={(e) => {
e.stopPropagation();
if (e.key === "Enter") {
e.preventDefault();
renamingCommittedRef.current = true;
void commitRename(thread.id, renamingTitle, thread.title);
} else if (e.key === "Escape") {
e.preventDefault();
renamingCommittedRef.current = true;
cancelRename();
}
}}
onBlur={() => {
if (!renamingCommittedRef.current) {
void commitRename(thread.id, renamingTitle, thread.title);
}
}}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</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"
@@ -1049,7 +816,7 @@ export default function Sidebar() {
})}
</SidebarMenu>
{projects.length === 0 && !addingProject && (
{state.projects.length === 0 && !addingProject && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet.
<br />
@@ -389,9 +389,6 @@ function TerminalViewport({
fitAddonRef.current = null;
terminal.dispose();
};
// autoFocus is intentionally omitted;
// it is only read at mount time and must not trigger terminal teardown/recreation.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cwd, runtimeEnv, terminalId, threadId]);
useEffect(() => {
+3 -2
View File
@@ -20,9 +20,10 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
) {
const chipsRef = React.useRef<Element | null>(null);
const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
return (
<ComboboxContext.Provider value={value}>
<ComboboxContext.Provider
value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
>
<ComboboxPrimitive.Root {...props} />
</ComboboxContext.Provider>
);
+5 -2
View File
@@ -22,7 +22,6 @@ function ToggleGroup({
children,
...props
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
const value = React.useMemo(() => ({ size, variant }), [size, variant]);
return (
<ToggleGroupPrimitive
className={cn(
@@ -43,7 +42,11 @@ function ToggleGroup({
orientation={orientation}
{...props}
>
<ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
<ToggleGroupContext.Provider
value={React.useMemo(() => ({ size, variant }), [size, variant])}
>
{children}
</ToggleGroupContext.Provider>
</ToggleGroupPrimitive>
);
}
@@ -1,27 +0,0 @@
import { describe, expect, it } from "vitest";
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
describe("splitPromptIntoComposerSegments", () => {
it("splits mention tokens followed by whitespace into mention segments", () => {
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md please")).toEqual([
{ type: "text", text: "Inspect " },
{ type: "mention", path: "AGENTS.md" },
{ type: "text", text: " please" },
]);
});
it("does not convert an incomplete trailing mention token", () => {
expect(splitPromptIntoComposerSegments("Inspect @AGENTS.md")).toEqual([
{ type: "text", text: "Inspect @AGENTS.md" },
]);
});
it("keeps newlines around mention tokens", () => {
expect(splitPromptIntoComposerSegments("one\n@src/index.ts \ntwo")).toEqual([
{ type: "text", text: "one\n" },
{ type: "mention", path: "src/index.ts" },
{ type: "text", text: " \ntwo" },
]);
});
});
-56
View File
@@ -1,56 +0,0 @@
export type ComposerPromptSegment =
| {
type: "text";
text: string;
}
| {
type: "mention";
path: string;
};
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
function pushTextSegment(segments: ComposerPromptSegment[], text: string): void {
if (!text) return;
const last = segments[segments.length - 1];
if (last && last.type === "text") {
last.text += text;
return;
}
segments.push({ type: "text", text });
}
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
const segments: ComposerPromptSegment[] = [];
if (!prompt) {
return segments;
}
let cursor = 0;
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
const fullMatch = match[0];
const prefix = match[1] ?? "";
const path = match[2] ?? "";
const matchIndex = match.index ?? 0;
const mentionStart = matchIndex + prefix.length;
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
if (mentionStart > cursor) {
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
}
if (path.length > 0) {
segments.push({ type: "mention", path });
} else {
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
}
cursor = mentionEnd;
}
if (cursor < prompt.length) {
pushTextSegment(segments, prompt.slice(cursor));
}
return segments;
}
+1 -29
View File
@@ -1,10 +1,6 @@
import { describe, expect, it } from "vitest";
import {
detectComposerTrigger,
expandCollapsedComposerCursor,
replaceTextRange,
} from "./composer-logic";
import { detectComposerTrigger, replaceTextRange } from "./composer-logic";
describe("detectComposerTrigger", () => {
it("detects @path trigger at cursor", () => {
@@ -53,27 +49,3 @@ describe("replaceTextRange", () => {
});
});
});
describe("expandCollapsedComposerCursor", () => {
it("keeps cursor unchanged when no mention segment is present", () => {
expect(expandCollapsedComposerCursor("plain text", 5)).toBe(5);
});
it("maps collapsed mention cursor to expanded text cursor", () => {
const text = "what's in my @AGENTS.md fsfdas";
const collapsedCursorAfterMention = "what's in my ".length + 2;
const expandedCursorAfterMention = "what's in my @AGENTS.md ".length;
expect(expandCollapsedComposerCursor(text, collapsedCursorAfterMention)).toBe(
expandedCursorAfterMention,
);
});
it("allows path trigger detection to close after selecting a mention", () => {
const text = "what's in my @AGENTS.md ";
const collapsedCursorAfterMention = "what's in my ".length + 2;
const expandedCursor = expandCollapsedComposerCursor(text, collapsedCursorAfterMention);
expect(detectComposerTrigger(text, expandedCursor)).toBeNull();
});
});
-34
View File
@@ -1,5 +1,3 @@
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
export interface ComposerTrigger {
@@ -26,38 +24,6 @@ function tokenStartForCursor(text: string, cursor: number): number {
return index + 1;
}
export function expandCollapsedComposerCursor(text: string, cursorInput: number): number {
const collapsedCursor = clampCursor(text, cursorInput);
const segments = splitPromptIntoComposerSegments(text);
if (segments.length === 0) {
return collapsedCursor;
}
let remaining = collapsedCursor;
let expandedCursor = 0;
for (const segment of segments) {
if (segment.type === "mention") {
const expandedLength = segment.path.length + 1;
if (remaining <= 1) {
return expandedCursor + (remaining === 0 ? 0 : expandedLength);
}
remaining -= 1;
expandedCursor += expandedLength;
continue;
}
const segmentLength = segment.text.length;
if (remaining <= segmentLength) {
return expandedCursor + remaining;
}
remaining -= segmentLength;
expandedCursor += segmentLength;
}
return expandedCursor;
}
export function detectComposerTrigger(text: string, cursorInput: number): ComposerTrigger | null {
const cursor = clampCursor(text, cursorInput);
const lineStart = text.lastIndexOf("\n", Math.max(0, cursor - 1)) + 1;
-350
View File
@@ -1,350 +0,0 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ComposerImageAttachment, useComposerDraftStore } from "./composerDraftStore";
function makeImage(input: {
id: string;
previewUrl: string;
name?: string;
mimeType?: string;
sizeBytes?: number;
lastModified?: number;
}): ComposerImageAttachment {
const name = input.name ?? "image.png";
const mimeType = input.mimeType ?? "image/png";
const sizeBytes = input.sizeBytes ?? 4;
const lastModified = input.lastModified ?? 1_700_000_000_000;
const file = new File([new Uint8Array(sizeBytes).fill(1)], name, {
type: mimeType,
lastModified,
});
return {
type: "image",
id: input.id,
name,
mimeType,
sizeBytes: file.size,
previewUrl: input.previewUrl,
file,
};
}
describe("composerDraftStore addImages", () => {
const threadId = ThreadId.makeUnsafe("thread-dedupe");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("deduplicates identical images in one batch by file signature", () => {
const first = makeImage({
id: "img-1",
previewUrl: "blob:first",
name: "same.png",
mimeType: "image/png",
sizeBytes: 12,
lastModified: 12345,
});
const duplicate = makeImage({
id: "img-2",
previewUrl: "blob:duplicate",
name: "same.png",
mimeType: "image/png",
sizeBytes: 12,
lastModified: 12345,
});
useComposerDraftStore.getState().addImages(threadId, [first, duplicate]);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-1"]);
expect(revokeSpy).toHaveBeenCalledWith("blob:duplicate");
});
it("deduplicates against existing images across calls by file signature", () => {
const first = makeImage({
id: "img-a",
previewUrl: "blob:a",
name: "same.png",
mimeType: "image/png",
sizeBytes: 9,
lastModified: 777,
});
const duplicateLater = makeImage({
id: "img-b",
previewUrl: "blob:b",
name: "same.png",
mimeType: "image/png",
sizeBytes: 9,
lastModified: 999,
});
useComposerDraftStore.getState().addImage(threadId, first);
useComposerDraftStore.getState().addImage(threadId, duplicateLater);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-a"]);
expect(revokeSpy).toHaveBeenCalledWith("blob:b");
});
it("does not revoke blob URLs that are still used by an accepted duplicate image", () => {
const first = makeImage({
id: "img-shared",
previewUrl: "blob:shared",
});
const duplicateSameUrl = makeImage({
id: "img-shared",
previewUrl: "blob:shared",
});
useComposerDraftStore.getState().addImages(threadId, [first, duplicateSameUrl]);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft?.images.map((image) => image.id)).toEqual(["img-shared"]);
expect(revokeSpy).not.toHaveBeenCalledWith("blob:shared");
});
});
describe("composerDraftStore clearComposerContent", () => {
const threadId = ThreadId.makeUnsafe("thread-clear");
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
let revokeSpy: ReturnType<typeof vi.fn<(url: string) => void>>;
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
originalRevokeObjectUrl = URL.revokeObjectURL;
revokeSpy = vi.fn();
URL.revokeObjectURL = revokeSpy;
});
afterEach(() => {
URL.revokeObjectURL = originalRevokeObjectUrl;
});
it("does not revoke blob preview URLs when clearing composer content", () => {
const first = makeImage({
id: "img-optimistic",
previewUrl: "blob:optimistic",
});
useComposerDraftStore.getState().addImage(threadId, first);
useComposerDraftStore.getState().clearComposerContent(threadId);
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
expect(draft).toBeUndefined();
expect(revokeSpy).not.toHaveBeenCalledWith("blob:optimistic");
});
});
describe("composerDraftStore project draft thread mapping", () => {
const projectId = ProjectId.makeUnsafe("project-a");
const otherProjectId = ProjectId.makeUnsafe("project-b");
const threadId = ThreadId.makeUnsafe("thread-a");
const otherThreadId = ThreadId.makeUnsafe("thread-b");
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("stores and reads project draft thread ids via actions", () => {
const store = useComposerDraftStore.getState();
expect(store.getDraftThreadByProjectId(projectId)).toBeNull();
expect(store.getDraftThread(threadId)).toBeNull();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toEqual({
threadId,
projectId,
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toEqual({
projectId,
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
createdAt: "2026-01-01T00:00:00.000Z",
});
});
it("clears only matching project draft mapping entries", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "hello");
store.clearProjectDraftThreadById(projectId, otherThreadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
threadId,
);
store.clearProjectDraftThreadById(projectId, threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears project draft mapping by project id", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "hello");
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears orphaned composer drafts when remapping a project to a new draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "orphan me");
store.setProjectDraftThreadId(projectId, otherThreadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
otherThreadId,
);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("keeps composer drafts when the thread is still mapped by another project", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setProjectDraftThreadId(otherProjectId, threadId);
store.setPrompt(threadId, "keep me");
store.clearProjectDraftThreadId(projectId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId).toBe(
threadId,
);
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("clears draft registration independently", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.clearDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
});
it("updates branch context on an existing draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "main",
worktreePath: null,
});
store.setDraftThreadContext(threadId, {
branch: "feature/next",
worktreePath: "/tmp/feature-next",
});
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)?.threadId).toBe(
threadId,
);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "feature/next",
worktreePath: "/tmp/feature-next",
envMode: "worktree",
});
});
it("preserves existing branch and worktree when setProjectDraftThreadId receives undefined", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "main",
worktreePath: "/tmp/main-worktree",
});
const runtimeUndefinedOptions = {
branch: undefined,
worktreePath: undefined,
} as unknown as {
branch?: string | null;
worktreePath?: string | null;
};
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "main",
worktreePath: "/tmp/main-worktree",
envMode: "worktree",
});
});
it("preserves worktree env mode without a worktree path", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
branch: "feature/base",
worktreePath: null,
envMode: "worktree",
});
const runtimeUndefinedOptions = {
branch: undefined,
worktreePath: undefined,
envMode: undefined,
} as unknown as {
branch?: string | null;
worktreePath?: string | null;
envMode?: "local" | "worktree";
};
store.setProjectDraftThreadId(projectId, threadId, runtimeUndefinedOptions);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toMatchObject({
projectId,
branch: "feature/base",
worktreePath: null,
envMode: "worktree",
});
});
});
describe("composerDraftStore setModel", () => {
const threadId = ThreadId.makeUnsafe("thread-model");
beforeEach(() => {
useComposerDraftStore.setState({
draftsByThreadId: {},
draftThreadsByThreadId: {},
projectDraftThreadIdByProjectId: {},
});
});
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
const store = useComposerDraftStore.getState();
store.setModel(threadId, "gpt-5.3-codex");
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe("gpt-5.3-codex");
});
});
File diff suppressed because it is too large. Load diff
+3 -5
View File
@@ -1,12 +1,10 @@
import type { ContextMenuItem } from "@t3tools/contracts";
/**
* Imperative DOM-based context menu for non-Electron environments.
* Shows a positioned dropdown and returns a promise that resolves
* with the clicked item id, or null if dismissed.
*/
export function showContextMenuFallback<T extends string>(
items: readonly ContextMenuItem<T>[],
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
): Promise<T | null> {
return new Promise<T | null>((resolve) => {
@@ -43,8 +41,8 @@ export function showContextMenuFallback<T extends string>(
const btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
const isDestructiveAction = item.destructive === true || item.id === "delete";
btn.className = isDestructiveAction
const isDeleteAction = item.id === "delete";
btn.className = isDeleteAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
btn.addEventListener("click", () => cleanup(item.id));
+16 -22
View File
@@ -15,7 +15,6 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { preferredTerminalEditor } from "../terminal-links";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
@@ -124,18 +123,13 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
const removeOrphanedTerminalStates = useTerminalStateStore(
(store) => store.removeOrphanedTerminalStates,
);
const { dispatch } = useStore();
const queryClient = useQueryClient();
const navigate = useNavigate();
const pathname = useRouterState({ select: (state) => state.location.pathname });
const pathnameRef = useRef(pathname);
const lastConfigIssuesSignatureRef = useRef<string | null>(null);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
pathnameRef.current = pathname;
useEffect(() => {
@@ -150,13 +144,7 @@ function EventRouter() {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
syncServerReadModel(snapshot);
const activeThreadIds = new Set(
snapshot.threads
.filter((t) => t.deletedAt === null)
.map((t) => t.id),
);
removeOrphanedTerminalStates(activeThreadIds);
dispatch({ type: "SYNC_SERVER_READ_MODEL", readModel: snapshot });
if (pending) {
pending = false;
await flushSnapshotSync();
@@ -169,13 +157,14 @@ function EventRouter() {
return;
}
syncing = true;
pending = false;
try {
pending = false;
await flushSnapshotSync();
} catch {
// Keep prior state and wait for next domain event to trigger a resync.
} finally {
syncing = false;
}
syncing = false;
};
void syncSnapshot().catch(() => undefined);
@@ -195,11 +184,12 @@ function EventRouter() {
if (hasRunningSubprocess === null) {
return;
}
useTerminalStateStore.getState().setTerminalActivity(
ThreadId.makeUnsafe(event.threadId),
event.terminalId,
dispatch({
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe(event.threadId),
terminalId: event.terminalId,
hasRunningSubprocess,
);
});
});
const unsubWelcome = onServerWelcome((payload) => {
void (async () => {
@@ -211,7 +201,11 @@ function EventRouter() {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
}
setProjectExpanded(payload.bootstrapProjectId, true);
dispatch({
type: "SET_PROJECT_EXPANDED",
projectId: payload.bootstrapProjectId,
expanded: true,
});
if (pathnameRef.current !== "/") {
return;
@@ -276,7 +270,7 @@ function EventRouter() {
unsubWelcome();
unsubServerConfigUpdated();
};
}, [navigate, queryClient, removeOrphanedTerminalStates, setProjectExpanded, syncServerReadModel]);
}, [dispatch, navigate, queryClient]);
return null;
}
+8 -13
View File
@@ -3,7 +3,6 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Suspense, lazy, type ReactNode, useCallback, useEffect } from "react";
import ChatView from "../components/ChatView";
import { useComposerDraftStore } from "../composerDraftStore";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { useStore } from "../store";
@@ -133,17 +132,13 @@ const DiffPanelInlineSidebar = (props: {
};
function ChatThreadRouteView() {
const threadsHydrated = useStore((store) => store.threadsHydrated);
const { state } = useStore();
const navigate = useNavigate();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
});
const search = Route.useSearch();
const threadExists = useStore((store) => store.threads.some((thread) => thread.id === threadId));
const draftThreadExists = useComposerDraftStore(
(store) => Object.hasOwn(store.draftThreadsByThreadId, threadId),
);
const routeThreadExists = threadExists || draftThreadExists;
const threadExists = state.threads.some((thread) => thread.id === threadId);
const diffOpen = search.diff === "1";
const shouldUseDiffSheet = useMediaQuery(DIFF_INLINE_LAYOUT_MEDIA_QUERY);
const closeDiff = useCallback(() => {
@@ -167,17 +162,17 @@ function ChatThreadRouteView() {
}, [navigate, threadId]);
useEffect(() => {
if (!threadsHydrated) {
if (!state.threadsHydrated) {
return;
}
if (!routeThreadExists) {
if (!threadExists) {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
}, [navigate, state.threadsHydrated, threadExists, threadId]);
if (!threadsHydrated || !routeThreadExists) {
if (!state.threadsHydrated || !threadExists) {
return null;
}
@@ -185,7 +180,7 @@ function ChatThreadRouteView() {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView key={threadId} threadId={threadId} />
<ChatView threadId={threadId} />
</SidebarInset>
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
</>
@@ -195,7 +190,7 @@ function ChatThreadRouteView() {
return (
<>
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<ChatView key={threadId} threadId={threadId} />
<ChatView threadId={threadId} />
</SidebarInset>
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
<Suspense fallback={<DiffLoadingFallback inline={false} />}>
+18 -18
View File
@@ -48,8 +48,7 @@ const RUNTIME_MODE_OPTIONS = [
function SettingsRouteView() {
const { theme, setTheme, resolvedTheme } = useTheme();
const runtimeMode = useStore((store) => store.runtimeMode);
const setRuntimeMode = useStore((store) => store.setRuntimeMode);
const { state, dispatch } = useStore();
const { settings, defaults, updateSettings } = useAppSettings();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
@@ -187,10 +186,9 @@ function SettingsRouteView() {
</div>
<div className="space-y-4">
<label htmlFor="codex-binary-path" className="block space-y-1">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">Codex binary path</span>
<Input
id="codex-binary-path"
value={codexBinaryPath}
onChange={(event) => updateSettings({ codexBinaryPath: event.target.value })}
placeholder="codex"
@@ -201,10 +199,9 @@ function SettingsRouteView() {
</span>
</label>
<label htmlFor="codex-home-path" className="block space-y-1">
<label className="block space-y-1">
<span className="text-xs font-medium text-foreground">CODEX_HOME path</span>
<Input
id="codex-home-path"
value={codexHomePath}
onChange={(event) => updateSettings({ codexHomePath: event.target.value })}
placeholder="/Users/you/.codex"
@@ -245,11 +242,16 @@ function SettingsRouteView() {
</div>
<div className="space-y-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start">
<label htmlFor="custom-model-slug" className="block flex-1 space-y-1">
<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
id="custom-model-slug"
value={customModelInput}
onChange={(event) => {
setCustomModelInput(event.target.value);
@@ -257,11 +259,6 @@ function SettingsRouteView() {
setCustomModelError(null);
}
}}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
addCustomModel();
}}
placeholder="your-model-slug"
spellCheck={false}
/>
@@ -270,10 +267,10 @@ function SettingsRouteView() {
</span>
</label>
<Button className="sm:mt-6" type="button" onClick={addCustomModel}>
<Button className="sm:mt-6" type="submit">
Add model
</Button>
</div>
</form>
{customModelError ? (
<p className="text-xs text-destructive">{customModelError}</p>
@@ -336,7 +333,7 @@ function SettingsRouteView() {
<div className="space-y-2" role="radiogroup" aria-label="Runtime mode preference">
{RUNTIME_MODE_OPTIONS.map((option) => {
const selected = runtimeMode === option.value;
const selected = state.runtimeMode === option.value;
return (
<button
key={option.value}
@@ -349,7 +346,10 @@ function SettingsRouteView() {
: "border-border bg-background text-muted-foreground hover:bg-accent"
}`}
onClick={() => {
setRuntimeMode(option.value);
dispatch({
type: "SET_RUNTIME_MODE",
mode: option.value,
});
}}
>
<span className="flex flex-col">
+84 -7
View File
@@ -1,8 +1,8 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { markThreadUnread, type AppState } from "./store";
import type { Thread } from "./types";
import { reducer, type AppState } from "./store";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
@@ -11,6 +11,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
model: "gpt-5-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
turnDiffSummaries: [],
@@ -42,8 +54,8 @@ function makeState(thread: Thread): AppState {
};
}
describe("store pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
describe("store reducer", () => {
it("marks a completed thread as unread by moving lastVisitedAt before completion", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
@@ -59,7 +71,10 @@ describe("store pure functions", () => {
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
const next = reducer(initialState, {
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined();
@@ -69,7 +84,7 @@ describe("store pure functions", () => {
);
});
it("markThreadUnread does not change a thread without a completed turn", () => {
it("does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurn: null,
@@ -77,8 +92,70 @@ describe("store pure functions", () => {
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
const next = reducer(initialState, {
type: "MARK_THREAD_UNREAD",
threadId: ThreadId.makeUnsafe("thread-1"),
});
expect(next).toEqual(initialState);
});
});
describe("store terminal activity reducer", () => {
it("adds a terminal to runningTerminalIds when subprocess activity starts", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
},
],
}),
);
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "alt",
hasRunningSubprocess: true,
});
expect(next.threads[0]?.runningTerminalIds).toEqual(["alt"]);
});
it("removes a terminal from runningTerminalIds when subprocess activity stops", () => {
const state = makeState(
makeThread({
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "alt"],
},
],
runningTerminalIds: ["alt"],
}),
);
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "alt",
hasRunningSubprocess: false,
});
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
});
it("ignores activity events for unknown terminal ids", () => {
const state = makeState(makeThread());
const next = reducer(state, {
type: "SET_THREAD_TERMINAL_ACTIVITY",
threadId: ThreadId.makeUnsafe("thread-1"),
terminalId: "missing",
hasRunningSubprocess: true,
});
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
});
});
+622 -209
View File
@@ -1,4 +1,13 @@
import { Fragment, type ReactNode, createElement, useEffect } from "react";
import {
type Dispatch,
type ReactNode,
createContext,
createElement,
useContext,
useEffect,
useReducer,
} from "react";
import {
DEFAULT_MODEL,
ProviderSessionId,
@@ -7,15 +16,48 @@ import {
type OrchestrationSessionStatus,
resolveModelSlug,
} from "@t3tools/contracts";
import { create } from "zustand";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
DEFAULT_RUNTIME_MODE,
MAX_THREAD_TERMINAL_COUNT,
type ChatMessage,
type Project,
type RuntimeMode,
type Thread,
type ThreadTerminalGroup,
} from "./types";
// ── Actions ──────────────────────────────────────────────────────────
type Action =
| { type: "SYNC_SERVER_READ_MODEL"; readModel: OrchestrationReadModel }
| { type: "MARK_THREAD_VISITED"; threadId: ThreadId; visitedAt?: string }
| { type: "MARK_THREAD_UNREAD"; threadId: ThreadId }
| { type: "TOGGLE_PROJECT"; projectId: Project["id"] }
| {
type: "SET_THREAD_TERMINAL_ACTIVITY";
threadId: ThreadId;
terminalId: string;
hasRunningSubprocess: boolean;
}
| { type: "SET_PROJECT_EXPANDED"; projectId: Project["id"]; expanded: boolean }
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: ThreadId }
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: ThreadId; open: boolean }
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: ThreadId; height: number }
| { type: "SPLIT_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "NEW_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "CLOSE_THREAD_TERMINAL"; threadId: ThreadId; terminalId: string }
| { type: "SET_ERROR"; threadId: ThreadId; error: string | null }
| {
type: "SET_THREAD_BRANCH";
threadId: ThreadId;
branch: string | null;
worktreePath: string | null;
}
| { type: "SET_RUNTIME_MODE"; mode: RuntimeMode };
// ── State ────────────────────────────────────────────────────────────
export interface AppState {
@@ -45,10 +87,11 @@ const initialState: AppState = {
};
const persistedExpandedProjectCwds = new Set<string>();
// ── Persist helpers ──────────────────────────────────────────────────
// ── Helpers ──────────────────────────────────────────────────────────
function readPersistedState(): AppState {
if (typeof window === "undefined") return initialState;
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) return initialState;
@@ -76,6 +119,7 @@ function readPersistedState(): AppState {
function persistState(state: AppState): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
PERSISTED_STATE_KEY,
@@ -94,21 +138,12 @@ function persistState(state: AppState): void {
}
}
// ── Pure helpers ──────────────────────────────────────────────────────
function updateThread(
threads: Thread[],
threadId: ThreadId,
updater: (t: Thread) => Thread,
): Thread[] {
let changed = false;
const next = threads.map((t) => {
if (t.id !== threadId) return t;
const updated = updater(t);
if (updated !== t) changed = true;
return updated;
});
return changed ? next : threads;
return threads.map((t) => (t.id === threadId ? updater(t) : t));
}
function mapProjectsFromReadModel(
@@ -158,7 +193,9 @@ function toLegacyProvider(providerName: string | null): "codex" | "claudeCode" {
}
function resolveWsHttpOrigin(): string {
if (typeof window === "undefined") return "";
if (typeof window === "undefined") {
return "";
}
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsCandidate =
@@ -167,7 +204,10 @@ function resolveWsHttpOrigin(): string {
: typeof envWsUrl === "string" && envWsUrl.length > 0
? envWsUrl
: null;
if (!wsCandidate) return window.location.origin;
if (!wsCandidate) {
return window.location.origin;
}
try {
const wsUrl = new URL(wsCandidate);
const protocol =
@@ -193,221 +233,594 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
return `/attachments/${encodeURIComponent(attachmentId)}`;
}
// ── Pure state transition functions ────────────────────────────────────
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
const unique = [...new Set(ids)].slice(0, MAX_THREAD_TERMINAL_COUNT);
if (unique.length > 0) {
return unique;
}
return [DEFAULT_THREAD_TERMINAL_ID];
}
export function syncServerReadModel(
state: AppState,
readModel: OrchestrationReadModel,
): AppState {
const projects = mapProjectsFromReadModel(
readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
);
const threads = readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
return {
id: thread.id,
codexThreadId: thread.session?.providerThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
session: thread.session
? {
sessionId:
thread.session.providerSessionId ??
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
provider: toLegacyProvider(thread.session.providerName),
status: toLegacySessionStatus(thread.session.status),
orchestrationStatus: thread.session.status,
threadId: thread.session.providerThreadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.updatedAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => {
const attachments = message.attachments?.map((attachment) => ({
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
}));
const normalizedMessage: ChatMessage = {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
...(message.streaming ? {} : { completedAt: message.updatedAt }),
...(attachments && attachments.length > 0 ? { attachments } : {}),
};
return normalizedMessage;
}),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
turnId: checkpoint.turnId,
completedAt: checkpoint.completedAt,
status: checkpoint.status,
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
checkpointTurnCount: checkpoint.checkpointTurnCount,
checkpointRef: checkpoint.checkpointRef,
files: checkpoint.files.map((file) => ({ ...file })),
})),
activities: thread.activities.map((activity) => ({ ...activity })),
};
function normalizeRunningTerminalIds(
runningTerminalIds: string[],
terminalIds: string[],
): string[] {
if (runningTerminalIds.length === 0) return [];
const validTerminalIdSet = new Set(terminalIds);
return [...new Set(runningTerminalIds)]
.map((id) => id.trim())
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
if (!usedGroupIds.has(groupId)) {
usedGroupIds.add(groupId);
return groupId;
}
let suffix = 2;
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
suffix += 1;
}
const uniqueGroupId = `${groupId}-${suffix}`;
usedGroupIds.add(uniqueGroupId);
return uniqueGroupId;
}
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
const groups: ThreadTerminalGroup[] = [];
for (const group of thread.terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
return {
...state,
projects,
threads,
threadsHydrated: true,
};
}
export function markThreadVisited(
state: AppState,
threadId: ThreadId,
visitedAt?: string,
): AppState {
const at = visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(at);
const threads = updateThread(state.threads, threadId, (thread) => {
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return thread;
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
return { ...thread, lastVisitedAt: at };
});
return threads === state.threads ? state : { ...state, threads };
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
groups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
groups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (groups.length > 0) {
return groups;
}
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
export function markThreadUnread(state: AppState, threadId: ThreadId): AppState {
const threads = updateThread(state.threads, threadId, (thread) => {
if (!thread.latestTurn?.completedAt) return thread;
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) return thread;
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (thread.lastVisitedAt === unreadVisitedAt) return thread;
return { ...thread, lastVisitedAt: unreadVisitedAt };
});
return threads === state.threads ? state : { ...state, threads };
function findGroupIndexByTerminalId(
terminalGroups: ThreadTerminalGroup[],
terminalId: string,
): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
function normalizeThreadTerminals(thread: Thread): Thread {
const terminalIds = normalizeTerminalIds(thread.terminalIds);
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(activeTerminalId);
return {
...state,
projects: state.projects.map((p) =>
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
),
...thread,
terminalIds,
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
activeTerminalId,
terminalGroups,
activeTerminalGroupId,
};
}
export function setProjectExpanded(
state: AppState,
projectId: Project["id"],
expanded: boolean,
): AppState {
let changed = false;
const projects = state.projects.map((p) => {
if (p.id !== projectId || p.expanded === expanded) return p;
changed = true;
return { ...p, expanded };
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
if (!thread.terminalIds.includes(terminalId)) {
return thread;
}
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
const nextTerminalGroupId = fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID);
return normalizeThreadTerminals({
...thread,
terminalOpen: false,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: nextTerminalGroupId,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: nextTerminalGroupId,
});
}
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
const closedTerminalGroup = thread.terminalGroups.find((group) =>
group.terminalIds.includes(terminalId),
);
const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1;
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
(id) => id !== terminalId,
);
const nextActiveTerminalId =
thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
] ??
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: thread.activeTerminalId;
const nextTerminalGroups = thread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
return normalizeThreadTerminals({
...thread,
terminalIds: remainingTerminalIds,
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
activeTerminalId: nextActiveTerminalId,
terminalGroups: nextTerminalGroups,
});
return changed ? { ...state, projects } : state;
}
export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState {
const threads = updateThread(state.threads, threadId, (t) => {
if (t.error === error) return t;
return { ...t, error };
function setThreadTerminalActivity(
thread: Thread,
terminalId: string,
hasRunningSubprocess: boolean,
): Thread {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(terminalId)) {
return normalizedThread;
}
const runningTerminalIds = new Set(normalizedThread.runningTerminalIds);
if (hasRunningSubprocess) {
runningTerminalIds.add(terminalId);
} else {
runningTerminalIds.delete(terminalId);
}
return normalizeThreadTerminals({
...normalizedThread,
runningTerminalIds: [...runningTerminalIds],
});
return threads === state.threads ? state : { ...state, threads };
}
export function setThreadBranch(
state: AppState,
threadId: ThreadId,
branch: string | null,
worktreePath: string | null,
): AppState {
const threads = updateThread(state.threads, threadId, (t) => {
if (t.branch === branch && t.worktreePath === worktreePath) return t;
const cwdChanged = t.worktreePath !== worktreePath;
return {
...t,
branch,
worktreePath,
...(cwdChanged ? { session: null } : {}),
};
});
return threads === state.threads ? state : { ...state, threads };
// ── Reducer ──────────────────────────────────────────────────────────
export function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case "SYNC_SERVER_READ_MODEL": {
const projects = mapProjectsFromReadModel(
action.readModel.projects.filter((project) => project.deletedAt === null),
state.projects,
);
const existingThreadById = new Map(
state.threads.map((thread) => [thread.id, thread] as const),
);
const threads = action.readModel.threads
.filter((thread) => thread.deletedAt === null)
.map((thread) => {
const existing = existingThreadById.get(thread.id);
return normalizeThreadTerminals({
id: thread.id,
codexThreadId: thread.session?.providerThreadId ?? null,
projectId: thread.projectId,
title: thread.title,
model: resolveModelSlug(thread.model),
terminalOpen: existing?.terminalOpen ?? false,
terminalHeight: existing?.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: existing?.terminalIds ?? [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: existing?.runningTerminalIds ?? [],
activeTerminalId: existing?.activeTerminalId ?? DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: existing?.terminalGroups ?? [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId:
existing?.activeTerminalGroupId ?? `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: thread.session
? {
sessionId:
thread.session.providerSessionId ??
ProviderSessionId.makeUnsafe(`thread:${thread.id}`),
provider: toLegacyProvider(thread.session.providerName),
status: toLegacySessionStatus(thread.session.status),
orchestrationStatus: thread.session.status,
threadId: thread.session.providerThreadId,
activeTurnId: thread.session.activeTurnId ?? undefined,
createdAt: thread.session.updatedAt,
updatedAt: thread.session.updatedAt,
...(thread.session.lastError ? { lastError: thread.session.lastError } : {}),
}
: null,
messages: thread.messages.map((message) => {
const attachments = message.attachments?.map((attachment) => ({
type: "image" as const,
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)),
}));
const normalizedMessage: ChatMessage = {
id: message.id,
role: message.role,
text: message.text,
createdAt: message.createdAt,
streaming: message.streaming,
...(message.streaming ? {} : { completedAt: message.updatedAt }),
...(attachments && attachments.length > 0 ? { attachments } : {}),
};
return normalizedMessage;
}),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({
turnId: checkpoint.turnId,
completedAt: checkpoint.completedAt,
status: checkpoint.status,
assistantMessageId: checkpoint.assistantMessageId ?? undefined,
checkpointTurnCount: checkpoint.checkpointTurnCount,
checkpointRef: checkpoint.checkpointRef,
files: checkpoint.files.map((file) => ({ ...file })),
})),
activities: thread.activities.map((activity) => ({ ...activity })),
});
});
return {
...state,
projects,
threads,
threadsHydrated: true,
};
}
case "MARK_THREAD_VISITED": {
const visitedAt = action.visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(visitedAt);
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return thread;
}
return {
...thread,
lastVisitedAt: visitedAt,
};
}),
};
}
case "MARK_THREAD_UNREAD": {
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
if (!thread.latestTurn?.completedAt) {
return thread;
}
const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return thread;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (thread.lastVisitedAt === unreadVisitedAt) {
return thread;
}
return {
...thread,
lastVisitedAt: unreadVisitedAt,
};
}),
};
}
case "TOGGLE_PROJECT":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: !p.expanded } : p,
),
};
case "SET_THREAD_TERMINAL_ACTIVITY":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
setThreadTerminalActivity(thread, action.terminalId, action.hasRunningSubprocess),
),
};
case "SET_PROJECT_EXPANDED":
return {
...state,
projects: state.projects.map((p) =>
p.id === action.projectId ? { ...p, expanded: action.expanded } : p,
),
};
case "TOGGLE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalOpen: !t.terminalOpen,
})),
};
case "SET_THREAD_TERMINAL_OPEN":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalOpen: action.open,
})),
};
case "SET_THREAD_TERMINAL_HEIGHT":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
terminalHeight: action.height,
})),
};
case "SPLIT_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
...group,
terminalIds: [...group.terminalIds],
}));
let activeGroupIndex = terminalGroups.findIndex(
(group) => group.id === normalizedThread.activeTerminalGroupId,
);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
normalizedThread.activeTerminalId,
);
}
if (activeGroupIndex < 0) {
terminalGroups.push({
id: fallbackGroupId(normalizedThread.activeTerminalId),
terminalIds: [normalizedThread.activeTerminalId],
});
activeGroupIndex = terminalGroups.length - 1;
}
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
]!.terminalIds.filter((id) => id !== action.terminalId);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
if (existingGroupIndex < activeGroupIndex) {
activeGroupIndex -= 1;
}
}
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalizedThread;
}
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(
normalizedThread.activeTerminalId,
);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
} else {
destinationGroup.terminalIds.push(action.terminalId);
}
}
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: destinationGroup.id,
terminalGroups,
});
}),
};
case "NEW_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const isNewTerminal = !normalizedThread.terminalIds.includes(action.terminalId);
if (isNewTerminal && normalizedThread.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalizedThread;
}
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
? normalizedThread.terminalIds
: [...normalizedThread.terminalIds, action.terminalId];
const terminalGroups = normalizedThread.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextGroupId = fallbackGroupId(action.terminalId);
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
return normalizeThreadTerminals({
...normalizedThread,
terminalIds,
activeTerminalId: action.terminalId,
activeTerminalGroupId: nextGroupId,
terminalGroups,
});
}),
};
case "SET_THREAD_ACTIVE_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
return thread;
}
const nextActiveGroupIndex = findGroupIndexByTerminalId(
normalizedThread.terminalGroups,
action.terminalId,
);
const activeTerminalGroupId =
nextActiveGroupIndex >= 0
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
normalizedThread.activeTerminalGroupId)
: normalizedThread.activeTerminalGroupId;
return normalizeThreadTerminals({
...normalizedThread,
activeTerminalId: action.terminalId,
activeTerminalGroupId,
});
}),
};
case "CLOSE_THREAD_TERMINAL":
return {
...state,
threads: updateThread(state.threads, action.threadId, (thread) =>
closeThreadTerminal(thread, action.terminalId),
),
};
case "SET_ERROR":
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => ({
...t,
error: action.error,
})),
};
case "SET_THREAD_BRANCH": {
return {
...state,
threads: updateThread(state.threads, action.threadId, (t) => {
// When the effective cwd changes (worktreePath differs), the old
// session is no longer valid — clear it so ensureSession creates a
// new one with the correct cwd on the next message.
const cwdChanged = t.worktreePath !== action.worktreePath;
return {
...t,
branch: action.branch,
worktreePath: action.worktreePath,
...(cwdChanged ? { session: null } : {}),
};
}),
};
}
case "SET_RUNTIME_MODE":
return {
...state,
runtimeMode: action.mode,
};
default:
return state;
}
}
export function setRuntimeMode(state: AppState, mode: RuntimeMode): AppState {
if (state.runtimeMode === mode) return state;
return { ...state, runtimeMode: mode };
}
// ── Context ──────────────────────────────────────────────────────────
// ── Zustand store ────────────────────────────────────────────────────
interface AppStore extends AppState {
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId) => void;
toggleProject: (projectId: Project["id"]) => void;
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
setError: (threadId: ThreadId, error: string | null) => void;
setThreadBranch: (
threadId: ThreadId,
branch: string | null,
worktreePath: string | null,
) => void;
setRuntimeMode: (mode: RuntimeMode) => void;
}
export const useStore = create<AppStore>((set) => ({
...readPersistedState(),
syncServerReadModel: (readModel) =>
set((state) => syncServerReadModel(state, readModel)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId) =>
set((state) => markThreadUnread(state, threadId)),
toggleProject: (projectId) =>
set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
setError: (threadId, error) =>
set((state) => setError(state, threadId, error)),
setThreadBranch: (threadId, branch, worktreePath) =>
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
setRuntimeMode: (mode) =>
set((state) => setRuntimeMode(state, mode)),
}));
// Persist on every state change (only runtimeMode + expandedProjectCwds)
useStore.subscribe((state) => persistState(state));
const StoreContext = createContext<{
state: AppState;
dispatch: Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
export function StoreProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(reducer, undefined, readPersistedState);
useEffect(() => {
persistState(useStore.getState());
}, []);
return createElement(Fragment, null, children);
persistState(state);
}, [state]);
return createElement(StoreContext.Provider, { value: { state, dispatch } }, children);
}
export function useStore() {
return useContext(StoreContext);
}
-89
View File
@@ -1,89 +0,0 @@
import { ThreadId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it } from "vitest";
import { selectThreadTerminalState, useTerminalStateStore } from "./terminalStateStore";
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
describe("terminalStateStore actions", () => {
beforeEach(() => {
if (typeof localStorage !== "undefined") {
localStorage.clear();
}
useTerminalStateStore.setState({ terminalStateByThreadId: {} });
});
it("returns a closed default terminal state for unknown threads", () => {
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
expect(terminalState).toEqual({
terminalOpen: false,
terminalHeight: 280,
terminalIds: ["default"],
runningTerminalIds: [],
activeTerminalId: "default",
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
activeTerminalGroupId: "group-default",
});
});
it("opens and splits terminals into the active group", () => {
const store = useTerminalStateStore.getState();
store.setTerminalOpen(THREAD_ID, true);
store.splitTerminal(THREAD_ID, "terminal-2");
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
expect(terminalState.terminalOpen).toBe(true);
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
expect(terminalState.activeTerminalId).toBe("terminal-2");
expect(terminalState.terminalGroups).toEqual([
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
]);
});
it("creates new terminals in a separate group", () => {
useTerminalStateStore.getState().newTerminal(THREAD_ID, "terminal-2");
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
expect(terminalState.activeTerminalId).toBe("terminal-2");
expect(terminalState.activeTerminalGroupId).toBe("group-terminal-2");
expect(terminalState.terminalGroups).toEqual([
{ id: "group-default", terminalIds: ["default"] },
{ id: "group-terminal-2", terminalIds: ["terminal-2"] },
]);
});
it("tracks and clears terminal subprocess activity", () => {
const store = useTerminalStateStore.getState();
store.splitTerminal(THREAD_ID, "terminal-2");
store.setTerminalActivity(THREAD_ID, "terminal-2", true);
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([
"terminal-2",
]);
store.setTerminalActivity(THREAD_ID, "terminal-2", false);
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).runningTerminalIds).toEqual([]);
});
it("resets to default and clears persisted entry when closing the last terminal", () => {
const store = useTerminalStateStore.getState();
store.closeTerminal(THREAD_ID, "default");
expect(useTerminalStateStore.getState().terminalStateByThreadId[THREAD_ID]).toBeUndefined();
expect(selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID).terminalIds).toEqual(["default"]);
});
it("keeps a valid active terminal after closing an active split terminal", () => {
const store = useTerminalStateStore.getState();
store.splitTerminal(THREAD_ID, "terminal-2");
store.splitTerminal(THREAD_ID, "terminal-3");
store.closeTerminal(THREAD_ID, "terminal-3");
const terminalState = selectThreadTerminalState(useTerminalStateStore.getState().terminalStateByThreadId, THREAD_ID);
expect(terminalState.activeTerminalId).toBe("terminal-2");
expect(terminalState.terminalIds).toEqual(["default", "terminal-2"]);
expect(terminalState.terminalGroups).toEqual([
{ id: "group-default", terminalIds: ["default", "terminal-2"] },
]);
});
});
-532
View File
@@ -1,532 +0,0 @@
/**
* Single Zustand store for terminal UI state keyed by threadId.
*
* Terminal transition helpers are intentionally private to keep the public
* API constrained to store actions/selectors.
*/
import type { ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
MAX_THREAD_TERMINAL_COUNT,
type ThreadTerminalGroup,
} from "./types";
interface ThreadTerminalState {
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
}
const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))].slice(
0,
MAX_THREAD_TERMINAL_COUNT,
);
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
}
function normalizeRunningTerminalIds(runningTerminalIds: string[], terminalIds: string[]): string[] {
if (runningTerminalIds.length === 0) return [];
const validTerminalIdSet = new Set(terminalIds);
return [...new Set(runningTerminalIds)]
.map((id) => id.trim())
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
}
function fallbackGroupId(terminalId: string): string {
return `group-${terminalId}`;
}
function assignUniqueGroupId(baseId: string, usedGroupIds: Set<string>): string {
let candidate = baseId;
let index = 2;
while (usedGroupIds.has(candidate)) {
candidate = `${baseId}-${index}`;
index += 1;
}
usedGroupIds.add(candidate);
return candidate;
}
function findGroupIndexByTerminalId(terminalGroups: ThreadTerminalGroup[], terminalId: string): number {
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
}
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
}
function normalizeTerminalGroups(
terminalGroups: ThreadTerminalGroup[],
terminalIds: string[],
): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const nextGroups: ThreadTerminalGroup[] = [];
const usedGroupIds = new Set<string>();
for (const group of terminalGroups) {
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
if (!validTerminalIdSet.has(terminalId)) return false;
if (assignedTerminalIds.has(terminalId)) return false;
return true;
});
if (groupTerminalIds.length === 0) continue;
for (const terminalId of groupTerminalIds) {
assignedTerminalIds.add(terminalId);
}
const baseGroupId =
group.id.trim().length > 0
? group.id.trim()
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
nextGroups.push({
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
terminalIds: groupTerminalIds,
});
}
for (const terminalId of terminalIds) {
if (assignedTerminalIds.has(terminalId)) continue;
nextGroups.push({
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
terminalIds: [terminalId],
});
}
if (nextGroups.length === 0) {
return [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
];
}
return nextGroups;
}
function arraysEqual(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false;
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) return false;
}
return true;
}
function terminalGroupsEqual(left: ThreadTerminalGroup[], right: ThreadTerminalGroup[]): boolean {
if (left.length !== right.length) return false;
for (let index = 0; index < left.length; index += 1) {
const leftGroup = left[index];
const rightGroup = right[index];
if (!leftGroup || !rightGroup) return false;
if (leftGroup.id !== rightGroup.id) return false;
if (!arraysEqual(leftGroup.terminalIds, rightGroup.terminalIds)) return false;
}
return true;
}
function threadTerminalStateEqual(left: ThreadTerminalState, right: ThreadTerminalState): boolean {
return (
left.terminalOpen === right.terminalOpen &&
left.terminalHeight === right.terminalHeight &&
left.activeTerminalId === right.activeTerminalId &&
left.activeTerminalGroupId === right.activeTerminalGroupId &&
arraysEqual(left.terminalIds, right.terminalIds) &&
arraysEqual(left.runningTerminalIds, right.runningTerminalIds) &&
terminalGroupsEqual(left.terminalGroups, right.terminalGroups)
);
}
const DEFAULT_THREAD_TERMINAL_STATE: ThreadTerminalState = Object.freeze({
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
});
function createDefaultThreadTerminalState(): ThreadTerminalState {
return {
...DEFAULT_THREAD_TERMINAL_STATE,
terminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.terminalIds],
runningTerminalIds: [...DEFAULT_THREAD_TERMINAL_STATE.runningTerminalIds],
terminalGroups: copyTerminalGroups(DEFAULT_THREAD_TERMINAL_STATE.terminalGroups),
};
}
function getDefaultThreadTerminalState(): ThreadTerminalState {
return DEFAULT_THREAD_TERMINAL_STATE;
}
function normalizeThreadTerminalState(state: ThreadTerminalState): ThreadTerminalState {
const terminalIds = normalizeTerminalIds(state.terminalIds);
const nextTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const runningTerminalIds = normalizeRunningTerminalIds(state.runningTerminalIds, nextTerminalIds);
const activeTerminalId = nextTerminalIds.includes(state.activeTerminalId)
? state.activeTerminalId
: (nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
const terminalGroups = normalizeTerminalGroups(state.terminalGroups, nextTerminalIds);
const activeGroupIdFromState = terminalGroups.some((group) => group.id === state.activeTerminalGroupId)
? state.activeTerminalGroupId
: null;
const activeGroupIdFromTerminal =
terminalGroups.find((group) => group.terminalIds.includes(activeTerminalId))?.id ?? null;
const normalized: ThreadTerminalState = {
terminalOpen: state.terminalOpen,
terminalHeight:
Number.isFinite(state.terminalHeight) && state.terminalHeight > 0
? state.terminalHeight
: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: nextTerminalIds,
runningTerminalIds,
activeTerminalId,
terminalGroups,
activeTerminalGroupId:
activeGroupIdFromState ??
activeGroupIdFromTerminal ??
terminalGroups[0]?.id ??
fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
};
return threadTerminalStateEqual(state, normalized) ? state : normalized;
}
function isDefaultThreadTerminalState(state: ThreadTerminalState): boolean {
const normalized = normalizeThreadTerminalState(state);
return threadTerminalStateEqual(normalized, DEFAULT_THREAD_TERMINAL_STATE);
}
function isValidTerminalId(terminalId: string): boolean {
return terminalId.trim().length > 0;
}
function copyTerminalGroups(groups: ThreadTerminalGroup[]): ThreadTerminalGroup[] {
return groups.map((group) => ({
id: group.id,
terminalIds: [...group.terminalIds],
}));
}
function upsertTerminalIntoGroups(
state: ThreadTerminalState,
terminalId: string,
mode: "split" | "new",
): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!isValidTerminalId(terminalId)) {
return normalized;
}
const isNewTerminal = !normalized.terminalIds.includes(terminalId);
if (isNewTerminal && normalized.terminalIds.length >= MAX_THREAD_TERMINAL_COUNT) {
return normalized;
}
const terminalIds = isNewTerminal ? [...normalized.terminalIds, terminalId] : normalized.terminalIds;
const terminalGroups = copyTerminalGroups(normalized.terminalGroups);
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, terminalId);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[existingGroupIndex]!.terminalIds.filter(
(id) => id !== terminalId,
);
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
terminalGroups.splice(existingGroupIndex, 1);
}
}
if (mode === "new") {
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
const nextGroupId = assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds);
terminalGroups.push({ id: nextGroupId, terminalIds: [terminalId] });
return normalizeThreadTerminalState({
...normalized,
terminalOpen: true,
terminalIds,
activeTerminalId: terminalId,
terminalGroups,
activeTerminalGroupId: nextGroupId,
});
}
let activeGroupIndex = terminalGroups.findIndex((group) => group.id === normalized.activeTerminalGroupId);
if (activeGroupIndex < 0) {
activeGroupIndex = findGroupIndexByTerminalId(terminalGroups, normalized.activeTerminalId);
}
if (activeGroupIndex < 0) {
const usedGroupIds = new Set(terminalGroups.map((group) => group.id));
const nextGroupId = assignUniqueGroupId(fallbackGroupId(normalized.activeTerminalId), usedGroupIds);
terminalGroups.push({ id: nextGroupId, terminalIds: [normalized.activeTerminalId] });
activeGroupIndex = terminalGroups.length - 1;
}
const destinationGroup = terminalGroups[activeGroupIndex];
if (!destinationGroup) {
return normalized;
}
if (!destinationGroup.terminalIds.includes(terminalId)) {
const anchorIndex = destinationGroup.terminalIds.indexOf(normalized.activeTerminalId);
if (anchorIndex >= 0) {
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, terminalId);
} else {
destinationGroup.terminalIds.push(terminalId);
}
}
return normalizeThreadTerminalState({
...normalized,
terminalOpen: true,
terminalIds,
activeTerminalId: terminalId,
terminalGroups,
activeTerminalGroupId: destinationGroup.id,
});
}
function setThreadTerminalOpen(state: ThreadTerminalState, open: boolean): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (normalized.terminalOpen === open) return normalized;
return { ...normalized, terminalOpen: open };
}
function setThreadTerminalHeight(state: ThreadTerminalState, height: number): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!Number.isFinite(height) || height <= 0 || normalized.terminalHeight === height) {
return normalized;
}
return { ...normalized, terminalHeight: height };
}
function splitThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
return upsertTerminalIntoGroups(state, terminalId, "split");
}
function newThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
return upsertTerminalIntoGroups(state, terminalId, "new");
}
function setThreadActiveTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!normalized.terminalIds.includes(terminalId)) {
return normalized;
}
const activeTerminalGroupId =
normalized.terminalGroups.find((group) => group.terminalIds.includes(terminalId))?.id ??
normalized.activeTerminalGroupId;
if (
normalized.activeTerminalId === terminalId &&
normalized.activeTerminalGroupId === activeTerminalGroupId
) {
return normalized;
}
return {
...normalized,
activeTerminalId: terminalId,
activeTerminalGroupId,
};
}
function closeThreadTerminal(state: ThreadTerminalState, terminalId: string): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!normalized.terminalIds.includes(terminalId)) {
return normalized;
}
const remainingTerminalIds = normalized.terminalIds.filter((id) => id !== terminalId);
if (remainingTerminalIds.length === 0) {
return createDefaultThreadTerminalState();
}
const closedTerminalIndex = normalized.terminalIds.indexOf(terminalId);
const nextActiveTerminalId =
normalized.activeTerminalId === terminalId
? (remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
remainingTerminalIds[0] ??
DEFAULT_THREAD_TERMINAL_ID)
: normalized.activeTerminalId;
const terminalGroups = normalized.terminalGroups
.map((group) => ({
...group,
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
}))
.filter((group) => group.terminalIds.length > 0);
const nextActiveTerminalGroupId =
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
terminalGroups[0]?.id ??
fallbackGroupId(nextActiveTerminalId);
return normalizeThreadTerminalState({
terminalOpen: normalized.terminalOpen,
terminalHeight: normalized.terminalHeight,
terminalIds: remainingTerminalIds,
runningTerminalIds: normalized.runningTerminalIds.filter((id) => id !== terminalId),
activeTerminalId: nextActiveTerminalId,
terminalGroups,
activeTerminalGroupId: nextActiveTerminalGroupId,
});
}
function setThreadTerminalActivity(
state: ThreadTerminalState,
terminalId: string,
hasRunningSubprocess: boolean,
): ThreadTerminalState {
const normalized = normalizeThreadTerminalState(state);
if (!normalized.terminalIds.includes(terminalId)) {
return normalized;
}
const alreadyRunning = normalized.runningTerminalIds.includes(terminalId);
if (hasRunningSubprocess === alreadyRunning) {
return normalized;
}
const runningTerminalIds = new Set(normalized.runningTerminalIds);
if (hasRunningSubprocess) {
runningTerminalIds.add(terminalId);
} else {
runningTerminalIds.delete(terminalId);
}
return { ...normalized, runningTerminalIds: [...runningTerminalIds] };
}
export function selectThreadTerminalState(
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
threadId: ThreadId,
): ThreadTerminalState {
if (threadId.length === 0) {
return getDefaultThreadTerminalState();
}
return terminalStateByThreadId[threadId] ?? getDefaultThreadTerminalState();
}
function updateTerminalStateByThreadId(
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>,
threadId: ThreadId,
updater: (state: ThreadTerminalState) => ThreadTerminalState,
): Record<ThreadId, ThreadTerminalState> {
if (threadId.length === 0) {
return terminalStateByThreadId;
}
const current = selectThreadTerminalState(terminalStateByThreadId, threadId);
const next = updater(current);
if (next === current) {
return terminalStateByThreadId;
}
if (isDefaultThreadTerminalState(next)) {
if (terminalStateByThreadId[threadId] === undefined) {
return terminalStateByThreadId;
}
const { [threadId]: _removed, ...rest } = terminalStateByThreadId;
return rest as Record<ThreadId, ThreadTerminalState>;
}
return {
...terminalStateByThreadId,
[threadId]: next,
};
}
interface TerminalStateStoreState {
terminalStateByThreadId: Record<ThreadId, ThreadTerminalState>;
setTerminalOpen: (threadId: ThreadId, open: boolean) => void;
setTerminalHeight: (threadId: ThreadId, height: number) => void;
splitTerminal: (threadId: ThreadId, terminalId: string) => void;
newTerminal: (threadId: ThreadId, terminalId: string) => void;
setActiveTerminal: (threadId: ThreadId, terminalId: string) => void;
closeTerminal: (threadId: ThreadId, terminalId: string) => void;
setTerminalActivity: (
threadId: ThreadId,
terminalId: string,
hasRunningSubprocess: boolean,
) => void;
clearTerminalState: (threadId: ThreadId) => void;
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
}
export const useTerminalStateStore = create<TerminalStateStoreState>()(
persist(
(set) => {
const updateTerminal = (
threadId: ThreadId,
updater: (state: ThreadTerminalState) => ThreadTerminalState,
) => {
set((state) => {
const nextTerminalStateByThreadId = updateTerminalStateByThreadId(
state.terminalStateByThreadId,
threadId,
updater,
);
if (nextTerminalStateByThreadId === state.terminalStateByThreadId) {
return state;
}
return {
terminalStateByThreadId: nextTerminalStateByThreadId,
};
});
};
return {
terminalStateByThreadId: {},
setTerminalOpen: (threadId, open) =>
updateTerminal(threadId, (state) => setThreadTerminalOpen(state, open)),
setTerminalHeight: (threadId, height) =>
updateTerminal(threadId, (state) => setThreadTerminalHeight(state, height)),
splitTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => splitThreadTerminal(state, terminalId)),
newTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => newThreadTerminal(state, terminalId)),
setActiveTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => setThreadActiveTerminal(state, terminalId)),
closeTerminal: (threadId, terminalId) =>
updateTerminal(threadId, (state) => closeThreadTerminal(state, terminalId)),
setTerminalActivity: (threadId, terminalId, hasRunningSubprocess) =>
updateTerminal(threadId, (state) =>
setThreadTerminalActivity(state, terminalId, hasRunningSubprocess),
),
clearTerminalState: (threadId) =>
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
removeOrphanedTerminalStates: (activeThreadIds) =>
set((state) => {
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
(id) => !activeThreadIds.has(id as ThreadId),
);
if (orphanedIds.length === 0) return state;
const next = { ...state.terminalStateByThreadId };
for (const id of orphanedIds) {
delete next[id as ThreadId];
}
return { terminalStateByThreadId: next };
}),
};
},
{
name: TERMINAL_STATE_STORAGE_KEY,
version: 1,
storage: createJSONStorage(() => localStorage),
partialize: (state) => ({
terminalStateByThreadId: state.terminalStateByThreadId,
}),
},
),
);
+7
View File
@@ -79,6 +79,13 @@ export interface Thread {
projectId: ProjectId;
title: string;
model: string;
terminalOpen: boolean;
terminalHeight: number;
terminalIds: string[];
runningTerminalIds: string[];
activeTerminalId: string;
terminalGroups: ThreadTerminalGroup[];
activeTerminalGroupId: string;
session: ThreadSession | null;
messages: ChatMessage[];
error: string | null;
+13 -1
View File
@@ -1,7 +1,7 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import type { Thread } from "./types";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -11,6 +11,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
model: "gpt-5.3-codex",
terminalOpen: false,
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
runningTerminalIds: [],
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
terminalGroups: [
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
},
],
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
session: null,
messages: [],
turnDiffSummaries: [],
-70
View File
@@ -1,6 +1,5 @@
import {
CommandId,
type ContextMenuItem,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
ProjectId,
@@ -10,12 +9,6 @@ import {
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const requestMock = vi.fn<(...args: Array<unknown>) => Promise<unknown>>();
const showContextMenuFallbackMock = vi.fn<
<T extends string>(
items: readonly ContextMenuItem<T>[],
position?: { x: number; y: number },
) => Promise<T | null>
>();
const channelListeners = new Map<string, Set<(data: unknown) => void>>();
const subscribeMock = vi.fn<(channel: string, listener: (data: unknown) => void) => () => void>(
(channel, listener) => {
@@ -40,10 +33,6 @@ vi.mock("./wsTransport", () => {
};
});
vi.mock("./contextMenuFallback", () => ({
showContextMenuFallback: showContextMenuFallbackMock,
}));
function emitPush(channel: string, data: unknown): void {
const listeners = channelListeners.get(channel);
if (!listeners) return;
@@ -52,23 +41,11 @@ function emitPush(channel: string, data: unknown): void {
}
}
function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unknown } {
const testGlobal = globalThis as typeof globalThis & {
window?: Window & typeof globalThis & { desktopBridge?: unknown };
};
if (!testGlobal.window) {
testGlobal.window = {} as Window & typeof globalThis & { desktopBridge?: unknown };
}
return testGlobal.window;
}
beforeEach(() => {
vi.resetModules();
requestMock.mockReset();
showContextMenuFallbackMock.mockReset();
subscribeMock.mockClear();
channelListeners.clear();
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
});
afterEach(() => {
@@ -330,51 +307,4 @@ describe("wsNativeApi", () => {
toTurnCount: 1,
});
});
it("forwards context menu metadata to desktop bridge", async () => {
const showContextMenu = vi.fn().mockResolvedValue("delete");
Object.defineProperty(getWindowForTest(), "desktopBridge", {
configurable: true,
writable: true,
value: {
showContextMenu,
},
});
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
await api.contextMenu.show(
[
{ id: "rename", label: "Rename thread" },
{ id: "delete", label: "Delete", destructive: true },
],
{ x: 200, y: 300 },
);
expect(showContextMenu).toHaveBeenCalledWith(
[
{ id: "rename", label: "Rename thread" },
{ id: "delete", label: "Delete", destructive: true },
],
{ x: 200, y: 300 },
);
});
it("uses fallback context menu when desktop bridge is unavailable", async () => {
showContextMenuFallbackMock.mockResolvedValue("delete");
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
await api.contextMenu.show(
[{ id: "delete", label: "Delete", destructive: true }],
{ x: 20, y: 30 },
);
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(
[{ id: "delete", label: "Delete", destructive: true }],
{ x: 20, y: 30 },
);
});
});
+6 -6
View File
@@ -2,7 +2,6 @@ import {
OrchestrationEvent,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
type ContextMenuItem,
type NativeApi,
ServerConfigUpdatedPayload,
TerminalEvent,
@@ -154,9 +153,10 @@ export function createWsNativeApi(): NativeApi {
return;
}
// Some mobile browsers can return null here even when the tab opens.
// Avoid false negatives and let the browser handle popup policy.
window.open(url, "_blank", "noopener,noreferrer");
const popup = window.open(url, "_blank", "noopener,noreferrer");
if (!popup) {
throw new Error("Unable to open link. Allow popups and try again.");
}
},
},
git: {
@@ -172,11 +172,11 @@ export function createWsNativeApi(): NativeApi {
},
contextMenu: {
show: async <T extends string>(
items: readonly ContextMenuItem<T>[],
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
): Promise<T | null> => {
if (window.desktopBridge) {
return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
return window.desktopBridge.showContextMenu(items) as Promise<T | null>;
}
return showContextMenuFallback(items, position);
},
+23 -103
View File
@@ -5,9 +5,6 @@
"": {
"name": "@t3tools/monorepo",
"devDependencies": {
"@effect/platform-node": "catalog:",
"@types/node": "^24.10.13",
"effect": "catalog:",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"turbo": "^2.3.3",
@@ -17,13 +14,13 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"dependencies": {
"electron": "40.6.0",
},
"devDependencies": {
"@t3tools/contracts": "workspace:*",
"@types/node": "^24.10.13",
"@types/node": "^22.10.2",
"electronmon": "^2.0.2",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
@@ -33,7 +30,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.0-alpha.4",
"version": "0.1.0",
"bin": {
"t3": "./dist/index.mjs",
},
@@ -52,7 +49,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/web": "workspace:*",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"@types/node": "^22.10.2",
"@types/ws": "^8.5.13",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
@@ -61,10 +58,9 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"dependencies": {
"@base-ui/react": "^1.2.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-pacer": "^0.19.4",
@@ -75,14 +71,12 @@
"@xterm/xterm": "^6.0.0",
"class-variance-authority": "^0.7.1",
"effect": "catalog:",
"lexical": "^0.41.0",
"lucide-react": "^0.564.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.4.0",
"zustand": "^5.0.11",
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -99,7 +93,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"dependencies": {
"effect": "catalog:",
},
@@ -113,10 +107,10 @@
},
"catalog": {
"@effect/language-service": "0.75.1",
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738",
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738",
},
"packages": {
"@babel/code-frame": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw=="],
@@ -169,13 +163,13 @@
"@effect/language-service": ["@effect/[email protected]", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-g9xD2tAQgRFpYC2YgpZq02VeSL5fBbFJ0B/g1o+14NuNmwtaYJc7SjiLWAA9eyhJHosNrn6h1Ye+Kx6j5mN0AA=="],
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25", "ioredis": "^5.7.0" } }],
"@effect/platform-node": ["@effect/platform-node@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738", { "dependencies": { "@effect/platform-node-shared": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@f59173885df0eb490dc2e6619ae89467feac0413", "mime": "^4.1.0", "undici": "^7.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.19", "ioredis": "^5.7.0" } }],
"@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@8881a9b606d84a6f5eb6615279138322984f5368", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.25" } }],
"@effect/platform-node-shared": ["@effect/platform-node-shared@https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node-shared@f59173885df0eb490dc2e6619ae89467feac0413", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.19" } }],
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25" } }],
"@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738", { "peerDependencies": { "effect": "^4.0.0-beta.19" } }],
"@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b", { "peerDependencies": { "effect": "^4.0.0-beta.25", "vitest": "^3.0.0 || ^4.0.0" } }],
"@effect/vitest": ["@effect/vitest@https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738", { "peerDependencies": { "effect": "^4.0.0-beta.19", "vitest": "^3.0.0" } }],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
@@ -241,8 +235,6 @@
"@floating-ui/dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/core": "^1.7.4", "@floating-ui/utils": "^0.2.10" } }, "sha512-N0bD2kIPInNHUHehXhMke1rBGs1dwqvC9O9KYMyyjK7iXt7GAhnro7UlcuYcGdS/yYOlq0MAVgrow8IbWJwyqg=="],
"@floating-ui/react": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/react-dom": "^2.1.7", "@floating-ui/utils": "^0.2.10", "tabbable": "^6.0.0" }, "peerDependencies": { "react": ">=17.0.0", "react-dom": ">=17.0.0" } }, "sha512-xJWJxvmy3a05j643gQt+pRbht5XnTlGpsEsAPnMi5F5YTOEEJymA90uZKBD8OvIv5XvZ1qi4GcccSlqT3Bq44Q=="],
"@floating-ui/react-dom": ["@floating-ui/[email protected]", "", { "dependencies": { "@floating-ui/dom": "^1.7.5" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-0tLRojf/1Go2JgEVm+3Frg9A3IW8bJgKgdO0BN5RkF//ufuz2joZM63Npau2ff3J6lUVYgDSNzNkR+aH3IVfjg=="],
"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="],
@@ -281,50 +273,6 @@
"@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@lexical/clipboard": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/html": "0.41.0", "@lexical/list": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-Ex5lPkb4NBBX1DCPzOAIeHBJFH1bJcmATjREaqpnTfxCbuOeQkt44wchezUA0oDl+iAxNZ3+pLLWiUju9icoSA=="],
"@lexical/code": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "lexical": "0.41.0", "prismjs": "^1.30.0" } }, "sha512-0hoNi1KC9/N3SBOGcOcFqnT0OpwmcRRAhfxTKMGqfCtCvAMzULVwZ8RWc9/NV9bKYESgBTW5D9xkDANP2mspHg=="],
"@lexical/devtools-core": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/html": "0.41.0", "@lexical/link": "0.41.0", "@lexical/mark": "0.41.0", "@lexical/table": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" }, "peerDependencies": { "react": ">=17.x", "react-dom": ">=17.x" } }, "sha512-FzJtluBhBc8bKS11TUZe72KoZN/hnzIyiiM0SPJAsPwGpoXuM01jqpXQGybWf/1bWB+bmmhOae7O4Nywi/Csuw=="],
"@lexical/dragon": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "lexical": "0.41.0" } }, "sha512-gBEqkk8Q6ZPruvDaRcOdF1EK9suCVBODzOCcR+EnoJTaTjfDkCM7pkPAm4w90Wa1wCZEtFHvCfas+jU9MDSumg=="],
"@lexical/extension": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "@preact/signals-core": "^1.11.0", "lexical": "0.41.0" } }, "sha512-sF4SPiP72yXvIGchmmIZ7Yg2XZTxNLOpFEIIzdqG7X/1fa1Ham9P/T7VbrblWpF6Ei5LJtK9JgNVB0hb4l3o1g=="],
"@lexical/hashtag": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/text": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-tFWM74RW4KU0E/sj2aowfWl26vmLUTp331CgVESnhQKcZBfT40KJYd57HEqBDTfQKn4MUhylQCCA0hbpw6EeFQ=="],
"@lexical/history": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-kGoVWsiOn62+RMjRolRa+NXZl8jFwxav6GNDiHH8yzivtoaH8n1SwUfLJELXCzeqzs81HySqD4q30VLJVTGoDg=="],
"@lexical/html": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-3RyZy+H/IDKz2D66rNN/NqYx87xVFrngfEbyu1OWtbY963RUFnopiVHCQvsge/8kT04QSZ7U/DzjVFqeNS6clg=="],
"@lexical/link": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-Rjtx5cGWAkKcnacncbVsZ1TqRnUB2Wm4eEVKpaAEG41+kHgqghzM2P+UGT15yROroxJu8KvAC9ISiYFiU4XE1w=="],
"@lexical/list": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/extension": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-RXvB+xcbzVoQLGRDOBRCacztG7V+bI95tdoTwl8pz5xvgPtAaRnkZWMDP+yMNzMJZsqEChdtpxbf0NgtMkun6g=="],
"@lexical/mark": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-UO5WVs9uJAYIKHSlYh4Z1gHrBBchTOi21UCYBIZ7eAs4suK84hPzD+3/LAX5CB7ZltL6ke5Sly3FOwNXv/wfpA=="],
"@lexical/markdown": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/code": "0.41.0", "@lexical/link": "0.41.0", "@lexical/list": "0.41.0", "@lexical/rich-text": "0.41.0", "@lexical/text": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-bzI73JMXpjGFhqUWNV6KqfjWcgAWzwFT+J3RHtbCF5rysC8HLldBYojOgAAtPfXqfxyv2mDzsY7SoJ75s9uHZA=="],
"@lexical/offset": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-2RHBXZqC8gm3X9C0AyRb0M8w7zJu5dKiasrif+jSKzsxPjAUeF1m95OtIOsWs1XLNUgASOSUqGovDZxKJslZfA=="],
"@lexical/overflow": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-Iy6ZiJip8X14EBYt1zKPOrXyQ4eG9JLBEoPoSVBTiSbVd+lYicdUvaOThT0k0/qeVTN9nqTaEltBjm56IrVKCQ=="],
"@lexical/plain-text": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/dragon": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-HIsGgmFUYRUNNyvckun33UQfU7LRzDlxymHUq67+Bxd5bXqdZOrStEKJXuDX+LuLh/GXZbaWNbDLqwLBObfbQg=="],
"@lexical/react": ["@lexical/[email protected]", "", { "dependencies": { "@floating-ui/react": "^0.27.16", "@lexical/devtools-core": "0.41.0", "@lexical/dragon": "0.41.0", "@lexical/extension": "0.41.0", "@lexical/hashtag": "0.41.0", "@lexical/history": "0.41.0", "@lexical/link": "0.41.0", "@lexical/list": "0.41.0", "@lexical/mark": "0.41.0", "@lexical/markdown": "0.41.0", "@lexical/overflow": "0.41.0", "@lexical/plain-text": "0.41.0", "@lexical/rich-text": "0.41.0", "@lexical/table": "0.41.0", "@lexical/text": "0.41.0", "@lexical/utils": "0.41.0", "@lexical/yjs": "0.41.0", "lexical": "0.41.0", "react-error-boundary": "^6.0.0" }, "peerDependencies": { "react": ">=17.x", "react-dom": ">=17.x" } }, "sha512-7+GUdZUm6sofWm+zdsWAs6cFBwKNsvsHezZTrf6k8jrZxL461ZQmbz/16b4DvjCGL9r5P1fR7md9/LCmk8TiCg=="],
"@lexical/rich-text": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/dragon": "0.41.0", "@lexical/selection": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-yUcr7ZaaVTZNi8bow4CK1M8jy2qyyls1Vr+5dVjwBclVShOL/F/nFyzBOSb6RtXXRbd3Ahuk9fEleppX/RNIdw=="],
"@lexical/selection": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-1s7/kNyRzcv5uaTwsUL28NpiisqTf5xZ1zNukLsCN1xY+TWbv9RE9OxIv+748wMm4pxNczQe/UbIBODkbeknLw=="],
"@lexical/table": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/clipboard": "0.41.0", "@lexical/extension": "0.41.0", "@lexical/utils": "0.41.0", "lexical": "0.41.0" } }, "sha512-d3SPThBAr+oZ8O74TXU0iXM3rLbrAVC7/HcOnSAq7/AhWQW8yMutT51JQGN+0fMLP9kqoWSAojNtkdvzXfU/+A=="],
"@lexical/text": ["@lexical/[email protected]", "", { "dependencies": { "lexical": "0.41.0" } }, "sha512-gGA+Anc7ck110EXo4KVKtq6Ui3M7Vz3OpGJ4QE6zJHWW8nV5h273koUGSutAMeoZgRVb6t01Izh3ORoFt/j1CA=="],
"@lexical/utils": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/selection": "0.41.0", "lexical": "0.41.0" } }, "sha512-Wlsokr5NQCq83D+7kxZ9qs5yQ3dU3Qaf2M+uXxLRoPoDaXqW8xTWZq1+ZFoEzsHzx06QoPa4Vu/40BZR91uQPg=="],
"@lexical/yjs": ["@lexical/[email protected]", "", { "dependencies": { "@lexical/offset": "0.41.0", "@lexical/selection": "0.41.0", "lexical": "0.41.0" }, "peerDependencies": { "yjs": ">=13.5.22" } }, "sha512-PaKTxSbVC4fpqUjQ7vUL9RkNF1PjL8TFl5jRe03PqoPYpE33buf3VXX6+cOUEfv9+uknSqLCPHoBS/4jN3a97w=="],
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
@@ -429,8 +377,6 @@
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-McjTuEPuacSIcXdoI2O9W6VSHIOs9ApEHnEUwONKZnKqIo2GGv1vNg9Pr8tgBOL7lgBWNEHX5ROJ5z1X74sENQ=="],
"@preact/signals-core": ["@preact/[email protected]", "", {}, "sha512-slT6XeTCAbdql61GVLlGU4x7XHI7kCZV5Um5uhE4zLX4ApgiiXc0UYFvVOKq06xcovzp7p+61l68oPi563ARKg=="],
"@quansync/fs": ["@quansync/[email protected]", "", { "dependencies": { "quansync": "^1.0.0" } }, "sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ=="],
"@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-0T1k9FinuBZ/t7rZ8jN6OpUKPnUjNdYHoj/cESWrQ3ZraAJ4OMm6z7QjSfCxqj8mOp9kTKc1zHK3kGz5vMu+nQ=="],
@@ -637,7 +583,7 @@
"@types/ms": ["@types/[email protected]", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="],
"@types/node": ["@types/node@24.10.13", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
"@types/node": ["@types/node@22.19.11", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
@@ -811,7 +757,7 @@
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }],
"effect": ["effect@https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
@@ -973,8 +919,6 @@
"isbot": ["[email protected]", "", {}, "sha512-waFfC72ZNfwLLuJ2iLaoVaqcNo+CAaLR7xCpAn0Y5WfGzkNHv7ZN39Vbi1y+kb+Zs46XHOX3tZNExroFUPX+Kg=="],
"isomorphic.js": ["[email protected]", "", {}, "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw=="],
"jiti": ["[email protected]", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
"joi": ["[email protected]", "", { "dependencies": { "@hapi/address": "^5.1.1", "@hapi/formula": "^3.0.2", "@hapi/hoek": "^11.0.7", "@hapi/pinpoint": "^2.0.1", "@hapi/tlds": "^1.1.1", "@hapi/topo": "^6.0.2", "@standard-schema/spec": "^1.0.0" } }, "sha512-RuCOQMIt78LWnktPoeBL0GErkNaJPTBGcYuyaBvUOQSpcpcLfWrHPPihYdOGbV5pam9VTWbeoF7TsGiHugcjGA=="],
@@ -995,10 +939,6 @@
"kubernetes-types": ["[email protected]", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
"lexical": ["[email protected]", "", {}, "sha512-pNIm5+n+hVnJHB9gYPDYsIO5Y59dNaDU9rJmPPsfqQhP2ojKFnUoPbcRnrI9FJLXB14sSumcY8LUw7Sq70TZqA=="],
"lib0": ["[email protected]", "", { "dependencies": { "isomorphic.js": "^0.2.4" }, "bin": { "0serve": "bin/0serve.js", "0gentesthtml": "bin/gentesthtml.js", "0ecdsa-generate-keypair": "bin/0ecdsa-generate-keypair.js" } }, "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw=="],
"lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.31.1", "lightningcss-darwin-arm64": "1.31.1", "lightningcss-darwin-x64": "1.31.1", "lightningcss-freebsd-x64": "1.31.1", "lightningcss-linux-arm-gnueabihf": "1.31.1", "lightningcss-linux-arm64-gnu": "1.31.1", "lightningcss-linux-arm64-musl": "1.31.1", "lightningcss-linux-x64-gnu": "1.31.1", "lightningcss-linux-x64-musl": "1.31.1", "lightningcss-win32-arm64-msvc": "1.31.1", "lightningcss-win32-x64-msvc": "1.31.1" } }, "sha512-l51N2r93WmGUye3WuFoN5k10zyvrVs0qfKBhyC5ogUQ6Ew6JUSswh78mbSO+IU3nTWsyOArqPCcShdQSadghBQ=="],
"lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-HXJF3x8w9nQ4jbXRiNppBCqeZPIAfUo8zE/kOEGbW5NZvGc/K7nMxbhIr+YlFlHW5mpbg/YFPdbnCh1wAXCKFg=="],
@@ -1211,8 +1151,6 @@
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
"prismjs": ["[email protected]", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="],
"progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],
"property-information": ["[email protected]", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
@@ -1231,8 +1169,6 @@
"react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ=="],
"react-error-boundary": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0" } }, "sha512-BrYwPOdXi5mqkk5lw+Uvt0ThHx32rCt3BkukS4X23A2AIWDPSGX6iaWTc0y9TU/mHDA/6qOSGel+B2ERkOvD1w=="],
"react-markdown": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "html-url-attributes": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "unified": "^11.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="],
"react-refresh": ["[email protected]", "", {}, "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw=="],
@@ -1409,7 +1345,7 @@
"undici": ["[email protected]", "", {}, "sha512-RqslV2Us5BrllB+JeiZnK4peryVTndy9Dnqq62S3yYRRTj0tFQCwEniUy2167skdGOy3vqRzEvl1Dm4sV2ReDg=="],
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"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=="],
@@ -1475,14 +1411,10 @@
"yauzl": ["[email protected]", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"yjs": ["[email protected]", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-kHqDPdltoXH+X4w1lVmMtddE3Oeqq48nM40FD5ojTd8xYhQpzIDcfE2keMSU5bAgRPJBe225WTUdyUgj1DtbiQ=="],
"yoctocolors-cjs": ["[email protected]", "", {}, "sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw=="],
"zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg=="],
"zwitch": ["[email protected]", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
"@babel/code-frame/@babel/helper-validator-identifier": ["@babel/[email protected]", "", {}, "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q=="],
@@ -1535,26 +1467,20 @@
"@types/babel__template/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
"@types/cacheable-request/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/keyv/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/responselike/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/ws/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@types/yauzl/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w=="],
"@vitejs/plugin-react/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA=="],
"anymatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
"babel-dead-code-elimination/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww=="],
"bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
"cliui/wrap-ansi": ["[email protected]", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"clone-response/mimic-response": ["[email protected]", "", {}, "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ=="],
"electron/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg=="],
"mdast-util-find-and-replace/escape-string-regexp": ["[email protected]", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"micromatch/picomatch": ["[email protected]", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
@@ -1599,15 +1525,9 @@
"@tailwindcss/node/lightningcss/lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw=="],
"@types/cacheable-request/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"bun-types/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"@types/keyv/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/responselike/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/ws/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"@types/yauzl/@types/node/undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"electron/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"rolldown-plugin-dts/@babel/types/@babel/helper-string-parser": ["@babel/[email protected]", "", {}, "sha512-vi/pfmbrOtQmqgfboaBhaCU50G7mcySVu69VU8z+lYoPPB6WzI9VgV7WQfL908M4oeSH5fDkmoupIqoE0SdApw=="],
}
-125
View File
@@ -1,125 +0,0 @@
# Release Checklist
This document covers how to run desktop releases from one tag, first without signing, then with signing.
## What the workflow does
- Trigger: push tag matching `v*.*.*`.
- Runs quality gates first: lint, typecheck, test.
- Builds four artifacts in parallel:
- macOS `arm64` DMG
- macOS `x64` DMG
- Linux `x64` AppImage
- Windows `x64` NSIS installer
- Publishes one GitHub Release with all produced files.
- Publishes the CLI package (`apps/server`, npm package `t3`) with OIDC trusted publishing.
- Signing is optional and auto-detected per platform from secrets.
## 0) npm OIDC trusted publishing setup (CLI)
The workflow publishes the CLI with `bun publish` from `apps/server` after bumping
the package version to the release tag version.
Checklist:
1. Confirm npm org/user owns package `t3` (or rename package first if needed).
2. In npm package settings, configure Trusted Publisher:
- Provider: GitHub Actions
- Repository: this repo
- Workflow file: `.github/workflows/release.yml`
- Environment (if used): match your npm trusted publishing config
3. Ensure npm account and org policies allow trusted publishing for the package.
4. Create release tag `vX.Y.Z` and push; workflow will:
- set `apps/server/package.json` version to `X.Y.Z`
- build web + server
- run `bun publish --access public`
## 1) Dry-run release without signing
Use this first to validate the release pipeline.
1. Confirm no signing secrets are required for this test.
2. Create a test tag:
- `git tag v0.0.0-test.1`
- `git push origin v0.0.0-test.1`
3. Wait for `.github/workflows/release.yml` to finish.
4. Verify the GitHub Release contains all platform artifacts.
5. Download each artifact and sanity-check installation on each OS.
## 2) Apple signing + notarization setup (macOS)
Required secrets used by the workflow:
- `CSC_LINK`
- `CSC_KEY_PASSWORD`
- `APPLE_API_KEY`
- `APPLE_API_KEY_ID`
- `APPLE_API_ISSUER`
Checklist:
1. Apple Developer account access:
- Team has rights to create Developer ID certificates.
2. Create `Developer ID Application` certificate.
3. Export certificate + private key as `.p12` from Keychain.
4. Base64-encode the `.p12` and store as `CSC_LINK`.
5. Store the `.p12` export password as `CSC_KEY_PASSWORD`.
6. In App Store Connect, create an API key (Team key).
7. Add API key values:
- `APPLE_API_KEY`: contents of the downloaded `.p8`
- `APPLE_API_KEY_ID`: Key ID
- `APPLE_API_ISSUER`: Issuer ID
8. Re-run a tag release and confirm macOS artifacts are signed/notarized.
Notes:
- `APPLE_API_KEY` is stored as raw key text in secrets.
- The workflow writes it to a temporary `AuthKey_<id>.p8` file at runtime.
## 3) Azure Trusted Signing setup (Windows)
Required secrets used by the workflow:
- `AZURE_TENANT_ID`
- `AZURE_CLIENT_ID`
- `AZURE_CLIENT_SECRET`
- `AZURE_TRUSTED_SIGNING_ENDPOINT`
- `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`
- `AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`
- `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`
Checklist:
1. Create Azure Trusted Signing account and certificate profile.
2. Record ATS values:
- Endpoint
- Account name
- Certificate profile name
- Publisher name
3. Create/choose an Entra app registration (service principal).
4. Grant service principal permissions required by Trusted Signing.
5. Create a client secret for the service principal.
6. Add Azure secrets listed above in GitHub Actions secrets.
7. Re-run a tag release and confirm Windows installer is signed.
## 4) Ongoing release checklist
1. Ensure `main` is green in CI.
2. Bump app version as needed.
3. Create release tag: `vX.Y.Z`.
4. Push tag.
5. Verify workflow steps:
- preflight passes
- all matrix builds pass
- release job uploads expected files
6. Smoke test downloaded artifacts.
## 5) Troubleshooting
- macOS build unsigned when expected signed:
- Check all Apple secrets are populated and non-empty.
- Windows build unsigned when expected signed:
- Check all Azure ATS and auth secrets are populated and non-empty.
- Build fails with signing error:
- Retry with secrets removed to confirm unsigned path still works.
- Re-check certificate/profile names and tenant/client credentials.
+7 -14
View File
@@ -7,14 +7,13 @@
"packages/*"
],
"catalog": {
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@8881a9b",
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@8881a9b",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@8881a9b",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@8881a9b",
"effect": "https://pkg.pr.new/Effect-TS/effect-smol/effect@f591738",
"@effect/platform-node": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/platform-node@f591738",
"@effect/sql-sqlite-bun": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/sql-sqlite-bun@f591738",
"@effect/vitest": "https://pkg.pr.new/Effect-TS/effect-smol/@effect/vitest@f591738",
"@effect/language-service": "0.75.1"
}
},
"type": "module",
"scripts": {
"dev": "bun run scripts/dev-runner.mjs dev",
"dev:server": "bun run scripts/dev-runner.mjs dev:server",
@@ -30,19 +29,13 @@
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
"fmt": "oxfmt",
"build:contracts": "turbo run build --filter=@t3tools/contracts",
"dist:desktop:artifact": "node scripts/build-desktop-artifact.ts",
"dist:desktop:dmg": "node scripts/build-desktop-artifact.ts --platform mac --target dmg",
"dist:desktop:dmg:arm64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch arm64",
"dist:desktop:dmg:x64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch x64",
"dist:desktop:linux": "node scripts/build-desktop-artifact.ts --platform linux --target AppImage --arch x64",
"dist:desktop:win": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64",
"dist:desktop:dmg": "node scripts/build-desktop-dmg.mjs",
"dist:desktop:dmg:arm64": "node scripts/build-desktop-dmg.mjs --arch arm64",
"dist:desktop:dmg:x64": "node scripts/build-desktop-dmg.mjs --arch x64",
"clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .turbo apps/*/.turbo packages/*/.turbo",
"sync:vscode-icons": "node scripts/sync-vscode-icons.mjs"
},
"devDependencies": {
"@effect/platform-node": "catalog:",
"@types/node": "^24.10.13",
"effect": "catalog:",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"turbo": "^2.3.3",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/contracts",
"version": "0.0.0-alpha.4",
"version": "0.0.0",
"private": true,
"files": [
"dist"
-2
View File
@@ -3,8 +3,6 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
export const EDITORS = [
{ id: "cursor", label: "Cursor", command: "cursor" },
{ id: "vscode", label: "VS Code", command: "code" },
{ id: "zed", label: "Zed", command: "zed" },
{ id: "file-manager", label: "File Manager", command: null },
] as const;
-2
View File
@@ -23,8 +23,6 @@ export type GitStatusPrState = typeof GitStatusPrState.Type;
export const GitBranch = Schema.Struct({
name: TrimmedNonEmptyStringSchema,
isRemote: Schema.optional(Schema.Boolean),
remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
current: Schema.Boolean,
isDefault: Schema.Boolean,
worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),
+2 -8
View File
@@ -37,18 +37,12 @@ import type {
} from "./orchestration";
import { EditorId } from "./editor";
export interface ContextMenuItem<T extends string = string> {
id: T;
label: string;
destructive?: boolean;
}
export interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
showContextMenu: <T extends string>(
items: readonly ContextMenuItem<T>[],
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
) => Promise<T | null>;
openExternal: (url: string) => Promise<boolean>;
@@ -91,7 +85,7 @@ export interface NativeApi {
};
contextMenu: {
show: <T extends string>(
items: readonly ContextMenuItem<T>[],
items: readonly { id: T; label: string }[],
position?: { x: number; y: number },
) => Promise<T | null>;
};
-2
View File
@@ -1,7 +1,6 @@
import { Schema } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas";
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
import { EditorId } from "./editor";
export const KeybindingsMalformedConfigIssue = Schema.Struct({
kind: Schema.Literal("keybindings.malformed-config"),
@@ -30,7 +29,6 @@ export const ServerConfig = Schema.Struct({
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
issues: ServerConfigIssues,
availableEditors: Schema.Array(EditorId),
});
export type ServerConfig = typeof ServerConfig.Type;
-655
View File
@@ -1,655 +0,0 @@
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
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;
}> {}
function resolveGitCommitHash(repoRoot: string): string {
const result = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], {
cwd: repoRoot,
encoding: "utf8",
});
if (result.status !== 0) {
return "unknown";
}
const hash = result.stdout.trim();
if (!/^[0-9a-f]{7,40}$/i.test(hash)) {
return "unknown";
}
return hash.toLowerCase();
}
interface ResolvedBuildOptions {
readonly platform: typeof BuildPlatform.Type;
readonly target: string;
readonly arch: typeof BuildArch.Type;
readonly version: string | undefined;
readonly outputDir: string;
readonly skipBuild: boolean;
readonly keepStage: boolean;
readonly signed: boolean;
readonly verbose: boolean;
}
interface StagePackageJson {
readonly name: string;
readonly version: string;
readonly buildVersion: string;
readonly t3codeCommitHash: string;
readonly private: true;
readonly description: string;
readonly author: string;
readonly main: string;
readonly build: Record<string, unknown>;
readonly dependencies: Record<string, unknown>;
readonly devDependencies: {
readonly electron: string;
};
}
const AzureTrustedSigningOptionsConfig = Config.all({
publisherName: Config.string("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(
Config.withDefault(() => "SHA256"),
),
timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
Config.withDefault(() => "SHA256"),
),
timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
Config.withDefault(() => "http://timestamp.acs.microsoft.com"),
),
});
const BuildEnvConfig = Config.all({
platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
target: Config.string("T3CODE_DESKTOP_TARGET").pipe(Config.option),
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(() => false)),
keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(() => false)),
signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(() => false)),
verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(() => false)),
});
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
const resolveBuildOptions = Effect.fn(function* (input: BuildCliInput) {
const path = yield* Path.Path;
const repoRoot = yield* RepoRoot;
const env = yield* BuildEnvConfig.asEffect();
const platform = mergeOptions(
input.platform,
env.platform,
detectHostBuildPlatform(process.platform),
);
if (!platform) {
return yield* new BuildScriptError({
message: `Unsupported host platform '${process.platform}'.`,
});
}
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform));
const version = mergeOptions(input.buildVersion, env.version, undefined);
const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release"));
const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
const signed = resolveBooleanFlag(input.signed, env.signed);
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
return {
platform,
target,
arch,
version,
outputDir,
skipBuild,
keepStage,
signed,
verbose,
} satisfies ResolvedBuildOptions;
});
const commandOutputOptions = (verbose: boolean) =>
({
stdout: verbose ? "inherit" : "ignore",
stderr: "inherit",
}) as const;
const runCommand = Effect.fn(function* (command: ChildProcess.Command) {
const exitCode = yield* ChildProcess.exitCode(command);
if (exitCode !== 0) {
return yield* new BuildScriptError({
message: "Command exited with non-zero exit code",
});
}
});
function generateMacIconSet(
sourcePng: string,
targetIcns: string,
tmpRoot: string,
path: Path.Path,
verbose: boolean,
) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const iconsetDir = path.join(tmpRoot, "icon.iconset");
yield* fs.makeDirectory(iconsetDir, { recursive: true });
const iconSizes = [16, 32, 128, 256, 512] as const;
for (const size of iconSizes) {
yield* runCommand(
ChildProcess.make({
...commandOutputOptions(verbose),
})`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
);
const retinaSize = size * 2;
yield* runCommand(
ChildProcess.make({
...commandOutputOptions(verbose),
})`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
);
}
yield* runCommand(
ChildProcess.make({
...commandOutputOptions(verbose),
})`iconutil -c icns ${iconsetDir} -o ${targetIcns}`,
);
});
}
function stageMacIcons(stageResourcesDir: string, verbose: boolean) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const iconSource = yield* IconSource;
if (!(yield* fs.exists(iconSource))) {
return yield* new BuildScriptError({
message: `Production icon source is missing at ${iconSource}`,
});
}
const tmpRoot = yield* fs.makeTempDirectoryScoped({
prefix: "t3code-icon-build-",
});
const iconPngPath = path.join(stageResourcesDir, "icon.png");
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
yield* runCommand(
ChildProcess.make({
...commandOutputOptions(verbose),
})`sips -z 512 512 ${iconSource} --out ${iconPngPath}`,
);
yield* generateMacIconSet(iconSource, iconIcnsPath, tmpRoot, path, verbose);
});
}
function validateBundledClientAssets(clientDir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const indexPath = path.join(clientDir, "index.html");
const indexHtml = yield* fs.readFileString(indexPath);
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map(
(match) => match[1],
);
const missing: string[] = [];
for (const ref of refs) {
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
if (!normalizedRef) continue;
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
const ext = path.extname(normalizedRef);
if (!ext) continue;
const relativePath = normalizedRef.replace(/^\/+/, "");
const assetPath = path.join(clientDir, relativePath);
if (!(yield* fs.exists(assetPath))) {
missing.push(normalizedRef);
}
}
if (missing.length > 0) {
const preview = missing.slice(0, 6).join(", ");
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
return yield* new BuildScriptError({
message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
});
}
});
}
function resolveCatalogDependencies(
dependencies: Record<string, unknown>,
catalog: Record<string, unknown>,
dependencySourceLabel: string,
): Record<string, unknown> {
return Object.fromEntries(
Object.entries(dependencies).map(([dependencyName, spec]) => {
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
return [dependencyName, spec];
}
const catalogKey = spec.slice("catalog:".length).trim();
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
const resolvedSpec = catalog[lookupKey];
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
throw new BuildScriptError({
message: `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. Expected key '${lookupKey}' in root workspace catalog.`,
});
}
return [dependencyName, resolvedSpec];
}),
);
}
const createBuildConfig = Effect.fn(function* (
platform: typeof BuildPlatform.Type,
target: string,
productName: string,
signed: boolean,
) {
const buildConfig: Record<string, unknown> = {
appId: "com.t3tools.t3code",
productName,
artifactName: "T3-Code-${version}-${arch}.${ext}",
directories: {
buildResources: "apps/desktop/resources",
},
};
if (platform === "mac") {
buildConfig.mac = {
target: [target],
icon: "icon.icns",
category: "public.app-category.developer-tools",
};
}
if (platform === "linux") {
buildConfig.linux = {
target: [target],
icon: "icon.png",
category: "Development",
};
}
if (platform === "win") {
const winConfig: Record<string, unknown> = {
target: [target],
icon: "icon.ico",
};
if (signed) {
winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
}
buildConfig.win = winConfig;
}
return buildConfig;
});
const assertPlatformBuildResources = Effect.fn(function* (
platform: typeof BuildPlatform.Type,
stageResourcesDir: string,
verbose: boolean,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
if (platform === "mac") {
yield* stageMacIcons(stageResourcesDir, verbose);
return;
}
if (platform === "linux") {
const iconPath = path.join(stageResourcesDir, "icon.png");
if (!(yield* fs.exists(iconPath))) {
return yield* new BuildScriptError({
message: `Missing Linux icon at ${iconPath}`,
});
}
return;
}
if (platform === "win") {
const iconPath = path.join(stageResourcesDir, "icon.ico");
if (!(yield* fs.exists(iconPath))) {
return yield* new BuildScriptError({
message: `Missing Windows icon at ${iconPath}`,
});
}
}
});
const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions) {
const repoRoot = yield* RepoRoot;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const platformConfig = PLATFORM_CONFIG[options.platform];
if (!platformConfig) {
return yield* new BuildScriptError({
message: `Unsupported platform '${options.platform}'.`,
});
}
const electronVersion = desktopPackageJson.dependencies.electron;
const dependencies = serverPackageJson.dependencies;
if (!dependencies || Object.keys(dependencies).length === 0) {
return yield* new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
});
}
const resolvedDependencies = yield* Effect.try({
try: () =>
resolveCatalogDependencies(dependencies, rootPackageJson.workspaces.catalog, "apps/server"),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve production dependencies from apps/server/package.json.",
cause,
}),
});
const appVersion = options.version ?? serverPackageJson.version;
const commitHash = resolveGitCommitHash(repoRoot);
const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
const stageRoot = yield* mkdir({
prefix: `t3code-desktop-${options.platform}-stage-`,
});
const stageAppDir = path.join(stageRoot, "app");
const stageResourcesDir = path.join(stageAppDir, "apps/desktop/resources");
const distDirs = {
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
serverDist: path.join(repoRoot, "apps/server/dist"),
};
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
if (!options.skipBuild) {
yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");
yield* runCommand(
ChildProcess.make({
cwd: repoRoot,
...commandOutputOptions(options.verbose),
})`bun run build:desktop`,
);
}
for (const [label, dir] of Object.entries(distDirs)) {
if (!(yield* fs.exists(dir))) {
return yield* new BuildScriptError({
message: `Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`,
});
}
}
if (!(yield* fs.exists(bundledClientEntry))) {
return yield* new BuildScriptError({
message: `Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
});
}
yield* validateBundledClientAssets(path.dirname(bundledClientEntry));
yield* fs.makeDirectory(path.join(stageAppDir, "apps/desktop"), { recursive: true });
yield* fs.makeDirectory(path.join(stageAppDir, "apps/server"), { recursive: true });
yield* Effect.log("[desktop-artifact] Staging release app...");
yield* fs.copy(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"));
yield* fs.copy(distDirs.desktopResources, stageResourcesDir);
yield* fs.copy(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"));
yield* assertPlatformBuildResources(options.platform, stageResourcesDir, options.verbose);
const stagePackageJson: StagePackageJson = {
name: "t3-code-desktop",
version: appVersion,
buildVersion: appVersion,
t3codeCommitHash: commitHash,
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",
main: "apps/desktop/dist-electron/main.js",
build: yield* createBuildConfig(
options.platform,
options.target,
desktopPackageJson.productName ?? "T3 Code",
options.signed,
),
dependencies: resolvedDependencies,
devDependencies: {
electron: electronVersion,
},
};
yield* fs.writeFileString(
path.join(stageAppDir, "package.json"),
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
);
yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
yield* runCommand(
ChildProcess.make({
cwd: stageAppDir,
...commandOutputOptions(options.verbose),
})`bun install --production`,
);
const buildEnv: NodeJS.ProcessEnv = {
...process.env,
};
for (const [key, value] of Object.entries(buildEnv)) {
if (value === "") {
delete buildEnv[key];
}
}
if (!options.signed) {
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
delete buildEnv.CSC_LINK;
delete buildEnv.CSC_KEY_PASSWORD;
delete buildEnv.APPLE_API_KEY;
delete buildEnv.APPLE_API_KEY_ID;
delete buildEnv.APPLE_API_ISSUER;
}
yield* Effect.log(
`[desktop-artifact] Building ${options.platform}/${options.target} (arch=${options.arch}, version=${appVersion})...`,
);
yield* runCommand(
ChildProcess.make({
cwd: stageAppDir,
env: buildEnv,
...commandOutputOptions(options.verbose),
})`bunx electron-builder ${platformConfig.cliFlag} ${options.target} --${options.arch} --publish never`,
);
const stageDistDir = path.join(stageAppDir, "dist");
if (!(yield* fs.exists(stageDistDir))) {
return yield* new BuildScriptError({
message: `Build completed but dist directory was not found at ${stageDistDir}`,
});
}
const stageEntries = yield* fs.readDirectory(stageDistDir);
yield* fs.makeDirectory(options.outputDir, { recursive: true });
const copiedArtifacts: string[] = [];
for (const entry of stageEntries) {
const from = path.join(stageDistDir, entry);
const stat = yield* fs.stat(from).pipe(Effect.catch(() => Effect.succeed(null)));
if (!stat || stat.type !== "File") continue;
const to = path.join(options.outputDir, entry);
yield* fs.copyFile(from, to);
copiedArtifacts.push(to);
}
if (copiedArtifacts.length === 0) {
return yield* new BuildScriptError({
message: `Build completed but no files were produced in ${stageDistDir}`,
});
}
yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
Effect.annotateLogs({ artifacts: copiedArtifacts }),
);
});
const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
platform: Flag.choice("platform", BuildPlatform.literals).pipe(
Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
Flag.optional,
),
target: Flag.string("target").pipe(
Flag.withDescription(
"Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
),
Flag.optional,
),
arch: Flag.choice("arch", BuildArch.literals).pipe(
Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
Flag.optional,
),
buildVersion: Flag.string("build-version").pipe(
Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),
Flag.optional,
),
outputDir: Flag.string("output-dir").pipe(
Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
Flag.optional,
),
skipBuild: Flag.boolean("skip-build").pipe(
Flag.withDescription(
"Skip `bun run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
),
Flag.optional,
),
keepStage: Flag.boolean("keep-stage").pipe(
Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
Flag.optional,
),
signed: Flag.boolean("signed").pipe(
Flag.withDescription(
"Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
),
Flag.optional,
),
verbose: Flag.boolean("verbose").pipe(
Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
Flag.optional,
),
}).pipe(
Command.withDescription("Build a desktop artifact for T3 Code."),
Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
);
Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
Effect.scoped,
Effect.provide(Logger.layer([Logger.consolePretty()])),
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env node
import { spawn } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, "..");
const PRODUCTION_ICON_SOURCE = path.join(repoRoot, "assets/macos-icon-1024.png");
const ARCH_CHOICES = new Set(["arm64", "x64", "universal"]);
function printUsage() {
console.log(`Build a shareable macOS .dmg for T3 Code desktop.
Usage:
node scripts/build-desktop-dmg.mjs [options]
Options:
--arch <arm64|x64|universal> Target arch (default: host arch if supported)
--version <semver> App version in DMG metadata (default: apps/server version)
--output-dir <path> Output folder for final artifacts (default: release)
--skip-build Skip 'bun run build:desktop' (requires existing dist artifacts)
--keep-stage Keep temporary staging directory
--signed Allow automatic code signing discovery
--help Show this message
`);
}
function fail(message) {
console.error(`[desktop-dmg] ${message}`);
process.exit(1);
}
function parseArgs(argv) {
const defaultArch = process.arch === "arm64" || process.arch === "x64" ? process.arch : "arm64";
const options = {
arch: defaultArch,
version: null,
skipBuild: false,
keepStage: false,
signed: false,
outputDir: path.join(repoRoot, "release"),
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === "--help") {
options.help = true;
continue;
}
if (arg === "--skip-build") {
options.skipBuild = true;
continue;
}
if (arg === "--keep-stage") {
options.keepStage = true;
continue;
}
if (arg === "--signed") {
options.signed = true;
continue;
}
if (arg === "--arch" || arg === "--version" || arg === "--output-dir") {
const value = argv[i + 1];
if (!value || value.startsWith("--")) {
fail(`Missing value for ${arg}`);
}
i += 1;
if (arg === "--arch") options.arch = value;
if (arg === "--version") options.version = value;
if (arg === "--output-dir") options.outputDir = path.resolve(repoRoot, value);
continue;
}
fail(`Unknown argument: ${arg}`);
}
if (!ARCH_CHOICES.has(options.arch)) {
fail(`Invalid arch '${options.arch}'. Expected one of: ${Array.from(ARCH_CHOICES).join(", ")}`);
}
return options;
}
async function readJson(filePath) {
const raw = await fs.readFile(filePath, "utf8");
return JSON.parse(raw);
}
async function exists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
function run(command, args, { cwd, env = process.env, stdio = "inherit" } = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd,
env,
stdio,
});
child.on("error", reject);
child.on("exit", (code, signal) => {
if (signal) {
reject(new Error(`${command} exited via signal ${signal}`));
return;
}
if (code !== 0) {
reject(new Error(`${command} exited with code ${code}`));
return;
}
resolve();
});
});
}
async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
const iconsetDir = path.join(tmpRoot, "icon.iconset");
await fs.mkdir(iconsetDir, { recursive: true });
const iconSizes = [16, 32, 128, 256, 512];
for (const size of iconSizes) {
await run(
"sips",
[
"-z",
String(size),
String(size),
sourcePng,
"--out",
path.join(iconsetDir, `icon_${size}x${size}.png`),
],
{ stdio: "ignore" },
);
const retinaSize = size * 2;
await run(
"sips",
[
"-z",
String(retinaSize),
String(retinaSize),
sourcePng,
"--out",
path.join(iconsetDir, `icon_${size}x${size}@2x.png`),
],
{ stdio: "ignore" },
);
}
await run("iconutil", ["-c", "icns", iconsetDir, "-o", targetIcns], { stdio: "ignore" });
}
async function stageProductionIcons(stageResourcesDir) {
if (!(await exists(PRODUCTION_ICON_SOURCE))) {
fail(`Production icon source is missing at ${PRODUCTION_ICON_SOURCE}`);
}
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "t3code-icon-build-"));
try {
const iconPngPath = path.join(stageResourcesDir, "icon.png");
const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
await run("sips", ["-z", "512", "512", PRODUCTION_ICON_SOURCE, "--out", iconPngPath], {
stdio: "ignore",
});
await generateMacIconSet(PRODUCTION_ICON_SOURCE, iconIcnsPath, tmpRoot);
} finally {
await fs.rm(tmpRoot, { recursive: true, force: true });
}
}
async function validateBundledClientAssets(clientDir) {
const indexPath = path.join(clientDir, "index.html");
const indexHtml = await fs.readFile(indexPath, "utf8");
const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map((match) => match[1]);
const missing = [];
for (const ref of refs) {
const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
if (!normalizedRef) continue;
if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
const ext = path.extname(normalizedRef);
if (!ext) continue;
const relativePath = normalizedRef.replace(/^\/+/, "");
const assetPath = path.join(clientDir, relativePath);
if (!(await exists(assetPath))) {
missing.push(normalizedRef);
}
}
if (missing.length > 0) {
const preview = missing.slice(0, 6).join(", ");
const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
fail(
`Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
);
}
}
function readWorkspaceCatalog(rootPackageJson) {
const workspaces = rootPackageJson?.workspaces;
if (!workspaces || typeof workspaces !== "object" || Array.isArray(workspaces)) {
return {};
}
const catalog = workspaces.catalog;
if (!catalog || typeof catalog !== "object" || Array.isArray(catalog)) {
return {};
}
return catalog;
}
function resolveCatalogDependencies(dependencies, catalog, dependencySourceLabel) {
return Object.fromEntries(
Object.entries(dependencies).map(([dependencyName, spec]) => {
if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
return [dependencyName, spec];
}
const catalogKey = spec.slice("catalog:".length).trim();
const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
const resolvedSpec = catalog[lookupKey];
if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
fail(
`Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. ` +
`Expected key '${lookupKey}' in root workspace catalog.`,
);
}
return [dependencyName, resolvedSpec];
}),
);
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
printUsage();
return;
}
if (process.platform !== "darwin") {
fail("This script only builds macOS .dmg artifacts and must run on macOS.");
}
const rootPkg = await readJson(path.join(repoRoot, "package.json"));
const desktopPkg = await readJson(path.join(repoRoot, "apps/desktop/package.json"));
const serverPkg = await readJson(path.join(repoRoot, "apps/server/package.json"));
const electronVersion = desktopPkg.dependencies?.electron;
if (typeof electronVersion !== "string" || electronVersion.length === 0) {
fail("Could not resolve apps/desktop electron dependency version.");
}
const dependencies = serverPkg.dependencies;
if (!dependencies || Object.keys(dependencies).length === 0) {
fail("Could not resolve production dependencies from apps/server/package.json.");
}
const resolvedDependencies = resolveCatalogDependencies(
dependencies,
readWorkspaceCatalog(rootPkg),
"apps/server",
);
const appVersion = options.version ?? serverPkg.version ?? "0.1.0";
const stageRoot = path.join(os.tmpdir(), "t3code-desktop-dmg-stage");
const stageAppDir = path.join(stageRoot, "app");
const distDirs = {
desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
desktopResources: path.join(repoRoot, "apps/desktop/resources"),
serverDist: path.join(repoRoot, "apps/server/dist"),
};
const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
if (!options.skipBuild) {
console.log("[desktop-dmg] Building desktop/server/web artifacts...");
await run("bun", ["run", "build:desktop"], { cwd: repoRoot });
}
for (const [label, dir] of Object.entries(distDirs)) {
if (!(await exists(dir))) {
fail(`Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`);
}
}
if (!(await exists(bundledClientEntry))) {
fail(
`Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
);
}
await validateBundledClientAssets(path.dirname(bundledClientEntry));
await fs.rm(stageRoot, { recursive: true, force: true });
await fs.mkdir(path.join(stageAppDir, "apps/desktop"), { recursive: true });
await fs.mkdir(path.join(stageAppDir, "apps/server"), { recursive: true });
console.log("[desktop-dmg] Staging release app...");
await fs.cp(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"), {
recursive: true,
});
await fs.cp(distDirs.desktopResources, path.join(stageAppDir, "apps/desktop/resources"), {
recursive: true,
});
await fs.cp(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"), { recursive: true });
await stageProductionIcons(path.join(stageAppDir, "apps/desktop/resources"));
const stagePackageJson = {
name: "t3-code-desktop",
version: appVersion,
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",
main: "apps/desktop/dist-electron/main.js",
build: {
appId: "com.t3tools.t3code",
productName: desktopPkg.productName ?? "T3 Code",
artifactName: "T3-Code-${version}-${arch}.${ext}",
directories: {
buildResources: "apps/desktop/resources",
},
mac: {
target: ["dmg"],
icon: "icon.icns",
category: "public.app-category.developer-tools",
},
},
dependencies: resolvedDependencies,
devDependencies: {
electron: electronVersion,
},
};
await fs.writeFile(
path.join(stageAppDir, "package.json"),
`${JSON.stringify(stagePackageJson, null, 2)}\n`,
"utf8",
);
console.log("[desktop-dmg] Installing staged production dependencies...");
await run("bun", ["install", "--production"], { cwd: stageAppDir });
const buildEnv = {
...process.env,
};
if (!options.signed) {
buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
}
const buildArgs = ["--bun", "electron-builder", "--mac", "dmg", `--${options.arch}`];
console.log(`[desktop-dmg] Building .dmg (arch=${options.arch}, version=${appVersion})...`);
await run("bunx", buildArgs, { cwd: stageAppDir, env: buildEnv });
const stageDistDir = path.join(stageAppDir, "dist");
const stageFiles = await fs.readdir(stageDistDir);
const dmgFiles = stageFiles.filter((file) => file.endsWith(".dmg"));
if (dmgFiles.length === 0) {
fail(`Build completed but no .dmg found in ${stageDistDir}`);
}
await fs.mkdir(options.outputDir, { recursive: true });
const copiedArtifacts = [];
for (const file of stageFiles) {
if (!file.endsWith(".dmg") && !file.endsWith(".dmg.blockmap")) continue;
const from = path.join(stageDistDir, file);
const to = path.join(options.outputDir, file);
await fs.copyFile(from, to);
copiedArtifacts.push(to);
}
if (!options.keepStage) {
await fs.rm(stageRoot, { recursive: true, force: true });
}
console.log("[desktop-dmg] Done. Artifacts:");
for (const artifact of copiedArtifacts) {
console.log(` - ${artifact}`);
}
}
main().catch((error) => {
const message = error instanceof Error ? error.message : String(error);
fail(message);
});
+14 -165
View File
@@ -1,5 +1,4 @@
import { spawn } from "node:child_process";
import net from "node:net";
import { homedir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -7,7 +6,6 @@ import { pathToFileURL } from "node:url";
const BASE_SERVER_PORT = 3773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
export const DEFAULT_DEV_STATE_DIR = path.join(homedir(), ".t3", "dev");
const MODE_ARGS = {
dev: [
@@ -211,133 +209,7 @@ export function createDevRunnerEnv({ mode, env, offset, envOverrides }) {
return output;
}
function portPairForOffset(offset) {
return {
serverPort: BASE_SERVER_PORT + offset,
webPort: BASE_WEB_PORT + offset,
};
}
async function canListenOnHost(port, host) {
return await new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", (error) => {
const code = error?.code;
if (code === "EADDRNOTAVAIL") {
// Host family unavailable on this machine (for example, no IPv6 loopback).
resolve(true);
return;
}
resolve(false);
});
server.once("listening", () => {
server.close(() => {
resolve(true);
});
});
server.listen({ host, port });
});
}
async function isPortAvailable(port) {
// Vite/dev traffic uses localhost loopback. Verify both IPv4 and IPv6 loopback
// so we don't pick a port that fails later on one address family.
const [ipv4, ipv6] = await Promise.all([
canListenOnHost(port, "127.0.0.1"),
canListenOnHost(port, "::1"),
]);
return ipv4 && ipv6;
}
const defaultCheckPortAvailability = isPortAvailable;
export async function findFirstAvailableOffset({
startOffset,
requireServerPort,
requireWebPort,
checkPortAvailability = defaultCheckPortAvailability,
}) {
for (let candidate = startOffset; ; candidate += 1) {
const { serverPort, webPort } = portPairForOffset(candidate);
const serverPortOutOfRange = serverPort > MAX_PORT;
const webPortOutOfRange = webPort > MAX_PORT;
if (
(requireServerPort && serverPortOutOfRange) ||
(requireWebPort && webPortOutOfRange) ||
(!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
) {
break;
}
const checks = [];
if (requireServerPort) {
checks.push(checkPortAvailability(serverPort));
}
if (requireWebPort) {
checks.push(checkPortAvailability(webPort));
}
if (checks.length === 0) {
return candidate;
}
const availability = await Promise.all(checks);
if (availability.every(Boolean)) {
return candidate;
}
}
throw new Error(
`No available dev ports found from offset ${startOffset}. Tried server=${BASE_SERVER_PORT}+n web=${BASE_WEB_PORT}+n up to port ${MAX_PORT}.`,
);
}
export async function resolveModePortOffsets({
mode,
startOffset,
envOverrides,
checkPortAvailability,
}) {
const hasExplicitServerPort = typeof envOverrides.T3CODE_PORT === "string";
const hasExplicitDevUrl = typeof envOverrides.VITE_DEV_SERVER_URL === "string";
if (mode === "dev:web") {
if (hasExplicitDevUrl) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const webOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: false,
requireWebPort: true,
checkPortAvailability,
});
return { serverOffset: startOffset, webOffset };
}
if (mode === "dev:server") {
if (hasExplicitServerPort) {
return { serverOffset: startOffset, webOffset: startOffset };
}
const serverOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability,
});
return { serverOffset, webOffset: serverOffset };
}
const sharedOffset = await findFirstAvailableOffset({
startOffset,
requireServerPort: !hasExplicitServerPort,
requireWebPort: !hasExplicitDevUrl,
checkPortAvailability,
});
return { serverOffset: sharedOffset, webOffset: sharedOffset };
}
export async function runDevRunner(argv = process.argv) {
export function runDevRunner(argv = process.argv) {
const mode = argv[2];
const parsedArgs = parseDevRunnerArgs(argv.slice(3));
if (!mode || !(mode in MODE_ARGS)) {
@@ -346,49 +218,24 @@ export async function runDevRunner(argv = process.argv) {
}
const { offset, source } = resolveOffset();
const { serverOffset, webOffset } = await resolveModePortOffsets({
mode,
startOffset: offset,
envOverrides: parsedArgs.envOverrides,
});
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const mergedEnvOverrides = { ...parsedArgs.envOverrides };
if (!("VITE_DEV_SERVER_URL" in mergedEnvOverrides)) {
const { webPort } = portPairForOffset(webOffset);
mergedEnvOverrides.PORT = String(webPort);
mergedEnvOverrides.ELECTRON_RENDERER_PORT = String(webPort);
mergedEnvOverrides.VITE_DEV_SERVER_URL = `http://localhost:${webPort}`;
if (serverPort > 65535 || webPort > 65535) {
throw new Error(
`Port offset too large (${offset}). Computed ports: server=${serverPort}, web=${webPort}`,
);
}
const env = createDevRunnerEnv({
mode,
env: process.env,
offset: serverOffset,
envOverrides: mergedEnvOverrides,
offset,
envOverrides: parsedArgs.envOverrides,
});
const parsedServerPort = Number(env.T3CODE_PORT);
const parsedWebPort = Number(env.PORT);
if (
!Number.isInteger(parsedServerPort) ||
parsedServerPort < 1 ||
parsedServerPort > MAX_PORT ||
!Number.isInteger(parsedWebPort) ||
parsedWebPort < 1 ||
parsedWebPort > MAX_PORT
) {
throw new Error(
`Invalid computed dev ports: server='${String(env.T3CODE_PORT)}' web='${String(env.PORT)}'.`,
);
}
const selectionSuffix =
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
console.info(
`[dev-runner] mode=${mode} source=${source}${selectionSuffix} serverPort=${parsedServerPort} webPort=${parsedWebPort} stateDir=${env.T3CODE_STATE_DIR}`,
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort} stateDir=${env.T3CODE_STATE_DIR}`,
);
if (parsedArgs.isDryRun) {
@@ -418,8 +265,10 @@ export async function runDevRunner(argv = process.argv) {
const entrypointPath = process.argv[1] ? pathToFileURL(process.argv[1]).href : "";
if (import.meta.url === entrypointPath) {
runDevRunner().catch((error) => {
try {
runDevRunner();
} catch (error) {
console.error("[dev-runner]", error);
process.exit(1);
});
}
}
-98
View File
@@ -3,9 +3,7 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_DEV_STATE_DIR,
createDevRunnerEnv,
findFirstAvailableOffset,
parseDevRunnerArgs,
resolveModePortOffsets,
} from "./dev-runner.mjs";
describe("parseDevRunnerArgs", () => {
@@ -125,99 +123,3 @@ describe("createDevRunnerEnv", () => {
).toThrow("Invalid T3CODE_PORT override");
});
});
describe("findFirstAvailableOffset", () => {
it("returns the starting offset when required ports are available", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async () => true,
});
expect(offset).toBe(0);
});
it("advances until all required ports are available", async () => {
const taken = new Set([3773, 5733, 3774, 5734]);
const offset = await findFirstAvailableOffset({
startOffset: 0,
requireServerPort: true,
requireWebPort: true,
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offset).toBe(2);
});
it("allows offsets where only non-required ports exceed max", async () => {
const offset = await findFirstAvailableOffset({
startOffset: 59_803,
requireServerPort: true,
requireWebPort: false,
checkPortAvailability: async () => true,
});
expect(offset).toBe(59_803);
});
});
describe("resolveModePortOffsets", () => {
it("uses a shared fallback offset for dev mode", async () => {
const taken = new Set([3773, 5733]);
const offsets = await resolveModePortOffsets({
mode: "dev",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("keeps server offset stable for dev:web and only shifts web offset", async () => {
const taken = new Set([5733]);
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 1 });
});
it("shifts only server offset for dev:server", async () => {
const taken = new Set([3773]);
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: {},
checkPortAvailability: async (port) => !taken.has(port),
});
expect(offsets).toEqual({ serverOffset: 1, webOffset: 1 });
});
it("respects explicit dev-url override for dev:web", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:web",
startOffset: 0,
envOverrides: { VITE_DEV_SERVER_URL: "http://localhost:9999" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
it("respects explicit server port override for dev:server", async () => {
const offsets = await resolveModePortOffsets({
mode: "dev:server",
startOffset: 0,
envOverrides: { T3CODE_PORT: "4888" },
checkPortAvailability: async () => false,
});
expect(offsets).toEqual({ serverOffset: 0, webOffset: 0 });
});
});