| ... | ... | @@ -1,32 +1,44 @@ |
| 1 | | import { EventEmitter } from "node:events"; |
| 2 | | import fs from "node:fs"; |
| 3 | 1 | import path from "node:path"; |
| 4 | 2 | |
| 5 | 3 | import { |
| 6 | 4 | DEFAULT_TERMINAL_ID, |
| 7 | | TerminalClearInput, |
| 8 | | TerminalCloseInput, |
| 9 | | TerminalOpenInput, |
| 10 | | TerminalResizeInput, |
| 11 | | TerminalRestartInput, |
| 12 | | TerminalWriteInput, |
| 13 | 5 | type TerminalEvent, |
| 14 | 6 | type TerminalSessionSnapshot, |
| 7 | type TerminalSessionStatus, |
| 15 | 8 | } from "@t3tools/contracts"; |
| 16 | | import { Effect, Encoding, Layer, Schema } from "effect"; |
| 9 | import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; |
| 10 | import { |
| 11 | Data, |
| 12 | Effect, |
| 13 | Encoding, |
| 14 | Equal, |
| 15 | Exit, |
| 16 | Fiber, |
| 17 | FileSystem, |
| 18 | Layer, |
| 19 | Option, |
| 20 | Scope, |
| 21 | Semaphore, |
| 22 | SynchronizedRef, |
| 23 | } from "effect"; |
| 17 | 24 | |
| 18 | | import { createLogger } from "../../logger"; |
| 19 | | import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY"; |
| 20 | | import { runProcess } from "../../processRunner"; |
| 21 | 25 | import { ServerConfig } from "../../config"; |
| 26 | import { runProcess } from "../../processRunner"; |
| 22 | 27 | import { |
| 23 | | ShellCandidate, |
| 24 | | TerminalError, |
| 28 | TerminalCwdError, |
| 29 | TerminalHistoryError, |
| 25 | 30 | TerminalManager, |
| 26 | | TerminalManagerShape, |
| 27 | | TerminalSessionState, |
| 28 | | TerminalStartInput, |
| 31 | TerminalNotRunningError, |
| 32 | TerminalSessionLookupError, |
| 33 | type TerminalManagerShape, |
| 29 | 34 | } from "../Services/Manager"; |
| 35 | import { |
| 36 | PtyAdapter, |
| 37 | PtySpawnError, |
| 38 | type PtyAdapterShape, |
| 39 | type PtyExitEvent, |
| 40 | type PtyProcess, |
| 41 | } from "../Services/PTY"; |
| 30 | 42 | |
| 31 | 43 | const DEFAULT_HISTORY_LINE_LIMIT = 5_000; |
| 32 | 44 | const DEFAULT_PERSIST_DEBOUNCE_MS = 40; |
| ... | ... | @@ -37,14 +49,128 @@ const DEFAULT_OPEN_COLS = 120; |
| 37 | 49 | const DEFAULT_OPEN_ROWS = 30; |
| 38 | 50 | const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); |
| 39 | 51 | |
| 40 | | const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput); |
| 41 | | const decodeTerminalRestartInput = Schema.decodeUnknownSync(TerminalRestartInput); |
| 42 | | const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput); |
| 43 | | const decodeTerminalResizeInput = Schema.decodeUnknownSync(TerminalResizeInput); |
| 44 | | const decodeTerminalClearInput = Schema.decodeUnknownSync(TerminalClearInput); |
| 45 | | const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput); |
| 52 | type TerminalSubprocessChecker = ( |
| 53 | terminalPid: number, |
| 54 | ) => Effect.Effect<boolean, TerminalSubprocessCheckError>; |
| 55 | |
| 56 | class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{ |
| 57 | readonly message: string; |
| 58 | readonly cause?: unknown; |
| 59 | readonly terminalPid: number; |
| 60 | readonly command: "powershell" | "pgrep" | "ps"; |
| 61 | }> {} |
| 62 | |
| 63 | class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{ |
| 64 | readonly message: string; |
| 65 | readonly cause?: unknown; |
| 66 | readonly signal: "SIGTERM" | "SIGKILL"; |
| 67 | }> {} |
| 68 | |
| 69 | interface ShellCandidate { |
| 70 | shell: string; |
| 71 | args?: string[]; |
| 72 | } |
| 73 | |
| 74 | interface TerminalStartInput { |
| 75 | threadId: string; |
| 76 | terminalId: string; |
| 77 | cwd: string; |
| 78 | cols: number; |
| 79 | rows: number; |
| 80 | env?: Record<string, string>; |
| 81 | } |
| 82 | |
| 83 | interface TerminalSessionState { |
| 84 | threadId: string; |
| 85 | terminalId: string; |
| 86 | cwd: string; |
| 87 | status: TerminalSessionStatus; |
| 88 | pid: number | null; |
| 89 | history: string; |
| 90 | pendingHistoryControlSequence: string; |
| 91 | pendingProcessEvents: Array<PendingProcessEvent>; |
| 92 | pendingProcessEventIndex: number; |
| 93 | processEventDrainRunning: boolean; |
| 94 | exitCode: number | null; |
| 95 | exitSignal: number | null; |
| 96 | updatedAt: string; |
| 97 | cols: number; |
| 98 | rows: number; |
| 99 | process: PtyProcess | null; |
| 100 | unsubscribeData: (() => void) | null; |
| 101 | unsubscribeExit: (() => void) | null; |
| 102 | hasRunningSubprocess: boolean; |
| 103 | runtimeEnv: Record<string, string> | null; |
| 104 | } |
| 105 | |
| 106 | interface PersistHistoryRequest { |
| 107 | history: string; |
| 108 | immediate: boolean; |
| 109 | } |
| 110 | |
| 111 | type PendingProcessEvent = { type: "output"; data: string } | { type: "exit"; event: PtyExitEvent }; |
| 112 | |
| 113 | type DrainProcessEventAction = |
| 114 | | { type: "idle" } |
| 115 | | { |
| 116 | type: "output"; |
| 117 | threadId: string; |
| 118 | terminalId: string; |
| 119 | history: string | null; |
| 120 | data: string; |
| 121 | } |
| 122 | | { |
| 123 | type: "exit"; |
| 124 | process: PtyProcess | null; |
| 125 | threadId: string; |
| 126 | terminalId: string; |
| 127 | exitCode: number | null; |
| 128 | exitSignal: number | null; |
| 129 | }; |
| 130 | |
| 131 | interface TerminalManagerState { |
| 132 | sessions: Map<string, TerminalSessionState>; |
| 133 | killFibers: Map<PtyProcess, Fiber.Fiber<void, never>>; |
| 134 | } |
| 135 | |
| 136 | function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { |
| 137 | return { |
| 138 | threadId: session.threadId, |
| 139 | terminalId: session.terminalId, |
| 140 | cwd: session.cwd, |
| 141 | status: session.status, |
| 142 | pid: session.pid, |
| 143 | history: session.history, |
| 144 | exitCode: session.exitCode, |
| 145 | exitSignal: session.exitSignal, |
| 146 | updatedAt: session.updatedAt, |
| 147 | }; |
| 148 | } |
| 149 | |
| 150 | function cleanupProcessHandles(session: TerminalSessionState): void { |
| 151 | session.unsubscribeData?.(); |
| 152 | session.unsubscribeData = null; |
| 153 | session.unsubscribeExit?.(); |
| 154 | session.unsubscribeExit = null; |
| 155 | } |
| 156 | |
| 157 | function enqueueProcessEvent( |
| 158 | session: TerminalSessionState, |
| 159 | expectedPid: number, |
| 160 | event: PendingProcessEvent, |
| 161 | ): boolean { |
| 162 | if (!session.process || session.status !== "running" || session.pid !== expectedPid) { |
| 163 | return false; |
| 164 | } |
| 165 | |
| 166 | session.pendingProcessEvents.push(event); |
| 167 | if (session.processEventDrainRunning) { |
| 168 | return false; |
| 169 | } |
| 46 | 170 | |
| 47 | | type TerminalSubprocessChecker = (terminalPid: number) => Promise<boolean>; |
| 171 | session.processEventDrainRunning = true; |
| 172 | return true; |
| 173 | } |
| 48 | 174 | |
| 49 | 175 | function defaultShellResolver(): string { |
| 50 | 176 | if (process.platform === "win32") { |
| ... | ... | @@ -118,7 +244,7 @@ function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] { |
| 118 | 244 | ]); |
| 119 | 245 | } |
| 120 | 246 | |
| 121 | | function isRetryableShellSpawnError(error: unknown): boolean { |
| 247 | function isRetryableShellSpawnError(error: PtySpawnError): boolean { |
| 122 | 248 | const queue: unknown[] = [error]; |
| 123 | 249 | const seen = new Set<unknown>(); |
| 124 | 250 | const messages: string[] = []; |
| ... | ... | @@ -165,82 +291,107 @@ function isRetryableShellSpawnError(error: unknown): boolean { |
| 165 | 291 | ); |
| 166 | 292 | } |
| 167 | 293 | |
| 168 | | async function checkWindowsSubprocessActivity(terminalPid: number): Promise<boolean> { |
| 294 | function checkWindowsSubprocessActivity( |
| 295 | terminalPid: number, |
| 296 | ): Effect.Effect<boolean, TerminalSubprocessCheckError> { |
| 169 | 297 | const command = [ |
| 170 | 298 | `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`, |
| 171 | 299 | "if ($children) { exit 0 }", |
| 172 | 300 | "exit 1", |
| 173 | 301 | ].join("; "); |
| 174 | | try { |
| 175 | | const result = await runProcess( |
| 176 | | "powershell.exe", |
| 177 | | ["-NoProfile", "-NonInteractive", "-Command", command], |
| 178 | | { |
| 302 | return Effect.tryPromise({ |
| 303 | try: () => |
| 304 | runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { |
| 179 | 305 | timeoutMs: 1_500, |
| 180 | 306 | allowNonZeroExit: true, |
| 181 | 307 | maxBufferBytes: 32_768, |
| 182 | 308 | outputMode: "truncate", |
| 183 | | }, |
| 184 | | ); |
| 185 | | return result.code === 0; |
| 186 | | } catch { |
| 187 | | return false; |
| 188 | | } |
| 309 | }), |
| 310 | catch: (cause) => |
| 311 | new TerminalSubprocessCheckError({ |
| 312 | message: "Failed to check Windows terminal subprocess activity.", |
| 313 | cause, |
| 314 | terminalPid, |
| 315 | command: "powershell", |
| 316 | }), |
| 317 | }).pipe(Effect.map((result) => result.code === 0)); |
| 189 | 318 | } |
| 190 | 319 | |
| 191 | | async function checkPosixSubprocessActivity(terminalPid: number): Promise<boolean> { |
| 192 | | try { |
| 193 | | const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], { |
| 194 | | timeoutMs: 1_000, |
| 195 | | allowNonZeroExit: true, |
| 196 | | maxBufferBytes: 32_768, |
| 197 | | outputMode: "truncate", |
| 198 | | }); |
| 199 | | if (pgrepResult.code === 0) { |
| 200 | | return pgrepResult.stdout.trim().length > 0; |
| 320 | const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* ( |
| 321 | terminalPid: number, |
| 322 | ): Effect.fn.Return<boolean, TerminalSubprocessCheckError> { |
| 323 | const runPgrep = Effect.tryPromise({ |
| 324 | try: () => |
| 325 | runProcess("pgrep", ["-P", String(terminalPid)], { |
| 326 | timeoutMs: 1_000, |
| 327 | allowNonZeroExit: true, |
| 328 | maxBufferBytes: 32_768, |
| 329 | outputMode: "truncate", |
| 330 | }), |
| 331 | catch: (cause) => |
| 332 | new TerminalSubprocessCheckError({ |
| 333 | message: "Failed to inspect terminal subprocesses with pgrep.", |
| 334 | cause, |
| 335 | terminalPid, |
| 336 | command: "pgrep", |
| 337 | }), |
| 338 | }); |
| 339 | |
| 340 | const runPs = Effect.tryPromise({ |
| 341 | try: () => |
| 342 | runProcess("ps", ["-eo", "pid=,ppid="], { |
| 343 | timeoutMs: 1_000, |
| 344 | allowNonZeroExit: true, |
| 345 | maxBufferBytes: 262_144, |
| 346 | outputMode: "truncate", |
| 347 | }), |
| 348 | catch: (cause) => |
| 349 | new TerminalSubprocessCheckError({ |
| 350 | message: "Failed to inspect terminal subprocesses with ps.", |
| 351 | cause, |
| 352 | terminalPid, |
| 353 | command: "ps", |
| 354 | }), |
| 355 | }); |
| 356 | |
| 357 | const pgrepResult = yield* Effect.exit(runPgrep); |
| 358 | if (pgrepResult._tag === "Success") { |
| 359 | if (pgrepResult.value.code === 0) { |
| 360 | return pgrepResult.value.stdout.trim().length > 0; |
| 201 | 361 | } |
| 202 | | if (pgrepResult.code === 1) { |
| 362 | if (pgrepResult.value.code === 1) { |
| 203 | 363 | return false; |
| 204 | 364 | } |
| 205 | | } catch { |
| 206 | | // Fall back to ps when pgrep is unavailable. |
| 207 | 365 | } |
| 208 | 366 | |
| 209 | | try { |
| 210 | | const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], { |
| 211 | | timeoutMs: 1_000, |
| 212 | | allowNonZeroExit: true, |
| 213 | | maxBufferBytes: 262_144, |
| 214 | | outputMode: "truncate", |
| 215 | | }); |
| 216 | | if (psResult.code !== 0) { |
| 217 | | return false; |
| 218 | | } |
| 367 | const psResult = yield* Effect.exit(runPs); |
| 368 | if (psResult._tag === "Failure" || psResult.value.code !== 0) { |
| 369 | return false; |
| 370 | } |
| 219 | 371 | |
| 220 | | for (const line of psResult.stdout.split(/\r?\n/g)) { |
| 221 | | const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); |
| 222 | | const pid = Number(pidRaw); |
| 223 | | const ppid = Number(ppidRaw); |
| 224 | | if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; |
| 225 | | if (ppid === terminalPid) { |
| 226 | | return true; |
| 227 | | } |
| 372 | for (const line of psResult.value.stdout.split(/\r?\n/g)) { |
| 373 | const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); |
| 374 | const pid = Number(pidRaw); |
| 375 | const ppid = Number(ppidRaw); |
| 376 | if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; |
| 377 | if (ppid === terminalPid) { |
| 378 | return true; |
| 228 | 379 | } |
| 229 | | return false; |
| 230 | | } catch { |
| 231 | | return false; |
| 232 | 380 | } |
| 233 | | } |
| 381 | return false; |
| 382 | }); |
| 234 | 383 | |
| 235 | | async function defaultSubprocessChecker(terminalPid: number): Promise<boolean> { |
| 384 | const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* ( |
| 385 | terminalPid: number, |
| 386 | ): Effect.fn.Return<boolean, TerminalSubprocessCheckError> { |
| 236 | 387 | if (!Number.isInteger(terminalPid) || terminalPid <= 0) { |
| 237 | 388 | return false; |
| 238 | 389 | } |
| 239 | 390 | if (process.platform === "win32") { |
| 240 | | return checkWindowsSubprocessActivity(terminalPid); |
| 391 | return yield* checkWindowsSubprocessActivity(terminalPid); |
| 241 | 392 | } |
| 242 | | return checkPosixSubprocessActivity(terminalPid); |
| 243 | | } |
| 393 | return yield* checkPosixSubprocessActivity(terminalPid); |
| 394 | }); |
| 244 | 395 | |
| 245 | 396 | function capHistory(history: string, maxLines: number): string { |
| 246 | 397 | if (history.length === 0) return history; |
| ... | ... | @@ -482,12 +633,8 @@ function normalizedRuntimeEnv( |
| 482 | 633 | return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right))); |
| 483 | 634 | } |
| 484 | 635 | |
| 485 | | interface TerminalManagerEvents { |
| 486 | | event: [event: TerminalEvent]; |
| 487 | | } |
| 488 | | |
| 489 | 636 | interface TerminalManagerOptions { |
| 490 | | logsDir?: string; |
| 637 | logsDir: string; |
| 491 | 638 | historyLineLimit?: number; |
| 492 | 639 | ptyAdapter: PtyAdapterShape; |
| 493 | 640 | shellResolver?: () => string; |
| ... | ... | @@ -497,917 +644,1192 @@ interface TerminalManagerOptions { |
| 497 | 644 | maxRetainedInactiveSessions?: number; |
| 498 | 645 | } |
| 499 | 646 | |
| 500 | | export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents> { |
| 501 | | private readonly sessions = new Map<string, TerminalSessionState>(); |
| 502 | | private readonly logsDir: string; |
| 503 | | private readonly historyLineLimit: number; |
| 504 | | private readonly ptyAdapter: PtyAdapterShape; |
| 505 | | private readonly shellResolver: () => string; |
| 506 | | private readonly persistQueues = new Map<string, Promise<void>>(); |
| 507 | | private readonly persistTimers = new Map<string, ReturnType<typeof setTimeout>>(); |
| 508 | | private readonly pendingPersistHistory = new Map<string, string>(); |
| 509 | | private readonly threadLocks = new Map<string, Promise<void>>(); |
| 510 | | private readonly persistDebounceMs: number; |
| 511 | | private readonly subprocessChecker: TerminalSubprocessChecker; |
| 512 | | private readonly subprocessPollIntervalMs: number; |
| 513 | | private readonly processKillGraceMs: number; |
| 514 | | private readonly maxRetainedInactiveSessions: number; |
| 515 | | private subprocessPollTimer: ReturnType<typeof setInterval> | null = null; |
| 516 | | private subprocessPollInFlight = false; |
| 517 | | private readonly killEscalationTimers = new Map<PtyProcess, ReturnType<typeof setTimeout>>(); |
| 518 | | private readonly logger = createLogger("terminal"); |
| 519 | | |
| 520 | | constructor(options: TerminalManagerOptions) { |
| 521 | | super(); |
| 522 | | this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals"); |
| 523 | | this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; |
| 524 | | this.ptyAdapter = options.ptyAdapter; |
| 525 | | this.shellResolver = options.shellResolver ?? defaultShellResolver; |
| 526 | | this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS; |
| 527 | | this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; |
| 528 | | this.subprocessPollIntervalMs = |
| 647 | const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () { |
| 648 | const { terminalLogsDir } = yield* ServerConfig; |
| 649 | const ptyAdapter = yield* PtyAdapter; |
| 650 | return yield* makeTerminalManagerWithOptions({ |
| 651 | logsDir: terminalLogsDir, |
| 652 | ptyAdapter, |
| 653 | }); |
| 654 | }); |
| 655 | |
| 656 | export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWithOptions")( |
| 657 | function* (options: TerminalManagerOptions) { |
| 658 | const fileSystem = yield* FileSystem.FileSystem; |
| 659 | const services = yield* Effect.services(); |
| 660 | const runFork = Effect.runForkWith(services); |
| 661 | |
| 662 | const logsDir = options.logsDir; |
| 663 | const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; |
| 664 | const shellResolver = options.shellResolver ?? defaultShellResolver; |
| 665 | const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; |
| 666 | const subprocessPollIntervalMs = |
| 529 | 667 | options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; |
| 530 | | this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; |
| 531 | | this.maxRetainedInactiveSessions = |
| 668 | const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; |
| 669 | const maxRetainedInactiveSessions = |
| 532 | 670 | options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS; |
| 533 | | fs.mkdirSync(this.logsDir, { recursive: true }); |
| 534 | | } |
| 535 | 671 | |
| 536 | | async open(raw: TerminalOpenInput): Promise<TerminalSessionSnapshot> { |
| 537 | | const input = decodeTerminalOpenInput(raw); |
| 538 | | return this.runWithThreadLock(input.threadId, async () => { |
| 539 | | await this.assertValidCwd(input.cwd); |
| 540 | | |
| 541 | | const sessionKey = toSessionKey(input.threadId, input.terminalId); |
| 542 | | const existing = this.sessions.get(sessionKey); |
| 543 | | if (!existing) { |
| 544 | | await this.flushPersistQueue(input.threadId, input.terminalId); |
| 545 | | const history = await this.readHistory(input.threadId, input.terminalId); |
| 546 | | const cols = input.cols ?? DEFAULT_OPEN_COLS; |
| 547 | | const rows = input.rows ?? DEFAULT_OPEN_ROWS; |
| 548 | | const session: TerminalSessionState = { |
| 549 | | threadId: input.threadId, |
| 550 | | terminalId: input.terminalId, |
| 551 | | cwd: input.cwd, |
| 552 | | status: "starting", |
| 553 | | pid: null, |
| 554 | | history, |
| 555 | | pendingHistoryControlSequence: "", |
| 556 | | exitCode: null, |
| 557 | | exitSignal: null, |
| 558 | | updatedAt: new Date().toISOString(), |
| 559 | | cols, |
| 560 | | rows, |
| 561 | | process: null, |
| 562 | | unsubscribeData: null, |
| 563 | | unsubscribeExit: null, |
| 564 | | hasRunningSubprocess: false, |
| 565 | | runtimeEnv: normalizedRuntimeEnv(input.env), |
| 566 | | }; |
| 567 | | this.sessions.set(sessionKey, session); |
| 568 | | this.evictInactiveSessionsIfNeeded(); |
| 569 | | await this.startSession(session, { ...input, cols, rows }, "started"); |
| 570 | | return this.snapshot(session); |
| 571 | | } |
| 672 | yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); |
| 572 | 673 | |
| 573 | | const nextRuntimeEnv = normalizedRuntimeEnv(input.env); |
| 574 | | const currentRuntimeEnv = existing.runtimeEnv; |
| 575 | | const targetCols = input.cols ?? existing.cols; |
| 576 | | const targetRows = input.rows ?? existing.rows; |
| 577 | | const runtimeEnvChanged = |
| 578 | | JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv); |
| 579 | | |
| 580 | | if (existing.cwd !== input.cwd || runtimeEnvChanged) { |
| 581 | | this.stopProcess(existing); |
| 582 | | existing.cwd = input.cwd; |
| 583 | | existing.runtimeEnv = nextRuntimeEnv; |
| 584 | | existing.history = ""; |
| 585 | | existing.pendingHistoryControlSequence = ""; |
| 586 | | await this.persistHistory(existing.threadId, existing.terminalId, existing.history); |
| 587 | | } else if (existing.status === "exited" || existing.status === "error") { |
| 588 | | existing.runtimeEnv = nextRuntimeEnv; |
| 589 | | existing.history = ""; |
| 590 | | existing.pendingHistoryControlSequence = ""; |
| 591 | | await this.persistHistory(existing.threadId, existing.terminalId, existing.history); |
| 592 | | } else if (currentRuntimeEnv !== nextRuntimeEnv) { |
| 593 | | existing.runtimeEnv = nextRuntimeEnv; |
| 674 | const managerStateRef = yield* SynchronizedRef.make<TerminalManagerState>({ |
| 675 | sessions: new Map(), |
| 676 | killFibers: new Map(), |
| 677 | }); |
| 678 | const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>()); |
| 679 | const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>(); |
| 680 | const workerScope = yield* Scope.make("sequential"); |
| 681 | yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void)); |
| 682 | |
| 683 | const publishEvent = (event: TerminalEvent) => |
| 684 | Effect.gen(function* () { |
| 685 | for (const listener of terminalEventListeners) { |
| 686 | yield* listener(event).pipe(Effect.ignoreCause({ log: true })); |
| 687 | } |
| 688 | }); |
| 689 | |
| 690 | const historyPath = (threadId: string, terminalId: string) => { |
| 691 | const threadPart = toSafeThreadId(threadId); |
| 692 | if (terminalId === DEFAULT_TERMINAL_ID) { |
| 693 | return path.join(logsDir, `${threadPart}.log`); |
| 594 | 694 | } |
| 695 | return path.join(logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); |
| 696 | }; |
| 697 | |
| 698 | const legacyHistoryPath = (threadId: string) => |
| 699 | path.join(logsDir, `${legacySafeThreadId(threadId)}.log`); |
| 595 | 700 | |
| 596 | | if (!existing.process) { |
| 597 | | await this.startSession( |
| 598 | | existing, |
| 599 | | { ...input, cols: targetCols, rows: targetRows }, |
| 600 | | "started", |
| 701 | const toTerminalHistoryError = |
| 702 | (operation: "read" | "truncate" | "migrate", threadId: string, terminalId: string) => |
| 703 | (cause: unknown) => |
| 704 | new TerminalHistoryError({ |
| 705 | operation, |
| 706 | threadId, |
| 707 | terminalId, |
| 708 | cause, |
| 709 | }); |
| 710 | |
| 711 | const readManagerState = SynchronizedRef.get(managerStateRef); |
| 712 | |
| 713 | const modifyManagerState = <A>( |
| 714 | f: (state: TerminalManagerState) => readonly [A, TerminalManagerState], |
| 715 | ) => SynchronizedRef.modify(managerStateRef, f); |
| 716 | |
| 717 | const getThreadSemaphore = (threadId: string) => |
| 718 | SynchronizedRef.modifyEffect(threadLocksRef, (current) => { |
| 719 | const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr( |
| 720 | current.get(threadId), |
| 601 | 721 | ); |
| 602 | | return this.snapshot(existing); |
| 603 | | } |
| 722 | return Option.match(existing, { |
| 723 | onNone: () => |
| 724 | Semaphore.make(1).pipe( |
| 725 | Effect.map((semaphore) => { |
| 726 | const next = new Map(current); |
| 727 | next.set(threadId, semaphore); |
| 728 | return [semaphore, next] as const; |
| 729 | }), |
| 730 | ), |
| 731 | onSome: (semaphore) => Effect.succeed([semaphore, current] as const), |
| 732 | }); |
| 733 | }); |
| 604 | 734 | |
| 605 | | if (existing.cols !== targetCols || existing.rows !== targetRows) { |
| 606 | | existing.cols = targetCols; |
| 607 | | existing.rows = targetRows; |
| 608 | | existing.process.resize(targetCols, targetRows); |
| 609 | | existing.updatedAt = new Date().toISOString(); |
| 735 | const withThreadLock = <A, E, R>( |
| 736 | threadId: string, |
| 737 | effect: Effect.Effect<A, E, R>, |
| 738 | ): Effect.Effect<A, E, R> => |
| 739 | Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); |
| 740 | |
| 741 | const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* ( |
| 742 | process: PtyProcess | null, |
| 743 | ) { |
| 744 | if (!process) return; |
| 745 | const fiber: Option.Option<Fiber.Fiber<void, never>> = yield* modifyManagerState< |
| 746 | Option.Option<Fiber.Fiber<void, never>> |
| 747 | >((state) => { |
| 748 | const existing: Option.Option<Fiber.Fiber<void, never>> = Option.fromNullishOr( |
| 749 | state.killFibers.get(process), |
| 750 | ); |
| 751 | if (Option.isNone(existing)) { |
| 752 | return [Option.none<Fiber.Fiber<void, never>>(), state] as const; |
| 753 | } |
| 754 | const killFibers = new Map(state.killFibers); |
| 755 | killFibers.delete(process); |
| 756 | return [existing, { ...state, killFibers }] as const; |
| 757 | }); |
| 758 | if (Option.isSome(fiber)) { |
| 759 | yield* Fiber.interrupt(fiber.value).pipe(Effect.ignore); |
| 610 | 760 | } |
| 761 | }); |
| 611 | 762 | |
| 612 | | return this.snapshot(existing); |
| 763 | const registerKillFiber = Effect.fn("terminal.registerKillFiber")(function* ( |
| 764 | process: PtyProcess, |
| 765 | fiber: Fiber.Fiber<void, never>, |
| 766 | ) { |
| 767 | yield* modifyManagerState((state) => { |
| 768 | const killFibers = new Map(state.killFibers); |
| 769 | killFibers.set(process, fiber); |
| 770 | return [undefined, { ...state, killFibers }] as const; |
| 771 | }); |
| 613 | 772 | }); |
| 614 | | } |
| 615 | 773 | |
| 616 | | async write(raw: TerminalWriteInput): Promise<void> { |
| 617 | | const input = decodeTerminalWriteInput(raw); |
| 618 | | const session = this.requireSession(input.threadId, input.terminalId); |
| 619 | | if (!session.process || session.status !== "running") { |
| 620 | | if (session.status === "exited") { |
| 774 | const runKillEscalation = Effect.fn("terminal.runKillEscalation")(function* ( |
| 775 | process: PtyProcess, |
| 776 | threadId: string, |
| 777 | terminalId: string, |
| 778 | ) { |
| 779 | const terminated = yield* Effect.try({ |
| 780 | try: () => process.kill("SIGTERM"), |
| 781 | catch: (cause) => |
| 782 | new TerminalProcessSignalError({ |
| 783 | message: "Failed to send SIGTERM to terminal process.", |
| 784 | cause, |
| 785 | signal: "SIGTERM", |
| 786 | }), |
| 787 | }).pipe( |
| 788 | Effect.as(true), |
| 789 | Effect.catch((error) => |
| 790 | Effect.logWarning("failed to kill terminal process", { |
| 791 | threadId, |
| 792 | terminalId, |
| 793 | signal: "SIGTERM", |
| 794 | error: error.message, |
| 795 | }).pipe(Effect.as(false)), |
| 796 | ), |
| 797 | ); |
| 798 | if (!terminated) { |
| 621 | 799 | return; |
| 622 | 800 | } |
| 623 | | throw new Error( |
| 624 | | `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, |
| 801 | |
| 802 | yield* Effect.sleep(processKillGraceMs); |
| 803 | |
| 804 | yield* Effect.try({ |
| 805 | try: () => process.kill("SIGKILL"), |
| 806 | catch: (cause) => |
| 807 | new TerminalProcessSignalError({ |
| 808 | message: "Failed to send SIGKILL to terminal process.", |
| 809 | cause, |
| 810 | signal: "SIGKILL", |
| 811 | }), |
| 812 | }).pipe( |
| 813 | Effect.catch((error) => |
| 814 | Effect.logWarning("failed to force-kill terminal process", { |
| 815 | threadId, |
| 816 | terminalId, |
| 817 | signal: "SIGKILL", |
| 818 | error: error.message, |
| 819 | }), |
| 820 | ), |
| 625 | 821 | ); |
| 626 | | } |
| 627 | | session.process.write(input.data); |
| 628 | | } |
| 822 | }); |
| 629 | 823 | |
| 630 | | async resize(raw: TerminalResizeInput): Promise<void> { |
| 631 | | const input = decodeTerminalResizeInput(raw); |
| 632 | | const session = this.requireSession(input.threadId, input.terminalId); |
| 633 | | if (!session.process || session.status !== "running") { |
| 634 | | throw new Error( |
| 635 | | `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, |
| 824 | const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* ( |
| 825 | process: PtyProcess, |
| 826 | threadId: string, |
| 827 | terminalId: string, |
| 828 | ) { |
| 829 | const fiber = yield* runKillEscalation(process, threadId, terminalId).pipe( |
| 830 | Effect.ensuring( |
| 831 | modifyManagerState((state) => { |
| 832 | if (!state.killFibers.has(process)) { |
| 833 | return [undefined, state] as const; |
| 834 | } |
| 835 | const killFibers = new Map(state.killFibers); |
| 836 | killFibers.delete(process); |
| 837 | return [undefined, { ...state, killFibers }] as const; |
| 838 | }), |
| 839 | ), |
| 840 | Effect.forkIn(workerScope), |
| 636 | 841 | ); |
| 637 | | } |
| 638 | | session.cols = input.cols; |
| 639 | | session.rows = input.rows; |
| 640 | | session.updatedAt = new Date().toISOString(); |
| 641 | | session.process.resize(input.cols, input.rows); |
| 642 | | } |
| 643 | 842 | |
| 644 | | async clear(raw: TerminalClearInput): Promise<void> { |
| 645 | | const input = decodeTerminalClearInput(raw); |
| 646 | | await this.runWithThreadLock(input.threadId, async () => { |
| 647 | | const session = this.requireSession(input.threadId, input.terminalId); |
| 648 | | session.history = ""; |
| 649 | | session.pendingHistoryControlSequence = ""; |
| 650 | | session.updatedAt = new Date().toISOString(); |
| 651 | | await this.persistHistory(input.threadId, input.terminalId, session.history); |
| 652 | | this.emitEvent({ |
| 653 | | type: "cleared", |
| 654 | | threadId: input.threadId, |
| 655 | | terminalId: input.terminalId, |
| 656 | | createdAt: new Date().toISOString(), |
| 843 | yield* registerKillFiber(process, fiber); |
| 844 | }); |
| 845 | |
| 846 | const persistWorker = yield* makeKeyedCoalescingWorker< |
| 847 | string, |
| 848 | PersistHistoryRequest, |
| 849 | never, |
| 850 | never |
| 851 | >({ |
| 852 | merge: (current, next) => ({ |
| 853 | history: next.history, |
| 854 | immediate: current.immediate || next.immediate, |
| 855 | }), |
| 856 | process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { |
| 857 | if (!request.immediate) { |
| 858 | yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS); |
| 859 | } |
| 860 | |
| 861 | const [threadId, terminalId] = sessionKey.split("\u0000"); |
| 862 | if (!threadId || !terminalId) { |
| 863 | return; |
| 864 | } |
| 865 | |
| 866 | yield* fileSystem.writeFileString(historyPath(threadId, terminalId), request.history).pipe( |
| 867 | Effect.catch((error) => |
| 868 | Effect.logWarning("failed to persist terminal history", { |
| 869 | threadId, |
| 870 | terminalId, |
| 871 | error: error instanceof Error ? error.message : String(error), |
| 872 | }), |
| 873 | ), |
| 874 | ); |
| 875 | }), |
| 876 | }); |
| 877 | |
| 878 | const queuePersist = Effect.fn("terminal.queuePersist")(function* ( |
| 879 | threadId: string, |
| 880 | terminalId: string, |
| 881 | history: string, |
| 882 | ) { |
| 883 | yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { |
| 884 | history, |
| 885 | immediate: false, |
| 657 | 886 | }); |
| 658 | 887 | }); |
| 659 | | } |
| 660 | 888 | |
| 661 | | async restart(raw: TerminalRestartInput): Promise<TerminalSessionSnapshot> { |
| 662 | | const input = decodeTerminalRestartInput(raw); |
| 663 | | return this.runWithThreadLock(input.threadId, async () => { |
| 664 | | await this.assertValidCwd(input.cwd); |
| 665 | | |
| 666 | | const sessionKey = toSessionKey(input.threadId, input.terminalId); |
| 667 | | let session = this.sessions.get(sessionKey); |
| 668 | | if (!session) { |
| 669 | | const cols = input.cols ?? DEFAULT_OPEN_COLS; |
| 670 | | const rows = input.rows ?? DEFAULT_OPEN_ROWS; |
| 671 | | session = { |
| 672 | | threadId: input.threadId, |
| 673 | | terminalId: input.terminalId, |
| 674 | | cwd: input.cwd, |
| 675 | | status: "starting", |
| 676 | | pid: null, |
| 677 | | history: "", |
| 678 | | pendingHistoryControlSequence: "", |
| 679 | | exitCode: null, |
| 680 | | exitSignal: null, |
| 681 | | updatedAt: new Date().toISOString(), |
| 682 | | cols, |
| 683 | | rows, |
| 684 | | process: null, |
| 685 | | unsubscribeData: null, |
| 686 | | unsubscribeExit: null, |
| 687 | | hasRunningSubprocess: false, |
| 688 | | runtimeEnv: normalizedRuntimeEnv(input.env), |
| 689 | | }; |
| 690 | | this.sessions.set(sessionKey, session); |
| 691 | | this.evictInactiveSessionsIfNeeded(); |
| 692 | | } else { |
| 693 | | this.stopProcess(session); |
| 694 | | session.cwd = input.cwd; |
| 695 | | session.runtimeEnv = normalizedRuntimeEnv(input.env); |
| 889 | const flushPersist = Effect.fn("terminal.flushPersist")(function* ( |
| 890 | threadId: string, |
| 891 | terminalId: string, |
| 892 | ) { |
| 893 | yield* persistWorker.drainKey(toSessionKey(threadId, terminalId)); |
| 894 | }); |
| 895 | |
| 896 | const persistHistory = Effect.fn("terminal.persistHistory")(function* ( |
| 897 | threadId: string, |
| 898 | terminalId: string, |
| 899 | history: string, |
| 900 | ) { |
| 901 | yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { |
| 902 | history, |
| 903 | immediate: true, |
| 904 | }); |
| 905 | yield* flushPersist(threadId, terminalId); |
| 906 | }); |
| 907 | |
| 908 | const readHistory = Effect.fn("terminal.readHistory")(function* ( |
| 909 | threadId: string, |
| 910 | terminalId: string, |
| 911 | ) { |
| 912 | const nextPath = historyPath(threadId, terminalId); |
| 913 | if ( |
| 914 | yield* fileSystem |
| 915 | .exists(nextPath) |
| 916 | .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))) |
| 917 | ) { |
| 918 | const raw = yield* fileSystem |
| 919 | .readFileString(nextPath) |
| 920 | .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))); |
| 921 | const capped = capHistory(raw, historyLineLimit); |
| 922 | if (capped !== raw) { |
| 923 | yield* fileSystem |
| 924 | .writeFileString(nextPath, capped) |
| 925 | .pipe(Effect.mapError(toTerminalHistoryError("truncate", threadId, terminalId))); |
| 926 | } |
| 927 | return capped; |
| 928 | } |
| 929 | |
| 930 | if (terminalId !== DEFAULT_TERMINAL_ID) { |
| 931 | return ""; |
| 696 | 932 | } |
| 697 | 933 | |
| 698 | | const cols = input.cols ?? session.cols; |
| 699 | | const rows = input.rows ?? session.rows; |
| 934 | const legacyPath = legacyHistoryPath(threadId); |
| 935 | if ( |
| 936 | !(yield* fileSystem |
| 937 | .exists(legacyPath) |
| 938 | .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId)))) |
| 939 | ) { |
| 940 | return ""; |
| 941 | } |
| 700 | 942 | |
| 701 | | session.history = ""; |
| 702 | | session.pendingHistoryControlSequence = ""; |
| 703 | | await this.persistHistory(input.threadId, input.terminalId, session.history); |
| 704 | | await this.startSession(session, { ...input, cols, rows }, "restarted"); |
| 705 | | return this.snapshot(session); |
| 943 | const raw = yield* fileSystem |
| 944 | .readFileString(legacyPath) |
| 945 | .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); |
| 946 | const capped = capHistory(raw, historyLineLimit); |
| 947 | yield* fileSystem |
| 948 | .writeFileString(nextPath, capped) |
| 949 | .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); |
| 950 | yield* fileSystem.remove(legacyPath, { force: true }).pipe( |
| 951 | Effect.catch((cleanupError) => |
| 952 | Effect.logWarning("failed to remove legacy terminal history", { |
| 953 | threadId, |
| 954 | error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), |
| 955 | }), |
| 956 | ), |
| 957 | ); |
| 958 | return capped; |
| 706 | 959 | }); |
| 707 | | } |
| 708 | 960 | |
| 709 | | async close(raw: TerminalCloseInput): Promise<void> { |
| 710 | | const input = decodeTerminalCloseInput(raw); |
| 711 | | await this.runWithThreadLock(input.threadId, async () => { |
| 712 | | if (input.terminalId) { |
| 713 | | await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true); |
| 714 | | return; |
| 961 | const deleteHistory = Effect.fn("terminal.deleteHistory")(function* ( |
| 962 | threadId: string, |
| 963 | terminalId: string, |
| 964 | ) { |
| 965 | yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe( |
| 966 | Effect.catch((error) => |
| 967 | Effect.logWarning("failed to delete terminal history", { |
| 968 | threadId, |
| 969 | terminalId, |
| 970 | error: error instanceof Error ? error.message : String(error), |
| 971 | }), |
| 972 | ), |
| 973 | ); |
| 974 | if (terminalId === DEFAULT_TERMINAL_ID) { |
| 975 | yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe( |
| 976 | Effect.catch((error) => |
| 977 | Effect.logWarning("failed to delete terminal history", { |
| 978 | threadId, |
| 979 | terminalId, |
| 980 | error: error instanceof Error ? error.message : String(error), |
| 981 | }), |
| 982 | ), |
| 983 | ); |
| 715 | 984 | } |
| 985 | }); |
| 716 | 986 | |
| 717 | | const threadSessions = this.sessionsForThread(input.threadId); |
| 718 | | for (const session of threadSessions) { |
| 719 | | this.stopProcess(session); |
| 720 | | this.sessions.delete(toSessionKey(session.threadId, session.terminalId)); |
| 721 | | } |
| 722 | | await Promise.all( |
| 723 | | threadSessions.map((session) => |
| 724 | | this.flushPersistQueue(session.threadId, session.terminalId), |
| 987 | const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* ( |
| 988 | threadId: string, |
| 989 | ) { |
| 990 | const threadPrefix = `${toSafeThreadId(threadId)}_`; |
| 991 | const entries = yield* fileSystem |
| 992 | .readDirectory(logsDir, { recursive: false }) |
| 993 | .pipe(Effect.catch(() => Effect.succeed([] as Array<string>))); |
| 994 | yield* Effect.forEach( |
| 995 | entries.filter( |
| 996 | (name) => |
| 997 | name === `${toSafeThreadId(threadId)}.log` || |
| 998 | name === `${legacySafeThreadId(threadId)}.log` || |
| 999 | name.startsWith(threadPrefix), |
| 725 | 1000 | ), |
| 1001 | (name) => |
| 1002 | fileSystem.remove(path.join(logsDir, name), { force: true }).pipe( |
| 1003 | Effect.catch((error) => |
| 1004 | Effect.logWarning("failed to delete terminal histories for thread", { |
| 1005 | threadId, |
| 1006 | error: error instanceof Error ? error.message : String(error), |
| 1007 | }), |
| 1008 | ), |
| 1009 | ), |
| 1010 | { discard: true }, |
| 726 | 1011 | ); |
| 1012 | }); |
| 727 | 1013 | |
| 728 | | if (input.deleteHistory) { |
| 729 | | await this.deleteAllHistoryForThread(input.threadId); |
| 1014 | const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) { |
| 1015 | const stats = yield* fileSystem.stat(cwd).pipe( |
| 1016 | Effect.mapError( |
| 1017 | (cause) => |
| 1018 | new TerminalCwdError({ |
| 1019 | cwd, |
| 1020 | reason: cause.reason._tag === "NotFound" ? "notFound" : "statFailed", |
| 1021 | cause, |
| 1022 | }), |
| 1023 | ), |
| 1024 | ); |
| 1025 | if (stats.type !== "Directory") { |
| 1026 | return yield* new TerminalCwdError({ |
| 1027 | cwd, |
| 1028 | reason: "notDirectory", |
| 1029 | }); |
| 730 | 1030 | } |
| 731 | | this.updateSubprocessPollingState(); |
| 732 | 1031 | }); |
| 733 | | } |
| 734 | 1032 | |
| 735 | | dispose(): void { |
| 736 | | this.stopSubprocessPolling(); |
| 737 | | const sessions = [...this.sessions.values()]; |
| 738 | | this.sessions.clear(); |
| 739 | | for (const session of sessions) { |
| 740 | | this.stopProcess(session); |
| 741 | | } |
| 742 | | for (const timer of this.persistTimers.values()) { |
| 743 | | clearTimeout(timer); |
| 744 | | } |
| 745 | | this.persistTimers.clear(); |
| 746 | | for (const timer of this.killEscalationTimers.values()) { |
| 747 | | clearTimeout(timer); |
| 748 | | } |
| 749 | | this.killEscalationTimers.clear(); |
| 750 | | this.pendingPersistHistory.clear(); |
| 751 | | this.threadLocks.clear(); |
| 752 | | this.persistQueues.clear(); |
| 753 | | } |
| 1033 | const getSession = Effect.fn("terminal.getSession")(function* ( |
| 1034 | threadId: string, |
| 1035 | terminalId: string, |
| 1036 | ): Effect.fn.Return<Option.Option<TerminalSessionState>> { |
| 1037 | return yield* Effect.map(readManagerState, (state) => |
| 1038 | Option.fromNullishOr(state.sessions.get(toSessionKey(threadId, terminalId))), |
| 1039 | ); |
| 1040 | }); |
| 754 | 1041 | |
| 755 | | private async startSession( |
| 756 | | session: TerminalSessionState, |
| 757 | | input: TerminalStartInput, |
| 758 | | eventType: "started" | "restarted", |
| 759 | | ): Promise<void> { |
| 760 | | this.stopProcess(session); |
| 761 | | |
| 762 | | session.status = "starting"; |
| 763 | | session.cwd = input.cwd; |
| 764 | | session.cols = input.cols; |
| 765 | | session.rows = input.rows; |
| 766 | | session.exitCode = null; |
| 767 | | session.exitSignal = null; |
| 768 | | session.hasRunningSubprocess = false; |
| 769 | | session.updatedAt = new Date().toISOString(); |
| 770 | | |
| 771 | | let ptyProcess: PtyProcess | null = null; |
| 772 | | let startedShell: string | null = null; |
| 773 | | try { |
| 774 | | const shellCandidates = resolveShellCandidates(this.shellResolver); |
| 775 | | const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); |
| 776 | | let lastSpawnError: unknown = null; |
| 777 | | |
| 778 | | const spawnWithCandidate = (candidate: ShellCandidate) => |
| 779 | | Effect.runPromise( |
| 780 | | this.ptyAdapter.spawn({ |
| 781 | | shell: candidate.shell, |
| 782 | | ...(candidate.args ? { args: candidate.args } : {}), |
| 783 | | cwd: session.cwd, |
| 784 | | cols: session.cols, |
| 785 | | rows: session.rows, |
| 786 | | env: terminalEnv, |
| 787 | | }), |
| 788 | | ); |
| 1042 | const requireSession = Effect.fn("terminal.requireSession")(function* ( |
| 1043 | threadId: string, |
| 1044 | terminalId: string, |
| 1045 | ): Effect.fn.Return<TerminalSessionState, TerminalSessionLookupError> { |
| 1046 | return yield* Effect.flatMap(getSession(threadId, terminalId), (session) => |
| 1047 | Option.match(session, { |
| 1048 | onNone: () => |
| 1049 | Effect.fail( |
| 1050 | new TerminalSessionLookupError({ |
| 1051 | threadId, |
| 1052 | terminalId, |
| 1053 | }), |
| 1054 | ), |
| 1055 | onSome: Effect.succeed, |
| 1056 | }), |
| 1057 | ); |
| 1058 | }); |
| 789 | 1059 | |
| 790 | | const trySpawn = async ( |
| 791 | | candidates: ShellCandidate[], |
| 792 | | index = 0, |
| 793 | | ): Promise<{ process: PtyProcess; shellLabel: string } | null> => { |
| 794 | | if (index >= candidates.length) { |
| 795 | | return null; |
| 796 | | } |
| 797 | | const candidate = candidates[index]; |
| 798 | | if (!candidate) { |
| 799 | | return null; |
| 1060 | const sessionsForThread = Effect.fn("terminal.sessionsForThread")(function* (threadId: string) { |
| 1061 | return yield* readManagerState.pipe( |
| 1062 | Effect.map((state) => |
| 1063 | [...state.sessions.values()].filter((session) => session.threadId === threadId), |
| 1064 | ), |
| 1065 | ); |
| 1066 | }); |
| 1067 | |
| 1068 | const evictInactiveSessionsIfNeeded = Effect.fn("terminal.evictInactiveSessionsIfNeeded")( |
| 1069 | function* () { |
| 1070 | yield* modifyManagerState((state) => { |
| 1071 | const inactiveSessions = [...state.sessions.values()].filter( |
| 1072 | (session) => session.status !== "running", |
| 1073 | ); |
| 1074 | if (inactiveSessions.length <= maxRetainedInactiveSessions) { |
| 1075 | return [undefined, state] as const; |
| 1076 | } |
| 1077 | |
| 1078 | inactiveSessions.sort( |
| 1079 | (left, right) => |
| 1080 | left.updatedAt.localeCompare(right.updatedAt) || |
| 1081 | left.threadId.localeCompare(right.threadId) || |
| 1082 | left.terminalId.localeCompare(right.terminalId), |
| 1083 | ); |
| 1084 | |
| 1085 | const sessions = new Map(state.sessions); |
| 1086 | |
| 1087 | const toEvict = inactiveSessions.length - maxRetainedInactiveSessions; |
| 1088 | for (const session of inactiveSessions.slice(0, toEvict)) { |
| 1089 | const key = toSessionKey(session.threadId, session.terminalId); |
| 1090 | sessions.delete(key); |
| 1091 | } |
| 1092 | |
| 1093 | return [undefined, { ...state, sessions }] as const; |
| 1094 | }); |
| 1095 | }, |
| 1096 | ); |
| 1097 | |
| 1098 | const drainProcessEvents = Effect.fn("terminal.drainProcessEvents")(function* ( |
| 1099 | session: TerminalSessionState, |
| 1100 | expectedPid: number, |
| 1101 | ) { |
| 1102 | while (true) { |
| 1103 | const action: DrainProcessEventAction = yield* Effect.sync(() => { |
| 1104 | if (session.pid !== expectedPid || !session.process || session.status !== "running") { |
| 1105 | session.pendingProcessEvents = []; |
| 1106 | session.pendingProcessEventIndex = 0; |
| 1107 | session.processEventDrainRunning = false; |
| 1108 | return { type: "idle" } as const; |
| 1109 | } |
| 1110 | |
| 1111 | const nextEvent = session.pendingProcessEvents[session.pendingProcessEventIndex]; |
| 1112 | if (!nextEvent) { |
| 1113 | session.pendingProcessEvents = []; |
| 1114 | session.pendingProcessEventIndex = 0; |
| 1115 | session.processEventDrainRunning = false; |
| 1116 | return { type: "idle" } as const; |
| 1117 | } |
| 1118 | |
| 1119 | session.pendingProcessEventIndex += 1; |
| 1120 | if (session.pendingProcessEventIndex >= session.pendingProcessEvents.length) { |
| 1121 | session.pendingProcessEvents = []; |
| 1122 | session.pendingProcessEventIndex = 0; |
| 1123 | } |
| 1124 | |
| 1125 | if (nextEvent.type === "output") { |
| 1126 | const sanitized = sanitizeTerminalHistoryChunk( |
| 1127 | session.pendingHistoryControlSequence, |
| 1128 | nextEvent.data, |
| 1129 | ); |
| 1130 | session.pendingHistoryControlSequence = sanitized.pendingControlSequence; |
| 1131 | if (sanitized.visibleText.length > 0) { |
| 1132 | session.history = capHistory( |
| 1133 | `${session.history}${sanitized.visibleText}`, |
| 1134 | historyLineLimit, |
| 1135 | ); |
| 1136 | } |
| 1137 | session.updatedAt = new Date().toISOString(); |
| 1138 | |
| 1139 | return { |
| 1140 | type: "output", |
| 1141 | threadId: session.threadId, |
| 1142 | terminalId: session.terminalId, |
| 1143 | history: sanitized.visibleText.length > 0 ? session.history : null, |
| 1144 | data: nextEvent.data, |
| 1145 | } as const; |
| 1146 | } |
| 1147 | |
| 1148 | const process = session.process; |
| 1149 | cleanupProcessHandles(session); |
| 1150 | session.process = null; |
| 1151 | session.pid = null; |
| 1152 | session.hasRunningSubprocess = false; |
| 1153 | session.status = "exited"; |
| 1154 | session.pendingHistoryControlSequence = ""; |
| 1155 | session.pendingProcessEvents = []; |
| 1156 | session.pendingProcessEventIndex = 0; |
| 1157 | session.processEventDrainRunning = false; |
| 1158 | session.exitCode = Number.isInteger(nextEvent.event.exitCode) |
| 1159 | ? nextEvent.event.exitCode |
| 1160 | : null; |
| 1161 | session.exitSignal = Number.isInteger(nextEvent.event.signal) |
| 1162 | ? nextEvent.event.signal |
| 1163 | : null; |
| 1164 | session.updatedAt = new Date().toISOString(); |
| 1165 | |
| 1166 | return { |
| 1167 | type: "exit", |
| 1168 | process, |
| 1169 | threadId: session.threadId, |
| 1170 | terminalId: session.terminalId, |
| 1171 | exitCode: session.exitCode, |
| 1172 | exitSignal: session.exitSignal, |
| 1173 | } as const; |
| 1174 | }); |
| 1175 | |
| 1176 | if (action.type === "idle") { |
| 1177 | return; |
| 800 | 1178 | } |
| 801 | 1179 | |
| 802 | | try { |
| 803 | | const process = await spawnWithCandidate(candidate); |
| 804 | | return { process, shellLabel: formatShellCandidate(candidate) }; |
| 805 | | } catch (error) { |
| 806 | | lastSpawnError = error; |
| 807 | | if (!isRetryableShellSpawnError(error)) { |
| 808 | | throw error; |
| 1180 | if (action.type === "output") { |
| 1181 | if (action.history !== null) { |
| 1182 | yield* queuePersist(action.threadId, action.terminalId, action.history); |
| 809 | 1183 | } |
| 810 | | return trySpawn(candidates, index + 1); |
| 1184 | |
| 1185 | yield* publishEvent({ |
| 1186 | type: "output", |
| 1187 | threadId: action.threadId, |
| 1188 | terminalId: action.terminalId, |
| 1189 | createdAt: new Date().toISOString(), |
| 1190 | data: action.data, |
| 1191 | }); |
| 1192 | continue; |
| 811 | 1193 | } |
| 812 | | }; |
| 813 | 1194 | |
| 814 | | const spawnResult = await trySpawn(shellCandidates); |
| 815 | | if (spawnResult) { |
| 816 | | ptyProcess = spawnResult.process; |
| 817 | | startedShell = spawnResult.shellLabel; |
| 1195 | yield* clearKillFiber(action.process); |
| 1196 | yield* publishEvent({ |
| 1197 | type: "exited", |
| 1198 | threadId: action.threadId, |
| 1199 | terminalId: action.terminalId, |
| 1200 | createdAt: new Date().toISOString(), |
| 1201 | exitCode: action.exitCode, |
| 1202 | exitSignal: action.exitSignal, |
| 1203 | }); |
| 1204 | yield* evictInactiveSessionsIfNeeded(); |
| 1205 | return; |
| 818 | 1206 | } |
| 1207 | }); |
| 1208 | |
| 1209 | const stopProcess = Effect.fn("terminal.stopProcess")(function* ( |
| 1210 | session: TerminalSessionState, |
| 1211 | ) { |
| 1212 | const process = session.process; |
| 1213 | if (!process) return; |
| 1214 | |
| 1215 | yield* modifyManagerState((state) => { |
| 1216 | cleanupProcessHandles(session); |
| 1217 | session.process = null; |
| 1218 | session.pid = null; |
| 1219 | session.hasRunningSubprocess = false; |
| 1220 | session.status = "exited"; |
| 1221 | session.pendingHistoryControlSequence = ""; |
| 1222 | session.pendingProcessEvents = []; |
| 1223 | session.pendingProcessEventIndex = 0; |
| 1224 | session.processEventDrainRunning = false; |
| 1225 | session.updatedAt = new Date().toISOString(); |
| 1226 | return [undefined, state] as const; |
| 1227 | }); |
| 819 | 1228 | |
| 820 | | if (!ptyProcess) { |
| 821 | | const detail = |
| 822 | | lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed"; |
| 1229 | yield* clearKillFiber(process); |
| 1230 | yield* startKillEscalation(process, session.threadId, session.terminalId); |
| 1231 | yield* evictInactiveSessionsIfNeeded(); |
| 1232 | }); |
| 1233 | |
| 1234 | const trySpawn = Effect.fn("terminal.trySpawn")(function* ( |
| 1235 | shellCandidates: ReadonlyArray<ShellCandidate>, |
| 1236 | spawnEnv: NodeJS.ProcessEnv, |
| 1237 | session: TerminalSessionState, |
| 1238 | index = 0, |
| 1239 | lastError: PtySpawnError | null = null, |
| 1240 | ): Effect.fn.Return<{ process: PtyProcess; shellLabel: string }, PtySpawnError> { |
| 1241 | if (index >= shellCandidates.length) { |
| 1242 | const detail = lastError?.message ?? "Failed to spawn PTY process"; |
| 823 | 1243 | const tried = |
| 824 | 1244 | shellCandidates.length > 0 |
| 825 | 1245 | ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.` |
| 826 | 1246 | : ""; |
| 827 | | throw new Error(`${detail}.${tried}`.trim()); |
| 1247 | return yield* new PtySpawnError({ |
| 1248 | adapter: "terminal-manager", |
| 1249 | message: `${detail}.${tried}`.trim(), |
| 1250 | ...(lastError ? { cause: lastError } : {}), |
| 1251 | }); |
| 828 | 1252 | } |
| 829 | 1253 | |
| 830 | | session.process = ptyProcess; |
| 831 | | session.pid = ptyProcess.pid; |
| 832 | | session.status = "running"; |
| 833 | | session.updatedAt = new Date().toISOString(); |
| 834 | | session.unsubscribeData = ptyProcess.onData((data) => { |
| 835 | | this.onProcessData(session, data); |
| 836 | | }); |
| 837 | | session.unsubscribeExit = ptyProcess.onExit((event) => { |
| 838 | | this.onProcessExit(session, event); |
| 839 | | }); |
| 840 | | this.updateSubprocessPollingState(); |
| 841 | | this.emitEvent({ |
| 842 | | type: eventType, |
| 843 | | threadId: session.threadId, |
| 844 | | terminalId: session.terminalId, |
| 845 | | createdAt: new Date().toISOString(), |
| 846 | | snapshot: this.snapshot(session), |
| 847 | | }); |
| 848 | | } catch (error) { |
| 849 | | if (ptyProcess) { |
| 850 | | this.killProcessWithEscalation(ptyProcess, session.threadId, session.terminalId); |
| 1254 | const candidate = shellCandidates[index]; |
| 1255 | if (!candidate) { |
| 1256 | return yield* ( |
| 1257 | lastError ?? |
| 1258 | new PtySpawnError({ |
| 1259 | adapter: "terminal-manager", |
| 1260 | message: "No shell candidate available for PTY spawn.", |
| 1261 | }) |
| 1262 | ); |
| 851 | 1263 | } |
| 852 | | session.status = "error"; |
| 853 | | session.pid = null; |
| 854 | | session.process = null; |
| 855 | | session.hasRunningSubprocess = false; |
| 856 | | session.updatedAt = new Date().toISOString(); |
| 857 | | this.evictInactiveSessionsIfNeeded(); |
| 858 | | this.updateSubprocessPollingState(); |
| 859 | | const message = error instanceof Error ? error.message : "Terminal start failed"; |
| 860 | | this.emitEvent({ |
| 861 | | type: "error", |
| 862 | | threadId: session.threadId, |
| 863 | | terminalId: session.terminalId, |
| 864 | | createdAt: new Date().toISOString(), |
| 865 | | message, |
| 866 | | }); |
| 867 | | this.logger.error("failed to start terminal", { |
| 868 | | threadId: session.threadId, |
| 869 | | terminalId: session.terminalId, |
| 870 | | error: message, |
| 871 | | ...(startedShell ? { shell: startedShell } : {}), |
| 872 | | }); |
| 873 | | } |
| 874 | | } |
| 875 | 1264 | |
| 876 | | private onProcessData(session: TerminalSessionState, data: string): void { |
| 877 | | const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data); |
| 878 | | session.pendingHistoryControlSequence = sanitized.pendingControlSequence; |
| 879 | | if (sanitized.visibleText.length > 0) { |
| 880 | | session.history = capHistory( |
| 881 | | `${session.history}${sanitized.visibleText}`, |
| 882 | | this.historyLineLimit, |
| 1265 | const attempt = yield* Effect.result( |
| 1266 | options.ptyAdapter.spawn({ |
| 1267 | shell: candidate.shell, |
| 1268 | ...(candidate.args ? { args: candidate.args } : {}), |
| 1269 | cwd: session.cwd, |
| 1270 | cols: session.cols, |
| 1271 | rows: session.rows, |
| 1272 | env: spawnEnv, |
| 1273 | }), |
| 883 | 1274 | ); |
| 884 | | this.queuePersist(session.threadId, session.terminalId, session.history); |
| 885 | | } |
| 886 | | session.updatedAt = new Date().toISOString(); |
| 887 | | this.emitEvent({ |
| 888 | | type: "output", |
| 889 | | threadId: session.threadId, |
| 890 | | terminalId: session.terminalId, |
| 891 | | createdAt: new Date().toISOString(), |
| 892 | | data, |
| 893 | | }); |
| 894 | | } |
| 895 | 1275 | |
| 896 | | private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void { |
| 897 | | this.clearKillEscalationTimer(session.process); |
| 898 | | this.cleanupProcessHandles(session); |
| 899 | | session.process = null; |
| 900 | | session.pid = null; |
| 901 | | session.hasRunningSubprocess = false; |
| 902 | | session.status = "exited"; |
| 903 | | session.pendingHistoryControlSequence = ""; |
| 904 | | session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null; |
| 905 | | session.exitSignal = Number.isInteger(event.signal) ? event.signal : null; |
| 906 | | session.updatedAt = new Date().toISOString(); |
| 907 | | this.emitEvent({ |
| 908 | | type: "exited", |
| 909 | | threadId: session.threadId, |
| 910 | | terminalId: session.terminalId, |
| 911 | | createdAt: new Date().toISOString(), |
| 912 | | exitCode: session.exitCode, |
| 913 | | exitSignal: session.exitSignal, |
| 914 | | }); |
| 915 | | this.evictInactiveSessionsIfNeeded(); |
| 916 | | this.updateSubprocessPollingState(); |
| 917 | | } |
| 1276 | if (attempt._tag === "Success") { |
| 1277 | return { |
| 1278 | process: attempt.success, |
| 1279 | shellLabel: formatShellCandidate(candidate), |
| 1280 | }; |
| 1281 | } |
| 918 | 1282 | |
| 919 | | private stopProcess(session: TerminalSessionState): void { |
| 920 | | const process = session.process; |
| 921 | | if (!process) return; |
| 922 | | this.cleanupProcessHandles(session); |
| 923 | | session.process = null; |
| 924 | | session.pid = null; |
| 925 | | session.hasRunningSubprocess = false; |
| 926 | | session.status = "exited"; |
| 927 | | session.pendingHistoryControlSequence = ""; |
| 928 | | session.updatedAt = new Date().toISOString(); |
| 929 | | this.killProcessWithEscalation(process, session.threadId, session.terminalId); |
| 930 | | this.evictInactiveSessionsIfNeeded(); |
| 931 | | this.updateSubprocessPollingState(); |
| 932 | | } |
| 1283 | const spawnError = attempt.failure; |
| 1284 | if (!isRetryableShellSpawnError(spawnError)) { |
| 1285 | return yield* spawnError; |
| 1286 | } |
| 933 | 1287 | |
| 934 | | private cleanupProcessHandles(session: TerminalSessionState): void { |
| 935 | | session.unsubscribeData?.(); |
| 936 | | session.unsubscribeData = null; |
| 937 | | session.unsubscribeExit?.(); |
| 938 | | session.unsubscribeExit = null; |
| 939 | | } |
| 1288 | return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError); |
| 1289 | }); |
| 940 | 1290 | |
| 941 | | private clearKillEscalationTimer(process: PtyProcess | null): void { |
| 942 | | if (!process) return; |
| 943 | | const timer = this.killEscalationTimers.get(process); |
| 944 | | if (!timer) return; |
| 945 | | clearTimeout(timer); |
| 946 | | this.killEscalationTimers.delete(process); |
| 947 | | } |
| 1291 | const startSession = Effect.fn("terminal.startSession")(function* ( |
| 1292 | session: TerminalSessionState, |
| 1293 | input: TerminalStartInput, |
| 1294 | eventType: "started" | "restarted", |
| 1295 | ) { |
| 1296 | yield* stopProcess(session); |
| 948 | 1297 | |
| 949 | | private killProcessWithEscalation( |
| 950 | | process: PtyProcess, |
| 951 | | threadId: string, |
| 952 | | terminalId: string, |
| 953 | | ): void { |
| 954 | | this.clearKillEscalationTimer(process); |
| 955 | | try { |
| 956 | | process.kill("SIGTERM"); |
| 957 | | } catch (error) { |
| 958 | | const message = error instanceof Error ? error.message : String(error); |
| 959 | | this.logger.warn("failed to kill terminal process", { |
| 960 | | threadId, |
| 961 | | terminalId, |
| 962 | | signal: "SIGTERM", |
| 963 | | error: message, |
| 1298 | yield* modifyManagerState((state) => { |
| 1299 | session.status = "starting"; |
| 1300 | session.cwd = input.cwd; |
| 1301 | session.cols = input.cols; |
| 1302 | session.rows = input.rows; |
| 1303 | session.exitCode = null; |
| 1304 | session.exitSignal = null; |
| 1305 | session.hasRunningSubprocess = false; |
| 1306 | session.pendingProcessEvents = []; |
| 1307 | session.pendingProcessEventIndex = 0; |
| 1308 | session.processEventDrainRunning = false; |
| 1309 | session.updatedAt = new Date().toISOString(); |
| 1310 | return [undefined, state] as const; |
| 964 | 1311 | }); |
| 965 | | return; |
| 966 | | } |
| 967 | 1312 | |
| 968 | | const timer = setTimeout(() => { |
| 969 | | this.killEscalationTimers.delete(process); |
| 970 | | try { |
| 971 | | process.kill("SIGKILL"); |
| 972 | | } catch (error) { |
| 973 | | const message = error instanceof Error ? error.message : String(error); |
| 974 | | this.logger.warn("failed to force-kill terminal process", { |
| 975 | | threadId, |
| 976 | | terminalId, |
| 977 | | signal: "SIGKILL", |
| 978 | | error: message, |
| 979 | | }); |
| 980 | | } |
| 981 | | }, this.processKillGraceMs); |
| 982 | | timer.unref?.(); |
| 983 | | this.killEscalationTimers.set(process, timer); |
| 984 | | } |
| 1313 | let ptyProcess: PtyProcess | null = null; |
| 1314 | let startedShell: string | null = null; |
| 1315 | |
| 1316 | const startResult = yield* Effect.result( |
| 1317 | Effect.gen(function* () { |
| 1318 | const shellCandidates = resolveShellCandidates(shellResolver); |
| 1319 | const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); |
| 1320 | const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session); |
| 1321 | ptyProcess = spawnResult.process; |
| 1322 | startedShell = spawnResult.shellLabel; |
| 1323 | |
| 1324 | const processPid = ptyProcess.pid; |
| 1325 | const unsubscribeData = ptyProcess.onData((data) => { |
| 1326 | if (!enqueueProcessEvent(session, processPid, { type: "output", data })) { |
| 1327 | return; |
| 1328 | } |
| 1329 | runFork(drainProcessEvents(session, processPid)); |
| 1330 | }); |
| 1331 | const unsubscribeExit = ptyProcess.onExit((event) => { |
| 1332 | if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) { |
| 1333 | return; |
| 1334 | } |
| 1335 | runFork(drainProcessEvents(session, processPid)); |
| 1336 | }); |
| 985 | 1337 | |
| 986 | | private evictInactiveSessionsIfNeeded(): void { |
| 987 | | const inactiveSessions = [...this.sessions.values()].filter( |
| 988 | | (session) => session.status !== "running", |
| 989 | | ); |
| 990 | | if (inactiveSessions.length <= this.maxRetainedInactiveSessions) { |
| 991 | | return; |
| 992 | | } |
| 1338 | yield* modifyManagerState((state) => { |
| 1339 | session.process = ptyProcess; |
| 1340 | session.pid = processPid; |
| 1341 | session.status = "running"; |
| 1342 | session.updatedAt = new Date().toISOString(); |
| 1343 | session.unsubscribeData = unsubscribeData; |
| 1344 | session.unsubscribeExit = unsubscribeExit; |
| 1345 | return [undefined, state] as const; |
| 1346 | }); |
| 993 | 1347 | |
| 994 | | inactiveSessions.sort( |
| 995 | | (left, right) => |
| 996 | | left.updatedAt.localeCompare(right.updatedAt) || |
| 997 | | left.threadId.localeCompare(right.threadId) || |
| 998 | | left.terminalId.localeCompare(right.terminalId), |
| 999 | | ); |
| 1000 | | const toEvict = inactiveSessions.length - this.maxRetainedInactiveSessions; |
| 1001 | | for (const session of inactiveSessions.slice(0, toEvict)) { |
| 1002 | | const key = toSessionKey(session.threadId, session.terminalId); |
| 1003 | | this.sessions.delete(key); |
| 1004 | | this.clearPersistTimer(session.threadId, session.terminalId); |
| 1005 | | this.pendingPersistHistory.delete(key); |
| 1006 | | this.persistQueues.delete(key); |
| 1007 | | this.clearKillEscalationTimer(session.process); |
| 1008 | | } |
| 1009 | | } |
| 1348 | yield* publishEvent({ |
| 1349 | type: eventType, |
| 1350 | threadId: session.threadId, |
| 1351 | terminalId: session.terminalId, |
| 1352 | createdAt: new Date().toISOString(), |
| 1353 | snapshot: snapshot(session), |
| 1354 | }); |
| 1355 | }), |
| 1356 | ); |
| 1010 | 1357 | |
| 1011 | | private queuePersist(threadId: string, terminalId: string, history: string): void { |
| 1012 | | const persistenceKey = toSessionKey(threadId, terminalId); |
| 1013 | | this.pendingPersistHistory.set(persistenceKey, history); |
| 1014 | | this.schedulePersist(threadId, terminalId); |
| 1015 | | } |
| 1358 | if (startResult._tag === "Success") { |
| 1359 | return; |
| 1360 | } |
| 1016 | 1361 | |
| 1017 | | private async persistHistory( |
| 1018 | | threadId: string, |
| 1019 | | terminalId: string, |
| 1020 | | history: string, |
| 1021 | | ): Promise<void> { |
| 1022 | | const persistenceKey = toSessionKey(threadId, terminalId); |
| 1023 | | this.clearPersistTimer(threadId, terminalId); |
| 1024 | | this.pendingPersistHistory.delete(persistenceKey); |
| 1025 | | await this.enqueuePersistWrite(threadId, terminalId, history); |
| 1026 | | } |
| 1362 | { |
| 1363 | const error = startResult.failure; |
| 1364 | if (ptyProcess) { |
| 1365 | yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); |
| 1366 | } |
| 1027 | 1367 | |
| 1028 | | private enqueuePersistWrite( |
| 1029 | | threadId: string, |
| 1030 | | terminalId: string, |
| 1031 | | history: string, |
| 1032 | | ): Promise<void> { |
| 1033 | | const persistenceKey = toSessionKey(threadId, terminalId); |
| 1034 | | const task = async () => { |
| 1035 | | await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8"); |
| 1036 | | }; |
| 1037 | | const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve(); |
| 1038 | | const next = previous |
| 1039 | | .catch(() => undefined) |
| 1040 | | .then(task) |
| 1041 | | .catch((error) => { |
| 1042 | | this.logger.warn("failed to persist terminal history", { |
| 1043 | | threadId, |
| 1044 | | terminalId, |
| 1045 | | error: error instanceof Error ? error.message : String(error), |
| 1368 | yield* modifyManagerState((state) => { |
| 1369 | session.status = "error"; |
| 1370 | session.pid = null; |
| 1371 | session.process = null; |
| 1372 | session.unsubscribeData = null; |
| 1373 | session.unsubscribeExit = null; |
| 1374 | session.hasRunningSubprocess = false; |
| 1375 | session.pendingProcessEvents = []; |
| 1376 | session.pendingProcessEventIndex = 0; |
| 1377 | session.processEventDrainRunning = false; |
| 1378 | session.updatedAt = new Date().toISOString(); |
| 1379 | return [undefined, state] as const; |
| 1380 | }); |
| 1381 | |
| 1382 | yield* evictInactiveSessionsIfNeeded(); |
| 1383 | |
| 1384 | const message = error.message; |
| 1385 | yield* publishEvent({ |
| 1386 | type: "error", |
| 1387 | threadId: session.threadId, |
| 1388 | terminalId: session.terminalId, |
| 1389 | createdAt: new Date().toISOString(), |
| 1390 | message, |
| 1391 | }); |
| 1392 | yield* Effect.logError("failed to start terminal", { |
| 1393 | threadId: session.threadId, |
| 1394 | terminalId: session.terminalId, |
| 1395 | error: message, |
| 1396 | ...(startedShell ? { shell: startedShell } : {}), |
| 1046 | 1397 | }); |
| 1047 | | }); |
| 1048 | | this.persistQueues.set(persistenceKey, next); |
| 1049 | | const finalized = next.finally(() => { |
| 1050 | | if (this.persistQueues.get(persistenceKey) === next) { |
| 1051 | | this.persistQueues.delete(persistenceKey); |
| 1052 | | } |
| 1053 | | if ( |
| 1054 | | this.pendingPersistHistory.has(persistenceKey) && |
| 1055 | | !this.persistTimers.has(persistenceKey) |
| 1056 | | ) { |
| 1057 | | this.schedulePersist(threadId, terminalId); |
| 1058 | 1398 | } |
| 1059 | 1399 | }); |
| 1060 | | void finalized.catch(() => undefined); |
| 1061 | | return finalized; |
| 1062 | | } |
| 1063 | 1400 | |
| 1064 | | private schedulePersist(threadId: string, terminalId: string): void { |
| 1065 | | const persistenceKey = toSessionKey(threadId, terminalId); |
| 1066 | | if (this.persistTimers.has(persistenceKey)) return; |
| 1067 | | const timer = setTimeout(() => { |
| 1068 | | this.persistTimers.delete(persistenceKey); |
| 1069 | | const pendingHistory = this.pendingPersistHistory.get(persistenceKey); |
| 1070 | | if (pendingHistory === undefined) return; |
| 1071 | | this.pendingPersistHistory.delete(persistenceKey); |
| 1072 | | void this.enqueuePersistWrite(threadId, terminalId, pendingHistory); |
| 1073 | | }, this.persistDebounceMs); |
| 1074 | | this.persistTimers.set(persistenceKey, timer); |
| 1075 | | } |
| 1401 | const closeSession = Effect.fn("terminal.closeSession")(function* ( |
| 1402 | threadId: string, |
| 1403 | terminalId: string, |
| 1404 | deleteHistoryOnClose: boolean, |
| 1405 | ) { |
| 1406 | const key = toSessionKey(threadId, terminalId); |
| 1407 | const session = yield* getSession(threadId, terminalId); |
| 1408 | |
| 1409 | if (Option.isSome(session)) { |
| 1410 | yield* stopProcess(session.value); |
| 1411 | yield* persistHistory(threadId, terminalId, session.value.history); |
| 1412 | } |
| 1076 | 1413 | |
| 1077 | | private clearPersistTimer(threadId: string, terminalId: string): void { |
| 1078 | | const persistenceKey = toSessionKey(threadId, terminalId); |
| 1079 | | const timer = this.persistTimers.get(persistenceKey); |
| 1080 | | if (!timer) return; |
| 1081 | | clearTimeout(timer); |
| 1082 | | this.persistTimers.delete(persistenceKey); |
| 1083 | | } |
| 1414 | yield* flushPersist(threadId, terminalId); |
| 1084 | 1415 | |
| 1085 | | private async readHistory(threadId: string, terminalId: string): Promise<string> { |
| 1086 | | const nextPath = this.historyPath(threadId, terminalId); |
| 1087 | | try { |
| 1088 | | const raw = await fs.promises.readFile(nextPath, "utf8"); |
| 1089 | | const capped = capHistory(raw, this.historyLineLimit); |
| 1090 | | if (capped !== raw) { |
| 1091 | | await fs.promises.writeFile(nextPath, capped, "utf8"); |
| 1092 | | } |
| 1093 | | return capped; |
| 1094 | | } catch (error) { |
| 1095 | | if ((error as NodeJS.ErrnoException).code !== "ENOENT") { |
| 1096 | | throw error; |
| 1416 | yield* modifyManagerState((state) => { |
| 1417 | if (!state.sessions.has(key)) { |
| 1418 | return [undefined, state] as const; |
| 1419 | } |
| 1420 | const sessions = new Map(state.sessions); |
| 1421 | sessions.delete(key); |
| 1422 | return [undefined, { ...state, sessions }] as const; |
| 1423 | }); |
| 1424 | |
| 1425 | if (deleteHistoryOnClose) { |
| 1426 | yield* deleteHistory(threadId, terminalId); |
| 1097 | 1427 | } |
| 1098 | | } |
| 1428 | }); |
| 1099 | 1429 | |
| 1100 | | if (terminalId !== DEFAULT_TERMINAL_ID) { |
| 1101 | | return ""; |
| 1102 | | } |
| 1430 | const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { |
| 1431 | const state = yield* readManagerState; |
| 1432 | const runningSessions = [...state.sessions.values()].filter( |
| 1433 | (session): session is TerminalSessionState & { pid: number } => |
| 1434 | session.status === "running" && Number.isInteger(session.pid), |
| 1435 | ); |
| 1103 | 1436 | |
| 1104 | | const legacyPath = this.legacyHistoryPath(threadId); |
| 1105 | | try { |
| 1106 | | const raw = await fs.promises.readFile(legacyPath, "utf8"); |
| 1107 | | const capped = capHistory(raw, this.historyLineLimit); |
| 1108 | | |
| 1109 | | // Migrate legacy transcript filename to the terminal-scoped path. |
| 1110 | | await fs.promises.writeFile(nextPath, capped, "utf8"); |
| 1111 | | try { |
| 1112 | | await fs.promises.rm(legacyPath, { force: true }); |
| 1113 | | } catch (cleanupError) { |
| 1114 | | this.logger.warn("failed to remove legacy terminal history", { |
| 1115 | | threadId, |
| 1116 | | error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), |
| 1117 | | }); |
| 1437 | if (runningSessions.length === 0) { |
| 1438 | return; |
| 1118 | 1439 | } |
| 1119 | 1440 | |
| 1120 | | return capped; |
| 1121 | | } catch (error) { |
| 1122 | | if ((error as NodeJS.ErrnoException).code === "ENOENT") { |
| 1123 | | return ""; |
| 1124 | | } |
| 1125 | | throw error; |
| 1126 | | } |
| 1127 | | } |
| 1441 | const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( |
| 1442 | session: TerminalSessionState & { pid: number }, |
| 1443 | ) { |
| 1444 | const terminalPid = session.pid; |
| 1445 | const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe( |
| 1446 | Effect.map(Option.some), |
| 1447 | Effect.catch((error) => |
| 1448 | Effect.logWarning("failed to check terminal subprocess activity", { |
| 1449 | threadId: session.threadId, |
| 1450 | terminalId: session.terminalId, |
| 1451 | terminalPid, |
| 1452 | error: error instanceof Error ? error.message : String(error), |
| 1453 | }).pipe(Effect.as(Option.none<boolean>())), |
| 1454 | ), |
| 1455 | ); |
| 1128 | 1456 | |
| 1129 | | private async deleteHistory(threadId: string, terminalId: string): Promise<void> { |
| 1130 | | const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })]; |
| 1131 | | if (terminalId === DEFAULT_TERMINAL_ID) { |
| 1132 | | deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true })); |
| 1133 | | } |
| 1134 | | try { |
| 1135 | | await Promise.all(deletions); |
| 1136 | | } catch (error) { |
| 1137 | | this.logger.warn("failed to delete terminal history", { |
| 1138 | | threadId, |
| 1139 | | terminalId, |
| 1140 | | error: error instanceof Error ? error.message : String(error), |
| 1141 | | }); |
| 1142 | | } |
| 1143 | | } |
| 1457 | if (Option.isNone(hasRunningSubprocess)) { |
| 1458 | return; |
| 1459 | } |
| 1144 | 1460 | |
| 1145 | | private async flushPersistQueue(threadId: string, terminalId: string): Promise<void> { |
| 1146 | | const persistenceKey = toSessionKey(threadId, terminalId); |
| 1147 | | this.clearPersistTimer(threadId, terminalId); |
| 1461 | const event = yield* modifyManagerState((state) => { |
| 1462 | const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr( |
| 1463 | state.sessions.get(toSessionKey(session.threadId, session.terminalId)), |
| 1464 | ); |
| 1465 | if ( |
| 1466 | Option.isNone(liveSession) || |
| 1467 | liveSession.value.status !== "running" || |
| 1468 | liveSession.value.pid !== terminalPid || |
| 1469 | liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value |
| 1470 | ) { |
| 1471 | return [Option.none(), state] as const; |
| 1472 | } |
| 1148 | 1473 | |
| 1149 | | while (true) { |
| 1150 | | const pendingHistory = this.pendingPersistHistory.get(persistenceKey); |
| 1151 | | if (pendingHistory !== undefined) { |
| 1152 | | this.pendingPersistHistory.delete(persistenceKey); |
| 1153 | | await this.enqueuePersistWrite(threadId, terminalId, pendingHistory); |
| 1154 | | } |
| 1474 | liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value; |
| 1475 | liveSession.value.updatedAt = new Date().toISOString(); |
| 1476 | |
| 1477 | return [ |
| 1478 | Option.some({ |
| 1479 | type: "activity" as const, |
| 1480 | threadId: liveSession.value.threadId, |
| 1481 | terminalId: liveSession.value.terminalId, |
| 1482 | createdAt: new Date().toISOString(), |
| 1483 | hasRunningSubprocess: hasRunningSubprocess.value, |
| 1484 | }), |
| 1485 | state, |
| 1486 | ] as const; |
| 1487 | }); |
| 1155 | 1488 | |
| 1156 | | const pending = this.persistQueues.get(persistenceKey); |
| 1157 | | if (!pending) { |
| 1158 | | return; |
| 1159 | | } |
| 1160 | | await pending.catch(() => undefined); |
| 1161 | | } |
| 1162 | | } |
| 1489 | if (Option.isSome(event)) { |
| 1490 | yield* publishEvent(event.value); |
| 1491 | } |
| 1492 | }); |
| 1163 | 1493 | |
| 1164 | | private updateSubprocessPollingState(): void { |
| 1165 | | const hasRunningSessions = [...this.sessions.values()].some( |
| 1166 | | (session) => session.status === "running" && session.pid !== null, |
| 1167 | | ); |
| 1168 | | if (hasRunningSessions) { |
| 1169 | | this.ensureSubprocessPolling(); |
| 1170 | | return; |
| 1171 | | } |
| 1172 | | this.stopSubprocessPolling(); |
| 1173 | | } |
| 1494 | yield* Effect.forEach(runningSessions, checkSubprocessActivity, { |
| 1495 | concurrency: "unbounded", |
| 1496 | discard: true, |
| 1497 | }); |
| 1498 | }); |
| 1174 | 1499 | |
| 1175 | | private ensureSubprocessPolling(): void { |
| 1176 | | if (this.subprocessPollTimer) return; |
| 1177 | | this.subprocessPollTimer = setInterval(() => { |
| 1178 | | void this.pollSubprocessActivity(); |
| 1179 | | }, this.subprocessPollIntervalMs); |
| 1180 | | this.subprocessPollTimer.unref?.(); |
| 1181 | | void this.pollSubprocessActivity(); |
| 1182 | | } |
| 1500 | const hasRunningSessions = readManagerState.pipe( |
| 1501 | Effect.map((state) => |
| 1502 | [...state.sessions.values()].some((session) => session.status === "running"), |
| 1503 | ), |
| 1504 | ); |
| 1183 | 1505 | |
| 1184 | | private stopSubprocessPolling(): void { |
| 1185 | | if (!this.subprocessPollTimer) return; |
| 1186 | | clearInterval(this.subprocessPollTimer); |
| 1187 | | this.subprocessPollTimer = null; |
| 1188 | | } |
| 1506 | yield* Effect.forever( |
| 1507 | hasRunningSessions.pipe( |
| 1508 | Effect.flatMap((active) => |
| 1509 | active |
| 1510 | ? pollSubprocessActivity().pipe( |
| 1511 | Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)), |
| 1512 | ) |
| 1513 | : Effect.sleep(subprocessPollIntervalMs), |
| 1514 | ), |
| 1515 | ), |
| 1516 | ).pipe(Effect.forkIn(workerScope)); |
| 1517 | |
| 1518 | yield* Effect.addFinalizer(() => |
| 1519 | Effect.gen(function* () { |
| 1520 | const sessions = yield* modifyManagerState( |
| 1521 | (state) => |
| 1522 | [ |
| 1523 | [...state.sessions.values()], |
| 1524 | { |
| 1525 | ...state, |
| 1526 | sessions: new Map(), |
| 1527 | }, |
| 1528 | ] as const, |
| 1529 | ); |
| 1189 | 1530 | |
| 1190 | | private async pollSubprocessActivity(): Promise<void> { |
| 1191 | | if (this.subprocessPollInFlight) return; |
| 1531 | const cleanupSession = Effect.fn("terminal.cleanupSession")(function* ( |
| 1532 | session: TerminalSessionState, |
| 1533 | ) { |
| 1534 | cleanupProcessHandles(session); |
| 1535 | if (!session.process) return; |
| 1536 | yield* clearKillFiber(session.process); |
| 1537 | yield* runKillEscalation(session.process, session.threadId, session.terminalId); |
| 1538 | }); |
| 1192 | 1539 | |
| 1193 | | const runningSessions = [...this.sessions.values()].filter( |
| 1194 | | (session): session is TerminalSessionState & { pid: number } => |
| 1195 | | session.status === "running" && Number.isInteger(session.pid), |
| 1540 | yield* Effect.forEach(sessions, cleanupSession, { |
| 1541 | concurrency: "unbounded", |
| 1542 | discard: true, |
| 1543 | }); |
| 1544 | }).pipe(Effect.ignoreCause({ log: true })), |
| 1196 | 1545 | ); |
| 1197 | | if (runningSessions.length === 0) { |
| 1198 | | this.stopSubprocessPolling(); |
| 1199 | | return; |
| 1200 | | } |
| 1201 | 1546 | |
| 1202 | | this.subprocessPollInFlight = true; |
| 1203 | | try { |
| 1204 | | await Promise.all( |
| 1205 | | runningSessions.map(async (session) => { |
| 1206 | | const terminalPid = session.pid; |
| 1207 | | let hasRunningSubprocess = false; |
| 1208 | | try { |
| 1209 | | hasRunningSubprocess = await this.subprocessChecker(terminalPid); |
| 1210 | | } catch (error) { |
| 1211 | | this.logger.warn("failed to check terminal subprocess activity", { |
| 1212 | | threadId: session.threadId, |
| 1213 | | terminalId: session.terminalId, |
| 1214 | | terminalPid, |
| 1215 | | error: error instanceof Error ? error.message : String(error), |
| 1547 | const open: TerminalManagerShape["open"] = (input) => |
| 1548 | withThreadLock( |
| 1549 | input.threadId, |
| 1550 | Effect.gen(function* () { |
| 1551 | const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; |
| 1552 | yield* assertValidCwd(input.cwd); |
| 1553 | |
| 1554 | const sessionKey = toSessionKey(input.threadId, terminalId); |
| 1555 | const existing = yield* getSession(input.threadId, terminalId); |
| 1556 | if (Option.isNone(existing)) { |
| 1557 | yield* flushPersist(input.threadId, terminalId); |
| 1558 | const history = yield* readHistory(input.threadId, terminalId); |
| 1559 | const cols = input.cols ?? DEFAULT_OPEN_COLS; |
| 1560 | const rows = input.rows ?? DEFAULT_OPEN_ROWS; |
| 1561 | const session: TerminalSessionState = { |
| 1562 | threadId: input.threadId, |
| 1563 | terminalId, |
| 1564 | cwd: input.cwd, |
| 1565 | status: "starting", |
| 1566 | pid: null, |
| 1567 | history, |
| 1568 | pendingHistoryControlSequence: "", |
| 1569 | pendingProcessEvents: [], |
| 1570 | pendingProcessEventIndex: 0, |
| 1571 | processEventDrainRunning: false, |
| 1572 | exitCode: null, |
| 1573 | exitSignal: null, |
| 1574 | updatedAt: new Date().toISOString(), |
| 1575 | cols, |
| 1576 | rows, |
| 1577 | process: null, |
| 1578 | unsubscribeData: null, |
| 1579 | unsubscribeExit: null, |
| 1580 | hasRunningSubprocess: false, |
| 1581 | runtimeEnv: normalizedRuntimeEnv(input.env), |
| 1582 | }; |
| 1583 | |
| 1584 | const createdSession = session; |
| 1585 | yield* modifyManagerState((state) => { |
| 1586 | const sessions = new Map(state.sessions); |
| 1587 | sessions.set(sessionKey, createdSession); |
| 1588 | return [undefined, { ...state, sessions }] as const; |
| 1216 | 1589 | }); |
| 1217 | | return; |
| 1590 | |
| 1591 | yield* evictInactiveSessionsIfNeeded(); |
| 1592 | yield* startSession( |
| 1593 | session, |
| 1594 | { |
| 1595 | threadId: input.threadId, |
| 1596 | terminalId, |
| 1597 | cwd: input.cwd, |
| 1598 | cols, |
| 1599 | rows, |
| 1600 | ...(input.env ? { env: input.env } : {}), |
| 1601 | }, |
| 1602 | "started", |
| 1603 | ); |
| 1604 | return snapshot(session); |
| 1218 | 1605 | } |
| 1219 | 1606 | |
| 1220 | | const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId)); |
| 1221 | | if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) { |
| 1222 | | return; |
| 1607 | const liveSession = existing.value; |
| 1608 | const nextRuntimeEnv = normalizedRuntimeEnv(input.env); |
| 1609 | const currentRuntimeEnv = liveSession.runtimeEnv; |
| 1610 | const targetCols = input.cols ?? liveSession.cols; |
| 1611 | const targetRows = input.rows ?? liveSession.rows; |
| 1612 | const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv); |
| 1613 | |
| 1614 | if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { |
| 1615 | yield* stopProcess(liveSession); |
| 1616 | liveSession.cwd = input.cwd; |
| 1617 | liveSession.runtimeEnv = nextRuntimeEnv; |
| 1618 | liveSession.history = ""; |
| 1619 | liveSession.pendingHistoryControlSequence = ""; |
| 1620 | liveSession.pendingProcessEvents = []; |
| 1621 | liveSession.pendingProcessEventIndex = 0; |
| 1622 | liveSession.processEventDrainRunning = false; |
| 1623 | yield* persistHistory( |
| 1624 | liveSession.threadId, |
| 1625 | liveSession.terminalId, |
| 1626 | liveSession.history, |
| 1627 | ); |
| 1628 | } else if (liveSession.status === "exited" || liveSession.status === "error") { |
| 1629 | liveSession.runtimeEnv = nextRuntimeEnv; |
| 1630 | liveSession.history = ""; |
| 1631 | liveSession.pendingHistoryControlSequence = ""; |
| 1632 | liveSession.pendingProcessEvents = []; |
| 1633 | liveSession.pendingProcessEventIndex = 0; |
| 1634 | liveSession.processEventDrainRunning = false; |
| 1635 | yield* persistHistory( |
| 1636 | liveSession.threadId, |
| 1637 | liveSession.terminalId, |
| 1638 | liveSession.history, |
| 1639 | ); |
| 1223 | 1640 | } |
| 1224 | | if (liveSession.hasRunningSubprocess === hasRunningSubprocess) { |
| 1225 | | return; |
| 1641 | |
| 1642 | if (!liveSession.process) { |
| 1643 | yield* startSession( |
| 1644 | liveSession, |
| 1645 | { |
| 1646 | threadId: input.threadId, |
| 1647 | terminalId, |
| 1648 | cwd: input.cwd, |
| 1649 | cols: targetCols, |
| 1650 | rows: targetRows, |
| 1651 | ...(input.env ? { env: input.env } : {}), |
| 1652 | }, |
| 1653 | "started", |
| 1654 | ); |
| 1655 | return snapshot(liveSession); |
| 1226 | 1656 | } |
| 1227 | 1657 | |
| 1228 | | liveSession.hasRunningSubprocess = hasRunningSubprocess; |
| 1229 | | liveSession.updatedAt = new Date().toISOString(); |
| 1230 | | this.emitEvent({ |
| 1231 | | type: "activity", |
| 1232 | | threadId: liveSession.threadId, |
| 1233 | | terminalId: liveSession.terminalId, |
| 1234 | | createdAt: new Date().toISOString(), |
| 1235 | | hasRunningSubprocess, |
| 1236 | | }); |
| 1658 | if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { |
| 1659 | liveSession.cols = targetCols; |
| 1660 | liveSession.rows = targetRows; |
| 1661 | liveSession.updatedAt = new Date().toISOString(); |
| 1662 | liveSession.process.resize(targetCols, targetRows); |
| 1663 | } |
| 1664 | |
| 1665 | return snapshot(liveSession); |
| 1237 | 1666 | }), |
| 1238 | 1667 | ); |
| 1239 | | } finally { |
| 1240 | | this.subprocessPollInFlight = false; |
| 1241 | | } |
| 1242 | | } |
| 1243 | 1668 | |
| 1244 | | private async assertValidCwd(cwd: string): Promise<void> { |
| 1245 | | let stats: fs.Stats; |
| 1246 | | try { |
| 1247 | | stats = await fs.promises.stat(cwd); |
| 1248 | | } catch (error) { |
| 1249 | | if ((error as NodeJS.ErrnoException).code === "ENOENT") { |
| 1250 | | throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error }); |
| 1669 | const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) { |
| 1670 | const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; |
| 1671 | const session = yield* requireSession(input.threadId, terminalId); |
| 1672 | const process = session.process; |
| 1673 | if (!process || session.status !== "running") { |
| 1674 | if (session.status === "exited") return; |
| 1675 | return yield* new TerminalNotRunningError({ |
| 1676 | threadId: input.threadId, |
| 1677 | terminalId, |
| 1678 | }); |
| 1251 | 1679 | } |
| 1252 | | throw error; |
| 1253 | | } |
| 1254 | | if (!stats.isDirectory()) { |
| 1255 | | throw new Error(`Terminal cwd is not a directory: ${cwd}`); |
| 1256 | | } |
| 1257 | | } |
| 1258 | | |
| 1259 | | private async closeSession( |
| 1260 | | threadId: string, |
| 1261 | | terminalId: string, |
| 1262 | | deleteHistory: boolean, |
| 1263 | | ): Promise<void> { |
| 1264 | | const key = toSessionKey(threadId, terminalId); |
| 1265 | | const session = this.sessions.get(key); |
| 1266 | | if (session) { |
| 1267 | | this.stopProcess(session); |
| 1268 | | this.sessions.delete(key); |
| 1269 | | } |
| 1270 | | this.updateSubprocessPollingState(); |
| 1271 | | await this.flushPersistQueue(threadId, terminalId); |
| 1272 | | if (deleteHistory) { |
| 1273 | | await this.deleteHistory(threadId, terminalId); |
| 1274 | | } |
| 1275 | | } |
| 1276 | | |
| 1277 | | private sessionsForThread(threadId: string): TerminalSessionState[] { |
| 1278 | | return [...this.sessions.values()].filter((session) => session.threadId === threadId); |
| 1279 | | } |
| 1280 | | |
| 1281 | | private async deleteAllHistoryForThread(threadId: string): Promise<void> { |
| 1282 | | const threadPrefix = `${toSafeThreadId(threadId)}_`; |
| 1283 | | try { |
| 1284 | | const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true }); |
| 1285 | | const removals = entries |
| 1286 | | .filter((entry) => entry.isFile()) |
| 1287 | | .map((entry) => entry.name) |
| 1288 | | .filter( |
| 1289 | | (name) => |
| 1290 | | name === `${toSafeThreadId(threadId)}.log` || |
| 1291 | | name === `${legacySafeThreadId(threadId)}.log` || |
| 1292 | | name.startsWith(threadPrefix), |
| 1293 | | ) |
| 1294 | | .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true })); |
| 1295 | | await Promise.all(removals); |
| 1296 | | } catch (error) { |
| 1297 | | this.logger.warn("failed to delete terminal histories for thread", { |
| 1298 | | threadId, |
| 1299 | | error: error instanceof Error ? error.message : String(error), |
| 1300 | | }); |
| 1301 | | } |
| 1302 | | } |
| 1303 | | |
| 1304 | | private requireSession(threadId: string, terminalId: string): TerminalSessionState { |
| 1305 | | const session = this.sessions.get(toSessionKey(threadId, terminalId)); |
| 1306 | | if (!session) { |
| 1307 | | throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`); |
| 1308 | | } |
| 1309 | | return session; |
| 1310 | | } |
| 1680 | yield* Effect.sync(() => process.write(input.data)); |
| 1681 | }); |
| 1311 | 1682 | |
| 1312 | | private snapshot(session: TerminalSessionState): TerminalSessionSnapshot { |
| 1313 | | return { |
| 1314 | | threadId: session.threadId, |
| 1315 | | terminalId: session.terminalId, |
| 1316 | | cwd: session.cwd, |
| 1317 | | status: session.status, |
| 1318 | | pid: session.pid, |
| 1319 | | history: session.history, |
| 1320 | | exitCode: session.exitCode, |
| 1321 | | exitSignal: session.exitSignal, |
| 1322 | | updatedAt: session.updatedAt, |
| 1323 | | }; |
| 1324 | | } |
| 1683 | const resize: TerminalManagerShape["resize"] = Effect.fn("terminal.resize")(function* (input) { |
| 1684 | const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; |
| 1685 | const session = yield* requireSession(input.threadId, terminalId); |
| 1686 | const process = session.process; |
| 1687 | if (!process || session.status !== "running") { |
| 1688 | return yield* new TerminalNotRunningError({ |
| 1689 | threadId: input.threadId, |
| 1690 | terminalId, |
| 1691 | }); |
| 1692 | } |
| 1693 | session.cols = input.cols; |
| 1694 | session.rows = input.rows; |
| 1695 | session.updatedAt = new Date().toISOString(); |
| 1696 | yield* Effect.sync(() => process.resize(input.cols, input.rows)); |
| 1697 | }); |
| 1325 | 1698 | |
| 1326 | | private emitEvent(event: TerminalEvent): void { |
| 1327 | | this.emit("event", event); |
| 1328 | | } |
| 1699 | const clear: TerminalManagerShape["clear"] = (input) => |
| 1700 | withThreadLock( |
| 1701 | input.threadId, |
| 1702 | Effect.gen(function* () { |
| 1703 | const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; |
| 1704 | const session = yield* requireSession(input.threadId, terminalId); |
| 1705 | session.history = ""; |
| 1706 | session.pendingHistoryControlSequence = ""; |
| 1707 | session.pendingProcessEvents = []; |
| 1708 | session.pendingProcessEventIndex = 0; |
| 1709 | session.processEventDrainRunning = false; |
| 1710 | session.updatedAt = new Date().toISOString(); |
| 1711 | yield* persistHistory(input.threadId, terminalId, session.history); |
| 1712 | yield* publishEvent({ |
| 1713 | type: "cleared", |
| 1714 | threadId: input.threadId, |
| 1715 | terminalId, |
| 1716 | createdAt: new Date().toISOString(), |
| 1717 | }); |
| 1718 | }), |
| 1719 | ); |
| 1329 | 1720 | |
| 1330 | | private historyPath(threadId: string, terminalId: string): string { |
| 1331 | | const threadPart = toSafeThreadId(threadId); |
| 1332 | | if (terminalId === DEFAULT_TERMINAL_ID) { |
| 1333 | | return path.join(this.logsDir, `${threadPart}.log`); |
| 1334 | | } |
| 1335 | | return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); |
| 1336 | | } |
| 1721 | const restart: TerminalManagerShape["restart"] = (input) => |
| 1722 | withThreadLock( |
| 1723 | input.threadId, |
| 1724 | Effect.gen(function* () { |
| 1725 | const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; |
| 1726 | yield* assertValidCwd(input.cwd); |
| 1727 | |
| 1728 | const sessionKey = toSessionKey(input.threadId, terminalId); |
| 1729 | const existingSession = yield* getSession(input.threadId, terminalId); |
| 1730 | let session: TerminalSessionState; |
| 1731 | if (Option.isNone(existingSession)) { |
| 1732 | const cols = input.cols ?? DEFAULT_OPEN_COLS; |
| 1733 | const rows = input.rows ?? DEFAULT_OPEN_ROWS; |
| 1734 | session = { |
| 1735 | threadId: input.threadId, |
| 1736 | terminalId, |
| 1737 | cwd: input.cwd, |
| 1738 | status: "starting", |
| 1739 | pid: null, |
| 1740 | history: "", |
| 1741 | pendingHistoryControlSequence: "", |
| 1742 | pendingProcessEvents: [], |
| 1743 | pendingProcessEventIndex: 0, |
| 1744 | processEventDrainRunning: false, |
| 1745 | exitCode: null, |
| 1746 | exitSignal: null, |
| 1747 | updatedAt: new Date().toISOString(), |
| 1748 | cols, |
| 1749 | rows, |
| 1750 | process: null, |
| 1751 | unsubscribeData: null, |
| 1752 | unsubscribeExit: null, |
| 1753 | hasRunningSubprocess: false, |
| 1754 | runtimeEnv: normalizedRuntimeEnv(input.env), |
| 1755 | }; |
| 1756 | const createdSession = session; |
| 1757 | yield* modifyManagerState((state) => { |
| 1758 | const sessions = new Map(state.sessions); |
| 1759 | sessions.set(sessionKey, createdSession); |
| 1760 | return [undefined, { ...state, sessions }] as const; |
| 1761 | }); |
| 1762 | yield* evictInactiveSessionsIfNeeded(); |
| 1763 | } else { |
| 1764 | session = existingSession.value; |
| 1765 | yield* stopProcess(session); |
| 1766 | session.cwd = input.cwd; |
| 1767 | session.runtimeEnv = normalizedRuntimeEnv(input.env); |
| 1768 | } |
| 1337 | 1769 | |
| 1338 | | private legacyHistoryPath(threadId: string): string { |
| 1339 | | return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`); |
| 1340 | | } |
| 1770 | const cols = input.cols ?? session.cols; |
| 1771 | const rows = input.rows ?? session.rows; |
| 1772 | |
| 1773 | session.history = ""; |
| 1774 | session.pendingHistoryControlSequence = ""; |
| 1775 | session.pendingProcessEvents = []; |
| 1776 | session.pendingProcessEventIndex = 0; |
| 1777 | session.processEventDrainRunning = false; |
| 1778 | yield* persistHistory(input.threadId, terminalId, session.history); |
| 1779 | yield* startSession( |
| 1780 | session, |
| 1781 | { |
| 1782 | threadId: input.threadId, |
| 1783 | terminalId, |
| 1784 | cwd: input.cwd, |
| 1785 | cols, |
| 1786 | rows, |
| 1787 | ...(input.env ? { env: input.env } : {}), |
| 1788 | }, |
| 1789 | "restarted", |
| 1790 | ); |
| 1791 | return snapshot(session); |
| 1792 | }), |
| 1793 | ); |
| 1341 | 1794 | |
| 1342 | | private async runWithThreadLock<T>(threadId: string, task: () => Promise<T>): Promise<T> { |
| 1343 | | const previous = this.threadLocks.get(threadId) ?? Promise.resolve(); |
| 1344 | | let release!: () => void; |
| 1345 | | const current = new Promise<void>((resolve) => { |
| 1346 | | release = resolve; |
| 1347 | | }); |
| 1348 | | this.threadLocks.set(threadId, current); |
| 1349 | | await previous.catch(() => undefined); |
| 1350 | | try { |
| 1351 | | return await task(); |
| 1352 | | } finally { |
| 1353 | | release(); |
| 1354 | | if (this.threadLocks.get(threadId) === current) { |
| 1355 | | this.threadLocks.delete(threadId); |
| 1356 | | } |
| 1357 | | } |
| 1358 | | } |
| 1359 | | } |
| 1795 | const close: TerminalManagerShape["close"] = (input) => |
| 1796 | withThreadLock( |
| 1797 | input.threadId, |
| 1798 | Effect.gen(function* () { |
| 1799 | if (input.terminalId) { |
| 1800 | yield* closeSession(input.threadId, input.terminalId, input.deleteHistory === true); |
| 1801 | return; |
| 1802 | } |
| 1360 | 1803 | |
| 1361 | | export const TerminalManagerLive = Layer.effect( |
| 1362 | | TerminalManager, |
| 1363 | | Effect.gen(function* () { |
| 1364 | | const { terminalLogsDir } = yield* ServerConfig; |
| 1804 | const threadSessions = yield* sessionsForThread(input.threadId); |
| 1805 | yield* Effect.forEach( |
| 1806 | threadSessions, |
| 1807 | (session) => closeSession(input.threadId, session.terminalId, false), |
| 1808 | { discard: true }, |
| 1809 | ); |
| 1365 | 1810 | |
| 1366 | | const ptyAdapter = yield* PtyAdapter; |
| 1367 | | const runtime = yield* Effect.acquireRelease( |
| 1368 | | Effect.sync(() => new TerminalManagerRuntime({ logsDir: terminalLogsDir, ptyAdapter })), |
| 1369 | | (r) => Effect.sync(() => r.dispose()), |
| 1370 | | ); |
| 1811 | if (input.deleteHistory) { |
| 1812 | yield* deleteAllHistoryForThread(input.threadId); |
| 1813 | } |
| 1814 | }), |
| 1815 | ); |
| 1371 | 1816 | |
| 1372 | 1817 | return { |
| 1373 | | open: (input) => |
| 1374 | | Effect.tryPromise({ |
| 1375 | | try: () => runtime.open(input), |
| 1376 | | catch: (cause) => new TerminalError({ message: "Failed to open terminal", cause }), |
| 1377 | | }), |
| 1378 | | write: (input) => |
| 1379 | | Effect.tryPromise({ |
| 1380 | | try: () => runtime.write(input), |
| 1381 | | catch: (cause) => new TerminalError({ message: "Failed to write to terminal", cause }), |
| 1382 | | }), |
| 1383 | | resize: (input) => |
| 1384 | | Effect.tryPromise({ |
| 1385 | | try: () => runtime.resize(input), |
| 1386 | | catch: (cause) => new TerminalError({ message: "Failed to resize terminal", cause }), |
| 1387 | | }), |
| 1388 | | clear: (input) => |
| 1389 | | Effect.tryPromise({ |
| 1390 | | try: () => runtime.clear(input), |
| 1391 | | catch: (cause) => new TerminalError({ message: "Failed to clear terminal", cause }), |
| 1392 | | }), |
| 1393 | | restart: (input) => |
| 1394 | | Effect.tryPromise({ |
| 1395 | | try: () => runtime.restart(input), |
| 1396 | | catch: (cause) => new TerminalError({ message: "Failed to restart terminal", cause }), |
| 1397 | | }), |
| 1398 | | close: (input) => |
| 1399 | | Effect.tryPromise({ |
| 1400 | | try: () => runtime.close(input), |
| 1401 | | catch: (cause) => new TerminalError({ message: "Failed to close terminal", cause }), |
| 1402 | | }), |
| 1818 | open, |
| 1819 | write, |
| 1820 | resize, |
| 1821 | clear, |
| 1822 | restart, |
| 1823 | close, |
| 1403 | 1824 | subscribe: (listener) => |
| 1404 | 1825 | Effect.sync(() => { |
| 1405 | | runtime.on("event", listener); |
| 1826 | terminalEventListeners.add(listener); |
| 1406 | 1827 | return () => { |
| 1407 | | runtime.off("event", listener); |
| 1828 | terminalEventListeners.delete(listener); |
| 1408 | 1829 | }; |
| 1409 | 1830 | }), |
| 1410 | | dispose: Effect.sync(() => runtime.dispose()), |
| 1411 | 1831 | } satisfies TerminalManagerShape; |
| 1412 | | }), |
| 1832 | }, |
| 1413 | 1833 | ); |
| 1834 | |
| 1835 | export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()); |