Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4df41a0d7 |
No files matched your search
@@ -1,57 +0,0 @@
|
||||
import type { BrowserWindow } from "electron";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { showMessageBoxMock } = vi.hoisted(() => ({
|
||||
showMessageBoxMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
dialog: {
|
||||
showMessageBox: showMessageBoxMock,
|
||||
},
|
||||
}));
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
|
||||
describe("showDesktopConfirmDialog", () => {
|
||||
beforeEach(() => {
|
||||
showMessageBoxMock.mockReset();
|
||||
});
|
||||
|
||||
it("returns false and does not open a dialog for empty messages", async () => {
|
||||
const result = await showDesktopConfirmDialog(" ", null);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(showMessageBoxMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("opens a dialog for the focused window and returns true on confirm", async () => {
|
||||
const ownerWindow = { id: 1 } as BrowserWindow;
|
||||
showMessageBoxMock.mockResolvedValue({ response: 1 });
|
||||
|
||||
const result = await showDesktopConfirmDialog("Delete worktree?", ownerWindow);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(showMessageBoxMock).toHaveBeenCalledWith(
|
||||
ownerWindow,
|
||||
expect.objectContaining({
|
||||
buttons: ["No", "Yes"],
|
||||
message: "Delete worktree?",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("opens an app-level dialog when there is no focused window", async () => {
|
||||
showMessageBoxMock.mockResolvedValue({ response: 0 });
|
||||
|
||||
const result = await showDesktopConfirmDialog("Delete worktree?", null);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(showMessageBoxMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
buttons: ["No", "Yes"],
|
||||
message: "Delete worktree?",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { type BrowserWindow, dialog } from "electron";
|
||||
|
||||
const CONFIRM_BUTTON_INDEX = 1;
|
||||
|
||||
export async function showDesktopConfirmDialog(
|
||||
message: string,
|
||||
ownerWindow: BrowserWindow | null,
|
||||
): Promise<boolean> {
|
||||
const normalizedMessage = message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: CONFIRM_BUTTON_INDEX,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
};
|
||||
const result = ownerWindow
|
||||
? await dialog.showMessageBox(ownerWindow, options)
|
||||
: await dialog.showMessageBox(options);
|
||||
return result.response === CONFIRM_BUTTON_INDEX;
|
||||
}
|
||||
@@ -7,13 +7,11 @@ import path from "node:path";
|
||||
|
||||
import { app, BrowserWindow, dialog, ipcMain, Menu, shell } from "electron";
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { fixPath } from "./fixPath";
|
||||
|
||||
fixPath();
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
@@ -83,12 +81,7 @@ function startBackend(): void {
|
||||
|
||||
const child = spawn(process.execPath, [BACKEND_ENTRY], {
|
||||
cwd: ROOT_DIR,
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
// Run the child in Node mode so this backend process does not become a GUI app instance.
|
||||
env: {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
env: backendEnv(),
|
||||
stdio: "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
@@ -149,16 +142,6 @@ function registerIpcHandlers(): void {
|
||||
return result.filePaths[0] ?? null;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONFIRM_CHANNEL);
|
||||
ipcMain.handle(CONFIRM_CHANNEL, async (_event, message: unknown) => {
|
||||
if (typeof message !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
return showDesktopConfirmDialog(message, owner);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
ipcMain.handle(CONTEXT_MENU_CHANNEL, async (_event, items: { id: string; label: string }[]) => {
|
||||
const window = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { contextBridge, ipcRenderer } from "electron";
|
||||
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
@@ -9,7 +8,6 @@ const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL) as Promise<string | null>,
|
||||
confirm: (message: string) => ipcRenderer.invoke(CONFIRM_CHANNEL, message) as Promise<boolean>,
|
||||
showContextMenu: (items: { id: string; label: string }[]) =>
|
||||
ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items) as Promise<string | null>,
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url) as Promise<boolean>,
|
||||
|
||||
+5
-108
@@ -2,7 +2,7 @@ import { existsSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
GitCoreService,
|
||||
@@ -51,25 +51,6 @@ async function initRepoWithCommit(cwd: string): Promise<void> {
|
||||
await git(cwd, "commit -m 'initial commit'");
|
||||
}
|
||||
|
||||
async function commitWithDate(
|
||||
cwd: string,
|
||||
fileName: string,
|
||||
fileContents: string,
|
||||
dateIsoString: string,
|
||||
message: string,
|
||||
): Promise<void> {
|
||||
await writeFile(path.join(cwd, fileName), fileContents);
|
||||
await git(cwd, `add ${fileName}`);
|
||||
const commitResult = await runTerminalCommand({
|
||||
command: `GIT_AUTHOR_DATE="${dateIsoString}" GIT_COMMITTER_DATE="${dateIsoString}" git commit -m "${message}"`,
|
||||
cwd,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (commitResult.code !== 0) {
|
||||
throw new Error(`git dated commit failed: ${commitResult.stderr}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tests ──
|
||||
|
||||
describe("git integration", () => {
|
||||
@@ -125,82 +106,14 @@ describe("git integration", () => {
|
||||
expect(current!.current).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps current branch first and sorts the remaining branches by recency", async () => {
|
||||
it("sorts current branch first", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const initialBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
await createGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"older.txt",
|
||||
"older branch change\n",
|
||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
||||
"older branch change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: initialBranch });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"newer.txt",
|
||||
"newer branch change\n",
|
||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
||||
"newer branch change",
|
||||
);
|
||||
|
||||
// Switch away to show current branch is pinned, then remaining branches are recency-sorted.
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "older-branch" });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "aaa-first-alpha" });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "zzz-last" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches[0]!.name).toBe("older-branch");
|
||||
expect(result.branches[1]!.name).toBe("newer-branch");
|
||||
});
|
||||
|
||||
it("keeps default branch right after current branch", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await using remote = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const defaultBranch = (await listGitBranches({ cwd: tmp.path })).branches.find(
|
||||
(branch) => branch.current,
|
||||
)!.name;
|
||||
|
||||
await git(remote.path, "init --bare");
|
||||
await git(tmp.path, `remote add origin ${JSON.stringify(remote.path)}`);
|
||||
await git(tmp.path, `push -u origin ${defaultBranch}`);
|
||||
await git(tmp.path, `remote set-head origin ${defaultBranch}`);
|
||||
|
||||
await createGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"current.txt",
|
||||
"current change\n",
|
||||
"Thu, 1 Jan 2037 00:00:00 +0000",
|
||||
"current change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: defaultBranch });
|
||||
await createGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "newer-branch" });
|
||||
await commitWithDate(
|
||||
tmp.path,
|
||||
"newer.txt",
|
||||
"newer change\n",
|
||||
"Fri, 1 Jan 2038 00:00:00 +0000",
|
||||
"newer change",
|
||||
);
|
||||
|
||||
await checkoutGitBranch({ cwd: tmp.path, branch: "current-branch" });
|
||||
|
||||
const result = await listGitBranches({ cwd: tmp.path });
|
||||
expect(result.branches[0]!.name).toBe("current-branch");
|
||||
expect(result.branches[1]!.name).toBe(defaultBranch);
|
||||
expect(result.branches[2]!.name).toBe("newer-branch");
|
||||
expect(result.branches[0]!.current).toBe(true);
|
||||
});
|
||||
|
||||
it("lists multiple branches after creating them", async () => {
|
||||
@@ -603,21 +516,5 @@ describe("git integration", () => {
|
||||
const skipped = await core.pushCurrentBranch(tmp.path, null);
|
||||
expect(skipped.status).toBe("skipped_up_to_date");
|
||||
});
|
||||
|
||||
it("lists branches when recency lookup fails", async () => {
|
||||
await using tmp = await makeTmpDir();
|
||||
await initRepoWithCommit(tmp.path);
|
||||
const core = new GitCoreService();
|
||||
const recencySpy = vi
|
||||
.spyOn(core as any, "readBranchRecency")
|
||||
.mockRejectedValueOnce(new Error("timeout"));
|
||||
|
||||
const result = await core.listBranches({ cwd: tmp.path });
|
||||
|
||||
expect(result.isRepo).toBe(true);
|
||||
expect(result.branches.length).toBeGreaterThan(0);
|
||||
expect(result.branches[0]?.current).toBe(true);
|
||||
recencySpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
+3
-42
@@ -312,40 +312,7 @@ export class GitCoreService {
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
private async readBranchRecency(cwd: string): Promise<Map<string, number>> {
|
||||
const branchRecency = await executeGit(
|
||||
cwd,
|
||||
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
|
||||
{
|
||||
timeoutMs: 15_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
);
|
||||
|
||||
const branchLastCommit = new Map<string, number>();
|
||||
if (branchRecency.code !== 0) {
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
for (const line of branchRecency.stdout.split("\n")) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [name, lastCommitRaw] = line.split("\t");
|
||||
if (!name) {
|
||||
continue;
|
||||
}
|
||||
const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10);
|
||||
branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0);
|
||||
}
|
||||
|
||||
return branchLastCommit;
|
||||
}
|
||||
|
||||
async listBranches(input: GitListBranchesInput): Promise<GitListBranchesResult> {
|
||||
const branchRecencyPromise = this.readBranchRecency(input.cwd).catch(
|
||||
() => new Map<string, number>(),
|
||||
);
|
||||
const result = await executeGit(input.cwd, ["branch", "--no-color"], {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -359,7 +326,7 @@ export class GitCoreService {
|
||||
throw new Error(stderr || "git branch failed");
|
||||
}
|
||||
|
||||
const [defaultRef, worktreeList, branchLastCommit] = await Promise.all([
|
||||
const [defaultRef, worktreeList] = await Promise.all([
|
||||
executeGit(input.cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
@@ -368,7 +335,6 @@ export class GitCoreService {
|
||||
timeoutMs: 5_000,
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
branchRecencyPromise,
|
||||
]);
|
||||
const defaultBranch =
|
||||
defaultRef.code === 0
|
||||
@@ -404,13 +370,8 @@ export class GitCoreService {
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
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);
|
||||
});
|
||||
|
||||
|
||||
@@ -137,11 +137,7 @@ describe("TerminalManager", () => {
|
||||
|
||||
function makeManager(
|
||||
historyLineLimit = 5,
|
||||
options: {
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: (terminalPid: number) => Promise<boolean>;
|
||||
subprocessPollIntervalMs?: number;
|
||||
} = {},
|
||||
options: { shellResolver?: () => string } = {},
|
||||
) {
|
||||
const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-"));
|
||||
tempDirs.push(logsDir);
|
||||
@@ -151,10 +147,6 @@ describe("TerminalManager", () => {
|
||||
ptyAdapter,
|
||||
historyLineLimit,
|
||||
shellResolver: options.shellResolver ?? (() => "/bin/bash"),
|
||||
...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}),
|
||||
...(options.subprocessPollIntervalMs
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
});
|
||||
return { logsDir, ptyAdapter, manager };
|
||||
}
|
||||
@@ -281,42 +273,6 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("emits subprocess activity events when child-process state changes", async () => {
|
||||
let hasRunningSubprocess = false;
|
||||
const { manager } = makeManager(5, {
|
||||
subprocessChecker: async () => hasRunningSubprocess,
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
const events: TerminalEvent[] = [];
|
||||
manager.on("event", (event) => {
|
||||
events.push(event);
|
||||
});
|
||||
|
||||
await manager.open(openInput());
|
||||
await waitFor(() => events.some((event) => event.type === "started"));
|
||||
expect(events.some((event) => event.type === "activity")).toBe(false);
|
||||
|
||||
hasRunningSubprocess = true;
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some(
|
||||
(event) => event.type === "activity" && event.hasRunningSubprocess === true,
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
hasRunningSubprocess = false;
|
||||
await waitFor(
|
||||
() =>
|
||||
events.some(
|
||||
(event) => event.type === "activity" && event.hasRunningSubprocess === false,
|
||||
),
|
||||
1_200,
|
||||
);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("caps persisted history to configured line limit", async () => {
|
||||
const { manager, ptyAdapter } = makeManager(3);
|
||||
await manager.open(openInput());
|
||||
@@ -378,18 +334,15 @@ describe("TerminalManager", () => {
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => {
|
||||
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");
|
||||
const nextPath = historyLogPath(logsDir);
|
||||
fs.writeFileSync(legacyPath, "legacy-line\n", "utf8");
|
||||
|
||||
const snapshot = await manager.open(openInput());
|
||||
|
||||
expect(snapshot.history).toBe("legacy-line\n");
|
||||
expect(fs.existsSync(nextPath)).toBe(true);
|
||||
expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n");
|
||||
expect(fs.existsSync(legacyPath)).toBe(false);
|
||||
expect(fs.existsSync(legacyPath)).toBe(true);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
@@ -21,13 +21,9 @@ import {
|
||||
|
||||
import { createLogger } from "./logger";
|
||||
import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||
|
||||
type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
|
||||
|
||||
export interface TerminalManagerEvents {
|
||||
event: [event: TerminalEvent];
|
||||
@@ -38,8 +34,6 @@ export interface TerminalManagerOptions {
|
||||
historyLineLimit?: number;
|
||||
ptyAdapter?: PtyAdapter;
|
||||
shellResolver?: () => string;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
subprocessPollIntervalMs?: number;
|
||||
}
|
||||
|
||||
interface TerminalSessionState {
|
||||
@@ -57,7 +51,6 @@ interface TerminalSessionState {
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
}
|
||||
|
||||
function defaultShellResolver(): string {
|
||||
@@ -129,83 +122,6 @@ function isRetryableShellSpawnError(error: unknown): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if ($children) { exit 0 }",
|
||||
"exit 1",
|
||||
].join("; ");
|
||||
try {
|
||||
const result = await runProcess(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
{
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
},
|
||||
);
|
||||
return result.code === 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
|
||||
try {
|
||||
const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (pgrepResult.code === 0) {
|
||||
return pgrepResult.stdout.trim().length > 0;
|
||||
}
|
||||
if (pgrepResult.code === 1) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
// Fall back to ps when pgrep is unavailable.
|
||||
}
|
||||
|
||||
try {
|
||||
const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
if (psResult.code !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const line of psResult.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
if (ppid === terminalPid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return checkPosixSubprocessActivity(terminalPid);
|
||||
}
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
if (history.length === 0) return history;
|
||||
const hasTrailingNewline = history.endsWith("\n");
|
||||
@@ -245,10 +161,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
private readonly pendingPersistHistory = new Map<string, string>();
|
||||
private readonly threadLocks = new Map<string, Promise<void>>();
|
||||
private readonly persistDebounceMs: number;
|
||||
private readonly subprocessChecker: TerminalSubprocessChecker;
|
||||
private readonly subprocessPollIntervalMs: number;
|
||||
private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private subprocessPollInFlight = false;
|
||||
private readonly logger = createLogger("terminal");
|
||||
|
||||
constructor(options: TerminalManagerOptions = {}) {
|
||||
@@ -258,9 +170,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
|
||||
this.shellResolver = options.shellResolver ?? defaultShellResolver;
|
||||
this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
|
||||
this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
this.subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
fs.mkdirSync(this.logsDir, { recursive: true });
|
||||
}
|
||||
|
||||
@@ -289,7 +198,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
this.startSession(session, input, "started");
|
||||
@@ -386,7 +294,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
};
|
||||
this.sessions.set(sessionKey, session);
|
||||
} else {
|
||||
@@ -427,17 +334,14 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
if (input.deleteHistory) {
|
||||
await this.deleteAllHistoryForThread(input.threadId);
|
||||
}
|
||||
this.updateSubprocessPollingState();
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.stopSubprocessPolling();
|
||||
const sessions = [...this.sessions.values()];
|
||||
this.sessions.clear();
|
||||
for (const session of sessions) {
|
||||
for (const session of this.sessions.values()) {
|
||||
this.stopProcess(session);
|
||||
}
|
||||
this.sessions.clear();
|
||||
for (const timer of this.persistTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
@@ -460,7 +364,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.rows = input.rows;
|
||||
session.exitCode = null;
|
||||
session.exitSignal = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
|
||||
let ptyProcess: PtyProcess | null = null;
|
||||
@@ -510,7 +413,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.unsubscribeExit = ptyProcess.onExit((event) => {
|
||||
this.onProcessExit(session, event);
|
||||
});
|
||||
this.updateSubprocessPollingState();
|
||||
this.emitEvent({
|
||||
type: eventType,
|
||||
threadId: session.threadId,
|
||||
@@ -529,9 +431,7 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
session.status = "error";
|
||||
session.pid = null;
|
||||
session.process = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
this.updateSubprocessPollingState();
|
||||
const message = error instanceof Error ? error.message : "Terminal start failed";
|
||||
this.emitEvent({
|
||||
type: "error",
|
||||
@@ -566,7 +466,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.cleanupProcessHandles(session);
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.status = "exited";
|
||||
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
|
||||
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
|
||||
@@ -579,7 +478,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
exitCode: session.exitCode,
|
||||
exitSignal: session.exitSignal,
|
||||
});
|
||||
this.updateSubprocessPollingState();
|
||||
}
|
||||
|
||||
private stopProcess(session: TerminalSessionState): void {
|
||||
@@ -588,7 +486,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.cleanupProcessHandles(session);
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.status = "exited";
|
||||
session.updatedAt = new Date().toISOString();
|
||||
try {
|
||||
@@ -601,7 +498,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
this.updateSubprocessPollingState();
|
||||
}
|
||||
|
||||
private cleanupProcessHandles(session: TerminalSessionState): void {
|
||||
@@ -686,12 +582,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
|
||||
private async readHistory(threadId: string, terminalId: string): Promise<string> {
|
||||
const nextPath = this.historyPath(threadId, terminalId);
|
||||
const historyPath = this.historyPath(threadId, terminalId);
|
||||
try {
|
||||
const raw = await fs.promises.readFile(nextPath, "utf8");
|
||||
const raw = await fs.promises.readFile(historyPath, "utf8");
|
||||
const capped = capHistory(raw, this.historyLineLimit);
|
||||
if (capped !== raw) {
|
||||
await fs.promises.writeFile(nextPath, capped, "utf8");
|
||||
await fs.promises.writeFile(historyPath, capped, "utf8");
|
||||
}
|
||||
return capped;
|
||||
} catch (error) {
|
||||
@@ -704,22 +600,12 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
return "";
|
||||
}
|
||||
|
||||
const legacyPath = this.legacyHistoryPath(threadId);
|
||||
try {
|
||||
const raw = await fs.promises.readFile(legacyPath, "utf8");
|
||||
const raw = await fs.promises.readFile(this.legacyHistoryPath(threadId), "utf8");
|
||||
const capped = capHistory(raw, this.historyLineLimit);
|
||||
|
||||
// Migrate legacy transcript filename to the terminal-scoped path.
|
||||
await fs.promises.writeFile(nextPath, capped, "utf8");
|
||||
try {
|
||||
await fs.promises.rm(legacyPath, { force: true });
|
||||
} catch (cleanupError) {
|
||||
this.logger.warn("failed to remove legacy terminal history", {
|
||||
threadId,
|
||||
error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
|
||||
});
|
||||
if (capped !== raw) {
|
||||
await fs.promises.writeFile(this.legacyHistoryPath(threadId), capped, "utf8");
|
||||
}
|
||||
|
||||
return capped;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
@@ -764,86 +650,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
private updateSubprocessPollingState(): void {
|
||||
const hasRunningSessions = [...this.sessions.values()].some(
|
||||
(session) => session.status === "running" && session.pid !== null,
|
||||
);
|
||||
if (hasRunningSessions) {
|
||||
this.ensureSubprocessPolling();
|
||||
return;
|
||||
}
|
||||
this.stopSubprocessPolling();
|
||||
}
|
||||
|
||||
private ensureSubprocessPolling(): void {
|
||||
if (this.subprocessPollTimer) return;
|
||||
this.subprocessPollTimer = setInterval(() => {
|
||||
void this.pollSubprocessActivity();
|
||||
}, this.subprocessPollIntervalMs);
|
||||
this.subprocessPollTimer.unref?.();
|
||||
void this.pollSubprocessActivity();
|
||||
}
|
||||
|
||||
private stopSubprocessPolling(): void {
|
||||
if (!this.subprocessPollTimer) return;
|
||||
clearInterval(this.subprocessPollTimer);
|
||||
this.subprocessPollTimer = null;
|
||||
}
|
||||
|
||||
private async pollSubprocessActivity(): Promise<void> {
|
||||
if (this.subprocessPollInFlight) return;
|
||||
|
||||
const runningSessions = [...this.sessions.values()].filter(
|
||||
(session): session is TerminalSessionState & { pid: number } =>
|
||||
session.status === "running" && Number.isInteger(session.pid),
|
||||
);
|
||||
if (runningSessions.length === 0) {
|
||||
this.stopSubprocessPolling();
|
||||
return;
|
||||
}
|
||||
|
||||
this.subprocessPollInFlight = true;
|
||||
try {
|
||||
await Promise.all(
|
||||
runningSessions.map(async (session) => {
|
||||
const terminalPid = session.pid;
|
||||
let hasRunningSubprocess = false;
|
||||
try {
|
||||
hasRunningSubprocess = await this.subprocessChecker(terminalPid);
|
||||
} catch (error) {
|
||||
this.logger.warn("failed to check terminal subprocess activity", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
terminalPid,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
|
||||
if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
|
||||
return;
|
||||
}
|
||||
if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
|
||||
return;
|
||||
}
|
||||
|
||||
liveSession.hasRunningSubprocess = hasRunningSubprocess;
|
||||
liveSession.updatedAt = new Date().toISOString();
|
||||
this.emitEvent({
|
||||
type: "activity",
|
||||
threadId: liveSession.threadId,
|
||||
terminalId: liveSession.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess,
|
||||
});
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
this.subprocessPollInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async assertValidCwd(cwd: string): Promise<void> {
|
||||
let stats: fs.Stats;
|
||||
try {
|
||||
@@ -870,7 +676,6 @@ export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
|
||||
this.stopProcess(session);
|
||||
this.sessions.delete(key);
|
||||
}
|
||||
this.updateSubprocessPollingState();
|
||||
await this.flushPersistQueue(threadId, terminalId);
|
||||
if (deleteHistory) {
|
||||
await this.deleteHistory(threadId, terminalId);
|
||||
|
||||
@@ -27,16 +27,6 @@ function EventRouter() {
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api) return;
|
||||
return api.terminal.onEvent((event) => {
|
||||
dispatch({
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event,
|
||||
});
|
||||
});
|
||||
}, [api, dispatch]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -92,7 +82,6 @@ function AutoProjectBootstrap() {
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
|
||||
@@ -262,10 +262,11 @@ export default function ChatView() {
|
||||
}, []);
|
||||
const toggleTerminalVisibility = useCallback(() => {
|
||||
if (!activeThreadId) return;
|
||||
const isOpen = Boolean(activeThread?.terminalOpen);
|
||||
dispatch({
|
||||
type: "SET_THREAD_TERMINAL_OPEN",
|
||||
threadId: activeThreadId,
|
||||
open: !activeThread?.terminalOpen,
|
||||
open: !isOpen,
|
||||
});
|
||||
}, [activeThread?.terminalOpen, activeThreadId, dispatch]);
|
||||
const splitTerminal = useCallback(() => {
|
||||
@@ -302,13 +303,21 @@ export default function ChatView() {
|
||||
(terminalId: string) => {
|
||||
if (!activeThreadId || !api) return;
|
||||
const fallbackExitWrite = () =>
|
||||
api.terminal.write({ threadId: activeThreadId, terminalId, data: "exit\n" }).catch(() => undefined);
|
||||
api.terminal
|
||||
.write({ threadId: activeThreadId, terminalId, data: "exit\n" })
|
||||
.catch(() => undefined);
|
||||
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 })
|
||||
.catch(() => fallbackExitWrite());
|
||||
.close({ threadId: activeThreadId, terminalId, deleteHistory: true })
|
||||
.catch(() => fallbackClearAndExit());
|
||||
} else {
|
||||
void fallbackExitWrite();
|
||||
void fallbackClearAndExit();
|
||||
}
|
||||
dispatch({
|
||||
type: "CLOSE_THREAD_TERMINAL",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MonitorIcon, MoonIcon, SunIcon, TerminalIcon } from "lucide-react";
|
||||
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
type Thread,
|
||||
} from "../types";
|
||||
import { useNativeApi } from "../hooks/useNativeApi";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
|
||||
const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;
|
||||
function formatRelativeTime(iso: string): string {
|
||||
@@ -39,12 +38,6 @@ interface ThreadStatusPill {
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
interface TerminalStatusIndicator {
|
||||
label: "Terminal process running";
|
||||
colorClass: string;
|
||||
pulse: boolean;
|
||||
}
|
||||
|
||||
function hasUnseenCompletion(thread: Thread): boolean {
|
||||
if (!thread.latestTurnCompletedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurnCompletedAt);
|
||||
@@ -96,17 +89,6 @@ function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadS
|
||||
return null;
|
||||
}
|
||||
|
||||
function terminalStatusIndicator(thread: Thread): TerminalStatusIndicator | null {
|
||||
if (thread.runningTerminalIds.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
label: "Terminal process running",
|
||||
colorClass: "text-teal-600 dark:text-teal-300/90",
|
||||
pulse: true,
|
||||
};
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useNativeApi();
|
||||
@@ -136,7 +118,6 @@ export default function Sidebar() {
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -263,22 +244,6 @@ export default function Sidebar() {
|
||||
|
||||
const thread = state.threads.find((t) => t.id === threadId);
|
||||
if (!thread) return;
|
||||
const threadProject = state.projects.find((project) => project.id === thread.projectId);
|
||||
const orphanedWorktreePath = getOrphanedWorktreePathForThread(state.threads, threadId);
|
||||
const displayWorktreePath = orphanedWorktreePath
|
||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
||||
: null;
|
||||
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
|
||||
const shouldDeleteWorktree =
|
||||
canDeleteWorktree &&
|
||||
(await api.dialogs.confirm(
|
||||
[
|
||||
"This thread is the only one linked to this worktree:",
|
||||
displayWorktreePath ?? orphanedWorktreePath,
|
||||
"",
|
||||
"Delete the worktree too?",
|
||||
].join("\n"),
|
||||
));
|
||||
|
||||
// Stop active session if running
|
||||
if (thread.session?.sessionId) {
|
||||
@@ -301,21 +266,8 @@ export default function Sidebar() {
|
||||
}
|
||||
|
||||
dispatch({ type: "DELETE_THREAD", threadId });
|
||||
|
||||
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.git.removeWorktree({
|
||||
cwd: threadProject.cwd,
|
||||
path: orphanedWorktreePath,
|
||||
});
|
||||
} catch {
|
||||
// Worktree deletion is best-effort and should not block thread deletion.
|
||||
}
|
||||
},
|
||||
[api, dispatch, state.projects, state.threads],
|
||||
[api, dispatch, state.threads],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -436,7 +388,6 @@ export default function Sidebar() {
|
||||
thread,
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
);
|
||||
const terminalStatus = terminalStatusIndicator(thread);
|
||||
return (
|
||||
<button
|
||||
key={thread.id}
|
||||
@@ -475,23 +426,9 @@ export default function Sidebar() {
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>
|
||||
</div>
|
||||
<div className="ml-2 flex shrink-0 items-center gap-1.5">
|
||||
{terminalStatus && (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={terminalStatus.label}
|
||||
title={terminalStatus.label}
|
||||
className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
|
||||
>
|
||||
<TerminalIcon
|
||||
className={`size-3 ${terminalStatus.pulse ? "animate-pulse" : ""}`}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/40">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
<span className="shrink-0 text-[10px] text-muted-foreground/40">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -278,7 +278,6 @@ describe("toPersistedState", () => {
|
||||
terminalOpen: true,
|
||||
terminalHeight: 320,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: "term-2",
|
||||
terminalGroups: [
|
||||
{ id: `group-${DEFAULT_THREAD_TERMINAL_ID}`, terminalIds: [DEFAULT_THREAD_TERMINAL_ID] },
|
||||
|
||||
@@ -243,7 +243,6 @@ function hydrateThread(
|
||||
terminalOpen: thread.terminalOpen ?? false,
|
||||
terminalHeight: thread.terminalHeight ?? DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: safeTerminalIds,
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId,
|
||||
terminalGroups: normalizedGroups,
|
||||
activeTerminalGroupId,
|
||||
|
||||
+1
-108
@@ -1,13 +1,10 @@
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
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 type { Thread } from "./types";
|
||||
|
||||
type TerminalStartedEvent = Extract<TerminalEvent, { type: "started" }>;
|
||||
type TerminalActivityEvent = Extract<TerminalEvent, { type: "activity" }>;
|
||||
|
||||
function makeSession(overrides: Partial<ProviderSession> = {}): ProviderSession {
|
||||
return {
|
||||
sessionId: "sess-1",
|
||||
@@ -41,7 +38,6 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -79,42 +75,6 @@ function makeState(thread: Thread): AppState {
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalStartedEvent(
|
||||
overrides: Partial<TerminalStartedEvent> = {},
|
||||
): TerminalStartedEvent {
|
||||
return {
|
||||
type: "started",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:01.000Z",
|
||||
snapshot: {
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
cwd: "/tmp/project",
|
||||
status: "running",
|
||||
pid: 1234,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: "2026-02-09T00:00:01.000Z",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTerminalActivityEvent(
|
||||
overrides: Partial<TerminalActivityEvent> = {},
|
||||
): TerminalActivityEvent {
|
||||
return {
|
||||
type: "activity",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:02.000Z",
|
||||
hasRunningSubprocess: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("store reducer thread continuity", () => {
|
||||
it("stores codexThreadId from UPDATE_SESSION", () => {
|
||||
const state = makeState(
|
||||
@@ -295,7 +255,6 @@ describe("store reducer thread continuity", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalOpen: true,
|
||||
runningTerminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
}),
|
||||
);
|
||||
const next = reducer(state, {
|
||||
@@ -306,7 +265,6 @@ describe("store reducer thread continuity", () => {
|
||||
|
||||
expect(next.threads[0]?.terminalOpen).toBe(false);
|
||||
expect(next.threads[0]?.terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
expect(next.threads[0]?.activeTerminalId).toBe(DEFAULT_THREAD_TERMINAL_ID);
|
||||
expect(next.threads[0]?.terminalGroups).toEqual([
|
||||
{
|
||||
@@ -316,71 +274,6 @@ describe("store reducer thread continuity", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("tracks running terminals from subprocess activity events", () => {
|
||||
const state = makeState(makeThread());
|
||||
const started = reducer(state, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalStartedEvent(),
|
||||
});
|
||||
expect(started.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
|
||||
const active = reducer(started, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent(),
|
||||
});
|
||||
expect(active.threads[0]?.runningTerminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
|
||||
|
||||
const idle = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: makeTerminalActivityEvent({ hasRunningSubprocess: false }),
|
||||
});
|
||||
expect(idle.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
|
||||
const exited = reducer(active, {
|
||||
type: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:05.000Z",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
},
|
||||
});
|
||||
expect(exited.threads[0]?.runningTerminalIds).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps running status when another terminal in the thread is still running", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID, "term-2"],
|
||||
runningTerminalIds: [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: "APPLY_TERMINAL_EVENT",
|
||||
event: {
|
||||
type: "exited",
|
||||
threadId: "thread-local-1",
|
||||
terminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
createdAt: "2026-02-09T00:00:07.000Z",
|
||||
exitCode: 0,
|
||||
exitSignal: null,
|
||||
},
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.runningTerminalIds).toEqual(["term-2"]);
|
||||
});
|
||||
|
||||
it("backfills codexThreadId from routed provider events", () => {
|
||||
const state = makeState(makeThread({ codexThreadId: null }));
|
||||
const next = reducer(state, {
|
||||
|
||||
+1
-47
@@ -8,7 +8,7 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
@@ -43,7 +43,6 @@ type Action =
|
||||
event: ProviderEvent;
|
||||
activeAssistantItemRef: { current: string | null };
|
||||
}
|
||||
| { type: "APPLY_TERMINAL_EVENT"; event: TerminalEvent }
|
||||
| { type: "UPDATE_SESSION"; threadId: string; session: ProviderSession }
|
||||
| {
|
||||
type: "PUSH_USER_MESSAGE";
|
||||
@@ -150,17 +149,6 @@ function normalizeTerminalIds(terminalIds: string[]): string[] {
|
||||
return [DEFAULT_THREAD_TERMINAL_ID];
|
||||
}
|
||||
|
||||
function normalizeRunningTerminalIds(
|
||||
runningTerminalIds: string[],
|
||||
terminalIds: string[],
|
||||
): string[] {
|
||||
if (runningTerminalIds.length === 0) return [];
|
||||
const validTerminalIdSet = new Set(terminalIds);
|
||||
return [...new Set(runningTerminalIds)]
|
||||
.map((id) => id.trim())
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
}
|
||||
@@ -264,7 +252,6 @@ function normalizeThreadTerminals(thread: Thread): Thread {
|
||||
return {
|
||||
...thread,
|
||||
terminalIds,
|
||||
runningTerminalIds: normalizeRunningTerminalIds(thread.runningTerminalIds, terminalIds),
|
||||
activeTerminalId,
|
||||
terminalGroups,
|
||||
activeTerminalGroupId,
|
||||
@@ -282,7 +269,6 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
...thread,
|
||||
terminalOpen: false,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
@@ -323,7 +309,6 @@ function closeThreadTerminal(thread: Thread, terminalId: string): Thread {
|
||||
return normalizeThreadTerminals({
|
||||
...thread,
|
||||
terminalIds: remainingTerminalIds,
|
||||
runningTerminalIds: thread.runningTerminalIds.filter((id) => id !== terminalId),
|
||||
activeTerminalId: nextActiveTerminalId,
|
||||
terminalGroups: nextTerminalGroups,
|
||||
});
|
||||
@@ -665,37 +650,6 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
case "TOGGLE_DIFF":
|
||||
return { ...state, diffOpen: !state.diffOpen };
|
||||
|
||||
case "APPLY_TERMINAL_EVENT":
|
||||
if (!state.threads.some((thread) => thread.id === action.event.threadId)) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.event.threadId, (thread) => {
|
||||
const normalizedThread = normalizeThreadTerminals(thread);
|
||||
const runningTerminalIdSet = new Set(normalizedThread.runningTerminalIds);
|
||||
if (
|
||||
action.event.type === "started" ||
|
||||
action.event.type === "restarted"
|
||||
) {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
} else if (action.event.type === "activity") {
|
||||
if (action.event.hasRunningSubprocess) {
|
||||
runningTerminalIdSet.add(action.event.terminalId);
|
||||
} else {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
} else if (action.event.type === "exited" || action.event.type === "error") {
|
||||
runningTerminalIdSet.delete(action.event.terminalId);
|
||||
}
|
||||
|
||||
return normalizeThreadTerminals({
|
||||
...normalizedThread,
|
||||
runningTerminalIds: [...runningTerminalIdSet],
|
||||
});
|
||||
}),
|
||||
};
|
||||
|
||||
case "APPLY_EVENT": {
|
||||
const { event, activeAssistantItemRef } = action;
|
||||
const target = findThreadBySessionId(state.threads, event.sessionId);
|
||||
|
||||
@@ -48,7 +48,6 @@ export interface Thread {
|
||||
terminalOpen: boolean;
|
||||
terminalHeight: number;
|
||||
terminalIds: string[];
|
||||
runningTerminalIds: string[];
|
||||
activeTerminalId: string;
|
||||
terminalGroups: ThreadTerminalGroup[];
|
||||
activeTerminalGroupId: string;
|
||||
|
||||
Vendored
-1
@@ -5,7 +5,6 @@ import type { NativeApi } from "@t3tools/contracts";
|
||||
interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
showContextMenu: (items: readonly { id: string; label: string }[]) => Promise<string | null>;
|
||||
openExternal: (url: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, type Thread } from "./types";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: "thread-1",
|
||||
codexThreadId: null,
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
terminalOpen: false,
|
||||
terminalHeight: DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
runningTerminalIds: [],
|
||||
activeTerminalId: DEFAULT_THREAD_TERMINAL_ID,
|
||||
terminalGroups: [
|
||||
{
|
||||
id: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
terminalIds: [DEFAULT_THREAD_TERMINAL_ID],
|
||||
},
|
||||
],
|
||||
activeTerminalGroupId: `group-${DEFAULT_THREAD_TERMINAL_ID}`,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("getOrphanedWorktreePathForThread", () => {
|
||||
it("returns null when the target thread does not exist", () => {
|
||||
const result = getOrphanedWorktreePathForThread([], "missing-thread");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when the target thread has no worktree", () => {
|
||||
const threads = [makeThread()];
|
||||
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the path when no other thread links to that worktree", () => {
|
||||
const threads = [makeThread({ worktreePath: "/tmp/repo/worktrees/feature-a" })];
|
||||
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
|
||||
expect(result).toBe("/tmp/repo/worktrees/feature-a");
|
||||
});
|
||||
|
||||
it("returns null when another thread links to the same worktree", () => {
|
||||
const threads = [
|
||||
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
|
||||
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-a" }),
|
||||
];
|
||||
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores threads linked to different worktrees", () => {
|
||||
const threads = [
|
||||
makeThread({ id: "thread-1", worktreePath: "/tmp/repo/worktrees/feature-a" }),
|
||||
makeThread({ id: "thread-2", worktreePath: "/tmp/repo/worktrees/feature-b" }),
|
||||
];
|
||||
const result = getOrphanedWorktreePathForThread(threads, "thread-1");
|
||||
expect(result).toBe("/tmp/repo/worktrees/feature-a");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatWorktreePathForDisplay", () => {
|
||||
it("shows only the last path segment for unix-like paths", () => {
|
||||
const result = formatWorktreePathForDisplay(
|
||||
"/Users/julius/.t3/worktrees/codething-mvp/codething-4e609bb8",
|
||||
);
|
||||
expect(result).toBe("codething-4e609bb8");
|
||||
});
|
||||
|
||||
it("normalizes windows separators before selecting the final segment", () => {
|
||||
const result = formatWorktreePathForDisplay(
|
||||
"C:\\Users\\julius\\.t3\\worktrees\\codething-mvp\\codething-4e609bb8",
|
||||
);
|
||||
expect(result).toBe("codething-4e609bb8");
|
||||
});
|
||||
|
||||
it("uses the final segment even when outside ~/.t3/worktrees", () => {
|
||||
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree");
|
||||
expect(result).toBe("my-worktree");
|
||||
});
|
||||
|
||||
it("ignores trailing slashes", () => {
|
||||
const result = formatWorktreePathForDisplay("/tmp/custom-worktrees/my-worktree/");
|
||||
expect(result).toBe("my-worktree");
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import type { Thread } from "./types";
|
||||
|
||||
function normalizeWorktreePath(path: string | null): string | null {
|
||||
const trimmed = path?.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function getOrphanedWorktreePathForThread(
|
||||
threads: readonly Thread[],
|
||||
threadId: string,
|
||||
): string | null {
|
||||
const targetThread = threads.find((thread) => thread.id === threadId);
|
||||
if (!targetThread) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const targetWorktreePath = normalizeWorktreePath(targetThread.worktreePath);
|
||||
if (!targetWorktreePath) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isShared = threads.some((thread) => {
|
||||
if (thread.id === threadId) {
|
||||
return false;
|
||||
}
|
||||
return normalizeWorktreePath(thread.worktreePath) === targetWorktreePath;
|
||||
});
|
||||
|
||||
return isShared ? null : targetWorktreePath;
|
||||
}
|
||||
|
||||
export function formatWorktreePathForDisplay(worktreePath: string): string {
|
||||
const trimmed = worktreePath.trim();
|
||||
if (!trimmed) {
|
||||
return worktreePath;
|
||||
}
|
||||
|
||||
const normalized = trimmed.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
const parts = normalized.split("/");
|
||||
const lastPart = parts[parts.length - 1]?.trim() ?? "";
|
||||
return lastPart.length > 0 ? lastPart : trimmed;
|
||||
}
|
||||
@@ -60,12 +60,6 @@ export function createWsNativeApi(): NativeApi {
|
||||
if (!window.desktopBridge) return null;
|
||||
return window.desktopBridge.pickFolder();
|
||||
},
|
||||
confirm: async (message) => {
|
||||
if (window.desktopBridge) {
|
||||
return window.desktopBridge.confirm(message);
|
||||
}
|
||||
return window.confirm(message);
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
|
||||
|
||||
@@ -56,7 +56,6 @@ export interface NativeApi {
|
||||
};
|
||||
dialogs: {
|
||||
pickFolder: () => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
};
|
||||
terminal: {
|
||||
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
|
||||
|
||||
@@ -139,15 +139,4 @@ describe("terminalEventSchema", () => {
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts activity events", () => {
|
||||
const result = terminalEventSchema.safeParse({
|
||||
type: "activity",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess: true,
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -91,11 +91,6 @@ export const terminalRestartedEventSchema = terminalEventBaseSchema.extend({
|
||||
snapshot: terminalSessionSnapshotSchema,
|
||||
});
|
||||
|
||||
export const terminalActivityEventSchema = terminalEventBaseSchema.extend({
|
||||
type: z.literal("activity"),
|
||||
hasRunningSubprocess: z.boolean(),
|
||||
});
|
||||
|
||||
export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||
terminalStartedEventSchema,
|
||||
terminalOutputEventSchema,
|
||||
@@ -103,7 +98,6 @@ export const terminalEventSchema = z.discriminatedUnion("type", [
|
||||
terminalErrorEventSchema,
|
||||
terminalClearedEventSchema,
|
||||
terminalRestartedEventSchema,
|
||||
terminalActivityEventSchema,
|
||||
]);
|
||||
|
||||
export type TerminalThreadInput = z.input<typeof terminalThreadInputSchema>;
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# New Poem
|
||||
|
||||
Morning threads the city seams,
|
||||
Coffee steam and careful dreams.
|
||||
Keys begin their silver rain,
|
||||
Small ideas become a plane.
|
||||
|
||||
Windows glow with patient light,
|
||||
Bugs turn understandable by night.
|
||||
Line by line, the silence hums,
|
||||
Tomorrow starts where this one comes.
|
||||
Reference in new issue
Block a user