The best way to control Claude Code, Codex and more from any computer or phone

main
ts 3,256 lines 129 KB
Raw
1 import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { assert, it } from "@effect/vitest";
5 import {
6 DEFAULT_TERMINAL_ID,
7 ProjectId,
8 ThreadId,
9 TerminalCwdNotFoundError,
10 type TerminalAttachStreamEvent,
11 type TerminalEvent,
12 type TerminalOpenInput,
13 ProviderDriverKind,
14 ProviderInstanceId,
15 retainedTerminalHistory,
16 terminalSequenceEnd,
17 terminalSequenceStateAfter,
18 TerminalProviderInstanceNotFoundError,
19 } from "@t3tools/contracts";
20 import * as HostProcess from "@t3tools/shared/HostProcess";
21 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
22 import * as NodePtyAdapter from "./NodePtyAdapter.ts";
23 import * as Clock from "effect/Clock";
24 import * as Deferred from "effect/Deferred";
25 import * as Duration from "effect/Duration";
26 import * as Effect from "effect/Effect";
27 import * as Base64Url from "effect/encoding/Base64Url";
28 import * as Exit from "effect/Exit";
29 import * as Fiber from "effect/Fiber";
30 import * as FileSystem from "effect/FileSystem";
31 import * as Layer from "effect/Layer";
32 import * as Option from "effect/Option";
33 import * as PlatformError from "effect/PlatformError";
34 import * as Path from "effect/Path";
35 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
36 import * as Ref from "effect/Ref";
37 import * as Queue from "effect/Queue";
38 import * as Schema from "effect/Schema";
39 import * as Scope from "effect/Scope";
40 import * as Stream from "effect/Stream";
41 import * as SynchronizedRef from "effect/SynchronizedRef";
42 import * as TestClock from "effect/testing/TestClock";
43 import { expect, vi } from "vite-plus/test";
44
45 import * as ServerConfig from "../config.ts";
46 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
47 import * as ProcessRunner from "../processRunner.ts";
48 import * as ServerSettings from "../serverSettings.ts";
49 import * as ProjectService from "../project/ProjectService.ts";
50 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
51 import * as TerminalManager from "./Manager.ts";
52 import * as GitWorkflowService from "../git/GitWorkflowService.ts";
53 import { makePrepareTerminalLaunch } from "../workspace/restoreMissingWorktree.ts";
54 import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
55 import { terminalOutputStream } from "./OutputProtocol.ts";
56 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
57 import packageJson from "../../package.json" with { type: "json" };
58
59 vi.mock("effect/SynchronizedRef", async (importOriginal) => {
60 const original = await importOriginal<typeof SynchronizedRef>();
61 return { ...original, make: vi.fn(original.make) };
62 });
63
64 // The server omits DOM types, which include TypeScript's WebAssembly declarations.
65
66 const POWERSHELL_ARGS = [
67 "-NoLogo",
68 "-NoExit",
69 "-Command",
70 "[Console]::OutputEncoding = $OutputEncoding = [System.Text.UTF8Encoding]::new()",
71 ];
72 const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
73
74 class FakePtyProcess implements PtyAdapter.PtyProcess {
75 readonly writes: Array<string | Buffer> = [];
76 readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
77 readonly killSignals: Array<string | undefined> = [];
78 readonly pid: number;
79 writeFailure: unknown | undefined;
80 resizeFailure: unknown | undefined;
81 private readonly dataListeners = new Set<(data: string) => void>();
82 private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
83 killed = false;
84 exitOnSubscribe: PtyAdapter.PtyExitEvent | undefined;
85 onKill: ((signal?: string) => void) | undefined;
86
87 constructor(pid: number) {
88 this.pid = pid;
89 }
90
91 write(data: string | Buffer): void {
92 if (this.writeFailure !== undefined) {
93 throw this.writeFailure;
94 }
95 this.writes.push(data);
96 }
97
98 resize(cols: number, rows: number): void {
99 if (this.resizeFailure !== undefined) {
100 throw this.resizeFailure;
101 }
102 this.resizeCalls.push({ cols, rows });
103 }
104
105 kill(signal?: string): void {
106 this.killed = true;
107 this.killSignals.push(signal);
108 this.onKill?.(signal);
109 }
110
111 onData(callback: (data: string) => void): () => void {
112 this.dataListeners.add(callback);
113 return () => {
114 this.dataListeners.delete(callback);
115 };
116 }
117
118 onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
119 if (this.exitOnSubscribe) callback(this.exitOnSubscribe);
120 this.exitListeners.add(callback);
121 return () => {
122 this.exitListeners.delete(callback);
123 };
124 }
125
126 emitData(data: string): void {
127 for (const listener of this.dataListeners) {
128 listener(data);
129 }
130 }
131
132 get exitListenerCount(): number {
133 return this.exitListeners.size;
134 }
135
136 emitExit(event: PtyAdapter.PtyExitEvent): void {
137 for (const listener of this.exitListeners) {
138 listener(event);
139 }
140 }
141 }
142
143 class FakePtyAdapter {
144 readonly spawnInputs: PtyAdapter.PtySpawnInput[] = [];
145 readonly processes: FakePtyProcess[] = [];
146 readonly spawnFailures: Error[] = [];
147 private readonly mode: "sync" | "async";
148 private nextPid = 9000;
149 exitOnSubscribe: PtyAdapter.PtyExitEvent | undefined;
150
151 constructor(mode: "sync" | "async" = "sync") {
152 this.mode = mode;
153 }
154
155 spawn(
156 input: PtyAdapter.PtySpawnInput,
157 ): Effect.Effect<PtyAdapter.PtyProcess, PtyAdapter.PtySpawnError> {
158 this.spawnInputs.push(input);
159 const failure = this.spawnFailures.shift();
160 if (failure) {
161 return Effect.fail(
162 new PtyAdapter.PtySpawnError({
163 adapter: "fake",
164 shell: input.shell,
165 cause: failure,
166 }),
167 );
168 }
169 const process = new FakePtyProcess(this.nextPid++);
170 process.exitOnSubscribe = this.exitOnSubscribe;
171 this.processes.push(process);
172 if (this.mode === "async") {
173 return Effect.tryPromise({
174 try: async () => process,
175 catch: (cause) =>
176 new PtyAdapter.PtySpawnError({
177 adapter: "fake",
178 shell: input.shell,
179 cause,
180 }),
181 });
182 }
183 return Effect.succeed(process);
184 }
185 }
186
187 // Publishes 9 MiB of output, past a stream's 8 MiB budget, while nothing pulls.
188 const publishPastOutputBudget = (
189 manager: TerminalManager.TerminalManager["Service"],
190 process: FakePtyProcess,
191 ) =>
192 Effect.gen(function* () {
193 const published = yield* Deferred.make<void>();
194 const unsubscribe = yield* manager.subscribe((event) =>
195 event.type === "output" && event.data === "last\n"
196 ? Deferred.succeed(published, undefined).pipe(Effect.asVoid)
197 : Effect.void,
198 );
199 for (let index = 0; index < 9; index++) process.emitData("x".repeat(1024 * 1024));
200 process.emitData("last\n");
201 yield* Deferred.await(published);
202 unsubscribe();
203 });
204
205 // Holds the next spawn, and with it the thread lock, until `release` succeeds.
206 class GatedPtyAdapter extends FakePtyAdapter {
207 gate: {
208 readonly spawning: Deferred.Deferred<void>;
209 readonly release: Deferred.Deferred<void>;
210 } | null = null;
211
212 override spawn(
213 input: PtyAdapter.PtySpawnInput,
214 ): Effect.Effect<PtyAdapter.PtyProcess, PtyAdapter.PtySpawnError> {
215 const gate = this.gate;
216 this.gate = null;
217 if (!gate) return super.spawn(input);
218 return Deferred.succeed(gate.spawning, undefined).pipe(
219 Effect.andThen(Deferred.await(gate.release)),
220 Effect.andThen(super.spawn(input)),
221 );
222 }
223 }
224
225 function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
226 return {
227 threadId: "thread-1",
228 terminalId: DEFAULT_TERMINAL_ID,
229 cwd: process.cwd(),
230 cols: 100,
231 rows: 24,
232 ...overrides,
233 };
234 }
235
236 const historyLogPath = (logsDir: string, threadId = "thread-1") =>
237 Effect.service(Path.Path).pipe(
238 Effect.map(({ join }) => join(logsDir, `terminal_${Base64Url.encode(threadId)}.log`)),
239 );
240
241 interface CreateManagerOptions {
242 shellResolver?: () => string;
243 env?: NodeJS.ProcessEnv;
244 subprocessInspector?: (terminalPid: number) => Effect.Effect<{
245 readonly hasRunningSubprocess: boolean;
246 readonly childCommand: string | null;
247 readonly processIds: ReadonlyArray<number>;
248 }>;
249 processTable?: Effect.Effect<
250 ReadonlyArray<{ readonly pid: number; readonly ppid: number; readonly name: string }>,
251 never
252 >;
253 foregroundProcessGroup?: (terminalPid: number) => Effect.Effect<number | null>;
254 subprocessPollIntervalMs?: number;
255 processKillGraceMs?: number;
256 registerTerminalProcesses?: Parameters<
257 typeof TerminalManager.makeWithOptions
258 >[0]["registerTerminalProcesses"];
259 maxRetainedInactiveSessions?: number;
260 historyByteLimit?: number;
261 ptyAdapter?: FakePtyAdapter;
262 resolveProviderInstanceEnvironment?: Parameters<
263 typeof TerminalManager.makeWithOptions
264 >[0]["resolveProviderInstanceEnvironment"];
265 managedBinaryCacheDir?: string;
266 managedBinaryToolsDir?: string;
267 }
268
269 interface ManagerFixture {
270 readonly baseDir: string;
271 readonly logsDir: string;
272 readonly ptyAdapter: FakePtyAdapter;
273 readonly manager: TerminalManager.TerminalManager["Service"];
274 readonly getEvents: Effect.Effect<ReadonlyArray<TerminalEvent>>;
275 }
276
277 const createManager = (
278 historyLineLimit = 5,
279 options: CreateManagerOptions = {},
280 ): Effect.Effect<
281 ManagerFixture,
282 PlatformError.PlatformError,
283 FileSystem.FileSystem | Path.Path | Scope.Scope | ProcessRunner.ProcessRunner
284 > =>
285 Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
286 Effect.gen(function* () {
287 const { join } = yield* Path.Path;
288 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" });
289 const logsDir = join(baseDir, "userdata", "logs", "terminals");
290 const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
291
292 const manager = yield* TerminalManager.makeWithOptions({
293 logsDir,
294 historyLineLimit,
295 ptyAdapter,
296 ...(options.historyByteLimit !== undefined
297 ? { historyByteLimit: options.historyByteLimit }
298 : {}),
299 ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}),
300 ...(options.env !== undefined ? { env: options.env } : {}),
301 ...(options.subprocessInspector !== undefined
302 ? { subprocessInspector: options.subprocessInspector }
303 : {}),
304 ...(options.processTable !== undefined ? { processTable: options.processTable } : {}),
305 // Fixture pids are not real processes; default to a shell idle at its prompt.
306 foregroundProcessGroup: options.foregroundProcessGroup ?? ((pid) => Effect.succeed(pid)),
307 ...(options.subprocessPollIntervalMs !== undefined
308 ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
309 : {}),
310 processKillGraceMs: options.processKillGraceMs ?? 1,
311 ...(options.registerTerminalProcesses !== undefined
312 ? { registerTerminalProcesses: options.registerTerminalProcesses }
313 : {}),
314 ...(options.maxRetainedInactiveSessions !== undefined
315 ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions }
316 : {}),
317 ...(options.resolveProviderInstanceEnvironment !== undefined
318 ? { resolveProviderInstanceEnvironment: options.resolveProviderInstanceEnvironment }
319 : {}),
320 ...(options.managedBinaryCacheDir === undefined
321 ? {}
322 : {
323 managedBinaryCacheDir: options.managedBinaryCacheDir,
324 managedBinaryToolsDir: options.managedBinaryToolsDir,
325 }),
326 }).pipe(Effect.provideService(SpawnExecutableResolution, (command) => command));
327 const eventsRef = yield* Ref.make<ReadonlyArray<TerminalEvent>>([]);
328 const unsubscribe = yield* manager.subscribe((event) =>
329 Ref.update(eventsRef, (events) => [...events, event]),
330 );
331 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
332
333 return {
334 baseDir,
335 logsDir,
336 join,
337 ptyAdapter,
338 manager,
339 getEvents: Ref.get(eventsRef),
340 };
341 }),
342 );
343
344 const layerWithHostPlatform = (platform: NodeJS.Platform) =>
345 Layer.succeed(HostProcess.Platform, platform);
346
347 function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): string {
348 const terminated = text.endsWith("\n");
349 const lines = text.split("\n");
350 if (terminated) lines.pop();
351 const retained = lines.slice(Math.max(0, lines.length - maxLines)).join("\n");
352 const capped = terminated ? `${retained}\n` : retained;
353 const points = Array.from(capped);
354 let start = points.length;
355 let bytes = 0;
356 while (start > 0) {
357 const next = Buffer.byteLength(points[start - 1]!);
358 if (bytes + next > maxBytes) break;
359 bytes += next;
360 start -= 1;
361 }
362 const kept = points.slice(start).join("");
363 if (maxLines <= 0 || maxBytes <= 0) return kept;
364 // A cut inside a control sequence drops the rest of that sequence too.
365 const state = terminalSequenceStateAfter(0, text, 0, text.length - kept.length);
366 return kept.slice(terminalSequenceEnd(state, kept));
367 }
368
369 it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequences, and clear", () => {
370 let randomSeed = 0x20260904;
371 const fragments = [
372 "",
373 "a",
374 "\n",
375 "\n\n",
376 "\r",
377 "\r\n",
378 "café",
379 "名",
380 "🚀",
381 "\u001b[31m",
382 "\u001b[0m",
383 "\u001b]8;;url\u0007",
384 "\u001b]0;",
385 "\u001bP",
386 "\u0007",
387 "\u001b\\",
388 "\ud83d",
389 "\ude80",
390 ];
391 const nextFragment = () => {
392 randomSeed = (Math.imul(randomSeed, 1_664_525) + 1_013_904_223) >>> 0;
393 return fragments[randomSeed % fragments.length]!;
394 };
395
396 for (const maxBytes of [0, 3, 8, 64, Infinity]) {
397 for (const maxLines of [0, 1, 3, 5, 5_000]) {
398 let full = "before\ninitial\n";
399 let expected = retainedHistory(full, maxLines, maxBytes);
400 const history = new TerminalManager.BoundedTerminalHistory(
401 maxLines,
402 "before\ninitial\n",
403 maxBytes,
404 );
405 expect(history.value()).toBe(expected);
406
407 for (let step = 0; step < 300; step += 1) {
408 if (step % 73 === 0) {
409 history.clear();
410 full = "";
411 expect(history.value()).toBe("");
412 }
413 const chunk = nextFragment() + nextFragment();
414 history.append(chunk);
415 full += chunk;
416 expected = retainedHistory(full, maxLines, maxBytes);
417 expect(history.value()).toBe(expected);
418 }
419 }
420 }
421 });
422
423 it("does not retain the tail of a control sequence whose introducer was trimmed", () => {
424 for (const [text, maxBytes, retained] of [
425 ["prefix\u001b[31mOK", 6, "OK"],
426 ["prefix\u001b]0;HIDDEN\u0007OK", 10, "OK"],
427 ["prefix\u001b]0;🙂HIDDEN\u0007OK", 9, "OK"],
428 // libghostty leaves every string but OSC at the emoji's second byte, so HELLO was visible.
429 ["prefix\u001bP🙂HELLO\u001b\\OK", 9, "HELLO\u001b\\OK"],
430 ] as const) {
431 expect(new TerminalManager.BoundedTerminalHistory(5_000, text, maxBytes).value()).toBe(
432 retained,
433 );
434 }
435 });
436
437 it("bounds long partial lines and joins surrogate pairs across chunk boundaries", () => {
438 const maxBytes = 65_539;
439 let expected = "";
440 const history = new TerminalManager.BoundedTerminalHistory(5_000, "", maxBytes);
441 const writes = [
442 "a".repeat(16_383) + "😀" + "b".repeat(70_000),
443 "\r" + "c".repeat(70_000) + "\ud83d",
444 "\ude80" + "d".repeat(100),
445 "\uFEFF" + "名".repeat(30_000),
446 ];
447 for (const text of writes) {
448 history.append(text);
449 expected = retainedHistory(expected + text, 5_000, maxBytes);
450 expect(history.value()).toBe(expected);
451 expect(Buffer.byteLength(history.value())).toBeLessThanOrEqual(maxBytes);
452 }
453 });
454
455 it("restores bounded history across append compaction, clears and split Unicode", () => {
456 const maxBytes = 64;
457 const history = new TerminalManager.BoundedTerminalHistory(3, "", maxBytes);
458 let cursor: ReturnType<typeof history.persistenceUpdate>["cursor"] | undefined;
459 let persisted = "";
460 let compactions = 0;
461 const flush = () => {
462 const update = history.persistenceUpdate(cursor);
463 if (!update.append) compactions += 1;
464 const encoded = Buffer.from(update.data).toString();
465 persisted = update.append ? persisted + encoded : encoded;
466 cursor = update.cursor;
467 expect(Buffer.byteLength(persisted)).toBeLessThanOrEqual(maxBytes * 2);
468 expect(retainedHistory(persisted, 3, maxBytes)).toBe(Buffer.from(history.value()).toString());
469 };
470 for (let index = 0; index < 100; index += 1) {
471 history.append(`line ${index} 名\n`);
472 flush();
473 }
474 expect(compactions).toBeGreaterThan(1);
475 expect(compactions).toBeLessThan(50);
476 history.clear();
477 flush();
478 expect(persisted).toBe("");
479 history.append("\ud83d");
480 flush();
481 history.append("\ude80");
482 flush();
483 expect(persisted).toBe("🚀");
484 // More output than the retained window between flushes must replace the file.
485 history.append("z".repeat(maxBytes * 3));
486 flush();
487 expect(persisted).toBe("z".repeat(maxBytes));
488 });
489
490 it.layer(
491 Layer.mergeAll(
492 NodeServices.layer,
493 NodeCrypto.layer,
494 ProcessRunner.layer.pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
495 ),
496 { excludeTestServices: true },
497 )("TerminalManager", (it) => {
498 it.effect.each([
499 { method: "open", location: "managed" },
500 { method: "attach", location: "managed" },
501 { method: "open", location: "subdirectory" },
502 { method: "open", location: "unmanaged" },
503 { method: "open", location: "no-worktree" },
504 ] as const)(
505 "recovers $method with a $location cwd without a cleanup gap",
506 ({ method, location }) =>
507 Effect.gen(function* () {
508 const fs = yield* FileSystem.FileSystem;
509 const path = yield* Path.Path;
510 const { manager, ptyAdapter, baseDir } = yield* createManager();
511 const worktreesDir = path.join(baseDir, "worktrees");
512 const worktreePath =
513 location === "unmanaged"
514 ? path.join(baseDir, "missing")
515 : path.join(worktreesDir, "project", "feature");
516 const cwd = location === "subdirectory" ? path.join(worktreePath, "src") : worktreePath;
517 const cleanupQueued = yield* Deferred.make<Fiber.Fiber<void>>();
518 let creations = 0;
519 const prepareLaunch = yield* makePrepareTerminalLaunch(() =>
520 Effect.succeed({
521 id: ThreadId.make("thread-1"),
522 projectId: ProjectId.make("project-1"),
523 worktreePath: location === "no-worktree" ? null : worktreePath,
524 branch: "feature",
525 }),
526 ).pipe(
527 Effect.provide(
528 Layer.mergeAll(
529 Layer.mock(ServerConfig.ServerConfig)({
530 worktreesDir,
531 } as ServerConfig.ServerConfig["Service"]),
532 ServerSettings.layerTest(),
533 Layer.mock(ProjectService.ProjectService)({
534 getById: () => Effect.succeedSome({ workspaceRoot: baseDir } as never),
535 }),
536 Layer.mock(GitWorkflowService.GitWorkflowService)({
537 pruneWorktrees: () => Effect.void,
538 listLocalBranchNames: () => Effect.succeed(["feature"]),
539 createWorktree: () =>
540 Effect.gen(function* () {
541 creations++;
542 yield* fs.makeDirectory(cwd, { recursive: true }).pipe(Effect.orDie);
543 const cleanup = yield* withWorkspaceLease(
544 worktreePath,
545 Effect.sync(() => {
546 assert.equal(ptyAdapter.spawnInputs.length, 1);
547 }),
548 ).pipe(Effect.forkChild({ startImmediately: true }));
549 yield* Deferred.succeed(cleanupQueued, cleanup);
550 return {} as never;
551 }),
552 }),
553 ),
554 ),
555 );
556 const input = openInput({
557 cwd,
558 worktreePath: location === "subdirectory" ? null : worktreePath,
559 });
560 const launch = prepareLaunch(input).pipe(
561 Effect.flatMap(({ input, recover }) =>
562 (method === "attach"
563 ? manager.attachStream(input, () => Effect.void).pipe(Effect.asVoid)
564 : manager.open(input).pipe(Effect.asVoid)
565 ).pipe(Effect.provideService(TerminalManager.TerminalCwdRecovery, recover)),
566 ),
567 );
568 if (location === "unmanaged" || location === "no-worktree") {
569 const error = yield* launch.pipe(Effect.flip);
570 assert.deepEqual(error, new TerminalCwdNotFoundError({ cwd }));
571 assert.equal(creations, 0);
572 assert.equal(ptyAdapter.spawnInputs.length, 0);
573 return;
574 }
575 yield* launch;
576 yield* Fiber.join(yield* Deferred.await(cleanupQueued));
577 assert.equal(creations, 1);
578 assert.equal(ptyAdapter.spawnInputs.length, 1);
579 assert.isTrue(yield* fs.exists(cwd));
580 }),
581 );
582
583 it.effect("spawns lazily and reuses running terminal per thread", () =>
584 Effect.gen(function* () {
585 const { manager, ptyAdapter } = yield* createManager();
586 const [first, second] = yield* Effect.all(
587 [manager.open(openInput()), manager.open(openInput())],
588 { concurrency: "unbounded" },
589 );
590 const third = yield* manager.open(openInput());
591
592 assert.equal(first.threadId, "thread-1");
593 assert.equal(first.terminalId, DEFAULT_TERMINAL_ID);
594 assert.equal(second.threadId, "thread-1");
595 assert.equal(third.threadId, "thread-1");
596 expect(ptyAdapter.spawnInputs).toHaveLength(1);
597 }),
598 );
599
600 it.effect("keeps attach streams live when a terminal id is closed and reopened", () =>
601 Effect.gen(function* () {
602 const { manager, ptyAdapter } = yield* createManager();
603 const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
604 const unsubscribe = yield* manager.attachStream(openInput(), (event) =>
605 Ref.update(attachEvents, (events) => [...events, event]),
606 );
607 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
608
609 yield* manager.close({
610 threadId: "thread-1",
611 terminalId: DEFAULT_TERMINAL_ID,
612 deleteHistory: true,
613 });
614 yield* manager.open(openInput());
615
616 const events = yield* Ref.get(attachEvents);
617 expect(events.map((event) => event.type)).toEqual(["snapshot", "closed", "snapshot"]);
618 expect(
619 events.filter((event) => event.type === "snapshot").map((event) => event.snapshot.status),
620 ).toEqual(["running", "running"]);
621 expect(ptyAdapter.spawnInputs).toHaveLength(2);
622 }),
623 );
624
625 // Which client owns the shared PTY size is left open by the issue, so this only asserts
626 // that every attached renderer is told the grid the PTY actually has.
627 it.effect("tells every attached stream the shared PTY size when attaches disagree", () =>
628 Effect.gen(function* () {
629 const { manager, ptyAdapter } = yield* createManager();
630 const wideEvents: TerminalAttachStreamEvent[] = [];
631 const narrowEvents: TerminalAttachStreamEvent[] = [];
632 const stopWide = yield* manager.attachStream(openInput({ cols: 130, rows: 15 }), (event) =>
633 Effect.sync(() => {
634 wideEvents.push(event);
635 }),
636 );
637 yield* Effect.addFinalizer(() => Effect.sync(stopWide));
638 const stopNarrow = yield* manager.attachStream(openInput({ cols: 54, rows: 15 }), (event) =>
639 Effect.sync(() => {
640 narrowEvents.push(event);
641 }),
642 );
643 yield* Effect.addFinalizer(() => Effect.sync(stopNarrow));
644
645 const spawned = ptyAdapter.spawnInputs[0]!;
646 const ptySize = ptyAdapter.processes[0]!.resizeCalls.at(-1) ?? {
647 cols: spawned.cols,
648 rows: spawned.rows,
649 };
650 const lastReportedSize = (events: ReadonlyArray<TerminalAttachStreamEvent>) => {
651 for (const event of events.toReversed()) {
652 const source: Record<string, unknown> =
653 event.type === "snapshot" ? event.snapshot : event;
654 if (typeof source.cols === "number" && typeof source.rows === "number") {
655 return { cols: source.cols, rows: source.rows };
656 }
657 }
658 return null;
659 };
660
661 expect({
662 wide: lastReportedSize(wideEvents),
663 narrow: lastReportedSize(narrowEvents),
664 }).toEqual({ wide: ptySize, narrow: ptySize });
665 }),
666 );
667
668 it.effect("gives the PTY back to the remaining viewer when the narrowest one detaches", () =>
669 Effect.gen(function* () {
670 const { manager, ptyAdapter } = yield* createManager();
671 const restored = yield* Deferred.make<void>();
672 const stopWide = yield* manager.attachStream(
673 openInput({ cols: 130, rows: 15 }),
674 (event) =>
675 event.type === "activity" && event.cols === 130 && event.rows === 15
676 ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid)
677 : Effect.void,
678 undefined,
679 "wide",
680 );
681 yield* Effect.addFinalizer(() => Effect.sync(stopWide));
682 const stopNarrow = yield* manager.attachStream(
683 openInput({ cols: 54, rows: 15 }),
684 () => Effect.void,
685 undefined,
686 "narrow",
687 );
688 const process = ptyAdapter.processes[0]!;
689
690 yield* manager.resize(
691 { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 80, rows: 12 },
692 "narrow",
693 );
694 // A resize from a client with no attached stream cannot override attached viewers.
695 yield* manager.resize({
696 threadId: "thread-1",
697 terminalId: DEFAULT_TERMINAL_ID,
698 cols: 200,
699 rows: 50,
700 });
701 expect(process.resizeCalls.at(-1)).toEqual({ cols: 80, rows: 12 });
702
703 stopNarrow();
704 yield* Deferred.await(restored);
705 expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
706 }),
707 );
708
709 // Client retries resend the first attach's size, which a later resize may have replaced.
710 it.effect("keeps a viewer's resized grid when the same viewer attaches again", () =>
711 Effect.gen(function* () {
712 const { manager, ptyAdapter } = yield* createManager();
713 const restored = yield* Deferred.make<void>();
714 const stopWide = yield* manager.attachStream(
715 openInput({ cols: 130, rows: 15 }),
716 (event) =>
717 event.type === "activity" && event.cols === 130 && event.rows === 15
718 ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid)
719 : Effect.void,
720 undefined,
721 "wide",
722 );
723 yield* Effect.addFinalizer(() => Effect.sync(stopWide));
724 const stopFirst = yield* manager.attachStream(
725 openInput({ cols: 54, rows: 15 }),
726 () => Effect.void,
727 undefined,
728 "phone",
729 );
730 const process = ptyAdapter.processes[0]!;
731 yield* manager.resize(
732 { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 100, rows: 15 },
733 "phone",
734 );
735
736 const stopRetry = yield* manager.attachStream(
737 { ...openInput({ cols: 54, rows: 15 }), resume: true },
738 () => Effect.void,
739 undefined,
740 "phone",
741 );
742 expect(process.resizeCalls.at(-1)).toEqual({ cols: 100, rows: 15 });
743
744 stopRetry();
745 stopFirst();
746 yield* Deferred.await(restored);
747 expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
748 expect(ptyAdapter.spawnInputs).toHaveLength(1);
749 }),
750 );
751
752 // Every attached renderer answers the same query; a second DECRQM answer breaks Vim's input.
753 it.effect("lets one attached viewer answer terminal queries on a shared PTY", () =>
754 Effect.gen(function* () {
755 const { manager, ptyAdapter } = yield* createManager();
756 const attach = (terminalId: string, viewerId: string) =>
757 manager.attachStream(openInput({ terminalId }), () => Effect.void, undefined, viewerId);
758 const stopFirst = yield* attach(DEFAULT_TERMINAL_ID, "first");
759 const stopSecond = yield* attach(DEFAULT_TERMINAL_ID, "second");
760 const stopOther = yield* attach("other", "second");
761 yield* Effect.addFinalizer(() => Effect.sync(() => (stopSecond(), stopOther())));
762 const [shared, other] = ptyAdapter.processes;
763 const modeReply = "\x1b[?12;2$y";
764 const write = (terminalId: string, viewerId: string, data: string, reply?: boolean) =>
765 manager.write(
766 { threadId: "thread-1", terminalId, data, ...(reply ? { reply } : {}) },
767 viewerId,
768 );
769
770 yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true);
771 yield* write(DEFAULT_TERMINAL_ID, "second", modeReply, true);
772 yield* write(DEFAULT_TERMINAL_ID, "second", "iHELLO");
773 yield* write("other", "second", modeReply, true);
774 expect(shared!.writes).toEqual([modeReply, "iHELLO"]);
775 expect(other!.writes).toEqual([modeReply]);
776
777 stopFirst();
778 yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true);
779 yield* write(DEFAULT_TERMINAL_ID, "second", modeReply, true);
780 yield* write(DEFAULT_TERMINAL_ID, "first", modeReply, true);
781 expect(shared!.writes).toEqual([modeReply, "iHELLO", modeReply]);
782 }),
783 );
784
785 it.effect("resumed attaches after close never respawn until the terminal is reopened", () =>
786 Effect.gen(function* () {
787 const { manager, ptyAdapter } = yield* createManager();
788 yield* manager.open(openInput());
789 yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
790
791 const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
792 const unsubscribe = yield* manager.attachStream(
793 { ...openInput(), restartIfNotRunning: true, resume: true },
794 (event) => Ref.update(attachEvents, (events) => [...events, event]),
795 );
796 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
797 expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]);
798 expect(ptyAdapter.spawnInputs).toHaveLength(1);
799
800 yield* manager.open(openInput());
801 const events = yield* Ref.get(attachEvents);
802 expect(events.map((event) => event.type)).toEqual(["closed", "snapshot"]);
803 expect(ptyAdapter.spawnInputs).toHaveLength(2);
804 }),
805 );
806
807 it.effect("resumed attaches respect closes before this server has seen a terminal", () =>
808 Effect.gen(function* () {
809 const { manager, ptyAdapter } = yield* createManager();
810 yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
811
812 const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
813 const unsubscribe = yield* manager.attachStream(
814 { ...openInput(), restartIfNotRunning: true, resume: true },
815 (event) => Ref.update(attachEvents, (events) => [...events, event]),
816 );
817 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
818 expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]);
819 expect(ptyAdapter.spawnInputs).toHaveLength(0);
820 }),
821 );
822
823 it.effect("resumed attaches leave exited and evicted terminals stopped", () =>
824 Effect.gen(function* () {
825 const { manager, ptyAdapter } = yield* createManager(5, {
826 maxRetainedInactiveSessions: 1,
827 });
828 const exited = yield* Deferred.make<void>();
829 const unsubscribeEvents = yield* manager.subscribe((event) =>
830 event.type === "exited"
831 ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid)
832 : Effect.void,
833 );
834 yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvents));
835 yield* manager.open(openInput());
836 ptyAdapter.processes[0]?.emitExit({ exitCode: 0, signal: 0 });
837 yield* Deferred.await(exited);
838
839 const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
840 const unsubscribe = yield* manager.attachStream(
841 { ...openInput(), restartIfNotRunning: true, resume: true },
842 (event) => Ref.update(attachEvents, (events) => [...events, event]),
843 );
844 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
845 expect(yield* Ref.get(attachEvents)).toEqual([
846 { type: "snapshot", snapshot: expect.objectContaining({ status: "exited" }) },
847 ]);
848 expect(ptyAdapter.spawnInputs).toHaveLength(1);
849
850 // Opening another terminal completes eviction before the next resumed attach.
851 yield* manager.open(openInput({ threadId: "thread-2" }));
852 const unsubscribeEvicted = yield* manager.attachStream(
853 { ...openInput(), restartIfNotRunning: true, resume: true },
854 (event) => Ref.update(attachEvents, (events) => [...events, event]),
855 );
856 yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvicted));
857 expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([
858 "snapshot",
859 "closed",
860 ]);
861 expect(ptyAdapter.spawnInputs).toHaveLength(2);
862 }),
863 );
864
865 it.effect("resumed attaches recreate terminals this server has never seen", () =>
866 Effect.gen(function* () {
867 const { manager, ptyAdapter } = yield* createManager();
868 const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
869 const unsubscribe = yield* manager.attachStream({ ...openInput(), resume: true }, (event) =>
870 Ref.update(attachEvents, (events) => [...events, event]),
871 );
872 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
873 expect(yield* Ref.get(attachEvents)).toEqual([
874 { type: "snapshot", snapshot: expect.objectContaining({ status: "running" }) },
875 ]);
876 expect(ptyAdapter.spawnInputs).toHaveLength(1);
877 }),
878 );
879
880 const pathExists = (filePath: string) =>
881 Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.exists(filePath));
882
883 const readFileString = (filePath: string) =>
884 Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.readFileString(filePath));
885
886 const writeFileString = (filePath: string, contents: string) =>
887 Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
888 fs.writeFileString(filePath, contents),
889 );
890
891 it.effect("handles an exit replayed during subscription after publishing startup", () =>
892 Effect.gen(function* () {
893 const ptyAdapter = new FakePtyAdapter();
894 ptyAdapter.exitOnSubscribe = { exitCode: 7, signal: null };
895 const { manager, getEvents } = yield* createManager(5, { ptyAdapter });
896 const exited = yield* Deferred.make<void>();
897 const unsubscribe = yield* manager.subscribe((event) =>
898 event.type === "exited"
899 ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid)
900 : Effect.void,
901 );
902 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
903 yield* manager.open(openInput());
904 yield* Deferred.await(exited);
905 const events = yield* getEvents;
906 expect(events.map((event) => event.type)).toEqual(["started", "exited"]);
907 expect(events[1]).toMatchObject({ exitCode: 7 });
908 const attached: TerminalAttachStreamEvent[] = [];
909 const stopAttach = yield* manager.attachStream(openInput(), (event) =>
910 Effect.sync(() => {
911 attached.push(event);
912 }),
913 );
914 yield* Effect.addFinalizer(() => Effect.sync(stopAttach));
915 expect(attached.find((event) => event.type === "snapshot")).toMatchObject({
916 snapshot: { status: "exited", exitCode: 7 },
917 });
918 }),
919 );
920
921 it.effect("supports multiple terminals per thread independently", () =>
922 Effect.gen(function* () {
923 const { manager, ptyAdapter } = yield* createManager();
924 yield* manager.open(openInput({ terminalId: "default" }));
925 yield* manager.open(openInput({ terminalId: "term-2" }));
926
927 const first = ptyAdapter.processes[0];
928 const second = ptyAdapter.processes[1];
929 expect(first).toBeDefined();
930 expect(second).toBeDefined();
931 if (!first || !second) return;
932
933 yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" });
934 yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" });
935 yield* manager.write({
936 threadId: "thread-1",
937 terminalId: "term-2",
938 data: "\x1b[M \x80(",
939 binary: true,
940 });
941
942 expect(first.writes).toEqual(["pwd\n"]);
943 expect(second.writes).toEqual(["ls\n", Buffer.from([0x1b, 0x5b, 0x4d, 0x20, 0x80, 0x28])]);
944 expect(ptyAdapter.spawnInputs).toHaveLength(2);
945 }),
946 );
947
948 it.effect(
949 "closes idle shells and opted-in actions on settlement without stopping other commands",
950 () =>
951 Effect.gen(function* () {
952 const { manager, ptyAdapter } = yield* createManager(5, {
953 processTable: Effect.succeed([
954 { pid: 9000, ppid: 1, name: "zsh" },
955 { pid: 100, ppid: 9000, name: "zsh" },
956 { pid: 9001, ppid: 1, name: "zsh" },
957 { pid: 200, ppid: 9001, name: "node" },
958 { pid: 9002, ppid: 1, name: "zsh" },
959 { pid: 300, ppid: 9002, name: "zsh" },
960 { pid: 301, ppid: 300, name: "sleep" },
961 { pid: 9003, ppid: 1, name: "zsh" },
962 { pid: 9004, ppid: 1, name: "zsh" },
963 { pid: 400, ppid: 9004, name: "node" },
964 ]),
965 }).pipe(Effect.provide(layerWithHostPlatform("linux")));
966 yield* manager.open(openInput({ terminalId: "idle" }));
967 yield* manager.open(openInput({ terminalId: "dev-server" }));
968 yield* manager.open(openInput({ terminalId: "subshell" }));
969 yield* manager.open(openInput({ threadId: "thread-2", stopOnSettle: true }));
970 yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: true }));
971
972 yield* manager.closeIdle({ threadId: "thread-1" });
973
974 expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
975 true,
976 false,
977 false,
978 false,
979 false,
980 ]);
981 yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: false }));
982 yield* manager.closeOnSettle({ threadId: "thread-1" });
983 expect(ptyAdapter.processes[4]?.killed).toBe(false);
984 yield* manager.open(openInput({ terminalId: "managed-dev", stopOnSettle: true }));
985 yield* manager.closeOnSettle({ threadId: "thread-1" });
986 expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
987 true,
988 false,
989 false,
990 false,
991 true,
992 ]);
993 }),
994 );
995
996 it.effect("reports whether any terminal session for a thread has an active subprocess", () =>
997 Effect.gen(function* () {
998 const { manager } = yield* createManager(5, {
999 processTable: Effect.succeed([
1000 { pid: 9000, ppid: 1, name: "zsh" },
1001 { pid: 100, ppid: 9000, name: "zsh" },
1002 { pid: 9001, ppid: 1, name: "zsh" },
1003 { pid: 200, ppid: 9001, name: "node" },
1004 ]),
1005 }).pipe(Effect.provide(layerWithHostPlatform("linux")));
1006 yield* manager.open(openInput({ terminalId: "idle", threadId: "thread-idle" }));
1007 yield* manager.open(openInput({ terminalId: "dev-server", threadId: "thread-active" }));
1008
1009 expect(yield* manager.hasActiveSubprocess({ threadId: "thread-none" })).toBe(false);
1010 expect(yield* manager.hasActiveSubprocess({ threadId: "thread-idle" })).toBe(false);
1011 expect(yield* manager.hasActiveSubprocess({ threadId: "thread-active" })).toBe(true);
1012 }),
1013 );
1014
1015 it.effect.each([
1016 ["linux", ["SIGHUP", "SIGTERM"]],
1017 ["win32", ["SIGTERM"]],
1018 ] as const)("closing a %s terminal hangs up the shell's jobs", ([platform, signals]) =>
1019 Effect.gen(function* () {
1020 const { manager, ptyAdapter } = yield* createManager(5).pipe(
1021 Effect.provide(layerWithHostPlatform(platform)),
1022 );
1023 yield* manager.open(openInput());
1024 const shell = ptyAdapter.processes[0]!;
1025 const terminated = yield* Deferred.make<void>();
1026 shell.onKill = (signal) => {
1027 if (signal === "SIGTERM") Deferred.doneUnsafe(terminated, Effect.void);
1028 };
1029
1030 yield* manager.close({ threadId: "thread-1" });
1031 yield* Deferred.await(terminated);
1032
1033 expect(shell.killSignals).toEqual(signals);
1034 shell.emitExit({ exitCode: 0, signal: 0 });
1035 }).pipe(Effect.provide(TestClock.layer())),
1036 );
1037
1038 it.effect("keeps a terminal whose shell was replaced by exec open on settlement", () =>
1039 Effect.gen(function* () {
1040 const { manager, ptyAdapter } = yield* createManager(5, {
1041 shellResolver: () => "/bin/bash",
1042 processTable: Effect.succeed([{ pid: 9000, ppid: 1, name: "node" }]),
1043 }).pipe(Effect.provide(layerWithHostPlatform("linux")));
1044 yield* manager.open(openInput());
1045
1046 yield* manager.closeOnSettle({ threadId: "thread-1" });
1047
1048 expect(ptyAdapter.processes[0]?.killed).toBe(false);
1049 }),
1050 );
1051
1052 it.effect.each([
1053 { label: "idle prompt", platform: "linux", foregroundProcessGroup: 9000, killed: true },
1054 { label: "foreground job", platform: "linux", foregroundProcessGroup: 100, killed: false },
1055 {
1056 label: "unknown foreground group",
1057 platform: "linux",
1058 foregroundProcessGroup: null,
1059 killed: false,
1060 },
1061 { label: "idle prompt", platform: "darwin", foregroundProcessGroup: 9000, killed: true },
1062 { label: "foreground job", platform: "darwin", foregroundProcessGroup: 100, killed: false },
1063 ] as const)(
1064 "settles a shell with a childless shell-named child by its foreground group: $label ($platform)",
1065 ({ platform, foregroundProcessGroup, killed }) =>
1066 Effect.gen(function* () {
1067 const { manager, ptyAdapter } = yield* createManager(5, {
1068 shellResolver: () => "/bin/bash",
1069 processTable: Effect.succeed([
1070 { pid: 9000, ppid: 1, name: "bash" },
1071 { pid: 100, ppid: 9000, name: "bash" },
1072 ]),
1073 foregroundProcessGroup: () => Effect.succeed(foregroundProcessGroup),
1074 }).pipe(Effect.provide(layerWithHostPlatform(platform)));
1075 yield* manager.open(openInput());
1076
1077 yield* manager.closeOnSettle({ threadId: "thread-1" });
1078
1079 expect(ptyAdapter.processes[0]?.killed).toBe(killed);
1080 }),
1081 );
1082
1083 it.effect("labels a running command by its whole process name, spaces included", () =>
1084 Effect.gen(function* () {
1085 const { manager } = yield* createManager(5, {
1086 subprocessPollIntervalMs: 1_000,
1087 processKillGraceMs: 0,
1088 processTable: Effect.succeed([
1089 { pid: 9000, ppid: 1, name: "zsh" },
1090 { pid: 200, ppid: 9000, name: "Google Chrome" },
1091 ]),
1092 }).pipe(Effect.provide(layerWithHostPlatform("darwin")));
1093 const label = yield* Deferred.make<string>();
1094 const unsubscribe = yield* manager.subscribe((event) =>
1095 event.type === "activity"
1096 ? Deferred.succeed(label, event.label).pipe(Effect.asVoid)
1097 : Effect.void,
1098 );
1099 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1100 yield* manager.open(openInput());
1101 yield* TestClock.adjust("1 second");
1102
1103 expect(yield* Deferred.await(label)).toBe("Google Chrome");
1104 }).pipe(Effect.provide(TestClock.layer())),
1105 );
1106
1107 // Answers process-table queries after `queryDuration`, honoring the caller's
1108 // timeout the way ProcessRunner's `timedOutResult` mode does.
1109 const slowProcessTable = (
1110 platform: "linux" | "win32",
1111 queryDuration: Duration.Input,
1112 queries: Array<{ start: number; end?: number }>,
1113 started: ReadonlyArray<Deferred.Deferred<void>>,
1114 ): ProcessRunner.ProcessRunner["Service"] => ({
1115 run: (input) =>
1116 Effect.gen(function* () {
1117 const query: { start: number; end?: number } = { start: yield* Clock.currentTimeMillis };
1118 queries.push(query);
1119 const deferred = started[queries.length - 1];
1120 if (deferred) yield* Deferred.succeed(deferred, undefined);
1121 const completed = yield* Effect.sleep(queryDuration).pipe(
1122 Effect.timeoutOption(input.timeout ?? "1 hour"),
1123 );
1124 query.end = yield* Clock.currentTimeMillis;
1125 return {
1126 stdout: Option.isNone(completed)
1127 ? ""
1128 : platform === "win32"
1129 ? "100|9000|node.exe\n"
1130 : " 100 9000 node\n",
1131 stderr: "",
1132 code: Option.isSome(completed) ? ChildProcessSpawner.ExitCode(0) : null,
1133 timedOut: Option.isNone(completed),
1134 stdoutTruncated: false,
1135 stderrTruncated: false,
1136 stdoutInvalidUtf8: false,
1137 stderrInvalidUtf8: false,
1138 };
1139 }),
1140 });
1141
1142 const createFallbackManager = (
1143 platform: "linux" | "win32",
1144 runner: ProcessRunner.ProcessRunner["Service"],
1145 ) =>
1146 createManager(5, { subprocessPollIntervalMs: 1_000, processKillGraceMs: 0 }).pipe(
1147 Effect.provideService(ProcessRunner.ProcessRunner, runner),
1148 Effect.provide(layerWithHostPlatform(platform)),
1149 );
1150
1151 it.effect.each(["linux", "win32"] as const)(
1152 "reports activity from a slow but successful %s process-table query",
1153 (platform) =>
1154 Effect.gen(function* () {
1155 const started = yield* Deferred.make<void>();
1156 const queries: Array<{ start: number; end?: number }> = [];
1157 const { manager, getEvents } = yield* createFallbackManager(
1158 platform,
1159 slowProcessTable(platform, "5 seconds", queries, [started]),
1160 );
1161
1162 yield* manager.open(openInput());
1163 yield* TestClock.adjust("1 second");
1164 yield* Deferred.await(started);
1165 yield* TestClock.adjust("5 seconds");
1166
1167 expect(
1168 (yield* getEvents).some(
1169 (event) =>
1170 event.type === "activity" && event.hasRunningSubprocess && event.label === "node",
1171 ),
1172 ).toBe(true);
1173 yield* manager.close({ threadId: "thread-1" });
1174 }).pipe(Effect.provide(TestClock.layer())),
1175 );
1176
1177 it.effect("idles at least as long as a slow process-table query took before the next", () =>
1178 Effect.gen(function* () {
1179 const started = yield* Deferred.make<void>();
1180 const queries: Array<{ start: number; end?: number }> = [];
1181 const { manager } = yield* createFallbackManager(
1182 "linux",
1183 slowProcessTable("linux", "5 seconds", queries, [started]),
1184 );
1185
1186 yield* manager.open(openInput());
1187 yield* TestClock.adjust("1 second");
1188 yield* Deferred.await(started);
1189 yield* TestClock.adjust("5 seconds");
1190 yield* TestClock.adjust(Duration.millis(19_999));
1191
1192 expect(queries).toHaveLength(1);
1193 yield* TestClock.adjust("1 millis");
1194 const [slow, next] = queries;
1195 expect(next?.start).toBe(slow!.end! + 20_000);
1196 yield* manager.close({ threadId: "thread-1" });
1197 }).pipe(Effect.provide(TestClock.layer())),
1198 );
1199
1200 it.effect("ends a hung process-table query and paces the retry", () =>
1201 Effect.gen(function* () {
1202 const started = yield* Deferred.make<void>();
1203 const queries: Array<{ start: number; end?: number }> = [];
1204 const { manager } = yield* createFallbackManager(
1205 "win32",
1206 slowProcessTable("win32", "1 day", queries, [started]),
1207 );
1208
1209 yield* manager.open(openInput());
1210 yield* TestClock.adjust("1 second");
1211 yield* Deferred.await(started);
1212 yield* TestClock.adjust("2 minutes");
1213 yield* TestClock.adjust("2 minutes");
1214
1215 const [hung, next] = queries;
1216 expect(hung!.end! - hung!.start).toBe(15_000);
1217 expect(next!.start - hung!.end!).toBe(60_000);
1218 yield* manager.close({ threadId: "thread-1" });
1219 }).pipe(Effect.provide(TestClock.layer())),
1220 );
1221
1222 it.effect.each([
1223 ["linux", 1_000],
1224 ["win32", 1_500],
1225 ] as const)(
1226 "bounds closeIdle's %s query so other operations on the thread still run",
1227 ([platform, budgetMs]) =>
1228 Effect.gen(function* () {
1229 const started = yield* Deferred.make<void>();
1230 const queries: Array<{ start: number; end?: number }> = [];
1231 const { manager, ptyAdapter } = yield* createFallbackManager(
1232 platform,
1233 slowProcessTable(platform, "1 day", queries, [started]),
1234 );
1235 yield* manager.open(openInput());
1236
1237 const closing = yield* manager
1238 .closeIdle({ threadId: "thread-1" })
1239 .pipe(Effect.forkChild({ startImmediately: true }));
1240 yield* Deferred.await(started);
1241 const resizing = yield* manager
1242 .resize({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 80, rows: 30 })
1243 .pipe(Effect.forkChild({ startImmediately: true }));
1244 yield* TestClock.adjust(Duration.millis(budgetMs));
1245
1246 expect(closing.pollUnsafe()).toBeDefined();
1247 expect(resizing.pollUnsafe()).toBeDefined();
1248 expect(queries[0]!.end! - queries[0]!.start).toBe(budgetMs);
1249 expect(ptyAdapter.processes[0]!.resizeCalls).toEqual([{ cols: 80, rows: 30 }]);
1250 expect(ptyAdapter.processes[0]!.killed).toBe(false);
1251 yield* manager.close({ threadId: "thread-1" });
1252 }).pipe(Effect.provide(TestClock.layer())),
1253 );
1254
1255 it.effect("keeps terminals that get input or output while closeIdle checks them", () =>
1256 Effect.gen(function* () {
1257 const ptyAdapter = new FakePtyAdapter();
1258 let duringCheck: (pid: number) => Effect.Effect<void> = () => Effect.void;
1259 const { manager } = yield* createManager(5, {
1260 ptyAdapter,
1261 subprocessPollIntervalMs: 60_000,
1262 subprocessInspector: (pid) =>
1263 duringCheck(pid).pipe(
1264 Effect.as({ hasRunningSubprocess: false, childCommand: null, processIds: [] }),
1265 ),
1266 });
1267 const outputSeen = yield* Deferred.make<void>();
1268 const unsubscribeOutput = yield* manager.subscribe((event) =>
1269 event.type === "output"
1270 ? Deferred.succeed(outputSeen, undefined).pipe(Effect.asVoid)
1271 : Effect.void,
1272 );
1273 yield* Effect.addFinalizer(() => Effect.sync(unsubscribeOutput));
1274 yield* manager.open(openInput({ terminalId: "typed" }));
1275 yield* manager.open(openInput({ terminalId: "echoed" }));
1276 const [typed, echoed] = ptyAdapter.processes;
1277 duringCheck = (pid) =>
1278 pid === typed!.pid
1279 ? manager
1280 .write({ threadId: "thread-1", terminalId: "typed", data: "make build\r" })
1281 .pipe(Effect.orDie)
1282 : Effect.gen(function* () {
1283 echoed!.emitData("make build\r\n");
1284 yield* Deferred.await(outputSeen);
1285 }).pipe(Effect.orDie);
1286
1287 yield* manager.closeIdle({ threadId: "thread-1" });
1288
1289 expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([false, false]);
1290 }),
1291 );
1292
1293 it.effect("caps incrementally appended history without losing partial or empty lines", () =>
1294 Effect.gen(function* () {
1295 const { manager, ptyAdapter } = yield* createManager(3);
1296 yield* manager.open(openInput());
1297 const process = ptyAdapter.processes[0];
1298 expect(process).toBeDefined();
1299 if (!process) return;
1300
1301 process.emitData("line1\n");
1302 process.emitData("\n");
1303 process.emitData("line3");
1304 process.emitData("-continued\nline4");
1305 yield* manager.close({ threadId: "thread-1" });
1306
1307 const reopened = yield* manager.open(openInput());
1308 expect(reopened.history).toBe("\nline3-continued\nline4");
1309 }),
1310 );
1311
1312 it.effect("bounds persisted and attached history without truncating live output", () =>
1313 Effect.gen(function* () {
1314 const { manager, ptyAdapter, logsDir } = yield* createManager(5, { historyByteLimit: 10 });
1315 const attachEvents = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
1316 const unsubscribe = yield* manager.attachStream(openInput(), (event) =>
1317 Ref.update(attachEvents, (events) => [...events, event]),
1318 );
1319 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1320 const writes = ["a".repeat(32), "😀\rEND"];
1321 const process = ptyAdapter.processes[0]!;
1322 for (const text of writes) process.emitData(text);
1323 yield* manager.close({ threadId: "thread-1" });
1324 expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe("aa😀\rEND");
1325
1326 const reopened = yield* manager.open(openInput());
1327 const events = yield* Ref.get(attachEvents);
1328 expect(events.filter((event) => event.type === "output").map((event) => event.data)).toEqual(
1329 writes,
1330 );
1331 const snapshot = events.filter((event) => event.type === "snapshot").at(-1)?.snapshot;
1332 expect(snapshot?.history).toBe("aa😀\rEND");
1333 expect(snapshot?.sequence).toBe(reopened.sequence);
1334 }),
1335 );
1336
1337 it.effect("clears a terminal that keeps printing while its history is saved", () =>
1338 Effect.gen(function* () {
1339 const fs = yield* FileSystem.FileSystem;
1340 let printWhileSaving = Effect.void;
1341 const printing = FileSystem.FileSystem.of({
1342 ...fs,
1343 writeFileString: (filePath, data, options) =>
1344 printWhileSaving.pipe(Effect.andThen(fs.writeFileString(filePath, data, options))),
1345 });
1346 const { manager, ptyAdapter, getEvents } = yield* createManager().pipe(
1347 Effect.provideService(FileSystem.FileSystem, printing),
1348 );
1349 yield* manager.open(openInput());
1350 const process = ptyAdapter.processes[0]!;
1351 // Each save sees fresh output, so the history worker never goes idle.
1352 printWhileSaving = Effect.gen(function* () {
1353 const printed = yield* Deferred.make<void>();
1354 const unsubscribe = yield* manager.subscribe((event) =>
1355 event.type === "output" ? Deferred.succeed(printed, undefined) : Effect.void,
1356 );
1357 process.emitData("tick\n");
1358 yield* Deferred.await(printed);
1359 unsubscribe();
1360 });
1361
1362 yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
1363
1364 expect((yield* getEvents).map((event) => event.type)).toContain("cleared");
1365 }),
1366 );
1367
1368 it.effect("restores a log tail that starts inside a control sequence without its remainder", () =>
1369 Effect.gen(function* () {
1370 const fs = yield* FileSystem.FileSystem;
1371 for (const [persisted, restored] of [
1372 ["\u001b]0;x\u0007ABCD", "ABCD"],
1373 ["名\u001b]0;名\u0007ABCD", "ABCD"],
1374 ["\u001b]0;x\u0007\u001b[31mABCD", "ABCD"],
1375 ] as const) {
1376 const { manager, logsDir } = yield* createManager(5, { historyByteLimit: 8 });
1377 const path = yield* historyLogPath(logsDir);
1378 yield* fs.makeDirectory(logsDir, { recursive: true });
1379 yield* fs.writeFileString(path, persisted);
1380 expect((yield* manager.open(openInput())).history).toBe(restored);
1381 expect(yield* fs.readFileString(path)).toBe(restored);
1382 }
1383 }),
1384 );
1385
1386 it.effect("persists small terminal updates without rewriting the retained history", () =>
1387 Effect.gen(function* () {
1388 const fs = yield* FileSystem.FileSystem;
1389 const writes = yield* Queue.unbounded<number>();
1390 const maxBytes = 64 * 1024;
1391 const { manager, ptyAdapter, logsDir } = yield* createManager(5_000, {
1392 historyByteLimit: maxBytes,
1393 }).pipe(
1394 Effect.provideService(FileSystem.FileSystem, {
1395 ...fs,
1396 writeFileString: (path, data, options) =>
1397 fs
1398 .writeFileString(path, data, options)
1399 .pipe(
1400 Effect.tap(() =>
1401 data.length > 0 ? Queue.offer(writes, Buffer.byteLength(data)) : Effect.void,
1402 ),
1403 ),
1404 }),
1405 );
1406 yield* manager.open(openInput());
1407 const process = ptyAdapter.processes[0]!;
1408 process.emitData("a".repeat(maxBytes));
1409 let written = yield* Queue.take(writes);
1410 for (let index = 0; index < 16; index += 1) {
1411 process.emitData("b".repeat(1024));
1412 written += yield* Queue.take(writes);
1413 }
1414 expect(written).toBeLessThan(maxBytes * 2);
1415 const expected = "a".repeat(maxBytes - 16 * 1024) + "b".repeat(16 * 1024);
1416 const persisted = yield* fs.readFileString(yield* historyLogPath(logsDir));
1417 expect(Buffer.byteLength(persisted)).toBe(maxBytes + 16 * 1024);
1418 for (const failure of [undefined, "write", "rename"] as const) {
1419 let failed = false;
1420 const fail = () => {
1421 failed = true;
1422 return Effect.fail(
1423 PlatformError.systemError({
1424 _tag: "Unknown",
1425 module: "FileSystem",
1426 method: failure === "write" ? "writeFileString" : "rename",
1427 cause: { code: "ENOSPC" },
1428 }),
1429 );
1430 };
1431 const recovered = yield* createManager(5_000, { historyByteLimit: maxBytes }).pipe(
1432 Effect.provideService(FileSystem.FileSystem, {
1433 ...fs,
1434 writeFileString: (file, data, options) =>
1435 failure === "write" && !failed && data === expected
1436 ? fs.writeFileString(file, "partial", options).pipe(Effect.andThen(fail))
1437 : fs.writeFileString(file, data, options),
1438 rename: (from, to) => (failure === "rename" && !failed ? fail() : fs.rename(from, to)),
1439 }),
1440 );
1441 const recoveredPath = yield* historyLogPath(recovered.logsDir);
1442 yield* fs.makeDirectory(recovered.logsDir, { recursive: true });
1443 yield* fs.writeFileString(recoveredPath, persisted);
1444 const snapshot = yield* recovered.manager.open(openInput());
1445 expect(snapshot.status).toBe("running");
1446 expect(snapshot.history).toBe(expected);
1447 expect(failed).toBe(failure !== undefined);
1448 expect(yield* fs.readFileString(recoveredPath)).toBe(
1449 failure === undefined ? expected : persisted,
1450 );
1451 expect(yield* fs.readDirectory(recovered.logsDir)).toHaveLength(1);
1452 }
1453 yield* manager.close({ threadId: "thread-1" });
1454 expect((yield* manager.open(openInput())).history).toBe(expected);
1455 expect(yield* fs.readFileString(yield* historyLogPath(logsDir))).toBe(expected);
1456 }),
1457 );
1458
1459 it.effect("rewrites history after an append fails partway through", () =>
1460 Effect.gen(function* () {
1461 const fs = yield* FileSystem.FileSystem;
1462 const writes = yield* Queue.unbounded<void>();
1463 let failAppend = false;
1464 const { manager, ptyAdapter, logsDir } = yield* createManager().pipe(
1465 Effect.provideService(FileSystem.FileSystem, {
1466 ...fs,
1467 writeFileString: (path, data, options) => {
1468 if (options?.flag === "a" && failAppend) {
1469 failAppend = false;
1470 return fs.writeFileString(path, data.slice(0, 1), options).pipe(
1471 // The file cannot also be a parent directory: fail after the partial append.
1472 Effect.andThen(fs.writeFileString(`${path}/missing`, data)),
1473 Effect.ensuring(Queue.offer(writes, undefined)),
1474 );
1475 }
1476 return fs
1477 .writeFileString(path, data, options)
1478 .pipe(
1479 Effect.tap(() => (data.length > 0 ? Queue.offer(writes, undefined) : Effect.void)),
1480 );
1481 },
1482 }),
1483 );
1484 yield* manager.open(openInput());
1485 const process = ptyAdapter.processes[0]!;
1486 process.emitData("start:");
1487 yield* Queue.take(writes);
1488 failAppend = true;
1489 process.emitData("middle");
1490 yield* Queue.take(writes);
1491 expect(failAppend).toBe(false);
1492 process.emitData(":end");
1493 yield* Queue.take(writes);
1494 expect(yield* fs.readFileString(yield* historyLogPath(logsDir))).toBe("start:middle:end");
1495 yield* manager.close({ threadId: "thread-1" });
1496 }),
1497 );
1498
1499 it.effect("releases delivered output while the process queue stays busy", () =>
1500 Effect.gen(function* () {
1501 // Observe retained payloads, since delivery and bounded history alone cannot detect a leak.
1502 let readState: Effect.Effect<unknown> = Effect.void;
1503 const makeRef = vi.mocked(SynchronizedRef.make).getMockImplementation()!;
1504 using _capture = vi.spyOn(SynchronizedRef, "make").mockImplementation(<A>(value: A) =>
1505 makeRef(value).pipe(
1506 Effect.tap((ref) =>
1507 Effect.sync(() => {
1508 if (typeof value === "object" && value !== null && "sessions" in value) {
1509 readState = SynchronizedRef.get(ref);
1510 }
1511 }),
1512 ),
1513 ),
1514 );
1515 const { manager, ptyAdapter } = yield* createManager(5, { historyByteLimit: 1024 });
1516 yield* manager.open(openInput());
1517 const process = ptyAdapter.processes[0]!;
1518 const entered = yield* Deferred.make<void>();
1519 const release = yield* Deferred.make<void>();
1520 const measured = yield* Deferred.make<void>();
1521 const finish = yield* Deferred.make<void>();
1522 const drained = yield* Deferred.make<void>();
1523 yield* Effect.addFinalizer(() => Deferred.succeed(finish, undefined));
1524 yield* Effect.addFinalizer(() => Deferred.succeed(release, undefined));
1525 const chunkBytes = 64 * 1024;
1526 const chunkCount = 256;
1527 let delivered = 0;
1528 const unsubscribe = yield* manager.subscribe((event) =>
1529 Effect.gen(function* () {
1530 if (event.type !== "output") return;
1531 delivered += 1;
1532 expect(event.data).toBe(
1533 delivered === 1
1534 ? "start"
1535 : (delivered === 2
1536 ? "queued-a"
1537 : delivered === 3
1538 ? "queued-b"
1539 : `${delivered - 3}`
1540 ).padEnd(chunkBytes, "x"),
1541 );
1542 if (delivered === 1) {
1543 yield* Deferred.succeed(entered, undefined);
1544 yield* Deferred.await(release);
1545 }
1546 if (delivered === chunkCount) {
1547 yield* Deferred.succeed(measured, undefined);
1548 yield* Deferred.await(finish);
1549 } else if (delivered < chunkCount) {
1550 process.emitData(`${delivered}`.padEnd(chunkBytes, "x"));
1551 } else if (delivered === chunkCount + 2) {
1552 yield* Deferred.succeed(drained, undefined);
1553 }
1554 }),
1555 );
1556 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1557 process.emitData("start");
1558 yield* Deferred.await(entered);
1559 process.emitData("queued-a".padEnd(chunkBytes, "x"));
1560 process.emitData("queued-b".padEnd(chunkBytes, "x"));
1561 yield* Deferred.succeed(release, undefined);
1562 yield* Deferred.await(measured);
1563
1564 const state = (yield* readState) as {
1565 sessions: ReadonlyMap<
1566 string,
1567 { pendingProcessEvents: ReadonlyArray<{ data?: string } | undefined> }
1568 >;
1569 };
1570 const retained = [...state.sessions.values()].flatMap(
1571 (session) => session.pendingProcessEvents,
1572 );
1573 const retainedBytes = retained.reduce(
1574 (bytes, event) => bytes + (event?.data?.length ?? 0),
1575 0,
1576 );
1577 expect(delivered).toBe(chunkCount);
1578 expect(retainedBytes).toBeLessThanOrEqual(2 * chunkBytes);
1579 expect(retained.length).toBeLessThanOrEqual(4);
1580 yield* Deferred.succeed(finish, undefined);
1581 yield* Deferred.await(drained);
1582 }),
1583 );
1584
1585 it.effect("retains plain Unicode and control characters around a split query", () =>
1586 Effect.gen(function* () {
1587 const { manager, ptyAdapter } = yield* createManager();
1588 yield* manager.open(openInput());
1589 const process = ptyAdapter.processes[0]!;
1590 // Mojibake like "â€\u009d" (for ”) carries C1 code points that libghostty prints as text.
1591 const before = "café\t界🙂\u0007\u009c\u0085 â€\u009d Ð\u0090 \u009e\u009f\u009b6n";
1592 const after = "e\u0301\r\n";
1593
1594 process.emitData(before);
1595 process.emitData("\u001b[5");
1596 process.emitData(`n${after}`);
1597 yield* manager.close({ threadId: "thread-1" });
1598
1599 expect((yield* manager.open(openInput())).history).toBe(before + after);
1600 }),
1601 );
1602
1603 it.effect("strips replayable CSI and DCS traffic while preserving setters", () =>
1604 Effect.gen(function* () {
1605 const { manager, ptyAdapter } = yield* createManager();
1606 yield* manager.open(openInput());
1607 const process = ptyAdapter.processes[0];
1608 expect(process).toBeDefined();
1609 if (!process) return;
1610
1611 process.emitData("prompt ");
1612 process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u");
1613 process.emitData("\u001b[=c\u001b[=0c\u001bZ");
1614 process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\");
1615 process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\");
1616 // BEL is DCS payload, not a terminator: only ST ends the string.
1617 process.emitData("\u001bP$qm\u0007hidden\u001b\\\u001bP+q544e\u0007hidden\u001b\\");
1618 process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u');
1619 process.emitData("\u001b]0;x\u001b\u001b[?2026$p");
1620 process.emitData("done\n");
1621
1622 yield* manager.close({ threadId: "thread-1" });
1623
1624 const reopened = yield* manager.open(openInput());
1625 expect(
1626 reopened.history.startsWith(
1627 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[u\u001b]0;x\u001bdone\n',
1628 ),
1629 ).toBe(true);
1630 }),
1631 );
1632
1633 // Ghostty executes 0x00-0x0F inside a CSI and ignores DEL and 0x10-0x1F; none change the query.
1634 it.effect.each([
1635 { name: "NUL in DA", data: "A\u001b[0\u0000cB", history: "AB" },
1636 { name: "DEL in DA", data: "A\u001b[0\u007fcB", history: "AB" },
1637 { name: "NUL in DECRQM", data: "A\u001b[?2026\u0000$pB", history: "AB" },
1638 { name: "CR in DSR", data: "AB\u001b[5\rnC", history: "AB\rC" },
1639 { name: "DLE in DSR", data: "AB\u001b[5\u0010nC", history: "ABC" },
1640 // Ghostty reads non-ASCII there as UTF-8 bytes: it drops é and runs 0x80-0x9F as C1 controls.
1641 { name: "é in DA", data: "A\u001b[0écB", history: "AB" },
1642 { name: "DECID byte in a CSI", data: "A\u001b[嚠B", history: "A\ufffdB" },
1643 {
1644 name: "C1 DCS then C1 CSI in DSR",
1645 data: "A\u001b[\u0090\u009b6nB",
1646 history: "A\u001bP\u009cB",
1647 },
1648 { name: "ESC in DSR", data: "A\u001b[5\u001b[6nB", history: "AB" },
1649 ])(
1650 "strips a query with an embedded control but keeps what the terminal ran ($name)",
1651 ({ data, history }) =>
1652 Effect.gen(function* () {
1653 const { manager, ptyAdapter } = yield* createManager();
1654 yield* manager.open(openInput());
1655 ptyAdapter.processes[0]!.emitData(data);
1656 yield* manager.close({ threadId: "thread-1" });
1657
1658 const reopened = yield* manager.open(openInput());
1659 const restored = reopened.history.replaceAll("\u0000", "");
1660 expect(restored.split("\u001b[?1049h")[0]).toBe(history);
1661 }),
1662 );
1663
1664 // Ghostty aborts a CSI at a non-ASCII code point and prints it and what follows.
1665 it.effect("keeps a CSI interrupted by non-ASCII text in history", () =>
1666 Effect.gen(function* () {
1667 const { manager, ptyAdapter } = yield* createManager();
1668 yield* manager.open(openInput());
1669 ptyAdapter.processes[0]!.emitData("A\u001b[界nB");
1670 yield* manager.close({ threadId: "thread-1" });
1671
1672 const reopened = yield* manager.open(openInput());
1673 expect(reopened.history.split("\u001b[?1049h")[0]).toBe("A\u001b[界nB");
1674 }),
1675 );
1676
1677 it.effect.each([
1678 { name: "OSC", sequence: "\u001b]0;unfinished" },
1679 { name: "DCS", sequence: "\u001bPunfinished" },
1680 { name: "PM", sequence: "\u001b^unfinished" },
1681 { name: "APC", sequence: "\u001b_unfinished" },
1682 { name: "CSI", sequence: "\u001b[5" },
1683 ])("keeps output after a cancelled $name sequence in history", ({ sequence }) =>
1684 Effect.gen(function* () {
1685 const { manager, ptyAdapter } = yield* createManager(10);
1686 yield* manager.open(openInput());
1687 const process = ptyAdapter.processes[0]!;
1688 // A new escape sequence also aborts one, as in xterm.js; keep it last so CAN cannot end it.
1689 for (const cancel of ["\u0018", "\u001a", "\u001b[0m"]) {
1690 process.emitData(sequence);
1691 process.emitData(cancel);
1692 process.emitData("next line\n");
1693 process.emitData(`${sequence}${cancel}next line\n`);
1694 }
1695 yield* manager.close({ threadId: "thread-1" });
1696
1697 const reopened = yield* manager.open(openInput());
1698 expect(reopened.history.match(/next line/g)).toHaveLength(6);
1699 }),
1700 );
1701
1702 it.effect("handles CSI and DCS query sequences split across output chunks", () =>
1703 Effect.gen(function* () {
1704 const { manager, ptyAdapter } = yield* createManager();
1705 yield* manager.open(openInput());
1706 const process = ptyAdapter.processes[0];
1707 expect(process).toBeDefined();
1708 if (!process) return;
1709
1710 process.emitData("before ");
1711 process.emitData("\u001b[?2026$");
1712 process.emitData("pafter ");
1713 process.emitData("\u001bP$q ");
1714 process.emitData("m\u001b");
1715 process.emitData("\\after ");
1716 process.emitData("\u001b[?3");
1717 process.emitData("1uafter ");
1718 process.emitData("\u001bP+q544e");
1719 process.emitData("\u001b\\after\n");
1720
1721 yield* manager.close({ threadId: "thread-1" });
1722
1723 const reopened = yield* manager.open(openInput());
1724 assert.equal(reopened.history, "before after after after after\n");
1725 }),
1726 );
1727
1728 it.effect("keeps a decoded U+009C inside a stripped OSC query out of history", () =>
1729 Effect.gen(function* () {
1730 const { manager, ptyAdapter } = yield* createManager();
1731 yield* manager.open(openInput());
1732 const process = ptyAdapter.processes[0]!;
1733 // libghostty receives UTF-8 (c2 9c), which is OSC payload; only ESC \ ends this string.
1734 process.emitData("A\u001b]11;?\u009cHIDDEN\u001b\\B\n");
1735 // A DCS string does end at U+009C there, so the text after it stays visible.
1736 process.emitData("C\u001bP$qm\u009cSHOWN\u001b\\D\n");
1737 yield* manager.close({ threadId: "thread-1" });
1738
1739 expect((yield* manager.open(openInput())).history).toMatch(/^AB\nCSHOWN\u001b\\D\n/);
1740 }),
1741 );
1742
1743 it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () =>
1744 Effect.gen(function* () {
1745 const { manager, ptyAdapter, logsDir } = yield* createManager();
1746 yield* manager.open(openInput());
1747 const process = ptyAdapter.processes[0]!;
1748 const outputSeen = yield* Deferred.make<void>();
1749 const unsubscribe = yield* manager.subscribe((event) =>
1750 event.type === "output" && event.data === "done\n"
1751 ? Deferred.succeed(outputSeen, undefined).pipe(Effect.asVoid)
1752 : Effect.void,
1753 );
1754 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1755 const sequences = [
1756 { prefix: `\u001b]52;c;${"YWJj".repeat(16_384)}\u001b`, terminator: "\\" },
1757 { prefix: `\u001bPq${"?".repeat(65_536)}`, terminator: "\u001b\\" },
1758 ];
1759 const stripped = "\u001b]11;?\u0007\u001bP$q m\u001b\\";
1760 const preserved = "\u001b[31m\u001b]52;c;YWJj\u0007";
1761 const expected =
1762 sequences.map(({ prefix, terminator }) => prefix + terminator + preserved).join("") +
1763 "done\n";
1764
1765 // Counts reads of strings larger than one emitted chunk, so rescanning the
1766 // pending prefix on every chunk shows up as quadratic work.
1767 const charCodeAt = String.prototype.charCodeAt;
1768 let largeStringReads = 0;
1769 yield* Effect.gen(function* () {
1770 // eslint-disable-next-line no-extend-native -- Count reads without retaining millions of spy call records.
1771 String.prototype.charCodeAt = function (this: string, index: number) {
1772 if (this.length > 4_096) largeStringReads += 1;
1773 return charCodeAt.call(this, index);
1774 };
1775 for (const { prefix, terminator } of sequences) {
1776 for (let offset = 0; offset < prefix.length; offset += 4_096) {
1777 process.emitData(prefix.slice(offset, offset + 4_096));
1778 }
1779 process.emitData(terminator + stripped + preserved);
1780 }
1781 process.emitData("done\n");
1782 yield* Deferred.await(outputSeen);
1783 }).pipe(
1784 Effect.ensuring(
1785 Effect.sync(() => {
1786 // eslint-disable-next-line no-extend-native -- Restore the counting hook even when the test fails.
1787 String.prototype.charCodeAt = charCodeAt;
1788 }),
1789 ),
1790 );
1791 yield* manager.close({ threadId: "thread-1" });
1792
1793 expect(largeStringReads).toBeLessThan(2 * expected.length);
1794 expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe(expected);
1795 expect((yield* manager.open(openInput())).history.startsWith(expected)).toBe(true);
1796 }),
1797 );
1798
1799 it.effect(
1800 "preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes",
1801 () =>
1802 Effect.gen(function* () {
1803 const { manager, ptyAdapter } = yield* createManager();
1804 yield* manager.open(openInput());
1805 const process = ptyAdapter.processes[0];
1806 expect(process).toBeDefined();
1807 if (!process) return;
1808
1809 process.emitData("before ");
1810 process.emitData("\u001b(");
1811 process.emitData("Bafter\n");
1812
1813 yield* manager.close({ threadId: "thread-1" });
1814
1815 const reopened = yield* manager.open(openInput());
1816 expect(reopened.history.startsWith("before \u001b(Bafter\n")).toBe(true);
1817 }),
1818 );
1819
1820 it.effect.each([
1821 {
1822 label: "subagent",
1823 threadId:
1824 "thread:provider:claudeAgent:native-thread:provider-thread%3Aprovider%3AclaudeAgent%3Anative-thread%3Apending%253Arun%253Athread%253A9175fb53-52d7-4d4d-9be7-25a76cf84b91%253Aordinal%253A7%3Aad899ae84c7a131b0",
1825 },
1826 // Also too long for the legacy `<sanitized id>.log` lookup.
1827 { label: "300-character", threadId: "x".repeat(300) },
1828 ])("persists history for a $label thread id too long to encode into a filename", ({ threadId }) =>
1829 Effect.gen(function* () {
1830 const terminalId = "t".repeat(128);
1831 const { manager, ptyAdapter, logsDir } = yield* createManager();
1832 const fs = yield* FileSystem.FileSystem;
1833 yield* manager.open(openInput({ threadId }));
1834 yield* manager.open(openInput({ threadId, terminalId }));
1835 ptyAdapter.processes[0]!.emitData("default\n");
1836 ptyAdapter.processes[1]!.emitData("long\n");
1837 yield* manager.close({ threadId });
1838
1839 expect((yield* manager.open(openInput({ threadId }))).history).toBe("default\n");
1840 expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe("long\n");
1841
1842 yield* manager.close({ threadId, deleteHistory: true });
1843 expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1844 }),
1845 );
1846
1847 // Case-insensitive filesystems resolve "Terminal_YQ.log" to thread "a"'s "terminal_YQ.log",
1848 // so the mixed-case file stands in for that alias on case-sensitive hosts.
1849 it.effect.each(["terminal_", "Terminal_"])(
1850 "never resolves a %s legacy history name to another thread's history file",
1851 (prefix) =>
1852 Effect.gen(function* () {
1853 const { manager, logsDir } = yield* createManager();
1854 const fs = yield* FileSystem.FileSystem;
1855 const path = yield* Path.Path;
1856 const threadId = `${prefix}${Base64Url.encode("a")}`;
1857 const otherThreadPath = path.join(logsDir, `${threadId}.log`);
1858 yield* fs.makeDirectory(logsDir, { recursive: true });
1859 yield* fs.writeFileString(otherThreadPath, "thread a\n");
1860
1861 expect((yield* manager.open(openInput({ threadId }))).history).toBe("");
1862 yield* manager.close({ threadId, terminalId: DEFAULT_TERMINAL_ID, deleteHistory: true });
1863 yield* manager.close({ threadId, deleteHistory: true });
1864
1865 expect(yield* fs.readFileString(otherThreadPath)).toBe("thread a\n");
1866 }),
1867 );
1868
1869 it.effect("keeps reading and deleting history at an encoded path that already fit", () =>
1870 Effect.gen(function* () {
1871 const threadId = "x".repeat(48);
1872 const { manager, logsDir } = yield* createManager();
1873 const fs = yield* FileSystem.FileSystem;
1874 const logPath = yield* historyLogPath(logsDir, threadId);
1875 yield* fs.makeDirectory(logsDir, { recursive: true });
1876 yield* fs.writeFileString(logPath, "before upgrade\n");
1877
1878 expect((yield* manager.open(openInput({ threadId }))).history).toBe("before upgrade\n");
1879 // A long terminal id pushes only this terminal's name past the limit, so the thread's
1880 // history is split across both forms and deleting the thread must remove both.
1881 yield* manager.open(openInput({ threadId, terminalId: "t".repeat(128) }));
1882
1883 yield* manager.close({ threadId, deleteHistory: true });
1884 expect(yield* fs.exists(logPath)).toBe(false);
1885 expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1886 }),
1887 );
1888
1889 it.effect.each([
1890 {
1891 label: "delegated setup",
1892 threadId:
1893 "thread:delegated-task:command%3Amcp%3A00000000-0000-4000-8000-000000000000%3Adelegate-task%3Aexample-r4-workspace-prepare-engine3",
1894 terminalId: "setup-setup-worktree-2",
1895 },
1896 { label: "long thread", threadId: "t".repeat(400), terminalId: DEFAULT_TERMINAL_ID },
1897 { label: "Unicode thread", threadId: "项目😀".repeat(60), terminalId: "setup" },
1898 { label: "long terminal", threadId: "short", terminalId: "t".repeat(128) },
1899 { label: "142-byte boundary", threadId: "t".repeat(48), terminalId: "s".repeat(48) },
1900 { label: "144-byte boundary", threadId: "t".repeat(49), terminalId: "s".repeat(48) },
1901 ])("persists $label history with a 143-byte filename limit", ({ threadId, terminalId }) =>
1902 Effect.gen(function* () {
1903 const fs = yield* FileSystem.FileSystem;
1904 const path = yield* Path.Path;
1905 const check = (filePath: string) =>
1906 Buffer.byteLength(path.basename(filePath)) <= 143
1907 ? Effect.void
1908 : Effect.fail(
1909 PlatformError.systemError({
1910 _tag: "Unknown",
1911 module: "FileSystem",
1912 method: "access",
1913 pathOrDescriptor: filePath,
1914 cause: { code: "ENAMETOOLONG" },
1915 }),
1916 );
1917 const limited = FileSystem.FileSystem.of({
1918 ...fs,
1919 exists: (filePath) => Effect.andThen(check(filePath), fs.exists(filePath)),
1920 open: (filePath, options) => Effect.andThen(check(filePath), fs.open(filePath, options)),
1921 writeFileString: (filePath, data, options) =>
1922 Effect.andThen(check(filePath), fs.writeFileString(filePath, data, options)),
1923 remove: (filePath, options) =>
1924 Effect.andThen(check(filePath), fs.remove(filePath, options)),
1925 });
1926 const { manager, ptyAdapter, logsDir } = yield* createManager().pipe(
1927 Effect.provideService(FileSystem.FileSystem, limited),
1928 );
1929 yield* manager.open(openInput({ threadId, terminalId }));
1930 ptyAdapter.processes[0]!.emitData("setup output\n");
1931 yield* manager.close({ threadId, terminalId });
1932 const names = yield* fs.readDirectory(logsDir);
1933 expect(names).toHaveLength(1);
1934 expect(Buffer.byteLength(names[0]!)).toBeLessThanOrEqual(143);
1935 expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe(
1936 "setup output\n",
1937 );
1938 const otherThread = `${threadId}-other`;
1939 expect((yield* manager.open(openInput({ threadId: otherThread, terminalId }))).history).toBe(
1940 "",
1941 );
1942 ptyAdapter.processes[2]!.emitData("other output\n");
1943 yield* manager.close({ threadId: otherThread, terminalId });
1944 expect(yield* fs.readDirectory(logsDir)).toHaveLength(2);
1945 yield* manager.close({ threadId, terminalId, deleteHistory: true });
1946 expect(yield* fs.readDirectory(logsDir)).toHaveLength(1);
1947 yield* manager.close({ threadId: otherThread, deleteHistory: true });
1948 expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1949 }),
1950 );
1951
1952 it.effect.each([
1953 { source: "encoded", terminalId: DEFAULT_TERMINAL_ID },
1954 { source: "encoded", terminalId: "setup-setup-worktree-2" },
1955 { source: "sanitized", terminalId: DEFAULT_TERMINAL_ID },
1956 ])("migrates oversized $source history for $terminalId", ({ source, terminalId }) =>
1957 Effect.gen(function* () {
1958 const fs = yield* FileSystem.FileSystem;
1959 const path = yield* Path.Path;
1960 const { manager, logsDir } = yield* createManager();
1961 const threadId = "m".repeat(100);
1962 const oldPath =
1963 source === "encoded"
1964 ? path.join(
1965 logsDir,
1966 `terminal_${Base64Url.encode(threadId)}${terminalId === DEFAULT_TERMINAL_ID ? "" : `_${Base64Url.encode(terminalId)}`}.log`,
1967 )
1968 : path.join(logsDir, `${threadId}.log`);
1969 yield* fs.writeFileString(oldPath, "old output\n");
1970 expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe(
1971 "old output\n",
1972 );
1973 const names = yield* fs.readDirectory(logsDir);
1974 expect(names).toHaveLength(1);
1975 expect(Buffer.byteLength(names[0]!)).toBeLessThanOrEqual(143);
1976 expect(yield* fs.exists(oldPath)).toBe(false);
1977 expect(yield* fs.readFileString(path.join(logsDir, names[0]!))).toBe("old output\n");
1978 yield* manager.close({ threadId, terminalId, deleteHistory: true });
1979 expect(yield* fs.readDirectory(logsDir)).toEqual([]);
1980 }),
1981 );
1982
1983 it.effect.each(["terminal", "thread"] as const)(
1984 "deletes compact and older encoded history when closing a %s",
1985 (scope) =>
1986 Effect.gen(function* () {
1987 const fs = yield* FileSystem.FileSystem;
1988 const path = yield* Path.Path;
1989 const { manager, logsDir } = yield* createManager();
1990 const threadId = "d".repeat(100);
1991 const terminalId = "setup-setup-worktree-2";
1992 yield* manager.open(openInput({ threadId, terminalId }));
1993 yield* manager.close({ threadId, terminalId });
1994 const oldPath = path.join(
1995 logsDir,
1996 `terminal_${Base64Url.encode(threadId)}_${Base64Url.encode(terminalId)}.log`,
1997 );
1998 yield* fs.writeFileString(oldPath, "stale copy\n");
1999 yield* fs.writeFileString(path.join(logsDir, "unrelated.log"), "keep\n");
2000 if (scope === "terminal") {
2001 yield* manager.close({ threadId, terminalId, deleteHistory: true });
2002 } else {
2003 yield* manager.close({ threadId, deleteHistory: true });
2004 }
2005 expect(yield* fs.readDirectory(logsDir)).toEqual(["unrelated.log"]);
2006 }),
2007 );
2008
2009 it.effect("prefers bounded history over a stale encoded copy", () =>
2010 Effect.gen(function* () {
2011 const { manager, ptyAdapter, logsDir } = yield* createManager();
2012 const fs = yield* FileSystem.FileSystem;
2013 const threadId = "p".repeat(100);
2014 yield* manager.open(openInput({ threadId }));
2015 ptyAdapter.processes[0]!.emitData("current\n");
2016 yield* manager.close({ threadId });
2017 const oldPath = yield* historyLogPath(logsDir, threadId);
2018 yield* fs.writeFileString(oldPath, "stale\n");
2019
2020 expect((yield* manager.open(openInput({ threadId }))).history).toBe("current\n");
2021 yield* manager.close({ threadId, terminalId: DEFAULT_TERMINAL_ID, deleteHistory: true });
2022 expect(yield* fs.readDirectory(logsDir)).toEqual([]);
2023 }),
2024 );
2025
2026 it.effect("retains encoded history if migration cannot write the bounded file", () =>
2027 Effect.gen(function* () {
2028 const fs = yield* FileSystem.FileSystem;
2029 let failNextWrite = true;
2030 const limited = FileSystem.FileSystem.of({
2031 ...fs,
2032 writeFileString: (filePath, data, options) => {
2033 if (!failNextWrite) return fs.writeFileString(filePath, data, options);
2034 failNextWrite = false;
2035 return fs.writeFileString(filePath, "partial").pipe(
2036 Effect.andThen(
2037 Effect.fail(
2038 PlatformError.systemError({
2039 _tag: "Unknown",
2040 module: "FileSystem",
2041 method: "writeFileString",
2042 cause: { code: "ENOSPC" },
2043 }),
2044 ),
2045 ),
2046 );
2047 },
2048 });
2049 const { manager, logsDir } = yield* createManager().pipe(
2050 Effect.provideService(FileSystem.FileSystem, limited),
2051 );
2052 const threadId = "f".repeat(100);
2053 const oldPath = yield* historyLogPath(logsDir, threadId);
2054 yield* fs.writeFileString(oldPath, "preserve me\n");
2055
2056 expect(Exit.isFailure(yield* Effect.exit(manager.open(openInput({ threadId }))))).toBe(true);
2057 expect(yield* fs.readFileString(oldPath)).toBe("preserve me\n");
2058 expect(yield* fs.readDirectory(logsDir)).toHaveLength(1);
2059 expect((yield* manager.open(openInput({ threadId }))).history).toBe("preserve me\n");
2060 }),
2061 );
2062
2063 it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>
2064 Effect.gen(function* () {
2065 const { manager, logsDir } = yield* createManager();
2066 const path = yield* Path.Path;
2067 const legacyPath = path.join(logsDir, "thread-1.log");
2068 const nextPath = yield* historyLogPath(logsDir);
2069 yield* writeFileString(legacyPath, "legacy-line\n");
2070
2071 const snapshot = yield* manager.open(openInput());
2072
2073 assert.equal(snapshot.history, "legacy-line\n");
2074 expect(yield* pathExists(nextPath)).toBe(true);
2075 expect(yield* readFileString(nextPath)).toBe("legacy-line\n");
2076 expect(yield* pathExists(legacyPath)).toBe(false);
2077 }),
2078 );
2079
2080 it.effect("keeps a startup failure in the snapshot every later attachment receives", () =>
2081 Effect.gen(function* () {
2082 const { manager, ptyAdapter } = yield* createManager();
2083 ptyAdapter.spawnFailures.push(new Error("forkpty(3) failed."));
2084 const startupFailure = {
2085 type: "snapshot",
2086 snapshot: {
2087 status: "error",
2088 error: expect.stringContaining("Failed to spawn PTY process"),
2089 },
2090 };
2091 const record = (events: TerminalAttachStreamEvent[]) => (event: TerminalAttachStreamEvent) =>
2092 Effect.sync(() => events.push(event));
2093
2094 const creating: TerminalAttachStreamEvent[] = [];
2095 (yield* manager.attachStream(openInput(), record(creating)))();
2096 const resumed: TerminalAttachStreamEvent[] = [];
2097 (yield* manager.attachStream({ ...openInput(), resume: true }, record(resumed)))();
2098 const observed: TerminalAttachStreamEvent[] = [];
2099 (yield* manager.observeStream(
2100 { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID },
2101 record(observed),
2102 ))();
2103 expect([creating, resumed, observed]).toMatchObject([
2104 [startupFailure],
2105 [startupFailure],
2106 [startupFailure],
2107 ]);
2108
2109 const restarted = yield* manager.open(openInput());
2110 expect(restarted.status).toBe("running");
2111 expect(restarted).not.toHaveProperty("error");
2112 }),
2113 );
2114
2115 it.effect("retries with fallback shells when preferred shell spawn fails", () =>
2116 Effect.gen(function* () {
2117 const platform = yield* HostProcess.Platform;
2118 const missingShell =
2119 platform === "win32" ? "C:\\definitely\\missing-shell.exe" : "/definitely/missing-shell -l";
2120 const { manager, ptyAdapter } = yield* createManager(5, {
2121 shellResolver: () => missingShell,
2122 });
2123 ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));
2124
2125 const snapshot = yield* manager.open(openInput());
2126
2127 assert.equal(snapshot.status, "running");
2128 expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
2129 expect(ptyAdapter.spawnInputs[0]?.shell).toBe(
2130 platform === "win32" ? missingShell : "/definitely/missing-shell",
2131 );
2132
2133 if (platform === "win32") {
2134 expect(
2135 ptyAdapter.spawnInputs.some(
2136 (input) =>
2137 input.shell === "pwsh.exe" ||
2138 input.shell === "powershell.exe" ||
2139 input.shell === "cmd.exe",
2140 ),
2141 ).toBe(true);
2142 } else {
2143 expect(
2144 ptyAdapter.spawnInputs
2145 .slice(1)
2146 .some((input) => input.shell !== "/definitely/missing-shell"),
2147 ).toBe(true);
2148 }
2149 }),
2150 );
2151
2152 it.effect("starts an existing $SHELL whose path contains spaces before a dash", () =>
2153 Effect.gen(function* () {
2154 const fs = yield* FileSystem.FileSystem;
2155 const { join } = yield* Path.Path;
2156 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-shell-path-" });
2157 const bin = join(root, "Jane -Doe Smith", ".local", "bin");
2158 yield* fs.makeDirectory(bin, { recursive: true });
2159 yield* fs.writeFileString(join(bin, "fish"), "");
2160 // Temp dirs are not POSIX-absolute on Windows, so stat maps a fixed POSIX prefix onto them.
2161 const fixtureFs = FileSystem.FileSystem.of({
2162 ...fs,
2163 stat: (filePath) =>
2164 fs.stat(
2165 filePath.startsWith("/shell-fixture/")
2166 ? join(root, filePath.slice("/shell-fixture/".length))
2167 : filePath,
2168 ),
2169 });
2170 const { manager, ptyAdapter } = yield* createManager(5, {
2171 env: { SHELL: "/shell-fixture/Jane -Doe Smith/.local/bin/fish -l" },
2172 }).pipe(
2173 Effect.provide(layerWithHostPlatform("darwin")),
2174 Effect.provideService(FileSystem.FileSystem, fixtureFs),
2175 );
2176
2177 yield* manager.open(openInput());
2178
2179 expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual([
2180 "/shell-fixture/Jane -Doe Smith/.local/bin/fish",
2181 ]);
2182 }),
2183 );
2184
2185 it.effect("keeps missing or quoted $SHELL paths that contain spaces", () =>
2186 Effect.gen(function* () {
2187 for (const [shell, expected] of [
2188 ["/Users/Jane Doe/.local/bin/fish", "/Users/Jane Doe/.local/bin/fish"],
2189 ['"/opt/my -shell/fish" -l', "/opt/my -shell/fish"],
2190 ]) {
2191 const { manager, ptyAdapter } = yield* createManager(5, {
2192 env: { SHELL: shell },
2193 }).pipe(Effect.provide(layerWithHostPlatform("darwin")));
2194
2195 yield* manager.open(openInput());
2196
2197 expect(
2198 ptyAdapter.spawnInputs.map((input) => input.shell),
2199 shell,
2200 ).toEqual([expected]);
2201 }
2202 }),
2203 );
2204
2205 it.effect(
2206 "writes completion syntax for the fallback shell instead of the configured fish shell",
2207 () =>
2208 Effect.gen(function* () {
2209 const env = { SHELL: "/missing/fish" };
2210 const { manager, ptyAdapter, baseDir } = yield* createManager(5, { env }).pipe(
2211 Effect.provide(layerWithHostPlatform("linux")),
2212 );
2213 ptyAdapter.spawnFailures.push(new Error("spawn fish ENOENT"));
2214 const written = yield* Deferred.make<void>();
2215 const terminals = TerminalManager.TerminalManager.of({
2216 ...manager,
2217 write: (input) =>
2218 manager.write(input).pipe(Effect.tap(() => Deferred.succeed(written, undefined))),
2219 });
2220 const runner = yield* ProjectSetupScriptRunner.make.pipe(
2221 Effect.provide(
2222 Layer.mergeAll(
2223 Layer.succeed(TerminalManager.TerminalManager, terminals),
2224 Layer.mock(ProjectService.ProjectService)({}),
2225 Layer.mock(ProjectionStore.ProjectionStoreV2)({
2226 getThreadShell: () => Effect.succeed(null),
2227 }),
2228 ServerSettings.layerTest(),
2229 Layer.succeed(HostProcess.Platform, "linux"),
2230 Layer.succeed(HostProcess.Environment, env),
2231 ),
2232 ),
2233 );
2234 yield* runner.runForThread({
2235 threadId: "thread-setup-fallback",
2236 worktreePath: baseDir,
2237 project: {
2238 id: ProjectId.make("project-setup-fallback"),
2239 workspaceRoot: baseDir,
2240 scripts: [
2241 {
2242 id: "setup",
2243 name: "Setup",
2244 command: "echo setup-ready",
2245 icon: "play",
2246 runOnWorktreeCreate: true,
2247 },
2248 ],
2249 },
2250 observeCompletion: {},
2251 });
2252 const process = ptyAdapter.processes[0]!;
2253 process.emitData("\x1b[?2004h");
2254 yield* Deferred.await(written);
2255 const command = process.writes[0]!;
2256 expect(command).toContain('"$?"');
2257 }),
2258 );
2259
2260 it.effect.each([
2261 { platform: "win32", shell: String.raw`C:\Program Files\Git\bin\bash.exe` },
2262 { platform: "linux", shell: "/opt/custom shell/bin/bash" },
2263 ] as const)("prefers the configured terminal shell on $platform: $shell", ({ platform, shell }) =>
2264 Effect.gen(function* () {
2265 const { manager, ptyAdapter } = yield* createManager(5, {
2266 env: { T3CODE_TERMINAL_SHELL: ` ${shell} `, SHELL: "/bin/zsh" },
2267 }).pipe(Effect.provide(layerWithHostPlatform(platform)));
2268
2269 yield* manager.open(openInput());
2270
2271 expect(ptyAdapter.spawnInputs[0]?.shell).toBe(shell);
2272 }),
2273 );
2274
2275 it.effect("lets script terminals keep the default shell without changing other terminals", () =>
2276 Effect.gen(function* () {
2277 const gitBash = String.raw`C:\Program Files\Git\bin\bash.exe`;
2278 const { manager, ptyAdapter } = yield* createManager(5, {
2279 env: { T3CODE_TERMINAL_SHELL: gitBash },
2280 }).pipe(Effect.provide(layerWithHostPlatform("win32")));
2281
2282 yield* manager.open(openInput({ env: { T3CODE_TERMINAL_SHELL: "" } }));
2283 yield* manager.open(openInput({ terminalId: "interactive" }));
2284
2285 expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual(["pwsh.exe", gitBash]);
2286 }),
2287 );
2288
2289 // POSIX exec failures are asynchronous in node-pty; ConPTY has a separate readiness protocol.
2290 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
2291 "resolves configured shells and falls back from invalid paths with the real PTY adapter",
2292 () =>
2293 Effect.gen(function* () {
2294 const fs = yield* FileSystem.FileSystem;
2295 const path = yield* Path.Path;
2296 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-real-shell-" });
2297 const nonExecutable = path.join(baseDir, "not-executable");
2298 yield* fs.writeFileString(nonExecutable, "#!/bin/sh\nexit 0\n");
2299 yield* fs.chmod(nonExecutable, 0o644);
2300 const ptyAdapter = yield* PtyAdapter.PtyAdapter.pipe(Effect.provide(NodePtyAdapter.layer));
2301 const toolsDir = path.join(baseDir, "tools");
2302 const customShell = path.join(toolsDir, "custom-shell");
2303 yield* fs.makeDirectory(toolsDir);
2304 yield* fs.writeFileString(customShell, "#!/bin/sh\nexec /bin/sh\n");
2305 yield* fs.chmod(customShell, 0o755);
2306 const spacedDir = path.join(baseDir, "shells ");
2307 const spacedShell = path.join(spacedDir, "custom-shell");
2308 yield* fs.makeDirectory(spacedDir);
2309 yield* fs.writeFileString(spacedShell, "#!/bin/sh\nexec /bin/sh\n");
2310 yield* fs.chmod(spacedShell, 0o755);
2311 for (const { shell, searchPath, cwd, expectedShell } of [
2312 { shell: path.join(baseDir, "missing"), searchPath: "/bin", expectedShell: "/bin/sh" },
2313 { shell: nonExecutable, searchPath: "/bin", expectedShell: "/bin/sh" },
2314 { shell: "custom-shell", searchPath: "./tools", expectedShell: customShell },
2315 { shell: "custom-shell", searchPath: toolsDir, expectedShell: customShell },
2316 { shell: "custom-shell", searchPath: '"./tools"', expectedShell: customShell },
2317 { shell: "custom-shell", searchPath: ":/bin", cwd: toolsDir, expectedShell: customShell },
2318 { shell: "custom-shell", searchPath: `${spacedDir}:/bin`, expectedShell: spacedShell },
2319 ] as ReadonlyArray<{
2320 shell: string;
2321 searchPath: string;
2322 cwd?: string;
2323 expectedShell: string;
2324 }>) {
2325 const spawnedShells: string[] = [];
2326 const manager = yield* TerminalManager.makeWithOptions({
2327 logsDir: path.join(baseDir, "logs"),
2328 ptyAdapter: {
2329 spawn: (input) => {
2330 spawnedShells.push(input.shell);
2331 return ptyAdapter.spawn(input);
2332 },
2333 },
2334 shellResolver: () => "/bin/sh",
2335 env: { ...process.env, T3CODE_TERMINAL_SHELL: shell, PATH: searchPath },
2336 });
2337 const snapshot = yield* manager.open(openInput({ cwd: cwd ?? baseDir }));
2338 expect(spawnedShells).toEqual([expectedShell]);
2339 expect(snapshot.status).toBe("running");
2340 yield* manager.close({ threadId: "thread-1" });
2341 }
2342 }),
2343 );
2344
2345 it.effect("preserves Windows Path casing when appending managed ACP binaries", () =>
2346 Effect.gen(function* () {
2347 const fileSystem = yield* FileSystem.FileSystem;
2348 const path = yield* Path.Path;
2349 const cacheDir = yield* fileSystem.makeTempDirectoryScoped({
2350 prefix: "t3-terminal-acp-path-",
2351 });
2352 const installBin = path.join(
2353 cacheDir,
2354 "tools",
2355 "example-agent",
2356 "1.2.3",
2357 "windows-x86_64",
2358 "bin",
2359 );
2360 yield* fileSystem.makeDirectory(installBin, { recursive: true });
2361 yield* fileSystem.makeDirectory(path.join(cacheDir, "acp-registry"), { recursive: true });
2362 yield* fileSystem.writeFileString(
2363 path.join(cacheDir, "acp-registry", "registry.json"),
2364 encodeUnknownJson({
2365 version: "1.0.0",
2366 agents: [
2367 {
2368 id: "example-agent",
2369 name: "Example Agent",
2370 version: "1.2.3",
2371 description: "ACP Registry test agent",
2372 distribution: {
2373 binary: {
2374 "windows-x86_64": {
2375 archive: "https://registry.test/example-agent.zip",
2376 cmd: "bin/example-agent.exe",
2377 },
2378 },
2379 },
2380 },
2381 ],
2382 }),
2383 );
2384 const { manager, ptyAdapter } = yield* createManager(5, {
2385 managedBinaryCacheDir: cacheDir,
2386 managedBinaryToolsDir: path.join(cacheDir, "tools"),
2387 env: {
2388 ComSpec: "C:\\Windows\\System32\\cmd.exe",
2389 Path: "C:\\Windows\\System32",
2390 SystemRoot: "C:\\Windows",
2391 },
2392 }).pipe(
2393 Effect.provide(
2394 Layer.merge(
2395 layerWithHostPlatform("win32"),
2396 Layer.succeed(HostProcess.Architecture, "x64"),
2397 ),
2398 ),
2399 );
2400
2401 yield* manager.open(openInput());
2402
2403 const spawnEnv = ptyAdapter.spawnInputs[0]?.env;
2404 expect(spawnEnv?.PATH).toBeUndefined();
2405 expect(spawnEnv?.Path).toBe(`C:\\Windows\\System32;${installBin}`);
2406 }),
2407 );
2408
2409 it.effect("falls back to built-in PowerShell by absolute path on Windows", () =>
2410 Effect.gen(function* () {
2411 const ptyAdapter = new FakePtyAdapter();
2412 const { manager } = yield* createManager(5, {
2413 ptyAdapter,
2414 env: {
2415 T3CODE_TERMINAL_SHELL: "C:\\missing\\custom-shell.exe",
2416 ComSpec: "C:\\Windows\\System32\\cmd.exe",
2417 PATH: "C:\\Windows\\System32",
2418 SystemRoot: "C:\\Windows",
2419 },
2420 }).pipe(Effect.provide(layerWithHostPlatform("win32")));
2421 ptyAdapter.spawnFailures.push(
2422 new Error("spawn custom-shell.exe ENOENT"),
2423 new Error("spawn pwsh.exe ENOENT"),
2424 );
2425
2426 yield* manager.open(openInput());
2427
2428 expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual([
2429 "C:\\missing\\custom-shell.exe",
2430 "pwsh.exe",
2431 "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
2432 ]);
2433 expect(ptyAdapter.spawnInputs[1]?.args).toEqual(POWERSHELL_ARGS);
2434 expect(ptyAdapter.spawnInputs[2]?.args).toEqual(POWERSHELL_ARGS);
2435 }),
2436 );
2437
2438 it.effect("closes an idle cmd fallback before rejecting its completion wrapper", () =>
2439 Effect.gen(function* () {
2440 const { manager, ptyAdapter, baseDir } = yield* createManager(5, {
2441 env: { SystemRoot: "C:\\Windows" },
2442 subprocessInspector: () =>
2443 Effect.succeed({
2444 hasRunningSubprocess: false,
2445 childCommand: null,
2446 processIds: [],
2447 }),
2448 }).pipe(Effect.provide(layerWithHostPlatform("win32")));
2449 ptyAdapter.spawnFailures.push(
2450 new Error("spawn pwsh ENOENT"),
2451 new Error("spawn WindowsPowerShell ENOENT"),
2452 new Error("spawn powershell ENOENT"),
2453 );
2454 const runner = yield* ProjectSetupScriptRunner.make.pipe(
2455 Effect.provide(
2456 Layer.mergeAll(
2457 Layer.succeed(TerminalManager.TerminalManager, manager),
2458 Layer.mock(ProjectService.ProjectService)({}),
2459 Layer.mock(ProjectionStore.ProjectionStoreV2)({
2460 getThreadShell: () => Effect.succeed(null),
2461 }),
2462 ServerSettings.layerTest(),
2463 ),
2464 ),
2465 );
2466 const error = yield* runner
2467 .runForThread({
2468 threadId: "thread-cmd-fallback",
2469 worktreePath: baseDir,
2470 project: {
2471 id: ProjectId.make("project-cmd-fallback"),
2472 workspaceRoot: baseDir,
2473 scripts: [
2474 {
2475 id: "setup",
2476 name: "Setup",
2477 command: "echo setup-ready",
2478 icon: "play",
2479 runOnWorktreeCreate: true,
2480 },
2481 ],
2482 },
2483 observeCompletion: {},
2484 })
2485 .pipe(Effect.flip);
2486
2487 expect(error._tag).toBe("ProjectSetupScriptUnsupportedShellError");
2488 expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("C:\\Windows\\System32\\cmd.exe");
2489 expect(ptyAdapter.processes[0]?.writes).toEqual([]);
2490 expect(ptyAdapter.processes[0]?.killed).toBe(true);
2491 }),
2492 );
2493
2494 it.effect("turns off fish terminal queries unless the user chose query-term", () =>
2495 Effect.gen(function* () {
2496 for (const [platform, env, runtimeEnv, expected] of [
2497 ["linux", {}, {}, { fish_features: "no-query-term" }],
2498 [
2499 "linux",
2500 { fish_features: "qmark-noglob" },
2501 {},
2502 { fish_features: "qmark-noglob,no-query-term" },
2503 ],
2504 [
2505 "linux",
2506 { fish_features: "qmark-noglob,query-term" },
2507 {},
2508 { fish_features: "qmark-noglob,query-term" },
2509 ],
2510 [
2511 "linux",
2512 { fish_features: "qmark-noglob,no-query-term" },
2513 {},
2514 { fish_features: "qmark-noglob,no-query-term" },
2515 ],
2516 [
2517 "linux",
2518 { fish_features: "query-term" },
2519 { fish_features: "qmark-noglob" },
2520 { fish_features: "qmark-noglob,no-query-term" },
2521 ],
2522 [
2523 "win32",
2524 { FISH_FEATURES: "qmark-noglob" },
2525 {},
2526 { FISH_FEATURES: "qmark-noglob,no-query-term" },
2527 ],
2528 [
2529 "win32",
2530 { Fish_Features: "qmark-noglob,query-term" },
2531 {},
2532 { Fish_Features: "qmark-noglob,query-term" },
2533 ],
2534 [
2535 "win32",
2536 { FISH_FEATURES: "qmark-noglob,no-query-term" },
2537 {},
2538 { FISH_FEATURES: "qmark-noglob,no-query-term" },
2539 ],
2540 [
2541 "win32",
2542 { Fish_Features: "query-term" },
2543 { fish_features: "qmark-noglob" },
2544 { Fish_Features: "qmark-noglob,no-query-term" },
2545 ],
2546 [
2547 "win32",
2548 { FISH_FEATURES: "no-query-term" },
2549 { fish_features: "qmark-noglob,query-term" },
2550 { FISH_FEATURES: "qmark-noglob,query-term" },
2551 ],
2552 ] as const) {
2553 const { manager, ptyAdapter } = yield* createManager(5, {
2554 env,
2555 }).pipe(Effect.provide(layerWithHostPlatform(platform)));
2556 yield* manager.open(openInput({ env: runtimeEnv }));
2557 const fishFeatures = Object.fromEntries(
2558 Object.entries(ptyAdapter.spawnInputs[0]!.env).filter(
2559 ([key]) => key.toLowerCase() === "fish_features",
2560 ),
2561 );
2562 expect.soft(fishFeatures, JSON.stringify({ platform, env, runtimeEnv })).toEqual(expected);
2563 }
2564 }),
2565 );
2566
2567 it.effect.each([
2568 {
2569 platform: "linux",
2570 parentEnv: { TERM_PROGRAM: "Apple_Terminal", TERM_PROGRAM_VERSION: "455" },
2571 runtimeEnv: { TERM_PROGRAM: "", TERM_PROGRAM_VERSION: "custom-version" },
2572 },
2573 {
2574 platform: "win32",
2575 parentEnv: { term_program: "Apple_Terminal", Term_Program_Version: "455" },
2576 runtimeEnv: { Term_Program: "", term_program_version: "custom-version" },
2577 },
2578 ] as const)(
2579 "identifies as T3 Code unless the terminal env overrides it on $platform",
2580 ({ platform, parentEnv, runtimeEnv }) =>
2581 Effect.gen(function* () {
2582 const originalEnv = { ...parentEnv };
2583 const env = Object.freeze(parentEnv);
2584 const { manager, ptyAdapter } = yield* createManager(5, { env }).pipe(
2585 Effect.provide(layerWithHostPlatform(platform)),
2586 );
2587
2588 yield* manager.open(openInput());
2589 yield* manager.open(openInput({ terminalId: "override", env: runtimeEnv }));
2590
2591 expect(ptyAdapter.spawnInputs).toHaveLength(2);
2592 for (const [index, expected] of [
2593 { TERM_PROGRAM: "t3code", TERM_PROGRAM_VERSION: packageJson.version },
2594 { TERM_PROGRAM: "", TERM_PROGRAM_VERSION: "custom-version" },
2595 ].entries()) {
2596 const spawnEnv = ptyAdapter.spawnInputs[index]!.env;
2597 for (const [key, value] of Object.entries(expected)) {
2598 expect
2599 .soft(
2600 Object.entries(spawnEnv)
2601 .filter(([candidate]) => candidate.toUpperCase() === key)
2602 .map(([, entryValue]) => entryValue),
2603 `${index === 0 ? "default" : "override"} ${key}`,
2604 )
2605 .toEqual([value]);
2606 }
2607 }
2608 expect(env).toEqual(originalEnv);
2609 }),
2610 );
2611
2612 it.effect("filters app runtime env variables from terminal sessions", () =>
2613 Effect.gen(function* () {
2614 const { manager, ptyAdapter } = yield* createManager(5, {
2615 env: {
2616 PORT: "5173",
2617 T3CODE_PORT: "3773",
2618 T3CODE_THREAD_ID: "server-thread",
2619 VITE_DEV_SERVER_URL: "http://localhost:5173",
2620 TEST_TERMINAL_KEEP: "keep-me",
2621 TMUX: "/tmp/tmux-1000/default,1234,0",
2622 TMUX_PANE: "%3",
2623 ZELLIJ_SESSION_NAME: "work",
2624 ZELLIJ_CONFIG_DIR: "/home/user/.config/zellij",
2625 },
2626 });
2627 yield* manager.open(openInput());
2628 yield* manager.open(
2629 openInput({
2630 terminalId: "explicit",
2631 env: { TMUX_PANE: "%9", T3CODE_THREAD_ID: "client-thread" },
2632 }),
2633 );
2634 const spawnInput = ptyAdapter.spawnInputs[0];
2635 expect(spawnInput).toBeDefined();
2636 if (!spawnInput) return;
2637
2638 expect(spawnInput.env.PORT).toBeUndefined();
2639 expect(spawnInput.env.T3CODE_PORT).toBeUndefined();
2640 expect(spawnInput.env.T3CODE_THREAD_ID).toBe("thread-1");
2641 expect(ptyAdapter.spawnInputs[1]?.env.T3CODE_THREAD_ID).toBe("thread-1");
2642 expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined();
2643 expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
2644 expect(spawnInput.env.TMUX).toBeUndefined();
2645 expect(spawnInput.env.TMUX_PANE).toBeUndefined();
2646 expect(spawnInput.env.ZELLIJ_SESSION_NAME).toBeUndefined();
2647 expect(spawnInput.env.ZELLIJ_CONFIG_DIR).toBe("/home/user/.config/zellij");
2648 expect(ptyAdapter.spawnInputs[1]?.env.TMUX_PANE).toBe("%9");
2649 }),
2650 );
2651
2652 it.effect("strips AppImage runtime env from terminal sessions", () =>
2653 Effect.gen(function* () {
2654 const appDir = "/tmp/.mount_T3Codeabc123";
2655 const { manager, ptyAdapter } = yield* createManager(5, {
2656 env: {
2657 APPIMAGE: "/home/user/T3-Code.AppImage",
2658 APPDIR: appDir,
2659 ARGV0: "/home/user/T3-Code.AppImage",
2660 OWD: "/home/user/project",
2661 PATH: `${appDir}/usr/bin:${appDir}:/usr/local/bin:/usr/bin:/bin`,
2662 LD_LIBRARY_PATH: `${appDir}/usr/lib:/home/user/.local/lib`,
2663 XDG_DATA_DIRS: `${appDir}/usr/share:/usr/local/share:/usr/share`,
2664 GSETTINGS_SCHEMA_DIR: `${appDir}/usr/share/glib-2.0/schemas`,
2665 TEST_TERMINAL_KEEP: "keep-me",
2666 },
2667 });
2668 yield* manager.open(openInput());
2669 const spawnInput = ptyAdapter.spawnInputs[0];
2670 expect(spawnInput).toBeDefined();
2671 if (!spawnInput) return;
2672
2673 expect(spawnInput.env.APPIMAGE).toBeUndefined();
2674 expect(spawnInput.env.APPDIR).toBeUndefined();
2675 expect(spawnInput.env.ARGV0).toBeUndefined();
2676 expect(spawnInput.env.OWD).toBeUndefined();
2677 expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
2678 expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
2679 expect(spawnInput.env.XDG_DATA_DIRS).toBe("/usr/local/share:/usr/share");
2680 expect(spawnInput.env.GSETTINGS_SCHEMA_DIR).toBeUndefined();
2681 expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
2682 }),
2683 );
2684
2685 it.effect("resolves a provider instance environment before spawning", () =>
2686 Effect.gen(function* () {
2687 const providerInstanceId = ProviderInstanceId.make("codex_work");
2688 const { manager, ptyAdapter } = yield* createManager(5, {
2689 env: { T3CODE_SECRET: "server-only" },
2690 resolveProviderInstanceEnvironment: (requestedId, env) =>
2691 Effect.succeed({
2692 ...env,
2693 PROVIDER_SECRET: requestedId === providerInstanceId ? "secret-value" : "wrong",
2694 CODEX_HOME: "/accounts/codex-work",
2695 }),
2696 });
2697
2698 const snapshot = yield* manager.open(
2699 openInput({ providerInstanceId, env: { CLIENT_FLAG: "1" } }),
2700 );
2701
2702 expect(ptyAdapter.spawnInputs[0]?.env.PROVIDER_SECRET).toBe("secret-value");
2703 expect(ptyAdapter.spawnInputs[0]?.env.CODEX_HOME).toBe("/accounts/codex-work");
2704 expect(ptyAdapter.spawnInputs[0]?.env.CLIENT_FLAG).toBe("1");
2705 expect(ptyAdapter.spawnInputs[0]?.env.T3CODE_SECRET).toBeUndefined();
2706 expect(snapshot).not.toHaveProperty("env");
2707 expect(snapshot).not.toHaveProperty("providerInstanceId");
2708 }),
2709 );
2710
2711 it.effect("expands a provider home named in any case on Windows", () =>
2712 Effect.gen(function* () {
2713 const path = yield* Path.Path;
2714 const home = yield* HostProcess.HomeDirectory;
2715 const { manager, ptyAdapter } = yield* createManager(5, {
2716 env: { GROK_HOME: "C:\\inherited-grok" },
2717 });
2718
2719 yield* manager.open(openInput({ env: { grok_home: "~/.grok-work" } }));
2720
2721 expect(ptyAdapter.spawnInputs[0]?.env.GROK_HOME).toBe(path.join(home, ".grok-work"));
2722 }).pipe(Effect.provide(layerWithHostPlatform("win32"))),
2723 );
2724
2725 it.effect("fails closed when a provider instance is missing", () =>
2726 Effect.gen(function* () {
2727 const providerInstanceId = ProviderInstanceId.make("deleted_instance");
2728 const { manager, ptyAdapter } = yield* createManager(5, {
2729 resolveProviderInstanceEnvironment: (requestedId) =>
2730 Effect.fail(
2731 new TerminalProviderInstanceNotFoundError({
2732 providerInstanceId: ProviderInstanceId.make(requestedId),
2733 }),
2734 ),
2735 });
2736
2737 const error = yield* manager.open(openInput({ providerInstanceId })).pipe(Effect.flip);
2738
2739 assert.deepStrictEqual(
2740 error,
2741 new TerminalProviderInstanceNotFoundError({ providerInstanceId }),
2742 );
2743 expect(ptyAdapter.spawnInputs).toHaveLength(0);
2744 }),
2745 );
2746
2747 it.effect.each([
2748 {
2749 name: "Codex home",
2750 driver: "codex",
2751 variable: "CODEX_HOME",
2752 config: { homePath: "/configured/codex" },
2753 expectedHome: "/configured/codex",
2754 },
2755 {
2756 name: "Codex shadow home",
2757 driver: "codex",
2758 variable: "CODEX_HOME",
2759 config: { homePath: "/configured/codex", shadowHomePath: "/configured/codex-shadow" },
2760 expectedHome: "/configured/codex-shadow",
2761 },
2762 {
2763 name: "Claude home",
2764 driver: "claudeAgent",
2765 variable: "CLAUDE_CONFIG_DIR",
2766 config: { homePath: "/configured/claude" },
2767 expectedHome: "/configured/claude",
2768 },
2769 ])("prefers $name over the instance environment", ({ driver, variable, config, expectedHome }) =>
2770 Effect.gen(function* () {
2771 const path = yield* Path.Path;
2772 const serverSettings = yield* ServerSettings.ServerSettingsService;
2773 const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
2774 deriveProviderInstanceConfigMap,
2775 serverSettings,
2776 path,
2777 rawProviderInstanceId: "configured_home",
2778 env: undefined,
2779 });
2780
2781 expect(environment[variable]).toBe(path.resolve(expectedHome));
2782 }).pipe(
2783 Effect.provide(
2784 ServerSettings.layerTest({
2785 providerInstances: {
2786 [ProviderInstanceId.make("configured_home")]: {
2787 driver: ProviderDriverKind.make(driver),
2788 environment: [{ name: variable, value: "~/.environment-account", sensitive: false }],
2789 config,
2790 },
2791 },
2792 }),
2793 ),
2794 ),
2795 );
2796
2797 it.effect("restarts a running terminal when the resolved provider environment changes", () =>
2798 Effect.gen(function* () {
2799 const providerInstanceId = ProviderInstanceId.make("codex_work");
2800 let providerSecret = "first-secret";
2801 const { manager, ptyAdapter } = yield* createManager(5, {
2802 resolveProviderInstanceEnvironment: () =>
2803 Effect.succeed({ PROVIDER_SECRET: providerSecret }),
2804 });
2805
2806 yield* manager.open(openInput({ providerInstanceId }));
2807 providerSecret = "second-secret";
2808 yield* manager.open(openInput({ providerInstanceId }));
2809
2810 expect(ptyAdapter.processes[0]?.killed).toBe(true);
2811 expect(ptyAdapter.spawnInputs).toHaveLength(2);
2812 expect(ptyAdapter.spawnInputs[1]?.env.PROVIDER_SECRET).toBe("second-secret");
2813 }),
2814 );
2815
2816 it.effect("force-kills a closed terminal that ignores SIGTERM when the manager shuts down", () =>
2817 Effect.gen(function* () {
2818 const scope = yield* Scope.make();
2819 const { manager, ptyAdapter } = yield* createManager(5, {
2820 processKillGraceMs: 1_000,
2821 }).pipe(Effect.provideService(Scope.Scope, scope));
2822 yield* manager.open(openInput());
2823 const process = ptyAdapter.processes[0]!;
2824 const sigterm = yield* Deferred.make<void>();
2825 process.onKill = (signal) => {
2826 if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void);
2827 };
2828 yield* manager.close({ threadId: "thread-1" });
2829 yield* Deferred.await(sigterm);
2830
2831 const shutdown = yield* Scope.close(scope, Exit.void).pipe(Effect.forkChild);
2832 yield* TestClock.adjust("1 second");
2833 yield* Fiber.join(shutdown);
2834
2835 const platform = yield* HostProcess.Platform;
2836 expect(process.killSignals).toEqual(
2837 platform === "win32" ? ["SIGTERM", "SIGKILL"] : ["SIGHUP", "SIGTERM", "SIGKILL"],
2838 );
2839 expect(process.exitListenerCount).toBe(0);
2840 }).pipe(Effect.provide(TestClock.layer())),
2841 );
2842
2843 it.effect("attaches to a running provider terminal without resolving the provider again", () =>
2844 Effect.gen(function* () {
2845 const providerInstanceId = ProviderInstanceId.make("codex_work");
2846 let providerAvailable = true;
2847 const { manager, ptyAdapter } = yield* createManager(5, {
2848 resolveProviderInstanceEnvironment: (requestedId) =>
2849 providerAvailable
2850 ? Effect.succeed({ PROVIDER_SECRET: "secret-value" })
2851 : Effect.fail(
2852 new TerminalProviderInstanceNotFoundError({
2853 providerInstanceId: ProviderInstanceId.make(requestedId),
2854 }),
2855 ),
2856 });
2857 yield* manager.open(openInput({ providerInstanceId }));
2858 providerAvailable = false;
2859 const events: TerminalAttachStreamEvent[] = [];
2860
2861 const unsubscribe = yield* manager.attachStream(
2862 { ...openInput({ providerInstanceId }), restartIfNotRunning: true },
2863 (event) => Effect.sync(() => events.push(event)),
2864 );
2865 unsubscribe();
2866
2867 expect(events[0]?.type).toBe("snapshot");
2868 expect(ptyAdapter.spawnInputs).toHaveLength(1);
2869 expect(ptyAdapter.processes[0]?.killed).toBe(false);
2870 }),
2871 );
2872
2873 it.effect("starts bash as a login shell on macOS and Windows", () =>
2874 Effect.gen(function* () {
2875 for (const [platform, shell, args] of [
2876 ["darwin", "/bin/bash", ["-l"]],
2877 ["darwin", "/opt/homebrew/bin/bash", ["-l"]],
2878 ["linux", "/bin/bash", undefined],
2879 ["win32", "C:\\Program Files\\Git\\bin\\bash.exe", ["--login", "-i"]],
2880 ["darwin", "/bin/zsh", ["-o", "nopromptsp"]],
2881 ["linux", "/bin/zsh", ["-o", "nopromptsp"]],
2882 ["win32", "pwsh.exe", POWERSHELL_ARGS],
2883 ] as const) {
2884 const { manager, ptyAdapter } = yield* createManager(5, {
2885 shellResolver: () => shell,
2886 }).pipe(Effect.provide(layerWithHostPlatform(platform)));
2887 yield* manager.open(openInput());
2888 expect.soft(ptyAdapter.spawnInputs[0]?.args, `${platform} ${shell}`).toEqual(args);
2889 }
2890 }),
2891 );
2892 it.effect("removes terminal metadata subscriptions when initial delivery fails", () =>
2893 Effect.gen(function* () {
2894 const { manager } = yield* createManager();
2895 yield* manager.open(openInput({ threadId: "existing-thread" }));
2896
2897 const leakedLiveEvents = yield* Ref.make(0);
2898 const exit = yield* Effect.exit(
2899 manager.subscribeMetadata((event) =>
2900 event.type === "snapshot"
2901 ? Effect.die("snapshot listener failed")
2902 : Ref.update(leakedLiveEvents, (count) => count + 1),
2903 ),
2904 );
2905
2906 expect(Exit.isFailure(exit)).toBe(true);
2907
2908 yield* manager.open(openInput({ threadId: "new-thread" }));
2909 expect(yield* Ref.get(leakedLiveEvents)).toBe(0);
2910 }),
2911 );
2912
2913 it.effect("finishes shell startup when its creating attachment is cancelled", () =>
2914 Effect.gen(function* () {
2915 const ptyAdapter = new GatedPtyAdapter();
2916 const { manager } = yield* createManager(5, { ptyAdapter });
2917 const input = openInput();
2918 const gate = {
2919 spawning: yield* Deferred.make<void>(),
2920 release: yield* Deferred.make<void>(),
2921 };
2922 ptyAdapter.gate = gate;
2923 const consumer = yield* Stream.runDrain(
2924 terminalOutputStream(
2925 (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup),
2926 (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup),
2927 ),
2928 ).pipe(Effect.forkChild({ startImmediately: true }));
2929 yield* Deferred.await(gate.spawning);
2930 const cancelled = yield* Fiber.interrupt(consumer).pipe(
2931 Effect.forkChild({ startImmediately: true }),
2932 );
2933 yield* Deferred.succeed(gate.release, undefined);
2934 yield* Fiber.join(cancelled);
2935
2936 const snapshots: TerminalAttachStreamEvent[] = [];
2937 const stop = yield* manager.attachStream(input, (event) =>
2938 Effect.sync(() => {
2939 snapshots.push(event);
2940 }),
2941 );
2942 stop();
2943 expect(snapshots).toMatchObject([
2944 { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } },
2945 ]);
2946 expect(ptyAdapter.processes).toHaveLength(1);
2947 }),
2948 );
2949
2950 it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () =>
2951 Effect.gen(function* () {
2952 const ptyAdapter = new GatedPtyAdapter();
2953 const historyByteLimit = 64 * 1024;
2954 const { manager } = yield* createManager(5, { ptyAdapter, historyByteLimit });
2955 const input = openInput();
2956 const pull = yield* Stream.toPull(
2957 terminalOutputStream(
2958 (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup),
2959 (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup),
2960 ),
2961 );
2962 expect(yield* pull).toMatchObject([{ type: "snapshot", snapshot: { history: "" } }]);
2963 const process = ptyAdapter.processes[0]!;
2964 yield* publishPastOutputBudget(manager, process);
2965
2966 const resumed = yield* pull;
2967 expect(resumed).toHaveLength(1);
2968 expect(resumed[0]?.type).toBe("snapshot");
2969 if (resumed[0]?.type !== "snapshot") throw new Error("Expected a recovery snapshot");
2970 expect(Buffer.byteLength(resumed[0].snapshot.history)).toBeLessThanOrEqual(historyByteLimit);
2971 expect(resumed[0].snapshot.history.endsWith("last\n")).toBe(true);
2972 process.emitData("after recovery\n");
2973 expect(yield* pull).toMatchObject([{ type: "output", data: "after recovery\n" }]);
2974 expect(ptyAdapter.spawnInputs).toHaveLength(1);
2975
2976 yield* publishPastOutputBudget(manager, process);
2977 yield* manager.close(input);
2978 expect(yield* pull).toEqual([
2979 { type: "closed", threadId: input.threadId, terminalId: input.terminalId },
2980 ]);
2981 expect(ptyAdapter.spawnInputs).toHaveLength(1);
2982 yield* manager.open(input);
2983 expect(yield* pull).toMatchObject([
2984 { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[1]!.pid } },
2985 ]);
2986 const reopenedProcess = ptyAdapter.processes[1]!;
2987 reopenedProcess.emitData("after reopen\n");
2988 expect(yield* pull).toMatchObject([{ type: "output", data: "after reopen\n" }]);
2989
2990 yield* publishPastOutputBudget(manager, reopenedProcess);
2991 // Queue close/reopen ahead of recovery while another spawn owns the thread lock.
2992 const gate = {
2993 spawning: yield* Deferred.make<void>(),
2994 release: yield* Deferred.make<void>(),
2995 };
2996 ptyAdapter.gate = gate;
2997 const holder = yield* manager
2998 .open(openInput({ terminalId: "other" }))
2999 .pipe(Effect.forkChild({ startImmediately: true }));
3000 yield* Deferred.await(gate.spawning);
3001 const closed = yield* manager.close(input).pipe(Effect.forkChild({ startImmediately: true }));
3002 const reopened = yield* manager
3003 .open(input)
3004 .pipe(Effect.forkChild({ startImmediately: true }));
3005 const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true }));
3006 reopenedProcess.emitData("old session\n");
3007 yield* Deferred.succeed(gate.release, undefined);
3008 yield* Fiber.join(holder);
3009 yield* Fiber.join(closed);
3010 yield* Fiber.join(reopened);
3011
3012 const batch = yield* Fiber.join(recovery);
3013 expect(batch).toHaveLength(1);
3014 expect(batch[0]).toMatchObject({
3015 type: "snapshot",
3016 snapshot: { status: "running", pid: ptyAdapter.processes.at(-1)!.pid },
3017 });
3018 ptyAdapter.processes.at(-1)!.emitData("new session only\n");
3019 expect(yield* pull).toMatchObject([{ type: "output", data: "new session only\n" }]);
3020 expect(ptyAdapter.spawnInputs).toHaveLength(4);
3021 }),
3022 );
3023
3024 it.effect.each([
3025 { recovered: true, label: "after recovery" },
3026 { recovered: false, label: "when cancelled before recovery" },
3027 ])("keeps a stalled viewer's size until its attach stream ends ($label)", ({ recovered }) =>
3028 Effect.gen(function* () {
3029 const { manager, ptyAdapter } = yield* createManager();
3030 const restored = yield* Deferred.make<void>();
3031 const stopWide = yield* manager.attachStream(
3032 openInput({ cols: 130, rows: 15 }),
3033 (event) =>
3034 event.type === "activity" && event.cols === 130 && event.rows === 15
3035 ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid)
3036 : Effect.void,
3037 undefined,
3038 "wide",
3039 );
3040 yield* Effect.addFinalizer(() => Effect.sync(stopWide));
3041 const process = ptyAdapter.processes[0]!;
3042
3043 yield* Effect.gen(function* () {
3044 const pull = yield* Stream.toPull(
3045 manager.attachOutputStream(openInput({ cols: 54, rows: 15 }), "narrow"),
3046 );
3047 expect(yield* pull).toMatchObject([{ type: "snapshot" }]);
3048 expect(process.resizeCalls.at(-1)).toEqual({ cols: 54, rows: 15 });
3049 // Overflow releases the inner subscription before any recovery pull.
3050 yield* publishPastOutputBudget(manager, process);
3051 yield* manager.resize(
3052 { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 50, rows: 12 },
3053 "narrow",
3054 );
3055 expect(process.resizeCalls.at(-1)).toEqual({ cols: 50, rows: 12 });
3056 if (!recovered) return;
3057
3058 expect(yield* pull).toMatchObject([{ type: "snapshot" }]);
3059 yield* manager.resize(
3060 { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 48, rows: 12 },
3061 "narrow",
3062 );
3063 expect(process.resizeCalls.at(-1)).toEqual({ cols: 48, rows: 12 });
3064 }).pipe(Effect.scoped);
3065
3066 yield* Deferred.await(restored);
3067 expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
3068 }),
3069 );
3070
3071 it.effect("sends bounded attach streams only the history the client retains", () =>
3072 Effect.gen(function* () {
3073 const { manager, ptyAdapter } = yield* createManager();
3074 const maxHistoryBytes = 9;
3075 yield* manager.open(openInput());
3076 const process = ptyAdapter.processes[0]!;
3077 const published = yield* Deferred.make<void>();
3078 const unsubscribe = yield* manager.subscribe((event) =>
3079 event.type === "output" && event.data === "yz\n"
3080 ? Deferred.succeed(published, undefined).pipe(Effect.asVoid)
3081 : Effect.void,
3082 );
3083 process.emitData("aaaa\nx名😀");
3084 process.emitData("yz\n");
3085 yield* Deferred.await(published);
3086 unsubscribe();
3087
3088 const full = yield* Stream.toPull(manager.attachOutputStream(openInput(), "full"));
3089 const bounded = yield* Stream.toPull(
3090 manager.attachOutputStream({ ...openInput(), maxHistoryBytes }, "bounded"),
3091 );
3092 const expectRetained = Effect.fnUntraced(function* () {
3093 const [fullEvents, boundedEvents] = [yield* full, yield* bounded];
3094 const fullSnapshot = fullEvents.at(-1);
3095 if (fullSnapshot?.type !== "snapshot") throw new Error("Expected a full snapshot");
3096 expect(boundedEvents.at(-1)).toEqual({
3097 ...fullSnapshot,
3098 snapshot: {
3099 ...fullSnapshot.snapshot,
3100 history: retainedTerminalHistory(fullSnapshot.snapshot.history, maxHistoryBytes),
3101 },
3102 });
3103 return fullSnapshot.snapshot.history;
3104 });
3105
3106 expect(yield* expectRetained()).toBe("aaaa\nx名😀yz\n");
3107 // The cap starts inside 名, so the tail begins at the next code point.
3108 expect(retainedTerminalHistory("aaaa\nx名😀yz\n", maxHistoryBytes)).toBe("😀yz\n");
3109 process.emitData("after\n");
3110 expect(yield* full).toEqual(yield* bounded);
3111
3112 yield* publishPastOutputBudget(manager, process);
3113 expect(yield* expectRetained()).toMatch(/last\n$/);
3114
3115 process.emitExit({ exitCode: 0, signal: 0 });
3116 expect(yield* full).toEqual(yield* bounded);
3117 yield* manager.attachStream({ ...openInput(), restartIfNotRunning: true }, () => Effect.void);
3118 yield* expectRetained();
3119 }),
3120 );
3121
3122 it.effect("does not replay in-flight output already included in an observer snapshot", () =>
3123 Effect.gen(function* () {
3124 const { manager, ptyAdapter } = yield* createManager();
3125 const input = openInput();
3126 yield* manager.open(input);
3127 const reached = yield* Deferred.make<void>();
3128 const release = yield* Deferred.make<void>();
3129 const delivered = yield* Deferred.make<void>();
3130 // The snapshot sees history before this earlier fanout listener releases it.
3131 const unsubscribe = yield* manager.subscribe((event) =>
3132 event.type === "output" && event.data === "in flight\n"
3133 ? Deferred.succeed(reached, undefined).pipe(Effect.andThen(Deferred.await(release)))
3134 : Effect.void,
3135 );
3136 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
3137 ptyAdapter.processes[0]!.emitData("in flight\n");
3138 yield* Deferred.await(reached);
3139 const observed: TerminalAttachStreamEvent[] = [];
3140 const stopObserving = yield* manager.observeStream(input, (event) =>
3141 Effect.gen(function* () {
3142 observed.push(event);
3143 if (event.type === "output" && event.data === "after\n") {
3144 yield* Deferred.succeed(delivered, undefined);
3145 }
3146 }),
3147 );
3148 yield* Effect.addFinalizer(() => Effect.sync(stopObserving));
3149 expect(observed).toMatchObject([{ type: "snapshot", snapshot: { history: "in flight\n" } }]);
3150 yield* Deferred.succeed(release, undefined);
3151 ptyAdapter.processes[0]!.emitData("after\n");
3152 yield* Deferred.await(delivered);
3153 expect(observed.filter((event) => event.type === "output")).toMatchObject([
3154 { data: "after\n" },
3155 ]);
3156 }),
3157 );
3158
3159 it.effect("observes terminal history and live output without changing the process", () =>
3160 Effect.gen(function* () {
3161 const { manager, ptyAdapter } = yield* createManager();
3162 const opened = yield* manager.open(openInput({ env: { OBSERVER_TEST: "original" } }));
3163 const process = ptyAdapter.processes[0]!;
3164 const historyReceived = yield* Deferred.make<void>();
3165 const unsubscribeHistory = yield* manager.subscribe((event) =>
3166 event.type === "output"
3167 ? Deferred.succeed(historyReceived, undefined).pipe(Effect.asVoid)
3168 : Effect.void,
3169 );
3170 process.emitData("existing history\n");
3171 yield* Deferred.await(historyReceived);
3172 unsubscribeHistory();
3173
3174 const observed = yield* Ref.make<ReadonlyArray<TerminalAttachStreamEvent>>([]);
3175 const liveReceived = yield* Deferred.make<void>();
3176 const unsubscribe = yield* manager.observeStream(
3177 { threadId: opened.threadId, terminalId: opened.terminalId },
3178 (event) =>
3179 Ref.update(observed, (events) => [...events, event]).pipe(
3180 Effect.andThen(
3181 event.type === "output"
3182 ? Deferred.succeed(liveReceived, undefined).pipe(Effect.asVoid)
3183 : Effect.void,
3184 ),
3185 ),
3186 );
3187 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
3188 process.emitData("live output\n");
3189 yield* Deferred.await(liveReceived);
3190
3191 expect(yield* Ref.get(observed)).toMatchObject([
3192 {
3193 type: "snapshot",
3194 snapshot: {
3195 cwd: opened.cwd,
3196 worktreePath: opened.worktreePath,
3197 pid: opened.pid,
3198 history: "existing history\n",
3199 },
3200 },
3201 { type: "output", data: "live output\n" },
3202 ]);
3203 expect(ptyAdapter.spawnInputs).toHaveLength(1);
3204 expect(ptyAdapter.spawnInputs[0]?.env.OBSERVER_TEST).toBe("original");
3205 expect(process.resizeCalls).toEqual([]);
3206 expect(process.writes).toEqual([]);
3207 expect(process.killSignals).toEqual([]);
3208 }),
3209 );
3210
3211 it.effect("observes exited terminals without restarting and rejects missing sessions", () =>
3212 Effect.gen(function* () {
3213 const { manager, ptyAdapter } = yield* createManager();
3214 const missingEvents: TerminalAttachStreamEvent[] = [];
3215 const missing = yield* manager
3216 .observeStream({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }, (event) =>
3217 Effect.sync(() => {
3218 missingEvents.push(event);
3219 }),
3220 )
3221 .pipe(Effect.flip);
3222 expect(missing._tag).toBe("TerminalSessionLookupError");
3223 expect(ptyAdapter.spawnInputs).toEqual([]);
3224
3225 yield* manager.open(openInput());
3226 const process = ptyAdapter.processes[0]!;
3227 const exited = yield* Deferred.make<void>();
3228 const unsubscribeExit = yield* manager.subscribe((event) =>
3229 event.type === "exited"
3230 ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid)
3231 : Effect.void,
3232 );
3233 process.emitExit({ exitCode: 7, signal: 0 });
3234 yield* Deferred.await(exited);
3235 unsubscribeExit();
3236
3237 const events: TerminalAttachStreamEvent[] = [];
3238 const unsubscribe = yield* manager.observeStream(
3239 { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID },
3240 (event) =>
3241 Effect.sync(() => {
3242 events.push(event);
3243 }),
3244 );
3245 unsubscribe();
3246 expect(events).toMatchObject([
3247 { type: "snapshot", snapshot: { status: "exited", exitCode: 7, pid: null } },
3248 ]);
3249 expect(ptyAdapter.spawnInputs).toHaveLength(1);
3250 expect(process.resizeCalls).toEqual([]);
3251 expect(process.writes).toEqual([]);
3252 expect(process.killSignals).toEqual([]);
3253 expect(missingEvents).toEqual([]);
3254 }),
3255 );
3256 });