Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42b2a881b0 | ||
|
|
e4c1729ab3 | ||
|
|
c561a86997 |
No files matched your search
@@ -5,7 +5,7 @@ import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu } from "electron";
|
||||
|
||||
import { fixPath } from "./fixPath";
|
||||
|
||||
@@ -13,7 +13,6 @@ fixPath();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
const BACKEND_ENTRY = path.join(ROOT_DIR, "apps/server/dist/index.mjs");
|
||||
const WEB_ENTRY = path.join(ROOT_DIR, "apps/web/dist/index.html");
|
||||
@@ -160,31 +159,6 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(OPEN_EXTERNAL_CHANNEL);
|
||||
ipcMain.handle(OPEN_EXTERNAL_CHANNEL, async (_event, rawUrl: unknown) => {
|
||||
if (typeof rawUrl !== "string" || rawUrl.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let parsedUrl: URL;
|
||||
try {
|
||||
parsedUrl = new URL(rawUrl);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parsedUrl.protocol !== "https:" && parsedUrl.protocol !== "http:") {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await shell.openExternal(parsedUrl.toString());
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
|
||||
@@ -2,7 +2,6 @@ import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
@@ -10,5 +9,4 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
|
||||
showContextMenu: (items: { id: string; label: string }[]) =>
|
||||
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
||||
});
|
||||
@@ -1,42 +1,11 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.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")
|
||||
.mockResolvedValue({
|
||||
turn: {
|
||||
id: "turn_1",
|
||||
},
|
||||
});
|
||||
const updateSession = vi
|
||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -106,88 +75,3 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
it("sends text and image user input items to turn/start", async () => {
|
||||
const { manager, context, requireSession, sendRequest, updateSession } = createSendTurnHarness();
|
||||
|
||||
const result = await manager.sendTurn({
|
||||
sessionId: "sess_1",
|
||||
input: "Inspect this image",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "error.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
dataUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3",
|
||||
effort: "high",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turnId: "turn_1",
|
||||
});
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Inspect this image",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "running",
|
||||
activeTurnId: "turn_1",
|
||||
});
|
||||
});
|
||||
|
||||
it("supports image-only turns", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
sessionId: "sess_1",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 256,
|
||||
dataUrl: "data:image/png;base64,BBBB",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "image",
|
||||
url: "data:image/png;base64,BBBB",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty turn input", async () => {
|
||||
const { manager } = createSendTurnHarness();
|
||||
|
||||
await expect(
|
||||
manager.sendTurn({
|
||||
sessionId: "sess_1",
|
||||
}),
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
});
|
||||
@@ -257,40 +257,20 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const turnInput: Array<
|
||||
| { type: "text"; text: string; text_elements: [] }
|
||||
| { type: "image"; url: string }
|
||||
> = [];
|
||||
if (input.input) {
|
||||
turnInput.push({
|
||||
type: "text",
|
||||
text: input.input,
|
||||
text_elements: [],
|
||||
});
|
||||
}
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
if (attachment.type === "image") {
|
||||
turnInput.push({
|
||||
type: "image",
|
||||
url: attachment.dataUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (turnInput.length === 0) {
|
||||
throw new Error("Turn input must include text or attachments.");
|
||||
}
|
||||
|
||||
const turnStartParams: {
|
||||
threadId: string;
|
||||
input: Array<
|
||||
| { type: "text"; text: string; text_elements: [] }
|
||||
| { type: "image"; url: string }
|
||||
>;
|
||||
input: Array<{ type: "text"; text: string; text_elements: [] }>;
|
||||
model?: string;
|
||||
effort?: string;
|
||||
} = {
|
||||
threadId: context.session.threadId,
|
||||
input: turnInput,
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: input.input,
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
if (normalizedModel) {
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
CommitMessageGenerationInput,
|
||||
CommitMessageGenerationResult,
|
||||
PrContentGenerationInput,
|
||||
PrContentGenerationResult,
|
||||
TextGenerationService,
|
||||
} from "./coreServices";
|
||||
import { type ProcessRunOptions, type ProcessRunResult, runProcess } from "./processRunner";
|
||||
|
||||
type ProcessRunner = (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>;
|
||||
|
||||
const CODEX_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_REASONING_EFFORT = "low";
|
||||
|
||||
const COMMIT_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
subject: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["subject", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
const PR_OUTPUT_SCHEMA_JSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
body: { type: "string" },
|
||||
},
|
||||
required: ["title", "body"],
|
||||
additionalProperties: false,
|
||||
} as const;
|
||||
|
||||
function parseCommitOutput(raw: unknown): { subject: string; body: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
throw new Error("Codex returned a non-object commit message payload.");
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
const subject = typeof record.subject === "string" ? record.subject.trim() : "";
|
||||
const body = typeof record.body === "string" ? record.body : "";
|
||||
if (subject.length === 0) {
|
||||
throw new Error("Codex returned an empty commit subject.");
|
||||
}
|
||||
return { subject, body };
|
||||
}
|
||||
|
||||
function parsePrOutput(raw: unknown): { title: string; body: string } {
|
||||
if (!raw || typeof raw !== "object") {
|
||||
throw new Error("Codex returned a non-object PR payload.");
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
const title = typeof record.title === "string" ? record.title.trim() : "";
|
||||
const body = typeof record.body === "string" ? record.body.trim() : "";
|
||||
if (title.length === 0 || body.length === 0) {
|
||||
throw new Error("Codex returned an invalid PR title/body payload.");
|
||||
}
|
||||
return { title, body };
|
||||
}
|
||||
|
||||
function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
const truncated = value.slice(0, maxChars);
|
||||
return `${truncated}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
async function writeTempFile(prefix: string, content: string): Promise<string> {
|
||||
const filePath = path.join(os.tmpdir(), `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
|
||||
await fs.writeFile(filePath, content, "utf8");
|
||||
return filePath;
|
||||
}
|
||||
|
||||
async function safeUnlink(filePath: string): Promise<void> {
|
||||
try {
|
||||
await fs.unlink(filePath);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeCommitSubject(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
|
||||
if (withoutTrailingPeriod.length === 0) {
|
||||
return "Update project files";
|
||||
}
|
||||
|
||||
if (withoutTrailingPeriod.length <= 72) {
|
||||
return withoutTrailingPeriod;
|
||||
}
|
||||
return withoutTrailingPeriod.slice(0, 72).trimEnd();
|
||||
}
|
||||
|
||||
function sanitizePrTitle(raw: string): string {
|
||||
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
if (singleLine.length > 0) {
|
||||
return singleLine;
|
||||
}
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
async function runCodexJson<T>({
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
parse,
|
||||
run,
|
||||
}: {
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: object;
|
||||
parse: (raw: unknown) => T;
|
||||
run: ProcessRunner;
|
||||
}): Promise<T> {
|
||||
const schemaPath = await writeTempFile("codex-schema", JSON.stringify(outputSchemaJson));
|
||||
let outputPath: string | null = null;
|
||||
|
||||
try {
|
||||
outputPath = await writeTempFile("codex-output", "");
|
||||
await run(
|
||||
"codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
"-",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
timeoutMs: 180_000,
|
||||
stdin: prompt,
|
||||
},
|
||||
);
|
||||
|
||||
const rawOutput = (await fs.readFile(outputPath, "utf8")).trim();
|
||||
if (rawOutput.length === 0) {
|
||||
throw new Error("Codex returned an empty response.");
|
||||
}
|
||||
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
parsedJson = JSON.parse(rawOutput);
|
||||
} catch {
|
||||
throw new Error("Codex returned invalid JSON output.");
|
||||
}
|
||||
|
||||
return parse(parsedJson);
|
||||
} finally {
|
||||
await Promise.all([safeUnlink(schemaPath), ...(outputPath ? [safeUnlink(outputPath)] : [])]);
|
||||
}
|
||||
}
|
||||
|
||||
interface CodexTextGeneratorDeps {
|
||||
runProcess?: ProcessRunner;
|
||||
}
|
||||
|
||||
export class CodexTextGenerator implements TextGenerationService {
|
||||
private readonly run: ProcessRunner;
|
||||
|
||||
constructor(deps: CodexTextGeneratorDeps = {}) {
|
||||
this.run = deps.runProcess ?? runProcess;
|
||||
}
|
||||
|
||||
async generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult> {
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
"Return a JSON object with keys: subject, body.",
|
||||
"Rules:",
|
||||
"- subject must be imperative, <= 72 chars, and no trailing period",
|
||||
"- body can be empty string or short bullet points",
|
||||
"- capture the primary user-visible or developer-visible change",
|
||||
"",
|
||||
`Branch: ${input.branch ?? "(detached)"}`,
|
||||
"",
|
||||
"Staged files:",
|
||||
limitSection(input.stagedSummary, 6_000),
|
||||
"",
|
||||
"Staged patch:",
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const generated = await runCodexJson({
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: COMMIT_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parseCommitOutput(raw),
|
||||
run: this.run,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
async generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult> {
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
"",
|
||||
"Commits:",
|
||||
limitSection(input.commitSummary, 12_000),
|
||||
"",
|
||||
"Diff stat:",
|
||||
limitSection(input.diffSummary, 12_000),
|
||||
"",
|
||||
"Diff patch:",
|
||||
limitSection(input.diffPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
const generated = await runCodexJson({
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: PR_OUTPUT_SCHEMA_JSON,
|
||||
parse: (raw) => parsePrOutput(raw),
|
||||
run: this.run,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface TextGenerationService {
|
||||
generateCommitMessage(
|
||||
input: CommitMessageGenerationInput,
|
||||
): Promise<CommitMessageGenerationResult>;
|
||||
generatePrContent(
|
||||
input: PrContentGenerationInput,
|
||||
): Promise<PrContentGenerationResult>;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
GitCoreService,
|
||||
checkoutGitBranch,
|
||||
createGitBranch,
|
||||
createGitWorktree,
|
||||
@@ -436,85 +435,4 @@ describe("git integration", () => {
|
||||
expect(result.branches.find((b) => b.current)!.name).toBe(initialBranch);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GitCoreService", () => {
|
||||
it("supports branch lifecycle operations through the service API", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
const core = new GitCoreService();
|
||||
|
||||
await core.initRepo({ cwd: tmp.path });
|
||||
await git(tmp.path, "config user.email '[email protected]'");
|
||||
await git(tmp.path, "config user.name 'Test'");
|
||||
await writeFile(path.join(tmp.path, "README.md"), "# test\n");
|
||||
await git(tmp.path, "add .");
|
||||
await git(tmp.path, "commit -m 'initial commit'");
|
||||
|
||||
await core.createBranch({ cwd: tmp.path, branch: "feature/service-api" });
|
||||
await core.checkoutBranch({ cwd: tmp.path, branch: "feature/service-api" });
|
||||
const branches = await core.listBranches({ cwd: tmp.path });
|
||||
|
||||
expect(branches.isRepo).toBe(true);
|
||||
expect(branches.branches.find((branch) => branch.current)?.name).toBe("feature/service-api");
|
||||
});
|
||||
|
||||
it("reports status details and dirty state", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
|
||||
const clean = await core.status({ cwd: tmp.path });
|
||||
expect(clean.hasWorkingTreeChanges).toBe(false);
|
||||
expect(clean.branch).toBeTruthy();
|
||||
|
||||
await writeFile(path.join(tmp.path, "README.md"), "updated\n");
|
||||
const dirty = await core.statusDetails(tmp.path);
|
||||
expect(dirty.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
it("prepares commit context by auto-staging and creates commit", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
|
||||
await writeFile(path.join(tmp.path, "README.md"), "new content\n");
|
||||
const context = await core.prepareCommitContext(tmp.path);
|
||||
expect(context).not.toBeNull();
|
||||
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",
|
||||
);
|
||||
expect(created.commitSha.length).toBeGreaterThan(0);
|
||||
expect(await git(tmp.path, "log -1 --pretty=%s")).toBe("Add README update");
|
||||
});
|
||||
|
||||
it("pushes with upstream setup and then skips when up to date", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await using remote = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
await git(remote.path, "init --bare");
|
||||
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await createGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "feature/core-push" });
|
||||
|
||||
await writeFile(path.join(tmp.path, "feature.txt"), "push me\n");
|
||||
const core = new GitCoreService();
|
||||
const context = await core.prepareCommitContext(tmp.path);
|
||||
expect(context).not.toBeNull();
|
||||
await core.commit(tmp.path, "Add feature file", "");
|
||||
|
||||
const pushed = await core.pushCurrentBranch(tmp.path, null);
|
||||
expect(pushed.status).toBe("pushed");
|
||||
expect(pushed.setUpstream).toBe(true);
|
||||
expect(await git(tmp.path, "rev-parse --abbrev-ref @{upstream}")).toBe(
|
||||
"origin/feature/core-push",
|
||||
);
|
||||
|
||||
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
||||
expect(skipped.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
});
|
||||
});
|
||||
+237
-434
@@ -1,22 +1,18 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
gitStatusInputSchema,
|
||||
gitStatusResultSchema,
|
||||
type GitCheckoutInput,
|
||||
type GitCreateBranchInput,
|
||||
type GitCreateWorktreeInput,
|
||||
type GitCreateWorktreeResult,
|
||||
type GitInitInput,
|
||||
type GitListBranchesInput,
|
||||
type GitListBranchesResult,
|
||||
type GitRemoveWorktreeInput,
|
||||
type GitStatusInput,
|
||||
type GitStatusResult,
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
GitCreateWorktreeInput,
|
||||
GitCreateWorktreeResult,
|
||||
GitInitInput,
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
GitRemoveWorktreeInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ProcessRunResult, runProcess } from "./processRunner";
|
||||
|
||||
export interface TerminalCommandInput {
|
||||
command: string;
|
||||
@@ -25,419 +21,95 @@ export interface TerminalCommandInput {
|
||||
maxOutputBytes?: number;
|
||||
}
|
||||
|
||||
export type TerminalCommandResult = ProcessRunResult;
|
||||
|
||||
export interface GitStatusDetails extends Omit<GitStatusResult, "openPr"> {
|
||||
upstreamRef: string | null;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}
|
||||
|
||||
export interface GitPushResult {
|
||||
status: "pushed" | "skipped_up_to_date";
|
||||
branch: string;
|
||||
upstreamBranch?: string | undefined;
|
||||
setUpstream?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface GitRangeContext {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}
|
||||
|
||||
interface RunGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
export interface TerminalCommandResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
timedOut: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(
|
||||
args: readonly string[],
|
||||
cwd: string,
|
||||
timeoutMs = 30_000,
|
||||
): Promise<ProcessRunResult> {
|
||||
return runProcess("git", args, {
|
||||
cwd,
|
||||
timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
}
|
||||
|
||||
function trimStdout(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function parseBranchAb(value: string): { ahead: number; behind: number } {
|
||||
const match = value.match(/^\+(\d+)\s+-(\d+)$/);
|
||||
if (!match) return { ahead: 0, behind: 0 };
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
chunk: Buffer,
|
||||
maxBytes: number,
|
||||
): {
|
||||
next: string;
|
||||
nextBytes: number;
|
||||
truncated: boolean;
|
||||
} {
|
||||
const remaining = maxBytes - currentBytes;
|
||||
if (remaining <= 0) {
|
||||
return { next: target, nextBytes: currentBytes, truncated: true };
|
||||
}
|
||||
if (chunk.length <= remaining) {
|
||||
return {
|
||||
next: `${target}${chunk.toString()}`,
|
||||
nextBytes: currentBytes + chunk.length,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
ahead: Number(match[1] ?? "0"),
|
||||
behind: Number(match[2] ?? "0"),
|
||||
next: `${target}${chunk.subarray(0, remaining).toString()}`,
|
||||
nextBytes: currentBytes + remaining,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function commandLabel(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
/** Spawn git directly with an argv array — no shell, no quoting needed. */
|
||||
function runGit(args: string[], cwd: string, timeoutMs = 30_000): Promise<TerminalCommandResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn("git", args, {
|
||||
cwd,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
function normalizeGitSpawnError(cwd: string, error: unknown): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error("Failed to run git command.");
|
||||
}
|
||||
if (!fs.existsSync(cwd)) {
|
||||
return new Error(`Working directory does not exist: ${cwd}`);
|
||||
}
|
||||
if (error.message.includes("Command not found: git")) {
|
||||
return new Error("Git is required but not available on PATH.");
|
||||
}
|
||||
return new Error(`Failed to run git command: ${error.message}`);
|
||||
}
|
||||
const maxOutputBytes = DEFAULT_MAX_OUTPUT_BYTES;
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
let timedOut = false;
|
||||
let outputTruncated = false;
|
||||
|
||||
function normalizeGitExecutionError(args: readonly string[], result: TerminalCommandResult): Error {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return new Error("Current folder is not a git repository.");
|
||||
}
|
||||
if (result.timedOut) {
|
||||
return new Error(`${commandLabel(args)} timed out.`);
|
||||
}
|
||||
const detail =
|
||||
stderr.length > 0 ? stderr : `code=${result.code ?? "null"}, signal=${result.signal ?? "null"}`;
|
||||
return new Error(`${commandLabel(args)} failed: ${detail}`);
|
||||
}
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (!child.killed) child.kill("SIGKILL");
|
||||
}, 1_000).unref();
|
||||
}, timeoutMs);
|
||||
|
||||
async function runGitOrThrow(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: RunGitOptions = {},
|
||||
): Promise<TerminalCommandResult> {
|
||||
let result: TerminalCommandResult;
|
||||
try {
|
||||
result = await runGit(args, cwd, options.timeoutMs);
|
||||
} catch (error) {
|
||||
throw normalizeGitSpawnError(cwd, error);
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw normalizeGitExecutionError(args, result);
|
||||
}
|
||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
||||
throw normalizeGitExecutionError(args, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function executeGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: ExecuteGitOptions = {},
|
||||
): Promise<TerminalCommandResult> {
|
||||
const result = await runGitOrThrow(cwd, args, {
|
||||
timeoutMs: options.timeoutMs,
|
||||
allowNonZeroExit: true,
|
||||
child.stdout?.on("data", (chunk: Buffer) => {
|
||||
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunk, maxOutputBytes);
|
||||
stdout = appended.next;
|
||||
stdoutBytes = appended.nextBytes;
|
||||
outputTruncated = outputTruncated || appended.truncated;
|
||||
});
|
||||
child.stderr?.on("data", (chunk: Buffer) => {
|
||||
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunk, maxOutputBytes);
|
||||
stderr = appended.next;
|
||||
stderrBytes = appended.nextBytes;
|
||||
outputTruncated = outputTruncated || appended.truncated;
|
||||
});
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.on("close", (code, signal) => {
|
||||
clearTimeout(timeout);
|
||||
if (outputTruncated) {
|
||||
stderr = `${stderr}\n[output truncated at ${maxOutputBytes} bytes]`;
|
||||
}
|
||||
resolve({ stdout, stderr, code: code ?? null, signal: signal ?? null, timedOut });
|
||||
});
|
||||
});
|
||||
|
||||
if (options.allowNonZeroExit || result.code === 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.length > 0) {
|
||||
throw new Error(stderr);
|
||||
}
|
||||
if (options.fallbackErrorMessage) {
|
||||
throw new Error(options.fallbackErrorMessage);
|
||||
}
|
||||
throw normalizeGitExecutionError(args, result);
|
||||
}
|
||||
|
||||
export class GitCoreService {
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.statusDetails(input.cwd);
|
||||
return gitStatusResultSchema.parse({
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr: null,
|
||||
});
|
||||
}
|
||||
|
||||
async statusDetails(cwd: string): Promise<GitStatusDetails> {
|
||||
const stdout = await this.gitStdout(cwd, ["status", "--porcelain=2", "--branch"]);
|
||||
|
||||
let branch: string | null = null;
|
||||
let upstreamRef: string | null = null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
let hasWorkingTreeChanges = false;
|
||||
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
if (line.startsWith("# branch.head ")) {
|
||||
const value = line.slice("# branch.head ".length).trim();
|
||||
branch = value.startsWith("(") ? null : value;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.upstream ")) {
|
||||
const value = line.slice("# branch.upstream ".length).trim();
|
||||
upstreamRef = value.length > 0 ? value : null;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("# branch.ab ")) {
|
||||
const value = line.slice("# branch.ab ".length).trim();
|
||||
const parsed = parseBranchAb(value);
|
||||
aheadCount = parsed.ahead;
|
||||
behindCount = parsed.behind;
|
||||
continue;
|
||||
}
|
||||
if (line.trim().length > 0 && !line.startsWith("#")) {
|
||||
hasWorkingTreeChanges = true;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
branch,
|
||||
upstreamRef,
|
||||
hasWorkingTreeChanges,
|
||||
hasUpstream: upstreamRef !== null,
|
||||
aheadCount,
|
||||
behindCount,
|
||||
};
|
||||
}
|
||||
|
||||
async prepareCommitContext(cwd: string): Promise<GitPreparedCommitContext | null> {
|
||||
await this.git(cwd, ["add", "-A"]);
|
||||
|
||||
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",
|
||||
]);
|
||||
|
||||
return {
|
||||
stagedSummary,
|
||||
stagedPatch,
|
||||
};
|
||||
}
|
||||
|
||||
async commit(cwd: string, subject: string, body: string): Promise<{ commitSha: string }> {
|
||||
const args = ["commit", "-m", subject];
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length > 0) {
|
||||
args.push("-m", trimmedBody);
|
||||
}
|
||||
await this.git(cwd, args);
|
||||
const commitSha = trimStdout(await this.gitStdout(cwd, ["rev-parse", "HEAD"]));
|
||||
return { commitSha };
|
||||
}
|
||||
|
||||
async pushCurrentBranch(cwd: string, fallbackBranch: string | null): Promise<GitPushResult> {
|
||||
const details = await this.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
throw new Error("Cannot push from detached HEAD.");
|
||||
}
|
||||
|
||||
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
|
||||
return {
|
||||
status: "skipped_up_to_date",
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!details.hasUpstream) {
|
||||
await this.git(cwd, ["push", "-u", "origin", branch]);
|
||||
return {
|
||||
status: "pushed",
|
||||
branch,
|
||||
upstreamBranch: `origin/${branch}`,
|
||||
setUpstream: true,
|
||||
};
|
||||
}
|
||||
|
||||
await this.git(cwd, ["push"]);
|
||||
return {
|
||||
status: "pushed",
|
||||
branch,
|
||||
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
|
||||
setUpstream: false,
|
||||
};
|
||||
}
|
||||
|
||||
async readRangeContext(cwd: string, baseBranch: string): Promise<GitRangeContext> {
|
||||
const range = `${baseBranch}..HEAD`;
|
||||
const [commitSummary, diffSummary, diffPatch] = await Promise.all([
|
||||
this.gitStdout(cwd, ["log", "--oneline", range]),
|
||||
this.gitStdout(cwd, ["diff", "--stat", range]),
|
||||
this.gitStdout(cwd, ["diff", "--patch", "--minimal", range]),
|
||||
]);
|
||||
|
||||
return {
|
||||
commitSummary,
|
||||
diffSummary,
|
||||
diffPatch,
|
||||
};
|
||||
}
|
||||
|
||||
async readConfigValue(cwd: string, key: string): Promise<string | null> {
|
||||
const stdout = await this.gitStdout(cwd, ["config", "--get", key], true);
|
||||
const value = trimStdout(stdout);
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.toLowerCase().includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
throw new Error(stderr || "git branch failed");
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList] = await Promise.all([
|
||||
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
executeGit(input.cwd, ["worktree", "list", "--porcelain"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
]);
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
|
||||
: null;
|
||||
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.code === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const branches = result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
if (a.current !== b.current) return a.current ? -1 : 1;
|
||||
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return { branches, isRepo: true };
|
||||
}
|
||||
|
||||
async createWorktree(input: GitCreateWorktreeInput): Promise<GitCreateWorktreeResult> {
|
||||
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath =
|
||||
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
|
||||
|
||||
await executeGit(
|
||||
input.cwd,
|
||||
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
|
||||
{ fallbackErrorMessage: "git worktree add failed" },
|
||||
);
|
||||
|
||||
return {
|
||||
worktree: {
|
||||
path: worktreePath,
|
||||
branch: input.newBranch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async removeWorktree(input: GitRemoveWorktreeInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["worktree", "remove", input.path], {
|
||||
timeoutMs: 15_000,
|
||||
fallbackErrorMessage: "git worktree remove failed",
|
||||
});
|
||||
}
|
||||
|
||||
async createBranch(input: GitCreateBranchInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["branch", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git branch create failed",
|
||||
});
|
||||
}
|
||||
|
||||
async checkoutBranch(input: GitCheckoutInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["checkout", input.branch], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git checkout failed",
|
||||
});
|
||||
}
|
||||
|
||||
async initRepo(input: GitInitInput): Promise<void> {
|
||||
await executeGit(input.cwd, ["init"], {
|
||||
timeoutMs: 10_000,
|
||||
fallbackErrorMessage: "git init failed",
|
||||
});
|
||||
}
|
||||
|
||||
async git(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<void> {
|
||||
await executeGit(cwd, args, { allowNonZeroExit });
|
||||
}
|
||||
|
||||
async gitStdout(cwd: string, args: readonly string[], allowNonZeroExit = false): Promise<string> {
|
||||
const result = await executeGit(cwd, args, { allowNonZeroExit });
|
||||
return result.stdout;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultGitCoreService = new GitCoreService();
|
||||
|
||||
export async function runTerminalCommand(
|
||||
input: TerminalCommandInput,
|
||||
): Promise<TerminalCommandResult> {
|
||||
@@ -450,46 +122,177 @@ export async function runTerminalCommand(
|
||||
const args =
|
||||
process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];
|
||||
|
||||
const result = await runProcess(shellPath, args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? 30_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: maxOutputBytes,
|
||||
outputMode: "truncate",
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(shellPath, args, {
|
||||
cwd: input.cwd,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
let timedOut = false;
|
||||
let outputTruncated = false;
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => {
|
||||
if (!child.killed) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 1_000).unref();
|
||||
}, input.timeoutMs ?? 30_000);
|
||||
|
||||
child.stdout?.on("data", (chunk: Buffer) => {
|
||||
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunk, maxOutputBytes);
|
||||
stdout = appended.next;
|
||||
stdoutBytes = appended.nextBytes;
|
||||
outputTruncated = outputTruncated || appended.truncated;
|
||||
});
|
||||
|
||||
child.stderr?.on("data", (chunk: Buffer) => {
|
||||
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunk, maxOutputBytes);
|
||||
stderr = appended.next;
|
||||
stderrBytes = appended.nextBytes;
|
||||
outputTruncated = outputTruncated || appended.truncated;
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
child.on("close", (code, signal) => {
|
||||
clearTimeout(timeout);
|
||||
if (outputTruncated) {
|
||||
stderr = `${stderr}\n[output truncated at ${maxOutputBytes} bytes]`;
|
||||
}
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
code: code ?? null,
|
||||
signal: signal ?? null,
|
||||
timedOut,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if (!result.stdoutTruncated && !result.stderrTruncated) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
...result,
|
||||
stderr: `${result.stderr}\n[output truncated at ${maxOutputBytes} bytes]`,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listGitBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||
return defaultGitCoreService.listBranches(input);
|
||||
const result = await runGit(["branch", "--no-color"], input.cwd, 10_000);
|
||||
|
||||
if (result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
if (stderr.includes("not a git repository")) {
|
||||
return { branches: [], isRepo: false };
|
||||
}
|
||||
throw new Error(stderr || "git branch failed");
|
||||
}
|
||||
|
||||
// Resolve the real default branch from the remote
|
||||
const [defaultRef, worktreeList] = await Promise.all([
|
||||
runGit(["symbolic-ref", "refs/remotes/origin/HEAD"], input.cwd, 5_000),
|
||||
runGit(["worktree", "list", "--porcelain"], input.cwd, 5_000),
|
||||
]);
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0 ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") : null;
|
||||
|
||||
// Build branch-name → worktree-path map from porcelain output.
|
||||
// Only include worktrees whose directories still exist on disk (skip prunable/stale ones).
|
||||
const worktreeMap = new Map<string, string>();
|
||||
if (worktreeList.code === 0) {
|
||||
let currentPath: string | null = null;
|
||||
for (const line of worktreeList.stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
const candidatePath = line.slice("worktree ".length);
|
||||
currentPath = fs.existsSync(candidatePath) ? candidatePath : null;
|
||||
} else if (line.startsWith("branch refs/heads/") && currentPath) {
|
||||
worktreeMap.set(line.slice("branch refs/heads/".length), currentPath);
|
||||
} else if (line === "") {
|
||||
currentPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const branches = result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => {
|
||||
const name = line.replace(/^[*+]\s+/, "");
|
||||
return {
|
||||
name,
|
||||
current: line.startsWith("* "),
|
||||
isDefault: name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
if (a.current !== b.current) return a.current ? -1 : 1;
|
||||
if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return { branches, isRepo: true };
|
||||
}
|
||||
|
||||
export async function createGitWorktree(
|
||||
input: GitCreateWorktreeInput,
|
||||
): Promise<GitCreateWorktreeResult> {
|
||||
return defaultGitCoreService.createWorktree(input);
|
||||
const sanitizedBranch = input.newBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath =
|
||||
input.path ?? path.join(os.homedir(), ".t3", "worktrees", repoName, sanitizedBranch);
|
||||
|
||||
// Create a new branch from the base branch in a new worktree
|
||||
const result = await runGit(
|
||||
["worktree", "add", "-b", input.newBranch, worktreePath, input.branch],
|
||||
input.cwd,
|
||||
);
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || "git worktree add failed");
|
||||
}
|
||||
|
||||
return {
|
||||
worktree: {
|
||||
path: worktreePath,
|
||||
branch: input.newBranch,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function removeGitWorktree(input: GitRemoveWorktreeInput): Promise<void> {
|
||||
await defaultGitCoreService.removeWorktree(input);
|
||||
const result = await runGit(["worktree", "remove", input.path], input.cwd, 15_000);
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || "git worktree remove failed");
|
||||
}
|
||||
}
|
||||
|
||||
export async function createGitBranch(input: GitCreateBranchInput): Promise<void> {
|
||||
await defaultGitCoreService.createBranch(input);
|
||||
const result = await runGit(["branch", input.branch], input.cwd, 10_000);
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || "git branch create failed");
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkoutGitBranch(input: GitCheckoutInput): Promise<void> {
|
||||
await defaultGitCoreService.checkoutBranch(input);
|
||||
const result = await runGit(["checkout", input.branch], input.cwd, 10_000);
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || "git checkout failed");
|
||||
}
|
||||
}
|
||||
|
||||
export async function initGitRepo(input: GitInitInput): Promise<void> {
|
||||
await defaultGitCoreService.initRepo(input);
|
||||
const result = await runGit(["init"], input.cwd, 10_000);
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || "git init failed");
|
||||
}
|
||||
}
|
||||
@@ -1,490 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { GitManager } from "./gitManager";
|
||||
import {
|
||||
type ProcessRunOptions,
|
||||
type ProcessRunResult,
|
||||
runProcess,
|
||||
} from "./processRunner";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
createdPrUrl?: string;
|
||||
defaultBranch?: string;
|
||||
failWith?: Error;
|
||||
}
|
||||
|
||||
interface FakeGitTextGenerator {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}) => Promise<{ subject: string; body: string }>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
}) => Promise<{ title: string; body: string }>;
|
||||
}
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(prefix: string): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
allowNonZeroExit = false,
|
||||
): Promise<ProcessRunResult> {
|
||||
return runProcess("git", args, { cwd, allowNonZeroExit });
|
||||
}
|
||||
|
||||
async function runGitStdout(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await runGit(cwd, args);
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
async function initRepo(cwd: string): Promise<void> {
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
await runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
await runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "hello\n");
|
||||
await runGit(cwd, ["add", "README.md"]);
|
||||
await runGit(cwd, ["commit", "-m", "Initial commit"]);
|
||||
}
|
||||
|
||||
async function createBareRemote(): Promise<string> {
|
||||
const remoteDir = makeTempDir("t3code-git-remote-");
|
||||
await runProcess("git", ["init", "--bare"], { cwd: remoteDir });
|
||||
return remoteDir;
|
||||
}
|
||||
|
||||
function createTextGenerator(
|
||||
overrides: Partial<FakeGitTextGenerator> = {},
|
||||
): FakeGitTextGenerator {
|
||||
return {
|
||||
generateCommitMessage: async () => ({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
}),
|
||||
generatePrContent: async () => ({
|
||||
title: "Add stacked git actions",
|
||||
body: "## Summary\n- Add stacked git workflow\n\n## Testing\n- Not run",
|
||||
}),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createRunnerWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
runner: (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>;
|
||||
ghCalls: string[];
|
||||
} {
|
||||
const prListQueue = [...(scenario.prListSequence ?? [])];
|
||||
const ghCalls: string[] = [];
|
||||
|
||||
const runner = async (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
): Promise<ProcessRunResult> => {
|
||||
if (command !== "gh") {
|
||||
return runProcess(command, args, options);
|
||||
}
|
||||
|
||||
ghCalls.push(args.join(" "));
|
||||
if (scenario.failWith) {
|
||||
throw scenario.failWith;
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "list") {
|
||||
const stdout = (prListQueue.shift() ?? "[]") + "\n";
|
||||
return {
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "create") {
|
||||
return {
|
||||
stdout:
|
||||
(scenario.createdPrUrl ??
|
||||
"https://github.com/pingdotgg/codething-mvp/pull/101") + "\n",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (args[0] === "pr" && args[1] === "view") {
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (args[0] === "repo" && args[1] === "view") {
|
||||
return {
|
||||
stdout: `${scenario.defaultBranch ?? "main"}\n`,
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected gh command: ${args.join(" ")}`);
|
||||
};
|
||||
|
||||
return { runner, ghCalls };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("GitManager", () => {
|
||||
it("status includes open PR metadata when branch already has an open PR", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/status-open-pr"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/status-open-pr"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-open-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
const status = await manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-open-pr");
|
||||
expect(status.openPr).toEqual({
|
||||
number: 13,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-open-pr",
|
||||
});
|
||||
});
|
||||
|
||||
it("status is resilient to gh lookup failures and returns openPr null", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/status-no-gh"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/status-no-gh"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
failWith: new Error("Command not found: gh"),
|
||||
});
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
const status = await manager.status({ cwd: repoDir });
|
||||
expect(status.branch).toBe("feature/status-no-gh");
|
||||
expect(status.openPr).toBeNull();
|
||||
});
|
||||
|
||||
it("creates a commit when working tree is dirty", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
|
||||
"Implement stacked git actions",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses custom commit message when provided", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator({
|
||||
generateCommitMessage: async () => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%s"])).toBe(
|
||||
"feat: custom summary line",
|
||||
);
|
||||
expect(await runGitStdout(repoDir, ["log", "-1", "--pretty=%b"])).toContain(
|
||||
"- details from user",
|
||||
);
|
||||
});
|
||||
|
||||
it("skips commit when there are no uncommitted changes", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
});
|
||||
|
||||
it("commits and pushes with upstream auto-setup when needed", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/stacked-flow"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
expect(await runGitStdout(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
|
||||
"origin/feature/stacked-flow",
|
||||
);
|
||||
});
|
||||
|
||||
it("skips push when branch is already up to date", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/up-to-date"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/up-to-date"]);
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("opens existing PR for commit/push/pr action", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/existing-pr"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/existing-pr"]);
|
||||
|
||||
const { runner, ghCalls } = createRunnerWithFakeGh({
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 42,
|
||||
title: "Existing PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/existing-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it("creates PR when one does not already exist", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
|
||||
await runGit(repoDir, ["add", "changes.txt"]);
|
||||
await runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
|
||||
await runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
|
||||
|
||||
const { runner, ghCalls } = createRunnerWithFakeGh({
|
||||
prListSequence: [
|
||||
"[]",
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 88,
|
||||
title: "Add stacked git actions",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/88",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature-create-pr",
|
||||
},
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
const result = await manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects push/pr actions from detached HEAD", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "--detach", "HEAD"]);
|
||||
|
||||
const manager = new GitManager({
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
await expect(
|
||||
manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
}),
|
||||
).rejects.toThrow("detached HEAD");
|
||||
});
|
||||
|
||||
it("surfaces missing gh binary errors", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/gh-missing"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-missing"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
failWith: new Error("Command not found: gh"),
|
||||
});
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
await expect(
|
||||
manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}),
|
||||
).rejects.toThrow("GitHub CLI (`gh`) is required");
|
||||
});
|
||||
|
||||
it("surfaces gh auth errors with guidance", async () => {
|
||||
const repoDir = makeTempDir("t3code-git-manager-");
|
||||
await initRepo(repoDir);
|
||||
await runGit(repoDir, ["checkout", "-b", "feature/gh-auth"]);
|
||||
const remoteDir = await createBareRemote();
|
||||
await runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
await runGit(repoDir, ["push", "-u", "origin", "feature/gh-auth"]);
|
||||
|
||||
const { runner } = createRunnerWithFakeGh({
|
||||
failWith: new Error("authentication failed"),
|
||||
});
|
||||
const manager = new GitManager({
|
||||
runProcess: runner,
|
||||
textGenerator: createTextGenerator(),
|
||||
});
|
||||
|
||||
await expect(
|
||||
manager.runStackedAction({
|
||||
cwd: repoDir,
|
||||
action: "commit_push_pr",
|
||||
}),
|
||||
).rejects.toThrow("gh auth login");
|
||||
});
|
||||
});
|
||||
@@ -1,506 +0,0 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
gitRunStackedActionInputSchema,
|
||||
gitRunStackedActionResultSchema,
|
||||
gitStatusInputSchema,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type GitStatusInput,
|
||||
type GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
CommitMessageGenerationResult,
|
||||
PrContentGenerationResult,
|
||||
TextGenerationService,
|
||||
} from "./coreServices";
|
||||
import { CodexTextGenerator } from "./codexTextGenerator";
|
||||
import { GitCoreService } from "./git";
|
||||
import {
|
||||
type ProcessRunOptions,
|
||||
type ProcessRunResult,
|
||||
runProcess,
|
||||
} from "./processRunner";
|
||||
|
||||
const GH_CLI_TIMEOUT_MS = 30_000;
|
||||
|
||||
interface GitManagerDeps {
|
||||
runProcess?: (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options?: ProcessRunOptions,
|
||||
) => Promise<ProcessRunResult>;
|
||||
textGenerator?: TextGenerationService;
|
||||
gitCore?: GitCoreService;
|
||||
}
|
||||
|
||||
interface OpenPrInfo {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseRefName: string;
|
||||
headRefName: string;
|
||||
}
|
||||
|
||||
function parseOpenPrList(raw: unknown): OpenPrInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: OpenPrInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
if (
|
||||
typeof number !== "number" ||
|
||||
!Number.isInteger(number) ||
|
||||
number <= 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function trimStdout(value: string): string {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function limitContext(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) return value;
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(
|
||||
generated: CommitMessageGenerationResult,
|
||||
): 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";
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function parseCustomCommitMessage(raw: string): CommitMessageGenerationResult | null {
|
||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [firstLine, ...rest] = normalized.split("\n");
|
||||
const subject = firstLine?.trim() ?? "";
|
||||
if (subject.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
subject,
|
||||
body: rest.join("\n").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function extractBranchFromRef(ref: string): string {
|
||||
const normalized = ref.trim();
|
||||
|
||||
if (normalized.startsWith("refs/remotes/")) {
|
||||
const withoutPrefix = normalized.slice("refs/remotes/".length);
|
||||
const firstSlash = withoutPrefix.indexOf("/");
|
||||
if (firstSlash === -1) {
|
||||
return withoutPrefix.trim();
|
||||
}
|
||||
return withoutPrefix.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
const firstSlash = normalized.indexOf("/");
|
||||
if (firstSlash === -1) {
|
||||
return normalized;
|
||||
}
|
||||
return normalized.slice(firstSlash + 1).trim();
|
||||
}
|
||||
|
||||
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") {
|
||||
return new Error("GitHub CLI (`gh`) is required but not available on PATH.");
|
||||
}
|
||||
if (command === "codex") {
|
||||
return new Error("Codex CLI (`codex`) is required but not available on PATH.");
|
||||
}
|
||||
return new Error(`${command} is required but not available on PATH.`);
|
||||
}
|
||||
|
||||
function normalizeGitHubAuthError(error: unknown): Error | undefined {
|
||||
if (!(error instanceof Error)) return undefined;
|
||||
const lower = error.message.toLowerCase();
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new Error("GitHub CLI is not authenticated. Run `gh auth login` and retry.");
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function toStatusOpenPr(pr: OpenPrInfo): {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
} {
|
||||
return {
|
||||
number: pr.number,
|
||||
title: pr.title,
|
||||
url: pr.url,
|
||||
baseBranch: pr.baseRefName,
|
||||
headBranch: pr.headRefName,
|
||||
};
|
||||
}
|
||||
|
||||
export class GitManager {
|
||||
private readonly run: NonNullable<GitManagerDeps["runProcess"]>;
|
||||
private readonly textGenerator: TextGenerationService;
|
||||
private readonly gitCore: GitCoreService;
|
||||
|
||||
constructor(deps: GitManagerDeps = {}) {
|
||||
this.run = deps.runProcess ?? runProcess;
|
||||
this.textGenerator = deps.textGenerator ?? new CodexTextGenerator();
|
||||
this.gitCore = deps.gitCore ?? new GitCoreService();
|
||||
}
|
||||
|
||||
async status(raw: GitStatusInput): Promise<GitStatusResult> {
|
||||
const input = gitStatusInputSchema.parse(raw);
|
||||
const details = await this.gitCore.statusDetails(input.cwd);
|
||||
|
||||
let openPr: ReturnType<typeof toStatusOpenPr> | null = null;
|
||||
if (details.branch && details.hasUpstream) {
|
||||
try {
|
||||
const existing = await this.findOpenPr(input.cwd, details.branch);
|
||||
if (existing) {
|
||||
openPr = toStatusOpenPr(existing);
|
||||
}
|
||||
} catch {
|
||||
// PR lookup is best-effort for status rendering.
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
branch: details.branch,
|
||||
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
|
||||
hasUpstream: details.hasUpstream,
|
||||
aheadCount: details.aheadCount,
|
||||
behindCount: details.behindCount,
|
||||
openPr,
|
||||
};
|
||||
}
|
||||
|
||||
async runStackedAction(
|
||||
raw: GitRunStackedActionInput,
|
||||
): Promise<GitRunStackedActionResult> {
|
||||
const input = gitRunStackedActionInputSchema.parse(raw);
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
const initialStatus = await this.gitCore.statusDetails(input.cwd);
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
throw new Error("Cannot push from detached HEAD.");
|
||||
}
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
throw new Error("Cannot create a pull request from detached HEAD.");
|
||||
}
|
||||
|
||||
const commit = await this.runCommitStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
? await this.gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? await this.runPrStep(input.cwd, initialStatus.branch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return gitRunStackedActionResultSchema.parse({
|
||||
action: input.action,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
});
|
||||
}
|
||||
|
||||
private async runCommitStep(
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
): Promise<{
|
||||
status: "created" | "skipped_no_changes";
|
||||
commitSha?: string | undefined;
|
||||
subject?: string | undefined;
|
||||
}> {
|
||||
const context = await this.gitCore.prepareCommitContext(cwd);
|
||||
if (!context) {
|
||||
return { status: "skipped_no_changes" };
|
||||
}
|
||||
|
||||
let generated: CommitMessageGenerationResult | null = parseCustomCommitMessage(
|
||||
commitMessage ?? "",
|
||||
);
|
||||
|
||||
if (!generated) {
|
||||
try {
|
||||
generated = sanitizeCommitMessage(
|
||||
await this.textGenerator.generateCommitMessage({
|
||||
cwd,
|
||||
branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
throw asCommandNotFound("codex", error) ?? error;
|
||||
}
|
||||
}
|
||||
|
||||
const { commitSha } = await this.gitCore.commit(cwd, generated.subject, generated.body);
|
||||
return {
|
||||
status: "created",
|
||||
commitSha,
|
||||
subject: generated.subject,
|
||||
};
|
||||
}
|
||||
|
||||
private async runPrStep(
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
): Promise<{
|
||||
status: "created" | "opened_existing" | "skipped_not_requested";
|
||||
url?: string | undefined;
|
||||
number?: number | undefined;
|
||||
baseBranch?: string | undefined;
|
||||
headBranch?: string | undefined;
|
||||
title?: string | undefined;
|
||||
}> {
|
||||
const details = await this.gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
if (!branch) {
|
||||
throw new Error("Cannot create a pull request from detached HEAD.");
|
||||
}
|
||||
if (!details.hasUpstream) {
|
||||
throw new Error("Current branch has not been pushed. Push before creating a PR.");
|
||||
}
|
||||
|
||||
const existing = await this.findOpenPr(cwd, branch);
|
||||
if (existing) {
|
||||
await this.openPrInBrowser(cwd, branch);
|
||||
return {
|
||||
status: "opened_existing",
|
||||
url: existing.url,
|
||||
number: existing.number,
|
||||
baseBranch: existing.baseRefName,
|
||||
headBranch: existing.headRefName,
|
||||
title: existing.title,
|
||||
};
|
||||
}
|
||||
|
||||
const baseBranch = await this.resolveBaseBranch(cwd, branch, details.upstreamRef);
|
||||
const rangeContext = await this.gitCore.readRangeContext(cwd, baseBranch);
|
||||
|
||||
let generated: PrContentGenerationResult;
|
||||
try {
|
||||
generated = await this.textGenerator.generatePrContent({
|
||||
cwd,
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
});
|
||||
} catch (error) {
|
||||
throw asCommandNotFound("codex", error) ?? error;
|
||||
}
|
||||
|
||||
const bodyFile = path.join(
|
||||
os.tmpdir(),
|
||||
`t3code-pr-body-${process.pid}-${randomUUID()}.md`,
|
||||
);
|
||||
await fs.writeFile(bodyFile, generated.body, "utf8");
|
||||
|
||||
try {
|
||||
await this.runGh(cwd, [
|
||||
"pr",
|
||||
"create",
|
||||
"--base",
|
||||
baseBranch,
|
||||
"--head",
|
||||
branch,
|
||||
"--title",
|
||||
generated.title,
|
||||
"--body-file",
|
||||
bodyFile,
|
||||
]);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(bodyFile);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
}
|
||||
|
||||
const created = await this.findOpenPr(cwd, branch);
|
||||
await this.openPrInBrowser(cwd, branch);
|
||||
|
||||
if (!created) {
|
||||
return {
|
||||
status: "created",
|
||||
baseBranch,
|
||||
headBranch: branch,
|
||||
title: generated.title,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: "created",
|
||||
url: created.url,
|
||||
number: created.number,
|
||||
baseBranch: created.baseRefName,
|
||||
headBranch: created.headRefName,
|
||||
title: created.title,
|
||||
};
|
||||
}
|
||||
|
||||
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> {
|
||||
const stdout = await this.runGhStdout(cwd, [
|
||||
"pr",
|
||||
"list",
|
||||
"--head",
|
||||
branch,
|
||||
"--state",
|
||||
"open",
|
||||
"--limit",
|
||||
"1",
|
||||
"--json",
|
||||
"number,title,url,baseRefName,headRefName",
|
||||
]);
|
||||
|
||||
const raw = trimStdout(stdout);
|
||||
if (raw.length === 0) return null;
|
||||
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
parsedJson = JSON.parse(raw);
|
||||
} catch {
|
||||
throw new Error("GitHub CLI returned invalid PR list JSON.");
|
||||
}
|
||||
|
||||
const parsed = parseOpenPrList(parsedJson);
|
||||
return parsed[0] ?? null;
|
||||
}
|
||||
|
||||
private async resolveBaseBranch(
|
||||
cwd: string,
|
||||
branch: string,
|
||||
upstreamRef: string | null,
|
||||
): Promise<string> {
|
||||
const configured = await this.gitCore.readConfigValue(
|
||||
cwd,
|
||||
`branch.${branch}.gh-merge-base`,
|
||||
);
|
||||
if (configured) return configured;
|
||||
|
||||
if (upstreamRef) {
|
||||
const upstreamBranch = extractBranchFromRef(upstreamRef);
|
||||
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
|
||||
return upstreamBranch;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const ghDefault = await this.runGhStdout(cwd, [
|
||||
"repo",
|
||||
"view",
|
||||
"--json",
|
||||
"defaultBranchRef",
|
||||
"--jq",
|
||||
".defaultBranchRef.name",
|
||||
]);
|
||||
const defaultBranch = trimStdout(ghDefault);
|
||||
if (defaultBranch.length > 0) return defaultBranch;
|
||||
} catch {
|
||||
// Fall through to deterministic fallback.
|
||||
}
|
||||
|
||||
return "main";
|
||||
}
|
||||
|
||||
private async runGh(cwd: string, args: readonly string[]): Promise<void> {
|
||||
await this.runGhCommand(cwd, args);
|
||||
}
|
||||
|
||||
private async runGhStdout(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await this.runGhCommand(cwd, args);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
private async runGhCommand(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
): Promise<ProcessRunResult> {
|
||||
try {
|
||||
return await this.run("gh", args, {
|
||||
cwd,
|
||||
timeoutMs: GH_CLI_TIMEOUT_MS,
|
||||
});
|
||||
} catch (error) {
|
||||
throw (
|
||||
asCommandNotFound("gh", error) ??
|
||||
normalizeGitHubAuthError(error) ??
|
||||
(error instanceof Error ? error : new Error("GitHub CLI command failed."))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
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 },
|
||||
),
|
||||
).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",
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.code).toBe(0);
|
||||
expect(result.stdout.length).toBeLessThanOrEqual(128);
|
||||
expect(result.stdoutTruncated).toBe(true);
|
||||
expect(result.stderrTruncated).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,271 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
timeoutMs?: number | undefined;
|
||||
env?: NodeJS.ProcessEnv | undefined;
|
||||
stdin?: string | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
maxBufferBytes?: number | undefined;
|
||||
outputMode?: "error" | "truncate" | undefined;
|
||||
}
|
||||
|
||||
export interface ProcessRunResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
code: number | null;
|
||||
signal: NodeJS.Signals | null;
|
||||
timedOut: boolean;
|
||||
stdoutTruncated?: boolean | undefined;
|
||||
stderrTruncated?: boolean | undefined;
|
||||
}
|
||||
|
||||
function commandLabel(command: string, args: readonly string[]): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
function normalizeSpawnError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
error: unknown,
|
||||
): Error {
|
||||
if (!(error instanceof Error)) {
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}.`);
|
||||
}
|
||||
|
||||
const maybeCode = (error as NodeJS.ErrnoException).code;
|
||||
if (maybeCode === "ENOENT") {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
return new Error(
|
||||
`Failed to run ${commandLabel(command, args)}: ${error.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
): Error {
|
||||
const reason = result.timedOut
|
||||
? "timed out"
|
||||
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
||||
const stderr = result.stderr.trim();
|
||||
const detail = stderr.length > 0 ? ` ${stderr}` : "";
|
||||
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
|
||||
}
|
||||
|
||||
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}`,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeBufferError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
stream: "stdout" | "stderr",
|
||||
maxBufferBytes: number,
|
||||
): Error {
|
||||
return new Error(
|
||||
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
|
||||
);
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
chunk: Buffer,
|
||||
maxBytes: number,
|
||||
): {
|
||||
next: string;
|
||||
nextBytes: number;
|
||||
truncated: boolean;
|
||||
} {
|
||||
const remaining = maxBytes - currentBytes;
|
||||
if (remaining <= 0) {
|
||||
return { next: target, nextBytes: currentBytes, truncated: true };
|
||||
}
|
||||
if (chunk.length <= remaining) {
|
||||
return {
|
||||
next: `${target}${chunk.toString()}`,
|
||||
nextBytes: currentBytes + chunk.length,
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
next: `${target}${chunk.subarray(0, remaining).toString()}`,
|
||||
nextBytes: currentBytes + remaining,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function runProcess(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: ProcessRunOptions = {},
|
||||
): Promise<ProcessRunResult> {
|
||||
const timeoutMs = options.timeoutMs ?? 60_000;
|
||||
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
|
||||
const outputMode = options.outputMode ?? "error";
|
||||
|
||||
return new Promise<ProcessRunResult>((resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let stdoutBytes = 0;
|
||||
let stderrBytes = 0;
|
||||
let stdoutTruncated = false;
|
||||
let stderrTruncated = false;
|
||||
let timedOut = false;
|
||||
let settled = false;
|
||||
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
const finalize = (callback: () => void): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeoutTimer);
|
||||
if (forceKillTimer) {
|
||||
clearTimeout(forceKillTimer);
|
||||
}
|
||||
callback();
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
child.kill("SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
};
|
||||
|
||||
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,
|
||||
);
|
||||
stdout = appended.next;
|
||||
stdoutBytes = appended.nextBytes;
|
||||
stdoutTruncated = stdoutTruncated || appended.truncated;
|
||||
return null;
|
||||
}
|
||||
stdout += text;
|
||||
stdoutBytes += byteLength;
|
||||
if (stdoutBytes > maxBufferBytes) {
|
||||
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
|
||||
}
|
||||
} else {
|
||||
if (outputMode === "truncate") {
|
||||
const appended = appendChunkWithinLimit(
|
||||
stderr,
|
||||
stderrBytes,
|
||||
chunkBuffer,
|
||||
maxBufferBytes,
|
||||
);
|
||||
stderr = appended.next;
|
||||
stderrBytes = appended.nextBytes;
|
||||
stderrTruncated = stderrTruncated || appended.truncated;
|
||||
return null;
|
||||
}
|
||||
stderr += text;
|
||||
stderrBytes += byteLength;
|
||||
if (stderrBytes > maxBufferBytes) {
|
||||
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
child.stdout.on("data", (chunk: Buffer | string) => {
|
||||
const error = appendOutput("stdout", chunk);
|
||||
if (error) {
|
||||
fail(error);
|
||||
}
|
||||
});
|
||||
|
||||
child.stderr.on("data", (chunk: Buffer | string) => {
|
||||
const error = appendOutput("stderr", chunk);
|
||||
if (error) {
|
||||
fail(error);
|
||||
}
|
||||
});
|
||||
|
||||
child.once("error", (error) => {
|
||||
finalize(() => {
|
||||
reject(normalizeSpawnError(command, args, error));
|
||||
});
|
||||
});
|
||||
|
||||
child.once("close", (code, signal) => {
|
||||
const result: ProcessRunResult = {
|
||||
stdout,
|
||||
stderr,
|
||||
code,
|
||||
signal,
|
||||
timedOut,
|
||||
stdoutTruncated,
|
||||
stderrTruncated,
|
||||
};
|
||||
|
||||
finalize(() => {
|
||||
if (
|
||||
!options.allowNonZeroExit &&
|
||||
(timedOut || (code !== null && code !== 0))
|
||||
) {
|
||||
reject(normalizeExitError(command, args, result));
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
});
|
||||
});
|
||||
|
||||
child.stdin.once("error", (error) => {
|
||||
fail(normalizeStdinError(command, args, error));
|
||||
});
|
||||
|
||||
if (options.stdin !== undefined) {
|
||||
child.stdin.write(options.stdin, (error) => {
|
||||
if (error) {
|
||||
fail(normalizeStdinError(command, args, error));
|
||||
return;
|
||||
}
|
||||
child.stdin.end();
|
||||
});
|
||||
return;
|
||||
}
|
||||
child.stdin.end();
|
||||
});
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ensureNodePtySpawnHelperExecutable } from "./ptyAdapter";
|
||||
|
||||
function fileMode(filePath: string): number {
|
||||
return fs.statSync(filePath).mode & 0o777;
|
||||
}
|
||||
|
||||
describe("ensureNodePtySpawnHelperExecutable", () => {
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("adds executable bits when helper exists but is not executable", () => {
|
||||
if (process.platform === "win32") return;
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
|
||||
tempDirs.push(dir);
|
||||
const helperPath = path.join(dir, "spawn-helper");
|
||||
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
|
||||
fs.chmodSync(helperPath, 0o644);
|
||||
|
||||
ensureNodePtySpawnHelperExecutable(helperPath);
|
||||
|
||||
expect(fileMode(helperPath) & 0o111).toBe(0o111);
|
||||
});
|
||||
|
||||
it("keeps executable helper as executable", () => {
|
||||
if (process.platform === "win32") return;
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pty-helper-test-"));
|
||||
tempDirs.push(dir);
|
||||
const helperPath = path.join(dir, "spawn-helper");
|
||||
fs.writeFileSync(helperPath, "#!/bin/sh\nexit 0\n", "utf8");
|
||||
fs.chmodSync(helperPath, 0o755);
|
||||
|
||||
ensureNodePtySpawnHelperExecutable(helperPath);
|
||||
|
||||
expect(fileMode(helperPath) & 0o111).toBe(0o111);
|
||||
});
|
||||
|
||||
it("does not throw when helper path is missing", () => {
|
||||
const missing = path.join(os.tmpdir(), `does-not-exist-${Date.now()}`);
|
||||
expect(() => ensureNodePtySpawnHelperExecutable(missing)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,3 @@
|
||||
import fs from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
|
||||
import * as nodePty from "node-pty";
|
||||
|
||||
export interface PtyExitEvent {
|
||||
@@ -30,57 +26,6 @@ export interface PtyAdapter {
|
||||
spawn(input: PtySpawnInput): PtyProcess;
|
||||
}
|
||||
|
||||
const requireForNodePty = createRequire(import.meta.url);
|
||||
let didEnsureSpawnHelperExecutable = false;
|
||||
|
||||
function resolveNodePtySpawnHelperPath(): string | null {
|
||||
try {
|
||||
const packageJsonPath = requireForNodePty.resolve("node-pty/package.json");
|
||||
const packageDir = path.dirname(packageJsonPath);
|
||||
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",
|
||||
),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureNodePtySpawnHelperExecutable(explicitPath?: string): void {
|
||||
if (process.platform === "win32") return;
|
||||
if (!explicitPath && didEnsureSpawnHelperExecutable) return;
|
||||
|
||||
const helperPath = explicitPath ?? resolveNodePtySpawnHelperPath();
|
||||
if (!helperPath) return;
|
||||
if (!explicitPath) {
|
||||
didEnsureSpawnHelperExecutable = true;
|
||||
}
|
||||
|
||||
try {
|
||||
const stat = fs.statSync(helperPath);
|
||||
const mode = stat.mode & 0o777;
|
||||
if ((mode & 0o111) === 0) {
|
||||
fs.chmodSync(helperPath, mode | 0o111);
|
||||
}
|
||||
} catch {
|
||||
// Best effort only. If chmod fails, node-pty spawn will surface the real error.
|
||||
}
|
||||
}
|
||||
|
||||
class NodePtyProcess implements PtyProcess {
|
||||
constructor(private readonly process: nodePty.IPty) {}
|
||||
|
||||
@@ -122,16 +67,12 @@ class NodePtyProcess implements PtyProcess {
|
||||
|
||||
export class NodePtyAdapter implements PtyAdapter {
|
||||
spawn(input: PtySpawnInput): PtyProcess {
|
||||
ensureNodePtySpawnHelperExecutable();
|
||||
const ptyProcess = nodePty.spawn(input.shell, [], {
|
||||
cwd: input.cwd,
|
||||
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,7 +2,10 @@ 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 type {
|
||||
TerminalEvent,
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import type { PtyAdapter, PtyExitEvent, PtyProcess, PtySpawnInput } from "./ptyAdapter";
|
||||
@@ -59,15 +62,10 @@ class FakePtyProcess implements PtyProcess {
|
||||
class FakePtyAdapter implements PtyAdapter {
|
||||
readonly spawnInputs: PtySpawnInput[] = [];
|
||||
readonly processes: FakePtyProcess[] = [];
|
||||
readonly spawnFailures: Error[] = [];
|
||||
private nextPid = 9000;
|
||||
|
||||
spawn(input: PtySpawnInput): PtyProcess {
|
||||
this.spawnInputs.push(input);
|
||||
const failure = this.spawnFailures.shift();
|
||||
if (failure) {
|
||||
throw failure;
|
||||
}
|
||||
const process = new FakePtyProcess(this.nextPid++);
|
||||
this.processes.push(process);
|
||||
return process;
|
||||
@@ -106,26 +104,10 @@ function historyLogName(threadId: string): string {
|
||||
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}.log`;
|
||||
}
|
||||
|
||||
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
|
||||
const threadPart = `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
return `${threadPart}.log`;
|
||||
}
|
||||
return `${threadPart}_${Buffer.from(terminalId, "utf8").toString("base64url")}.log`;
|
||||
}
|
||||
|
||||
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
|
||||
return path.join(logsDir, historyLogName(threadId));
|
||||
}
|
||||
|
||||
function multiTerminalHistoryLogPath(
|
||||
logsDir: string,
|
||||
threadId = "thread-1",
|
||||
terminalId = "default",
|
||||
): string {
|
||||
return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
|
||||
}
|
||||
|
||||
describe("TerminalManager", () => {
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
@@ -135,10 +117,7 @@ describe("TerminalManager", () => {
|
||||
}
|
||||
});
|
||||
|
||||
function makeManager(
|
||||
historyLineLimit = 5,
|
||||
options: { shellResolver?: () => string } = {},
|
||||
) {
|
||||
function makeManager(historyLineLimit = 5) {
|
||||
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
|
||||
tempDirs.push(logsDir);
|
||||
const ptyAdapter = new FakePtyAdapter();
|
||||
@@ -146,7 +125,7 @@ describe("TerminalManager", () => {
|
||||
logsDir,
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
shellResolver: () => "/bin/bash",
|
||||
});
|
||||
return { logsDir, ptyAdapter, manager };
|
||||
}
|
||||
@@ -157,7 +136,6 @@ describe("TerminalManager", () => {
|
||||
const third = await manager.open(openInput());
|
||||
|
||||
expect(first.threadId).toBe("thread-1");
|
||||
expect(first.terminalId).toBe("default");
|
||||
expect(second.threadId).toBe("thread-1");
|
||||
expect(third.threadId).toBe("thread-1");
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(1);
|
||||
@@ -181,27 +159,6 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("supports multiple terminals per thread with isolated sessions", async () => {
|
||||
const { manager, ptyAdapter } = makeManager();
|
||||
await manager.open(openInput({ terminalId: "default" }));
|
||||
await manager.open(openInput({ terminalId: "term-2" }));
|
||||
|
||||
const first = ptyAdapter.processes[0];
|
||||
const second = ptyAdapter.processes[1];
|
||||
expect(first).toBeDefined();
|
||||
expect(second).toBeDefined();
|
||||
if (!first || !second) return;
|
||||
|
||||
await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" });
|
||||
await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" });
|
||||
|
||||
expect(first.writes).toEqual(["pwd\n"]);
|
||||
expect(second.writes).toEqual(["ls\n"]);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(2);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("clears transcript and emits cleared event", async () => {
|
||||
const { manager, ptyAdapter, logsDir } = makeManager();
|
||||
const events: TerminalEvent[] = [];
|
||||
@@ -219,14 +176,6 @@ describe("TerminalManager", () => {
|
||||
await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === "");
|
||||
|
||||
expect(events.some((event) => event.type === "cleared")).toBe(true);
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "cleared" &&
|
||||
event.threadId === "thread-1" &&
|
||||
event.terminalId === "default",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
@@ -305,35 +254,6 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("closes all terminals for a thread when close omits terminalId", async () => {
|
||||
const { manager, ptyAdapter, logsDir } = makeManager();
|
||||
await manager.open(openInput({ terminalId: "default" }));
|
||||
await manager.open(openInput({ terminalId: "sidecar" }));
|
||||
const defaultProcess = ptyAdapter.processes[0];
|
||||
const sidecarProcess = ptyAdapter.processes[1];
|
||||
expect(defaultProcess).toBeDefined();
|
||||
expect(sidecarProcess).toBeDefined();
|
||||
if (!defaultProcess || !sidecarProcess) return;
|
||||
|
||||
defaultProcess.emitData("default\n");
|
||||
sidecarProcess.emitData("sidecar\n");
|
||||
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
|
||||
await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
|
||||
|
||||
await manager.close({ threadId: "thread-1", deleteHistory: true });
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("loads existing legacy transcript filenames and keeps new naming for writes", async () => {
|
||||
const { manager, logsDir } = makeManager();
|
||||
const legacyPath = path.join(logsDir, "thread-1.log");
|
||||
@@ -346,35 +266,4 @@ describe("TerminalManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("retries with fallback shells when preferred shell spawn fails", async () => {
|
||||
const { manager, ptyAdapter } = makeManager(5, {
|
||||
shellResolver: () => "/definitely/missing-shell -l",
|
||||
});
|
||||
ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));
|
||||
|
||||
const snapshot = await manager.open(openInput());
|
||||
|
||||
expect(snapshot.status).toBe("running");
|
||||
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
|
||||
expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell");
|
||||
|
||||
if (process.platform === "win32") {
|
||||
expect(
|
||||
ptyAdapter.spawnInputs.some(
|
||||
(input) => input.shell === "cmd.exe" || input.shell === "powershell.exe",
|
||||
),
|
||||
).toBe(true);
|
||||
} else {
|
||||
expect(
|
||||
ptyAdapter.spawnInputs.some((input) =>
|
||||
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(
|
||||
input.shell,
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -3,19 +3,17 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type TerminalClearInput,
|
||||
type TerminalCloseInput,
|
||||
type TerminalEvent,
|
||||
type TerminalOpenInput,
|
||||
type TerminalResizeInput,
|
||||
type TerminalSessionSnapshot,
|
||||
type TerminalSessionStatus,
|
||||
type TerminalThreadInput,
|
||||
type TerminalWriteInput,
|
||||
terminalClearInputSchema,
|
||||
terminalCloseInputSchema,
|
||||
terminalOpenInputSchema,
|
||||
terminalResizeInputSchema,
|
||||
terminalThreadInputSchema,
|
||||
terminalWriteInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -38,7 +36,6 @@ export interface TerminalManagerOptions {
|
||||
|
||||
interface TerminalSessionState {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
@@ -60,68 +57,6 @@ function defaultShellResolver(): string {
|
||||
return process.env.SHELL ?? "bash";
|
||||
}
|
||||
|
||||
function normalizeShellCommand(value: string | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
if (process.platform === "win32") {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const firstToken = trimmed.split(/\s+/g)[0]?.trim();
|
||||
if (!firstToken) return null;
|
||||
return firstToken.replace(/^['"]|['"]$/g, "");
|
||||
}
|
||||
|
||||
function uniqueShells(shells: Array<string | null>): string[] {
|
||||
const seen = new Set<string>();
|
||||
const ordered: string[] = [];
|
||||
for (const shell of shells) {
|
||||
if (!shell || shell.length === 0) continue;
|
||||
if (seen.has(shell)) continue;
|
||||
seen.add(shell);
|
||||
ordered.push(shell);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
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,
|
||||
normalizeShellCommand(process.env.SHELL),
|
||||
"/bin/zsh",
|
||||
"/bin/bash",
|
||||
"/bin/sh",
|
||||
"zsh",
|
||||
"bash",
|
||||
"sh",
|
||||
]);
|
||||
}
|
||||
|
||||
function isRetryableShellSpawnError(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const message = error.message.toLowerCase();
|
||||
return (
|
||||
message.includes("posix_spawnp failed") ||
|
||||
message.includes("enoent") ||
|
||||
message.includes("not found") ||
|
||||
message.includes("file not found") ||
|
||||
message.includes("no such file")
|
||||
);
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
if (history.length === 0) return history;
|
||||
const hasTrailingNewline = history.endsWith("\n");
|
||||
@@ -142,14 +77,6 @@ function toSafeThreadId(threadId: string): string {
|
||||
return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
|
||||
}
|
||||
|
||||
function toSafeTerminalId(terminalId: string): string {
|
||||
return Buffer.from(terminalId, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function toSessionKey(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private readonly sessions = new Map<string, TerminalSessionState>();
|
||||
private readonly logsDir: string;
|
||||
@@ -178,14 +105,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
return this.runWithThreadLock(input.threadId, async () => {
|
||||
await this.assertValidCwd(input.cwd);
|
||||
|
||||
const sessionKey = toSessionKey(input.threadId, input.terminalId);
|
||||
const existing = this.sessions.get(sessionKey);
|
||||
const existing = this.sessions.get(input.threadId);
|
||||
if (!existing) {
|
||||
await this.flushPersistQueue(input.threadId, input.terminalId);
|
||||
const history = await this.readHistory(input.threadId, input.terminalId);
|
||||
await this.flushPersistQueue(input.threadId);
|
||||
const history = await this.readHistory(input.threadId);
|
||||
const session: TerminalSessionState = {
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
cwd: input.cwd,
|
||||
status: "starting",
|
||||
pid: null,
|
||||
@@ -199,7 +124,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.sessions.set(input.threadId, session);
|
||||
this.startSession(session, input, "started");
|
||||
return this.snapshot(session);
|
||||
}
|
||||
@@ -208,10 +133,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.stopProcess(existing);
|
||||
existing.cwd = input.cwd;
|
||||
existing.history = "";
|
||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||
await this.persistHistory(existing.threadId, existing.history);
|
||||
} else if (existing.status === "exited" || existing.status === "error") {
|
||||
existing.history = "";
|
||||
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
|
||||
await this.persistHistory(existing.threadId, existing.history);
|
||||
}
|
||||
|
||||
if (!existing.process) {
|
||||
@@ -232,22 +157,18 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
|
||||
async write(raw: TerminalWriteInput): Promise<void> {
|
||||
const input = terminalWriteInputSchema.parse(raw);
|
||||
const session = this.requireSession(input.threadId, input.terminalId);
|
||||
const session = this.requireSession(input.threadId);
|
||||
if (!session.process || session.status !== "running") {
|
||||
throw new Error(
|
||||
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
||||
);
|
||||
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
|
||||
}
|
||||
session.process.write(input.data);
|
||||
}
|
||||
|
||||
async resize(raw: TerminalResizeInput): Promise<void> {
|
||||
async resize(raw: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {
|
||||
const input = terminalResizeInputSchema.parse(raw);
|
||||
const session = this.requireSession(input.threadId, input.terminalId);
|
||||
const session = this.requireSession(input.threadId);
|
||||
if (!session.process || session.status !== "running") {
|
||||
throw new Error(
|
||||
`Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
|
||||
);
|
||||
throw new Error(`Terminal is not running for thread: ${input.threadId}`);
|
||||
}
|
||||
session.cols = input.cols;
|
||||
session.rows = input.rows;
|
||||
@@ -255,17 +176,16 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.process.resize(input.cols, input.rows);
|
||||
}
|
||||
|
||||
async clear(raw: TerminalClearInput): Promise<void> {
|
||||
const input = terminalClearInputSchema.parse(raw);
|
||||
async clear(raw: TerminalThreadInput): Promise<void> {
|
||||
const input = terminalThreadInputSchema.parse(raw);
|
||||
await this.runWithThreadLock(input.threadId, async () => {
|
||||
const session = this.requireSession(input.threadId, input.terminalId);
|
||||
const session = this.requireSession(input.threadId);
|
||||
session.history = "";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
||||
await this.persistHistory(input.threadId, session.history);
|
||||
this.emitEvent({
|
||||
type: "cleared",
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
@@ -276,12 +196,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
return this.runWithThreadLock(input.threadId, async () => {
|
||||
await this.assertValidCwd(input.cwd);
|
||||
|
||||
const sessionKey = toSessionKey(input.threadId, input.terminalId);
|
||||
let session = this.sessions.get(sessionKey);
|
||||
let session = this.sessions.get(input.threadId);
|
||||
if (!session) {
|
||||
session = {
|
||||
threadId: input.threadId,
|
||||
terminalId: input.terminalId,
|
||||
cwd: input.cwd,
|
||||
status: "starting",
|
||||
pid: null,
|
||||
@@ -295,14 +213,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.sessions.set(input.threadId, session);
|
||||
} else {
|
||||
this.stopProcess(session);
|
||||
session.cwd = input.cwd;
|
||||
}
|
||||
|
||||
session.history = "";
|
||||
await this.persistHistory(input.threadId, input.terminalId, session.history);
|
||||
await this.persistHistory(input.threadId, session.history);
|
||||
this.startSession(session, input, "restarted");
|
||||
return this.snapshot(session);
|
||||
});
|
||||
@@ -311,28 +229,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
async close(raw: TerminalCloseInput): Promise<void> {
|
||||
const input = terminalCloseInputSchema.parse(raw);
|
||||
await this.runWithThreadLock(input.threadId, async () => {
|
||||
if (input.terminalId) {
|
||||
await this.closeSession(
|
||||
input.threadId,
|
||||
input.terminalId,
|
||||
input.deleteHistory === true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const threadSessions = this.sessionsForThread(input.threadId);
|
||||
for (const session of threadSessions) {
|
||||
const session = this.sessions.get(input.threadId);
|
||||
if (session) {
|
||||
this.stopProcess(session);
|
||||
this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
|
||||
this.sessions.delete(input.threadId);
|
||||
}
|
||||
await Promise.all(
|
||||
threadSessions.map((session) =>
|
||||
this.flushPersistQueue(session.threadId, session.terminalId),
|
||||
),
|
||||
);
|
||||
|
||||
await this.flushPersistQueue(input.threadId);
|
||||
if (input.deleteHistory) {
|
||||
await this.deleteAllHistoryForThread(input.threadId);
|
||||
await this.deleteHistory(input.threadId);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -366,43 +270,16 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.exitSignal = null;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
|
||||
const shell = this.shellResolver();
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
let startedShell: string | null = null;
|
||||
try {
|
||||
const shellCandidates = resolveShellCandidates(this.shellResolver);
|
||||
let lastSpawnError: unknown = null;
|
||||
|
||||
for (const shell of shellCandidates) {
|
||||
try {
|
||||
ptyProcess = this.ptyAdapter.spawn({
|
||||
shell,
|
||||
cwd: session.cwd,
|
||||
cols: session.cols,
|
||||
rows: session.rows,
|
||||
env: process.env,
|
||||
});
|
||||
startedShell = shell;
|
||||
break;
|
||||
} catch (error) {
|
||||
lastSpawnError = error;
|
||||
if (!isRetryableShellSpawnError(error)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!ptyProcess) {
|
||||
const detail =
|
||||
lastSpawnError instanceof Error
|
||||
? lastSpawnError.message
|
||||
: "Terminal start failed";
|
||||
const tried =
|
||||
shellCandidates.length > 0
|
||||
? ` Tried shells: ${shellCandidates.join(", ")}.`
|
||||
: "";
|
||||
throw new Error(`${detail}.${tried}`.trim());
|
||||
}
|
||||
|
||||
ptyProcess = this.ptyAdapter.spawn({
|
||||
shell,
|
||||
cwd: session.cwd,
|
||||
cols: session.cols,
|
||||
rows: session.rows,
|
||||
env: process.env,
|
||||
});
|
||||
session.process = ptyProcess;
|
||||
session.pid = ptyProcess.pid;
|
||||
session.status = "running";
|
||||
@@ -416,7 +293,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.emitEvent({
|
||||
type: eventType,
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
snapshot: this.snapshot(session),
|
||||
});
|
||||
@@ -436,15 +312,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.emitEvent({
|
||||
type: "error",
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
message,
|
||||
});
|
||||
this.logger.error("failed to start terminal", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
error: message,
|
||||
...(startedShell ? { shell: startedShell } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -452,11 +325,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private onProcessData(session: TerminalSessionState, data: string): void {
|
||||
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
|
||||
session.updatedAt = new Date().toISOString();
|
||||
this.queuePersist(session.threadId, session.terminalId, session.history);
|
||||
this.queuePersist(session.threadId, session.history);
|
||||
this.emitEvent({
|
||||
type: "output",
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
data,
|
||||
});
|
||||
@@ -473,7 +345,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.emitEvent({
|
||||
type: "exited",
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
exitCode: session.exitCode,
|
||||
exitSignal: session.exitSignal,
|
||||
@@ -494,7 +365,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.logger.warn("failed to kill terminal process", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
@@ -507,87 +377,69 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.unsubscribeExit = null;
|
||||
}
|
||||
|
||||
private queuePersist(threadId: string, terminalId: string, history: string): void {
|
||||
const persistenceKey = toSessionKey(threadId, terminalId);
|
||||
this.pendingPersistHistory.set(persistenceKey, history);
|
||||
this.schedulePersist(threadId, terminalId);
|
||||
private queuePersist(threadId: string, history: string): void {
|
||||
this.pendingPersistHistory.set(threadId, history);
|
||||
this.schedulePersist(threadId);
|
||||
}
|
||||
|
||||
private async persistHistory(
|
||||
threadId: string,
|
||||
terminalId: string,
|
||||
history: string,
|
||||
): Promise<void> {
|
||||
const persistenceKey = toSessionKey(threadId, terminalId);
|
||||
this.clearPersistTimer(threadId, terminalId);
|
||||
this.pendingPersistHistory.delete(persistenceKey);
|
||||
await this.enqueuePersistWrite(threadId, terminalId, history);
|
||||
private async persistHistory(threadId: string, history: string): Promise<void> {
|
||||
this.clearPersistTimer(threadId);
|
||||
this.pendingPersistHistory.delete(threadId);
|
||||
await this.enqueuePersistWrite(threadId, history);
|
||||
}
|
||||
|
||||
private enqueuePersistWrite(
|
||||
threadId: string,
|
||||
terminalId: string,
|
||||
history: string,
|
||||
): Promise<void> {
|
||||
const persistenceKey = toSessionKey(threadId, terminalId);
|
||||
private enqueuePersistWrite(threadId: string, history: string): Promise<void> {
|
||||
const task = async () => {
|
||||
await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
|
||||
await fs.promises.writeFile(this.historyPath(threadId), history, "utf8");
|
||||
};
|
||||
const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
|
||||
const previous = this.persistQueues.get(threadId) ?? Promise.resolve();
|
||||
const next = previous
|
||||
.catch(() => undefined)
|
||||
.then(task)
|
||||
.catch((error) => {
|
||||
this.logger.warn("failed to persist terminal history", {
|
||||
threadId,
|
||||
terminalId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
});
|
||||
this.persistQueues.set(persistenceKey, next);
|
||||
this.persistQueues.set(threadId, next);
|
||||
const finalized = next.finally(() => {
|
||||
if (this.persistQueues.get(persistenceKey) === next) {
|
||||
this.persistQueues.delete(persistenceKey);
|
||||
if (this.persistQueues.get(threadId) === next) {
|
||||
this.persistQueues.delete(threadId);
|
||||
}
|
||||
if (
|
||||
this.pendingPersistHistory.has(persistenceKey) &&
|
||||
!this.persistTimers.has(persistenceKey)
|
||||
) {
|
||||
this.schedulePersist(threadId, terminalId);
|
||||
if (this.pendingPersistHistory.has(threadId) && !this.persistTimers.has(threadId)) {
|
||||
this.schedulePersist(threadId);
|
||||
}
|
||||
});
|
||||
void finalized.catch(() => undefined);
|
||||
return finalized;
|
||||
}
|
||||
|
||||
private schedulePersist(threadId: string, terminalId: string): void {
|
||||
const persistenceKey = toSessionKey(threadId, terminalId);
|
||||
if (this.persistTimers.has(persistenceKey)) return;
|
||||
private schedulePersist(threadId: string): void {
|
||||
if (this.persistTimers.has(threadId)) return;
|
||||
const timer = setTimeout(() => {
|
||||
this.persistTimers.delete(persistenceKey);
|
||||
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
|
||||
this.persistTimers.delete(threadId);
|
||||
const pendingHistory = this.pendingPersistHistory.get(threadId);
|
||||
if (pendingHistory === undefined) return;
|
||||
this.pendingPersistHistory.delete(persistenceKey);
|
||||
void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
|
||||
this.pendingPersistHistory.delete(threadId);
|
||||
void this.enqueuePersistWrite(threadId, pendingHistory);
|
||||
}, this.persistDebounceMs);
|
||||
this.persistTimers.set(persistenceKey, timer);
|
||||
this.persistTimers.set(threadId, timer);
|
||||
}
|
||||
|
||||
private clearPersistTimer(threadId: string, terminalId: string): void {
|
||||
const persistenceKey = toSessionKey(threadId, terminalId);
|
||||
const timer = this.persistTimers.get(persistenceKey);
|
||||
private clearPersistTimer(threadId: string): void {
|
||||
const timer = this.persistTimers.get(threadId);
|
||||
if (!timer) return;
|
||||
clearTimeout(timer);
|
||||
this.persistTimers.delete(persistenceKey);
|
||||
this.persistTimers.delete(threadId);
|
||||
}
|
||||
|
||||
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
||||
const historyPath = this.historyPath(threadId, terminalId);
|
||||
private async readHistory(threadId: string): Promise<string> {
|
||||
try {
|
||||
const raw = await fs.promises.readFile(historyPath, "utf8");
|
||||
const raw = await fs.promises.readFile(this.historyPath(threadId), "utf8");
|
||||
const capped = capHistory(raw, this.historyLineLimit);
|
||||
if (capped !== raw) {
|
||||
await fs.promises.writeFile(historyPath, capped, "utf8");
|
||||
await fs.promises.writeFile(this.historyPath(threadId), capped, "utf8");
|
||||
}
|
||||
return capped;
|
||||
} catch (error) {
|
||||
@@ -596,10 +448,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
if (terminalId !== DEFAULT_TERMINAL_ID) {
|
||||
return "";
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
|
||||
const capped = capHistory(raw, this.historyLineLimit);
|
||||
@@ -615,34 +463,31 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
|
||||
const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
|
||||
}
|
||||
private async deleteHistory(threadId: string): Promise<void> {
|
||||
try {
|
||||
await Promise.all(deletions);
|
||||
await Promise.all([
|
||||
fs.promises.rm(this.historyPath(threadId), { force: true }),
|
||||
fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }),
|
||||
]);
|
||||
} catch (error) {
|
||||
this.logger.warn("failed to delete terminal history", {
|
||||
threadId,
|
||||
terminalId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
|
||||
const persistenceKey = toSessionKey(threadId, terminalId);
|
||||
this.clearPersistTimer(threadId, terminalId);
|
||||
private async flushPersistQueue(threadId: string): Promise<void> {
|
||||
this.clearPersistTimer(threadId);
|
||||
|
||||
while (true) {
|
||||
const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
|
||||
const pendingHistory = this.pendingPersistHistory.get(threadId);
|
||||
if (pendingHistory !== undefined) {
|
||||
this.pendingPersistHistory.delete(persistenceKey);
|
||||
await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
|
||||
this.pendingPersistHistory.delete(threadId);
|
||||
await this.enqueuePersistWrite(threadId, pendingHistory);
|
||||
}
|
||||
|
||||
const pending = this.persistQueues.get(persistenceKey);
|
||||
const pending = this.persistQueues.get(threadId);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
@@ -665,54 +510,10 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
private async closeSession(
|
||||
threadId: string,
|
||||
terminalId: string,
|
||||
deleteHistory: boolean,
|
||||
): Promise<void> {
|
||||
const key = toSessionKey(threadId, terminalId);
|
||||
const session = this.sessions.get(key);
|
||||
if (session) {
|
||||
this.stopProcess(session);
|
||||
this.sessions.delete(key);
|
||||
}
|
||||
await this.flushPersistQueue(threadId, terminalId);
|
||||
if (deleteHistory) {
|
||||
await this.deleteHistory(threadId, terminalId);
|
||||
}
|
||||
}
|
||||
|
||||
private sessionsForThread(threadId: string): TerminalSessionState[] {
|
||||
return [...this.sessions.values()].filter((session) => session.threadId === threadId);
|
||||
}
|
||||
|
||||
private async deleteAllHistoryForThread(threadId: string): Promise<void> {
|
||||
const threadPrefix = `${toSafeThreadId(threadId)}_`;
|
||||
try {
|
||||
const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
|
||||
const removals = entries
|
||||
.filter((entry) => entry.isFile())
|
||||
.map((entry) => entry.name)
|
||||
.filter(
|
||||
(name) =>
|
||||
name === `${toSafeThreadId(threadId)}.log` ||
|
||||
name === `${legacySafeThreadId(threadId)}.log` ||
|
||||
name.startsWith(threadPrefix),
|
||||
)
|
||||
.map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
|
||||
await Promise.all(removals);
|
||||
} catch (error) {
|
||||
this.logger.warn("failed to delete terminal histories for thread", {
|
||||
threadId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private requireSession(threadId: string, terminalId: string): TerminalSessionState {
|
||||
const session = this.sessions.get(toSessionKey(threadId, terminalId));
|
||||
private requireSession(threadId: string): TerminalSessionState {
|
||||
const session = this.sessions.get(threadId);
|
||||
if (!session) {
|
||||
throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
|
||||
throw new Error(`Unknown terminal thread: ${threadId}`);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
@@ -720,7 +521,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
|
||||
return {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
cwd: session.cwd,
|
||||
status: session.status,
|
||||
pid: session.pid,
|
||||
@@ -735,12 +535,8 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.emit("event", event);
|
||||
}
|
||||
|
||||
private historyPath(threadId: string, terminalId: string): string {
|
||||
const threadPart = toSafeThreadId(threadId);
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
return path.join(this.logsDir, `${threadPart}.log`);
|
||||
}
|
||||
return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
|
||||
private historyPath(threadId: string): string {
|
||||
return path.join(this.logsDir, `${toSafeThreadId(threadId)}.log`);
|
||||
}
|
||||
|
||||
private legacyHistoryPath(threadId: string): string {
|
||||
|
||||
@@ -7,21 +7,14 @@ import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WsPush,
|
||||
type WsResponse,
|
||||
} from "@t3tools/contracts";
|
||||
import { WS_CHANNELS, WS_METHODS, type WsPush, type WsResponse } from "@t3tools/contracts";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalEvent,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalThreadInput,
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import type { TerminalManager } from "./terminalManager";
|
||||
@@ -36,16 +29,10 @@ const pendingBySocket = new WeakMap<WebSocket, PendingMessages>();
|
||||
class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }> {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
|
||||
private key(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
async open(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
|
||||
const now = new Date().toISOString();
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const snapshot: TerminalSessionSnapshot = {
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
status: "running",
|
||||
pid: 4242,
|
||||
@@ -54,12 +41,11 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
exitSignal: null,
|
||||
updatedAt: now,
|
||||
};
|
||||
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
|
||||
this.sessions.set(input.threadId, snapshot);
|
||||
queueMicrotask(() => {
|
||||
this.emit("event", {
|
||||
type: "started",
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
createdAt: now,
|
||||
snapshot,
|
||||
});
|
||||
@@ -68,8 +54,7 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
}
|
||||
|
||||
async write(input: TerminalWriteInput): Promise<void> {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const existing = this.sessions.get(this.key(input.threadId, terminalId));
|
||||
const existing = this.sessions.get(input.threadId);
|
||||
if (!existing) {
|
||||
throw new Error(`Unknown terminal thread: ${input.threadId}`);
|
||||
}
|
||||
@@ -77,22 +62,19 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
this.emit("event", {
|
||||
type: "output",
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: input.data,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async resize(_input: TerminalResizeInput): Promise<void> {}
|
||||
async resize(_input: TerminalThreadInput & { cols: number; rows: number }): Promise<void> {}
|
||||
|
||||
async clear(input: TerminalClearInput): Promise<void> {
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
async clear(input: TerminalThreadInput): Promise<void> {
|
||||
queueMicrotask(() => {
|
||||
this.emit("event", {
|
||||
type: "cleared",
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
@@ -100,10 +82,8 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
|
||||
async restart(input: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
|
||||
const now = new Date().toISOString();
|
||||
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
|
||||
const snapshot: TerminalSessionSnapshot = {
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
status: "running",
|
||||
pid: 5252,
|
||||
@@ -112,12 +92,11 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
exitSignal: null,
|
||||
updatedAt: now,
|
||||
};
|
||||
this.sessions.set(this.key(input.threadId, terminalId), snapshot);
|
||||
this.sessions.set(input.threadId, snapshot);
|
||||
queueMicrotask(() => {
|
||||
this.emit("event", {
|
||||
type: "restarted",
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
createdAt: now,
|
||||
snapshot,
|
||||
});
|
||||
@@ -126,15 +105,7 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
}
|
||||
|
||||
async close(input: TerminalCloseInput): Promise<void> {
|
||||
if (input.terminalId) {
|
||||
this.sessions.delete(this.key(input.threadId, input.terminalId));
|
||||
return;
|
||||
}
|
||||
for (const key of [...this.sessions.keys()]) {
|
||||
if (key.startsWith(`${input.threadId}\u0000`)) {
|
||||
this.sessions.delete(key);
|
||||
}
|
||||
}
|
||||
this.sessions.delete(input.threadId);
|
||||
}
|
||||
|
||||
dispose(): void {}
|
||||
@@ -209,10 +180,6 @@ describe("WebSocket Server", () => {
|
||||
devUrl?: string;
|
||||
authToken?: string;
|
||||
stateDir?: string;
|
||||
gitManager?: {
|
||||
status: (input: { cwd: string }) => Promise<unknown>;
|
||||
runStackedAction: (input: { cwd: string; action: string }) => Promise<unknown>;
|
||||
};
|
||||
terminalManager?: TerminalManager;
|
||||
} = {},
|
||||
): ReturnType<typeof createServer> {
|
||||
@@ -223,7 +190,6 @@ describe("WebSocket Server", () => {
|
||||
...(options.devUrl ? { devUrl: options.devUrl } : {}),
|
||||
...(options.authToken ? { authToken: options.authToken } : {}),
|
||||
projectRegistry: new ProjectRegistry(stateDir),
|
||||
...(options.gitManager ? { gitManager: options.gitManager as never } : {}),
|
||||
...(options.terminalManager
|
||||
? { terminalManager: options.terminalManager }
|
||||
: {}),
|
||||
@@ -369,7 +335,6 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
expect(open.error).toBeUndefined();
|
||||
expect((open.result as TerminalSessionSnapshot).threadId).toBe("thread-1");
|
||||
expect((open.result as TerminalSessionSnapshot).terminalId).toBe(DEFAULT_TERMINAL_ID);
|
||||
|
||||
const write = await sendRequest(ws, WS_METHODS.terminalWrite, {
|
||||
threadId: "thread-1",
|
||||
@@ -406,7 +371,6 @@ describe("WebSocket Server", () => {
|
||||
const manualEvent: TerminalEvent = {
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "manual test output\n",
|
||||
};
|
||||
@@ -547,72 +511,6 @@ describe("WebSocket Server", () => {
|
||||
expect((afterInit.result as { isRepo: boolean }).isRepo).toBe(true);
|
||||
});
|
||||
|
||||
it("responds to git.status via the git manager", async () => {
|
||||
const gitManager = {
|
||||
status: vi.fn().mockResolvedValue({
|
||||
branch: "feature/test",
|
||||
hasWorkingTreeChanges: true,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
}),
|
||||
runStackedAction: vi.fn(),
|
||||
};
|
||||
|
||||
server = createTestServer({ cwd: "/test", gitManager });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.gitStatus, {
|
||||
cwd: "/test",
|
||||
});
|
||||
expect(response.error).toBeUndefined();
|
||||
expect(response.result).toEqual({
|
||||
branch: "feature/test",
|
||||
hasWorkingTreeChanges: true,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
});
|
||||
expect(gitManager.status).toHaveBeenCalledWith({ cwd: "/test" });
|
||||
});
|
||||
|
||||
it("returns errors from git.runStackedAction", async () => {
|
||||
const gitManager = {
|
||||
status: vi.fn(),
|
||||
runStackedAction: vi
|
||||
.fn()
|
||||
.mockRejectedValue(new Error("Cannot push from detached HEAD.")),
|
||||
};
|
||||
|
||||
server = createTestServer({ cwd: "/test", gitManager });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
});
|
||||
expect(response.result).toBeUndefined();
|
||||
expect(response.error?.message).toContain("detached HEAD");
|
||||
expect(gitManager.runStackedAction).toHaveBeenCalledWith({
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
});
|
||||
});
|
||||
|
||||
it("prunes missing projects on startup", async () => {
|
||||
const stateDir = makeTempDir("t3code-ws-prune-state-");
|
||||
const existing = makeTempDir("t3code-ws-existing-project-");
|
||||
|
||||
@@ -20,7 +20,6 @@ import { WebSocketServer, type WebSocket } from "ws";
|
||||
import { createLogger } from "./logger";
|
||||
import { ProjectRegistry } from "./projectRegistry";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
import { GitManager } from "./gitManager";
|
||||
import {
|
||||
checkoutGitBranch,
|
||||
createGitBranch,
|
||||
@@ -54,7 +53,6 @@ export interface ServerOptions {
|
||||
devUrl?: string | undefined;
|
||||
logWebSocketEvents?: boolean | undefined;
|
||||
projectRegistry?: ProjectRegistry | undefined;
|
||||
gitManager?: GitManager | undefined;
|
||||
terminalManager?: TerminalManager | undefined;
|
||||
authToken?: string | undefined;
|
||||
}
|
||||
@@ -76,7 +74,6 @@ export function createServer(options: ServerOptions) {
|
||||
devUrl,
|
||||
logWebSocketEvents: explicitLogWsEvents,
|
||||
projectRegistry: providedRegistry,
|
||||
gitManager: providedGitManager,
|
||||
terminalManager: providedTerminalManager,
|
||||
authToken,
|
||||
} = options;
|
||||
@@ -84,7 +81,6 @@ export function createServer(options: ServerOptions) {
|
||||
const terminalManager = providedTerminalManager ?? new TerminalManager();
|
||||
const projectRegistry =
|
||||
providedRegistry ?? new ProjectRegistry(path.join(os.homedir(), ".t3", "userdata"));
|
||||
const gitManager = providedGitManager ?? new GitManager();
|
||||
const clients = new Set<WebSocket>();
|
||||
const logger = createLogger("ws");
|
||||
const logWebSocketEvents =
|
||||
@@ -339,11 +335,6 @@ export function createServer(options: ServerOptions) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
case WS_METHODS.gitStatus:
|
||||
return gitManager.status(request.params as never);
|
||||
|
||||
case WS_METHODS.gitRunStackedAction:
|
||||
return gitManager.runStackedAction(request.params as never);
|
||||
case WS_METHODS.gitListBranches:
|
||||
return listGitBranches(request.params as never);
|
||||
|
||||
|
||||
+18
-15
@@ -1,18 +1,18 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import ChatView from "./components/ChatView";
|
||||
import DiffPanel from "./components/DiffPanel";
|
||||
import Sidebar from "./components/Sidebar";
|
||||
import { isElectron } from "./env";
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
import { readNativeApi } from "./session-logic";
|
||||
import { StoreProvider, useStore } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
|
||||
import { onServerWelcome } from "./wsNativeApi";
|
||||
import { useNativeApi } from "./hooks/useNativeApi";
|
||||
|
||||
function EventRouter() {
|
||||
const api = useNativeApi();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { dispatch } = useStore();
|
||||
const activeAssistantItemRef = useRef<string | null>(null);
|
||||
|
||||
@@ -27,6 +27,18 @@ function EventRouter() {
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
if (event.type !== "exited") return;
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: event.threadId,
|
||||
open: false,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -81,15 +93,6 @@ function AutoProjectBootstrap() {
|
||||
model: DEFAULT_MODEL,
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
@@ -106,7 +109,7 @@ function AutoProjectBootstrap() {
|
||||
}
|
||||
|
||||
function DesktopProjectBootstrap() {
|
||||
const api = useNativeApi();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { dispatch } = useStore();
|
||||
const bootstrappedRef = useRef(false);
|
||||
|
||||
@@ -156,7 +159,7 @@ function DesktopProjectBootstrap() {
|
||||
}
|
||||
|
||||
function Layout() {
|
||||
const api = useNativeApi();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { state } = useStore();
|
||||
|
||||
if (!api) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { readNativeApi } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
|
||||
interface BranchToolbarProps {
|
||||
envMode: "local" | "worktree";
|
||||
@@ -13,7 +13,7 @@ interface BranchToolbarProps {
|
||||
|
||||
export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: BranchToolbarProps) {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
|
||||
@@ -254,11 +254,7 @@ export default function BranchToolbar({ envMode, onEnvModeChange, envLocked }: B
|
||||
<span className="truncate">{branch.name}</span>
|
||||
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/45">
|
||||
{branch.current
|
||||
? "current"
|
||||
: hasSecondaryWorktree
|
||||
? "worktree"
|
||||
: "default"}
|
||||
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ProviderSendTurnAttachmentInput,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
type ClipboardEvent,
|
||||
type DragEvent,
|
||||
type FormEvent,
|
||||
Fragment,
|
||||
type KeyboardEvent,
|
||||
@@ -29,22 +25,19 @@ import {
|
||||
resolveModelSlug,
|
||||
} from "../model-logic";
|
||||
import {
|
||||
derivePendingApprovals,
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
formatDuration,
|
||||
formatElapsed,
|
||||
formatTimestamp,
|
||||
readNativeApi,
|
||||
} from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import type { ChatImageAttachment } from "../types";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import GitActionsControl from "./GitActionsControl";
|
||||
import { isTerminalToggleShortcut } from "../terminal-shortcuts";
|
||||
import ChatMarkdown from "./ChatMarkdown";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
@@ -63,9 +56,6 @@ function editorLabel(editor: (typeof EDITORS)[number]): string {
|
||||
|
||||
const LAST_EDITOR_KEY = "t3code:last-editor";
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
|
||||
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
|
||||
@@ -74,6 +64,13 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
return "text-muted-foreground/40";
|
||||
}
|
||||
|
||||
interface PendingApprovalCard {
|
||||
requestId: string;
|
||||
requestKind: "command" | "file-change";
|
||||
createdAt: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
type SessionContinuityState = "resumed" | "new" | "fallback_new";
|
||||
|
||||
interface EnsuredSessionInfo {
|
||||
@@ -82,40 +79,61 @@ interface EnsuredSessionInfo {
|
||||
continuityState: SessionContinuityState;
|
||||
}
|
||||
|
||||
interface ComposerImageAttachment extends Omit<ChatImageAttachment, "previewUrl"> {
|
||||
previewUrl: string;
|
||||
file: File;
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") return undefined;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface ExpandedImagePreview {
|
||||
src: string;
|
||||
name: string;
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function readFileAsDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener("load", () => {
|
||||
if (typeof reader.result === "string") {
|
||||
resolve(reader.result);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Could not read image data."));
|
||||
});
|
||||
reader.addEventListener("error", () => {
|
||||
reject(reader.error ?? new Error("Failed to read image."));
|
||||
});
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
function approvalDetail(event: ProviderEvent): string | undefined {
|
||||
const payload = asRecord(event.payload);
|
||||
const command = asString(payload?.command);
|
||||
if (command) return command;
|
||||
return asString(payload?.reason);
|
||||
}
|
||||
|
||||
function derivePendingApprovals(events: ProviderEvent[]): PendingApprovalCard[] {
|
||||
const pending = new Map<string, PendingApprovalCard>();
|
||||
const ordered = [...events].toReversed();
|
||||
|
||||
for (const event of ordered) {
|
||||
if (event.method === "session/closed" || event.method === "session/exited") {
|
||||
pending.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
const requestId = event.requestId ?? asString(asRecord(event.payload)?.requestId);
|
||||
if (!requestId) continue;
|
||||
|
||||
if (
|
||||
event.kind === "request" &&
|
||||
(event.requestKind === "command" || event.requestKind === "file-change")
|
||||
) {
|
||||
const detail = approvalDetail(event);
|
||||
pending.set(requestId, {
|
||||
requestId,
|
||||
requestKind: event.requestKind,
|
||||
createdAt: event.createdAt,
|
||||
...(detail ? { detail } : {}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.method === "item/requestApproval/decision") {
|
||||
pending.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(pending.values());
|
||||
}
|
||||
|
||||
export default function ChatView() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [composerImages, setComposerImages] = useState<ComposerImageAttachment[]>([]);
|
||||
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
|
||||
@@ -133,8 +151,6 @@ export default function ChatView() {
|
||||
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const dragDepthRef = useRef(0);
|
||||
const modelMenuRef = useRef<HTMLDivElement>(null);
|
||||
const editorMenuRef = useRef<HTMLDivElement>(null);
|
||||
const terminalOpenByThreadRef = useRef<Record<string, boolean>>({});
|
||||
@@ -240,19 +256,14 @@ export default function ChatView() {
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
} as const);
|
||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
if (!image.previewUrl) continue;
|
||||
URL.revokeObjectURL(image.previewUrl);
|
||||
}
|
||||
}, []);
|
||||
const terminalShortcutHint = navigator.platform.includes("Mac")
|
||||
? "\u2318J"
|
||||
: "Ctrl+J";
|
||||
const focusComposer = useCallback(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
@@ -269,65 +280,6 @@ export default function ChatView() {
|
||||
open: !isOpen,
|
||||
});
|
||||
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
|
||||
const splitTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId: `terminal-${crypto.randomUUID()}`,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
}, [activeThreadId, dispatch]);
|
||||
const createNewTerminal = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId: `terminal-${crypto.randomUUID()}`,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
}, [activeThreadId, dispatch]);
|
||||
const activateTerminal = useCallback(
|
||||
(terminalId: string) => {
|
||||
if (!activeThreadId) return;
|
||||
dispatch({
|
||||
type: "SET_THREAD_ACTIVE_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
},
|
||||
[activeThreadId, dispatch],
|
||||
);
|
||||
const closeTerminal = useCallback(
|
||||
(terminalId: string) => {
|
||||
if (!activeThreadId || !api) return;
|
||||
const fallbackExitWrite = () =>
|
||||
api.terminal
|
||||
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
|
||||
.catch(() => undefined);
|
||||
const fallbackClearAndExit = () =>
|
||||
api.terminal
|
||||
.clear({ threadId: activeThreadId, terminalId })
|
||||
.catch(() => undefined)
|
||||
.then(() => fallbackExitWrite())
|
||||
.catch(() => undefined);
|
||||
if ("close" in api.terminal && typeof api.terminal.close === "function") {
|
||||
void api.terminal
|
||||
.close({ threadId: activeThreadId, terminalId, deleteHistory: true })
|
||||
.catch(() => fallbackClearAndExit());
|
||||
} else {
|
||||
void fallbackClearAndExit();
|
||||
}
|
||||
dispatch({
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
threadId: activeThreadId,
|
||||
terminalId,
|
||||
});
|
||||
setTerminalFocusRequestId((value) => value + 1);
|
||||
},
|
||||
[activeThreadId, api, dispatch],
|
||||
);
|
||||
|
||||
const handleRuntimeModeChange = async (mode: "approval-required" | "full-access") => {
|
||||
if (mode === state.runtimeMode) return;
|
||||
@@ -366,46 +318,7 @@ export default function ChatView() {
|
||||
setExpandedWorkGroups({});
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
composerImagesRef.current = composerImages;
|
||||
}, [composerImages]);
|
||||
|
||||
useEffect(() => {
|
||||
setComposerImages((existing) => {
|
||||
revokePreviewUrls(existing);
|
||||
return [];
|
||||
});
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
setExpandedImage(null);
|
||||
}, [activeThread?.id, revokePreviewUrls]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
revokePreviewUrls(composerImagesRef.current);
|
||||
};
|
||||
}, [revokePreviewUrls]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!expandedImage) {
|
||||
return;
|
||||
}
|
||||
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.key !== "Escape") {
|
||||
return;
|
||||
}
|
||||
setExpandedImage(null);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [expandedImage]);
|
||||
|
||||
const activeWorktreePath = activeThread?.worktreePath;
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
setEnvMode(activeWorktreePath ? "worktree" : "local");
|
||||
@@ -516,125 +429,6 @@ export default function ChatView() {
|
||||
setIsEditorMenuOpen(false);
|
||||
};
|
||||
|
||||
const setThreadError = (threadId: string | null, error: string | null) => {
|
||||
if (!threadId) return;
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId,
|
||||
error,
|
||||
});
|
||||
};
|
||||
|
||||
const addComposerImages = (files: File[]) => {
|
||||
if (!activeThreadId || files.length === 0) return;
|
||||
|
||||
const nextImages = [...composerImagesRef.current];
|
||||
let error: string | null = null;
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
|
||||
continue;
|
||||
}
|
||||
if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
|
||||
error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`;
|
||||
continue;
|
||||
}
|
||||
if (nextImages.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
|
||||
break;
|
||||
}
|
||||
|
||||
const previewUrl = URL.createObjectURL(file);
|
||||
nextImages.push({
|
||||
type: "image",
|
||||
id: crypto.randomUUID(),
|
||||
name: file.name || "image",
|
||||
mimeType: file.type,
|
||||
sizeBytes: file.size,
|
||||
previewUrl,
|
||||
file,
|
||||
});
|
||||
}
|
||||
|
||||
setComposerImages(nextImages);
|
||||
setThreadError(activeThreadId, error);
|
||||
};
|
||||
|
||||
const removeComposerImage = (imageId: string) => {
|
||||
setComposerImages((existing) => {
|
||||
const match = existing.find((image) => image.id === imageId);
|
||||
if (match?.previewUrl) {
|
||||
URL.revokeObjectURL(match.previewUrl);
|
||||
}
|
||||
return existing.filter((image) => image.id !== imageId);
|
||||
});
|
||||
};
|
||||
|
||||
const openImageDialog = (src: string | undefined, name: string) => {
|
||||
if (!src) {
|
||||
return;
|
||||
}
|
||||
setExpandedImage({ src, name });
|
||||
};
|
||||
|
||||
const onComposerPaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
|
||||
const files = Array.from(event.clipboardData.files);
|
||||
if (files.length === 0) {
|
||||
return;
|
||||
}
|
||||
const imageFiles = files.filter((file) => file.type.startsWith("image/"));
|
||||
if (imageFiles.length === 0) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
addComposerImages(imageFiles);
|
||||
};
|
||||
|
||||
const onComposerDragEnter = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
dragDepthRef.current += 1;
|
||||
setIsDragOverComposer(true);
|
||||
};
|
||||
|
||||
const onComposerDragOver = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
setIsDragOverComposer(true);
|
||||
};
|
||||
|
||||
const onComposerDragLeave = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
const nextTarget = event.relatedTarget;
|
||||
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) {
|
||||
return;
|
||||
}
|
||||
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
|
||||
if (dragDepthRef.current === 0) {
|
||||
setIsDragOverComposer(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onComposerDrop = (event: DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
const files = Array.from(event.dataTransfer.files);
|
||||
addComposerImages(files);
|
||||
focusComposer();
|
||||
};
|
||||
|
||||
const ensureSession = async (cwdOverride?: string): Promise<EnsuredSessionInfo | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
@@ -696,9 +490,8 @@ export default function ChatView() {
|
||||
e.preventDefault();
|
||||
if (!api || !activeThread || isSending || isConnecting) return;
|
||||
const trimmed = prompt.trim();
|
||||
if (!trimmed && composerImages.length === 0) return;
|
||||
if (!trimmed) return;
|
||||
if (!activeProject) return;
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
|
||||
// On first message: lock in branch + create worktree if needed.
|
||||
let sessionCwd: string | undefined;
|
||||
@@ -734,12 +527,7 @@ export default function ChatView() {
|
||||
|
||||
// Auto-title from first message
|
||||
if (activeThread.messages.length === 0) {
|
||||
const titleSeed =
|
||||
trimmed ||
|
||||
(composerImagesSnapshot.length > 0
|
||||
? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
|
||||
: "New thread");
|
||||
const title = titleSeed.length > 50 ? `${titleSeed.slice(0, 50)}...` : titleSeed;
|
||||
const title = trimmed.length > 50 ? `${trimmed.slice(0, 50)}...` : trimmed;
|
||||
dispatch({
|
||||
type: "SET_THREAD_TITLE",
|
||||
threadId: activeThread.id,
|
||||
@@ -747,63 +535,43 @@ export default function ChatView() {
|
||||
});
|
||||
}
|
||||
|
||||
setThreadError(activeThread.id, null);
|
||||
const messageAttachments: ChatImageAttachment[] = composerImagesSnapshot.map((image) => ({
|
||||
type: "image",
|
||||
id: image.id,
|
||||
name: image.name,
|
||||
mimeType: image.mimeType,
|
||||
sizeBytes: image.sizeBytes,
|
||||
previewUrl: image.previewUrl,
|
||||
}));
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: null,
|
||||
});
|
||||
dispatch({
|
||||
type: "PUSH_USER_MESSAGE",
|
||||
threadId: activeThread.id,
|
||||
id: crypto.randomUUID(),
|
||||
text: trimmed,
|
||||
...(messageAttachments.length > 0 ? { attachments: messageAttachments } : {}),
|
||||
});
|
||||
const previousMessages = activeThread.messages;
|
||||
setPrompt("");
|
||||
setComposerImages([]);
|
||||
|
||||
const sessionInfo = await ensureSession(sessionCwd);
|
||||
if (!sessionInfo) return;
|
||||
|
||||
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),
|
||||
})),
|
||||
);
|
||||
const shouldBootstrap =
|
||||
previousMessages.length > 0 &&
|
||||
(sessionInfo.continuityState === "new" || sessionInfo.continuityState === "fallback_new");
|
||||
const latestPromptForBootstrap = trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT;
|
||||
const input = shouldBootstrap
|
||||
? buildBootstrapInput(
|
||||
previousMessages,
|
||||
latestPromptForBootstrap,
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
).text
|
||||
: (trimmed || undefined);
|
||||
? buildBootstrapInput(previousMessages, trimmed, PROVIDER_SEND_TURN_MAX_INPUT_CHARS).text
|
||||
: trimmed;
|
||||
await api.providers.sendTurn({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
...(input ? { input } : {}),
|
||||
...(turnAttachments.length > 0 ? { attachments: turnAttachments } : {}),
|
||||
input,
|
||||
model: selectedModel || undefined,
|
||||
effort: selectedEffort || undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
err instanceof Error ? err.message : "Failed to send message.",
|
||||
);
|
||||
dispatch({
|
||||
type: "SET_ERROR",
|
||||
threadId: activeThread.id,
|
||||
error: err instanceof Error ? err.message : "Failed to send message.",
|
||||
});
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
@@ -861,11 +629,7 @@ export default function ChatView() {
|
||||
if (!activeThread) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background text-muted-foreground/40">
|
||||
{isElectron && (
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
|
||||
<span className="text-xs text-muted-foreground/50">No active thread</span>
|
||||
</div>
|
||||
)}
|
||||
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-sm">Select a thread or create a new one to get started.</p>
|
||||
@@ -879,7 +643,7 @@ export default function ChatView() {
|
||||
<div className="flex min-h-0 flex-1 flex-col bg-background">
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={`flex items-center justify-between border-b border-border px-5 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
className={`flex items-center justify-between border-b border-border px-5 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-sm font-medium text-foreground">{activeThread.title}</h2>
|
||||
@@ -888,6 +652,12 @@ export default function ChatView() {
|
||||
{activeProject.name}
|
||||
</span>
|
||||
)}
|
||||
{activeThread.branch && (
|
||||
<span className="rounded-full bg-accent px-2 py-0.5 font-mono text-[10px] text-muted-foreground/50">
|
||||
{activeThread.branch}
|
||||
{activeThread.worktreePath ? " (worktree)" : ""}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Open in editor */}
|
||||
@@ -921,10 +691,18 @@ export default function ChatView() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Git actions */}
|
||||
{activeProject && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
|
||||
{/* Diff toggle */}
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
|
||||
activeThread.terminalOpen
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground/40 hover:text-muted-foreground/60"
|
||||
}`}
|
||||
onClick={toggleTerminalVisibility}
|
||||
>
|
||||
Terminal <span className="text-muted-foreground/50">{terminalShortcutHint}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md px-2 py-1 text-[10px] transition-colors duration-150 ${
|
||||
@@ -947,68 +725,64 @@ export default function ChatView() {
|
||||
)}
|
||||
|
||||
{pendingApprovals.length > 0 && (
|
||||
<div className="px-5 pt-3">
|
||||
<div className="mx-auto max-w-3xl space-y-2">
|
||||
{pendingApprovals.map((approval) => {
|
||||
const isResponding = respondingRequestIds.includes(approval.requestId);
|
||||
return (
|
||||
<div
|
||||
key={approval.requestId}
|
||||
className="rounded-lg border border-amber-300/40 bg-amber-50 px-3 py-2 dark:border-amber-300/20 dark:bg-amber-500/[0.07]"
|
||||
>
|
||||
<p className="text-xs font-medium text-amber-900 dark:text-amber-100">
|
||||
{approval.requestKind === "command"
|
||||
? "Command approval requested"
|
||||
: "File-change approval requested"}
|
||||
<div className="mx-4 mt-3 space-y-2">
|
||||
{pendingApprovals.map((approval) => {
|
||||
const isResponding = respondingRequestIds.includes(approval.requestId);
|
||||
return (
|
||||
<div
|
||||
key={approval.requestId}
|
||||
className="rounded-lg border border-amber-300/20 bg-amber-500/[0.07] px-3 py-2"
|
||||
>
|
||||
<p className="text-xs font-medium text-amber-100">
|
||||
{approval.requestKind === "command"
|
||||
? "Command approval requested"
|
||||
: "File-change approval requested"}
|
||||
</p>
|
||||
{approval.detail && (
|
||||
<p
|
||||
className="mt-1 truncate font-mono text-[11px] text-amber-100/75"
|
||||
title={approval.detail}
|
||||
>
|
||||
{approval.detail}
|
||||
</p>
|
||||
{approval.detail && (
|
||||
<p
|
||||
className="mt-1 truncate font-mono text-[11px] text-amber-900/80 dark:text-amber-100/75"
|
||||
title={approval.detail}
|
||||
>
|
||||
{approval.detail}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
|
||||
>
|
||||
Approve once
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-sky-300/70 bg-sky-100 px-2 py-1 text-[11px] text-sky-800 transition-colors duration-150 hover:bg-sky-200 disabled:cursor-not-allowed disabled:opacity-50 dark:border-sky-300/30 dark:bg-sky-500/15 dark:text-sky-100 dark:hover:bg-sky-500/22"
|
||||
disabled={isResponding}
|
||||
onClick={() =>
|
||||
void onRespondToApproval(approval.requestId, "acceptForSession")
|
||||
}
|
||||
>
|
||||
Always allow this session
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
|
||||
>
|
||||
Decline
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-rose-300/70 bg-rose-100 px-2 py-1 text-[11px] text-rose-800 transition-colors duration-150 hover:bg-rose-200 disabled:cursor-not-allowed disabled:opacity-50 dark:border-rose-300/30 dark:bg-rose-500/12 dark:text-rose-100 dark:hover:bg-rose-500/20"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
|
||||
>
|
||||
Cancel turn
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-border bg-accent px-2 py-1 text-[11px] text-foreground transition-colors duration-150 hover:bg-accent/80 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "accept")}
|
||||
>
|
||||
Approve once
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-sky-300/30 bg-sky-500/[0.15] px-2 py-1 text-[11px] text-sky-100 transition-colors duration-150 hover:bg-sky-500/[0.22] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "acceptForSession")}
|
||||
>
|
||||
Always allow this session
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-border px-2 py-1 text-[11px] text-foreground/90 transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "decline")}
|
||||
>
|
||||
Decline
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-rose-300/30 bg-rose-500/[0.12] px-2 py-1 text-[11px] text-rose-100 transition-colors duration-150 hover:bg-rose-500/[0.2] disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(approval.requestId, "cancel")}
|
||||
>
|
||||
Cancel turn
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1114,39 +888,13 @@ export default function ChatView() {
|
||||
}
|
||||
|
||||
if (timelineEntry.message.role === "user") {
|
||||
const userImages = timelineEntry.message.attachments ?? [];
|
||||
return (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
||||
{userImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full max-h-[220px] w-full cursor-zoom-in object-cover"
|
||||
onClick={() => openImageDialog(image.previewUrl, image.name)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{timelineEntry.message.text && (
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
)}
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-foreground">
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
<p className="mt-1.5 text-right text-[10px] text-muted-foreground/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
@@ -1209,48 +957,9 @@ export default function ChatView() {
|
||||
{/* Input bar */}
|
||||
<div className="px-5 pb-1 pt-2">
|
||||
<form onSubmit={onSend} className="mx-auto max-w-3xl">
|
||||
<div
|
||||
className={`group rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring ${
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border"
|
||||
}`}
|
||||
onDragEnter={onComposerDragEnter}
|
||||
onDragOver={onComposerDragOver}
|
||||
onDragLeave={onComposerDragLeave}
|
||||
onDrop={onComposerDrop}
|
||||
>
|
||||
<div className="group rounded-[20px] border border-border bg-card transition-colors duration-200 focus-within:border-ring">
|
||||
{/* Textarea area */}
|
||||
<div className="px-4 pt-4 pb-2">
|
||||
{composerImages.length > 0 && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{composerImages.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full cursor-zoom-in object-cover"
|
||||
onClick={() => openImageDialog(image.previewUrl, image.name)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-1 top-1 flex h-4 w-4 items-center justify-center rounded-full bg-background/80 text-[11px] leading-none text-foreground transition-colors duration-150 hover:bg-background"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
className="w-full resize-none bg-transparent text-[14px] leading-relaxed text-foreground placeholder:text-muted-foreground/35 focus:outline-none"
|
||||
@@ -1258,11 +967,8 @@ export default function ChatView() {
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
onPaste={onComposerPaste}
|
||||
placeholder={
|
||||
phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, or attach images..."
|
||||
phase === "disconnected" ? "Ask for follow-up changes" : "Ask anything..."
|
||||
}
|
||||
disabled={isSending || isConnecting}
|
||||
/>
|
||||
@@ -1452,7 +1158,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()}
|
||||
aria-label={
|
||||
isConnecting ? "Connecting" : isSending ? "Sending" : "Send message"
|
||||
}
|
||||
@@ -1508,17 +1214,9 @@ export default function ChatView() {
|
||||
key={activeThread.id}
|
||||
api={api}
|
||||
threadId={activeThread.id}
|
||||
cwd={gitCwd ?? activeProject.cwd}
|
||||
cwd={activeProject.cwd}
|
||||
height={activeThread.terminalHeight}
|
||||
terminalIds={activeThread.terminalIds}
|
||||
activeTerminalId={activeThread.activeTerminalId}
|
||||
terminalGroups={activeThread.terminalGroups}
|
||||
activeTerminalGroupId={activeThread.activeTerminalGroupId}
|
||||
focusRequestId={terminalFocusRequestId}
|
||||
onSplitTerminal={splitTerminal}
|
||||
onNewTerminal={createNewTerminal}
|
||||
onActiveTerminalChange={activateTerminal}
|
||||
onCloseTerminal={closeTerminal}
|
||||
onHeightChange={(height) =>
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_HEIGHT",
|
||||
@@ -1526,41 +1224,15 @@ export default function ChatView() {
|
||||
height,
|
||||
})
|
||||
}
|
||||
onThreadExited={() =>
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThread.id,
|
||||
open: false,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{expandedImage && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Expanded image preview"
|
||||
onClick={() => setExpandedImage(null)}
|
||||
>
|
||||
<div
|
||||
className="relative isolate max-h-[92vh] max-w-[92vw]"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-2 z-30 flex h-8 w-8 cursor-pointer items-center justify-center rounded-full bg-black/60 text-xl leading-none text-white transition-colors duration-150 hover:bg-black/80 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/80 [-webkit-app-region:no-drag]"
|
||||
onClick={() => setExpandedImage(null)}
|
||||
aria-label="Close image preview"
|
||||
>
|
||||
<span className="pointer-events-none">×</span>
|
||||
</button>
|
||||
<img
|
||||
src={expandedImage.src}
|
||||
alt={expandedImage.name}
|
||||
className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
|
||||
draggable={false}
|
||||
/>
|
||||
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
|
||||
{expandedImage.name}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ export default function DiffPanel() {
|
||||
<aside className="flex h-full w-[400px] shrink-0 flex-col border-l border-border bg-card">
|
||||
{/* Header */}
|
||||
<div
|
||||
className={`flex items-center justify-between border-b border-border px-4 ${isElectron ? "drag-region h-[52px]" : "py-3"}`}
|
||||
className={`flex items-center justify-between border-b border-border px-4 pb-3 ${isElectron ? "drag-region pt-[28px]" : "pt-3"}`}
|
||||
>
|
||||
<h3 className="text-xs font-medium text-foreground">Uncommitted changes</h3>
|
||||
<button
|
||||
|
||||
@@ -1,831 +0,0 @@
|
||||
import {
|
||||
type GitRunStackedActionResult,
|
||||
type GitStackedAction,
|
||||
type GitStatusResult,
|
||||
type NativeApi,
|
||||
} from "@t3tools/contracts";
|
||||
import { queryOptions, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
CheckIcon,
|
||||
CircleIcon,
|
||||
CloudUploadIcon,
|
||||
GitCommitIcon,
|
||||
Loader2Icon,
|
||||
MinusIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
|
||||
interface GitActionsControlProps {
|
||||
api: NativeApi | undefined;
|
||||
gitCwd: string | null;
|
||||
}
|
||||
|
||||
type GitActionIconName = "commit" | "push" | "pr";
|
||||
|
||||
interface GitActionMenuItem {
|
||||
id: "commit" | "push" | "pr";
|
||||
label: string;
|
||||
disabled: boolean;
|
||||
icon: GitActionIconName;
|
||||
kind: "open_modal" | "run_action" | "open_pr";
|
||||
action?: GitStackedAction;
|
||||
}
|
||||
|
||||
interface GitModalActionOption {
|
||||
action: GitStackedAction;
|
||||
label: string;
|
||||
disabled: boolean;
|
||||
icon: GitActionIconName;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
type GitProgressStepStatus = "pending" | "running" | "completed" | "skipped" | "failed";
|
||||
|
||||
interface GitProgressStep {
|
||||
id: "generate" | "commit" | "push" | "pr";
|
||||
label: string;
|
||||
status: GitProgressStepStatus;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
function GitActionIcon(props: { icon: GitActionIconName; disabled: boolean }) {
|
||||
const toneClass = props.disabled ? "text-muted-foreground/45" : "text-foreground/85";
|
||||
|
||||
if (props.icon === "commit") {
|
||||
return <GitCommitIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
|
||||
}
|
||||
|
||||
if (props.icon === "push") {
|
||||
return <CloudUploadIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
|
||||
}
|
||||
|
||||
return <GitHubIcon className={`h-5 w-5 shrink-0 ${toneClass}`} />;
|
||||
}
|
||||
|
||||
function gitActionModalTitle(): string {
|
||||
return "Commit your changes";
|
||||
}
|
||||
|
||||
function initialGitProgressSteps(
|
||||
action: GitStackedAction,
|
||||
commitMessage: string,
|
||||
): GitProgressStep[] {
|
||||
const hasCustomMessage = commitMessage.trim().length > 0;
|
||||
const steps: GitProgressStep[] = [];
|
||||
|
||||
if (!hasCustomMessage) {
|
||||
steps.push({
|
||||
id: "generate",
|
||||
label: "Generate commit message",
|
||||
status: "pending",
|
||||
});
|
||||
}
|
||||
|
||||
steps.push({
|
||||
id: "commit",
|
||||
label: "Commit changes",
|
||||
status: "pending",
|
||||
});
|
||||
|
||||
if (action !== "commit") {
|
||||
steps.push({
|
||||
id: "push",
|
||||
label: "Push branch",
|
||||
status: "pending",
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "commit_push_pr") {
|
||||
steps.push({
|
||||
id: "pr",
|
||||
label: "Create or open PR",
|
||||
status: "pending",
|
||||
});
|
||||
}
|
||||
|
||||
return steps;
|
||||
}
|
||||
|
||||
function updateProgressStep(
|
||||
steps: GitProgressStep[],
|
||||
id: GitProgressStep["id"],
|
||||
status: GitProgressStepStatus,
|
||||
detail?: string,
|
||||
): GitProgressStep[] {
|
||||
return steps.map((step) => {
|
||||
if (step.id !== id) return step;
|
||||
return {
|
||||
...step,
|
||||
status,
|
||||
...(detail ? { detail } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function runActionLabel(action: GitStackedAction): string {
|
||||
if (action === "commit") return "Commit changes";
|
||||
if (action === "commit_push") return "Commit and push";
|
||||
return "Commit and create PR";
|
||||
}
|
||||
|
||||
function buildGitActionMenuItems(
|
||||
gitStatus: GitStatusResult | null,
|
||||
isDisabled: boolean,
|
||||
): GitActionMenuItem[] {
|
||||
if (!gitStatus) return [];
|
||||
|
||||
const hasBranch = gitStatus.branch !== null;
|
||||
const hasOpenPr = gitStatus.openPr !== null;
|
||||
const hasChanges = gitStatus.hasWorkingTreeChanges;
|
||||
const hasAhead = gitStatus.aheadCount > 0;
|
||||
const canCommit = !isDisabled && hasChanges;
|
||||
const canPush = !isDisabled && hasBranch && !hasChanges && hasAhead;
|
||||
const canOpenPr = !isDisabled && hasOpenPr;
|
||||
const canCreatePr =
|
||||
!isDisabled &&
|
||||
hasBranch &&
|
||||
!hasOpenPr &&
|
||||
!hasChanges &&
|
||||
gitStatus.hasUpstream &&
|
||||
gitStatus.behindCount === 0;
|
||||
|
||||
return [
|
||||
{
|
||||
id: "commit",
|
||||
label: "Commit",
|
||||
disabled: !canCommit,
|
||||
icon: "commit",
|
||||
kind: "open_modal",
|
||||
},
|
||||
{
|
||||
id: "push",
|
||||
label: "Push",
|
||||
disabled: !canPush,
|
||||
icon: "push",
|
||||
kind: "run_action",
|
||||
action: "commit_push",
|
||||
},
|
||||
hasOpenPr
|
||||
? {
|
||||
id: "pr",
|
||||
label: "View PR",
|
||||
disabled: !canOpenPr,
|
||||
icon: "pr",
|
||||
kind: "open_pr",
|
||||
}
|
||||
: {
|
||||
id: "pr",
|
||||
label: "Create PR",
|
||||
disabled: !canCreatePr,
|
||||
icon: "pr",
|
||||
kind: "run_action",
|
||||
action: "commit_push_pr",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function buildGitModalActionOptions(
|
||||
gitStatus: GitStatusResult | null,
|
||||
isDisabled: boolean,
|
||||
): GitModalActionOption[] {
|
||||
const hasBranch = gitStatus?.branch !== null;
|
||||
const hasOpenPr = gitStatus?.openPr !== null;
|
||||
|
||||
return [
|
||||
{
|
||||
action: "commit",
|
||||
label: "Commit",
|
||||
disabled: isDisabled,
|
||||
icon: "commit",
|
||||
},
|
||||
{
|
||||
action: "commit_push",
|
||||
label: "Commit and push",
|
||||
disabled: isDisabled || !hasBranch,
|
||||
icon: "push",
|
||||
...(!hasBranch ? { detail: "Requires an attached branch." } : {}),
|
||||
},
|
||||
{
|
||||
action: "commit_push_pr",
|
||||
label: "Commit and create PR",
|
||||
disabled: isDisabled || !hasBranch || hasOpenPr,
|
||||
icon: "pr",
|
||||
...(!hasBranch
|
||||
? { detail: "Requires an attached branch." }
|
||||
: hasOpenPr
|
||||
? { detail: "A PR is already open for this branch." }
|
||||
: {}),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function getGitStatusQueryKey(gitCwd: string | null): readonly ["git", "status", string | null] {
|
||||
return ["git", "status", gitCwd];
|
||||
}
|
||||
|
||||
function gitStatusQueryOptions(api: NativeApi | undefined, gitCwd: string | null) {
|
||||
return queryOptions({
|
||||
queryKey: getGitStatusQueryKey(gitCwd),
|
||||
queryFn: async () => {
|
||||
if (!api || !gitCwd) {
|
||||
throw new Error("Git status is unavailable.");
|
||||
}
|
||||
return api.git.status({ cwd: gitCwd });
|
||||
},
|
||||
enabled: !!api && !!gitCwd,
|
||||
});
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ api, gitCwd }: GitActionsControlProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const [isGitMenuOpen, setIsGitMenuOpen] = useState(false);
|
||||
const [isGitModalActionRunning, setIsGitModalActionRunning] = useState(false);
|
||||
const [gitActionError, setGitActionError] = useState<string | null>(null);
|
||||
const [isGitModalOpen, setIsGitModalOpen] = useState(false);
|
||||
const [gitModalSelectedAction, setGitModalSelectedAction] = useState<GitStackedAction>("commit");
|
||||
const [gitModalCommitMessage, setGitModalCommitMessage] = useState("");
|
||||
const [gitModalProgress, setGitModalProgress] = useState<GitProgressStep[]>([]);
|
||||
const [gitModalError, setGitModalError] = useState<string | null>(null);
|
||||
const [gitModalResult, setGitModalResult] = useState<GitRunStackedActionResult | null>(null);
|
||||
const gitMenuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(
|
||||
gitStatusQueryOptions(api, gitCwd),
|
||||
);
|
||||
|
||||
const runImmediateGitActionMutation = useMutation({
|
||||
mutationFn: async (action: GitStackedAction) => {
|
||||
if (!api || !gitCwd) {
|
||||
throw new Error("Git action is unavailable.");
|
||||
}
|
||||
return api.git.runStackedAction({ cwd: gitCwd, action });
|
||||
},
|
||||
onMutate: () => {
|
||||
setIsGitMenuOpen(false);
|
||||
setGitActionError(null);
|
||||
setGitModalError(null);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: ["git"] });
|
||||
},
|
||||
onError: (error) => {
|
||||
setGitActionError(error instanceof Error ? error.message : "Git action failed.");
|
||||
},
|
||||
});
|
||||
|
||||
const isGitActionRunning = isGitModalActionRunning || runImmediateGitActionMutation.isPending;
|
||||
|
||||
const gitBaseDisabled = !api || !gitCwd || !gitStatus || isGitActionRunning;
|
||||
const gitActionMenuItems = useMemo(
|
||||
() => buildGitActionMenuItems(gitStatus, gitBaseDisabled),
|
||||
[gitBaseDisabled, gitStatus],
|
||||
);
|
||||
const gitModalActionOptions = useMemo(
|
||||
() => buildGitModalActionOptions(gitStatus, !gitStatus || isGitActionRunning),
|
||||
[gitStatus, isGitActionRunning],
|
||||
);
|
||||
const selectedGitModalActionOption = useMemo(
|
||||
() => gitModalActionOptions.find((option) => option.action === gitModalSelectedAction) ?? null,
|
||||
[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 refreshGitStatus = useCallback(async () => {
|
||||
if (!api || !gitCwd) return;
|
||||
await queryClient.invalidateQueries({ queryKey: ["git"] });
|
||||
setGitActionError(null);
|
||||
}, [api, gitCwd, queryClient]);
|
||||
|
||||
const openGitActionModal = useCallback(() => {
|
||||
setIsGitMenuOpen(false);
|
||||
setIsGitModalOpen(true);
|
||||
setGitModalSelectedAction("commit");
|
||||
setGitModalCommitMessage("");
|
||||
setGitModalProgress([]);
|
||||
setGitModalError(null);
|
||||
setGitModalResult(null);
|
||||
setGitActionError(null);
|
||||
}, []);
|
||||
|
||||
const closeGitActionModal = useCallback(() => {
|
||||
if (isGitActionRunning) return;
|
||||
setIsGitModalOpen(false);
|
||||
setGitModalSelectedAction("commit");
|
||||
setGitModalCommitMessage("");
|
||||
setGitModalProgress([]);
|
||||
setGitModalError(null);
|
||||
setGitModalResult(null);
|
||||
}, [isGitActionRunning]);
|
||||
|
||||
const runGitActionImmediately = useCallback(
|
||||
(action: GitStackedAction) => {
|
||||
runImmediateGitActionMutation.mutate(action);
|
||||
},
|
||||
[runImmediateGitActionMutation],
|
||||
);
|
||||
|
||||
const openExistingPr = useCallback(() => {
|
||||
setIsGitMenuOpen(false);
|
||||
setGitActionError(null);
|
||||
if (!api) {
|
||||
setGitActionError("Link opening is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const prUrl = gitStatus?.openPr?.url ?? null;
|
||||
if (!prUrl) {
|
||||
setGitActionError("No open PR found for the current branch.");
|
||||
return;
|
||||
}
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
setGitActionError(error instanceof Error ? error.message : "Unable to open PR link.");
|
||||
});
|
||||
}, [api, gitStatus?.openPr?.url]);
|
||||
|
||||
const openPrFromModal = useCallback(() => {
|
||||
if (!api) {
|
||||
setGitModalError("Link opening is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
const prUrl = gitModalOpenPrUrl;
|
||||
if (!prUrl) return;
|
||||
|
||||
void api.shell.openExternal(prUrl).catch((error) => {
|
||||
setGitModalError(error instanceof Error ? error.message : "Unable to open PR link.");
|
||||
});
|
||||
}, [api, gitModalOpenPrUrl]);
|
||||
|
||||
const runGitAction = useCallback(async () => {
|
||||
if (!api || !gitCwd || !isGitModalOpen) return;
|
||||
if (!selectedGitModalActionOption || selectedGitModalActionOption.disabled) return;
|
||||
const actionCwd = gitCwd;
|
||||
const action = selectedGitModalActionOption.action;
|
||||
const commitMessage = gitModalCommitMessage.trim();
|
||||
const includeGeneratedCommitMessage = commitMessage.length === 0;
|
||||
|
||||
setIsGitModalActionRunning(true);
|
||||
setGitModalError(null);
|
||||
setGitActionError(null);
|
||||
setGitModalResult(null);
|
||||
setGitModalProgress(initialGitProgressSteps(action, commitMessage));
|
||||
|
||||
let commit: GitRunStackedActionResult["commit"] = {
|
||||
status: "skipped_no_changes",
|
||||
};
|
||||
let push: GitRunStackedActionResult["push"] = {
|
||||
status: "skipped_not_requested",
|
||||
};
|
||||
let pr: GitRunStackedActionResult["pr"] = {
|
||||
status: "skipped_not_requested",
|
||||
};
|
||||
|
||||
const updateStep = (
|
||||
id: GitProgressStep["id"],
|
||||
status: GitProgressStepStatus,
|
||||
detail?: string,
|
||||
) => {
|
||||
setGitModalProgress((steps) => updateProgressStep(steps, id, status, detail));
|
||||
};
|
||||
|
||||
try {
|
||||
if (includeGeneratedCommitMessage) {
|
||||
updateStep("generate", "running");
|
||||
} else {
|
||||
updateStep("commit", "running");
|
||||
}
|
||||
|
||||
const commitRun = await api.git.runStackedAction({
|
||||
cwd: actionCwd,
|
||||
action: "commit",
|
||||
...(commitMessage.length > 0 ? { commitMessage } : {}),
|
||||
});
|
||||
commit = commitRun.commit;
|
||||
|
||||
if (includeGeneratedCommitMessage) {
|
||||
if (commitRun.commit.status === "created") {
|
||||
if (commitRun.commit.subject) {
|
||||
setGitModalCommitMessage(commitRun.commit.subject);
|
||||
}
|
||||
updateStep("generate", "completed");
|
||||
} else {
|
||||
updateStep("generate", "skipped", "No local changes to commit.");
|
||||
}
|
||||
}
|
||||
|
||||
if (commitRun.commit.status === "created") {
|
||||
updateStep("commit", "completed", commitRun.commit.subject ?? "Committed local changes.");
|
||||
} else {
|
||||
updateStep("commit", "skipped", "No local changes to commit.");
|
||||
}
|
||||
|
||||
if (action !== "commit") {
|
||||
updateStep("push", "running");
|
||||
const pushRun = await api.git.runStackedAction({
|
||||
cwd: actionCwd,
|
||||
action: "commit_push",
|
||||
});
|
||||
push = pushRun.push;
|
||||
if (pushRun.push.status === "pushed") {
|
||||
updateStep(
|
||||
"push",
|
||||
"completed",
|
||||
pushRun.push.upstreamBranch
|
||||
? `Pushed to ${pushRun.push.upstreamBranch}.`
|
||||
: "Pushed latest commits.",
|
||||
);
|
||||
} else {
|
||||
updateStep("push", "skipped", "Branch already up to date.");
|
||||
}
|
||||
}
|
||||
|
||||
if (action === "commit_push_pr") {
|
||||
updateStep("pr", "running");
|
||||
const prRun = await api.git.runStackedAction({
|
||||
cwd: actionCwd,
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
pr = prRun.pr;
|
||||
if (prRun.pr.status === "opened_existing") {
|
||||
updateStep(
|
||||
"pr",
|
||||
"completed",
|
||||
prRun.pr.number ? `Opened existing PR #${prRun.pr.number}.` : "Opened existing PR.",
|
||||
);
|
||||
} else if (prRun.pr.status === "created") {
|
||||
updateStep(
|
||||
"pr",
|
||||
"completed",
|
||||
prRun.pr.number ? `Created PR #${prRun.pr.number}.` : "Created PR.",
|
||||
);
|
||||
} else {
|
||||
updateStep("pr", "skipped", "PR step was not requested.");
|
||||
}
|
||||
}
|
||||
|
||||
setGitModalResult({ action, commit, push, pr });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Git action failed.";
|
||||
setGitModalError(message);
|
||||
setGitActionError(message);
|
||||
setGitModalProgress((steps) => {
|
||||
const active = steps.find((step) => step.status === "running");
|
||||
if (!active) return steps;
|
||||
return updateProgressStep(steps, active.id, "failed", message);
|
||||
});
|
||||
} finally {
|
||||
setIsGitModalActionRunning(false);
|
||||
await refreshGitStatus().catch(() => undefined);
|
||||
}
|
||||
}, [
|
||||
api,
|
||||
gitCwd,
|
||||
gitModalCommitMessage,
|
||||
isGitModalOpen,
|
||||
refreshGitStatus,
|
||||
selectedGitModalActionOption,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setGitActionError(null);
|
||||
setGitModalError(null);
|
||||
setIsGitModalOpen(false);
|
||||
setGitModalSelectedAction("commit");
|
||||
setGitModalCommitMessage("");
|
||||
setGitModalProgress([]);
|
||||
setGitModalResult(null);
|
||||
}, [gitCwd]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isGitModalOpen) return;
|
||||
if (selectedGitModalActionOption && !selectedGitModalActionOption.disabled) return;
|
||||
|
||||
const fallback = gitModalActionOptions.find((option) => !option.disabled);
|
||||
if (fallback) {
|
||||
setGitModalSelectedAction(fallback.action);
|
||||
}
|
||||
}, [gitModalActionOptions, isGitModalOpen, selectedGitModalActionOption]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isGitMenuOpen) return;
|
||||
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (!gitMenuRef.current) return;
|
||||
if (event.target instanceof Node && !gitMenuRef.current.contains(event.target)) {
|
||||
setIsGitMenuOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("mousedown", handleClickOutside);
|
||||
return () => {
|
||||
window.removeEventListener("mousedown", handleClickOutside);
|
||||
};
|
||||
}, [isGitMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isGitModalOpen) return;
|
||||
|
||||
const handleEscape = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return;
|
||||
if (isGitActionRunning) return;
|
||||
closeGitActionModal();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
};
|
||||
}, [closeGitActionModal, isGitActionRunning, isGitModalOpen]);
|
||||
|
||||
if (!gitCwd) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative" ref={gitMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] text-muted-foreground/70 transition-colors duration-150 hover:bg-accent hover:text-foreground/80 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
onClick={() => {
|
||||
if (!isGitMenuOpen) {
|
||||
void refreshGitStatus().catch(() => undefined);
|
||||
}
|
||||
setIsGitMenuOpen((v) => !v);
|
||||
}}
|
||||
disabled={!gitStatus || isGitActionRunning}
|
||||
>
|
||||
{isGitActionRunning ? "Running..." : "Git actions"}
|
||||
<span aria-hidden="true">▾</span>
|
||||
</button>
|
||||
{isGitMenuOpen && (
|
||||
<div className="absolute right-0 top-full z-50 mt-1 w-[280px] rounded-3xl border border-border bg-popover p-3 shadow-xl">
|
||||
<p className="px-3 pb-2 text-[13px] text-muted-foreground/75">Git actions</p>
|
||||
{gitActionMenuItems.map((item) => {
|
||||
return (
|
||||
<button
|
||||
key={`${item.id}-${item.label}`}
|
||||
type="button"
|
||||
className="mb-1.5 flex w-full items-center gap-3 rounded-2xl px-3 py-2.5 text-left text-[14px] text-foreground transition-colors duration-150 hover:bg-accent disabled:cursor-not-allowed disabled:text-muted-foreground/65"
|
||||
disabled={item.disabled}
|
||||
onClick={() => {
|
||||
if (item.kind === "open_modal") {
|
||||
openGitActionModal();
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.kind === "open_pr") {
|
||||
openExistingPr();
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.action) {
|
||||
void runGitActionImmediately(item.action);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<GitActionIcon icon={item.icon} disabled={item.disabled} />
|
||||
<span>{item.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{gitStatus?.branch === null && (
|
||||
<p className="px-2 pt-1 text-[10px] text-amber-500 dark:text-amber-300">
|
||||
Detached HEAD: push and PR actions are unavailable.
|
||||
</p>
|
||||
)}
|
||||
{gitStatus &&
|
||||
gitStatus.branch !== null &&
|
||||
!gitStatus.hasWorkingTreeChanges &&
|
||||
gitStatus.aheadCount === 0 &&
|
||||
gitStatus.behindCount > 0 && (
|
||||
<p className="px-3 pt-1 text-[10px] text-amber-500 dark:text-amber-300">
|
||||
Branch is behind upstream. Pull/rebase before opening a PR.
|
||||
</p>
|
||||
)}
|
||||
{visibleGitActionError && (
|
||||
<p className="px-3 pt-2 text-[11px] text-rose-500 dark:text-rose-300">
|
||||
{visibleGitActionError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isGitModalOpen && (
|
||||
<div
|
||||
className="fixed inset-0 z-80 flex items-center justify-center bg-black/35 px-4 py-6"
|
||||
onMouseDown={() => {
|
||||
closeGitActionModal();
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-[640px] rounded-3xl border border-border bg-popover p-6 shadow-2xl"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Git action confirmation"
|
||||
onMouseDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="rounded-2xl bg-accent p-3">
|
||||
<GitActionIcon
|
||||
icon={selectedGitModalActionOption?.icon ?? "commit"}
|
||||
disabled={false}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-[0.14em] text-muted-foreground/70">
|
||||
Git actions
|
||||
</p>
|
||||
<h3 className="text-3xl font-semibold tracking-tight text-foreground">
|
||||
{gitActionModalTitle()}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1 text-muted-foreground/60 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
||||
onClick={closeGitActionModal}
|
||||
disabled={isGitActionRunning}
|
||||
aria-label="Close git action dialog"
|
||||
>
|
||||
<XIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-6 space-y-2 rounded-2xl border border-border/80 bg-card/40 px-4 py-3">
|
||||
<div className="flex items-center justify-between gap-4 text-sm">
|
||||
<span className="text-muted-foreground/70">Branch</span>
|
||||
<span className="font-mono text-foreground">
|
||||
{gitStatus?.branch ?? "(detached HEAD)"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-4 text-sm">
|
||||
<span className="text-muted-foreground/70">Changes</span>
|
||||
<span className="text-foreground">
|
||||
{gitStatus?.hasWorkingTreeChanges
|
||||
? "Working tree has changes"
|
||||
: "No local changes"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<label
|
||||
htmlFor="git-commit-message"
|
||||
className="mb-2 block text-sm font-medium text-foreground"
|
||||
>
|
||||
Commit message
|
||||
</label>
|
||||
<textarea
|
||||
id="git-commit-message"
|
||||
rows={3}
|
||||
className="w-full resize-none rounded-2xl border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:border-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-70"
|
||||
placeholder="Leave blank to autogenerate a commit message"
|
||||
value={gitModalCommitMessage}
|
||||
onChange={(event) => setGitModalCommitMessage(event.target.value)}
|
||||
disabled={!gitModalSelectionMode || 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;
|
||||
|
||||
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={`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>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{(gitModalError ?? visibleGitActionError) && (
|
||||
<div className="mt-4 rounded-lg border border-rose-300/50 bg-rose-500/10 px-3 py-2 text-xs text-rose-600 dark:text-rose-200">
|
||||
{gitModalError ?? visibleGitActionError}
|
||||
</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"
|
||||
}
|
||||
onClick={closeGitActionModal}
|
||||
disabled={isGitActionRunning}
|
||||
>
|
||||
{gitModalResult ? "Done" : "Cancel"}
|
||||
</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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { SVGProps } from "react";
|
||||
|
||||
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
|
||||
|
||||
export const GitHubIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 1024 1024" fill="none">
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
clipRule="evenodd"
|
||||
d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
|
||||
transform="scale(64)"
|
||||
fill="#1B1F23"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
@@ -3,15 +3,9 @@ import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { derivePendingApprovals } from "../session-logic";
|
||||
import { readNativeApi } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project } from "../types";
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
function formatRelativeTime(iso: string): string {
|
||||
@@ -31,79 +25,22 @@ function inferProjectName(cwd: string): string {
|
||||
return last && last.length > 0 ? last : "project";
|
||||
}
|
||||
|
||||
interface ThreadStatusPill {
|
||||
label: "Working" | "Connecting" | "Completed" | "Awaiting response";
|
||||
colorClass: string;
|
||||
dotClass: string;
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurnCompletedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||
if (Number.isNaN(completedAt)) return false;
|
||||
if (!thread.lastVisitedAt) return true;
|
||||
|
||||
const lastVisitedAt = Date.parse(thread.lastVisitedAt);
|
||||
if (Number.isNaN(lastVisitedAt)) return true;
|
||||
return completedAt > lastVisitedAt;
|
||||
}
|
||||
|
||||
function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {
|
||||
if (hasPendingApprovals) {
|
||||
return {
|
||||
label: "Awaiting response",
|
||||
colorClass: "text-amber-600 dark:text-amber-300/90",
|
||||
dotClass: "bg-amber-500 dark:bg-amber-300/90",
|
||||
pulse: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
return {
|
||||
label: "Working",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
dotClass: "bg-sky-500 dark:bg-sky-300/80",
|
||||
pulse: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "connecting") {
|
||||
return {
|
||||
label: "Connecting",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
dotClass: "bg-sky-500 dark:bg-sky-300/80",
|
||||
pulse: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (hasUnseenCompletion(thread)) {
|
||||
return {
|
||||
label: "Completed",
|
||||
colorClass: "text-emerald-600 dark:text-emerald-300/90",
|
||||
dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
|
||||
pulse: false,
|
||||
};
|
||||
}
|
||||
|
||||
function threadStatusLabel(
|
||||
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
|
||||
): "Working" | "Connecting" | null {
|
||||
if (status === "running") return "Working";
|
||||
if (status === "connecting") return "Connecting";
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
const [isAddingProject, setIsAddingProject] = useState(false);
|
||||
const pendingApprovalByThreadId = useMemo(() => {
|
||||
const map = new Map<string, boolean>();
|
||||
for (const thread of state.threads) {
|
||||
map.set(thread.id, derivePendingApprovals(thread.events).length > 0);
|
||||
}
|
||||
return map;
|
||||
}, [state.threads]);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(projectId: string) => {
|
||||
@@ -117,15 +54,6 @@ export default function Sidebar() {
|
||||
model: state.projects.find((p) => p.id === projectId)?.model ?? DEFAULT_MODEL,
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
@@ -309,10 +237,10 @@ export default function Sidebar() {
|
||||
|
||||
return (
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-border bg-card">
|
||||
{/* Drag region / traffic light space (Electron only) */}
|
||||
{isElectron && <div className="drag-region h-[52px] shrink-0" />}
|
||||
{/* Branding */}
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-4 ${isElectron ? "drag-region h-[52px] pl-[76px]" : "py-4"}`}
|
||||
>
|
||||
<div className={`flex items-center gap-2.5 px-4 pb-4 ${isElectron ? "" : "pt-4"}`}>
|
||||
<span className="flex-1 text-sm font-semibold tracking-tight text-foreground">
|
||||
T3 <span className="font-normal text-muted-foreground">Code</span>
|
||||
</span>
|
||||
@@ -384,10 +312,7 @@ export default function Sidebar() {
|
||||
<div className="ml-2 border-l border-border/80 pl-2">
|
||||
{threads.map((thread) => {
|
||||
const isActive = state.activeThreadId === thread.id;
|
||||
const threadStatus = threadStatusPill(
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const threadStatus = threadStatusLabel(thread.session?.status);
|
||||
return (
|
||||
<button
|
||||
key={thread.id}
|
||||
@@ -413,15 +338,9 @@ export default function Sidebar() {
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
{threadStatus && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
|
||||
threadStatus.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="hidden md:inline">{threadStatus.label}</span>
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-sky-600 dark:text-sky-300/80">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />
|
||||
<span className="hidden xl:inline">{threadStatus}</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
|
||||
@@ -1,27 +1,15 @@
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2 } from "lucide-react";
|
||||
import { type NativeApi } from "@t3tools/contracts";
|
||||
import { Terminal, type ITheme } from "@xterm/xterm";
|
||||
import {
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
extractTerminalLinks,
|
||||
isTerminalLinkActivation,
|
||||
preferredTerminalEditor,
|
||||
resolvePathLinkTarget,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut } from "../terminal-shortcuts";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "../types";
|
||||
|
||||
const MIN_DRAWER_HEIGHT = 180;
|
||||
const MAX_DRAWER_HEIGHT_RATIO = 0.75;
|
||||
@@ -109,30 +97,162 @@ function terminalThemeFromApp(): ITheme {
|
||||
};
|
||||
}
|
||||
|
||||
interface TerminalViewportProps {
|
||||
interface ThreadTerminalDrawerProps {
|
||||
api: NativeApi;
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
height: number;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
resizeEpoch: number;
|
||||
drawerHeight: number;
|
||||
onHeightChange: (height: number) => void;
|
||||
onThreadExited: () => void;
|
||||
}
|
||||
|
||||
function TerminalViewport({
|
||||
export default function ThreadTerminalDrawer({
|
||||
api,
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd,
|
||||
height,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
drawerHeight,
|
||||
}: TerminalViewportProps) {
|
||||
onHeightChange,
|
||||
onThreadExited,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const drawerHeightRef = useRef(drawerHeight);
|
||||
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
|
||||
const onHeightChangeRef = useRef(onHeightChange);
|
||||
const onThreadExitedRef = useRef(onThreadExited);
|
||||
const resizeStateRef = useRef<{
|
||||
pointerId: number;
|
||||
startY: number;
|
||||
startHeight: number;
|
||||
} | null>(null);
|
||||
const didResizeDuringDragRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
}, [onHeightChange]);
|
||||
|
||||
useEffect(() => {
|
||||
onThreadExitedRef.current = onThreadExited;
|
||||
}, [onThreadExited]);
|
||||
|
||||
useEffect(() => {
|
||||
drawerHeightRef.current = drawerHeight;
|
||||
}, [drawerHeight]);
|
||||
|
||||
const syncHeight = useCallback(
|
||||
(nextHeight: number) => {
|
||||
const clampedHeight = clampDrawerHeight(nextHeight);
|
||||
if (lastSyncedHeightRef.current === clampedHeight) return;
|
||||
lastSyncedHeightRef.current = clampedHeight;
|
||||
onHeightChangeRef.current(clampedHeight);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const fitAndResizeTerminal = useCallback((preserveBottom = false) => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
const activeFitAddon = fitAddonRef.current;
|
||||
if (!activeTerminal || !activeFitAddon) return;
|
||||
const wasAtBottom =
|
||||
preserveBottom &&
|
||||
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
|
||||
activeFitAddon.fit();
|
||||
if (wasAtBottom) {
|
||||
activeTerminal.scrollToBottom();
|
||||
}
|
||||
void api.terminal
|
||||
.resize({
|
||||
threadId,
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}, [api, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
const clampedHeight = clampDrawerHeight(height);
|
||||
setDrawerHeight(clampedHeight);
|
||||
lastSyncedHeightRef.current = clampedHeight;
|
||||
}, [height, threadId]);
|
||||
|
||||
const handleResizePointerDown = useCallback(
|
||||
(event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
didResizeDuringDragRef.current = false;
|
||||
resizeStateRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
startY: event.clientY,
|
||||
startHeight: drawerHeightRef.current,
|
||||
};
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleResizePointerMove = useCallback(
|
||||
(event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const resizeState = resizeStateRef.current;
|
||||
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
|
||||
event.preventDefault();
|
||||
const clampedHeight = clampDrawerHeight(
|
||||
resizeState.startHeight + (resizeState.startY - event.clientY),
|
||||
);
|
||||
if (clampedHeight === drawerHeightRef.current) {
|
||||
return;
|
||||
}
|
||||
didResizeDuringDragRef.current = true;
|
||||
drawerHeightRef.current = clampedHeight;
|
||||
setDrawerHeight(clampedHeight);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleResizePointerEnd = useCallback(
|
||||
(event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const resizeState = resizeStateRef.current;
|
||||
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
|
||||
resizeStateRef.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
if (!didResizeDuringDragRef.current) {
|
||||
return;
|
||||
}
|
||||
syncHeight(drawerHeightRef.current);
|
||||
fitAndResizeTerminal(true);
|
||||
},
|
||||
[fitAndResizeTerminal, syncHeight],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowResize = () => {
|
||||
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
|
||||
const changed = clampedHeight !== drawerHeightRef.current;
|
||||
if (changed) {
|
||||
setDrawerHeight(clampedHeight);
|
||||
} else {
|
||||
fitAndResizeTerminal(true);
|
||||
}
|
||||
if (!resizeStateRef.current) {
|
||||
syncHeight(clampedHeight);
|
||||
}
|
||||
};
|
||||
window.addEventListener("resize", onWindowResize);
|
||||
return () => {
|
||||
window.removeEventListener("resize", onWindowResize);
|
||||
};
|
||||
}, [fitAndResizeTerminal, syncHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
syncHeight(drawerHeightRef.current);
|
||||
};
|
||||
}, [syncHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = containerRef.current;
|
||||
@@ -161,7 +281,7 @@ function TerminalViewport({
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
try {
|
||||
await api.terminal.write({ threadId, terminalId, data: "\u000c" });
|
||||
await api.terminal.write({ threadId, data: "\u000c" });
|
||||
} catch (error) {
|
||||
writeSystemMessage(
|
||||
activeTerminal,
|
||||
@@ -178,70 +298,9 @@ function TerminalViewport({
|
||||
return false;
|
||||
});
|
||||
|
||||
const terminalLinksDisposable = terminal.registerLinkProvider({
|
||||
provideLinks: (bufferLineNumber, callback) => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
|
||||
if (!line) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const lineText = line.translateToString(true);
|
||||
const matches = extractTerminalLinks(lineText);
|
||||
if (matches.length === 0) {
|
||||
callback(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
callback(
|
||||
matches.map((match) => ({
|
||||
text: match.text,
|
||||
range: {
|
||||
start: { x: match.start + 1, y: bufferLineNumber },
|
||||
end: { x: match.end, y: bufferLineNumber },
|
||||
},
|
||||
activate: (event: MouseEvent) => {
|
||||
if (!isTerminalLinkActivation(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const latestTerminal = terminalRef.current;
|
||||
if (!latestTerminal) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (match.kind === "url") {
|
||||
void api.shell.openExternal(match.text).catch((error) => {
|
||||
writeSystemMessage(
|
||||
latestTerminal,
|
||||
error instanceof Error ? error.message : "Unable to open link",
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const target = resolvePathLinkTarget(match.text, cwd);
|
||||
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
|
||||
writeSystemMessage(
|
||||
latestTerminal,
|
||||
error instanceof Error ? error.message : "Unable to open path",
|
||||
);
|
||||
});
|
||||
},
|
||||
})),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const inputDisposable = terminal.onData((data) => {
|
||||
void api.terminal
|
||||
.write({ threadId, terminalId, data })
|
||||
.write({ threadId, data })
|
||||
.catch((err) =>
|
||||
writeSystemMessage(
|
||||
terminal,
|
||||
@@ -269,7 +328,6 @@ function TerminalViewport({
|
||||
activeFitAddon.fit();
|
||||
const snapshot = await api.terminal.open({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd,
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
@@ -279,11 +337,9 @@ function TerminalViewport({
|
||||
if (snapshot.history.length > 0) {
|
||||
activeTerminal.write(snapshot.history);
|
||||
}
|
||||
if (autoFocus) {
|
||||
window.requestAnimationFrame(() => {
|
||||
activeTerminal.focus();
|
||||
});
|
||||
}
|
||||
window.requestAnimationFrame(() => {
|
||||
activeTerminal.focus();
|
||||
});
|
||||
} catch (err) {
|
||||
if (disposed) return;
|
||||
writeSystemMessage(
|
||||
@@ -294,7 +350,7 @@ function TerminalViewport({
|
||||
};
|
||||
|
||||
const unsubscribe = api.terminal.onEvent((event) => {
|
||||
if (event.threadId !== threadId || event.terminalId !== terminalId) return;
|
||||
if (event.threadId !== threadId) return;
|
||||
const activeTerminal = terminalRef.current;
|
||||
if (!activeTerminal) return;
|
||||
|
||||
@@ -323,37 +379,12 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
if (event.type === "exited") {
|
||||
const details = [
|
||||
typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
|
||||
typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
|
||||
]
|
||||
.filter((value): value is string => value !== null)
|
||||
.join(", ");
|
||||
writeSystemMessage(
|
||||
activeTerminal,
|
||||
details.length > 0 ? `Process exited (${details})` : "Process exited",
|
||||
);
|
||||
onThreadExitedRef.current();
|
||||
}
|
||||
});
|
||||
|
||||
const fitTimer = window.setTimeout(() => {
|
||||
const activeTerminal = terminalRef.current;
|
||||
const activeFitAddon = fitAddonRef.current;
|
||||
if (!activeTerminal || !activeFitAddon) return;
|
||||
const wasAtBottom =
|
||||
activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
|
||||
activeFitAddon.fit();
|
||||
if (wasAtBottom) {
|
||||
activeTerminal.scrollToBottom();
|
||||
}
|
||||
void api.terminal
|
||||
.resize({
|
||||
threadId,
|
||||
terminalId,
|
||||
cols: activeTerminal.cols,
|
||||
rows: activeTerminal.rows,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
fitAndResizeTerminal(true);
|
||||
}, 30);
|
||||
void openTerminal();
|
||||
|
||||
@@ -362,16 +393,14 @@ function TerminalViewport({
|
||||
window.clearTimeout(fitTimer);
|
||||
unsubscribe();
|
||||
inputDisposable.dispose();
|
||||
terminalLinksDisposable.dispose();
|
||||
themeObserver.disconnect();
|
||||
terminalRef.current = null;
|
||||
fitAddonRef.current = null;
|
||||
terminal.dispose();
|
||||
};
|
||||
}, [api, cwd, terminalId, threadId]);
|
||||
}, [api, cwd, fitAndResizeTerminal, threadId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoFocus) return;
|
||||
const terminal = terminalRef.current;
|
||||
if (!terminal) return;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -380,7 +409,7 @@ function TerminalViewport({
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [autoFocus, focusRequestId]);
|
||||
}, [focusRequestId]);
|
||||
|
||||
useEffect(() => {
|
||||
const terminal = terminalRef.current;
|
||||
@@ -395,7 +424,6 @@ function TerminalViewport({
|
||||
void api.terminal
|
||||
.resize({
|
||||
threadId,
|
||||
terminalId,
|
||||
cols: terminal.cols,
|
||||
rows: terminal.rows,
|
||||
})
|
||||
@@ -404,460 +432,27 @@ function TerminalViewport({
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [api, drawerHeight, resizeEpoch, terminalId, threadId]);
|
||||
|
||||
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
|
||||
}
|
||||
|
||||
interface ThreadTerminalDrawerProps {
|
||||
api: NativeApi;
|
||||
threadId: string;
|
||||
cwd: string;
|
||||
height: number;
|
||||
terminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
focusRequestId: number;
|
||||
onSplitTerminal: () => void;
|
||||
onNewTerminal: () => void;
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
}
|
||||
|
||||
export default function ThreadTerminalDrawer({
|
||||
api,
|
||||
threadId,
|
||||
cwd,
|
||||
height,
|
||||
terminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
focusRequestId,
|
||||
onSplitTerminal,
|
||||
onNewTerminal,
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const [resizeEpoch, setResizeEpoch] = useState(0);
|
||||
const drawerHeightRef = useRef(drawerHeight);
|
||||
const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
|
||||
const onHeightChangeRef = useRef(onHeightChange);
|
||||
const resizeStateRef = useRef<{
|
||||
pointerId: number;
|
||||
startY: number;
|
||||
startHeight: number;
|
||||
} | null>(null);
|
||||
const didResizeDuringDragRef = useRef(false);
|
||||
|
||||
const normalizedTerminalIds = useMemo(() => {
|
||||
const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}, [terminalIds]);
|
||||
|
||||
const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
|
||||
? activeTerminalId
|
||||
: (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
|
||||
const resolvedTerminalGroups = useMemo(() => {
|
||||
const validTerminalIdSet = new Set(normalizedTerminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const nextGroups: ThreadTerminalGroup[] = [];
|
||||
|
||||
const assignUniqueGroupId = (groupId: string): string => {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
};
|
||||
|
||||
for (const terminalGroup of terminalGroups) {
|
||||
const nextTerminalIds = [
|
||||
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
].filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (nextTerminalIds.length === 0) continue;
|
||||
|
||||
for (const terminalId of nextTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
|
||||
const baseGroupId =
|
||||
terminalGroup.id.trim().length > 0
|
||||
? terminalGroup.id.trim()
|
||||
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId),
|
||||
terminalIds: nextTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of normalizedTerminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
nextGroups.push({
|
||||
id: assignUniqueGroupId(`group-${terminalId}`),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (nextGroups.length > 0) {
|
||||
return nextGroups;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: `group-${resolvedActiveTerminalId}`,
|
||||
terminalIds: [resolvedActiveTerminalId],
|
||||
},
|
||||
];
|
||||
}, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
|
||||
|
||||
const resolvedActiveGroupIndex = useMemo(() => {
|
||||
const indexById = resolvedTerminalGroups.findIndex(
|
||||
(terminalGroup) => terminalGroup.id === activeTerminalGroupId,
|
||||
);
|
||||
if (indexById >= 0) return indexById;
|
||||
const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
|
||||
terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
|
||||
);
|
||||
return indexByTerminal >= 0 ? indexByTerminal : 0;
|
||||
}, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
|
||||
|
||||
const visibleTerminalIds =
|
||||
resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [resolvedActiveTerminalId];
|
||||
const hasTerminalSidebar = normalizedTerminalIds.length > 1;
|
||||
const isSplitView = visibleTerminalIds.length > 1;
|
||||
const showGroupHeaders =
|
||||
resolvedTerminalGroups.length > 1 ||
|
||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||
const terminalLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
}, [onHeightChange]);
|
||||
|
||||
useEffect(() => {
|
||||
drawerHeightRef.current = drawerHeight;
|
||||
}, [drawerHeight]);
|
||||
|
||||
const syncHeight = useCallback((nextHeight: number) => {
|
||||
const clampedHeight = clampDrawerHeight(nextHeight);
|
||||
if (lastSyncedHeightRef.current === clampedHeight) return;
|
||||
lastSyncedHeightRef.current = clampedHeight;
|
||||
onHeightChangeRef.current(clampedHeight);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const clampedHeight = clampDrawerHeight(height);
|
||||
setDrawerHeight(clampedHeight);
|
||||
drawerHeightRef.current = clampedHeight;
|
||||
lastSyncedHeightRef.current = clampedHeight;
|
||||
}, [height, threadId]);
|
||||
|
||||
const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
didResizeDuringDragRef.current = false;
|
||||
resizeStateRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
startY: event.clientY,
|
||||
startHeight: drawerHeightRef.current,
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const resizeState = resizeStateRef.current;
|
||||
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
|
||||
event.preventDefault();
|
||||
const clampedHeight = clampDrawerHeight(
|
||||
resizeState.startHeight + (resizeState.startY - event.clientY),
|
||||
);
|
||||
if (clampedHeight === drawerHeightRef.current) {
|
||||
return;
|
||||
}
|
||||
didResizeDuringDragRef.current = true;
|
||||
drawerHeightRef.current = clampedHeight;
|
||||
setDrawerHeight(clampedHeight);
|
||||
}, []);
|
||||
|
||||
const handleResizePointerEnd = useCallback(
|
||||
(event: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const resizeState = resizeStateRef.current;
|
||||
if (!resizeState || resizeState.pointerId !== event.pointerId) return;
|
||||
resizeStateRef.current = null;
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
}
|
||||
if (!didResizeDuringDragRef.current) {
|
||||
return;
|
||||
}
|
||||
syncHeight(drawerHeightRef.current);
|
||||
setResizeEpoch((value) => value + 1);
|
||||
},
|
||||
[syncHeight],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowResize = () => {
|
||||
const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
|
||||
const changed = clampedHeight !== drawerHeightRef.current;
|
||||
if (changed) {
|
||||
setDrawerHeight(clampedHeight);
|
||||
drawerHeightRef.current = clampedHeight;
|
||||
}
|
||||
if (!resizeStateRef.current) {
|
||||
syncHeight(clampedHeight);
|
||||
}
|
||||
setResizeEpoch((value) => value + 1);
|
||||
};
|
||||
window.addEventListener("resize", onWindowResize);
|
||||
return () => {
|
||||
window.removeEventListener("resize", onWindowResize);
|
||||
};
|
||||
}, [syncHeight]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
syncHeight(drawerHeightRef.current);
|
||||
};
|
||||
}, [syncHeight]);
|
||||
}, [api, cwd, drawerHeight, threadId]);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="thread-terminal-drawer relative flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
className="thread-terminal-drawer flex shrink-0 flex-col border-t border-border/80 bg-background"
|
||||
style={{ height: `${drawerHeight}px` }}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
|
||||
className="flex h-2 cursor-row-resize items-center justify-center"
|
||||
onPointerDown={handleResizePointerDown}
|
||||
onPointerMove={handleResizePointerMove}
|
||||
onPointerUp={handleResizePointerEnd}
|
||||
onPointerCancel={handleResizePointerEnd}
|
||||
/>
|
||||
|
||||
{!hasTerminalSidebar && (
|
||||
<div className="pointer-events-none absolute right-2 top-2 z-20">
|
||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||
<button
|
||||
type="button"
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onSplitTerminal}
|
||||
aria-label="Split Terminal"
|
||||
title="Split Terminal"
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</button>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<button
|
||||
type="button"
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminal}
|
||||
aria-label="New Terminal"
|
||||
title="New Terminal"
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</button>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<button
|
||||
type="button"
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
aria-label="Close Terminal"
|
||||
title="Close Terminal"
|
||||
>
|
||||
<Trash2 className="size-3.25" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-h-0 w-full flex-1">
|
||||
<div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
|
||||
<div className="min-w-0 flex-1">
|
||||
{isSplitView ? (
|
||||
<div
|
||||
className="grid h-full w-full gap-0 overflow-x-auto"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(260px, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{visibleTerminalIds.map((terminalId) => (
|
||||
<div
|
||||
key={terminalId}
|
||||
className={`min-h-0 min-w-0 border-l first:border-l-0 ${
|
||||
terminalId === resolvedActiveTerminalId
|
||||
? "border-border"
|
||||
: "border-border/70"
|
||||
}`}
|
||||
onMouseDown={() => {
|
||||
if (terminalId !== resolvedActiveTerminalId) {
|
||||
onActiveTerminalChange(terminalId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="h-full p-1">
|
||||
<TerminalViewport
|
||||
api={api}
|
||||
threadId={threadId}
|
||||
terminalId={terminalId}
|
||||
cwd={cwd}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus={terminalId === resolvedActiveTerminalId}
|
||||
resizeEpoch={resizeEpoch}
|
||||
drawerHeight={drawerHeight}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full p-1">
|
||||
<TerminalViewport
|
||||
key={resolvedActiveTerminalId}
|
||||
api={api}
|
||||
threadId={threadId}
|
||||
terminalId={resolvedActiveTerminalId}
|
||||
cwd={cwd}
|
||||
focusRequestId={focusRequestId}
|
||||
autoFocus
|
||||
resizeEpoch={resizeEpoch}
|
||||
drawerHeight={drawerHeight}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{hasTerminalSidebar && (
|
||||
<aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
|
||||
<div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
|
||||
<div className="inline-flex h-full items-stretch">
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex h-full items-center px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onSplitTerminal}
|
||||
aria-label="Split Terminal"
|
||||
title="Split Terminal"
|
||||
>
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminal}
|
||||
aria-label="New Terminal"
|
||||
title="New Terminal"
|
||||
>
|
||||
<Plus className="size-3.25" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
|
||||
aria-label="Close Terminal"
|
||||
title="Close Terminal"
|
||||
>
|
||||
<Trash2 className="size-3.25" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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 groupActiveTerminalId = isGroupActive
|
||||
? resolvedActiveTerminalId
|
||||
: (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
|
||||
|
||||
return (
|
||||
<div key={terminalGroup.id} className="pb-0.5">
|
||||
{showGroupHeaders && (
|
||||
<button
|
||||
type="button"
|
||||
className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
|
||||
isGroupActive
|
||||
? "bg-accent/70 text-foreground"
|
||||
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
|
||||
}`}
|
||||
onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
|
||||
>
|
||||
{terminalGroup.terminalIds.length > 1
|
||||
? `Split ${groupIndex + 1}`
|
||||
: `Terminal ${groupIndex + 1}`}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}>
|
||||
{terminalGroup.terminalIds.map((terminalId) => {
|
||||
const isActive = terminalId === resolvedActiveTerminalId;
|
||||
return (
|
||||
<div
|
||||
key={terminalId}
|
||||
className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
|
||||
isActive
|
||||
? "bg-accent text-foreground"
|
||||
: "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{showGroupHeaders && (
|
||||
<span className="text-[10px] text-muted-foreground/80">└</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-1 text-left"
|
||||
onClick={() => onActiveTerminalChange(terminalId)}
|
||||
>
|
||||
<TerminalSquare className="size-3 shrink-0" />
|
||||
<span className="truncate">
|
||||
{terminalLabelById.get(terminalId) ?? "Terminal"}
|
||||
</span>
|
||||
</button>
|
||||
{normalizedTerminalIds.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded px-1 text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onCloseTerminal(terminalId);
|
||||
}}
|
||||
aria-label={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||
title={`Close ${terminalLabelById.get(terminalId) ?? "terminal"}`}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
>
|
||||
<div className="h-px w-10 rounded-full bg-border/80" />
|
||||
</div>
|
||||
<div className="min-h-0 w-full flex-1 px-1.5 pb-1">
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="h-full w-full overflow-hidden rounded-[4px]"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
||||
@@ -91,32 +91,4 @@ describe("buildBootstrapInput", () => {
|
||||
expect(result.omittedCount).toBe(1);
|
||||
expect(result.truncated).toBe(true);
|
||||
});
|
||||
|
||||
it("captures user image attachment context in transcript blocks", () => {
|
||||
const result = buildBootstrapInput(
|
||||
[
|
||||
{
|
||||
id: "u-image",
|
||||
role: "user",
|
||||
text: "",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "screenshot.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 2_048,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-09T00:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
"What does this error mean?",
|
||||
1_500,
|
||||
);
|
||||
|
||||
expect(result.text).toContain("Attached image");
|
||||
expect(result.text).toContain("screenshot.png");
|
||||
});
|
||||
});
|
||||
@@ -18,34 +18,8 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
|
||||
return message.role === "assistant" ? "ASSISTANT" : "USER";
|
||||
}
|
||||
|
||||
function attachmentSummary(message: ChatMessage): string | null {
|
||||
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
|
||||
const count = imageAttachments?.length ?? 0;
|
||||
if (count === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
|
||||
const namesSummary = names.join(", ");
|
||||
const extraCount = count - names.length;
|
||||
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
|
||||
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
|
||||
}
|
||||
|
||||
function buildMessageBlock(message: ChatMessage): string {
|
||||
const text = message.text;
|
||||
const attachments = attachmentSummary(message);
|
||||
|
||||
if (text && attachments) {
|
||||
return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;
|
||||
}
|
||||
if (text) {
|
||||
return `${messageRoleLabel(message)}:\n${text}`;
|
||||
}
|
||||
if (attachments) {
|
||||
return `${messageRoleLabel(message)}:\n${attachments}`;
|
||||
}
|
||||
return `${messageRoleLabel(message)}:\n(empty message)`;
|
||||
return `${messageRoleLabel(message)}:\n${message.text}`;
|
||||
}
|
||||
|
||||
function finalizeWithPrompt(
|
||||
@@ -94,7 +68,7 @@ export function buildBootstrapInput(
|
||||
let includedNewestFirst: string[] = [];
|
||||
for (const block of newestFirstBlocks) {
|
||||
const nextNewestFirst = [...includedNewestFirst, block];
|
||||
const nextChronological = nextNewestFirst.toReversed();
|
||||
const nextChronological = [...nextNewestFirst].reverse();
|
||||
const omittedCount = newestFirstBlocks.length - nextChronological.length;
|
||||
const transcriptBody =
|
||||
omittedCount > 0
|
||||
@@ -106,7 +80,7 @@ export function buildBootstrapInput(
|
||||
includedNewestFirst = nextNewestFirst;
|
||||
}
|
||||
|
||||
let includedChronological = includedNewestFirst.toReversed();
|
||||
let includedChronological = [...includedNewestFirst].reverse();
|
||||
while (true) {
|
||||
const omittedCount = newestFirstBlocks.length - includedChronological.length;
|
||||
const transcriptBody =
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { readNativeApi } from "../session-logic";
|
||||
|
||||
export function useNativeApi() {
|
||||
return useMemo(() => readNativeApi(), []);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_MODEL } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
describe("hydratePersistedState", () => {
|
||||
@@ -50,14 +50,6 @@ describe("hydratePersistedState", () => {
|
||||
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
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]?.messages[0]?.streaming).toBe(false);
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
@@ -100,14 +92,6 @@ describe("hydratePersistedState", () => {
|
||||
expect(hydrated?.threads[0]?.codexThreadId).toBeNull();
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
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?.activeThreadId).toBe("t-1");
|
||||
expect(hydrated?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
@@ -133,7 +117,7 @@ describe("hydratePersistedState", () => {
|
||||
expect(hydrated?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("hydrates terminal fields from legacy v6 payload", () => {
|
||||
it("hydrates terminal fields from v6 payload", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 6,
|
||||
runtimeMode: "full-access",
|
||||
@@ -155,13 +139,8 @@ describe("hydratePersistedState", () => {
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalLayout: "tabs",
|
||||
splitTerminalIds: [],
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
@@ -170,60 +149,6 @@ describe("hydratePersistedState", () => {
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalOpen).toBe(true);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(360);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
|
||||
expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");
|
||||
});
|
||||
|
||||
it("hydrates legacy split layout into a grouped split", () => {
|
||||
const payload = JSON.stringify({
|
||||
version: 6,
|
||||
runtimeMode: "full-access",
|
||||
projects: [
|
||||
{
|
||||
id: "p-1",
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
model: "gpt-5.3-codex",
|
||||
expanded: true,
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: "t-1",
|
||||
codexThreadId: null,
|
||||
projectId: "p-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 360,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalLayout: "split",
|
||||
splitTerminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
messages: [],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
},
|
||||
],
|
||||
activeThreadId: "t-1",
|
||||
});
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalGroupId).toBe(
|
||||
`group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults terminalHeight when hydrating v5 payloads", () => {
|
||||
@@ -256,19 +181,11 @@ describe("hydratePersistedState", () => {
|
||||
|
||||
const hydrated = hydratePersistedState(payload, false);
|
||||
expect(hydrated?.threads[0]?.terminalHeight).toBe(DEFAULT_THREAD_TERMINAL_HEIGHT);
|
||||
expect(hydrated?.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(hydrated?.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
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}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toPersistedState", () => {
|
||||
it("writes v7 payload and strips non-persisted thread fields", () => {
|
||||
it("writes v6 payload and strips non-persisted thread fields", () => {
|
||||
const thread: Thread = {
|
||||
id: "t-1",
|
||||
codexThreadId: "thr_1",
|
||||
@@ -277,29 +194,12 @@ describe("toPersistedState", () => {
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
session: null,
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
previewUrl: "blob:preview-1",
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
@@ -307,7 +207,6 @@ describe("toPersistedState", () => {
|
||||
events: [],
|
||||
error: "boom",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
lastVisitedAt: "2026-02-08T10:02:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
};
|
||||
@@ -327,7 +226,7 @@ describe("toPersistedState", () => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
expect(persisted.version).toBe(7);
|
||||
expect(persisted.version).toBe(6);
|
||||
expect(persisted.runtimeMode).toBe("full-access");
|
||||
expect(persisted.threads[0]).toEqual({
|
||||
id: "t-1",
|
||||
@@ -337,33 +236,8 @@ describe("toPersistedState", () => {
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-2",
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "Hi",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "img-1",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 4_096,
|
||||
},
|
||||
],
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
messages: thread.messages,
|
||||
createdAt: thread.createdAt,
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
});
|
||||
|
||||
@@ -3,12 +3,10 @@ import { z } from "zod";
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
@@ -25,26 +23,10 @@ const persistedMessageSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
role: z.enum(["user", "assistant"]),
|
||||
text: z.string(),
|
||||
attachments: z
|
||||
.array(
|
||||
z.object({
|
||||
type: z.literal("image"),
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().min(1),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
createdAt: z.string().min(1),
|
||||
streaming: z.boolean(),
|
||||
});
|
||||
|
||||
const persistedTerminalGroupSchema = z.object({
|
||||
id: z.string().trim().min(1),
|
||||
terminalIds: z.array(z.string().trim().min(1)),
|
||||
});
|
||||
|
||||
const persistedThreadSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
codexThreadId: z.string().min(1).nullable().default(null),
|
||||
@@ -55,16 +37,8 @@ const persistedThreadSchema = z.object({
|
||||
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([]),
|
||||
activeTerminalGroupId: z.string().trim().min(1).optional(),
|
||||
// Legacy v6 and older fields retained for migration.
|
||||
terminalLayout: z.enum(["single", "split", "tabs"]).optional(),
|
||||
splitTerminalIds: z.array(z.string().trim().min(1)).optional(),
|
||||
messages: z.array(persistedMessageSchema),
|
||||
createdAt: z.string().min(1),
|
||||
lastVisitedAt: z.string().min(1).optional(),
|
||||
branch: z.string().min(1).nullable().optional(),
|
||||
worktreePath: z.string().min(1).nullable().optional(),
|
||||
});
|
||||
@@ -100,18 +74,12 @@ export const persistedStateV6Schema = persistedStateBodySchema.extend({
|
||||
version: z.literal(6).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV7Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(7).optional(),
|
||||
});
|
||||
|
||||
export const persistedStateV5Schema = persistedStateBodySchema.extend({
|
||||
runtimeMode: runtimeModeSchema.default(DEFAULT_RUNTIME_MODE),
|
||||
version: z.literal(5).optional(),
|
||||
});
|
||||
|
||||
const persistedStateSchema = z.union([
|
||||
persistedStateV7Schema,
|
||||
persistedStateV6Schema,
|
||||
persistedStateV5Schema,
|
||||
persistedStateV4Schema,
|
||||
@@ -149,91 +117,6 @@ 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 activeTerminalId = safeTerminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (safeTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const safeTerminalIdSet = new Set(safeTerminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const normalizedGroups: ThreadTerminalGroup[] = [];
|
||||
const assignUniqueGroupId = (groupId: string): string => {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
};
|
||||
|
||||
for (const terminalGroup of thread.terminalGroups) {
|
||||
const nextTerminalIds = [
|
||||
...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
|
||||
].filter((terminalId) => {
|
||||
if (!safeTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (nextTerminalIds.length === 0) continue;
|
||||
for (const terminalId of nextTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
terminalGroup.id.trim().length > 0
|
||||
? terminalGroup.id.trim()
|
||||
: `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(baseGroupId),
|
||||
terminalIds: nextTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
if (normalizedGroups.length === 0 && thread.terminalLayout === "split") {
|
||||
const splitTerminalIds = [
|
||||
...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);
|
||||
for (const terminalId of splitGroupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(`group-${splitGroupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`),
|
||||
terminalIds: splitGroupTerminalIds,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const terminalId of safeTerminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
normalizedGroups.push({
|
||||
id: assignUniqueGroupId(`group-${terminalId}`),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
const activeGroupIndexFromId = normalizedGroups.findIndex(
|
||||
(terminalGroup) => terminalGroup.id === thread.activeTerminalGroupId,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = normalizedGroups.findIndex((terminalGroup) =>
|
||||
terminalGroup.terminalIds.includes(activeTerminalId),
|
||||
);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
|
||||
const activeTerminalGroupId =
|
||||
normalizedGroups[activeGroupIndex]?.id ??
|
||||
normalizedGroups[0]?.id ??
|
||||
`group-${DEFAULT_THREAD_TERMINAL_ID}`;
|
||||
|
||||
return {
|
||||
id: thread.id,
|
||||
codexThreadId: thread.codexThreadId,
|
||||
@@ -242,28 +125,14 @@ function hydrateThread(
|
||||
model: resolveModelSlug(maybeMigrateLegacyModel(thread.model, isLegacyPayload)),
|
||||
terminalOpen: thread.terminalOpen ?? false,
|
||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: safeTerminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups: normalizedGroups,
|
||||
activeTerminalGroupId,
|
||||
session: null,
|
||||
messages: thread.messages.map((message) => {
|
||||
const hydratedAttachments = message.attachments?.map((attachment) => ({ ...attachment }));
|
||||
return {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(hydratedAttachments && hydratedAttachments.length > 0
|
||||
? { attachments: hydratedAttachments }
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: false,
|
||||
};
|
||||
}),
|
||||
messages: thread.messages.map((message) => ({
|
||||
...message,
|
||||
streaming: false,
|
||||
})),
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: thread.createdAt,
|
||||
lastVisitedAt: thread.lastVisitedAt,
|
||||
branch: thread.branch ?? null,
|
||||
worktreePath: thread.worktreePath ?? null,
|
||||
};
|
||||
@@ -308,9 +177,9 @@ export function hydratePersistedState(
|
||||
|
||||
export function toPersistedState(
|
||||
state: PersistedStoreSnapshot,
|
||||
): z.infer<typeof persistedStateV7Schema> {
|
||||
): z.infer<typeof persistedStateV6Schema> {
|
||||
return {
|
||||
version: 7,
|
||||
version: 6,
|
||||
projects: state.projects,
|
||||
threads: state.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
@@ -320,30 +189,8 @@ export function toPersistedState(
|
||||
model: thread.model,
|
||||
terminalOpen: thread.terminalOpen,
|
||||
terminalHeight: thread.terminalHeight,
|
||||
terminalIds: thread.terminalIds,
|
||||
activeTerminalId: thread.activeTerminalId,
|
||||
terminalGroups: thread.terminalGroups,
|
||||
activeTerminalGroupId: thread.activeTerminalGroupId,
|
||||
messages: thread.messages.map((message) => ({
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
...(message.attachments && message.attachments.length > 0
|
||||
? {
|
||||
attachments: message.attachments.map((attachment) => ({
|
||||
type: attachment.type,
|
||||
id: attachment.id,
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
createdAt: message.createdAt,
|
||||
streaming: message.streaming,
|
||||
})),
|
||||
messages: thread.messages,
|
||||
createdAt: thread.createdAt,
|
||||
...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
})),
|
||||
|
||||
@@ -4,7 +4,6 @@ import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
derivePendingApprovals,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
@@ -393,73 +392,6 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("derivePendingApprovals", () => {
|
||||
it("returns pending command/file-change approvals", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
makeEvent({
|
||||
id: "evt-request",
|
||||
kind: "request",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "req-1",
|
||||
requestKind: "command",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: { command: "git commit -m 'msg'" },
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(approvals).toEqual([
|
||||
{
|
||||
requestId: "req-1",
|
||||
requestKind: "command",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
detail: "git commit -m 'msg'",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("removes approvals after a decision event", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
makeEvent({
|
||||
id: "evt-decision",
|
||||
method: "item/requestApproval/decision",
|
||||
requestId: "req-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-request",
|
||||
kind: "request",
|
||||
method: "item/fileChange/requestApproval",
|
||||
requestId: "req-1",
|
||||
requestKind: "file-change",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(approvals).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("clears pending approvals after turn completion", () => {
|
||||
const approvals = derivePendingApprovals([
|
||||
makeEvent({
|
||||
id: "evt-turn-complete",
|
||||
method: "turn/completed",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-request",
|
||||
kind: "request",
|
||||
method: "item/commandExecution/requestApproval",
|
||||
requestId: "req-1",
|
||||
requestKind: "command",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(approvals).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evolveSession", () => {
|
||||
it("updates thread id when thread starts", () => {
|
||||
const previous = makeSession();
|
||||
|
||||
@@ -78,13 +78,6 @@ export interface WorkLogEntry {
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
}
|
||||
|
||||
export interface PendingApproval {
|
||||
requestId: string;
|
||||
requestKind: "command" | "file-change";
|
||||
createdAt: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export type TimelineEntry =
|
||||
| {
|
||||
id: string;
|
||||
@@ -105,52 +98,6 @@ function normalizeDetail(value: string | undefined): string | undefined {
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function approvalDetail(event: ProviderEvent): string | undefined {
|
||||
const payload = asObject(event.payload);
|
||||
const command = asString(payload?.command);
|
||||
if (command) return command;
|
||||
return asString(payload?.reason);
|
||||
}
|
||||
|
||||
export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {
|
||||
const pending = new Map<string, PendingApproval>();
|
||||
const ordered = [...events].toReversed();
|
||||
|
||||
for (const event of ordered) {
|
||||
if (
|
||||
event.method === "session/closed" ||
|
||||
event.method === "session/exited" ||
|
||||
event.method === "turn/completed"
|
||||
) {
|
||||
pending.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);
|
||||
if (!requestId) continue;
|
||||
|
||||
if (
|
||||
event.kind === "request" &&
|
||||
(event.requestKind === "command" || event.requestKind === "file-change")
|
||||
) {
|
||||
const detail = approvalDetail(event);
|
||||
pending.set(requestId, {
|
||||
requestId,
|
||||
requestKind: event.requestKind,
|
||||
createdAt: event.createdAt,
|
||||
...(detail ? { detail } : {}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.method === "item/requestApproval/decision") {
|
||||
pending.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(pending.values());
|
||||
}
|
||||
|
||||
function normalizeItemType(raw: string | undefined): string {
|
||||
if (!raw) return "item";
|
||||
return raw
|
||||
|
||||
+1
-208
@@ -2,7 +2,7 @@ import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { type AppState, reducer } from "./store";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID } from "./types";
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT } from "./types";
|
||||
import type { Thread } from "./types";
|
||||
|
||||
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||
@@ -37,15 +37,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: makeSession(),
|
||||
messages: [],
|
||||
events: [],
|
||||
@@ -120,160 +111,6 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.terminalHeight).toBe(360);
|
||||
});
|
||||
|
||||
it("splits the active terminal into side-by-side mode", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("creates a new full-width terminal and switches to tab mode", () => {
|
||||
const state = makeState(makeThread());
|
||||
const next = reducer(state, {
|
||||
type: "NEW_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-2", terminalIds: ["term-2"] },
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe("group-term-2");
|
||||
});
|
||||
|
||||
it("switches the active terminal and restores its owning group", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
],
|
||||
activeTerminalGroupId: "group-term-3",
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SET_THREAD_ACTIVE_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-2");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("supports splitting beyond two terminals in the same group", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "SPLIT_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "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}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
},
|
||||
]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe("term-3");
|
||||
expect(next.threads[0]?.activeTerminalGroupId).toBe(`group-${DEFAULT_THREAD_TERMINAL_ID}`);
|
||||
});
|
||||
|
||||
it("closes a terminal and keeps grouped layout coherent", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: "term-2",
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
{ id: "group-term-3", terminalIds: ["term-3"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the final terminal and hides the drawer", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalOpen: true,
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("backfills codexThreadId from routed provider events", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: null }));
|
||||
const next = reducer(state, {
|
||||
@@ -382,48 +219,4 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.projectId).toBe("project-new-a");
|
||||
expect(next.activeThreadId).toBe("thread-a");
|
||||
});
|
||||
|
||||
it("marks the active thread as visited when selected", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
lastVisitedAt: "2000-01-01T00:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "SET_ACTIVE_THREAD",
|
||||
threadId: "thread-local-1",
|
||||
});
|
||||
|
||||
expect(next.activeThreadId).toBe("thread-local-1");
|
||||
expect(next.threads[0]?.lastVisitedAt).toBeDefined();
|
||||
expect(next.threads[0]?.lastVisitedAt).not.toBe("2000-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("marks completion as seen immediately for the active thread", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
session: makeSession({
|
||||
status: "running",
|
||||
activeTurnId: "turn-1",
|
||||
}),
|
||||
lastVisitedAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const completedAt = "2026-02-08T10:00:10.000Z";
|
||||
const next = reducer(state, {
|
||||
type: "APPLY_EVENT",
|
||||
event: makeEvent({
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: completedAt,
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
activeAssistantItemRef: { current: null },
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
|
||||
});
|
||||
});
|
||||
+14
-346
@@ -13,13 +13,10 @@ import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
import {
|
||||
type ChatAttachment,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type RuntimeMode,
|
||||
type Thread,
|
||||
type ThreadTerminalGroup,
|
||||
} from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
@@ -33,10 +30,6 @@ type Action =
|
||||
| { type: "TOGGLE_THREAD_TERMINAL"; threadId: string }
|
||||
| { type: "SET_THREAD_TERMINAL_OPEN"; threadId: string; open: boolean }
|
||||
| { type: "SET_THREAD_TERMINAL_HEIGHT"; threadId: string; height: number }
|
||||
| { type: "SPLIT_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "NEW_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "SET_THREAD_ACTIVE_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "CLOSE_THREAD_TERMINAL"; threadId: string; terminalId: string }
|
||||
| { type: "TOGGLE_DIFF" }
|
||||
| {
|
||||
type: "APPLY_EVENT";
|
||||
@@ -44,13 +37,7 @@ type Action =
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
}
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| {
|
||||
type: "PUSH_USER_MESSAGE";
|
||||
threadId: string;
|
||||
id: string;
|
||||
text: string;
|
||||
attachments?: ChatAttachment[];
|
||||
}
|
||||
| { type: "PUSH_USER_MESSAGE"; threadId: string; id: string; text: string }
|
||||
| { type: "SET_ERROR"; threadId: string; error: string | null }
|
||||
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
|
||||
@@ -73,9 +60,8 @@ export interface AppState {
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v7";
|
||||
const PERSISTED_STATE_KEY = "t3code:renderer-state:v6";
|
||||
const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
"t3code:renderer-state:v6",
|
||||
"t3code:renderer-state:v5",
|
||||
"t3code:renderer-state:v4",
|
||||
"t3code:renderer-state:v3",
|
||||
@@ -140,180 +126,6 @@ function updateThread(
|
||||
return threads.map((t) => (t.id === threadId ? updater(t) : t));
|
||||
}
|
||||
|
||||
function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
const ids = terminalIds.map((id) => id.trim()).filter((id) => id.length > 0);
|
||||
const unique = [...new Set(ids)];
|
||||
if (unique.length > 0) {
|
||||
return unique;
|
||||
}
|
||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
|
||||
function fallbackGroupId(terminalId: string): string {
|
||||
return `group-${terminalId}`;
|
||||
}
|
||||
|
||||
function assignUniqueGroupId(groupId: string, usedGroupIds: Set<string>): string {
|
||||
if (!usedGroupIds.has(groupId)) {
|
||||
usedGroupIds.add(groupId);
|
||||
return groupId;
|
||||
}
|
||||
let suffix = 2;
|
||||
while (usedGroupIds.has(`${groupId}-${suffix}`)) {
|
||||
suffix += 1;
|
||||
}
|
||||
const uniqueGroupId = `${groupId}-${suffix}`;
|
||||
usedGroupIds.add(uniqueGroupId);
|
||||
return uniqueGroupId;
|
||||
}
|
||||
|
||||
function normalizeTerminalGroups(
|
||||
thread: Thread,
|
||||
terminalIds: string[],
|
||||
): ThreadTerminalGroup[] {
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
const assignedTerminalIds = new Set<string>();
|
||||
const usedGroupIds = new Set<string>();
|
||||
const groups: ThreadTerminalGroup[] = [];
|
||||
|
||||
for (const group of thread.terminalGroups) {
|
||||
const groupTerminalIds = normalizeTerminalGroupIds(group.terminalIds).filter((terminalId) => {
|
||||
if (!validTerminalIdSet.has(terminalId)) return false;
|
||||
if (assignedTerminalIds.has(terminalId)) return false;
|
||||
return true;
|
||||
});
|
||||
if (groupTerminalIds.length === 0) continue;
|
||||
for (const terminalId of groupTerminalIds) {
|
||||
assignedTerminalIds.add(terminalId);
|
||||
}
|
||||
const baseGroupId =
|
||||
group.id.trim().length > 0
|
||||
? group.id.trim()
|
||||
: fallbackGroupId(groupTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(baseGroupId, usedGroupIds),
|
||||
terminalIds: groupTerminalIds,
|
||||
});
|
||||
}
|
||||
|
||||
for (const terminalId of terminalIds) {
|
||||
if (assignedTerminalIds.has(terminalId)) continue;
|
||||
groups.push({
|
||||
id: assignUniqueGroupId(fallbackGroupId(terminalId), usedGroupIds),
|
||||
terminalIds: [terminalId],
|
||||
});
|
||||
}
|
||||
|
||||
if (groups.length > 0) {
|
||||
return groups;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function findGroupIndexByTerminalId(
|
||||
terminalGroups: ThreadTerminalGroup[],
|
||||
terminalId: string,
|
||||
): number {
|
||||
return terminalGroups.findIndex((group) => group.terminalIds.includes(terminalId));
|
||||
}
|
||||
|
||||
function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
const terminalIds = normalizeTerminalIds(thread.terminalIds);
|
||||
const activeTerminalId = terminalIds.includes(thread.activeTerminalId)
|
||||
? thread.activeTerminalId
|
||||
: (terminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
|
||||
const terminalGroups = normalizeTerminalGroups(thread, terminalIds);
|
||||
const activeGroupIndexFromId = terminalGroups.findIndex(
|
||||
(group) => group.id === thread.activeTerminalGroupId,
|
||||
);
|
||||
const activeGroupIndexFromTerminal = findGroupIndexByTerminalId(
|
||||
terminalGroups,
|
||||
activeTerminalId,
|
||||
);
|
||||
const activeGroupIndex =
|
||||
activeGroupIndexFromId >= 0
|
||||
? activeGroupIndexFromId
|
||||
: (activeGroupIndexFromTerminal >= 0 ? activeGroupIndexFromTerminal : 0);
|
||||
const activeTerminalGroupId =
|
||||
terminalGroups[activeGroupIndex]?.id ??
|
||||
terminalGroups[0]?.id ??
|
||||
fallbackGroupId(activeTerminalId);
|
||||
|
||||
return {
|
||||
...thread,
|
||||
terminalIds,
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
};
|
||||
}
|
||||
|
||||
function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
if (!thread.terminalIds.includes(terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
|
||||
const remainingTerminalIds = thread.terminalIds.filter((id) => id !== terminalId);
|
||||
if (remainingTerminalIds.length === 0) {
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: fallbackGroupId(DEFAULT_THREAD_TERMINAL_ID),
|
||||
});
|
||||
}
|
||||
|
||||
const closedTerminalIndex = thread.terminalIds.indexOf(terminalId);
|
||||
const closedTerminalGroup = thread.terminalGroups.find((group) =>
|
||||
group.terminalIds.includes(terminalId),
|
||||
);
|
||||
const closedTerminalGroupIndex = closedTerminalGroup
|
||||
? closedTerminalGroup.terminalIds.indexOf(terminalId)
|
||||
: -1;
|
||||
const remainingTerminalsInClosedGroup = (
|
||||
closedTerminalGroup?.terminalIds ?? []
|
||||
).filter((id) => id !== terminalId);
|
||||
const nextActiveTerminalId =
|
||||
thread.activeTerminalId === terminalId
|
||||
? (remainingTerminalsInClosedGroup[
|
||||
Math.min(closedTerminalGroupIndex, remainingTerminalsInClosedGroup.length - 1)
|
||||
] ??
|
||||
remainingTerminalIds[Math.min(closedTerminalIndex, remainingTerminalIds.length - 1)] ??
|
||||
remainingTerminalIds[0] ??
|
||||
DEFAULT_THREAD_TERMINAL_ID)
|
||||
: thread.activeTerminalId;
|
||||
const nextTerminalGroups = thread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
});
|
||||
}
|
||||
|
||||
function findThreadBySessionId(threads: Thread[], sessionId: string): Thread | undefined {
|
||||
return threads.find((t) => t.session?.sessionId === sessionId);
|
||||
}
|
||||
@@ -440,10 +252,10 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
if (!previousProject) return null;
|
||||
const mappedProjectId = nextProjectIdByCwd.get(previousProject.cwd);
|
||||
if (!mappedProjectId) return null;
|
||||
return normalizeThreadTerminals({
|
||||
return {
|
||||
...thread,
|
||||
projectId: mappedProjectId,
|
||||
});
|
||||
};
|
||||
})
|
||||
.filter((thread): thread is Thread => thread !== null);
|
||||
const activeThreadId = nextThreads.some((thread) => thread.id === state.activeThreadId)
|
||||
@@ -466,30 +278,21 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
),
|
||||
};
|
||||
|
||||
case "ADD_THREAD": {
|
||||
const nextThread = normalizeThreadTerminals({
|
||||
...action.thread,
|
||||
model: resolveModelSlug(action.thread.model),
|
||||
lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,
|
||||
});
|
||||
case "ADD_THREAD":
|
||||
return {
|
||||
...state,
|
||||
threads: [...state.threads, nextThread],
|
||||
threads: [
|
||||
...state.threads,
|
||||
{
|
||||
...action.thread,
|
||||
model: resolveModelSlug(action.thread.model),
|
||||
},
|
||||
],
|
||||
activeThreadId: action.thread.id,
|
||||
};
|
||||
}
|
||||
|
||||
case "SET_ACTIVE_THREAD": {
|
||||
const visitedAt = new Date().toISOString();
|
||||
return {
|
||||
...state,
|
||||
activeThreadId: action.threadId,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
lastVisitedAt: visitedAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
case "SET_ACTIVE_THREAD":
|
||||
return { ...state, activeThreadId: action.threadId };
|
||||
|
||||
case "TOGGLE_THREAD_TERMINAL":
|
||||
return {
|
||||
@@ -518,135 +321,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
})),
|
||||
};
|
||||
|
||||
case "SPLIT_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups.map((group) => ({
|
||||
...group,
|
||||
terminalIds: [...group.terminalIds],
|
||||
}));
|
||||
let activeGroupIndex = terminalGroups.findIndex(
|
||||
(group) => group.id === normalizedThread.activeTerminalGroupId,
|
||||
);
|
||||
if (activeGroupIndex < 0) {
|
||||
activeGroupIndex = findGroupIndexByTerminalId(
|
||||
terminalGroups,
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
}
|
||||
if (activeGroupIndex < 0) {
|
||||
terminalGroups.push({
|
||||
id: fallbackGroupId(normalizedThread.activeTerminalId),
|
||||
terminalIds: [normalizedThread.activeTerminalId],
|
||||
});
|
||||
activeGroupIndex = terminalGroups.length - 1;
|
||||
}
|
||||
|
||||
const existingGroupIndex = findGroupIndexByTerminalId(
|
||||
terminalGroups,
|
||||
action.terminalId,
|
||||
);
|
||||
if (existingGroupIndex >= 0) {
|
||||
terminalGroups[existingGroupIndex]!.terminalIds = terminalGroups[
|
||||
existingGroupIndex
|
||||
]!.terminalIds.filter((id) => id !== action.terminalId);
|
||||
if (terminalGroups[existingGroupIndex]!.terminalIds.length === 0) {
|
||||
terminalGroups.splice(existingGroupIndex, 1);
|
||||
if (existingGroupIndex < activeGroupIndex) {
|
||||
activeGroupIndex -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const destinationGroup = terminalGroups[activeGroupIndex];
|
||||
if (!destinationGroup) {
|
||||
return normalizedThread;
|
||||
}
|
||||
if (!destinationGroup.terminalIds.includes(action.terminalId)) {
|
||||
const anchorIndex = destinationGroup.terminalIds.indexOf(
|
||||
normalizedThread.activeTerminalId,
|
||||
);
|
||||
if (anchorIndex >= 0) {
|
||||
destinationGroup.terminalIds.splice(anchorIndex + 1, 0, action.terminalId);
|
||||
} else {
|
||||
destinationGroup.terminalIds.push(action.terminalId);
|
||||
}
|
||||
}
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: destinationGroup.id,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "NEW_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const terminalIds = normalizedThread.terminalIds.includes(action.terminalId)
|
||||
? normalizedThread.terminalIds
|
||||
: [...normalizedThread.terminalIds, action.terminalId];
|
||||
const terminalGroups = normalizedThread.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== action.terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
const nextGroupId = fallbackGroupId(action.terminalId);
|
||||
terminalGroups.push({ id: nextGroupId, terminalIds: [action.terminalId] });
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
terminalIds,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId: nextGroupId,
|
||||
terminalGroups,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_ACTIVE_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
if (!normalizedThread.terminalIds.includes(action.terminalId)) {
|
||||
return thread;
|
||||
}
|
||||
const nextActiveGroupIndex = findGroupIndexByTerminalId(
|
||||
normalizedThread.terminalGroups,
|
||||
action.terminalId,
|
||||
);
|
||||
const activeTerminalGroupId =
|
||||
nextActiveGroupIndex >= 0
|
||||
? (normalizedThread.terminalGroups[nextActiveGroupIndex]?.id ??
|
||||
normalizedThread.activeTerminalGroupId)
|
||||
: normalizedThread.activeTerminalGroupId;
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
activeTerminalId: action.terminalId,
|
||||
activeTerminalGroupId,
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "CLOSE_THREAD_TERMINAL":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (thread) =>
|
||||
closeThreadTerminal(thread, action.terminalId),
|
||||
),
|
||||
};
|
||||
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
@@ -675,9 +349,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),
|
||||
events: [event, ...t.events],
|
||||
...updateTurnFields(t, event),
|
||||
...(event.method === "turn/completed" && t.id === state.activeThreadId
|
||||
? { lastVisitedAt: event.createdAt }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -709,9 +380,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
id: action.id,
|
||||
role: "user" as const,
|
||||
text: action.text,
|
||||
...(action.attachments && action.attachments.length > 0
|
||||
? { attachments: action.attachments }
|
||||
: {}),
|
||||
createdAt: new Date().toISOString(),
|
||||
streaming: false,
|
||||
},
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
extractTerminalLinks,
|
||||
isTerminalLinkActivation,
|
||||
resolvePathLinkTarget,
|
||||
} from "./terminal-links";
|
||||
|
||||
describe("extractTerminalLinks", () => {
|
||||
it("finds http urls and path tokens", () => {
|
||||
const line =
|
||||
"failed at https://example.com/docs and src/components/ThreadTerminalDrawer.tsx:42";
|
||||
expect(extractTerminalLinks(line)).toEqual([
|
||||
{
|
||||
kind: "url",
|
||||
text: "https://example.com/docs",
|
||||
start: 10,
|
||||
end: 34,
|
||||
},
|
||||
{
|
||||
kind: "path",
|
||||
text: "src/components/ThreadTerminalDrawer.tsx:42",
|
||||
start: 39,
|
||||
end: 81,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("trims trailing punctuation from links", () => {
|
||||
const line = "(https://example.com/docs), ./src/main.ts:12.";
|
||||
expect(extractTerminalLinks(line)).toEqual([
|
||||
{
|
||||
kind: "url",
|
||||
text: "https://example.com/docs",
|
||||
start: 1,
|
||||
end: 25,
|
||||
},
|
||||
{
|
||||
kind: "path",
|
||||
text: "./src/main.ts:12",
|
||||
start: 28,
|
||||
end: 44,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePathLinkTarget", () => {
|
||||
it("resolves relative paths against cwd", () => {
|
||||
expect(
|
||||
resolvePathLinkTarget(
|
||||
"src/components/ThreadTerminalDrawer.tsx:42:7",
|
||||
"/Users/julius/project",
|
||||
),
|
||||
).toBe("/Users/julius/project/src/components/ThreadTerminalDrawer.tsx:42:7");
|
||||
});
|
||||
|
||||
it("keeps absolute paths unchanged", () => {
|
||||
expect(
|
||||
resolvePathLinkTarget(
|
||||
"/Users/julius/project/src/main.ts:12",
|
||||
"/Users/julius/project",
|
||||
),
|
||||
).toBe("/Users/julius/project/src/main.ts:12");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalLinkActivation", () => {
|
||||
it("requires cmd on macOS", () => {
|
||||
expect(
|
||||
isTerminalLinkActivation(
|
||||
{
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
},
|
||||
"MacIntel",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTerminalLinkActivation(
|
||||
{
|
||||
metaKey: false,
|
||||
ctrlKey: true,
|
||||
},
|
||||
"MacIntel",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("requires ctrl on non-macOS", () => {
|
||||
expect(
|
||||
isTerminalLinkActivation(
|
||||
{
|
||||
metaKey: false,
|
||||
ctrlKey: true,
|
||||
},
|
||||
"Win32",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTerminalLinkActivation(
|
||||
{
|
||||
metaKey: true,
|
||||
ctrlKey: false,
|
||||
},
|
||||
"Linux",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,200 +0,0 @@
|
||||
import { EDITORS, type EditorId } from "@t3tools/contracts";
|
||||
|
||||
export type TerminalLinkKind = "url" | "path";
|
||||
|
||||
export interface TerminalLinkMatch {
|
||||
kind: TerminalLinkKind;
|
||||
text: string;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
|
||||
const FILE_PATH_PATTERN =
|
||||
/(?:~\/|\.{1,2}\/|\/|[A-Za-z]:\\|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
|
||||
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
|
||||
const LAST_EDITOR_KEY = "t3code:last-editor";
|
||||
|
||||
function isMacPlatform(platform: string): boolean {
|
||||
return /mac|iphone|ipad|ipod/i.test(platform);
|
||||
}
|
||||
|
||||
function trimClosingDelimiters(value: string): string {
|
||||
let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
|
||||
if (output.length === 0) return output;
|
||||
|
||||
const trimUnbalanced = (open: string, close: string) => {
|
||||
while (output.endsWith(close)) {
|
||||
const opens = output.split(open).length - 1;
|
||||
const closes = output.split(close).length - 1;
|
||||
if (opens >= closes) return;
|
||||
output = output.slice(0, -1);
|
||||
}
|
||||
};
|
||||
|
||||
trimUnbalanced("(", ")");
|
||||
trimUnbalanced("[", "]");
|
||||
trimUnbalanced("{", "}");
|
||||
return output;
|
||||
}
|
||||
|
||||
function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
|
||||
return a.start < b.end && b.start < a.end;
|
||||
}
|
||||
|
||||
function collectMatches(
|
||||
line: string,
|
||||
kind: TerminalLinkKind,
|
||||
pattern: RegExp,
|
||||
existing: TerminalLinkMatch[],
|
||||
): TerminalLinkMatch[] {
|
||||
const matches: TerminalLinkMatch[] = [];
|
||||
pattern.lastIndex = 0;
|
||||
|
||||
for (const rawMatch of line.matchAll(pattern)) {
|
||||
const raw = rawMatch[0];
|
||||
const start = rawMatch.index ?? -1;
|
||||
if (start < 0 || raw.length === 0) continue;
|
||||
|
||||
const trimmed = trimClosingDelimiters(raw);
|
||||
if (trimmed.length === 0) continue;
|
||||
if (kind === "path" && /^https?:\/\//i.test(trimmed)) continue;
|
||||
|
||||
const candidate: TerminalLinkMatch = {
|
||||
kind,
|
||||
text: trimmed,
|
||||
start,
|
||||
end: start + trimmed.length,
|
||||
};
|
||||
|
||||
const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
|
||||
if (collides) continue;
|
||||
|
||||
matches.push(candidate);
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
function isWindowsAbsolutePath(value: string): boolean {
|
||||
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
|
||||
}
|
||||
|
||||
function isAbsolutePath(value: string): boolean {
|
||||
return value.startsWith("/") || isWindowsAbsolutePath(value);
|
||||
}
|
||||
|
||||
function isWindowsPathStyle(value: string): boolean {
|
||||
return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
|
||||
}
|
||||
|
||||
function joinPath(base: string, next: string, separator: "/" | "\\"): string {
|
||||
const cleanBase = base.replace(/[\\/]+$/, "");
|
||||
if (separator === "\\") {
|
||||
return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
|
||||
}
|
||||
return `${cleanBase}/${next.replace(/^\/+/, "")}`;
|
||||
}
|
||||
|
||||
function inferHomeFromCwd(cwd: string): string | undefined {
|
||||
const posixUser = cwd.match(/^\/Users\/([^/]+)/);
|
||||
if (posixUser?.[1]) {
|
||||
return `/Users/${posixUser[1]}`;
|
||||
}
|
||||
|
||||
const posixHome = cwd.match(/^\/home\/([^/]+)/);
|
||||
if (posixHome?.[1]) {
|
||||
return `/home/${posixHome[1]}`;
|
||||
}
|
||||
|
||||
const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
|
||||
if (windowsUser?.[1]) {
|
||||
return windowsUser[1];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function splitPathAndPosition(value: string): {
|
||||
path: string;
|
||||
line: string | undefined;
|
||||
column: string | undefined;
|
||||
} {
|
||||
let path = value;
|
||||
let column: string | undefined;
|
||||
let line: string | undefined;
|
||||
|
||||
const columnMatch = path.match(/:(\d+)$/);
|
||||
if (!columnMatch?.[1]) {
|
||||
return { path, line: undefined, column: undefined };
|
||||
}
|
||||
|
||||
column = columnMatch[1];
|
||||
path = path.slice(0, -columnMatch[0].length);
|
||||
|
||||
const lineMatch = path.match(/:(\d+)$/);
|
||||
if (lineMatch?.[1]) {
|
||||
line = lineMatch[1];
|
||||
path = path.slice(0, -lineMatch[0].length);
|
||||
} else {
|
||||
line = column;
|
||||
column = undefined;
|
||||
}
|
||||
|
||||
return { path, line, column };
|
||||
}
|
||||
|
||||
export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
|
||||
const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
|
||||
const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
|
||||
return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
|
||||
}
|
||||
|
||||
export function isTerminalLinkActivation(
|
||||
event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
|
||||
platform = typeof navigator === "undefined" ? "" : navigator.platform,
|
||||
): boolean {
|
||||
if (platform.length === 0) return false;
|
||||
return isMacPlatform(platform)
|
||||
? event.metaKey && !event.ctrlKey
|
||||
: event.ctrlKey && !event.metaKey;
|
||||
}
|
||||
|
||||
export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
|
||||
const { path, line, column } = splitPathAndPosition(rawPath);
|
||||
|
||||
let resolvedPath = path;
|
||||
if (path.startsWith("~/")) {
|
||||
const home = inferHomeFromCwd(cwd);
|
||||
if (home) {
|
||||
const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
|
||||
resolvedPath = joinPath(home, path.slice(2), separator);
|
||||
}
|
||||
} else if (!isAbsolutePath(path)) {
|
||||
const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
|
||||
resolvedPath = joinPath(cwd, path, separator);
|
||||
}
|
||||
|
||||
if (!line) return resolvedPath;
|
||||
return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
|
||||
}
|
||||
|
||||
export function preferredTerminalEditor(): EditorId {
|
||||
const fallback = EDITORS.find((editor) => editor.command)?.id ?? EDITORS[0]?.id ?? "cursor";
|
||||
|
||||
if (typeof window === "undefined") {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const storedEditor = window.localStorage.getItem(LAST_EDITOR_KEY);
|
||||
if (!storedEditor) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const configured = EDITORS.find((editor) => editor.id === storedEditor);
|
||||
if (!configured?.command) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return configured.id;
|
||||
}
|
||||
@@ -4,29 +4,11 @@ export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
export type RuntimeMode = "approval-required" | "full-access";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
|
||||
export const DEFAULT_THREAD_TERMINAL_ID = "default";
|
||||
|
||||
export interface ThreadTerminalGroup {
|
||||
id: string;
|
||||
terminalIds: string[];
|
||||
}
|
||||
|
||||
export interface ChatImageAttachment {
|
||||
type: "image";
|
||||
id: string;
|
||||
name: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
previewUrl?: string;
|
||||
}
|
||||
|
||||
export type ChatAttachment = ChatImageAttachment;
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
text: string;
|
||||
attachments?: ChatAttachment[];
|
||||
createdAt: string;
|
||||
streaming: boolean;
|
||||
}
|
||||
@@ -47,10 +29,6 @@ export interface Thread {
|
||||
model: string;
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
session: ProviderSession | null;
|
||||
messages: ChatMessage[];
|
||||
events: ProviderEvent[];
|
||||
@@ -60,7 +38,6 @@ export interface Thread {
|
||||
latestTurnStartedAt?: string | undefined;
|
||||
latestTurnCompletedAt?: string | undefined;
|
||||
latestTurnDurationMs?: number | undefined;
|
||||
lastVisitedAt?: string | undefined;
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}
|
||||
Vendored
-1
@@ -6,7 +6,6 @@ interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
|
||||
openExternal: (url: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -96,24 +96,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
|
||||
openExternal: async (url) => {
|
||||
if (window.desktopBridge) {
|
||||
const opened = await window.desktopBridge.openExternal(url);
|
||||
if (!opened) {
|
||||
throw new Error("Unable to open link.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const popup = window.open(url, "_blank", "noopener,noreferrer");
|
||||
if (!popup) {
|
||||
throw new Error("Unable to open link. Allow popups and try again.");
|
||||
}
|
||||
},
|
||||
},
|
||||
git: {
|
||||
status: (input) => transport.request(WS_METHODS.gitStatus, input),
|
||||
runStackedAction: (input) => transport.request(WS_METHODS.gitRunStackedAction, input),
|
||||
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
|
||||
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
|
||||
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
gitRunStackedActionInputSchema,
|
||||
gitRunStackedActionResultSchema,
|
||||
gitStackedActionSchema,
|
||||
gitStatusInputSchema,
|
||||
gitStatusResultSchema,
|
||||
} from "./git";
|
||||
|
||||
describe("git contracts", () => {
|
||||
it("parses git status input and trims cwd", () => {
|
||||
const parsed = gitStatusInputSchema.parse({ cwd: " /tmp/repo " });
|
||||
expect(parsed.cwd).toBe("/tmp/repo");
|
||||
});
|
||||
|
||||
it("parses git status result", () => {
|
||||
const parsed = gitStatusResultSchema.parse({
|
||||
branch: "feature/git-actions",
|
||||
hasWorkingTreeChanges: true,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
openPr: null,
|
||||
});
|
||||
expect(parsed.branch).toBe("feature/git-actions");
|
||||
expect(parsed.hasWorkingTreeChanges).toBe(true);
|
||||
});
|
||||
|
||||
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",
|
||||
);
|
||||
});
|
||||
|
||||
it("parses stacked action input", () => {
|
||||
const parsed = gitRunStackedActionInputSchema.parse({
|
||||
cwd: "/tmp/repo",
|
||||
action: "commit_push",
|
||||
});
|
||||
expect(parsed.action).toBe("commit_push");
|
||||
});
|
||||
|
||||
it("accepts custom commit message input", () => {
|
||||
const parsed = gitRunStackedActionInputSchema.parse({
|
||||
cwd: "/tmp/repo",
|
||||
action: "commit",
|
||||
commitMessage: " chore: update git action modal ",
|
||||
});
|
||||
expect(parsed.commitMessage).toBe("chore: update git action modal");
|
||||
});
|
||||
|
||||
it("parses stacked action result with metadata", () => {
|
||||
const parsed = gitRunStackedActionResultSchema.parse({
|
||||
action: "commit_push_pr",
|
||||
commit: {
|
||||
status: "created",
|
||||
commitSha: "abc123",
|
||||
subject: "Implement stacked git actions",
|
||||
},
|
||||
push: {
|
||||
status: "pushed",
|
||||
branch: "feature/git-actions",
|
||||
upstreamBranch: "origin/feature/git-actions",
|
||||
setUpstream: true,
|
||||
},
|
||||
pr: {
|
||||
status: "created",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/123",
|
||||
number: 123,
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/git-actions",
|
||||
title: "Add stacked git actions workflow",
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.commit.status).toBe("created");
|
||||
expect(parsed.pr.number).toBe(123);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── Existing branch/worktree Git API ─────────────────────────────────
|
||||
// ── Input schemas ──
|
||||
|
||||
export const gitListBranchesInputSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
@@ -8,7 +8,9 @@ export const gitListBranchesInputSchema = z.object({
|
||||
|
||||
export const gitCreateWorktreeInputSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
/** Base branch to create the worktree from. */
|
||||
branch: z.string().min(1),
|
||||
/** New branch name to create in the worktree. */
|
||||
newBranch: z.string().min(1),
|
||||
path: z.string().min(1).optional(),
|
||||
});
|
||||
@@ -32,6 +34,8 @@ export const gitInitInputSchema = z.object({
|
||||
cwd: z.string().min(1),
|
||||
});
|
||||
|
||||
// ── Output schemas ──
|
||||
|
||||
export const gitBranchSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
current: z.boolean(),
|
||||
@@ -44,6 +48,8 @@ export const gitWorktreeSchema = z.object({
|
||||
branch: z.string().min(1),
|
||||
});
|
||||
|
||||
// ── Types ──
|
||||
|
||||
export type GitListBranchesInput = z.infer<typeof gitListBranchesInputSchema>;
|
||||
export type GitBranch = z.infer<typeof gitBranchSchema>;
|
||||
export type GitCreateWorktreeInput = z.infer<typeof gitCreateWorktreeInputSchema>;
|
||||
@@ -61,79 +67,3 @@ export interface GitListBranchesResult {
|
||||
export interface GitCreateWorktreeResult {
|
||||
worktree: GitWorktree;
|
||||
}
|
||||
|
||||
// ── Stacked action Git API ───────────────────────────────────────────
|
||||
|
||||
export const gitStatusInputSchema = z.object({
|
||||
cwd: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const gitStatusResultSchema = z.object({
|
||||
branch: z.string().min(1).nullable(),
|
||||
hasWorkingTreeChanges: z.boolean(),
|
||||
hasUpstream: z.boolean(),
|
||||
aheadCount: z.number().int().nonnegative(),
|
||||
behindCount: z.number().int().nonnegative(),
|
||||
openPr: z
|
||||
.object({
|
||||
number: z.number().int().positive(),
|
||||
title: z.string().min(1),
|
||||
url: z.string().url(),
|
||||
baseBranch: z.string().min(1),
|
||||
headBranch: z.string().min(1),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
|
||||
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",
|
||||
]);
|
||||
|
||||
export const gitRunStackedActionInputSchema = z.object({
|
||||
cwd: z.string().trim().min(1),
|
||||
action: gitStackedActionSchema,
|
||||
commitMessage: z.string().trim().min(1).max(10_000).optional(),
|
||||
});
|
||||
|
||||
export const gitRunStackedActionResultSchema = z.object({
|
||||
action: gitStackedActionSchema,
|
||||
commit: z.object({
|
||||
status: gitCommitStepStatusSchema,
|
||||
commitSha: z.string().min(1).optional(),
|
||||
subject: z.string().min(1).optional(),
|
||||
}),
|
||||
push: z.object({
|
||||
status: gitPushStepStatusSchema,
|
||||
branch: z.string().min(1).optional(),
|
||||
upstreamBranch: z.string().min(1).optional(),
|
||||
setUpstream: z.boolean().optional(),
|
||||
}),
|
||||
pr: z.object({
|
||||
status: gitPrStepStatusSchema,
|
||||
url: z.string().url().optional(),
|
||||
number: z.number().int().positive().optional(),
|
||||
baseBranch: z.string().min(1).optional(),
|
||||
headBranch: z.string().min(1).optional(),
|
||||
title: z.string().min(1).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type GitStatusInput = z.input<typeof gitStatusInputSchema>;
|
||||
export type GitStatusResult = z.infer<typeof gitStatusResultSchema>;
|
||||
export type GitStackedAction = z.infer<typeof gitStackedActionSchema>;
|
||||
export type GitRunStackedActionInput = z.input<typeof gitRunStackedActionInputSchema>;
|
||||
export type GitRunStackedActionResult = z.infer<typeof gitRunStackedActionResultSchema>;
|
||||
@@ -8,10 +8,6 @@ import type {
|
||||
GitListBranchesInput,
|
||||
GitListBranchesResult,
|
||||
GitRemoveWorktreeInput,
|
||||
GitRunStackedActionInput,
|
||||
GitRunStackedActionResult,
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "./git";
|
||||
import type {
|
||||
ProviderEvent,
|
||||
@@ -30,12 +26,12 @@ import type {
|
||||
ProjectRemoveInput,
|
||||
} from "./project";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalEvent,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalThreadInput,
|
||||
TerminalWriteInput,
|
||||
} from "./terminal";
|
||||
import type { NewTodoInput, Todo } from "./todo";
|
||||
@@ -61,7 +57,7 @@ export interface NativeApi {
|
||||
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
|
||||
write: (input: TerminalWriteInput) => Promise<void>;
|
||||
resize: (input: TerminalResizeInput) => Promise<void>;
|
||||
clear: (input: TerminalClearInput) => Promise<void>;
|
||||
clear: (input: TerminalThreadInput) => Promise<void>;
|
||||
restart: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
|
||||
close: (input: TerminalCloseInput) => Promise<void>;
|
||||
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
|
||||
@@ -89,21 +85,14 @@ export interface NativeApi {
|
||||
};
|
||||
shell: {
|
||||
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
|
||||
openExternal: (url: string) => Promise<void>;
|
||||
};
|
||||
git: {
|
||||
// Existing branch/worktree API
|
||||
listBranches: (input: GitListBranchesInput) => Promise<GitListBranchesResult>;
|
||||
createWorktree: (input: GitCreateWorktreeInput) => Promise<GitCreateWorktreeResult>;
|
||||
removeWorktree: (input: GitRemoveWorktreeInput) => Promise<void>;
|
||||
createBranch: (input: GitCreateBranchInput) => Promise<void>;
|
||||
checkout: (input: GitCheckoutInput) => Promise<void>;
|
||||
init: (input: GitInitInput) => Promise<void>;
|
||||
// Stacked action API
|
||||
status: (input: GitStatusInput) => Promise<GitStatusResult>;
|
||||
runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
) => Promise<GitRunStackedActionResult>;
|
||||
};
|
||||
contextMenu: {
|
||||
show: <T extends string>(
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
export const MODEL_OPTIONS = [
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
] as const;
|
||||
export const MODEL_OPTIONS = ["gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.2"] as const;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const MODEL_SLUG_ALIASES: Record<string, string> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
};
|
||||
|
||||
export function normalizeModelSlug(model: string | null | undefined): string | null {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
providerEventSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
@@ -41,67 +40,9 @@ describe("providerSendTurnInputSchema", () => {
|
||||
effort: " high ",
|
||||
});
|
||||
expect(parsed.input).toBe("summarize this repo");
|
||||
expect(parsed.attachments).toEqual([]);
|
||||
expect(parsed.model).toBe("gpt-5.2-codex");
|
||||
expect(parsed.effort).toBe("high");
|
||||
});
|
||||
|
||||
it("accepts image-only turns", () => {
|
||||
const parsed = providerSendTurnInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "diagram.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
dataUrl: "data:image/png;base64,AAAA",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(parsed.input).toBeUndefined();
|
||||
expect(parsed.attachments).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects turns with neither text nor attachments", () => {
|
||||
expect(() =>
|
||||
providerSendTurnInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects non-image data urls", () => {
|
||||
expect(() =>
|
||||
providerSendTurnInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
name: "not-image.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 25,
|
||||
dataUrl: "data:text/plain;base64,QQ==",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects more than the max attachment count", () => {
|
||||
expect(() =>
|
||||
providerSendTurnInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
attachments: Array.from({ length: PROVIDER_SEND_TURN_MAX_ATTACHMENTS + 1 }, (_, index) => ({
|
||||
type: "image" as const,
|
||||
name: `image-${index}.png`,
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 1_024,
|
||||
dataUrl: "data:image/png;base64,AAAA",
|
||||
})),
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("providerEventSchema", () => {
|
||||
|
||||
@@ -55,48 +55,14 @@ export const providerSessionStartInputSchema = z.object({
|
||||
});
|
||||
|
||||
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
|
||||
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
|
||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
||||
export const PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;
|
||||
|
||||
export const providerSendTurnImageAttachmentSchema = z.object({
|
||||
type: z.literal("image"),
|
||||
name: z.string().trim().min(1).max(255),
|
||||
mimeType: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.regex(/^image\//i, "mimeType must be an image/* MIME type"),
|
||||
sizeBytes: z.number().int().min(1).max(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
|
||||
dataUrl: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),
|
||||
export const providerSendTurnInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
effort: z.string().trim().min(1).optional(),
|
||||
});
|
||||
|
||||
export const providerSendTurnAttachmentInputSchema = z.discriminatedUnion("type", [
|
||||
providerSendTurnImageAttachmentSchema,
|
||||
]);
|
||||
|
||||
export const providerSendTurnInputSchema = z
|
||||
.object({
|
||||
sessionId: z.string().min(1),
|
||||
input: z.string().trim().min(1).max(PROVIDER_SEND_TURN_MAX_INPUT_CHARS).optional(),
|
||||
attachments: z
|
||||
.array(providerSendTurnAttachmentInputSchema)
|
||||
.max(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)
|
||||
.default([]),
|
||||
model: z.string().trim().min(1).optional(),
|
||||
effort: z.string().trim().min(1).optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (!value.input && value.attachments.length === 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Either input text or at least one attachment is required",
|
||||
path: ["input"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const providerTurnStartResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
turnId: z.string().min(1),
|
||||
@@ -144,9 +110,6 @@ export type ProviderApprovalDecision = z.infer<typeof providerApprovalDecisionSc
|
||||
export type ProviderSessionStatus = z.infer<typeof providerSessionStatusSchema>;
|
||||
export type ProviderSession = z.infer<typeof providerSessionSchema>;
|
||||
export type ProviderSessionStartInput = z.input<typeof providerSessionStartInputSchema>;
|
||||
export type ProviderSendTurnImageAttachment = z.infer<typeof providerSendTurnImageAttachmentSchema>;
|
||||
export type ProviderSendTurnAttachment = z.infer<typeof providerSendTurnAttachmentInputSchema>;
|
||||
export type ProviderSendTurnAttachmentInput = z.input<typeof providerSendTurnAttachmentInputSchema>;
|
||||
export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
|
||||
export type ProviderTurnStartResult = z.infer<typeof providerTurnStartResultSchema>;
|
||||
export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
terminalClearInputSchema,
|
||||
terminalCloseInputSchema,
|
||||
terminalEventSchema,
|
||||
terminalOpenInputSchema,
|
||||
@@ -32,16 +30,6 @@ describe("terminalOpenInputSchema", () => {
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("defaults terminalId when missing", () => {
|
||||
const parsed = terminalOpenInputSchema.parse({
|
||||
threadId: "thread-1",
|
||||
cwd: "/tmp/project",
|
||||
cols: 100,
|
||||
rows: 24,
|
||||
});
|
||||
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalWriteInputSchema", () => {
|
||||
@@ -80,15 +68,6 @@ describe("terminalResizeInputSchema", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalClearInputSchema", () => {
|
||||
it("defaults terminal id", () => {
|
||||
const parsed = terminalClearInputSchema.parse({
|
||||
threadId: "thread-1",
|
||||
});
|
||||
expect(parsed.terminalId).toBe(DEFAULT_TERMINAL_ID);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalCloseInputSchema", () => {
|
||||
it("accepts optional deleteHistory", () => {
|
||||
const result = terminalCloseInputSchema.safeParse({
|
||||
@@ -103,7 +82,6 @@ describe("terminalSessionSnapshotSchema", () => {
|
||||
it("accepts running snapshots", () => {
|
||||
const result = terminalSessionSnapshotSchema.safeParse({
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
@@ -121,7 +99,6 @@ describe("terminalEventSchema", () => {
|
||||
const result = terminalEventSchema.safeParse({
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "line\n",
|
||||
});
|
||||
@@ -132,7 +109,6 @@ describe("terminalEventSchema", () => {
|
||||
const result = terminalEventSchema.safeParse({
|
||||
type: "exited",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
|
||||
@@ -1,38 +1,28 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const DEFAULT_TERMINAL_ID = "default";
|
||||
|
||||
const terminalColsSchema = z.number().int().min(20).max(400);
|
||||
const terminalRowsSchema = z.number().int().min(5).max(200);
|
||||
const terminalIdSchema = z.string().trim().min(1).max(128);
|
||||
|
||||
export const terminalThreadInputSchema = z.object({
|
||||
threadId: z.string().trim().min(1),
|
||||
});
|
||||
|
||||
export const terminalSessionInputSchema = terminalThreadInputSchema.extend({
|
||||
terminalId: terminalIdSchema.default(DEFAULT_TERMINAL_ID),
|
||||
});
|
||||
|
||||
export const terminalOpenInputSchema = terminalSessionInputSchema.extend({
|
||||
export const terminalOpenInputSchema = terminalThreadInputSchema.extend({
|
||||
cwd: z.string().trim().min(1),
|
||||
cols: terminalColsSchema,
|
||||
rows: terminalRowsSchema,
|
||||
});
|
||||
|
||||
export const terminalWriteInputSchema = terminalSessionInputSchema.extend({
|
||||
export const terminalWriteInputSchema = terminalThreadInputSchema.extend({
|
||||
data: z.string().min(1).max(65_536),
|
||||
});
|
||||
|
||||
export const terminalResizeInputSchema = terminalSessionInputSchema.extend({
|
||||
export const terminalResizeInputSchema = terminalThreadInputSchema.extend({
|
||||
cols: terminalColsSchema,
|
||||
rows: terminalRowsSchema,
|
||||
});
|
||||
|
||||
export const terminalClearInputSchema = terminalSessionInputSchema;
|
||||
|
||||
export const terminalCloseInputSchema = terminalThreadInputSchema.extend({
|
||||
terminalId: terminalIdSchema.optional(),
|
||||
deleteHistory: z.boolean().optional(),
|
||||
});
|
||||
|
||||
@@ -45,7 +35,6 @@ export const terminalSessionStatusSchema = z.enum([
|
||||
|
||||
export const terminalSessionSnapshotSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
terminalId: z.string().min(1),
|
||||
cwd: z.string().min(1),
|
||||
status: terminalSessionStatusSchema,
|
||||
pid: z.number().int().positive().nullable(),
|
||||
@@ -57,7 +46,6 @@ export const terminalSessionSnapshotSchema = z.object({
|
||||
|
||||
const terminalEventBaseSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
terminalId: z.string().min(1),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
||||
@@ -101,11 +89,9 @@ export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||
]);
|
||||
|
||||
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
|
||||
export type TerminalSessionInput = z.input<typeof terminalSessionInputSchema>;
|
||||
export type TerminalOpenInput = z.input<typeof terminalOpenInputSchema>;
|
||||
export type TerminalWriteInput = z.input<typeof terminalWriteInputSchema>;
|
||||
export type TerminalResizeInput = z.input<typeof terminalResizeInputSchema>;
|
||||
export type TerminalClearInput = z.input<typeof terminalClearInputSchema>;
|
||||
export type TerminalCloseInput = z.input<typeof terminalCloseInputSchema>;
|
||||
export type TerminalSessionStatus = z.infer<typeof terminalSessionStatusSchema>;
|
||||
export type TerminalSessionSnapshot = z.infer<typeof terminalSessionSnapshotSchema>;
|
||||
|
||||
@@ -20,8 +20,6 @@ export const WS_METHODS = {
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
|
||||
// Git methods
|
||||
gitStatus: "git.status",
|
||||
gitRunStackedAction: "git.runStackedAction",
|
||||
gitListBranches: "git.listBranches",
|
||||
gitCreateWorktree: "git.createWorktree",
|
||||
gitRemoveWorktree: "git.removeWorktree",
|
||||
|
||||
Reference in new issue
Block a user