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