Open History to see the last commit
1import { EventEmitter } from "node:events";
2import fs from "node:fs";
3import path from "node:path";
4
5import {
6 DEFAULT_TERMINAL_ID,
7 type TerminalClearInput,
8 type TerminalCloseInput,
9 type TerminalEvent,
10 type TerminalOpenInput,
11 type TerminalResizeInput,
12 type TerminalSessionSnapshot,
13 type TerminalSessionStatus,
14 type TerminalWriteInput,
15 terminalClearInputSchema,
16 terminalCloseInputSchema,
17 terminalOpenInputSchema,
18 terminalResizeInputSchema,
19 terminalWriteInputSchema,
20} from "@t3tools/contracts";
21
22import { createLogger } from "./logger";
23import { NodePtyAdapter, type PtyAdapter, type PtyExitEvent, type PtyProcess } from "./ptyAdapter";
24import { runProcess } from "./processRunner";
25
26const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
27const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
28const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
29const DEFAULT_OPEN_COLS = 120;
30const DEFAULT_OPEN_ROWS = 30;
31const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
32
33type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>;
34
35export interface TerminalManagerEvents {
36 event: [event: TerminalEvent];
37}
38
39export interface TerminalManagerOptions {
40 logsDir?: string;
41 historyLineLimit?: number;
42 ptyAdapter?: PtyAdapter;
43 shellResolver?: () => string;
44 subprocessChecker?: TerminalSubprocessChecker;
45 subprocessPollIntervalMs?: number;
46}
47
48interface TerminalSessionState {
49 threadId: string;
50 terminalId: string;
51 cwd: string;
52 status: TerminalSessionStatus;
53 pid: number | null;
54 history: string;
55 exitCode: number | null;
56 exitSignal: number | null;
57 updatedAt: string;
58 cols: number;
59 rows: number;
60 process: PtyProcess | null;
61 unsubscribeData: (() => void) | null;
62 unsubscribeExit: (() => void) | null;
63 hasRunningSubprocess: boolean;
64 runtimeEnv: Record<string, string> | null;
65}
66
67interface ShellCandidate {
68 shell: string;
69 args?: string[];
70}
71
72type TerminalStartInput = TerminalOpenInput & { cols: number; rows: number };
73
74function defaultShellResolver(): string {
75 if (process.platform === "win32") {
76 return process.env.ComSpec ?? "cmd.exe";
77 }
78 return process.env.SHELL ?? "bash";
79}
80
81function normalizeShellCommand(value: string | undefined): string | null {
82 if (!value) return null;
83 const trimmed = value.trim();
84 if (trimmed.length === 0) return null;
85
86 if (process.platform === "win32") {
87 return trimmed;
88 }
89
90 const firstToken = trimmed.split(/\s+/g)[0]?.trim();
91 if (!firstToken) return null;
92 return firstToken.replace(/^['"]|['"]$/g, "");
93}
94
95function shellCandidateFromCommand(command: string | null): ShellCandidate | null {
96 if (!command || command.length === 0) return null;
97 const shellName = path.basename(command).toLowerCase();
98 if (process.platform !== "win32" && shellName === "zsh") {
99 return { shell: command, args: ["-o", "nopromptsp"] };
100 }
101 return { shell: command };
102}
103
104function formatShellCandidate(candidate: ShellCandidate): string {
105 if (!candidate.args || candidate.args.length === 0) return candidate.shell;
106 return `${candidate.shell} ${candidate.args.join(" ")}`;
107}
108
109function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {
110 const seen = new Set<string>();
111 const ordered: ShellCandidate[] = [];
112 for (const candidate of candidates) {
113 if (!candidate) continue;
114 const key = formatShellCandidate(candidate);
115 if (seen.has(key)) continue;
116 seen.add(key);
117 ordered.push(candidate);
118 }
119 return ordered;
120}
121
122function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] {
123 const requested = shellCandidateFromCommand(normalizeShellCommand(shellResolver()));
124
125 if (process.platform === "win32") {
126 return uniqueShellCandidates([
127 requested,
128 shellCandidateFromCommand(process.env.ComSpec ?? null),
129 shellCandidateFromCommand("powershell.exe"),
130 shellCandidateFromCommand("cmd.exe"),
131 ]);
132 }
133
134 return uniqueShellCandidates([
135 requested,
136 shellCandidateFromCommand(normalizeShellCommand(process.env.SHELL)),
137 shellCandidateFromCommand("/bin/zsh"),
138 shellCandidateFromCommand("/bin/bash"),
139 shellCandidateFromCommand("/bin/sh"),
140 shellCandidateFromCommand("zsh"),
141 shellCandidateFromCommand("bash"),
142 shellCandidateFromCommand("sh"),
143 ]);
144}
145
146function isRetryableShellSpawnError(error: unknown): boolean {
147 if (!(error instanceof Error)) return false;
148 const message = error.message.toLowerCase();
149 return (
150 message.includes("posix_spawnp failed") ||
151 message.includes("enoent") ||
152 message.includes("not found") ||
153 message.includes("file not found") ||
154 message.includes("no such file")
155 );
156}
157
158async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> {
159 const command = [
160 `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
161 "if ($children) { exit 0 }",
162 "exit 1",
163 ].join("; ");
164 try {
165 const result = await runProcess(
166 "powershell.exe",
167 ["-NoProfile", "-NonInteractive", "-Command", command],
168 {
169 timeoutMs: 1_500,
170 allowNonZeroExit: true,
171 maxBufferBytes: 32_768,
172 outputMode: "truncate",
173 },
174 );
175 return result.code === 0;
176 } catch {
177 return false;
178 }
179}
180
181async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> {
182 try {
183 const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], {
184 timeoutMs: 1_000,
185 allowNonZeroExit: true,
186 maxBufferBytes: 32_768,
187 outputMode: "truncate",
188 });
189 if (pgrepResult.code === 0) {
190 return pgrepResult.stdout.trim().length > 0;
191 }
192 if (pgrepResult.code === 1) {
193 return false;
194 }
195 } catch {
196 // Fall back to ps when pgrep is unavailable.
197 }
198
199 try {
200 const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], {
201 timeoutMs: 1_000,
202 allowNonZeroExit: true,
203 maxBufferBytes: 262_144,
204 outputMode: "truncate",
205 });
206 if (psResult.code !== 0) {
207 return false;
208 }
209
210 for (const line of psResult.stdout.split(/\r?\n/g)) {
211 const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
212 const pid = Number(pidRaw);
213 const ppid = Number(ppidRaw);
214 if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
215 if (ppid === terminalPid) {
216 return true;
217 }
218 }
219 return false;
220 } catch {
221 return false;
222 }
223}
224
225async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> {
226 if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
227 return false;
228 }
229 if (process.platform === "win32") {
230 return checkWindowsSubprocessActivity(terminalPid);
231 }
232 return checkPosixSubprocessActivity(terminalPid);
233}
234
235function capHistory(history: string, maxLines: number): string {
236 if (history.length === 0) return history;
237 const hasTrailingNewline = history.endsWith("\n");
238 const lines = history.split("\n");
239 if (hasTrailingNewline) {
240 lines.pop();
241 }
242 if (lines.length <= maxLines) return history;
243 const capped = lines.slice(lines.length - maxLines).join("\n");
244 return hasTrailingNewline ? `${capped}\n` : capped;
245}
246
247function legacySafeThreadId(threadId: string): string {
248 return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
249}
250
251function toSafeThreadId(threadId: string): string {
252 return `terminal_${Buffer.from(threadId, "utf8").toString("base64url")}`;
253}
254
255function toSafeTerminalId(terminalId: string): string {
256 return Buffer.from(terminalId, "utf8").toString("base64url");
257}
258
259function toSessionKey(threadId: string, terminalId: string): string {
260 return `${threadId}\u0000${terminalId}`;
261}
262
263function shouldExcludeTerminalEnvKey(key: string): boolean {
264 const normalizedKey = key.toUpperCase();
265 if (normalizedKey.startsWith("T3CODE_")) {
266 return true;
267 }
268 if (normalizedKey.startsWith("VITE_")) {
269 return true;
270 }
271 return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
272}
273
274function createTerminalSpawnEnv(
275 baseEnv: NodeJS.ProcessEnv,
276 runtimeEnv?: Record<string, string> | null,
277): NodeJS.ProcessEnv {
278 const spawnEnv: NodeJS.ProcessEnv = {};
279 for (const [key, value] of Object.entries(baseEnv)) {
280 if (value === undefined) continue;
281 if (shouldExcludeTerminalEnvKey(key)) continue;
282 spawnEnv[key] = value;
283 }
284 if (runtimeEnv) {
285 for (const [key, value] of Object.entries(runtimeEnv)) {
286 spawnEnv[key] = value;
287 }
288 }
289 return spawnEnv;
290}
291
292function normalizedRuntimeEnv(
293 env: Record<string, string> | undefined,
294): Record<string, string> | null {
295 if (!env) return null;
296 const entries = Object.entries(env);
297 if (entries.length === 0) return null;
298 return Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right)));
299}
300
301export class TerminalManager extends EventEmitter<TerminalManagerEvents> {
302 private readonly sessions = new Map<string, TerminalSessionState>();
303 private readonly logsDir: string;
304 private readonly historyLineLimit: number;
305 private readonly ptyAdapter: PtyAdapter;
306 private readonly shellResolver: () => string;
307 private readonly persistQueues = new Map<string, Promise<void>>();
308 private readonly persistTimers = new Map<string, ReturnType<typeof setTimeout>>();
309 private readonly pendingPersistHistory = new Map<string, string>();
310 private readonly threadLocks = new Map<string, Promise<void>>();
311 private readonly persistDebounceMs: number;
312 private readonly subprocessChecker: TerminalSubprocessChecker;
313 private readonly subprocessPollIntervalMs: number;
314 private subprocessPollTimer: ReturnType<typeof setInterval> | null = null;
315 private subprocessPollInFlight = false;
316 private readonly logger = createLogger("terminal");
317
318 constructor(options: TerminalManagerOptions = {}) {
319 super();
320 this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals");
321 this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
322 this.ptyAdapter = options.ptyAdapter ?? new NodePtyAdapter();
323 this.shellResolver = options.shellResolver ?? defaultShellResolver;
324 this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS;
325 this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
326 this.subprocessPollIntervalMs =
327 options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
328 fs.mkdirSync(this.logsDir, { recursive: true });
329 }
330
331 async open(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
332 const input = terminalOpenInputSchema.parse(raw);
333 return this.runWithThreadLock(input.threadId, async () => {
334 await this.assertValidCwd(input.cwd);
335
336 const sessionKey = toSessionKey(input.threadId, input.terminalId);
337 const existing = this.sessions.get(sessionKey);
338 if (!existing) {
339 await this.flushPersistQueue(input.threadId, input.terminalId);
340 const history = await this.readHistory(input.threadId, input.terminalId);
341 const cols = input.cols ?? DEFAULT_OPEN_COLS;
342 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
343 const session: TerminalSessionState = {
344 threadId: input.threadId,
345 terminalId: input.terminalId,
346 cwd: input.cwd,
347 status: "starting",
348 pid: null,
349 history,
350 exitCode: null,
351 exitSignal: null,
352 updatedAt: new Date().toISOString(),
353 cols,
354 rows,
355 process: null,
356 unsubscribeData: null,
357 unsubscribeExit: null,
358 hasRunningSubprocess: false,
359 runtimeEnv: normalizedRuntimeEnv(input.env),
360 };
361 this.sessions.set(sessionKey, session);
362 this.startSession(session, { ...input, cols, rows }, "started");
363 return this.snapshot(session);
364 }
365
366 const nextRuntimeEnv = normalizedRuntimeEnv(input.env);
367 const currentRuntimeEnv = existing.runtimeEnv;
368 const targetCols = input.cols ?? existing.cols;
369 const targetRows = input.rows ?? existing.rows;
370 const runtimeEnvChanged =
371 JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv);
372
373 if (existing.cwd !== input.cwd || runtimeEnvChanged) {
374 this.stopProcess(existing);
375 existing.cwd = input.cwd;
376 existing.runtimeEnv = nextRuntimeEnv;
377 existing.history = "";
378 await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
379 } else if (existing.status === "exited" || existing.status === "error") {
380 existing.runtimeEnv = nextRuntimeEnv;
381 existing.history = "";
382 await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
383 } else if (currentRuntimeEnv !== nextRuntimeEnv) {
384 existing.runtimeEnv = nextRuntimeEnv;
385 }
386
387 if (!existing.process) {
388 this.startSession(existing, { ...input, cols: targetCols, rows: targetRows }, "started");
389 return this.snapshot(existing);
390 }
391
392 if (existing.cols !== targetCols || existing.rows !== targetRows) {
393 existing.cols = targetCols;
394 existing.rows = targetRows;
395 existing.process.resize(targetCols, targetRows);
396 existing.updatedAt = new Date().toISOString();
397 }
398
399 return this.snapshot(existing);
400 });
401 }
402
403 async write(raw: TerminalWriteInput): Promise<void> {
404 const input = terminalWriteInputSchema.parse(raw);
405 const session = this.requireSession(input.threadId, input.terminalId);
406 if (!session.process || session.status !== "running") {
407 throw new Error(
408 `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
409 );
410 }
411 session.process.write(input.data);
412 }
413
414 async resize(raw: TerminalResizeInput): Promise<void> {
415 const input = terminalResizeInputSchema.parse(raw);
416 const session = this.requireSession(input.threadId, input.terminalId);
417 if (!session.process || session.status !== "running") {
418 throw new Error(
419 `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`,
420 );
421 }
422 session.cols = input.cols;
423 session.rows = input.rows;
424 session.updatedAt = new Date().toISOString();
425 session.process.resize(input.cols, input.rows);
426 }
427
428 async clear(raw: TerminalClearInput): Promise<void> {
429 const input = terminalClearInputSchema.parse(raw);
430 await this.runWithThreadLock(input.threadId, async () => {
431 const session = this.requireSession(input.threadId, input.terminalId);
432 session.history = "";
433 session.updatedAt = new Date().toISOString();
434 await this.persistHistory(input.threadId, input.terminalId, session.history);
435 this.emitEvent({
436 type: "cleared",
437 threadId: input.threadId,
438 terminalId: input.terminalId,
439 createdAt: new Date().toISOString(),
440 });
441 });
442 }
443
444 async restart(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> {
445 const input = terminalOpenInputSchema.parse(raw);
446 return this.runWithThreadLock(input.threadId, async () => {
447 await this.assertValidCwd(input.cwd);
448
449 const sessionKey = toSessionKey(input.threadId, input.terminalId);
450 let session = this.sessions.get(sessionKey);
451 if (!session) {
452 const cols = input.cols ?? DEFAULT_OPEN_COLS;
453 const rows = input.rows ?? DEFAULT_OPEN_ROWS;
454 session = {
455 threadId: input.threadId,
456 terminalId: input.terminalId,
457 cwd: input.cwd,
458 status: "starting",
459 pid: null,
460 history: "",
461 exitCode: null,
462 exitSignal: null,
463 updatedAt: new Date().toISOString(),
464 cols,
465 rows,
466 process: null,
467 unsubscribeData: null,
468 unsubscribeExit: null,
469 hasRunningSubprocess: false,
470 runtimeEnv: normalizedRuntimeEnv(input.env),
471 };
472 this.sessions.set(sessionKey, session);
473 } else {
474 this.stopProcess(session);
475 session.cwd = input.cwd;
476 session.runtimeEnv = normalizedRuntimeEnv(input.env);
477 }
478
479 const cols = input.cols ?? session.cols;
480 const rows = input.rows ?? session.rows;
481
482 session.history = "";
483 await this.persistHistory(input.threadId, input.terminalId, session.history);
484 this.startSession(session, { ...input, cols, rows }, "restarted");
485 return this.snapshot(session);
486 });
487 }
488
489 async close(raw: TerminalCloseInput): Promise<void> {
490 const input = terminalCloseInputSchema.parse(raw);
491 await this.runWithThreadLock(input.threadId, async () => {
492 if (input.terminalId) {
493 await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true);
494 return;
495 }
496
497 const threadSessions = this.sessionsForThread(input.threadId);
498 for (const session of threadSessions) {
499 this.stopProcess(session);
500 this.sessions.delete(toSessionKey(session.threadId, session.terminalId));
501 }
502 await Promise.all(
503 threadSessions.map((session) =>
504 this.flushPersistQueue(session.threadId, session.terminalId),
505 ),
506 );
507
508 if (input.deleteHistory) {
509 await this.deleteAllHistoryForThread(input.threadId);
510 }
511 this.updateSubprocessPollingState();
512 });
513 }
514
515 dispose(): void {
516 this.stopSubprocessPolling();
517 const sessions = [...this.sessions.values()];
518 this.sessions.clear();
519 for (const session of sessions) {
520 this.stopProcess(session);
521 }
522 for (const timer of this.persistTimers.values()) {
523 clearTimeout(timer);
524 }
525 this.persistTimers.clear();
526 this.pendingPersistHistory.clear();
527 this.threadLocks.clear();
528 this.persistQueues.clear();
529 }
530
531 private startSession(
532 session: TerminalSessionState,
533 input: TerminalStartInput,
534 eventType: "started" | "restarted",
535 ): void {
536 this.stopProcess(session);
537
538 session.status = "starting";
539 session.cwd = input.cwd;
540 session.cols = input.cols;
541 session.rows = input.rows;
542 session.exitCode = null;
543 session.exitSignal = null;
544 session.hasRunningSubprocess = false;
545 session.updatedAt = new Date().toISOString();
546
547 let ptyProcess: PtyProcess | null = null;
548 let startedShell: string | null = null;
549 try {
550 const shellCandidates = resolveShellCandidates(this.shellResolver);
551 const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv);
552 let lastSpawnError: unknown = null;
553
554 for (const candidate of shellCandidates) {
555 try {
556 ptyProcess = this.ptyAdapter.spawn({
557 shell: candidate.shell,
558 ...(candidate.args ? { args: candidate.args } : {}),
559 cwd: session.cwd,
560 cols: session.cols,
561 rows: session.rows,
562 env: terminalEnv,
563 });
564 startedShell = formatShellCandidate(candidate);
565 break;
566 } catch (error) {
567 lastSpawnError = error;
568 if (!isRetryableShellSpawnError(error)) {
569 throw error;
570 }
571 }
572 }
573
574 if (!ptyProcess) {
575 const detail =
576 lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed";
577 const tried =
578 shellCandidates.length > 0
579 ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.`
580 : "";
581 throw new Error(`${detail}.${tried}`.trim());
582 }
583
584 session.process = ptyProcess;
585 session.pid = ptyProcess.pid;
586 session.status = "running";
587 session.updatedAt = new Date().toISOString();
588 session.unsubscribeData = ptyProcess.onData((data) => {
589 this.onProcessData(session, data);
590 });
591 session.unsubscribeExit = ptyProcess.onExit((event) => {
592 this.onProcessExit(session, event);
593 });
594 this.updateSubprocessPollingState();
595 this.emitEvent({
596 type: eventType,
597 threadId: session.threadId,
598 terminalId: session.terminalId,
599 createdAt: new Date().toISOString(),
600 snapshot: this.snapshot(session),
601 });
602 } catch (error) {
603 if (ptyProcess) {
604 try {
605 ptyProcess.kill();
606 } catch {
607 // Ignore kill errors during failed startup cleanup.
608 }
609 }
610 session.status = "error";
611 session.pid = null;
612 session.process = null;
613 session.hasRunningSubprocess = false;
614 session.updatedAt = new Date().toISOString();
615 this.updateSubprocessPollingState();
616 const message = error instanceof Error ? error.message : "Terminal start failed";
617 this.emitEvent({
618 type: "error",
619 threadId: session.threadId,
620 terminalId: session.terminalId,
621 createdAt: new Date().toISOString(),
622 message,
623 });
624 this.logger.error("failed to start terminal", {
625 threadId: session.threadId,
626 terminalId: session.terminalId,
627 error: message,
628 ...(startedShell ? { shell: startedShell } : {}),
629 });
630 }
631 }
632
633 private onProcessData(session: TerminalSessionState, data: string): void {
634 session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
635 session.updatedAt = new Date().toISOString();
636 this.queuePersist(session.threadId, session.terminalId, session.history);
637 this.emitEvent({
638 type: "output",
639 threadId: session.threadId,
640 terminalId: session.terminalId,
641 createdAt: new Date().toISOString(),
642 data,
643 });
644 }
645
646 private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void {
647 this.cleanupProcessHandles(session);
648 session.process = null;
649 session.pid = null;
650 session.hasRunningSubprocess = false;
651 session.status = "exited";
652 session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
653 session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
654 session.updatedAt = new Date().toISOString();
655 this.emitEvent({
656 type: "exited",
657 threadId: session.threadId,
658 terminalId: session.terminalId,
659 createdAt: new Date().toISOString(),
660 exitCode: session.exitCode,
661 exitSignal: session.exitSignal,
662 });
663 this.updateSubprocessPollingState();
664 }
665
666 private stopProcess(session: TerminalSessionState): void {
667 const process = session.process;
668 if (!process) return;
669 this.cleanupProcessHandles(session);
670 session.process = null;
671 session.pid = null;
672 session.hasRunningSubprocess = false;
673 session.status = "exited";
674 session.updatedAt = new Date().toISOString();
675 try {
676 process.kill();
677 } catch (error) {
678 const message = error instanceof Error ? error.message : String(error);
679 this.logger.warn("failed to kill terminal process", {
680 threadId: session.threadId,
681 terminalId: session.terminalId,
682 error: message,
683 });
684 }
685 this.updateSubprocessPollingState();
686 }
687
688 private cleanupProcessHandles(session: TerminalSessionState): void {
689 session.unsubscribeData?.();
690 session.unsubscribeData = null;
691 session.unsubscribeExit?.();
692 session.unsubscribeExit = null;
693 }
694
695 private queuePersist(threadId: string, terminalId: string, history: string): void {
696 const persistenceKey = toSessionKey(threadId, terminalId);
697 this.pendingPersistHistory.set(persistenceKey, history);
698 this.schedulePersist(threadId, terminalId);
699 }
700
701 private async persistHistory(
702 threadId: string,
703 terminalId: string,
704 history: string,
705 ): Promise<void> {
706 const persistenceKey = toSessionKey(threadId, terminalId);
707 this.clearPersistTimer(threadId, terminalId);
708 this.pendingPersistHistory.delete(persistenceKey);
709 await this.enqueuePersistWrite(threadId, terminalId, history);
710 }
711
712 private enqueuePersistWrite(
713 threadId: string,
714 terminalId: string,
715 history: string,
716 ): Promise<void> {
717 const persistenceKey = toSessionKey(threadId, terminalId);
718 const task = async () => {
719 await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8");
720 };
721 const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve();
722 const next = previous
723 .catch(() => undefined)
724 .then(task)
725 .catch((error) => {
726 this.logger.warn("failed to persist terminal history", {
727 threadId,
728 terminalId,
729 error: error instanceof Error ? error.message : String(error),
730 });
731 });
732 this.persistQueues.set(persistenceKey, next);
733 const finalized = next.finally(() => {
734 if (this.persistQueues.get(persistenceKey) === next) {
735 this.persistQueues.delete(persistenceKey);
736 }
737 if (
738 this.pendingPersistHistory.has(persistenceKey) &&
739 !this.persistTimers.has(persistenceKey)
740 ) {
741 this.schedulePersist(threadId, terminalId);
742 }
743 });
744 void finalized.catch(() => undefined);
745 return finalized;
746 }
747
748 private schedulePersist(threadId: string, terminalId: string): void {
749 const persistenceKey = toSessionKey(threadId, terminalId);
750 if (this.persistTimers.has(persistenceKey)) return;
751 const timer = setTimeout(() => {
752 this.persistTimers.delete(persistenceKey);
753 const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
754 if (pendingHistory === undefined) return;
755 this.pendingPersistHistory.delete(persistenceKey);
756 void this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
757 }, this.persistDebounceMs);
758 this.persistTimers.set(persistenceKey, timer);
759 }
760
761 private clearPersistTimer(threadId: string, terminalId: string): void {
762 const persistenceKey = toSessionKey(threadId, terminalId);
763 const timer = this.persistTimers.get(persistenceKey);
764 if (!timer) return;
765 clearTimeout(timer);
766 this.persistTimers.delete(persistenceKey);
767 }
768
769 private async readHistory(threadId: string, terminalId: string): Promise<string> {
770 const nextPath = this.historyPath(threadId, terminalId);
771 try {
772 const raw = await fs.promises.readFile(nextPath, "utf8");
773 const capped = capHistory(raw, this.historyLineLimit);
774 if (capped !== raw) {
775 await fs.promises.writeFile(nextPath, capped, "utf8");
776 }
777 return capped;
778 } catch (error) {
779 if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
780 throw error;
781 }
782 }
783
784 if (terminalId !== DEFAULT_TERMINAL_ID) {
785 return "";
786 }
787
788 const legacyPath = this.legacyHistoryPath(threadId);
789 try {
790 const raw = await fs.promises.readFile(legacyPath, "utf8");
791 const capped = capHistory(raw, this.historyLineLimit);
792
793 // Migrate legacy transcript filename to the terminal-scoped path.
794 await fs.promises.writeFile(nextPath, capped, "utf8");
795 try {
796 await fs.promises.rm(legacyPath, { force: true });
797 } catch (cleanupError) {
798 this.logger.warn("failed to remove legacy terminal history", {
799 threadId,
800 error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
801 });
802 }
803
804 return capped;
805 } catch (error) {
806 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
807 return "";
808 }
809 throw error;
810 }
811 }
812
813 private async deleteHistory(threadId: string, terminalId: string): Promise<void> {
814 const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })];
815 if (terminalId === DEFAULT_TERMINAL_ID) {
816 deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true }));
817 }
818 try {
819 await Promise.all(deletions);
820 } catch (error) {
821 this.logger.warn("failed to delete terminal history", {
822 threadId,
823 terminalId,
824 error: error instanceof Error ? error.message : String(error),
825 });
826 }
827 }
828
829 private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> {
830 const persistenceKey = toSessionKey(threadId, terminalId);
831 this.clearPersistTimer(threadId, terminalId);
832
833 while (true) {
834 const pendingHistory = this.pendingPersistHistory.get(persistenceKey);
835 if (pendingHistory !== undefined) {
836 this.pendingPersistHistory.delete(persistenceKey);
837 await this.enqueuePersistWrite(threadId, terminalId, pendingHistory);
838 }
839
840 const pending = this.persistQueues.get(persistenceKey);
841 if (!pending) {
842 return;
843 }
844 await pending.catch(() => undefined);
845 }
846 }
847
848 private updateSubprocessPollingState(): void {
849 const hasRunningSessions = [...this.sessions.values()].some(
850 (session) => session.status === "running" && session.pid !== null,
851 );
852 if (hasRunningSessions) {
853 this.ensureSubprocessPolling();
854 return;
855 }
856 this.stopSubprocessPolling();
857 }
858
859 private ensureSubprocessPolling(): void {
860 if (this.subprocessPollTimer) return;
861 this.subprocessPollTimer = setInterval(() => {
862 void this.pollSubprocessActivity();
863 }, this.subprocessPollIntervalMs);
864 this.subprocessPollTimer.unref?.();
865 void this.pollSubprocessActivity();
866 }
867
868 private stopSubprocessPolling(): void {
869 if (!this.subprocessPollTimer) return;
870 clearInterval(this.subprocessPollTimer);
871 this.subprocessPollTimer = null;
872 }
873
874 private async pollSubprocessActivity(): Promise<void> {
875 if (this.subprocessPollInFlight) return;
876
877 const runningSessions = [...this.sessions.values()].filter(
878 (session): session is TerminalSessionState & { pid: number } =>
879 session.status === "running" && Number.isInteger(session.pid),
880 );
881 if (runningSessions.length === 0) {
882 this.stopSubprocessPolling();
883 return;
884 }
885
886 this.subprocessPollInFlight = true;
887 try {
888 await Promise.all(
889 runningSessions.map(async (session) => {
890 const terminalPid = session.pid;
891 let hasRunningSubprocess = false;
892 try {
893 hasRunningSubprocess = await this.subprocessChecker(terminalPid);
894 } catch (error) {
895 this.logger.warn("failed to check terminal subprocess activity", {
896 threadId: session.threadId,
897 terminalId: session.terminalId,
898 terminalPid,
899 error: error instanceof Error ? error.message : String(error),
900 });
901 return;
902 }
903
904 const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId));
905 if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) {
906 return;
907 }
908 if (liveSession.hasRunningSubprocess === hasRunningSubprocess) {
909 return;
910 }
911
912 liveSession.hasRunningSubprocess = hasRunningSubprocess;
913 liveSession.updatedAt = new Date().toISOString();
914 this.emitEvent({
915 type: "activity",
916 threadId: liveSession.threadId,
917 terminalId: liveSession.terminalId,
918 createdAt: new Date().toISOString(),
919 hasRunningSubprocess,
920 });
921 }),
922 );
923 } finally {
924 this.subprocessPollInFlight = false;
925 }
926 }
927
928 private async assertValidCwd(cwd: string): Promise<void> {
929 let stats: fs.Stats;
930 try {
931 stats = await fs.promises.stat(cwd);
932 } catch (error) {
933 if ((error as NodeJS.ErrnoException).code === "ENOENT") {
934 throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error });
935 }
936 throw error;
937 }
938 if (!stats.isDirectory()) {
939 throw new Error(`Terminal cwd is not a directory: ${cwd}`);
940 }
941 }
942
943 private async closeSession(
944 threadId: string,
945 terminalId: string,
946 deleteHistory: boolean,
947 ): Promise<void> {
948 const key = toSessionKey(threadId, terminalId);
949 const session = this.sessions.get(key);
950 if (session) {
951 this.stopProcess(session);
952 this.sessions.delete(key);
953 }
954 this.updateSubprocessPollingState();
955 await this.flushPersistQueue(threadId, terminalId);
956 if (deleteHistory) {
957 await this.deleteHistory(threadId, terminalId);
958 }
959 }
960
961 private sessionsForThread(threadId: string): TerminalSessionState[] {
962 return [...this.sessions.values()].filter((session) => session.threadId === threadId);
963 }
964
965 private async deleteAllHistoryForThread(threadId: string): Promise<void> {
966 const threadPrefix = `${toSafeThreadId(threadId)}_`;
967 try {
968 const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true });
969 const removals = entries
970 .filter((entry) => entry.isFile())
971 .map((entry) => entry.name)
972 .filter(
973 (name) =>
974 name === `${toSafeThreadId(threadId)}.log` ||
975 name === `${legacySafeThreadId(threadId)}.log` ||
976 name.startsWith(threadPrefix),
977 )
978 .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true }));
979 await Promise.all(removals);
980 } catch (error) {
981 this.logger.warn("failed to delete terminal histories for thread", {
982 threadId,
983 error: error instanceof Error ? error.message : String(error),
984 });
985 }
986 }
987
988 private requireSession(threadId: string, terminalId: string): TerminalSessionState {
989 const session = this.sessions.get(toSessionKey(threadId, terminalId));
990 if (!session) {
991 throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`);
992 }
993 return session;
994 }
995
996 private snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
997 return {
998 threadId: session.threadId,
999 terminalId: session.terminalId,
1000 cwd: session.cwd,
1001 status: session.status,
1002 pid: session.pid,
1003 history: session.history,
1004 exitCode: session.exitCode,
1005 exitSignal: session.exitSignal,
1006 updatedAt: session.updatedAt,
1007 };
1008 }
1009
1010 private emitEvent(event: TerminalEvent): void {
1011 this.emit("event", event);
1012 }
1013
1014 private historyPath(threadId: string, terminalId: string): string {
1015 const threadPart = toSafeThreadId(threadId);
1016 if (terminalId === DEFAULT_TERMINAL_ID) {
1017 return path.join(this.logsDir, `${threadPart}.log`);
1018 }
1019 return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);
1020 }
1021
1022 private legacyHistoryPath(threadId: string): string {
1023 return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`);
1024 }
1025
1026 private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> {
1027 const previous = this.threadLocks.get(threadId) ?? Promise.resolve();
1028 let release: () => void = () => {};
1029 const current = new Promise<void>((resolve) => {
1030 release = resolve;
1031 });
1032 this.threadLocks.set(threadId, current);
1033 await previous.catch(() => undefined);
1034 try {
1035 return await task();
1036 } finally {
1037 release();
1038 if (this.threadLocks.get(threadId) === current) {
1039 this.threadLocks.delete(threadId);
1040 }
1041 }
1042 }
1043}