Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecea657eb0 | ||
|
|
9e3fa3e67f | ||
|
|
38de3417b8 | ||
|
|
4fff00c8c3 |
No files matched your search
@@ -15,10 +15,13 @@ await waitOn({
|
||||
});
|
||||
|
||||
const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(command, ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -40,7 +40,6 @@ child.on("exit", () => {
|
||||
"Uncaught Error",
|
||||
"Uncaught TypeError",
|
||||
"Uncaught ReferenceError",
|
||||
"ERR_FILE_NOT_FOUND",
|
||||
];
|
||||
const failures = fatalPatterns.filter((pattern) => output.includes(pattern));
|
||||
|
||||
|
||||
+30
-96
@@ -17,11 +17,8 @@ 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);
|
||||
|
||||
@@ -34,16 +31,22 @@ let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
|
||||
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;
|
||||
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 backendEnv(): NodeJS.ProcessEnv {
|
||||
@@ -80,7 +83,12 @@ function startBackend(): void {
|
||||
|
||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||
cwd: ROOT_DIR,
|
||||
env: backendEnv(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
@@ -126,76 +134,6 @@ 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 () => {
|
||||
@@ -293,7 +231,10 @@ function createWindow(): BrowserWindow {
|
||||
void window.loadURL(process.env.VITE_DEV_SERVER_URL as string);
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
} else {
|
||||
void window.loadURL(backendHttpUrl());
|
||||
if (!fs.existsSync(WEB_ENTRY)) {
|
||||
throw new Error(`Web bundle missing at ${WEB_ENTRY}`);
|
||||
}
|
||||
void window.loadFile(WEB_ENTRY);
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -306,17 +247,13 @@ function createWindow(): BrowserWindow {
|
||||
}
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = resolveBackendPort(process.env.T3CODE_PORT);
|
||||
process.env.T3CODE_PORT = String(backendPort);
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
backendWsUrl = `ws://${LOOPBACK_HOST}:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
|
||||
registerIpcHandlers();
|
||||
startBackend();
|
||||
if (!isDevelopment) {
|
||||
await waitForBackendReady();
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
|
||||
@@ -326,10 +263,7 @@ app.on("before-quit", () => {
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
void bootstrap().catch((error) => {
|
||||
console.error("[desktop] failed to bootstrap app", error);
|
||||
app.quit();
|
||||
});
|
||||
void bootstrap();
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
|
||||
@@ -21,16 +21,10 @@ 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",
|
||||
@@ -115,8 +109,7 @@ 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",
|
||||
|
||||
@@ -258,7 +258,8 @@ 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({
|
||||
@@ -282,7 +283,8 @@ 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;
|
||||
|
||||
@@ -28,5 +28,8 @@ export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult>;
|
||||
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
|
||||
generatePrContent(
|
||||
input: PrContentGenerationInput,
|
||||
): Promise<PrContentGenerationResult>;
|
||||
}
|
||||
|
||||
@@ -569,7 +569,11 @@ 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");
|
||||
});
|
||||
|
||||
+11
-2
@@ -224,12 +224,21 @@ 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,
|
||||
|
||||
@@ -5,7 +5,11 @@ 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[];
|
||||
@@ -67,7 +71,9 @@ 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",
|
||||
@@ -120,7 +126,8 @@ 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,
|
||||
@@ -336,7 +343,7 @@ describe("GitManager", () => {
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("opens existing PR for commit/push/pr action", async () => {
|
||||
it("returns existing PR metadata for commit/push/pr action", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
|
||||
@@ -369,7 +376,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 "))).toBe(false);
|
||||
});
|
||||
|
||||
it("creates PR when one does not already exist", async () => {
|
||||
@@ -413,6 +420,7 @@ describe("GitManager", () => {
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
).toBe(true);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects push/pr actions from detached HEAD", async () => {
|
||||
|
||||
@@ -20,7 +20,11 @@ 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;
|
||||
|
||||
@@ -54,7 +58,11 @@ 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 (
|
||||
@@ -90,7 +98,8 @@ 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(),
|
||||
@@ -134,7 +143,10 @@ 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") {
|
||||
@@ -213,7 +225,9 @@ 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";
|
||||
@@ -226,7 +240,11 @@ 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)
|
||||
@@ -307,7 +325,6 @@ export class GitManager {
|
||||
|
||||
const existing = await this.findOpenPr(cwd, branch);
|
||||
if (existing) {
|
||||
await this.openPrInBrowser(cwd, branch);
|
||||
return {
|
||||
status: "opened_existing",
|
||||
url: existing.url,
|
||||
@@ -335,7 +352,10 @@ 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 {
|
||||
@@ -360,7 +380,6 @@ export class GitManager {
|
||||
}
|
||||
|
||||
const created = await this.findOpenPr(cwd, branch);
|
||||
await this.openPrInBrowser(cwd, branch);
|
||||
|
||||
if (!created) {
|
||||
return {
|
||||
@@ -381,15 +400,10 @@ export class GitManager {
|
||||
};
|
||||
}
|
||||
|
||||
private async openPrInBrowser(cwd: string, branch: string): Promise<void> {
|
||||
try {
|
||||
await this.runGh(cwd, ["pr", "view", branch, "--web"]);
|
||||
} catch {
|
||||
// Opening the browser is best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
@@ -422,7 +436,10 @@ 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) {
|
||||
@@ -459,7 +476,10 @@ 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,15 +5,23 @@ 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);
|
||||
|
||||
@@ -24,7 +24,11 @@ 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)}.`);
|
||||
}
|
||||
@@ -34,7 +38,9 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
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(
|
||||
@@ -50,11 +56,17 @@ 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(
|
||||
@@ -149,13 +161,22 @@ 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;
|
||||
@@ -168,7 +189,12 @@ 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;
|
||||
@@ -215,7 +241,10 @@ 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;
|
||||
}
|
||||
|
||||
@@ -40,7 +40,12 @@ 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) {
|
||||
@@ -123,7 +128,10 @@ 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);
|
||||
}
|
||||
|
||||
@@ -2,11 +2,7 @@ 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";
|
||||
@@ -165,10 +161,7 @@ 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");
|
||||
@@ -306,14 +299,18 @@ 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,
|
||||
);
|
||||
|
||||
@@ -371,8 +368,12 @@ 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();
|
||||
});
|
||||
@@ -414,11 +415,58 @@ 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);
|
||||
}
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("filters app runtime env variables from terminal sessions", async () => {
|
||||
const originalValues = new Map<string, string | undefined>();
|
||||
const setEnv = (key: string, value: string | undefined) => {
|
||||
if (!originalValues.has(key)) {
|
||||
originalValues.set(key, process.env[key]);
|
||||
}
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
return;
|
||||
}
|
||||
process.env[key] = value;
|
||||
};
|
||||
const restoreEnv = () => {
|
||||
for (const [key, value] of originalValues) {
|
||||
if (value === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
setEnv("PORT", "5173");
|
||||
setEnv("T3CODE_PORT", "3773");
|
||||
setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173");
|
||||
setEnv("TEST_TERMINAL_KEEP", "keep-me");
|
||||
|
||||
try {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput());
|
||||
const spawnInput = ptyAdapter.spawnInputs[0];
|
||||
expect(spawnInput).toBeDefined();
|
||||
if (!spawnInput) return;
|
||||
|
||||
expect(spawnInput.env.PORT).toBeUndefined();
|
||||
expect(spawnInput.env.T3CODE_PORT).toBeUndefined();
|
||||
expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined();
|
||||
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
|
||||
|
||||
manager.dispose();
|
||||
} finally {
|
||||
restoreEnv();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,11 @@ import { runProcess } from "./processRunner";
|
||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set([
|
||||
"PORT",
|
||||
"ELECTRON_RENDERER_PORT",
|
||||
"ELECTRON_RUN_AS_NODE",
|
||||
]);
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
@@ -97,7 +102,12 @@ 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([
|
||||
@@ -229,6 +239,27 @@ function toSessionKey(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
function shouldExcludeTerminalEnvKey(key: string): boolean {
|
||||
const normalizedKey = key.toUpperCase();
|
||||
if (normalizedKey.startsWith("T3CODE_")) {
|
||||
return true;
|
||||
}
|
||||
if (normalizedKey.startsWith("VITE_")) {
|
||||
return true;
|
||||
}
|
||||
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
|
||||
}
|
||||
|
||||
function createTerminalSpawnEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
const spawnEnv: NodeJS.ProcessEnv = {};
|
||||
for (const [key, value] of Object.entries(baseEnv)) {
|
||||
if (value === undefined) continue;
|
||||
if (shouldExcludeTerminalEnvKey(key)) continue;
|
||||
spawnEnv[key] = value;
|
||||
}
|
||||
return spawnEnv;
|
||||
}
|
||||
|
||||
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private readonly sessions = new Map<string, TerminalSessionState>();
|
||||
private readonly logsDir: string;
|
||||
@@ -400,7 +431,11 @@ 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;
|
||||
}
|
||||
|
||||
@@ -458,6 +493,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
const terminalEnv = createTerminalSpawnEnv(process.env);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
for (const shell of shellCandidates) {
|
||||
@@ -467,7 +503,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
cwd: session.cwd,
|
||||
cols: session.cols,
|
||||
rows: session.rows,
|
||||
env: process.env,
|
||||
env: terminalEnv,
|
||||
});
|
||||
startedShell = shell;
|
||||
break;
|
||||
@@ -481,9 +517,13 @@ 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());
|
||||
}
|
||||
|
||||
@@ -929,7 +969,10 @@ 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) => {
|
||||
|
||||
@@ -224,7 +224,9 @@ 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 }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -585,7 +587,9 @@ 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 });
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@tanstack/react-query": "^5.90.0",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-react": "^0.563.0",
|
||||
"react": "^19.0.0",
|
||||
|
||||
@@ -302,9 +302,7 @@ 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 })
|
||||
@@ -766,15 +764,13 @@ 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 &&
|
||||
@@ -786,7 +782,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 } : {}),
|
||||
@@ -1447,9 +1443,7 @@ 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"
|
||||
}
|
||||
|
||||
@@ -8,11 +8,9 @@ import { queryOptions, useMutation, useQuery, useQueryClient } from "@tanstack/r
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
CheckIcon,
|
||||
CircleIcon,
|
||||
CloudUploadIcon,
|
||||
GitCommitIcon,
|
||||
Loader2Icon,
|
||||
MinusIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
@@ -64,6 +62,13 @@ function GitActionIcon(props: { icon: GitActionIconName; disabled: boolean }) {
|
||||
return <GitHubIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
|
||||
}
|
||||
|
||||
function runningStepMessage(stepId: GitProgressStep["id"]): string {
|
||||
if (stepId === "generate") return "Generating commit message...";
|
||||
if (stepId === "commit") return "Committing changes...";
|
||||
if (stepId === "push") return "Pushing branch...";
|
||||
return "Preparing pull request...";
|
||||
}
|
||||
|
||||
function gitActionModalTitle(): string {
|
||||
return "Commit your changes";
|
||||
}
|
||||
@@ -249,6 +254,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
const [gitModalProgress, setGitModalProgress] = useState<GitProgressStep[]>([]);
|
||||
const [gitModalError, setGitModalError] = useState<string | null>(null);
|
||||
const [gitModalResult, setGitModalResult] = useState<GitRunStackedActionResult | null>(null);
|
||||
const [isGitProgressToastVisible, setIsGitProgressToastVisible] = useState(false);
|
||||
const gitMenuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(
|
||||
@@ -291,10 +297,27 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
[gitModalActionOptions, gitModalSelectedAction],
|
||||
);
|
||||
const visibleGitActionError = gitActionError ?? gitStatusError?.message;
|
||||
const gitModalOpenPrUrl = gitModalResult?.pr.url ?? gitStatus?.openPr?.url ?? null;
|
||||
const gitModalHasProgress = gitModalProgress.length > 0;
|
||||
const gitModalSelectionMode = !gitModalHasProgress && gitModalResult === null;
|
||||
const gitModalSteps = gitModalProgress;
|
||||
const gitProgressToastOpenPrUrl = gitModalResult?.pr.url ?? gitStatus?.openPr?.url ?? null;
|
||||
const showGitProgressToast =
|
||||
isGitProgressToastVisible &&
|
||||
(isGitModalActionRunning ||
|
||||
gitModalProgress.length > 0 ||
|
||||
gitModalError !== null ||
|
||||
gitModalResult !== null);
|
||||
const activeGitProgressStep = useMemo(
|
||||
() => gitModalProgress.find((step) => step.status === "running") ?? null,
|
||||
[gitModalProgress],
|
||||
);
|
||||
const gitProgressToastStatus = isGitModalActionRunning
|
||||
? "running"
|
||||
: gitModalError
|
||||
? "failed"
|
||||
: "done";
|
||||
const gitProgressToastMessage = isGitModalActionRunning
|
||||
? runningStepMessage(activeGitProgressStep?.id ?? "commit")
|
||||
: gitModalError
|
||||
? "Git action failed."
|
||||
: "Done.";
|
||||
|
||||
const refreshGitStatus = useCallback(async () => {
|
||||
if (!api || !gitCwd) return;
|
||||
@@ -307,6 +330,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
setIsGitModalOpen(true);
|
||||
setGitModalSelectedAction("commit");
|
||||
setGitModalCommitMessage("");
|
||||
setIsGitProgressToastVisible(false);
|
||||
setGitModalProgress([]);
|
||||
setGitModalError(null);
|
||||
setGitModalResult(null);
|
||||
@@ -318,9 +342,6 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
setIsGitModalOpen(false);
|
||||
setGitModalSelectedAction("commit");
|
||||
setGitModalCommitMessage("");
|
||||
setGitModalProgress([]);
|
||||
setGitModalError(null);
|
||||
setGitModalResult(null);
|
||||
}, [isGitActionRunning]);
|
||||
|
||||
const runGitActionImmediately = useCallback(
|
||||
@@ -349,28 +370,39 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
});
|
||||
}, [api, gitStatus?.openPr?.url]);
|
||||
|
||||
const openPrFromModal = useCallback(() => {
|
||||
const openPrFromToast = useCallback(() => {
|
||||
if (!api) {
|
||||
setGitModalError("Link opening is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const prUrl = gitModalOpenPrUrl;
|
||||
const prUrl = gitProgressToastOpenPrUrl;
|
||||
if (!prUrl) return;
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
setGitModalError(error instanceof Error ? error.message : "Unable to open PR link.");
|
||||
});
|
||||
}, [api, gitModalOpenPrUrl]);
|
||||
}, [api, gitProgressToastOpenPrUrl]);
|
||||
|
||||
const dismissGitProgressToast = useCallback(() => {
|
||||
if (isGitModalActionRunning) return;
|
||||
setIsGitProgressToastVisible(false);
|
||||
setGitModalProgress([]);
|
||||
setGitModalError(null);
|
||||
setGitModalResult(null);
|
||||
}, [isGitModalActionRunning]);
|
||||
|
||||
const runGitAction = useCallback(async () => {
|
||||
if (!api || !gitCwd || !isGitModalOpen) return;
|
||||
if (!api || !gitCwd) return;
|
||||
if (!selectedGitModalActionOption || selectedGitModalActionOption.disabled) return;
|
||||
const actionCwd = gitCwd;
|
||||
const action = selectedGitModalActionOption.action;
|
||||
const commitMessage = gitModalCommitMessage.trim();
|
||||
const includeGeneratedCommitMessage = commitMessage.length === 0;
|
||||
|
||||
setIsGitMenuOpen(false);
|
||||
setIsGitModalOpen(false);
|
||||
setIsGitProgressToastVisible(true);
|
||||
setIsGitModalActionRunning(true);
|
||||
setGitModalError(null);
|
||||
setGitActionError(null);
|
||||
@@ -488,7 +520,6 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
api,
|
||||
gitCwd,
|
||||
gitModalCommitMessage,
|
||||
isGitModalOpen,
|
||||
refreshGitStatus,
|
||||
selectedGitModalActionOption,
|
||||
]);
|
||||
@@ -497,6 +528,7 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
setGitActionError(null);
|
||||
setGitModalError(null);
|
||||
setIsGitModalOpen(false);
|
||||
setIsGitProgressToastVisible(false);
|
||||
setGitModalSelectedAction("commit");
|
||||
setGitModalCommitMessage("");
|
||||
setGitModalProgress([]);
|
||||
@@ -690,92 +722,57 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
placeholder="Leave blank to autogenerate a commit message"
|
||||
value={gitModalCommitMessage}
|
||||
onChange={(event) => setGitModalCommitMessage(event.target.value)}
|
||||
disabled={!gitModalSelectionMode || isGitActionRunning}
|
||||
disabled={isGitActionRunning}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<p className="text-sm font-medium text-foreground">Next steps</p>
|
||||
<div className="mt-2 overflow-hidden rounded-2xl border border-border">
|
||||
{gitModalSelectionMode &&
|
||||
gitModalActionOptions.map((option, index) => {
|
||||
const borderClass =
|
||||
index < gitModalActionOptions.length - 1 ? "border-b border-border/70" : "";
|
||||
const selected = option.action === gitModalSelectedAction && !option.disabled;
|
||||
const disabled = option.disabled || isGitActionRunning;
|
||||
{gitModalActionOptions.map((option, index) => {
|
||||
const borderClass =
|
||||
index < gitModalActionOptions.length - 1 ? "border-b border-border/70" : "";
|
||||
const selected = option.action === gitModalSelectedAction && !option.disabled;
|
||||
const disabled = option.disabled || isGitActionRunning;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={option.action}
|
||||
type="button"
|
||||
className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors duration-150 ${borderClass} ${
|
||||
selected
|
||||
? "bg-accent/55"
|
||||
: disabled
|
||||
? "bg-card/25"
|
||||
: "bg-card/45 hover:bg-accent/35"
|
||||
} disabled:cursor-not-allowed`}
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
setGitModalSelectedAction(option.action);
|
||||
}}
|
||||
>
|
||||
<span className="mt-0.5">
|
||||
<GitActionIcon icon={option.icon} disabled={option.disabled} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
return (
|
||||
<button
|
||||
key={option.action}
|
||||
type="button"
|
||||
className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors duration-150 ${borderClass} ${
|
||||
selected
|
||||
? "bg-accent/55"
|
||||
: disabled
|
||||
? "bg-card/25"
|
||||
: "bg-card/45 hover:bg-accent/35"
|
||||
} disabled:cursor-not-allowed`}
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
setGitModalSelectedAction(option.action);
|
||||
}}
|
||||
>
|
||||
<span className="mt-0.5">
|
||||
<GitActionIcon icon={option.icon} disabled={option.disabled} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p
|
||||
className={`text-sm ${disabled ? "text-muted-foreground/60" : "text-foreground"}`}
|
||||
>
|
||||
{option.label}
|
||||
</p>
|
||||
{option.detail && (
|
||||
<p
|
||||
className={`text-sm ${disabled ? "text-muted-foreground/60" : "text-foreground"}`}
|
||||
className={`mt-0.5 text-xs ${disabled ? "text-muted-foreground/55" : "text-muted-foreground/70"}`}
|
||||
>
|
||||
{option.label}
|
||||
{option.detail}
|
||||
</p>
|
||||
{option.detail && (
|
||||
<p
|
||||
className={`mt-0.5 text-xs ${disabled ? "text-muted-foreground/55" : "text-muted-foreground/70"}`}
|
||||
>
|
||||
{option.detail}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{selected && !disabled ? (
|
||||
<CheckIcon className="mt-0.5 h-4 w-4 shrink-0 text-foreground" />
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{!gitModalSelectionMode &&
|
||||
gitModalSteps.map((step, index) => {
|
||||
const borderClass =
|
||||
index < gitModalSteps.length - 1 ? "border-b border-border/70" : "";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={step.id}
|
||||
className={`flex items-start gap-3 bg-card/45 px-4 py-3 ${borderClass}`}
|
||||
>
|
||||
<span className="mt-0.5">
|
||||
{step.status === "running" ? (
|
||||
<Loader2Icon className="h-4 w-4 animate-spin text-foreground" />
|
||||
) : step.status === "completed" ? (
|
||||
<CheckIcon className="h-4 w-4 text-emerald-600 dark:text-emerald-300" />
|
||||
) : step.status === "skipped" ? (
|
||||
<MinusIcon className="h-4 w-4 text-muted-foreground/70" />
|
||||
) : step.status === "failed" ? (
|
||||
<XIcon className="h-4 w-4 text-rose-500 dark:text-rose-300" />
|
||||
) : (
|
||||
<CircleIcon className="h-4 w-4 text-muted-foreground/60" />
|
||||
)}
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-foreground">{step.label}</p>
|
||||
{step.status === "failed" && step.detail && (
|
||||
<p className="mt-0.5 text-xs text-rose-500 dark:text-rose-300">
|
||||
{step.detail}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{selected && !disabled ? (
|
||||
<CheckIcon className="mt-0.5 h-4 w-4 shrink-0 text-foreground" />
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{(gitModalError ?? visibleGitActionError) && (
|
||||
@@ -784,48 +781,68 @@ export default function GitActionsControl({ api, gitCwd }: GitActionsControlProp
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-6 flex justify-end gap-2">
|
||||
{gitModalResult && gitModalOpenPrUrl && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={openPrFromModal}
|
||||
disabled={isGitActionRunning}
|
||||
>
|
||||
Open PR
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={
|
||||
gitModalResult
|
||||
? "rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
: "rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
|
||||
}
|
||||
className="rounded-xl border border-border px-4 py-2 text-sm text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={closeGitActionModal}
|
||||
disabled={isGitActionRunning}
|
||||
>
|
||||
{gitModalResult ? "Done" : "Cancel"}
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={() => {
|
||||
void runGitAction();
|
||||
}}
|
||||
disabled={isGitActionRunning || !selectedGitModalActionOption}
|
||||
>
|
||||
{runActionLabel(gitModalSelectedAction)}
|
||||
</button>
|
||||
{!gitModalResult && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-xl bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={() => {
|
||||
void runGitAction();
|
||||
}}
|
||||
disabled={isGitActionRunning || !selectedGitModalActionOption}
|
||||
>
|
||||
{isGitActionRunning
|
||||
? "Running..."
|
||||
: gitModalSelectionMode
|
||||
? "Continue"
|
||||
: runActionLabel(gitModalSelectedAction)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showGitProgressToast && (
|
||||
<div
|
||||
className="fixed bottom-4 right-4 z-[90]"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className="flex max-w-[calc(100vw-2rem)] items-center gap-2 rounded-xl border border-border bg-popover/95 px-3 py-2 shadow-xl backdrop-blur">
|
||||
<span className="shrink-0">
|
||||
{gitProgressToastStatus === "running" ? (
|
||||
<Loader2Icon className="h-4 w-4 animate-spin text-foreground" />
|
||||
) : gitProgressToastStatus === "failed" ? (
|
||||
<XIcon className="h-4 w-4 text-rose-500 dark:text-rose-300" />
|
||||
) : (
|
||||
<CheckIcon className="h-4 w-4 text-emerald-600 dark:text-emerald-300" />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 truncate text-sm text-foreground">{gitProgressToastMessage}</span>
|
||||
{!isGitModalActionRunning && gitModalResult && gitProgressToastOpenPrUrl && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md bg-foreground px-2.5 py-1 text-xs font-medium text-background transition-colors duration-150 hover:bg-foreground/90 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={openPrFromToast}
|
||||
disabled={isGitModalActionRunning}
|
||||
>
|
||||
Open PR
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded p-1 text-muted-foreground/60 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
||||
onClick={dismissGitProgressToast}
|
||||
disabled={isGitModalActionRunning}
|
||||
aria-label="Dismiss git action progress toast"
|
||||
>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -28,11 +28,16 @@ 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);
|
||||
}
|
||||
@@ -46,7 +51,8 @@ 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 {
|
||||
@@ -140,7 +146,8 @@ 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);
|
||||
@@ -531,9 +538,8 @@ 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 =
|
||||
@@ -701,7 +707,9 @@ 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) {
|
||||
@@ -777,8 +785,7 @@ 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);
|
||||
@@ -801,9 +808,7 @@ 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 (
|
||||
|
||||
@@ -55,7 +55,9 @@ 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");
|
||||
});
|
||||
@@ -103,7 +105,9 @@ 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");
|
||||
});
|
||||
@@ -217,7 +221,9 @@ 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", () => {
|
||||
@@ -255,7 +261,9 @@ 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}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -52,7 +52,9 @@ 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([]),
|
||||
@@ -147,10 +149,9 @@ 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);
|
||||
@@ -196,9 +197,7 @@ 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);
|
||||
@@ -229,9 +228,7 @@ function hydrateThread(
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: activeGroupIndexFromTerminal >= 0
|
||||
? activeGroupIndexFromTerminal
|
||||
: 0;
|
||||
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
|
||||
const activeTerminalGroupId =
|
||||
normalizedGroups[activeGroupIndex]?.id ??
|
||||
normalizedGroups[0]?.id ??
|
||||
|
||||
@@ -244,7 +244,11 @@ 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}`,
|
||||
|
||||
+27
-12
@@ -101,12 +101,17 @@ 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 };
|
||||
@@ -178,7 +183,10 @@ 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>();
|
||||
@@ -240,13 +248,14 @@ 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 ??
|
||||
@@ -292,9 +301,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[
|
||||
@@ -553,7 +562,10 @@ 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
|
||||
@@ -662,7 +674,10 @@ 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) {
|
||||
|
||||
@@ -57,7 +57,10 @@ 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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,45 +19,70 @@ 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);
|
||||
});
|
||||
});
|
||||
@@ -31,7 +31,13 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,9 @@ 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", () => {
|
||||
|
||||
@@ -85,11 +85,23 @@ 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),
|
||||
|
||||
@@ -102,7 +102,9 @@ 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>(
|
||||
|
||||
@@ -36,7 +36,12 @@ 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
@@ -2,7 +2,8 @@
|
||||
"$schema": "https://turbo.build/schema.json",
|
||||
"globalEnv": [
|
||||
"PORT",
|
||||
|
||||
"VITE_WS_URL",
|
||||
"VITE_DEV_SERVER_URL",
|
||||
"ELECTRON_RENDERER_PORT",
|
||||
"T3CODE_LOG_WS_EVENTS",
|
||||
"T3CODE_MODE",
|
||||
@@ -19,7 +20,6 @@
|
||||
},
|
||||
"dev": {
|
||||
"dependsOn": ["@t3tools/contracts#build"],
|
||||
"env": ["VITE_DEV_SERVER_URL", "VITE_WS_URL"],
|
||||
"cache": false,
|
||||
"persistent": true
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user