Compare commits

...
Author SHA1 Message Date
Julius Marminge 0a0f436ce2 fmt 2026-02-13 00:44:27 -08:00
Julius Marminge cabc938e5f Wait for desktop backend before loading production window
- Load production renderer from backend HTTP URL instead of local file path
- Poll loopback port with timeout before creating the window, and quit cleanly on bootstrap failure
- Treat `ERR_FILE_NOT_FOUND` as a fatal smoke-test pattern
2026-02-12 23:59:15 -08:00
Julius Marmingeandcodex 6b916d3a6f Handle branch recency lookup failures in branch listing
- move branch recency parsing into `readBranchRecency`
- fall back to an empty recency map if lookup fails
- add test to ensure branches still list when recency read times out

Co-authored-by: codex <[email protected]>
2026-02-12 23:29:44 -08:00
Julius Marmingeandcodex 21580dc1b0 Prioritize current and default branches in branch list ordering
- Keep the current branch first
- Place the default branch second
- Sort remaining branches by most recent commit and update tests for this behavior

Co-authored-by: codex <[email protected]>
2026-02-12 23:29:44 -08:00
Julius Marminge ba9585966c Sort git branches by latest commit timestamp
- Order `listGitBranches` by each branch's most recent commit date
- Keep current/default/name tiebreakers for stable ordering
- Add integration test coverage with dated commits to verify recency sort
2026-02-12 23:29:44 -08:00
Julius Marminge 293f7b1507 Guard orphaned worktree deletion behind project context
- Require both orphaned worktree path and thread project before prompting delete
- Prevents delete confirmation when project metadata is unavailable
2026-02-12 22:57:56 -08:00
Julius Marminge 4f5eb3be4d Show worktree name in thread delete confirmation
- Format orphaned worktree paths to display only the final segment
- Apply formatting in Sidebar delete prompt for cleaner UX
- Add tests for Unix, Windows, trailing slash, and fallback cases
2026-02-12 22:57:56 -08:00
Julius Marmingeandcodex b6523a15dc Use Yes/No labels for desktop worktree confirm
Co-authored-by: codex <[email protected]>
2026-02-12 22:57:56 -08:00
Julius Marmingeandcodex 8a4fed1bf2 Guard worktree cleanup on missing project
Co-authored-by: codex <[email protected]>
2026-02-12 22:57:56 -08:00
Julius Marminge 0068a93cfa Add desktop-backed confirm dialog API for worktree deletion
- add `dialogs.confirm` to native IPC/contracts and desktop preload/main bridge
- switch sidebar worktree deletion prompt from `window.confirm` to native API
- add `showDesktopConfirmDialog` helper with unit tests for dialog behavior
2026-02-12 22:57:56 -08:00
Julius Marminge dd912666f2 Delete orphaned worktree when deleting a thread
- Prompt to remove the worktree when a deleted thread is its only reference
- Best-effort cleanup via `api.git.removeWorktree` after thread deletion
- Add `getOrphanedWorktreePathForThread` helper with unit tests
2026-02-12 22:57:56 -08:00
Julius Marminge 521238cf8e Simplify terminal toggle to only update visibility state
- Remove terminal close/exit API calls from `toggleTerminalVisibility`
- Keep toggle behavior as a pure UI state change for active thread
2026-02-12 22:44:14 -08:00
38 changed files with 675 additions and 392 deletions

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ child.on("exit", () => {
"Uncaught Error",
"Uncaught TypeError",
"Uncaught ReferenceError",
"ERR_FILE_NOT_FOUND",
];
const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
+57
View File
@@ -0,0 +1,57 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
}));
vi.mock("electron", () => ({
dialog: {
showMessageBox: showMessageBoxMock,
},
}));
import { showDesktopConfirmDialog } from "./confirmDialog";
describe("showDesktopConfirmDialog", () => {
beforeEach(() => {
showMessageBoxMock.mockReset();
});
it("returns false and does not open a dialog for empty messages", async () => {
const result = await showDesktopConfirmDialog(" ", null);
expect(result).toBe(false);
expect(showMessageBoxMock).not.toHaveBeenCalled();
});
it("opens a dialog for the focused window and returns true on confirm", async () => {
const ownerWindow = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
expect(result).toBe(true);
expect(showMessageBoxMock).toHaveBeenCalledWith(
ownerWindow,
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
it("opens an app-level dialog when there is no focused window", async () => {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const result = await showDesktopConfirmDialog("Delete worktree?", null);
expect(result).toBe(false);
expect(showMessageBoxMock).toHaveBeenCalledWith(
expect.objectContaining({
buttons: ["No", "Yes"],
message: "Delete worktree?",
}),
);
});
});
+26
View File
@@ -0,0 +1,26 @@
import { type BrowserWindow, dialog } from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export async function showDesktopConfirmDialog(
message: string,
ownerWindow: BrowserWindow | null,
): Promise<boolean> {
const normalizedMessage = message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const result = ownerWindow
? await dialog.showMessageBox(ownerWindow, options)
: await dialog.showMessageBox(options);
return result.response === CONFIRM_BUTTON_INDEX;
}
+107 -24
View File
@@ -7,16 +7,21 @@ import path from "node:path";
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { fixPath } from "./fixPath";
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../..");
const LOOPBACK_HOST = "127.0.0.1";
const DEFAULT_BACKEND_PORT = 3773;
const BACKEND_READY_TIMEOUT_MS = 10_000;
const BACKEND_READY_RETRY_DELAY_MS = 100;
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
const STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -29,22 +34,16 @@ let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false;
async function reserveLoopbackPort(): Promise<number> {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, "127.0.0.1", () => {
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
probe.close(() => {
if (port > 0) {
resolve(port);
return;
}
reject(new Error("Failed to reserve backend port"));
});
});
probe.on("error", reject);
});
function resolveBackendPort(raw: string | undefined): number {
if (!raw || raw.trim().length === 0) {
return DEFAULT_BACKEND_PORT;
}
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65_535) {
throw new Error(`Invalid T3CODE_PORT: ${raw}`);
}
return parsed;
}
function backendEnv(): NodeJS.ProcessEnv {
@@ -127,6 +126,76 @@ function stopBackend(): void {
}
}
function backendHttpUrl(): string {
return `http://${LOOPBACK_HOST}:${backendPort}`;
}
function canConnectToBackendPort(port: number): Promise<boolean> {
return new Promise((resolve) => {
const socket = net.connect({ host: LOOPBACK_HOST, port });
let settled = false;
const finish = (connected: boolean) => {
if (settled) return;
settled = true;
socket.destroy();
resolve(connected);
};
socket.once("connect", () => finish(true));
socket.once("error", () => finish(false));
socket.setTimeout(500, () => finish(false));
});
}
async function waitForBackendReady(): Promise<void> {
const startedAt = Date.now();
return new Promise((resolve, reject) => {
let retryTimer: ReturnType<typeof setTimeout> | null = null;
const stop = () => {
if (retryTimer) {
clearTimeout(retryTimer);
retryTimer = null;
}
};
const attempt = () => {
if (isQuitting) {
stop();
reject(new Error("Backend startup cancelled while app is quitting"));
return;
}
if (Date.now() - startedAt >= BACKEND_READY_TIMEOUT_MS) {
stop();
reject(
new Error(
`Backend did not start listening on ${LOOPBACK_HOST}:${backendPort} within ${BACKEND_READY_TIMEOUT_MS}ms`,
),
);
return;
}
void canConnectToBackendPort(backendPort)
.then((connected) => {
if (connected) {
stop();
resolve();
return;
}
retryTimer = setTimeout(attempt, BACKEND_READY_RETRY_DELAY_MS);
})
.catch(() => {
retryTimer = setTimeout(attempt, BACKEND_READY_RETRY_DELAY_MS);
});
};
attempt();
});
}
function registerIpcHandlers(): void {
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
@@ -142,6 +211,16 @@ function registerIpcHandlers(): void {
return result.filePaths[0] ?? null;
});
ipcMain.removeHandler(CONFIRM_CHANNEL);
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
if (typeof message !== "string") {
return false;
}
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -214,10 +293,7 @@ function createWindow(): BrowserWindow {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" });
} else {
if (!fs.existsSync(WEB_ENTRY)) {
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
void window.loadURL(backendHttpUrl());
}
window.on("closed", () => {
@@ -230,13 +306,17 @@ function createWindow(): BrowserWindow {
}
async function bootstrap(): Promise<void> {
backendPort = await reserveLoopbackPort();
backendPort = resolveBackendPort(process.env.T3CODE_PORT);
process.env.T3CODE_PORT = String(backendPort);
backendAuthToken = randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
backendWsUrl = `ws://${LOOPBACK_HOST}:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
registerIpcHandlers();
startBackend();
if (!isDevelopment) {
await waitForBackendReady();
}
mainWindow = createWindow();
}
@@ -246,7 +326,10 @@ app.on("before-quit", () => {
});
app.whenReady().then(() => {
void bootstrap();
void bootstrap().catch((error) => {
console.error("[desktop] failed to bootstrap app", error);
app.quit();
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
+2
View File
@@ -1,6 +1,7 @@
import { contextBridge, ipcRenderer } from "electron";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
@@ -8,6 +9,7 @@ const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
showContextMenu: (items: { id: string; label: string }[]) =>
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
+10 -3
View File
@@ -21,10 +21,16 @@ function createSendTurnHarness() {
};
const requireSession = vi
.spyOn(manager as unknown as { requireSession: (sessionId: string) => unknown }, "requireSession")
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const sendRequest = vi
.spyOn(manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> }, "sendRequest")
.spyOn(
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
"sendRequest",
)
.mockResolvedValue({
turn: {
id: "turn_1",
@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {
describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => {
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
const { manager, context, requireSession, sendRequest, updateSession } =
createSendTurnHarness();
const result = await manager.sendTurn({
sessionId: "sess_1",
+2 -4
View File
@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
const turnInput: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
> = [];
if (input.input) {
turnInput.push({
@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: {
threadId: string;
input: Array<
| { type: "text"; text: string; text_elements: [] }
| { type: "image"; url: string }
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
>;
model?: string;
effort?: string;
+1 -4
View File
@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
}
+109 -10
View File
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
GitCoreService,
@@ -51,6 +51,25 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
await git(cwd, "commit -m 'initial commit'");
}
async function commitWithDate(
cwd: string,
fileName: string,
fileContents: string,
dateIsoString: string,
message: string,
): Promise<void> {
await writeFile(path.join(cwd, fileName), fileContents);
await git(cwd, `add ${fileName}`);
const commitResult = await runTerminalCommand({
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
cwd,
timeoutMs: 10_000,
});
if (commitResult.code !== 0) {
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
}
}
// ── Tests ──
describe("git integration", () => {
@@ -106,14 +125,82 @@ describe("git integration", () => {
expect(current!.current).toBe(true);
});
it("sorts current branch first", async () => {
it("keeps current branch first and sorts the remaining branches by recency", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
await commitWithDate(
tmp.path,
"older.txt",
"older branch change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"older branch change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer branch change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer branch change",
);
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.current).toBe(true);
expect(result.branches[0]!.name).toBe("older-branch");
expect(result.branches[1]!.name).toBe("newer-branch");
});
it("keeps default branch right after current branch", async () => {
await using tmp = await makeTmpDir();
await using remote = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
(branch) => branch.current,
)!.name;
await git(remote.path, "init --bare");
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
await git(tmp.path, `push -u origin ${defaultBranch}`);
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
await commitWithDate(
tmp.path,
"current.txt",
"current change\n",
"Thu, 1 Jan 2037 00:00:00 +0000",
"current change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
await commitWithDate(
tmp.path,
"newer.txt",
"newer change\n",
"Fri, 1 Jan 2038 00:00:00 +0000",
"newer change",
);
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
const result = await listGitBranches({ cwd: tmp.path });
expect(result.branches[0]!.name).toBe("current-branch");
expect(result.branches[1]!.name).toBe(defaultBranch);
expect(result.branches[2]!.name).toBe("newer-branch");
});
it("lists multiple branches after creating them", async () => {
@@ -482,11 +569,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0);
const created = await core.commit(
tmp.path,
"Add README update",
"- include updated content",
);
const created = await core.commit(tmp.path, "Add README update", "- include updated content");
expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
});
@@ -516,5 +599,21 @@ describe("git integration", () => {
const skipped = await core.pushCurrentBranch(tmp.path, null);
expect(skipped.status).toBe("skipped_up_to_date");
});
it("lists branches when recency lookup fails", async () => {
await using tmp = await makeTmpDir();
await initRepoWithCommit(tmp.path);
const core = new GitCoreService();
const recencySpy = vi
.spyOn(core as any, "readBranchRecency")
.mockRejectedValueOnce(new Error("timeout"));
const result = await core.listBranches({ cwd: tmp.path });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches[0]?.current).toBe(true);
recencySpy.mockRestore();
});
});
});
+44 -14
View File
@@ -224,21 +224,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]);
const stagedSummary = await this.gitStdout(cwd, [
"diff",
"--cached",
"--name-status",
]);
const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
if (trimStdout(stagedSummary).length === 0) {
return null;
}
const stagedPatch = await this.gitStdout(cwd, [
"diff",
"--cached",
"--patch",
"--minimal",
]);
const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
return {
stagedSummary,
@@ -312,7 +303,40 @@ export class GitCoreService {
return value.length > 0 ? value : null;
}
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
const branchRecency = await executeGit(
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
},
);
const branchLastCommit = new Map<string, number>();
if (branchRecency.code !== 0) {
return branchLastCommit;
}
for (const line of branchRecency.stdout.split("\n")) {
if (line.length === 0) {
continue;
}
const [name, lastCommitRaw] = line.split("\t");
if (!name) {
continue;
}
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
}
return branchLastCommit;
}
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
() => new Map<string, number>(),
);
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
timeoutMs: 10_000,
allowNonZeroExit: true,
@@ -326,7 +350,7 @@ export class GitCoreService {
throw new Error(stderr || "git branch failed");
}
const [defaultRef, worktreeList] = await Promise.all([
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
timeoutMs: 5_000,
allowNonZeroExit: true,
@@ -335,6 +359,7 @@ export class GitCoreService {
timeoutMs: 5_000,
allowNonZeroExit: true,
}),
branchRecencyPromise,
]);
const defaultBranch =
defaultRef.code === 0
@@ -370,8 +395,13 @@ export class GitCoreService {
};
})
.toSorted((a, b) => {
if (a.current !== b.current) return a.current ? -1 : 1;
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
if (aPriority !== bPriority) return aPriority - bPriority;
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);
});
+4 -13
View File
@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { GitManager } from "./gitManager";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
interface FakeGhScenario {
prListSequence?: string[];
@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir;
}
function createTextGenerator(
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
return {
generateCommitMessage: async () => ({
subject: "Implement stacked git actions",
@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") {
return {
stdout:
(scenario.createdPrUrl ??
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
(scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "",
code: 0,
signal: null,
@@ -376,9 +369,7 @@ describe("GitManager", () => {
expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42);
expect(
ghCalls.some((call) => call.startsWith("pr view feature/existing-pr --web")),
).toBe(true);
expect(ghCalls.some((call) => call.startsWith("pr view feature/existing-pr --web"))).toBe(true);
});
it("creates PR when one does not already exist", async () => {
+10 -40
View File
@@ -20,11 +20,7 @@ import type {
} from "./coreServices";
import { CodexTextGenerator } from "./codexTextGenerator";
import { GitCoreService } from "./git";
import {
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
const GH_CLI_TIMEOUT_MS = 30_000;
@@ -58,11 +54,7 @@ function parseOpenPrList(raw: unknown): OpenPrInfo[] {
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (
typeof number !== "number" ||
!Number.isInteger(number) ||
number <= 0
) {
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
continue;
}
if (
@@ -98,8 +90,7 @@ function sanitizeCommitMessage(
): CommitMessageGenerationResult {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim();
const safeSubject =
subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
return {
subject: safeSubject,
body: generated.body.trim(),
@@ -143,10 +134,7 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim();
}
function asCommandNotFound(
command: string,
error: unknown,
): Error | undefined {
function asCommandNotFound(command: string, error: unknown): Error | undefined {
if (!(error instanceof Error)) return undefined;
if (!error.message.includes(`Command not found: ${command}`)) return undefined;
if (command === "gh") {
@@ -225,9 +213,7 @@ export class GitManager {
};
}
async runStackedAction(
raw: GitRunStackedActionInput,
): Promise<GitRunStackedActionResult> {
async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
const input = gitRunStackedActionInputSchema.parse(raw);
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
@@ -240,11 +226,7 @@ export class GitManager {
throw new Error("Cannot create a pull request from detached HEAD.");
}
const commit = await this.runCommitStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
);
const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
const push = wantsPush
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
@@ -353,10 +335,7 @@ export class GitManager {
throw asCommandNotFound("codex", error) ?? error;
}
const bodyFile = path.join(
os.tmpdir(),
`t3code-pr-body-${process.pid}-${randomUUID()}.md`,
);
const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
await fs.writeFile(bodyFile, generated.body, "utf8");
try {
@@ -410,10 +389,7 @@ export class GitManager {
}
}
private async findOpenPr(
cwd: string,
branch: string,
): Promise<OpenPrInfo | null> {
private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
const stdout = await this.runGhStdout(cwd, [
"pr",
"list",
@@ -446,10 +422,7 @@ export class GitManager {
branch: string,
upstreamRef: string | null,
): Promise<string> {
const configured = await this.gitCore.readConfigValue(
cwd,
`branch.${branch}.gh-merge-base`,
);
const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
if (configured) return configured;
if (upstreamRef) {
@@ -486,10 +459,7 @@ export class GitManager {
return result.stdout;
}
private async runGhCommand(
cwd: string,
args: readonly string[],
): Promise<ProcessRunResult> {
private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
try {
return await this.run("gh", args, {
cwd,
+5 -13
View File
@@ -5,23 +5,15 @@ import { runProcess } from "./processRunner";
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
await expect(
runProcess(
"node",
["-e", "process.stdout.write('x'.repeat(2048))"],
{ maxBufferBytes: 128 },
),
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
).rejects.toThrow("exceeded stdout buffer limit");
});
it("truncates output when outputMode is truncate", async () => {
const result = await runProcess(
"node",
["-e", "process.stdout.write('x'.repeat(2048))"],
{
maxBufferBytes: 128,
outputMode: "truncate",
},
);
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
maxBufferBytes: 128,
outputMode: "truncate",
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
+9 -38
View File
@@ -24,11 +24,7 @@ function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
}
function normalizeSpawnError(
command: string,
args: readonly string[],
error: unknown,
): Error {
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
}
@@ -38,9 +34,7 @@ function normalizeSpawnError(
return new Error(`Command not found: ${command}`);
}
return new Error(
`Failed to run ${commandLabel(command, args)}: ${error.message}`,
);
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
function normalizeExitError(
@@ -56,17 +50,11 @@ function normalizeExitError(
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
}
function normalizeStdinError(
command: string,
args: readonly string[],
error: unknown,
): Error {
function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
}
return new Error(
`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`,
);
return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
}
function normalizeBufferError(
@@ -161,22 +149,13 @@ export async function runProcess(
});
};
const appendOutput = (
stream: "stdout" | "stderr",
chunk: Buffer | string,
): Error | null => {
const chunkBuffer =
typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(
stdout,
stdoutBytes,
chunkBuffer,
maxBufferBytes,
);
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
@@ -189,12 +168,7 @@ export async function runProcess(
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(
stderr,
stderrBytes,
chunkBuffer,
maxBufferBytes,
);
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
@@ -241,10 +215,7 @@ export async function runProcess(
};
finalize(() => {
if (
!options.allowNonZeroExit &&
(timedOut || (code !== null && code !== 0))
) {
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
reject(normalizeExitError(command, args, result));
return;
}
+2 -10
View File
@@ -40,12 +40,7 @@ function resolveNodePtySpawnHelperPath(): string | null {
const candidates = [
path.join(packageDir, "build", "Release", "spawn-helper"),
path.join(packageDir, "build", "Debug", "spawn-helper"),
path.join(
packageDir,
"prebuilds",
`${process.platform}-${process.arch}`,
"spawn-helper",
),
path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"),
];
for (const candidate of candidates) {
@@ -128,10 +123,7 @@ export class NodePtyAdapter implements PtyAdapter {
cols: input.cols,
rows: input.rows,
env: input.env,
name:
globalThis.process.platform === "win32"
? "xterm-color"
: "xterm-256color",
name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
});
return new NodePtyProcess(ptyProcess);
}
+14 -17
View File
@@ -2,7 +2,11 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DEFAULT_TERMINAL_ID, type TerminalEvent, type TerminalOpenInput } from "@t3tools/contracts";
import {
DEFAULT_TERMINAL_ID,
type TerminalEvent,
type TerminalOpenInput,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
@@ -161,7 +165,10 @@ describe("TerminalManager", () => {
it("spawns lazily and reuses running terminal per thread", async () => {
const { manager, ptyAdapter } = makeManager();
const [first, second] = await Promise.all([manager.open(openInput()), manager.open(openInput())]);
const [first, second] = await Promise.all([
manager.open(openInput()),
manager.open(openInput()),
]);
const third = await manager.open(openInput());
expect(first.threadId).toBe("thread-1");
@@ -299,18 +306,14 @@ describe("TerminalManager", () => {
hasRunningSubprocess = true;
await waitFor(
() =>
events.some(
(event) => event.type === "activity" && event.hasRunningSubprocess === true,
),
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
1_200,
);
hasRunningSubprocess = false;
await waitFor(
() =>
events.some(
(event) => event.type === "activity" && event.hasRunningSubprocess === false,
),
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
1_200,
);
@@ -368,12 +371,8 @@ describe("TerminalManager", () => {
expect(defaultProcess.killed).toBe(true);
expect(sidecarProcess.killed).toBe(true);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
false,
);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
false,
);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false);
manager.dispose();
});
@@ -415,9 +414,7 @@ describe("TerminalManager", () => {
} else {
expect(
ptyAdapter.spawnInputs.some((input) =>
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(
input.shell,
),
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
),
).toBe(true);
}
+5 -21
View File
@@ -97,12 +97,7 @@ function resolveShellCandidates(shellResolver: () => string): string[] {
const requested = normalizeShellCommand(shellResolver());
if (process.platform === "win32") {
return uniqueShells([
requested,
process.env.ComSpec ?? null,
"powershell.exe",
"cmd.exe",
]);
return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
}
return uniqueShells([
@@ -405,11 +400,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => {
if (input.terminalId) {
await this.closeSession(
input.threadId,
input.terminalId,
input.deleteHistory === true,
);
await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
return;
}
@@ -490,13 +481,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
if (!ptyProcess) {
const detail =
lastSpawnError instanceof Error
? lastSpawnError.message
: "Terminal start failed";
lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
const tried =
shellCandidates.length > 0
? ` Tried shells: ${shellCandidates.join(", ")}.`
: "";
shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
throw new Error(`${detail}.${tried}`.trim());
}
@@ -942,10 +929,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
}
private async runWithThreadLock<T>(
threadId: string,
task: () => Promise<T>,
): Promise<T> {
private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
let release: () => void = () => {};
const current = new Promise<void>((resolve) => {
+2 -6
View File
@@ -224,9 +224,7 @@ describe("WebSocket Server", () => {
...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir),
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
...(options.terminalManager
? { terminalManager: options.terminalManager }
: {}),
...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
});
}
@@ -587,9 +585,7 @@ describe("WebSocket Server", () => {
it("returns errors from git.runStackedAction", async () => {
const gitManager = {
status: vi.fn(),
runStackedAction: vi
.fn()
.mockRejectedValue(new Error("Cannot push from detached HEAD.")),
runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")),
};
server = createTestServer({ cwd: "/test", gitManager });
+2 -2
View File
@@ -11,10 +11,10 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"highlight.js": "^11.11.1",
"lucide-react": "^0.563.0",
"react": "^19.0.0",
+18 -24
View File
@@ -262,24 +262,12 @@ export default function ChatView() {
}, []);
const toggleTerminalVisibility = useCallback(() => {
if (!activeThreadId) return;
const isOpen = Boolean(activeThread?.terminalOpen);
if (isOpen && api) {
if (typeof api.terminal.close === "function") {
void api.terminal.close({ threadId: activeThreadId }).catch(() => {
void api.terminal.write({ threadId: activeThreadId, data: "exit\n" }).catch(() => undefined);
});
} else {
void api.terminal.write({ threadId: activeThreadId, data: "exit\n" }).catch(() => undefined);
}
}
dispatch({
type: "SET_THREAD_TERMINAL_OPEN",
threadId: activeThreadId,
open: !isOpen,
open: !activeThread?.terminalOpen,
});
}, [activeThread?.terminalOpen, activeThreadId, api, dispatch]);
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
const splitTerminal = useCallback(() => {
if (!activeThreadId) return;
dispatch({
@@ -314,7 +302,9 @@ export default function ChatView() {
(terminalId: string) => {
if (!activeThreadId || !api) return;
const fallbackExitWrite = () =>
api.terminal.write({ threadId: activeThreadId, terminalId, data: "exit\n" }).catch(() => undefined);
api.terminal
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
.catch(() => undefined);
if ("close" in api.terminal && typeof api.terminal.close === "function") {
void api.terminal
.close({ threadId: activeThreadId, terminalId })
@@ -776,13 +766,15 @@ export default function ChatView() {
setIsSending(true);
try {
const turnAttachments = await Promise.all(
composerImagesSnapshot.map(async (image): Promise<ProviderSendTurnAttachmentInput> => ({
type: "image",
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
})),
composerImagesSnapshot.map(
async (image): Promise<ProviderSendTurnAttachmentInput> => ({
type: "image",
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
dataUrl: await readFileAsDataUrl(image.file),
}),
),
);
const shouldBootstrap =
previousMessages.length > 0 &&
@@ -794,7 +786,7 @@ export default function ChatView() {
latestPromptForBootstrap,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
).text
: (trimmed || undefined);
: trimmed || undefined;
await api.providers.sendTurn({
sessionId: sessionInfo.sessionId,
...(input ? { input } : {}),
@@ -1455,7 +1447,9 @@ export default function ChatView() {
<button
type="submit"
className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100"
disabled={isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)}
disabled={
isSending || isConnecting || (!prompt.trim() && composerImages.length === 0)
}
aria-label={
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
}
+31 -1
View File
@@ -12,6 +12,7 @@ import {
type Thread,
} from "../types";
import { useNativeApi } from "../hooks/useNativeApi";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
function formatRelativeTime(iso: string): string {
@@ -262,6 +263,22 @@ export default function Sidebar() {
const thread = state.threads.find((t) => t.id === threadId);
if (!thread) return;
const threadProject = state.projects.find((project) => project.id === thread.projectId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
// Stop active session if running
if (thread.session?.sessionId) {
@@ -284,8 +301,21 @@ export default function Sidebar() {
}
dispatch({ type: "DELETE_THREAD", threadId });
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await api.git.removeWorktree({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
});
} catch {
// Worktree deletion is best-effort and should not block thread deletion.
}
},
[api, dispatch, state.threads],
[api, dispatch, state.projects, state.threads],
);
useEffect(() => {
@@ -28,16 +28,11 @@ const MAX_DRAWER_HEIGHT_RATIO = 0.75;
function maxDrawerHeight(): number {
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
return Math.max(
MIN_DRAWER_HEIGHT,
Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO),
);
return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));
}
function clampDrawerHeight(height: number): number {
const safeHeight = Number.isFinite(height)
? height
: DEFAULT_THREAD_TERMINAL_HEIGHT;
const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
const maxHeight = maxDrawerHeight();
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
}
@@ -51,8 +46,7 @@ function terminalThemeFromApp(): ITheme {
const bodyStyles = getComputedStyle(document.body);
const background =
bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
const foreground =
bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
if (isDark) {
return {
@@ -146,8 +140,7 @@ function TerminalViewport({
lineHeight: 1.2,
fontSize: 12,
scrollback: 5_000,
fontFamily:
'"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
theme: terminalThemeFromApp(),
});
terminal.loadAddon(fitAddon);
@@ -538,8 +531,9 @@ export default function ThreadTerminalDrawer({
return indexByTerminal >= 0 ? indexByTerminal : 0;
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
const visibleTerminalIds =
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [resolvedActiveTerminalId];
const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
resolvedActiveTerminalId,
];
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders =
@@ -707,9 +701,7 @@ export default function ThreadTerminalDrawer({
<div
key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId
? "border-border"
: "border-border/70"
terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
}`}
onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) {
@@ -785,7 +777,8 @@ export default function ThreadTerminalDrawer({
<div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive = terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const isGroupActive =
terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
@@ -808,7 +801,9 @@ export default function ThreadTerminalDrawer({
</button>
)}
<div className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}>
<div
className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
>
{terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId;
return (
+4 -12
View File
@@ -55,9 +55,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access");
});
@@ -105,9 +103,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access");
});
@@ -221,9 +217,7 @@ describe("hydratePersistedState", () => {
},
{ id: "group-term-3", terminalIds: ["term-3"] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
it("defaults terminalHeight when hydrating v5 payloads", () => {
@@ -261,9 +255,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
});
});
+11 -8
View File
@@ -52,9 +52,7 @@ const persistedThreadSchema = z.object({
title: z.string().min(1),
model: z.string().min(1),
terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default(
DEFAULT_THREAD_TERMINAL_HEIGHT,
),
terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: z.string().trim().min(1).default(DEFAULT_THREAD_TERMINAL_ID),
terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
@@ -149,9 +147,10 @@ function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean,
): Thread {
const terminalIds = [...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
const safeTerminalIds =
terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const terminalIds = [
...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
];
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
@@ -197,7 +196,9 @@ function hydrateThread(
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [
...new Set((thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0)),
...new Set(
(thread.splitTerminalIds ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
),
].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
@@ -228,7 +229,9 @@ function hydrateThread(
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ??
+1 -5
View File
@@ -244,11 +244,7 @@ describe("store reducer thread continuity", () => {
terminalId: "term-3",
});
expect(next.threads[0]?.terminalIds).toEqual([
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
]);
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]);
expect(next.threads[0]?.terminalGroups).toEqual([
{
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
+12 -27
View File
@@ -101,17 +101,12 @@ function readPersistedState(): AppState {
try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) =>
window.localStorage.getItem(key),
);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState(
raw,
!rawCurrent && raw === rawCodethingV1,
);
const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false };
@@ -183,10 +178,7 @@ function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string
return uniqueGroupId;
}
function normalizeTerminalGroups(
thread: Thread,
terminalIds: string[],
): ThreadTerminalGroup[] {
function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>();
@@ -248,14 +240,13 @@ function normalizeThreadTerminals(thread: Thread): Thread {
const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(
terminalGroups,
activeTerminalId,
);
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
const activeGroupIndex =
activeGroupIndexFromId >= 0
? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
: activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ??
@@ -301,9 +292,9 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1;
const remainingTerminalsInClosedGroup = (
closedTerminalGroup?.terminalIds ?? []
).filter((id) => id !== terminalId);
const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
(id) => id !== terminalId,
);
const nextActiveTerminalId =
thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[
@@ -562,10 +553,7 @@ export function reducer(state: AppState, action: Action): AppState {
activeGroupIndex = terminalGroups.length - 1;
}
const existingGroupIndex = findGroupIndexByTerminalId(
terminalGroups,
action.terminalId,
);
const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex
@@ -674,10 +662,7 @@ export function reducer(state: AppState, action: Action): AppState {
threads: updateThread(state.threads, action.event.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread);
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
if (
action.event.type === "started" ||
action.event.type === "restarted"
) {
if (action.event.type === "started" || action.event.type === "restarted") {
runningTerminalIdSet.delete(action.event.terminalId);
} else if (action.event.type === "activity") {
if (action.event.hasRunningSubprocess) {
+1 -4
View File
@@ -57,10 +57,7 @@ describe("resolvePathLinkTarget", () => {
it("keeps absolute paths unchanged", () => {
expect(
resolvePathLinkTarget(
"/Users/julius/project/src/main.ts:12",
"/Users/julius/project",
),
resolvePathLinkTarget("/Users/julius/project/src/main.ts:12", "/Users/julius/project"),
).toBe("/Users/julius/project/src/main.ts:12");
});
});
+13 -38
View File
@@ -19,70 +19,45 @@ function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => {
expect(
isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel"),
).toBe(true);
expect(isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
});
it("matches Ctrl+J on non-macOS", () => {
expect(
isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32"),
).toBe(true);
expect(isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32")).toBe(true);
});
it("rejects wrong modifiers", () => {
expect(
isTerminalToggleShortcut(
event({ ctrlKey: true, shiftKey: true }),
"Win32",
),
).toBe(false);
expect(
isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel"),
).toBe(false);
expect(isTerminalToggleShortcut(event({ ctrlKey: true, shiftKey: true }), "Win32")).toBe(false);
expect(isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel")).toBe(
false,
);
});
it("rejects non-j keys", () => {
expect(
isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux"),
).toBe(false);
expect(isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux")).toBe(false);
});
});
describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => {
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"),
).toBe(true);
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"),
).toBe(true);
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux")).toBe(true);
expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel")).toBe(true);
});
it("matches Cmd+K on macOS", () => {
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"),
).toBe(true);
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")).toBe(true);
});
it("rejects Cmd+K on non-macOS", () => {
expect(
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32"),
).toBe(false);
expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32")).toBe(false);
});
it("rejects wrong modifiers", () => {
expect(
isTerminalClearShortcut(
event({ key: "l", ctrlKey: true, shiftKey: true }),
"Linux",
),
isTerminalClearShortcut(event({ key: "l", ctrlKey: true, shiftKey: true }), "Linux"),
).toBe(false);
expect(
isTerminalClearShortcut(
event({ key: "k", metaKey: true, altKey: true }),
"MacIntel",
),
isTerminalClearShortcut(event({ key: "k", metaKey: true, altKey: true }), "MacIntel"),
).toBe(false);
});
});
+1 -7
View File
@@ -31,13 +31,7 @@ export function isTerminalClearShortcut(
): boolean {
const key = event.key.toLowerCase();
if (
key === "l" &&
event.ctrlKey &&
!event.metaKey &&
!event.altKey &&
!event.shiftKey
) {
if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
return true;
}
+1
View File
@@ -5,6 +5,7 @@ import type { NativeApi } from "@t3tools/contracts";
interface DesktopBridge {
getWsUrl: () => string | null;
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
openExternal: (url: string) => Promise<boolean>;
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
id: "thread-1",
codexThreadId: null,
projectId: "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: [],
events: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
branch: null,
worktreePath: null,
...overrides,
};
}
describe("getOrphanedWorktreePathForThread", () => {
it("returns null when the target thread does not exist", () => {
const result = getOrphanedWorktreePathForThread([], "missing-thread");
expect(result).toBeNull();
});
it("returns null when the target thread has no worktree", () => {
const threads = [makeThread()];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBeNull();
});
it("returns the path when no other thread links to that worktree", () => {
const threads = [makeThread({ worktreePath: "/tmp/repo/worktrees/feature-a" })];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
it("returns null when another thread links to the same worktree", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-a" }),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBeNull();
});
it("ignores threads linked to different worktrees", () => {
const threads = [
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-b" }),
];
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
expect(result).toBe("/tmp/repo/worktrees/feature-a");
});
});
describe("formatWorktreePathForDisplay", () => {
it("shows only the last path segment for unix-like paths", () => {
const result = formatWorktreePathForDisplay(
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
);
expect(result).toBe("codething-4e609bb8");
});
it("normalizes windows separators before selecting the final segment", () => {
const result = formatWorktreePathForDisplay(
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
);
expect(result).toBe("codething-4e609bb8");
});
it("uses the final segment even when outside ~/.t3/worktrees", () => {
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree");
expect(result).toBe("my-worktree");
});
it("ignores trailing slashes", () => {
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree/");
expect(result).toBe("my-worktree");
});
});
+45
View File
@@ -0,0 +1,45 @@
import type { Thread } from "./types";
function normalizeWorktreePath(path: string | null): string | null {
const trimmed = path?.trim();
if (!trimmed) {
return null;
}
return trimmed;
}
export function getOrphanedWorktreePathForThread(
threads: readonly Thread[],
threadId: string,
): string | null {
const targetThread = threads.find((thread) => thread.id === threadId);
if (!targetThread) {
return null;
}
const targetWorktreePath = normalizeWorktreePath(targetThread.worktreePath);
if (!targetWorktreePath) {
return null;
}
const isShared = threads.some((thread) => {
if (thread.id === threadId) {
return false;
}
return normalizeWorktreePath(thread.worktreePath) === targetWorktreePath;
});
return isShared ? null : targetWorktreePath;
}
export function formatWorktreePathForDisplay(worktreePath: string): string {
const trimmed = worktreePath.trim();
if (!trimmed) {
return worktreePath;
}
const normalized = trimmed.replace(/\\/g, "/").replace(/\/+$/, "");
const parts = normalized.split("/");
const lastPart = parts[parts.length - 1]?.trim() ?? "";
return lastPart.length > 0 ? lastPart : trimmed;
}
+6
View File
@@ -60,6 +60,12 @@ export function createWsNativeApi(): NativeApi {
if (!window.desktopBridge) return null;
return window.desktopBridge.pickFolder();
},
confirm: async (message) => {
if (window.desktopBridge) {
return window.desktopBridge.confirm(message);
}
return window.confirm(message);
},
},
terminal: {
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
+1 -3
View File
@@ -30,9 +30,7 @@ describe("git contracts", () => {
it("accepts supported stacked actions", () => {
expect(gitStackedActionSchema.parse("commit")).toBe("commit");
expect(gitStackedActionSchema.parse("commit_push")).toBe("commit_push");
expect(gitStackedActionSchema.parse("commit_push_pr")).toBe(
"commit_push_pr",
);
expect(gitStackedActionSchema.parse("commit_push_pr")).toBe("commit_push_pr");
});
it("parses stacked action input", () => {
+3 -15
View File
@@ -85,23 +85,11 @@ export const gitStatusResultSchema = z.object({
.nullable(),
});
export const gitStackedActionSchema = z.enum([
"commit",
"commit_push",
"commit_push_pr",
]);
export const gitStackedActionSchema = z.enum(["commit", "commit_push", "commit_push_pr"]);
const gitCommitStepStatusSchema = z.enum(["created", "skipped_no_changes"]);
const gitPushStepStatusSchema = z.enum([
"pushed",
"skipped_not_requested",
"skipped_up_to_date",
]);
const gitPrStepStatusSchema = z.enum([
"created",
"opened_existing",
"skipped_not_requested",
]);
const gitPushStepStatusSchema = z.enum(["pushed", "skipped_not_requested", "skipped_up_to_date"]);
const gitPrStepStatusSchema = z.enum(["created", "opened_existing", "skipped_not_requested"]);
export const gitRunStackedActionInputSchema = z.object({
cwd: z.string().trim().min(1),
+2 -3
View File
@@ -56,6 +56,7 @@ export interface NativeApi {
};
dialogs: {
pickFolder: () => Promise<string | null>;
confirm: (message: string) => Promise<boolean>;
};
terminal: {
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
@@ -101,9 +102,7 @@ export interface NativeApi {
init: (input: GitInitInput) => Promise<void>;
// Stacked action API
status: (input: GitStatusInput) => Promise<GitStatusResult>;
runStackedAction: (
input: GitRunStackedActionInput,
) => Promise<GitRunStackedActionResult>;
runStackedAction: (input: GitRunStackedActionInput) => Promise<GitRunStackedActionResult>;
};
contextMenu: {
show: <T extends string>(
+1 -6
View File
@@ -36,12 +36,7 @@ export const terminalCloseInputSchema = terminalThreadInputSchema.extend({
deleteHistory: z.boolean().optional(),
});
export const terminalSessionStatusSchema = z.enum([
"starting",
"running",
"exited",
"error",
]);
export const terminalSessionStatusSchema = z.enum(["starting", "running", "exited", "error"]);
export const terminalSessionSnapshotSchema = z.object({
threadId: z.string().min(1),
+2 -2
View File
@@ -2,8 +2,7 @@
"$schema": "https://turbo.build/schema.json",
"globalEnv": [
"PORT",
"VITE_WS_URL",
"VITE_DEV_SERVER_URL",
"ELECTRON_RENDERER_PORT",
"T3CODE_LOG_WS_EVENTS",
"T3CODE_MODE",
@@ -20,6 +19,7 @@
},
"dev": {
"dependsOn": ["@t3tools/contracts#build"],
"env": ["VITE_DEV_SERVER_URL", "VITE_WS_URL"],
"cache": false,
"persistent": true
},