Compare commits

...
Author SHA1 Message Date
Julius Marminge bde0115546 Fix Windows command detection and branch checkout error flow
- tighten win32 command availability checks for PATHEXT and PATH delimiter handling
- add server tests for Windows executable resolution edge cases
- stop branch/create flows after checkout/create failures to avoid stale optimistic UI
- remove OpenInPicker side effect that persisted last editor on render
2026-03-02 18:39:58 -08:00
Julius Marminge 4b0f77fd9c Sync thread metadata after worktree branch rename
- Dispatch `thread.meta.update` with the renamed branch after `git.renameBranch`
- Remove pre-rename active-branch status check and related skip path
- Update reactor tests to assert branch metadata moves to generated branch
2026-03-02 18:32:38 -08:00
Julius Marminge bb1eb98a8b Gate embedded commit hash lookup to packaged desktop builds
- Prefer `T3CODE_COMMIT_HASH` when set
- Return `null` for unpackaged desktop runs instead of reading embedded metadata
2026-03-02 18:29:00 -08:00
Julius Marminge 489fe2db59 Refactor commit hash resolution in About panel
- Remove git command execution for commit hash retrieval
- Simplify commit hash resolution to use environment variable and embedded hash only
- Clean up unused code in IPC handler registration
2026-03-02 18:21:27 -08:00
Julius Marminge c7918d5fba Show desktop commit hash in About panel
- embed `t3codeCommitHash` into staged desktop package metadata during builds
- resolve commit hash from env/package/git and display it as About panel version
2026-03-02 18:05:17 -08:00
Julius Marminge df4294aab6 Refactor branch toolbar actions to use transition-based git ops
- replace React Query mutations with direct git API calls wrapped in `useTransition`
- show toast errors for branch create/checkout failures and keep optimistic branch updates
- disable branch controls during pending actions and refresh branches when opening menu
2026-03-02 17:02:52 -08:00
Julius Marminge 10eab80c02 Add Zed editor support across open-in flow
- add `zed` to shared editor contracts and Open In picker
- add Zed icon and wire launch resolution tests on macOS
- wrap branch optimistic updates in `startTransition` to avoid sync warnings
2026-03-02 16:43:23 -08:00
Julius Marminge 7e0e835491 Expose available editors and gate Open In options
- Add server-side command detection and return `availableEditors` in server config
- Update Chat header Open In picker to show only installed editors and handle empty state
- Extend server/web tests and contracts for `availableEditors`; remove unused branch-sync logic
2026-03-02 16:35:30 -08:00
Julius Marminge 807a8c0f10 Show optimistic active branch during checkout and branch creation
- use `useOptimistic` in `BranchToolbar` to update active branch immediately
- keep optimistic branch in sync on success and roll back on mutation errors
2026-03-02 16:27:07 -08:00
Julius Marminge dcb2c2f225 Guard worktree branch rename and fix branch toolbar state
- Skip auto-rename when the active worktree branch no longer matches the temp branch
- Update reactor tests to cover branch-switch and first-turn rename behavior
- Show the actual current branch in the toolbar and use a VS Code icon in Open In picker
2026-03-02 16:17:07 -08:00
13 changed files with 641 additions and 242 deletions

No files matched your search

+56 -6
View File
@@ -26,6 +26,8 @@ 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;
@@ -36,6 +38,7 @@ 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;
@@ -81,6 +84,54 @@ 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");
}
@@ -277,8 +328,11 @@ 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") {
@@ -425,11 +479,7 @@ function registerIpcHandlers(): void {
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
async (
_event,
items: ContextMenuItem[],
position?: { x: number; y: number },
) => {
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
const normalizedItems = items
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
.map((item) => ({
@@ -480,7 +530,7 @@ function registerIpcHandlers(): void {
const menu = Menu.buildFromTemplate(template);
menu.popup({
window,
...(popupPosition ?? {}),
...popupPosition,
callback: () => resolve(null),
});
});
+110 -1
View File
@@ -1,6 +1,15 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { launchDetached, resolveEditorLaunch } from "./open";
import {
isCommandAvailable,
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { Effect } from "effect";
import { assertSuccess } from "@effect/vitest/utils";
@@ -24,6 +33,15 @@ describe("resolveEditorLaunch", () => {
command: "code",
args: ["/tmp/workspace"],
});
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
@@ -55,6 +73,15 @@ describe("resolveEditorLaunch", () => {
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"],
});
}),
);
@@ -111,3 +138,85 @@ 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 });
}
});
});
+140 -8
View File
@@ -7,6 +7,8 @@
* @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";
@@ -30,12 +32,149 @@ 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;
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
@@ -81,14 +220,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
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] };
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
export const launchDetached = (launch: EditorLaunch) =>
+24
View File
@@ -13,6 +13,7 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
import {
DEFAULT_TERMINAL_ID,
EDITORS,
EventId,
ORCHESTRATION_WS_CHANNELS,
ORCHESTRATION_WS_METHODS,
@@ -340,6 +341,15 @@ 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;
@@ -726,7 +736,9 @@ 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 () => {
@@ -749,7 +761,9 @@ 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"),
@@ -782,7 +796,9 @@ 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");
});
@@ -814,6 +830,7 @@ 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);
@@ -832,6 +849,7 @@ 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 () => {
@@ -929,7 +947,9 @@ 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 () => {
@@ -974,7 +994,11 @@ 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 -1
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 } from "./open";
import { Open, resolveAvailableEditors } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
@@ -193,6 +193,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const availableEditors = resolveAvailableEditors();
const gitManager = yield* GitManager;
const terminalManager = yield* TerminalManager;
@@ -734,6 +735,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
availableEditors,
};
case WS_METHODS.serverUpsertKeybinding: {
@@ -1,67 +1,10 @@
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import type { GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
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("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("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();
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
+1 -28
View File
@@ -1,12 +1,4 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
interface DeriveSyncedLocalBranchInput {
activeThreadId: ThreadId | undefined;
activeWorktreePath: string | null;
envMode: "local" | "worktree";
activeThreadBranch: string | null;
queryBranches: ReadonlyArray<GitBranch> | undefined;
}
import type { GitBranch } from "@t3tools/contracts";
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
@@ -55,22 +47,3 @@ export function dedupeRemoteBranchesWithLocalMatches(
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode,
activeThreadBranch,
queryBranches,
}: DeriveSyncedLocalBranchInput): string | null {
if (!activeThreadId || activeWorktreePath || envMode !== "local") {
return null;
}
const currentBranch = queryBranches?.find((branch) => branch.current);
if (!currentBranch || currentBranch.name === activeThreadBranch) {
return null;
}
return currentBranch.name;
}
+92 -104
View File
@@ -1,20 +1,15 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useOptimistic, useState, useTransition } from "react";
import { newCommandId } from "../lib/utils";
import {
gitBranchesQueryOptions,
gitCheckoutMutationOptions,
gitCreateBranchAndCheckoutMutationOptions,
} from "../lib/gitReactQuery";
import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
@@ -27,6 +22,7 @@ import {
ComboboxTrigger,
} from "./ui/combobox";
import { ChevronDownIcon } from "lucide-react";
import { toastManager } from "./ui/toast";
interface BranchToolbarProps {
threadId: ThreadId;
@@ -72,6 +68,11 @@ export default function BranchToolbar({
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 branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
@@ -84,60 +85,21 @@ 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: effectiveEnvMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, syncedBranch, null);
return;
}
setDraftThreadContext(threadId, {
branch: syncedBranch,
worktreePath: null,
});
}, [
activeThreadId,
activeWorktreePath,
activeThreadBranch,
queryBranches,
effectiveEnvMode,
setThreadBranchAction,
hasServerThread,
setDraftThreadContext,
threadId,
]);
// ── 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);
@@ -181,11 +143,10 @@ export default function BranchToolbar({
const selectBranch = (branch: GitBranch) => {
const api = readNativeApi();
if (!api || !activeThreadId || !branchCwd) return;
if (!api || !activeThreadId || !branchCwd || isBranchActionPending) return;
// For new worktree mode, selecting a branch picks the base branch.
if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
setThreadError(null);
setThreadBranch(branch.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
@@ -196,7 +157,6 @@ 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);
@@ -209,42 +169,71 @@ export default function BranchToolbar({
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
checkoutMutation.mutate(branch.name, {
onSuccess: async () => {
setThreadError(null);
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
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;
}
setThreadBranch(nextBranchName, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
onError: (error) => {
setThreadError(error instanceof Error ? error.message : "Failed to checkout branch.");
setIsBranchMenuOpen(true);
},
}
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, activeWorktreePath);
});
};
const createBranch = (rawName: string) => {
const name = rawName.trim();
const api = readNativeApi();
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 (!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("");
});
};
@@ -263,9 +252,7 @@ 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(effectiveEnvMode === "local" ? "worktree" : "local")}
>
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
</Button>
@@ -277,23 +264,22 @@ export default function BranchToolbar({
autoHighlight
onOpenChange={(open) => {
setIsBranchMenuOpen(open);
if (!open) {
setBranchQuery("");
}
if (!open) setBranchQuery("");
else void invalidateGitQueries(queryClient);
}}
open={isBranchMenuOpen}
value={activeThreadBranch}
value={resolvedActiveBranch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className="text-muted-foreground/70 hover:text-foreground/80"
disabled={branchesQuery.isLoading}
disabled={branchesQuery.isLoading || isBranchActionPending}
>
<span className="max-w-[240px] truncate">
{activeThreadBranch
{resolvedActiveBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${activeThreadBranch}`
: activeThreadBranch
? `From ${resolvedActiveBranch}`
: resolvedActiveBranch
: "Select branch"}
</span>
<ChevronDownIcon />
@@ -347,13 +333,15 @@ export default function BranchToolbar({
key={itemValue}
value={itemValue}
className={
itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
itemValue === resolvedActiveBranch ? "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>}
{badge && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
)}
</div>
</ComboboxItem>
);
+67 -35
View File
@@ -100,7 +100,7 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./u
import { Separator } from "./ui/separator";
import { Group, GroupSeparator } from "./ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import { CursorIcon, Icon } from "./Icons";
import { CursorIcon, Icon, VisualStudioCode, Zed } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -147,6 +147,7 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT =
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
const SCRIPT_TERMINAL_COLS = 120;
const SCRIPT_TERMINAL_ROWS = 30;
@@ -869,10 +870,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const keybindingsQuery = useQuery({
...serverConfigQueryOptions(),
select: (config) => config.keybindings,
});
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const workspaceEntriesQuery = useQuery(
projectSearchEntriesQueryOptions({
cwd: gitCwd,
@@ -944,7 +942,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
);
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const threadTerminalRuntimeEnv = useMemo(() => {
@@ -2486,6 +2485,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
availableEditors={availableEditors}
diffToggleShortcutLabel={diffPanelShortcutLabel}
gitCwd={gitCwd}
diffOpen={diffOpen}
@@ -2899,6 +2899,7 @@ interface ChatHeaderProps {
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
diffToggleShortcutLabel: string | null;
gitCwd: string | null;
diffOpen: boolean;
@@ -2915,6 +2916,7 @@ const ChatHeader = memo(function ChatHeader({
activeProjectScripts,
preferredScriptId,
keybindings,
availableEditors,
diffToggleShortcutLabel,
gitCwd,
diffOpen,
@@ -2951,7 +2953,11 @@ const ChatHeader = memo(function ChatHeader({
/>
)}
{activeProjectName && (
<OpenInPicker keybindings={keybindings} activeThreadId={activeThreadId} />
<OpenInPicker
keybindings={keybindings}
availableEditors={availableEditors}
activeThreadId={activeThreadId}
/>
)}
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
<Tooltip>
@@ -3663,9 +3669,11 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
const OpenInPicker = memo(function OpenInPicker({
keybindings,
availableEditors,
activeThreadId,
}: {
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
activeThreadId: ThreadId | null;
}) {
const [lastEditor, setLastEditor] = useState<EditorId>(() => {
@@ -3673,28 +3681,44 @@ const OpenInPicker = memo(function OpenInPicker({
return EDITORS.some((e) => e.id === stored) ? (stored as EditorId) : EDITORS[0].id;
});
const options = [
{
label: "Cursor",
Icon: CursorIcon,
value: "cursor",
},
{
label: "VS Code",
Icon: FileIcon,
value: "vscode",
},
{
label: isMacPlatform(navigator.platform)
? "Finder"
: isWindowsPlatform(navigator.platform)
? "Explorer"
: "Files",
Icon: FolderClosedIcon,
value: "file-manager",
},
] satisfies { label: string; Icon: Icon; value: EditorId }[];
const primaryOption = options.find(({ value }) => value === lastEditor);
const allOptions = useMemo<Array<{ label: string; Icon: Icon; value: EditorId }>>(
() => [
{
label: "Cursor",
Icon: CursorIcon,
value: "cursor",
},
{
label: "VS Code",
Icon: VisualStudioCode,
value: "vscode",
},
{
label: "Zed",
Icon: Zed,
value: "zed",
},
{
label: isMacPlatform(navigator.platform)
? "Finder"
: isWindowsPlatform(navigator.platform)
? "Explorer"
: "Files",
Icon: FolderClosedIcon,
value: "file-manager",
},
],
[],
);
const options = useMemo(
() => allOptions.filter((option) => availableEditors.includes(option.value)),
[allOptions, availableEditors],
);
const effectiveEditor = options.some((option) => option.value === lastEditor)
? lastEditor
: (options[0]?.value ?? null);
const primaryOption = options.find(({ value }) => value === effectiveEditor) ?? null;
const activeThread = useStore((store) =>
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
@@ -3708,13 +3732,14 @@ const OpenInPicker = memo(function OpenInPicker({
(editorId: EditorId | null) => {
const api = readNativeApi();
if (!api || !activeProject) return;
const editor = editorId ?? lastEditor;
const editor = editorId ?? effectiveEditor;
if (!editor) return;
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, editor);
localStorage.setItem(LAST_EDITOR_KEY, editor);
setLastEditor(editor);
},
[activeProject, activeThread, lastEditor, setLastEditor],
[activeProject, activeThread, effectiveEditor, setLastEditor],
);
const openFavoriteEditorShortcutLabel = useMemo(
@@ -3727,18 +3752,24 @@ const OpenInPicker = memo(function OpenInPicker({
const api = readNativeApi();
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
if (!api || !activeProject) return;
if (!effectiveEditor) return;
e.preventDefault();
const cwd = activeThread?.worktreePath ?? activeProject.cwd;
void api.shell.openInEditor(cwd, lastEditor);
void api.shell.openInEditor(cwd, effectiveEditor);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, [activeProject, activeThread, keybindings, lastEditor]);
}, [activeProject, activeThread, keybindings, effectiveEditor]);
return (
<Group aria-label="Subscription actions">
<Button size="xs" variant="outline" onClick={() => openInEditor(lastEditor)}>
<Button
size="xs"
variant="outline"
disabled={!effectiveEditor || !activeProject}
onClick={() => openInEditor(effectiveEditor)}
>
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
Open
@@ -3750,11 +3781,12 @@ const OpenInPicker = memo(function OpenInPicker({
<ChevronDownIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end">
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
{options.map(({ label, Icon, value }) => (
<MenuItem key={value} onClick={() => openInEditor(value)}>
<Icon aria-hidden="true" className="text-muted-foreground" />
{label}
{value === lastEditor && openFavoriteEditorShortcutLabel && (
{value === effectiveEditor && openFavoriteEditorShortcutLabel && (
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
)}
</MenuItem>
+124 -1
View File
@@ -1,4 +1,4 @@
import type { SVGProps } from "react";
import { type SVGProps, useId } from "react";
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
@@ -19,3 +19,126 @@ 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>
);
};
+1
View File
@@ -4,6 +4,7 @@ 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
@@ -1,6 +1,7 @@
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"),
@@ -29,6 +30,7 @@ export const ServerConfig = Schema.Struct({
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
issues: ServerConfigIssues,
availableEditors: Schema.Array(EditorId),
});
export type ServerConfig = typeof ServerConfig.Type;
+20
View File
@@ -1,5 +1,7 @@
#!/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" };
@@ -84,6 +86,21 @@ class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
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;
@@ -100,6 +117,7 @@ interface StagePackageJson {
readonly name: string;
readonly version: string;
readonly buildVersion: string;
readonly t3codeCommitHash: string;
readonly private: true;
readonly description: string;
readonly author: string;
@@ -436,6 +454,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
});
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-`,
@@ -490,6 +509,7 @@ const buildDesktopArtifact = Effect.fn(function* (options: ResolvedBuildOptions)
name: "t3-code-desktop",
version: appVersion,
buildVersion: appVersion,
t3codeCommitHash: commitHash,
private: true,
description: "T3 Code desktop build",
author: "T3 Tools",