Open History to see the last commit
1import "../index.css";
2
3import { scopeThreadRef } from "@t3tools/client-runtime";
4import { ThreadId, type TerminalAttachStreamEvent } from "@t3tools/contracts";
5import { afterEach, describe, expect, it, vi } from "vite-plus/test";
6import { render } from "vitest-browser-react";
7
8const {
9 terminalConstructorSpy,
10 terminalDisposeSpy,
11 fitAddonFitSpy,
12 fitAddonLoadSpy,
13 environmentApiById,
14 readEnvironmentApiMock,
15 readLocalApiMock,
16} = vi.hoisted(() => ({
17 terminalConstructorSpy: vi.fn(),
18 terminalDisposeSpy: vi.fn(),
19 fitAddonFitSpy: vi.fn(),
20 fitAddonLoadSpy: vi.fn(),
21 environmentApiById: new Map<
22 string,
23 {
24 terminal: {
25 open: ReturnType<typeof vi.fn>;
26 attach: ReturnType<typeof vi.fn>;
27 write: ReturnType<typeof vi.fn>;
28 resize: ReturnType<typeof vi.fn>;
29 };
30 }
31 >(),
32 readEnvironmentApiMock: vi.fn((environmentId: string) => environmentApiById.get(environmentId)),
33 readLocalApiMock: vi.fn<
34 () =>
35 | {
36 contextMenu: { show: ReturnType<typeof vi.fn> };
37 shell: { openExternal: ReturnType<typeof vi.fn> };
38 }
39 | undefined
40 >(() => ({
41 contextMenu: { show: vi.fn(async () => null) },
42 shell: { openExternal: vi.fn(async () => undefined) },
43 })),
44}));
45
46vi.mock("@xterm/addon-fit", () => ({
47 FitAddon: class MockFitAddon {
48 fit = fitAddonFitSpy;
49 },
50}));
51
52vi.mock("@xterm/xterm", () => ({
53 Terminal: class MockTerminal {
54 cols = 80;
55 rows = 24;
56 options: { theme?: unknown } = {};
57 buffer = {
58 active: {
59 viewportY: 0,
60 baseY: 0,
61 getLine: vi.fn(() => null),
62 },
63 };
64
65 constructor(options: unknown) {
66 terminalConstructorSpy(options);
67 }
68
69 loadAddon(addon: unknown) {
70 fitAddonLoadSpy(addon);
71 }
72
73 open() {}
74
75 write() {}
76
77 clear() {}
78
79 clearSelection() {}
80
81 focus() {}
82
83 refresh() {}
84
85 scrollToBottom() {}
86
87 hasSelection() {
88 return false;
89 }
90
91 getSelection() {
92 return "";
93 }
94
95 getSelectionPosition() {
96 return null;
97 }
98
99 attachCustomKeyEventHandler() {
100 return true;
101 }
102
103 registerLinkProvider() {
104 return { dispose: vi.fn() };
105 }
106
107 onData() {
108 return { dispose: vi.fn() };
109 }
110
111 onSelectionChange() {
112 return { dispose: vi.fn() };
113 }
114
115 dispose() {
116 terminalDisposeSpy();
117 }
118 },
119}));
120
121vi.mock("~/environmentApi", () => ({
122 readEnvironmentApi: readEnvironmentApiMock,
123}));
124
125vi.mock("~/localApi", () => ({
126 ensureLocalApi: vi.fn(() => {
127 throw new Error("ensureLocalApi not implemented in browser test");
128 }),
129 readLocalApi: readLocalApiMock,
130}));
131
132import { TerminalViewport } from "./ThreadTerminalDrawer";
133
134const THREAD_ID = ThreadId.make("thread-terminal-browser");
135
136function createEnvironmentApi() {
137 const snapshot = {
138 threadId: THREAD_ID,
139 terminalId: "term-1",
140 cwd: "/repo/project",
141 worktreePath: null,
142 status: "running" as const,
143 pid: 123,
144 history: "",
145 exitCode: null,
146 exitSignal: null,
147 label: "Terminal 1",
148 updatedAt: "2026-04-07T00:00:00.000Z",
149 };
150
151 return {
152 terminal: {
153 open: vi.fn(async () => snapshot),
154 attach: vi.fn(
155 (
156 _input: unknown,
157 listener: (event: TerminalAttachStreamEvent) => void,
158 _options?: unknown,
159 ) => {
160 listener({ type: "snapshot", snapshot });
161 return vi.fn();
162 },
163 ),
164 write: vi.fn(async () => undefined),
165 resize: vi.fn(async () => undefined),
166 },
167 };
168}
169
170async function mountTerminalViewport(props: {
171 threadRef: ReturnType<typeof scopeThreadRef>;
172 drawerBackgroundColor?: string;
173 drawerTextColor?: string;
174 runtimeEnv?: Record<string, string>;
175}) {
176 const drawer = document.createElement("div");
177 drawer.className = "thread-terminal-drawer";
178 if (props.drawerBackgroundColor) {
179 drawer.style.backgroundColor = props.drawerBackgroundColor;
180 }
181 if (props.drawerTextColor) {
182 drawer.style.color = props.drawerTextColor;
183 }
184
185 const host = document.createElement("div");
186 host.style.width = "800px";
187 host.style.height = "400px";
188 drawer.append(host);
189 document.body.append(drawer);
190
191 const screen = await render(
192 <TerminalViewport
193 threadRef={props.threadRef}
194 threadId={THREAD_ID}
195 terminalId="term-1"
196 terminalLabel="Terminal"
197 cwd="/repo/project"
198 {...(props.runtimeEnv ? { runtimeEnv: props.runtimeEnv } : {})}
199 onSessionExited={() => undefined}
200 onAddTerminalContext={() => undefined}
201 focusRequestId={0}
202 autoFocus={false}
203 resizeEpoch={0}
204 drawerHeight={320}
205 keybindings={[]}
206 />,
207 { container: host },
208 );
209
210 return {
211 rerender: async (nextProps: {
212 threadRef: ReturnType<typeof scopeThreadRef>;
213 runtimeEnv?: Record<string, string>;
214 }) => {
215 await screen.rerender(
216 <TerminalViewport
217 threadRef={nextProps.threadRef}
218 threadId={THREAD_ID}
219 terminalId="term-1"
220 terminalLabel="Terminal"
221 cwd="/repo/project"
222 {...(nextProps.runtimeEnv ? { runtimeEnv: nextProps.runtimeEnv } : {})}
223 onSessionExited={() => undefined}
224 onAddTerminalContext={() => undefined}
225 focusRequestId={0}
226 autoFocus={false}
227 resizeEpoch={0}
228 drawerHeight={320}
229 keybindings={[]}
230 />,
231 );
232 },
233 cleanup: async () => {
234 await screen.unmount();
235 drawer.remove();
236 },
237 };
238}
239
240describe("TerminalViewport", () => {
241 afterEach(() => {
242 environmentApiById.clear();
243 readEnvironmentApiMock.mockClear();
244 readLocalApiMock.mockClear();
245 terminalConstructorSpy.mockClear();
246 terminalDisposeSpy.mockClear();
247 fitAddonFitSpy.mockClear();
248 fitAddonLoadSpy.mockClear();
249 });
250
251 it("does not create a terminal when APIs are unavailable", async () => {
252 readEnvironmentApiMock.mockReturnValueOnce(undefined);
253 readLocalApiMock.mockReturnValueOnce(undefined);
254
255 const mounted = await mountTerminalViewport({
256 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
257 });
258
259 try {
260 await vi.waitFor(() => {
261 expect(terminalConstructorSpy).not.toHaveBeenCalled();
262 });
263 } finally {
264 await mounted.cleanup();
265 }
266 });
267
268 it("renders and attaches the terminal without the desktop local API", async () => {
269 const environment = createEnvironmentApi();
270 environmentApiById.set("environment-a", environment);
271 readLocalApiMock.mockReturnValueOnce(undefined);
272
273 const mounted = await mountTerminalViewport({
274 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
275 });
276
277 try {
278 await vi.waitFor(() => {
279 expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
280 });
281 expect(terminalConstructorSpy).toHaveBeenCalledTimes(1);
282 } finally {
283 await mounted.cleanup();
284 }
285 });
286
287 it("keeps the terminal mounted when xterm fit runs before dimensions are ready", async () => {
288 const environment = createEnvironmentApi();
289 environmentApiById.set("environment-a", environment);
290 fitAddonFitSpy.mockImplementationOnce(() => {
291 throw new TypeError("Cannot read properties of undefined (reading 'dimensions')");
292 });
293
294 const mounted = await mountTerminalViewport({
295 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
296 });
297
298 try {
299 await vi.waitFor(() => {
300 expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
301 });
302 expect(terminalConstructorSpy).toHaveBeenCalledTimes(1);
303 expect(fitAddonFitSpy).toHaveBeenCalled();
304 } finally {
305 await mounted.cleanup();
306 }
307 });
308
309 it("reattaches the terminal when the scoped thread reference changes", async () => {
310 const environmentA = createEnvironmentApi();
311 const environmentB = createEnvironmentApi();
312 environmentApiById.set("environment-a", environmentA);
313 environmentApiById.set("environment-b", environmentB);
314
315 const mounted = await mountTerminalViewport({
316 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
317 });
318
319 try {
320 await vi.waitFor(() => {
321 expect(environmentA.terminal.attach).toHaveBeenCalledTimes(1);
322 });
323
324 await mounted.rerender({
325 threadRef: scopeThreadRef("environment-b" as never, THREAD_ID),
326 });
327
328 await vi.waitFor(() => {
329 expect(environmentB.terminal.attach).toHaveBeenCalledTimes(1);
330 });
331 expect(terminalDisposeSpy).toHaveBeenCalledTimes(1);
332 } finally {
333 await mounted.cleanup();
334 }
335 });
336
337 it("does not reattach the terminal when the scoped thread reference values stay the same", async () => {
338 const environment = createEnvironmentApi();
339 environmentApiById.set("environment-a", environment);
340
341 const mounted = await mountTerminalViewport({
342 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
343 });
344
345 try {
346 await vi.waitFor(() => {
347 expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
348 });
349
350 await mounted.rerender({
351 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
352 });
353
354 await vi.waitFor(() => {
355 expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
356 });
357 expect(terminalDisposeSpy).not.toHaveBeenCalled();
358 } finally {
359 await mounted.cleanup();
360 }
361 });
362
363 it("does not reattach when runtime env contents are unchanged but object identity changes", async () => {
364 const environment = createEnvironmentApi();
365 environmentApiById.set("environment-a", environment);
366
367 const mounted = await mountTerminalViewport({
368 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
369 runtimeEnv: { PATH: "/usr/bin", T3: "1" },
370 });
371
372 try {
373 await vi.waitFor(() => {
374 expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
375 });
376
377 await mounted.rerender({
378 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
379 runtimeEnv: { T3: "1", PATH: "/usr/bin" },
380 });
381
382 await vi.waitFor(() => {
383 expect(environment.terminal.attach).toHaveBeenCalledTimes(1);
384 });
385 expect(terminalDisposeSpy).not.toHaveBeenCalled();
386 } finally {
387 await mounted.cleanup();
388 }
389 });
390
391 it("uses the drawer surface colors for the terminal theme", async () => {
392 const environment = createEnvironmentApi();
393 environmentApiById.set("environment-a", environment);
394
395 const mounted = await mountTerminalViewport({
396 threadRef: scopeThreadRef("environment-a" as never, THREAD_ID),
397 drawerBackgroundColor: "rgb(24, 28, 36)",
398 drawerTextColor: "rgb(228, 232, 240)",
399 });
400
401 try {
402 await vi.waitFor(() => {
403 expect(terminalConstructorSpy).toHaveBeenCalledTimes(1);
404 });
405
406 expect(terminalConstructorSpy).toHaveBeenCalledWith(
407 expect.objectContaining({
408 theme: expect.objectContaining({
409 background: "rgb(24, 28, 36)",
410 foreground: "rgb(228, 232, 240)",
411 }),
412 }),
413 );
414 } finally {
415 await mounted.cleanup();
416 }
417 });
418});