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
30 changed files with 245 additions and 369 deletions

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ child.on("exit", () => {
"Uncaught Error", "Uncaught Error",
"Uncaught TypeError", "Uncaught TypeError",
"Uncaught ReferenceError", "Uncaught ReferenceError",
"ERR_FILE_NOT_FOUND",
]; ];
const failures = fatalPatterns.filter((pattern) => output.includes(pattern)); const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
+95 -24
View File
@@ -17,8 +17,11 @@ const CONFIRM_CHANNEL = "desktop:confirm";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const ROOT_DIR = path.resolve(__dirname, "../../.."); 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 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 STATE_DIR = path.join(os.homedir(), ".t3", "userdata");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -31,22 +34,16 @@ let restartAttempt = 0;
let restartTimer: ReturnType<typeof setTimeout> | null = null; let restartTimer: ReturnType<typeof setTimeout> | null = null;
let isQuitting = false; let isQuitting = false;
async function reserveLoopbackPort(): Promise<number> { function resolveBackendPort(raw: string | undefined): number {
return new Promise((resolve, reject) => { if (!raw || raw.trim().length === 0) {
const probe = net.createServer(); return DEFAULT_BACKEND_PORT;
probe.listen(0, "127.0.0.1", () => { }
const address = probe.address();
const port = typeof address === "object" && address !== null ? address.port : 0; const parsed = Number(raw);
probe.close(() => { if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65_535) {
if (port > 0) { throw new Error(`Invalid T3CODE_PORT: ${raw}`);
resolve(port); }
return; return parsed;
}
reject(new Error("Failed to reserve backend port"));
});
});
probe.on("error", reject);
});
} }
function backendEnv(): NodeJS.ProcessEnv { function backendEnv(): NodeJS.ProcessEnv {
@@ -129,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 { function registerIpcHandlers(): void {
ipcMain.removeHandler(PICK_FOLDER_CHANNEL); ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => { ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
@@ -226,10 +293,7 @@ function createWindow(): BrowserWindow {
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string); void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
window.webContents.openDevTools({ mode: "detach" }); window.webContents.openDevTools({ mode: "detach" });
} else { } else {
if (!fs.existsSync(WEB_ENTRY)) { void window.loadURL(backendHttpUrl());
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
}
void window.loadFile(WEB_ENTRY);
} }
window.on("closed", () => { window.on("closed", () => {
@@ -242,13 +306,17 @@ function createWindow(): BrowserWindow {
} }
async function bootstrap(): Promise<void> { 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"); 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; process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
registerIpcHandlers(); registerIpcHandlers();
startBackend(); startBackend();
if (!isDevelopment) {
await waitForBackendReady();
}
mainWindow = createWindow(); mainWindow = createWindow();
} }
@@ -258,7 +326,10 @@ app.on("before-quit", () => {
}); });
app.whenReady().then(() => { app.whenReady().then(() => {
void bootstrap(); void bootstrap().catch((error) => {
console.error("[desktop] failed to bootstrap app", error);
app.quit();
});
app.on("activate", () => { app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) { if (BrowserWindow.getAllWindows().length === 0) {
+10 -3
View File
@@ -21,10 +21,16 @@ function createSendTurnHarness() {
}; };
const requireSession = vi 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); .mockReturnValue(context);
const sendRequest = vi 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({ .mockResolvedValue({
turn: { turn: {
id: "turn_1", id: "turn_1",
@@ -109,7 +115,8 @@ describe("isRecoverableThreadResumeError", () => {
describe("sendTurn", () => { describe("sendTurn", () => {
it("sends text and image user input items to turn/start", async () => { 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({ const result = await manager.sendTurn({
sessionId: "sess_1", sessionId: "sess_1",
+2 -4
View File
@@ -258,8 +258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
} }
const turnInput: Array< const turnInput: Array<
| { type: "text"; text: string; text_elements: [] } { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
| { type: "image"; url: string }
> = []; > = [];
if (input.input) { if (input.input) {
turnInput.push({ turnInput.push({
@@ -283,8 +282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turnStartParams: { const turnStartParams: {
threadId: string; threadId: string;
input: Array< input: Array<
| { type: "text"; text: string; text_elements: [] } { type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
| { type: "image"; url: string }
>; >;
model?: string; model?: string;
effort?: string; effort?: string;
+1 -4
View File
@@ -28,8 +28,5 @@ export interface TextGenerationService {
generateCommitMessage( generateCommitMessage(
input: CommitMessageGenerationInput, input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>; ): Promise<CommitMessageGenerationResult>;
generatePrContent( generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
input: PrContentGenerationInput,
): Promise<PrContentGenerationResult>;
} }
+1 -5
View File
@@ -569,11 +569,7 @@ describe("git integration", () => {
expect(context!.stagedSummary.length).toBeGreaterThan(0); expect(context!.stagedSummary.length).toBeGreaterThan(0);
expect(context!.stagedPatch.length).toBeGreaterThan(0); expect(context!.stagedPatch.length).toBeGreaterThan(0);
const created = await core.commit( const created = await core.commit(tmp.path, "Add README update", "- include updated content");
tmp.path,
"Add README update",
"- include updated content",
);
expect(created.commitSha.length).toBeGreaterThan(0); expect(created.commitSha.length).toBeGreaterThan(0);
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update"); expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
}); });
+2 -11
View File
@@ -224,21 +224,12 @@ export class GitCoreService {
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> { async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
await this.git(cwd, ["add", "-A"]); await this.git(cwd, ["add", "-A"]);
const stagedSummary = await this.gitStdout(cwd, [ const stagedSummary = await this.gitStdout(cwd, ["diff", "--cached", "--name-status"]);
"diff",
"--cached",
"--name-status",
]);
if (trimStdout(stagedSummary).length === 0) { if (trimStdout(stagedSummary).length === 0) {
return null; return null;
} }
const stagedPatch = await this.gitStdout(cwd, [ const stagedPatch = await this.gitStdout(cwd, ["diff", "--cached", "--patch", "--minimal"]);
"diff",
"--cached",
"--patch",
"--minimal",
]);
return { return {
stagedSummary, stagedSummary,
+4 -13
View File
@@ -5,11 +5,7 @@ import path from "node:path";
import { afterEach, describe, expect, it } from "vitest"; import { afterEach, describe, expect, it } from "vitest";
import { GitManager } from "./gitManager"; import { GitManager } from "./gitManager";
import { import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
interface FakeGhScenario { interface FakeGhScenario {
prListSequence?: string[]; prListSequence?: string[];
@@ -71,9 +67,7 @@ async function createBareRemote(): Promise<string> {
return remoteDir; return remoteDir;
} }
function createTextGenerator( function createTextGenerator(overrides: Partial<FakeGitTextGenerator> = {}): FakeGitTextGenerator {
overrides: Partial<FakeGitTextGenerator> = {},
): FakeGitTextGenerator {
return { return {
generateCommitMessage: async () => ({ generateCommitMessage: async () => ({
subject: "Implement stacked git actions", subject: "Implement stacked git actions",
@@ -126,8 +120,7 @@ function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
if (args[0] === "pr" && args[1] === "create") { if (args[0] === "pr" && args[1] === "create") {
return { return {
stdout: stdout:
(scenario.createdPrUrl ?? (scenario.createdPrUrl ?? "https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
stderr: "", stderr: "",
code: 0, code: 0,
signal: null, signal: null,
@@ -376,9 +369,7 @@ describe("GitManager", () => {
expect(result.pr.status).toBe("opened_existing"); expect(result.pr.status).toBe("opened_existing");
expect(result.pr.number).toBe(42); expect(result.pr.number).toBe(42);
expect( expect(ghCalls.some((call) => call.startsWith("pr view feature/existing-pr --web"))).toBe(true);
ghCalls.some((call) => call.startsWith("pr view feature/existing-pr --web")),
).toBe(true);
}); });
it("creates PR when one does not already exist", async () => { it("creates PR when one does not already exist", async () => {
+10 -40
View File
@@ -20,11 +20,7 @@ import type {
} from "./coreServices"; } from "./coreServices";
import { CodexTextGenerator } from "./codexTextGenerator"; import { CodexTextGenerator } from "./codexTextGenerator";
import { GitCoreService } from "./git"; import { GitCoreService } from "./git";
import { import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
type ProcessRunOptions,
type ProcessRunResult,
runProcess,
} from "./processRunner";
const GH_CLI_TIMEOUT_MS = 30_000; const GH_CLI_TIMEOUT_MS = 30_000;
@@ -58,11 +54,7 @@ function parseOpenPrList(raw: unknown): OpenPrInfo[] {
const url = record.url; const url = record.url;
const baseRefName = record.baseRefName; const baseRefName = record.baseRefName;
const headRefName = record.headRefName; const headRefName = record.headRefName;
if ( if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
typeof number !== "number" ||
!Number.isInteger(number) ||
number <= 0
) {
continue; continue;
} }
if ( if (
@@ -98,8 +90,7 @@ function sanitizeCommitMessage(
): CommitMessageGenerationResult { ): CommitMessageGenerationResult {
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? ""; const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const subject = rawSubject.replace(/[.]+$/g, "").trim(); const subject = rawSubject.replace(/[.]+$/g, "").trim();
const safeSubject = const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
subject.length > 0 ? subject.slice(0, 72).trimEnd() : "Update project files";
return { return {
subject: safeSubject, subject: safeSubject,
body: generated.body.trim(), body: generated.body.trim(),
@@ -143,10 +134,7 @@ function extractBranchFromRef(ref: string): string {
return normalized.slice(firstSlash + 1).trim(); return normalized.slice(firstSlash + 1).trim();
} }
function asCommandNotFound( function asCommandNotFound(command: string, error: unknown): Error | undefined {
command: string,
error: unknown,
): Error | undefined {
if (!(error instanceof Error)) return undefined; if (!(error instanceof Error)) return undefined;
if (!error.message.includes(`Command not found: ${command}`)) return undefined; if (!error.message.includes(`Command not found: ${command}`)) return undefined;
if (command === "gh") { if (command === "gh") {
@@ -225,9 +213,7 @@ export class GitManager {
}; };
} }
async runStackedAction( async runStackedAction(raw: GitRunStackedActionInput): Promise<GitRunStackedActionResult> {
raw: GitRunStackedActionInput,
): Promise<GitRunStackedActionResult> {
const input = gitRunStackedActionInputSchema.parse(raw); const input = gitRunStackedActionInputSchema.parse(raw);
const wantsPush = input.action !== "commit"; const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr"; 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."); throw new Error("Cannot create a pull request from detached HEAD.");
} }
const commit = await this.runCommitStep( const commit = await this.runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
input.cwd,
initialStatus.branch,
input.commitMessage,
);
const push = wantsPush const push = wantsPush
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch) ? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
@@ -353,10 +335,7 @@ export class GitManager {
throw asCommandNotFound("codex", error) ?? error; throw asCommandNotFound("codex", error) ?? error;
} }
const bodyFile = path.join( const bodyFile = path.join(os.tmpdir(), `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
os.tmpdir(),
`t3code-pr-body-${process.pid}-${randomUUID()}.md`,
);
await fs.writeFile(bodyFile, generated.body, "utf8"); await fs.writeFile(bodyFile, generated.body, "utf8");
try { try {
@@ -410,10 +389,7 @@ export class GitManager {
} }
} }
private async findOpenPr( private async findOpenPr(cwd: string, branch: string): Promise<OpenPrInfo | null> {
cwd: string,
branch: string,
): Promise<OpenPrInfo | null> {
const stdout = await this.runGhStdout(cwd, [ const stdout = await this.runGhStdout(cwd, [
"pr", "pr",
"list", "list",
@@ -446,10 +422,7 @@ export class GitManager {
branch: string, branch: string,
upstreamRef: string | null, upstreamRef: string | null,
): Promise<string> { ): Promise<string> {
const configured = await this.gitCore.readConfigValue( const configured = await this.gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
cwd,
`branch.${branch}.gh-merge-base`,
);
if (configured) return configured; if (configured) return configured;
if (upstreamRef) { if (upstreamRef) {
@@ -486,10 +459,7 @@ export class GitManager {
return result.stdout; return result.stdout;
} }
private async runGhCommand( private async runGhCommand(cwd: string, args: readonly string[]): Promise<ProcessRunResult> {
cwd: string,
args: readonly string[],
): Promise<ProcessRunResult> {
try { try {
return await this.run("gh", args, { return await this.run("gh", args, {
cwd, cwd,
+5 -13
View File
@@ -5,23 +5,15 @@ import { runProcess } from "./processRunner";
describe("runProcess", () => { describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => { it("fails when output exceeds max buffer in default mode", async () => {
await expect( await expect(
runProcess( runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
"node",
["-e", "process.stdout.write('x'.repeat(2048))"],
{ maxBufferBytes: 128 },
),
).rejects.toThrow("exceeded stdout buffer limit"); ).rejects.toThrow("exceeded stdout buffer limit");
}); });
it("truncates output when outputMode is truncate", async () => { it("truncates output when outputMode is truncate", async () => {
const result = await runProcess( const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
"node", maxBufferBytes: 128,
["-e", "process.stdout.write('x'.repeat(2048))"], outputMode: "truncate",
{ });
maxBufferBytes: 128,
outputMode: "truncate",
},
);
expect(result.code).toBe(0); expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128); 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(" "); return [command, ...args].join(" ");
} }
function normalizeSpawnError( function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
command: string,
args: readonly string[],
error: unknown,
): Error {
if (!(error instanceof Error)) { if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`); 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(`Command not found: ${command}`);
} }
return new Error( return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
`Failed to run ${commandLabel(command, args)}: ${error.message}`,
);
} }
function normalizeExitError( function normalizeExitError(
@@ -56,17 +50,11 @@ function normalizeExitError(
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`); return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
} }
function normalizeStdinError( function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
command: string,
args: readonly string[],
error: unknown,
): Error {
if (!(error instanceof 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)}.`);
} }
return new Error( return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`,
);
} }
function normalizeBufferError( function normalizeBufferError(
@@ -161,22 +149,13 @@ export async function runProcess(
}); });
}; };
const appendOutput = ( const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
stream: "stdout" | "stderr", const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
chunk: Buffer | string,
): Error | null => {
const chunkBuffer =
typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString(); const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length; const byteLength = chunkBuffer.length;
if (stream === "stdout") { if (stream === "stdout") {
if (outputMode === "truncate") { if (outputMode === "truncate") {
const appended = appendChunkWithinLimit( const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
stdout,
stdoutBytes,
chunkBuffer,
maxBufferBytes,
);
stdout = appended.next; stdout = appended.next;
stdoutBytes = appended.nextBytes; stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated; stdoutTruncated = stdoutTruncated || appended.truncated;
@@ -189,12 +168,7 @@ export async function runProcess(
} }
} else { } else {
if (outputMode === "truncate") { if (outputMode === "truncate") {
const appended = appendChunkWithinLimit( const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
stderr,
stderrBytes,
chunkBuffer,
maxBufferBytes,
);
stderr = appended.next; stderr = appended.next;
stderrBytes = appended.nextBytes; stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated; stderrTruncated = stderrTruncated || appended.truncated;
@@ -241,10 +215,7 @@ export async function runProcess(
}; };
finalize(() => { finalize(() => {
if ( if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
!options.allowNonZeroExit &&
(timedOut || (code !== null && code !== 0))
) {
reject(normalizeExitError(command, args, result)); reject(normalizeExitError(command, args, result));
return; return;
} }
+2 -10
View File
@@ -40,12 +40,7 @@ function resolveNodePtySpawnHelperPath(): string | null {
const candidates = [ const candidates = [
path.join(packageDir, "build", "Release", "spawn-helper"), path.join(packageDir, "build", "Release", "spawn-helper"),
path.join(packageDir, "build", "Debug", "spawn-helper"), path.join(packageDir, "build", "Debug", "spawn-helper"),
path.join( path.join(packageDir, "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper"),
packageDir,
"prebuilds",
`${process.platform}-${process.arch}`,
"spawn-helper",
),
]; ];
for (const candidate of candidates) { for (const candidate of candidates) {
@@ -128,10 +123,7 @@ export class NodePtyAdapter implements PtyAdapter {
cols: input.cols, cols: input.cols,
rows: input.rows, rows: input.rows,
env: input.env, env: input.env,
name: name: globalThis.process.platform === "win32" ? "xterm-color" : "xterm-256color",
globalThis.process.platform === "win32"
? "xterm-color"
: "xterm-256color",
}); });
return new NodePtyProcess(ptyProcess); return new NodePtyProcess(ptyProcess);
} }
+14 -17
View File
@@ -2,7 +2,11 @@ import fs from "node:fs";
import os from "node:os"; import os from "node:os";
import path from "node:path"; 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 { afterEach, describe, expect, it } from "vitest";
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter"; import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
@@ -161,7 +165,10 @@ describe("TerminalManager", () => {
it("spawns lazily and reuses running terminal per thread", async () => { it("spawns lazily and reuses running terminal per thread", async () => {
const { manager, ptyAdapter } = makeManager(); 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()); const third = await manager.open(openInput());
expect(first.threadId).toBe("thread-1"); expect(first.threadId).toBe("thread-1");
@@ -299,18 +306,14 @@ describe("TerminalManager", () => {
hasRunningSubprocess = true; hasRunningSubprocess = true;
await waitFor( await waitFor(
() => () =>
events.some( events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
(event) => event.type === "activity" && event.hasRunningSubprocess === true,
),
1_200, 1_200,
); );
hasRunningSubprocess = false; hasRunningSubprocess = false;
await waitFor( await waitFor(
() => () =>
events.some( events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
(event) => event.type === "activity" && event.hasRunningSubprocess === false,
),
1_200, 1_200,
); );
@@ -368,12 +371,8 @@ describe("TerminalManager", () => {
expect(defaultProcess.killed).toBe(true); expect(defaultProcess.killed).toBe(true);
expect(sidecarProcess.killed).toBe(true); expect(sidecarProcess.killed).toBe(true);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe( expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false);
false, expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false);
);
expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
false,
);
manager.dispose(); manager.dispose();
}); });
@@ -415,9 +414,7 @@ describe("TerminalManager", () => {
} else { } else {
expect( expect(
ptyAdapter.spawnInputs.some((input) => ptyAdapter.spawnInputs.some((input) =>
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes( ["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
input.shell,
),
), ),
).toBe(true); ).toBe(true);
} }
+5 -21
View File
@@ -97,12 +97,7 @@ function resolveShellCandidates(shellResolver: () => string): string[] {
const requested = normalizeShellCommand(shellResolver()); const requested = normalizeShellCommand(shellResolver());
if (process.platform === "win32") { if (process.platform === "win32") {
return uniqueShells([ return uniqueShells([requested, process.env.ComSpec ?? null, "powershell.exe", "cmd.exe"]);
requested,
process.env.ComSpec ?? null,
"powershell.exe",
"cmd.exe",
]);
} }
return uniqueShells([ return uniqueShells([
@@ -405,11 +400,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
const input = terminalCloseInputSchema.parse(raw); const input = terminalCloseInputSchema.parse(raw);
await this.runWithThreadLock(input.threadId, async () => { await this.runWithThreadLock(input.threadId, async () => {
if (input.terminalId) { if (input.terminalId) {
await this.closeSession( await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
input.threadId,
input.terminalId,
input.deleteHistory === true,
);
return; return;
} }
@@ -490,13 +481,9 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
if (!ptyProcess) { if (!ptyProcess) {
const detail = const detail =
lastSpawnError instanceof Error lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
? lastSpawnError.message
: "Terminal start failed";
const tried = const tried =
shellCandidates.length > 0 shellCandidates.length > 0 ? ` Tried shells: ${shellCandidates.join(", ")}.` : "";
? ` Tried shells: ${shellCandidates.join(", ")}.`
: "";
throw new Error(`${detail}.${tried}`.trim()); throw new Error(`${detail}.${tried}`.trim());
} }
@@ -942,10 +929,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`); return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
} }
private async runWithThreadLock<T>( private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
threadId: string,
task: () => Promise<T>,
): Promise<T> {
const previous = this.threadLocks.get(threadId) ?? Promise.resolve(); const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
let release: () => void = () => {}; let release: () => void = () => {};
const current = new Promise<void>((resolve) => { const current = new Promise<void>((resolve) => {
+2 -6
View File
@@ -224,9 +224,7 @@ describe("WebSocket Server", () => {
...(options.authToken ? { authToken: options.authToken } : {}), ...(options.authToken ? { authToken: options.authToken } : {}),
projectRegistry: new ProjectRegistry(stateDir), projectRegistry: new ProjectRegistry(stateDir),
...(options.gitManager ? { gitManager: options.gitManager as never } : {}), ...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
...(options.terminalManager ...(options.terminalManager ? { terminalManager: options.terminalManager } : {}),
? { terminalManager: options.terminalManager }
: {}),
}); });
} }
@@ -587,9 +585,7 @@ describe("WebSocket Server", () => {
it("returns errors from git.runStackedAction", async () => { it("returns errors from git.runStackedAction", async () => {
const gitManager = { const gitManager = {
status: vi.fn(), status: vi.fn(),
runStackedAction: vi runStackedAction: vi.fn().mockRejectedValue(new Error("Cannot push from detached HEAD.")),
.fn()
.mockRejectedValue(new Error("Cannot push from detached HEAD.")),
}; };
server = createTestServer({ cwd: "/test", gitManager }); server = createTestServer({ cwd: "/test", gitManager });
+2 -2
View File
@@ -11,10 +11,10 @@
"test": "vitest run --passWithNoTests" "test": "vitest run --passWithNoTests"
}, },
"dependencies": { "dependencies": {
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@t3tools/contracts": "workspace:*", "@t3tools/contracts": "workspace:*",
"@tanstack/react-query": "^5.90.0", "@tanstack/react-query": "^5.90.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"highlight.js": "^11.11.1", "highlight.js": "^11.11.1",
"lucide-react": "^0.563.0", "lucide-react": "^0.563.0",
"react": "^19.0.0", "react": "^19.0.0",
+16 -10
View File
@@ -302,7 +302,9 @@ export default function ChatView() {
(terminalId: string) => { (terminalId: string) => {
if (!activeThreadId || !api) return; if (!activeThreadId || !api) return;
const fallbackExitWrite = () => 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") { if ("close" in api.terminal && typeof api.terminal.close === "function") {
void api.terminal void api.terminal
.close({ threadId: activeThreadId, terminalId }) .close({ threadId: activeThreadId, terminalId })
@@ -764,13 +766,15 @@ export default function ChatView() {
setIsSending(true); setIsSending(true);
try { try {
const turnAttachments = await Promise.all( const turnAttachments = await Promise.all(
composerImagesSnapshot.map(async (image): Promise<ProviderSendTurnAttachmentInput> => ({ composerImagesSnapshot.map(
type: "image", async (image): Promise<ProviderSendTurnAttachmentInput> => ({
name: image.name, type: "image",
mimeType: image.mimeType, name: image.name,
sizeBytes: image.sizeBytes, mimeType: image.mimeType,
dataUrl: await readFileAsDataUrl(image.file), sizeBytes: image.sizeBytes,
})), dataUrl: await readFileAsDataUrl(image.file),
}),
),
); );
const shouldBootstrap = const shouldBootstrap =
previousMessages.length > 0 && previousMessages.length > 0 &&
@@ -782,7 +786,7 @@ export default function ChatView() {
latestPromptForBootstrap, latestPromptForBootstrap,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS, PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
).text ).text
: (trimmed || undefined); : trimmed || undefined;
await api.providers.sendTurn({ await api.providers.sendTurn({
sessionId: sessionInfo.sessionId, sessionId: sessionInfo.sessionId,
...(input ? { input } : {}), ...(input ? { input } : {}),
@@ -1443,7 +1447,9 @@ export default function ChatView() {
<button <button
type="submit" 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" 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={ aria-label={
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message" isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
} }
@@ -28,16 +28,11 @@ const MAX_DRAWER_HEIGHT_RATIO = 0.75;
function maxDrawerHeight(): number { function maxDrawerHeight(): number {
if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT; if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
return Math.max( return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));
MIN_DRAWER_HEIGHT,
Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO),
);
} }
function clampDrawerHeight(height: number): number { function clampDrawerHeight(height: number): number {
const safeHeight = Number.isFinite(height) const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
? height
: DEFAULT_THREAD_TERMINAL_HEIGHT;
const maxHeight = maxDrawerHeight(); const maxHeight = maxDrawerHeight();
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight); 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 bodyStyles = getComputedStyle(document.body);
const background = const background =
bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)"); bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
const foreground = const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
if (isDark) { if (isDark) {
return { return {
@@ -146,8 +140,7 @@ function TerminalViewport({
lineHeight: 1.2, lineHeight: 1.2,
fontSize: 12, fontSize: 12,
scrollback: 5_000, scrollback: 5_000,
fontFamily: fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
'"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
theme: terminalThemeFromApp(), theme: terminalThemeFromApp(),
}); });
terminal.loadAddon(fitAddon); terminal.loadAddon(fitAddon);
@@ -538,8 +531,9 @@ export default function ThreadTerminalDrawer({
return indexByTerminal >= 0 ? indexByTerminal : 0; return indexByTerminal >= 0 ? indexByTerminal : 0;
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]); }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
const visibleTerminalIds = const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [resolvedActiveTerminalId]; resolvedActiveTerminalId,
];
const hasTerminalSidebar = normalizedTerminalIds.length > 1; const hasTerminalSidebar = normalizedTerminalIds.length > 1;
const isSplitView = visibleTerminalIds.length > 1; const isSplitView = visibleTerminalIds.length > 1;
const showGroupHeaders = const showGroupHeaders =
@@ -707,9 +701,7 @@ export default function ThreadTerminalDrawer({
<div <div
key={terminalId} key={terminalId}
className={`min-h-0 min-w-0 border-l first:border-l-0 ${ className={`min-h-0 min-w-0 border-l first:border-l-0 ${
terminalId === resolvedActiveTerminalId terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
? "border-border"
: "border-border/70"
}`} }`}
onMouseDown={() => { onMouseDown={() => {
if (terminalId !== resolvedActiveTerminalId) { 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"> <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
{resolvedTerminalGroups.map((terminalGroup, groupIndex) => { {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
const isGroupActive = terminalGroup.terminalIds.includes(resolvedActiveTerminalId); const isGroupActive =
terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
const groupActiveTerminalId = isGroupActive const groupActiveTerminalId = isGroupActive
? resolvedActiveTerminalId ? resolvedActiveTerminalId
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId); : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
@@ -808,7 +801,9 @@ export default function ThreadTerminalDrawer({
</button> </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) => { {terminalGroup.terminalIds.map((terminalId) => {
const isActive = terminalId === resolvedActiveTerminalId; const isActive = terminalId === resolvedActiveTerminalId;
return ( return (
+4 -12
View File
@@ -55,9 +55,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.terminalGroups).toEqual([ expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] }, { id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]); ]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe( expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false); expect(hydrated?.threads[0]?.messages[0]?.streaming).toBe(false);
expect(hydrated?.runtimeMode).toBe("full-access"); expect(hydrated?.runtimeMode).toBe("full-access");
}); });
@@ -105,9 +103,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.terminalGroups).toEqual([ expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] }, { id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]); ]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe( expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
expect(hydrated?.activeThreadId).toBe("t-1"); expect(hydrated?.activeThreadId).toBe("t-1");
expect(hydrated?.runtimeMode).toBe("full-access"); expect(hydrated?.runtimeMode).toBe("full-access");
}); });
@@ -221,9 +217,7 @@ describe("hydratePersistedState", () => {
}, },
{ id: "group-term-3", terminalIds: ["term-3"] }, { id: "group-term-3", terminalIds: ["term-3"] },
]); ]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe( expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
}); });
it("defaults terminalHeight when hydrating v5 payloads", () => { it("defaults terminalHeight when hydrating v5 payloads", () => {
@@ -261,9 +255,7 @@ describe("hydratePersistedState", () => {
expect(hydrated?.threads[0]?.terminalGroups).toEqual([ expect(hydrated?.threads[0]?.terminalGroups).toEqual([
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] }, { id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
]); ]);
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe( expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
);
}); });
}); });
+11 -8
View File
@@ -52,9 +52,7 @@ const persistedThreadSchema = z.object({
title: z.string().min(1), title: z.string().min(1),
model: z.string().min(1), model: z.string().min(1),
terminalOpen: z.boolean().default(false), terminalOpen: z.boolean().default(false),
terminalHeight: z.number().int().min(120).max(4_096).default( terminalHeight: z.number().int().min(120).max(4_096).default(DEFAULT_THREAD_TERMINAL_HEIGHT),
DEFAULT_THREAD_TERMINAL_HEIGHT,
),
terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]), terminalIds: z.array(z.string().trim().min(1)).default([DEFAULT_THREAD_TERMINAL_ID]),
activeTerminalId: 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([]), terminalGroups: z.array(persistedTerminalGroupSchema).default([]),
@@ -149,9 +147,10 @@ function hydrateThread(
thread: z.infer<typeof persistedThreadSchema>, thread: z.infer<typeof persistedThreadSchema>,
isLegacyPayload: boolean, isLegacyPayload: boolean,
): Thread { ): Thread {
const terminalIds = [...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))]; const terminalIds = [
const safeTerminalIds = ...new Set(thread.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID]; ];
const safeTerminalIds = terminalIds.length > 0 ? terminalIds : [DEFAULT_THREAD_TERMINAL_ID];
const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId) const activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
? thread.activeTerminalId ? thread.activeTerminalId
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID); : (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
@@ -197,7 +196,9 @@ function hydrateThread(
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") { if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
const splitTerminalIds = [ 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)); ].filter((terminalId) => safeTerminalIdSet.has(terminalId));
if (splitTerminalIds.length >= 2) { if (splitTerminalIds.length >= 2) {
const splitGroupTerminalIds = splitTerminalIds.slice(0, 2); const splitGroupTerminalIds = splitTerminalIds.slice(0, 2);
@@ -228,7 +229,9 @@ function hydrateThread(
const activeGroupIndex = const activeGroupIndex =
activeGroupIndexFromId >= 0 activeGroupIndexFromId >= 0
? activeGroupIndexFromId ? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0); : activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId = const activeTerminalGroupId =
normalizedGroups[activeGroupIndex]?.id ?? normalizedGroups[activeGroupIndex]?.id ??
normalizedGroups[0]?.id ?? normalizedGroups[0]?.id ??
+1 -5
View File
@@ -244,11 +244,7 @@ describe("store reducer thread continuity", () => {
terminalId: "term-3", terminalId: "term-3",
}); });
expect(next.threads[0]?.terminalIds).toEqual([ expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]);
DEFAULT_THREAD_TERMINAL_ID,
"term-2",
"term-3",
]);
expect(next.threads[0]?.terminalGroups).toEqual([ expect(next.threads[0]?.terminalGroups).toEqual([
{ {
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
+12 -27
View File
@@ -101,17 +101,12 @@ function readPersistedState(): AppState {
try { try {
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY); const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => const legacyValues = LEGACY_PERSISTED_STATE_KEYS.map((key) => window.localStorage.getItem(key));
window.localStorage.getItem(key),
);
const rawLegacy = legacyValues.find((value) => value !== null) ?? null; const rawLegacy = legacyValues.find((value) => value !== null) ?? null;
const raw = rawCurrent ?? rawLegacy; const raw = rawCurrent ?? rawLegacy;
if (!raw) return initialState; if (!raw) return initialState;
const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1"); const rawCodethingV1 = window.localStorage.getItem("codething:renderer-state:v1");
const hydrated = hydratePersistedState( const hydrated = hydratePersistedState(raw, !rawCurrent && raw === rawCodethingV1);
raw,
!rawCurrent && raw === rawCodethingV1,
);
if (!hydrated) return initialState; if (!hydrated) return initialState;
return { ...hydrated, diffOpen: false }; return { ...hydrated, diffOpen: false };
@@ -183,10 +178,7 @@ function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string
return uniqueGroupId; return uniqueGroupId;
} }
function normalizeTerminalGroups( function normalizeTerminalGroups(thread: Thread, terminalIds: string[]): ThreadTerminalGroup[] {
thread: Thread,
terminalIds: string[],
): ThreadTerminalGroup[] {
const validTerminalIdSet = new Set(terminalIds); const validTerminalIdSet = new Set(terminalIds);
const assignedTerminalIds = new Set<string>(); const assignedTerminalIds = new Set<string>();
const usedGroupIds = new Set<string>(); const usedGroupIds = new Set<string>();
@@ -248,14 +240,13 @@ function normalizeThreadTerminals(thread: Thread): Thread {
const activeGroupIndexFromId = terminalGroups.findIndex( const activeGroupIndexFromId = terminalGroups.findIndex(
(group) => group.id === thread.activeTerminalGroupId, (group) => group.id === thread.activeTerminalGroupId,
); );
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId( const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(terminalGroups, activeTerminalId);
terminalGroups,
activeTerminalId,
);
const activeGroupIndex = const activeGroupIndex =
activeGroupIndexFromId >= 0 activeGroupIndexFromId >= 0
? activeGroupIndexFromId ? activeGroupIndexFromId
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0); : activeGroupIndexFromTerminal >= 0
? activeGroupIndexFromTerminal
: 0;
const activeTerminalGroupId = const activeTerminalGroupId =
terminalGroups[activeGroupIndex]?.id ?? terminalGroups[activeGroupIndex]?.id ??
terminalGroups[0]?.id ?? terminalGroups[0]?.id ??
@@ -301,9 +292,9 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
const closedTerminalGroupIndex = closedTerminalGroup const closedTerminalGroupIndex = closedTerminalGroup
? closedTerminalGroup.terminalIds.indexOf(terminalId) ? closedTerminalGroup.terminalIds.indexOf(terminalId)
: -1; : -1;
const remainingTerminalsInClosedGroup = ( const remainingTerminalsInClosedGroup = (closedTerminalGroup?.terminalIds ?? []).filter(
closedTerminalGroup?.terminalIds ?? [] (id) => id !== terminalId,
).filter((id) => id !== terminalId); );
const nextActiveTerminalId = const nextActiveTerminalId =
thread.activeTerminalId === terminalId thread.activeTerminalId === terminalId
? (remainingTerminalsInClosedGroup[ ? (remainingTerminalsInClosedGroup[
@@ -562,10 +553,7 @@ export function reducer(state: AppState, action: Action): AppState {
activeGroupIndex = terminalGroups.length - 1; activeGroupIndex = terminalGroups.length - 1;
} }
const existingGroupIndex = findGroupIndexByTerminalId( const existingGroupIndex = findGroupIndexByTerminalId(terminalGroups, action.terminalId);
terminalGroups,
action.terminalId,
);
if (existingGroupIndex >= 0) { if (existingGroupIndex >= 0) {
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[ terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
existingGroupIndex existingGroupIndex
@@ -674,10 +662,7 @@ export function reducer(state: AppState, action: Action): AppState {
threads: updateThread(state.threads, action.event.threadId, (thread) => { threads: updateThread(state.threads, action.event.threadId, (thread) => {
const normalizedThread = normalizeThreadTerminals(thread); const normalizedThread = normalizeThreadTerminals(thread);
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds); const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
if ( if (action.event.type === "started" || action.event.type === "restarted") {
action.event.type === "started" ||
action.event.type === "restarted"
) {
runningTerminalIdSet.delete(action.event.terminalId); runningTerminalIdSet.delete(action.event.terminalId);
} else if (action.event.type === "activity") { } else if (action.event.type === "activity") {
if (action.event.hasRunningSubprocess) { if (action.event.hasRunningSubprocess) {
+1 -4
View File
@@ -57,10 +57,7 @@ describe("resolvePathLinkTarget", () => {
it("keeps absolute paths unchanged", () => { it("keeps absolute paths unchanged", () => {
expect( expect(
resolvePathLinkTarget( resolvePathLinkTarget("/Users/julius/project/src/main.ts:12", "/Users/julius/project"),
"/Users/julius/project/src/main.ts:12",
"/Users/julius/project",
),
).toBe("/Users/julius/project/src/main.ts:12"); ).toBe("/Users/julius/project/src/main.ts:12");
}); });
}); });
+13 -38
View File
@@ -19,70 +19,45 @@ function event(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
describe("isTerminalToggleShortcut", () => { describe("isTerminalToggleShortcut", () => {
it("matches Cmd+J on macOS", () => { it("matches Cmd+J on macOS", () => {
expect( expect(isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel")).toBe(true);
isTerminalToggleShortcut(event({ metaKey: true }), "MacIntel"),
).toBe(true);
}); });
it("matches Ctrl+J on non-macOS", () => { it("matches Ctrl+J on non-macOS", () => {
expect( expect(isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32")).toBe(true);
isTerminalToggleShortcut(event({ ctrlKey: true }), "Win32"),
).toBe(true);
}); });
it("rejects wrong modifiers", () => { it("rejects wrong modifiers", () => {
expect( expect(isTerminalToggleShortcut(event({ ctrlKey: true, shiftKey: true }), "Win32")).toBe(false);
isTerminalToggleShortcut( expect(isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel")).toBe(
event({ ctrlKey: true, shiftKey: true }), false,
"Win32", );
),
).toBe(false);
expect(
isTerminalToggleShortcut(event({ metaKey: true, altKey: true }), "MacIntel"),
).toBe(false);
}); });
it("rejects non-j keys", () => { it("rejects non-j keys", () => {
expect( expect(isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux")).toBe(false);
isTerminalToggleShortcut(event({ key: "k", ctrlKey: true }), "Linux"),
).toBe(false);
}); });
}); });
describe("isTerminalClearShortcut", () => { describe("isTerminalClearShortcut", () => {
it("matches Ctrl+L on all platforms", () => { it("matches Ctrl+L on all platforms", () => {
expect( expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux")).toBe(true);
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "Linux"), expect(isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel")).toBe(true);
).toBe(true);
expect(
isTerminalClearShortcut(event({ key: "l", ctrlKey: true }), "MacIntel"),
).toBe(true);
}); });
it("matches Cmd+K on macOS", () => { it("matches Cmd+K on macOS", () => {
expect( expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel")).toBe(true);
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "MacIntel"),
).toBe(true);
}); });
it("rejects Cmd+K on non-macOS", () => { it("rejects Cmd+K on non-macOS", () => {
expect( expect(isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32")).toBe(false);
isTerminalClearShortcut(event({ key: "k", metaKey: true }), "Win32"),
).toBe(false);
}); });
it("rejects wrong modifiers", () => { it("rejects wrong modifiers", () => {
expect( expect(
isTerminalClearShortcut( isTerminalClearShortcut(event({ key: "l", ctrlKey: true, shiftKey: true }), "Linux"),
event({ key: "l", ctrlKey: true, shiftKey: true }),
"Linux",
),
).toBe(false); ).toBe(false);
expect( expect(
isTerminalClearShortcut( isTerminalClearShortcut(event({ key: "k", metaKey: true, altKey: true }), "MacIntel"),
event({ key: "k", metaKey: true, altKey: true }),
"MacIntel",
),
).toBe(false); ).toBe(false);
}); });
}); });
+1 -7
View File
@@ -31,13 +31,7 @@ export function isTerminalClearShortcut(
): boolean { ): boolean {
const key = event.key.toLowerCase(); const key = event.key.toLowerCase();
if ( if (key === "l" && event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
key === "l" &&
event.ctrlKey &&
!event.metaKey &&
!event.altKey &&
!event.shiftKey
) {
return true; return true;
} }
+1 -3
View File
@@ -30,9 +30,7 @@ describe("git contracts", () => {
it("accepts supported stacked actions", () => { it("accepts supported stacked actions", () => {
expect(gitStackedActionSchema.parse("commit")).toBe("commit"); expect(gitStackedActionSchema.parse("commit")).toBe("commit");
expect(gitStackedActionSchema.parse("commit_push")).toBe("commit_push"); expect(gitStackedActionSchema.parse("commit_push")).toBe("commit_push");
expect(gitStackedActionSchema.parse("commit_push_pr")).toBe( expect(gitStackedActionSchema.parse("commit_push_pr")).toBe("commit_push_pr");
"commit_push_pr",
);
}); });
it("parses stacked action input", () => { it("parses stacked action input", () => {
+3 -15
View File
@@ -85,23 +85,11 @@ export const gitStatusResultSchema = z.object({
.nullable(), .nullable(),
}); });
export const gitStackedActionSchema = z.enum([ export const gitStackedActionSchema = z.enum(["commit", "commit_push", "commit_push_pr"]);
"commit",
"commit_push",
"commit_push_pr",
]);
const gitCommitStepStatusSchema = z.enum(["created", "skipped_no_changes"]); const gitCommitStepStatusSchema = z.enum(["created", "skipped_no_changes"]);
const gitPushStepStatusSchema = z.enum([ const gitPushStepStatusSchema = z.enum(["pushed", "skipped_not_requested", "skipped_up_to_date"]);
"pushed", const gitPrStepStatusSchema = z.enum(["created", "opened_existing", "skipped_not_requested"]);
"skipped_not_requested",
"skipped_up_to_date",
]);
const gitPrStepStatusSchema = z.enum([
"created",
"opened_existing",
"skipped_not_requested",
]);
export const gitRunStackedActionInputSchema = z.object({ export const gitRunStackedActionInputSchema = z.object({
cwd: z.string().trim().min(1), cwd: z.string().trim().min(1),
+1 -3
View File
@@ -102,9 +102,7 @@ export interface NativeApi {
init: (input: GitInitInput) => Promise<void>; init: (input: GitInitInput) => Promise<void>;
// Stacked action API // Stacked action API
status: (input: GitStatusInput) => Promise<GitStatusResult>; status: (input: GitStatusInput) => Promise<GitStatusResult>;
runStackedAction: ( runStackedAction: (input: GitRunStackedActionInput) => Promise<GitRunStackedActionResult>;
input: GitRunStackedActionInput,
) => Promise<GitRunStackedActionResult>;
}; };
contextMenu: { contextMenu: {
show: <T extends string>( show: <T extends string>(
+1 -6
View File
@@ -36,12 +36,7 @@ export const terminalCloseInputSchema = terminalThreadInputSchema.extend({
deleteHistory: z.boolean().optional(), deleteHistory: z.boolean().optional(),
}); });
export const terminalSessionStatusSchema = z.enum([ export const terminalSessionStatusSchema = z.enum(["starting", "running", "exited", "error"]);
"starting",
"running",
"exited",
"error",
]);
export const terminalSessionSnapshotSchema = z.object({ export const terminalSessionSnapshotSchema = z.object({
threadId: z.string().min(1), threadId: z.string().min(1),
+2 -2
View File
@@ -2,8 +2,7 @@
"$schema": "https://turbo.build/schema.json", "$schema": "https://turbo.build/schema.json",
"globalEnv": [ "globalEnv": [
"PORT", "PORT",
"VITE_WS_URL",
"VITE_DEV_SERVER_URL",
"ELECTRON_RENDERER_PORT", "ELECTRON_RENDERER_PORT",
"T3CODE_LOG_WS_EVENTS", "T3CODE_LOG_WS_EVENTS",
"T3CODE_MODE", "T3CODE_MODE",
@@ -20,6 +19,7 @@
}, },
"dev": { "dev": {
"dependsOn": ["@t3tools/contracts#build"], "dependsOn": ["@t3tools/contracts#build"],
"env": ["VITE_DEV_SERVER_URL", "VITE_WS_URL"],
"cache": false, "cache": false,
"persistent": true "persistent": true
}, },