Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadTerminalDrawer.browser.test.tsx

687 lines25.6 KB

1import {
2 applyTerminalAttachStreamEvent,
3 EMPTY_TERMINAL_SESSION_STATE,
4} from "@t3tools/client-runtime/state/terminal";
5import {
6 EnvironmentId,
7 ThreadId,
8 TerminalProcessChangedError,
9 type ScopedThreadRef,
10 type FilesystemEntryMetadata,
11 type ResolvedKeybindingsConfig,
12 type TerminalSummary,
13} from "@t3tools/contracts";
14import { Cause } from "effect";
15import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";
16import { Atom, AsyncResult } from "effect/reactivity";
17import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
18import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry";
19import { useRightPanelStore } from "../rightPanelStore";
20import { useTerminalUiStateStore } from "../terminalUiStateStore";
21import { extractTerminalLinks } from "../terminal-links";
22import { expect, it, vi } from "vite-plus/test";
23import { act, fakeTimers, render } from "../../test/render";
24import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
25​
26const fixture = vi.hoisted(() => ({
27 statusByThreadId: new Map<string, "starting" | "running" | "exited">(),
28 supportsConditionalWrites: true,
29 pendingSurfaces: [] as Array<() => void>,
30 typeIntoSurface: null as ((data: string) => void) | null,
31 pressKey: null as ((event: KeyboardEvent) => boolean) | null,
32 writes: [] as Array<{ threadId: string; data: string; expectedPid?: number }>,
33 messages: [] as string[],
34 resetSessions: () => {},
35 terminalMetadata: (
36 _environmentId: EnvironmentId,
37 ): Atom.Atom<AsyncResult.AsyncResult<ReadonlyArray<TerminalSummary>>> =>
38 Atom.make(AsyncResult.success([])),
39 setMetadataPid: (_thread: ScopedThreadRef, _pid: number) => {},
40 setSession: (
41 _thread: ScopedThreadRef,
42 _status: "closed" | "starting" | "running",
43 _version: number,
44 _generation?: number,
45 ) => {},
46 sessionEvent: (
47 _thread: ScopedThreadRef,
48 _type: "snapshot" | "restarted" | "closed",
49 _pid = 123,
50 ) => {},
51 surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
52 reportedSize: null as { cols: number; rows: number } | null,
53 resizeCommand: {},
54 runWrite: (): Promise<{ _tag: "Success" } | AsyncResult.Failure<void, unknown>> =>
55 Promise.resolve({ _tag: "Success" }),
56 runResize: (_input: unknown): Promise<AsyncResult.AsyncResult<unknown, unknown>> =>
57 Promise.resolve(AsyncResult.success(undefined)),
58 metadata: new Map<
59 string,
60 Atom.Writable<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>
61 >(),
62}));
63​
64// Every other surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
65const fakeSurface: object = new Proxy(
66 {
67 input: document.createElement("textarea"),
68 write: (data: string) => fixture.messages.push(data),
69 // The real surface re-reports its measured grid.
70 resendSize: () => {
71 const size = fixture.reportedSize;
72 if (size) fixture.surfaceOptions.at(-1)!.onResize(size.cols, size.rows);
73 },
74 },
75 {
76 get: (target, key) =>
77 key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined,
78 },
79);
80vi.mock("~/terminal/ghostty/surface", () => ({
81 GhosttyTerminalSurface: {
82 create: (_mount: HTMLElement, options: GhosttyTerminalSurfaceOptions) =>
83 new Promise((resolve) => {
84 fixture.surfaceOptions.push(options);
85 fixture.pendingSurfaces.push(() => {
86 fixture.typeIntoSurface = options.onData;
87 fixture.pressKey = options.beforeKey ?? null;
88 resolve(fakeSurface);
89 });
90 }),
91 },
92}));
93vi.mock("../state/terminalSessions", async () => {
94 const Atom = await import("effect/reactivity/Atom");
95 // A strong map, not Atom.family: a family holds weakly, so a GC could hand setSession a new atom.
96 const summary = (threadId: ThreadId, pid: number) => ({
97 threadId,
98 terminalId: "term-1",
99 cwd: "/repo",
100 worktreePath: null,
101 status: "running" as const,
102 pid,
103 exitCode: null,
104 exitSignal: null,
105 hasRunningSubprocess: false,
106 label: "Terminal 1",
107 updatedAt: "2026-11-15T00:00:00.000Z",
108 });
109 const makeSession = (threadId: ThreadId) =>
110 Atom.make<typeof EMPTY_TERMINAL_SESSION_STATE>({
111 ...EMPTY_TERMINAL_SESSION_STATE,
112 summary: summary(threadId, 123),
113 pid: 123,
114 supportsConditionalWrites: fixture.supportsConditionalWrites,
115 status: fixture.statusByThreadId.get(threadId) ?? "closed",
116 version: 1,
117 });
118 let sessions = new Map<string, ReturnType<typeof makeSession>>();
119 const session = (environmentId: EnvironmentId, threadId: ThreadId) => {
120 const key = JSON.stringify([environmentId, threadId]);
121 const atom = sessions.get(key) ?? makeSession(threadId);
122 sessions.set(key, atom);
123 return atom;
124 };
125 fixture.resetSessions = () => {
126 sessions = new Map();
127 };
128 const metadata = Atom.family((_environmentId: EnvironmentId) =>
129 Atom.make<AsyncResult.AsyncResult<ReadonlyArray<TerminalSummary>>>(
130 AsyncResult.waiting(AsyncResult.success([])),
131 ).pipe(Atom.keepAlive),
132 );
133 fixture.terminalMetadata = metadata;
134 fixture.setMetadataPid = (thread, pid) =>
135 appAtomRegistry.set(
136 metadata(thread.environmentId),
137 AsyncResult.waiting(AsyncResult.success([summary(thread.threadId, pid)])),
138 );
139 fixture.setSession = (thread, status, version, generation) => {
140 appAtomRegistry.set(session(thread.environmentId, thread.threadId), {
141 ...EMPTY_TERMINAL_SESSION_STATE,
142 status,
143 version,
144 ...(generation === undefined
145 ? {}
146 : { output: { ...EMPTY_TERMINAL_SESSION_STATE.output, generation } }),
147 });
148 };
149 fixture.sessionEvent = (thread, type, pid = 123) => {
150 const atom = session(thread.environmentId, thread.threadId);
151 const current = appAtomRegistry.get(atom);
152 appAtomRegistry.set(atom, {
153 ...current,
154 ...applyTerminalAttachStreamEvent(current, {
155 threadId: thread.threadId,
156 terminalId: "term-1",
157 ...(type === "closed"
158 ? { type }
159 : {
160 type,
161 snapshot: {
162 threadId: thread.threadId,
163 terminalId: "term-1",
164 cwd: "/repo",
165 worktreePath: null,
166 status: "running",
167 pid,
168 supportsConditionalWrites: fixture.supportsConditionalWrites,
169 history: "",
170 exitCode: null,
171 exitSignal: null,
172 label: "Terminal 1",
173 updatedAt: "2026-11-15T00:00:00.000Z",
174 },
175 }),
176 }),
177 });
178 };
179 return {
180 attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) =>
181 session(environmentId, terminal.threadId),
182 };
183});
184vi.mock("../state/session", () => ({
185 useEnvironmentScope: () => true,
186 readEnvironmentScope: () => true,
187}));
188vi.mock("../state/use-atom-command", () => ({
189 useAtomCommand:
190 (command: object) =>
191 async (args: { input: { threadId: string; data?: string; expectedPid?: number } }) => {
192 if (command === fixture.resizeCommand) return fixture.runResize(args);
193 if (args.input.data !== undefined) {
194 const { threadId, data, expectedPid } = args.input;
195 fixture.writes.push({
196 threadId,
197 data,
198 ...(expectedPid === undefined ? {} : { expectedPid }),
199 });
200 return fixture.runWrite();
201 }
202 return { _tag: "Success" };
203 },
204}));
205// The commands are replaced above; importing their runtime would connect a client.
206vi.mock("../state/server", async () => {
207 const Atom = await import("effect/reactivity/Atom");
208 const config = Atom.make(null);
209 return { serverEnvironment: { configValueAtom: () => config } };
210});
211vi.mock("../state/terminal", () => ({
212 terminalEnvironment: {
213 write: {},
214 resize: fixture.resizeCommand,
215 metadata: ({ environmentId }: { environmentId: EnvironmentId }) =>
216 fixture.terminalMetadata(environmentId),
217 },
218}));
219vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
220vi.mock("../state/projects", async () => {
221 const { Atom, AsyncResult } = await import("effect/reactivity");
222 return {
223 projectEnvironment: {
224 fileMetadata: ({
225 environmentId,
226 input,
227 }: {
228 environmentId: string;
229 input: { path: string };
230 }) => {
231 const key = JSON.stringify([environmentId, input.path]);
232 let atom = fixture.metadata.get(key);
233 if (!atom) {
234 atom = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
235 AsyncResult.success(null),
236 );
237 fixture.metadata.set(key, atom);
238 }
239 return atom;
240 },
241 },
242 };
243});
244vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
245vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
246vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
247vi.mock("../hooks/useSettings", async () => {
248 const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings");
249 return {
250 useClientSettings: <T,>(select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) =>
251 select(DEFAULT_CLIENT_SETTINGS),
252 ensureClientSettingsHydrated: async () => {},
253 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
254 };
255});
256​
257function Drawer(props: {
258 threadRef: ScopedThreadRef;
259 cwd?: string;
260 onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
261 keybindings?: ResolvedKeybindingsConfig;
262}) {
263 return (
264 <ThreadTerminalDrawer
265 threadRef={props.threadRef}
266 threadId={props.threadRef.threadId}
267 cwd={props.cwd ?? "/repo"}
268 height={240}
269 terminalIds={["term-1"]}
270 activeTerminalId="term-1"
271 terminalGroups={[{ id: "group-1", terminalIds: ["term-1"] }]}
272 activeTerminalGroupId="group-1"
273 onSplitTerminal={() => {}}
274 onSplitTerminalVertical={() => {}}
275 onNewTerminal={() => {}}
276 onActiveTerminalChange={() => {}}
277 onCloseTerminal={props.onCloseTerminal}
278 onHeightChange={() => {}}
279 onAddTerminalContext={() => {}}
280 keybindings={props.keybindings ?? []}
281 />
282 );
284​
285function setup(originalStatus: "starting" | "exited" = "exited") {
286 fixture.resetSessions();
287 const original: ScopedThreadRef = {
288 environmentId: EnvironmentId.make(`environment-a-${expect.getState().currentTestName}`),
289 threadId: ThreadId.make("thread-a"),
290 };
291 const other: ScopedThreadRef = {
292 environmentId: EnvironmentId.make(`environment-b-${expect.getState().currentTestName}`),
293 threadId: ThreadId.make("thread-b"),
294 };
295 fixture.statusByThreadId = new Map([
296 [original.threadId, originalStatus],
297 [other.threadId, "running"],
298 ]);
299 fixture.pendingSurfaces = [];
300 fixture.typeIntoSurface = null;
301 fixture.pressKey = null;
302 fixture.writes = [];
303 fixture.messages = [];
304 fixture.surfaceOptions = [];
305 fixture.reportedSize = null;
306 fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined));
307 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
308 fixture.supportsConditionalWrites = true;
309 fixture.metadata.clear();
310 useRightPanelStore.setState(useRightPanelStore.getInitialState());
311 useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState());
312 return { original, other };
314​
315it("drops input until the shell runs instead of failing a write for every key", async () => {
316 const { original } = setup("starting");
317 fixture.setSession(original, "closed", 0);
318 await using _screen = await render(<Drawer threadRef={original} onCloseTerminal={() => {}} />);
319 await act(async () => {
320 fixture.pendingSurfaces.shift()?.();
321 });
322 const clearShortcut = () => new KeyboardEvent("keydown", { key: "l", ctrlKey: true });
323 fixture.typeIntoSurface?.("before attach");
324 fixture.pressKey?.(clearShortcut());
325 await act(() => fixture.setSession(original, "running", 0));
326 fixture.typeIntoSurface?.("stale metadata");
327 fixture.pressKey?.(clearShortcut());
328 await act(() => fixture.setSession(original, "starting", 1));
329 fixture.typeIntoSurface?.("early");
330 fixture.pressKey?.(clearShortcut());
331 expect(fixture.writes).toEqual([]);
332 await act(() => fixture.setSession(original, "running", 1));
333 fixture.typeIntoSurface?.("ready");
334 fixture.pressKey?.(clearShortcut());
335 expect(fixture.writes).toEqual([
336 { threadId: original.threadId, data: "ready" },
337 { threadId: original.threadId, data: "\u000c" },
338 ]);
339});
340​
341it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => {
342 const { original, other } = setup();
343 const onCloseTerminal = vi.fn();
344 await using screen = await render(
345 <Drawer threadRef={original} onCloseTerminal={onCloseTerminal} />,
346 );
347 using _timers = fakeTimers();
348 // The exit is seen once the surface loads, and its close waits for the next task.
349 await act(async () => {
350 fixture.pendingSurfaces.shift()?.();
351 });
352 await screen.rerender(<Drawer threadRef={other} onCloseTerminal={onCloseTerminal} />);
353 await act(async () => {
354 vi.runOnlyPendingTimers();
355 });
356 expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
357});
358​
359// Thread navigation defaults have no `!terminalFocus`, so they apply in a focused terminal.
360it("hands thread navigation shortcuts from a focused terminal back to the app", async () => {
361 const { other: threadRef } = setup();
362 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
363 useRightPanelStore.getState().openBrowser(threadRef, null);
364 await using _screen = await render(
365 <Drawer
366 threadRef={threadRef}
367 onCloseTerminal={() => {}}
368 keybindings={compileResolvedKeybindingsConfig([
369 ...DEFAULT_KEYBINDINGS,
370 { key: "ctrl+r", command: "thread.next", when: "!previewOpen" },
371 { key: "ctrl+g", command: "thread.previous", when: "terminalOpen" },
372 ])}
373 />,
374 );
375 await act(async () => {
376 fixture.pendingSurfaces.shift()?.();
377 });
378 const terminalHandles = (key: string, code: string, shiftKey = true) =>
379 fixture.surfaceOptions
380 .at(-1)!
381 .beforeKey(new KeyboardEvent("keydown", { key, code, ctrlKey: true, shiftKey }));
382​
383 expect([terminalHandles("{", "BracketLeft"), terminalHandles("}", "BracketRight")]).toEqual([
384 false,
385 false,
386 ]);
387 expect(terminalHandles("C", "KeyC")).toBe(true);
388 // Sidebar sees the open preview and the closed drawer and rejects these, so the shell keeps them.
389 expect([terminalHandles("r", "KeyR", false), terminalHandles("g", "KeyG", false)]).toEqual([
390 true,
391 true,
392 ]);
393});
394​
395it("only activates terminal paths confirmed to exist on their environment", async () => {
396 const { other: threadRef } = setup();
397 const key = (path: string) => JSON.stringify([threadRef.environmentId, path]);
398 const pending = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
399 AsyncResult.initial(),
400 );
401 fixture.metadata.set(key("/repo/src/main.ts"), pending);
402 fixture.metadata.set(
403 key("/repo/src/…notes.ts"),
404 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
405 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
406 ),
407 );
408 fixture.metadata.set(
409 key("/repo/src"),
410 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
411 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "directory" }),
412 ),
413 );
414 await using screen = await render(
415 <AppAtomRegistryProvider>
416 <Drawer threadRef={threadRef} onCloseTerminal={() => {}} />
417 </AppAtomRegistryProvider>,
418 );
419 await act(async () => {
420 fixture.pendingSurfaces.shift()?.();
421 });
422 const canActivate = (text: string) => fixture.surfaceOptions.at(-1)!.canActivateLink!(text);
423 const validate = (text: string) => fixture.surfaceOptions.at(-1)!.validateLink!(text);
424 const hover = (text: string | null, fallback?: string) =>
425 act(() => fixture.surfaceOptions.at(-1)!.onLinkHover!(text, fallback));
426​
427 expect(canActivate("https://example.com")).toBe(true);
428 for (const branch of ["t3/fix-html-image-details", "t3/fix-html-…mage-details"]) {
429 const candidates = extractTerminalLinks(branch);
430 expect(candidates.length).toBeGreaterThan(0);
431 for (const candidate of candidates) {
432 expect(canActivate(candidate.text)).toBe(false);
433 await hover(candidate.text);
434 expect(canActivate(candidate.text)).toBe(false);
435 expect(await validate(candidate.text)).toBe(false);
436 }
437 }
438 const pressedValidation = validate("src/main.ts:12:7");
439 await hover("src/main.ts:12:7");
440 expect(canActivate("src/main.ts:12:7")).toBe(false);
441 await act(async () => {
442 appAtomRegistry.set(pending, AsyncResult.success({ kind: "file" }));
443 });
444 expect(canActivate("src/main.ts:12:7")).toBe(true);
445 expect(await pressedValidation).toBe(true);
446 expect(canActivate("missing/file.ts")).toBe(false);
447 await hover("missing/file.ts");
448 expect(canActivate("missing/file.ts")).toBe(false);
449 for (const path of ["/repo/src/…notes.ts", "/repo/src"]) {
450 await hover(path);
451 expect(canActivate(path)).toBe(true);
452 }
453 const grepHit = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
454 AsyncResult.initial(),
455 );
456 fixture.metadata.set(key("/repo/src/a.js:1:function"), grepHit);
457 fixture.metadata.set(
458 key("/repo/src/a.js"),
459 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
460 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
461 ),
462 );
463 await hover("./src/a.js:1:function", "./src/a.js:1");
464 expect(canActivate("./src/a.js:1")).toBe(false);
465 await act(async () => {
466 appAtomRegistry.set(grepHit, AsyncResult.success(null));
467 });
468 expect(canActivate("./src/a.js:1:function")).toBe(false);
469 expect(canActivate("./src/a.js:1")).toBe(true);
470 fixture.metadata.set(
471 key("/repo/src:1:22:DD"),
472 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
473 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "directory" }),
474 ),
475 );
476 await hover("/repo/src:1:22:DD", "/repo/src:1:22");
477 expect(canActivate("/repo/src:1:22:DD")).toBe(true);
478 expect(canActivate("/repo/src:1:22")).toBe(false);
479 await hover(null);
480 expect(canActivate("/repo/src")).toBe(false);
481 fixture.metadata.set(
482 key("/home/alice/notes.ts"),
483 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
484 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
485 ),
486 );
487 await screen.rerender(
488 <AppAtomRegistryProvider>
489 <Drawer threadRef={threadRef} cwd="/home/alice/project" onCloseTerminal={() => {}} />
490 </AppAtomRegistryProvider>,
491 );
492 await act(async () => {
493 fixture.pendingSurfaces.shift()?.();
494 });
495 expect(await validate("~/notes.ts:5:2")).toBe(true);
496 await hover("~/notes.ts:5:2");
497 expect(canActivate("~/notes.ts:5:2")).toBe(true);
498});
499​
500it("drops the rest of a split paste when the shell restarts mid-paste", async () => {
501 const { other: threadRef } = setup();
502 let settleWrite = () => {};
503 fixture.runWrite = () =>
504 new Promise((resolve) => {
505 settleWrite = () => resolve({ _tag: "Success" });
506 });
507 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
508 await act(async () => {
509 fixture.pendingSurfaces.shift()?.();
510 });
511 fixture.typeIntoSurface?.("p".repeat(70_000));
512 await act(async () => {
513 fixture.sessionEvent(threadRef, "restarted");
514 settleWrite();
515 });
516 fixture.typeIntoSurface?.("after");
517 expect(fixture.writes.map(({ data }) => data.length)).toEqual([65_536, 5]);
518});
519​
520it.each([
521 { pid: 123, guarded: true, recovers: true },
522 { pid: 456, guarded: true, recovers: true },
523 { pid: 123, guarded: false, recovers: true },
524 { pid: 456, guarded: false, recovers: false },
525])(
526 "recovers interrupted paste with conditional writes $guarded and attachment PID $pid",
527 async ({ pid, guarded, recovers }) => {
528 const { other: threadRef } = setup();
529 fixture.supportsConditionalWrites = guarded;
530 if (!guarded) fixture.setMetadataPid(threadRef, 123);
531 let settleWrite = () => {};
532 fixture.runWrite = () =>
533 new Promise((resolve) => {
534 settleWrite = () => {
535 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
536 resolve({ _tag: "Success" });
537 };
538 });
539 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
540 await act(async () => {
541 fixture.pendingSurfaces.shift()?.();
542 });
543 const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
544 fixture.typeIntoSurface?.(large);
545 await act(async () => {
546 fixture.sessionEvent(threadRef, "snapshot", pid);
547 settleWrite();
548 });
549 await act(async () => {
550 fixture.typeIntoSurface?.("after");
551 });
552 expect(
553 fixture.messages.filter((message) => message.includes("paste interrupted")),
554 ).toHaveLength(1);
555 const identity = guarded ? { expectedPid: 123 } : {};
556 expect(fixture.writes.map(({ threadId: _, ...write }) => write)).toEqual([
557 { data: large.slice(0, 65_536), ...identity },
558 ...(recovers ? [{ data: "\x1b[201~", ...identity }] : []),
559 { data: "after" },
560 ]);
561 },
562);
563​
564it.each(["metadata first", "closed"] as const)(
565 "clears legacy paste recovery when the process is gone (%s)",
566 async (change) => {
567 const { other: threadRef } = setup();
568 fixture.supportsConditionalWrites = false;
569 fixture.setMetadataPid(threadRef, 123);
570 let failWrite = () => {};
571 fixture.runWrite = () =>
572 new Promise((resolve) => {
573 failWrite = () => {
574 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
575 resolve(AsyncResult.failure(Cause.die(new Error("acknowledgement lost"))));
576 };
577 });
578 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
579 await act(async () => {
580 fixture.pendingSurfaces.shift()?.();
581 });
582 const paste = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
583 fixture.typeIntoSurface?.(paste);
584 await act(async () => {
585 if (change === "closed") fixture.sessionEvent(threadRef, "closed");
586 else fixture.setMetadataPid(threadRef, 456);
587 failWrite();
588 });
589 expect(fixture.writes.map(({ data }) => data)).toEqual([paste.slice(0, 65_536)]);
590 await act(async () => {
591 // After close, reopen without a PID change to expose any stale recovery obligation.
592 fixture.sessionEvent(threadRef, "snapshot", change === "closed" ? 123 : 456);
593 fixture.typeIntoSurface?.("after");
594 });
595 expect(fixture.writes.map(({ data }) => data)).toEqual([paste.slice(0, 65_536), "after"]);
596 },
597);
598​
599it("stops a split paste on its original process once that process is replaced", async () => {
600 const { other: threadRef } = setup();
601 fixture.runWrite = async () =>
602 fixture.writes.length >= 2 && fixture.writes.at(-1)?.expectedPid !== undefined
603 ? AsyncResult.failure(Cause.fail(new TerminalProcessChangedError()))
604 : { _tag: "Success" };
605 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
606 await act(async () => {
607 fixture.pendingSurfaces.shift()?.();
608 });
609 const paste = `\x1b[200~${"p".repeat(140_000)}\x1b[201~`;
610 await act(async () => {
611 fixture.typeIntoSurface?.(paste);
612 fixture.typeIntoSurface?.("after");
613 });
614 expect(fixture.writes.map(({ data, expectedPid }) => ({ data, expectedPid }))).toEqual([
615 { data: paste.slice(0, 65_536), expectedPid: 123 },
616 { data: paste.slice(65_536, 131_072), expectedPid: 123 },
617 { data: "\x1b[201~", expectedPid: 123 },
618 { data: "after", expectedPid: undefined },
619 ]);
620});
621​
622it("closes an interrupted paste after disposal before input from a remounted view", async () => {
623 const { other: threadRef } = setup();
624 let settleWrite = () => {};
625 fixture.runWrite = () =>
626 new Promise((resolve) => {
627 settleWrite = () => {
628 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
629 resolve({ _tag: "Success" });
630 };
631 });
632 await using screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
633 await act(async () => {
634 fixture.pendingSurfaces.shift()?.();
635 });
636 const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
637 fixture.typeIntoSurface?.(large);
638 fixture.typeIntoSurface?.("stale");
639 await screen.rerender(<div />);
640 await act(async () => {
641 settleWrite();
642 });
643 await screen.rerender(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
644 await act(async () => {
645 fixture.pendingSurfaces.shift()?.();
646 });
647 await act(async () => {
648 fixture.typeIntoSurface?.("after");
649 });
650 expect(fixture.writes.map(({ data }) => data.length)).toEqual([65_536, 6, 5]);
651});
652​
653it("resends a failed resize once in each writable session", async () => {
654 const { other: threadRef } = setup();
655 const resizes: unknown[] = [];
656 const failure = AsyncResult.failure(Cause.die(new Error("resize rejected")));
657 let failFirstResize = () => {};
658 fixture.runResize = (input) => {
659 resizes.push(input);
660 if (resizes.length > 1) return Promise.resolve(failure);
661 return new Promise((resolve) => {
662 failFirstResize = () => resolve(failure);
663 });
664 };
665 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
666 await act(async () => {
667 fixture.pendingSurfaces.shift()?.();
668 });
669 await act(async () => {
670 fixture.reportedSize = { cols: 57, rows: 41 };
671 fixture.surfaceOptions.at(-1)!.onResize(57, 41);
672 });
673 // The first request fails while the attachment reconnects, so its retry is not sent.
674 await act(async () => {
675 fixture.setSession(threadRef, "running", 0, 1);
676 failFirstResize();
677 });
678 expect(resizes).toHaveLength(1);
679 await act(async () => {
680 fixture.setSession(threadRef, "running", 1, 2);
681 });
682 const resize = {
683 environmentId: threadRef.environmentId,
684 input: { threadId: threadRef.threadId, terminalId: "term-1", cols: 57, rows: 41 },
685 };
686 expect(resizes).toEqual([resize, resize, resize]);
687});