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