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