@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 556 lines 20.2 KB
Raw
1 import {
2 applyTerminalAttachStreamEvent,
3 EMPTY_TERMINAL_SESSION_STATE,
4 } from "@t3tools/client-runtime/state/terminal";
5 import {
6 EnvironmentId,
7 ThreadId,
8 type ScopedThreadRef,
9 type FilesystemEntryMetadata,
10 type ResolvedKeybindingsConfig,
11 } from "@t3tools/contracts";
12 import { Cause } from "effect";
13 import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";
14 import { Atom, AsyncResult } from "effect/reactivity";
15 import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
16 import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry";
17 import { useRightPanelStore } from "../rightPanelStore";
18 import { useTerminalUiStateStore } from "../terminalUiStateStore";
19 import { extractTerminalLinks } from "../terminal-links";
20 import { expect, it, vi } from "vite-plus/test";
21 import { act, fakeTimers, render } from "../../test/render";
22 import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
23
24 const 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.
52 const 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 );
67 vi.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 }));
80 vi.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 });
154 vi.mock("../state/session", () => ({
155 useEnvironmentScope: () => true,
156 readEnvironmentScope: () => true,
157 }));
158 vi.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.
170 vi.mock("../state/server", async () => {
171 const Atom = await import("effect/reactivity/Atom");
172 const config = Atom.make(null);
173 return { serverEnvironment: { configValueAtom: () => config } };
174 });
175 vi.mock("../state/terminal", () => ({
176 terminalEnvironment: { write: {}, resize: fixture.resizeCommand },
177 }));
178 vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
179 vi.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 });
203 vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
204 vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
205 vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
206 vi.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 ensureClientSettingsHydrated: async () => {},
212 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
213 };
214 });
215
216 function Drawer(props: {
217 threadRef: ScopedThreadRef;
218 cwd?: string;
219 onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
220 keybindings?: ResolvedKeybindingsConfig;
221 }) {
222 return (
223 <ThreadTerminalDrawer
224 threadRef={props.threadRef}
225 threadId={props.threadRef.threadId}
226 cwd={props.cwd ?? "/repo"}
227 height={240}
228 terminalIds={["term-1"]}
229 activeTerminalId="term-1"
230 terminalGroups={[{ id: "group-1", terminalIds: ["term-1"] }]}
231 activeTerminalGroupId="group-1"
232 onSplitTerminal={() => {}}
233 onSplitTerminalVertical={() => {}}
234 onNewTerminal={() => {}}
235 onActiveTerminalChange={() => {}}
236 onCloseTerminal={props.onCloseTerminal}
237 onHeightChange={() => {}}
238 onAddTerminalContext={() => {}}
239 keybindings={props.keybindings ?? []}
240 />
241 );
242 }
243
244 function setup(originalStatus: "starting" | "exited" = "exited") {
245 fixture.resetSessions();
246 const original: ScopedThreadRef = {
247 environmentId: EnvironmentId.make(`environment-a-${expect.getState().currentTestName}`),
248 threadId: ThreadId.make("thread-a"),
249 };
250 const other: ScopedThreadRef = {
251 environmentId: EnvironmentId.make(`environment-b-${expect.getState().currentTestName}`),
252 threadId: ThreadId.make("thread-b"),
253 };
254 fixture.statusByThreadId = new Map([
255 [original.threadId, originalStatus],
256 [other.threadId, "running"],
257 ]);
258 fixture.pendingSurfaces = [];
259 fixture.typeIntoSurface = null;
260 fixture.pressKey = null;
261 fixture.writes = [];
262 fixture.messages = [];
263 fixture.surfaceOptions = [];
264 fixture.reportedSize = null;
265 fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined));
266 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
267 fixture.metadata.clear();
268 useRightPanelStore.setState(useRightPanelStore.getInitialState());
269 useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState());
270 return { original, other };
271 }
272
273 it("drops input until the shell runs instead of failing a write for every key", async () => {
274 const { original } = setup("starting");
275 fixture.setSession(original, "closed", 0);
276 await using _screen = await render(<Drawer threadRef={original} onCloseTerminal={() => {}} />);
277 await act(async () => {
278 fixture.pendingSurfaces.shift()?.();
279 });
280 const clearShortcut = () => new KeyboardEvent("keydown", { key: "l", ctrlKey: true });
281 fixture.typeIntoSurface?.("before attach");
282 fixture.pressKey?.(clearShortcut());
283 await act(() => fixture.setSession(original, "running", 0));
284 fixture.typeIntoSurface?.("stale metadata");
285 fixture.pressKey?.(clearShortcut());
286 await act(() => fixture.setSession(original, "starting", 1));
287 fixture.typeIntoSurface?.("early");
288 fixture.pressKey?.(clearShortcut());
289 expect(fixture.writes).toEqual([]);
290 await act(() => fixture.setSession(original, "running", 1));
291 fixture.typeIntoSurface?.("ready");
292 fixture.pressKey?.(clearShortcut());
293 expect(fixture.writes).toEqual([
294 { threadId: original.threadId, data: "ready" },
295 { threadId: original.threadId, data: "\u000c" },
296 ]);
297 });
298
299 it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => {
300 const { original, other } = setup();
301 const onCloseTerminal = vi.fn();
302 await using screen = await render(
303 <Drawer threadRef={original} onCloseTerminal={onCloseTerminal} />,
304 );
305 using _timers = fakeTimers();
306 // The exit is seen once the surface loads, and its close waits for the next task.
307 await act(async () => {
308 fixture.pendingSurfaces.shift()?.();
309 });
310 await screen.rerender(<Drawer threadRef={other} onCloseTerminal={onCloseTerminal} />);
311 await act(async () => {
312 vi.runOnlyPendingTimers();
313 });
314 expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
315 });
316
317 // Thread navigation defaults have no `!terminalFocus`, so they apply in a focused terminal.
318 it("hands thread navigation shortcuts from a focused terminal back to the app", async () => {
319 const { other: threadRef } = setup();
320 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
321 useRightPanelStore.getState().openBrowser(threadRef, null);
322 await using _screen = await render(
323 <Drawer
324 threadRef={threadRef}
325 onCloseTerminal={() => {}}
326 keybindings={compileResolvedKeybindingsConfig([
327 ...DEFAULT_KEYBINDINGS,
328 { key: "ctrl+r", command: "thread.next", when: "!previewOpen" },
329 { key: "ctrl+g", command: "thread.previous", when: "terminalOpen" },
330 ])}
331 />,
332 );
333 await act(async () => {
334 fixture.pendingSurfaces.shift()?.();
335 });
336 const terminalHandles = (key: string, code: string, shiftKey = true) =>
337 fixture.surfaceOptions
338 .at(-1)!
339 .beforeKey(new KeyboardEvent("keydown", { key, code, ctrlKey: true, shiftKey }));
340
341 expect([terminalHandles("{", "BracketLeft"), terminalHandles("}", "BracketRight")]).toEqual([
342 false,
343 false,
344 ]);
345 expect(terminalHandles("C", "KeyC")).toBe(true);
346 // Sidebar sees the open preview and the closed drawer and rejects these, so the shell keeps them.
347 expect([terminalHandles("r", "KeyR", false), terminalHandles("g", "KeyG", false)]).toEqual([
348 true,
349 true,
350 ]);
351 });
352
353 it("only activates terminal paths confirmed to exist on their environment", async () => {
354 const { other: threadRef } = setup();
355 const key = (path: string) => JSON.stringify([threadRef.environmentId, path]);
356 const pending = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
357 AsyncResult.initial(),
358 );
359 fixture.metadata.set(key("/repo/src/main.ts"), pending);
360 fixture.metadata.set(
361 key("/repo/src/…notes.ts"),
362 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
363 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
364 ),
365 );
366 fixture.metadata.set(
367 key("/repo/src"),
368 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
369 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "directory" }),
370 ),
371 );
372 await using screen = await render(
373 <AppAtomRegistryProvider>
374 <Drawer threadRef={threadRef} onCloseTerminal={() => {}} />
375 </AppAtomRegistryProvider>,
376 );
377 await act(async () => {
378 fixture.pendingSurfaces.shift()?.();
379 });
380 const canActivate = (text: string) => fixture.surfaceOptions.at(-1)!.canActivateLink!(text);
381 const validate = (text: string) => fixture.surfaceOptions.at(-1)!.validateLink!(text);
382 const hover = (text: string | null) =>
383 act(() => fixture.surfaceOptions.at(-1)!.onLinkHover!(text));
384
385 expect(canActivate("https://example.com")).toBe(true);
386 for (const branch of ["t3/fix-html-image-details", "t3/fix-html-…mage-details"]) {
387 const candidates = extractTerminalLinks(branch);
388 expect(candidates.length).toBeGreaterThan(0);
389 for (const candidate of candidates) {
390 expect(canActivate(candidate.text)).toBe(false);
391 await hover(candidate.text);
392 expect(canActivate(candidate.text)).toBe(false);
393 expect(await validate(candidate.text)).toBe(false);
394 }
395 }
396 const pressedValidation = validate("src/main.ts:12:7");
397 await hover("src/main.ts:12:7");
398 expect(canActivate("src/main.ts:12:7")).toBe(false);
399 await act(async () => {
400 appAtomRegistry.set(pending, AsyncResult.success({ kind: "file" }));
401 });
402 expect(canActivate("src/main.ts:12:7")).toBe(true);
403 expect(await pressedValidation).toBe(true);
404 expect(canActivate("missing/file.ts")).toBe(false);
405 await hover("missing/file.ts");
406 expect(canActivate("missing/file.ts")).toBe(false);
407 for (const path of ["/repo/src/…notes.ts", "/repo/src"]) {
408 await hover(path);
409 expect(canActivate(path)).toBe(true);
410 }
411 await hover(null);
412 expect(canActivate("/repo/src")).toBe(false);
413 fixture.metadata.set(
414 key("/home/alice/notes.ts"),
415 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
416 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
417 ),
418 );
419 await screen.rerender(
420 <AppAtomRegistryProvider>
421 <Drawer threadRef={threadRef} cwd="/home/alice/project" onCloseTerminal={() => {}} />
422 </AppAtomRegistryProvider>,
423 );
424 await act(async () => {
425 fixture.pendingSurfaces.shift()?.();
426 });
427 expect(await validate("~/notes.ts:5:2")).toBe(true);
428 await hover("~/notes.ts:5:2");
429 expect(canActivate("~/notes.ts:5:2")).toBe(true);
430 });
431
432 it("drops the rest of a split paste when the shell restarts mid-paste", async () => {
433 const { other: threadRef } = setup();
434 let settleWrite = () => {};
435 fixture.runWrite = () =>
436 new Promise((resolve) => {
437 settleWrite = () => resolve({ _tag: "Success" });
438 });
439 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
440 await act(async () => {
441 fixture.pendingSurfaces.shift()?.();
442 });
443 fixture.typeIntoSurface?.("p".repeat(70_000));
444 await act(async () => {
445 fixture.sessionEvent(threadRef, "restarted");
446 settleWrite();
447 });
448 fixture.typeIntoSurface?.("after");
449 expect(fixture.writes.map(({ data }) => data.length)).toEqual([65_536, 5]);
450 });
451
452 it.each([
453 { pid: 123, closes: true },
454 { pid: 456, closes: false },
455 ])(
456 "closes interrupted bracket framing only for its process (PID $pid)",
457 async ({ pid, closes }) => {
458 const { other: threadRef } = setup();
459 let settleWrite = () => {};
460 fixture.runWrite = () =>
461 new Promise((resolve) => {
462 settleWrite = () => {
463 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
464 resolve({ _tag: "Success" });
465 };
466 });
467 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
468 await act(async () => {
469 fixture.pendingSurfaces.shift()?.();
470 });
471 const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
472 fixture.typeIntoSurface?.(large);
473 await act(async () => {
474 fixture.sessionEvent(threadRef, "snapshot", pid);
475 settleWrite();
476 });
477 await act(async () => {
478 fixture.typeIntoSurface?.("after");
479 });
480 expect(
481 fixture.messages.filter((message) => message.includes("paste interrupted")),
482 ).toHaveLength(1);
483 expect(fixture.writes.map(({ data }) => data)).toEqual([
484 large.slice(0, 65_536),
485 ...(closes ? ["\x1b[201~"] : []),
486 "after",
487 ]);
488 },
489 );
490
491 it("closes an interrupted paste after disposal before input from a remounted view", async () => {
492 const { other: threadRef } = setup();
493 let settleWrite = () => {};
494 fixture.runWrite = () =>
495 new Promise((resolve) => {
496 settleWrite = () => {
497 fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
498 resolve({ _tag: "Success" });
499 };
500 });
501 await using screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
502 await act(async () => {
503 fixture.pendingSurfaces.shift()?.();
504 });
505 const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
506 fixture.typeIntoSurface?.(large);
507 fixture.typeIntoSurface?.("stale");
508 await screen.rerender(<div />);
509 await act(async () => {
510 settleWrite();
511 });
512 await screen.rerender(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
513 await act(async () => {
514 fixture.pendingSurfaces.shift()?.();
515 });
516 await act(async () => {
517 fixture.typeIntoSurface?.("after");
518 });
519 expect(fixture.writes.map(({ data }) => data.length)).toEqual([65_536, 6, 5]);
520 });
521
522 it("resends a failed resize once in each writable session", async () => {
523 const { other: threadRef } = setup();
524 const resizes: unknown[] = [];
525 const failure = AsyncResult.failure(Cause.die(new Error("resize rejected")));
526 let failFirstResize = () => {};
527 fixture.runResize = (input) => {
528 resizes.push(input);
529 if (resizes.length > 1) return Promise.resolve(failure);
530 return new Promise((resolve) => {
531 failFirstResize = () => resolve(failure);
532 });
533 };
534 await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
535 await act(async () => {
536 fixture.pendingSurfaces.shift()?.();
537 });
538 await act(async () => {
539 fixture.reportedSize = { cols: 57, rows: 41 };
540 fixture.surfaceOptions.at(-1)!.onResize(57, 41);
541 });
542 // The first request fails while the attachment reconnects, so its retry is not sent.
543 await act(async () => {
544 fixture.setSession(threadRef, "running", 0, 1);
545 failFirstResize();
546 });
547 expect(resizes).toHaveLength(1);
548 await act(async () => {
549 fixture.setSession(threadRef, "running", 1, 2);
550 });
551 const resize = {
552 environmentId: threadRef.environmentId,
553 input: { threadId: threadRef.threadId, terminalId: "term-1", cols: 57, rows: 41 },
554 };
555 expect(resizes).toEqual([resize, resize, resize]);
556 });