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

ThreadTerminalDrawer.browser.test.tsx

250 lines9.0 KB

1import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal";
2import {
3 EnvironmentId,
4 ThreadId,
5 type ScopedThreadRef,
6 type FilesystemEntryMetadata,
7} from "@t3tools/contracts";
8import { Atom, AsyncResult } from "effect/reactivity";
9import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
10import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry";
11import { extractTerminalLinks } from "../terminal-links";
12import { expect, it, vi } from "vite-plus/test";
13import { act, fakeTimers, render } from "../../test/render";
14import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
15​
16const fixture = vi.hoisted(() => ({
17 statusByThreadId: new Map<string, "running" | "exited">(),
18 pendingSurfaces: [] as Array<() => void>,
19 surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
20 metadata: new Map<
21 string,
22 Atom.Writable<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>
23 >(),
24}));
25​
26// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
27const fakeSurface: object = new Proxy(
28 { input: document.createElement("textarea") },
29 {
30 get: (target, key) =>
31 key === "then" ? undefined : key in target ? Reflect.get(target, key) : () => undefined,
32 },
33);
34vi.mock("~/terminal/ghostty/surface", () => ({
35 GhosttyTerminalSurface: {
36 create: (_mount: HTMLElement, options: GhosttyTerminalSurfaceOptions) =>
37 new Promise((resolve) => {
38 fixture.surfaceOptions.push(options);
39 fixture.pendingSurfaces.push(() => resolve(fakeSurface));
40 }),
41 },
42}));
43vi.mock("../state/terminalSessions", async () => {
44 const Atom = await import("effect/reactivity/Atom");
45 const sessions = Atom.family((_environmentId: EnvironmentId) =>
46 Atom.family((threadId: ThreadId) =>
47 Atom.make({
48 ...EMPTY_TERMINAL_SESSION_STATE,
49 status: fixture.statusByThreadId.get(threadId) ?? "closed",
50 version: 1,
51 }),
52 ),
53 );
54 return {
55 attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) =>
56 sessions(environmentId)(terminal.threadId),
57 };
58});
59vi.mock("../state/session", () => ({
60 useEnvironmentScope: () => true,
61 readEnvironmentScope: () => true,
62}));
63vi.mock("../state/use-atom-command", () => ({
64 useAtomCommand: () => async () => ({ _tag: "Success" }),
65}));
66// The commands are replaced above; importing their runtime would connect a client.
67vi.mock("../state/server", async () => {
68 const Atom = await import("effect/reactivity/Atom");
69 const config = Atom.make(null);
70 return { serverEnvironment: { configValueAtom: () => config } };
71});
72vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } }));
73vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
74vi.mock("../state/projects", async () => {
75 const { Atom, AsyncResult } = await import("effect/reactivity");
76 return {
77 projectEnvironment: {
78 fileMetadata: ({
79 environmentId,
80 input,
81 }: {
82 environmentId: string;
83 input: { path: string };
84 }) => {
85 const key = JSON.stringify([environmentId, input.path]);
86 let atom = fixture.metadata.get(key);
87 if (!atom) {
88 atom = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
89 AsyncResult.success(null),
90 );
91 fixture.metadata.set(key, atom);
92 }
93 return atom;
94 },
95 },
96 };
97});
98vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
99vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
100vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
101vi.mock("../hooks/useSettings", async () => {
102 const { DEFAULT_CLIENT_SETTINGS } = await import("@t3tools/contracts/settings");
103 return {
104 useClientSettings: <T,>(select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) =>
105 select(DEFAULT_CLIENT_SETTINGS),
106 };
107});
108​
109function Drawer(props: {
110 threadRef: ScopedThreadRef;
111 cwd?: string;
112 onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
113}) {
114 return (
115 <ThreadTerminalDrawer
116 threadRef={props.threadRef}
117 threadId={props.threadRef.threadId}
118 cwd={props.cwd ?? "/repo"}
119 height={240}
120 terminalIds={["term-1"]}
121 activeTerminalId="term-1"
122 terminalGroups={[{ id: "group-1", terminalIds: ["term-1"] }]}
123 activeTerminalGroupId="group-1"
124 onSplitTerminal={() => {}}
125 onSplitTerminalVertical={() => {}}
126 onNewTerminal={() => {}}
127 onActiveTerminalChange={() => {}}
128 onCloseTerminal={props.onCloseTerminal}
129 onHeightChange={() => {}}
130 onAddTerminalContext={() => {}}
131 keybindings={[]}
132 />
133 );
135​
136function setup() {
137 const original: ScopedThreadRef = {
138 environmentId: EnvironmentId.make("environment-a"),
139 threadId: ThreadId.make("thread-a"),
140 };
141 const other: ScopedThreadRef = {
142 environmentId: EnvironmentId.make("environment-b"),
143 threadId: ThreadId.make("thread-b"),
144 };
145 fixture.statusByThreadId = new Map([
146 [original.threadId, "exited"],
147 [other.threadId, "running"],
148 ]);
149 fixture.pendingSurfaces = [];
150 fixture.surfaceOptions = [];
151 fixture.metadata.clear();
152 return { original, other };
154​
155it("closes an exited terminal on its own thread after navigating to one reusing its ID", async () => {
156 const { original, other } = setup();
157 const onCloseTerminal = vi.fn();
158 await using screen = await render(
159 <Drawer threadRef={original} onCloseTerminal={onCloseTerminal} />,
160 );
161 using _timers = fakeTimers();
162 // The exit is seen once the surface loads, and its close waits for the next task.
163 await act(async () => {
164 fixture.pendingSurfaces.shift()?.();
165 });
166 await screen.rerender(<Drawer threadRef={other} onCloseTerminal={onCloseTerminal} />);
167 await act(async () => {
168 vi.runOnlyPendingTimers();
169 });
170 expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
171});
172​
173it("only activates terminal paths confirmed to exist on their environment", async () => {
174 const { other: threadRef } = setup();
175 const key = (path: string) => JSON.stringify([threadRef.environmentId, path]);
176 const pending = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
177 AsyncResult.initial(),
178 );
179 fixture.metadata.set(key("/repo/src/main.ts"), pending);
180 fixture.metadata.set(
181 key("/repo/src/…notes.ts"),
182 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
183 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
184 ),
185 );
186 fixture.metadata.set(
187 key("/repo/src"),
188 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
189 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "directory" }),
190 ),
191 );
192 await using screen = await render(
193 <AppAtomRegistryProvider>
194 <Drawer threadRef={threadRef} onCloseTerminal={() => {}} />
195 </AppAtomRegistryProvider>,
196 );
197 await act(async () => {
198 fixture.pendingSurfaces.shift()?.();
199 });
200 const canActivate = (text: string) => fixture.surfaceOptions.at(-1)!.canActivateLink!(text);
201 const validate = (text: string) => fixture.surfaceOptions.at(-1)!.validateLink!(text);
202 const hover = (text: string | null) =>
203 act(() => fixture.surfaceOptions.at(-1)!.onLinkHover!(text));
204​
205 expect(canActivate("https://example.com")).toBe(true);
206 for (const branch of ["t3/fix-html-image-details", "t3/fix-html-…mage-details"]) {
207 const candidates = extractTerminalLinks(branch);
208 expect(candidates.length).toBeGreaterThan(0);
209 for (const candidate of candidates) {
210 expect(canActivate(candidate.text)).toBe(false);
211 await hover(candidate.text);
212 expect(canActivate(candidate.text)).toBe(false);
213 expect(await validate(candidate.text)).toBe(false);
214 }
215 }
216 const pressedValidation = validate("src/main.ts:12:7");
217 await hover("src/main.ts:12:7");
218 expect(canActivate("src/main.ts:12:7")).toBe(false);
219 await act(async () => {
220 appAtomRegistry.set(pending, AsyncResult.success({ kind: "file" }));
221 });
222 expect(canActivate("src/main.ts:12:7")).toBe(true);
223 expect(await pressedValidation).toBe(true);
224 expect(canActivate("missing/file.ts")).toBe(false);
225 await hover("missing/file.ts");
226 expect(canActivate("missing/file.ts")).toBe(false);
227 for (const path of ["/repo/src/…notes.ts", "/repo/src"]) {
228 await hover(path);
229 expect(canActivate(path)).toBe(true);
230 }
231 await hover(null);
232 expect(canActivate("/repo/src")).toBe(false);
233 fixture.metadata.set(
234 key("/home/alice/notes.ts"),
235 Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
236 AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
237 ),
238 );
239 await screen.rerender(
240 <AppAtomRegistryProvider>
241 <Drawer threadRef={threadRef} cwd="/home/alice/project" onCloseTerminal={() => {}} />
242 </AppAtomRegistryProvider>,
243 );
244 await act(async () => {
245 fixture.pendingSurfaces.shift()?.();
246 });
247 expect(await validate("~/notes.ts:5:2")).toBe(true);
248 await hover("~/notes.ts:5:2");
249 expect(canActivate("~/notes.ts:5:2")).toBe(true);
250});