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

ThreadTerminalDrawer.permissions.browser.test.tsx

257 lines9.1 KB

1import {
2 AuthTerminalOperateScope,
3 EnvironmentId,
4 ThreadId,
5 type AuthEnvironmentScope,
6} from "@t3tools/contracts";
7import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
8import { nextTerminalAttachSeedState } from "@t3tools/client-runtime/state/terminal";
9import { AsyncResult } from "effect/reactivity";
10import { act } from "react";
11import { createRoot, type Root } from "react-dom/client";
12import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
13import type {
14 GhosttyTerminalSurface,
15 GhosttyTerminalSurfaceOptions,
16} from "~/terminal/ghostty/surface";
17​
18const state = vi.hoisted(() => ({
19 allowed: true,
20 listeners: new Set<() => void>(),
21 resize: vi.fn(),
22 otherCommand: vi.fn(),
23 createSurface:
24 vi.fn<
25 (
26 mount: HTMLElement,
27 options: GhosttyTerminalSurfaceOptions,
28 ) => Promise<GhosttyTerminalSurface>
29 >(),
30}));
31​
32vi.mock(import("@effect/atom-react"), async (original) => ({
33 ...(await original()),
34 useAtomValue: (() => null) as never,
35}));
36vi.mock(import("../hooks/useSettings"), async (original) => ({
37 ...(await original()),
38 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
39 useClientSettings: ((select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
40 select(DEFAULT_CLIENT_SETTINGS)) as never,
41}));
42vi.mock(import("../editorPreferences"), async (original) => ({
43 ...(await original()),
44 useOpenInPreferredEditor: (() => state.otherCommand) as never,
45}));
46vi.mock(import("../state/terminal"), async (original) => {
47 const actual = await original();
48 return {
49 ...actual,
50 terminalEnvironment: { ...actual.terminalEnvironment, resize: "resize" as never },
51 };
52});
53vi.mock(import("../state/use-atom-command"), async (original) => ({
54 ...(await original()),
55 useAtomCommand: ((command: unknown) =>
56 command === "resize" ? state.resize : state.otherCommand) as never,
57}));
58vi.mock(import("../state/terminalSessions"), async (original) => ({
59 ...(await original()),
60 useAttachedTerminalSession: (() => session) as never,
61}));
62vi.mock(import("~/terminal/ghostty/surface"), async (original) => ({
63 ...(await original()),
64 GhosttyTerminalSurface: { create: state.createSurface } as never,
65}));
66vi.mock(import("../state/session"), async (original) => {
67 const { useSyncExternalStore } = await import("react");
68 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
69 id !== null &&
70 (scope !== AuthTerminalOperateScope || id !== threadRef.environmentId || state.allowed);
71 return {
72 ...(await original()),
73 readEnvironmentScope,
74 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
75 useSyncExternalStore(
76 (listener) => {
77 state.listeners.add(listener);
78 return () => state.listeners.delete(listener);
79 },
80 () => readEnvironmentScope(id, scope),
81 ),
82 };
83});
84​
85import ThreadTerminalDrawer, { TerminalViewport } from "./ThreadTerminalDrawer";
86​
87const threadRef = {
88 environmentId: EnvironmentId.make("secondary-terminal"),
89 threadId: ThreadId.make("thread"),
90};
91const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };
92let root: Root;
93let container: HTMLDivElement;
94​
95beforeEach(() => {
96 state.allowed = true;
97 state.listeners.clear();
98 state.resize.mockReset().mockResolvedValue(AsyncResult.success(undefined));
99 state.otherCommand.mockReset().mockResolvedValue(AsyncResult.success(undefined));
100 // A surface can report its initial grid while asynchronous WASM setup is
101 // pending. Keep that unrelated setup pending while exercising its callback.
102 state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));
103 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
104 container = document.createElement("div");
105 document.body.append(container);
106 root = createRoot(container);
107});
108​
109afterEach(async () => {
110 await act(async () => root.unmount());
111 container.remove();
112 vi.unstubAllGlobals();
113 vi.restoreAllMocks();
114});
115​
116it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {
117 await act(async () =>
118 root.render(
119 <TerminalViewport
120 advancedTypography={false}
121 threadRef={threadRef}
122 threadId={threadRef.threadId}
123 terminalId="terminal-1"
124 terminalLabel="Terminal 1"
125 cwd="/repo"
126 onSessionExited={state.otherCommand}
127 focusRequestId={0}
128 autoFocus={false}
129 visible={true}
130 resizeEpoch={0}
131 drawerHeight={200}
132 keybindings={[]}
133 />,
134 ),
135 );
136 expect(state.createSurface).toHaveBeenCalledOnce();
137 const onResize = state.createSurface.mock.calls[0]![1].onResize;
138 if (!onResize) throw new Error("The terminal did not register its resize callback.");
139​
140 onResize(80, 24);
141 expect(state.resize).toHaveBeenCalledExactlyOnceWith({
142 environmentId: threadRef.environmentId,
143 input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 80, rows: 24 },
144 });
145​
146 state.allowed = false;
147 onResize(120, 40);
148 expect(state.resize).toHaveBeenCalledTimes(1);
149​
150 state.allowed = true;
151 onResize(100, 30);
152 expect(state.resize).toHaveBeenCalledTimes(2);
153 expect(state.resize).toHaveBeenLastCalledWith({
154 environmentId: threadRef.environmentId,
155 input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 100, rows: 30 },
156 });
157});
158​
159it("keeps held Kitty keys and the original surface through split, focus, and unsplit", async () => {
160 const { GhosttyTerminalSurface } = await vi.importActual<
161 typeof import("~/terminal/ghostty/surface")
162 >("~/terminal/ghostty/surface");
163 const output: string[][] = [];
164 state.createSurface.mockImplementation((mount, options) => {
165 const data: string[] = [];
166 output.push(data);
167 return GhosttyTerminalSurface.create(mount, {
168 ...options,
169 onData: (chunk) => {
170 data.push(chunk);
171 options.onData(chunk);
172 },
173 });
174 });
175 const consumeShortcut = (event: KeyboardEvent) => {
176 if ((event.code === "KeyD" && event.ctrlKey) || (event.code === "KeyB" && event.repeat)) {
177 event.preventDefault();
178 event.stopPropagation();
179 }
180 };
181 // ChatView installs its capture listener before the terminal mounts.
182 window.addEventListener("keydown", consumeShortcut, { capture: true });
183 const composer = document.createElement("textarea");
184 document.body.append(composer);
185 const render = async (terminalIds: string[]) => {
186 await act(async () =>
187 root.render(
188 <ThreadTerminalDrawer
189 threadRef={threadRef}
190 threadId={threadRef.threadId}
191 cwd="/repo"
192 height={280}
193 terminalIds={terminalIds}
194 activeTerminalId="original"
195 terminalGroups={[{ id: "group", terminalIds }]}
196 activeTerminalGroupId="group"
197 focusRequestId={0}
198 onSplitTerminal={state.otherCommand}
199 onSplitTerminalVertical={state.otherCommand}
200 onNewTerminal={state.otherCommand}
201 onActiveTerminalChange={state.otherCommand}
202 onCloseTerminal={state.otherCommand}
203 onHeightChange={state.otherCommand}
204 onAddTerminalContext={state.otherCommand}
205 keybindings={[]}
206 />,
207 ),
208 );
209 await act(async () => {
210 await Promise.all(state.createSurface.mock.results.map((result) => result.value));
211 });
212 };
213 try {
214 await render(["original"]);
215 const original = await state.createSurface.mock.results[0]!.value;
216 const disposeOriginal = vi.spyOn(original, "dispose");
217 original.write("\x1b[>11u");
218 const key = (type: "keydown" | "keyup", init: KeyboardEventInit) =>
219 original.input.dispatchEvent(
220 new KeyboardEvent(type, { bubbles: true, cancelable: true, ...init }),
221 );
222 original.focus();
223 key("keydown", { key: "Control", code: "ControlLeft", ctrlKey: true });
224 key("keydown", { key: "d", code: "KeyD", ctrlKey: true });
225 await render(["original", "split"]);
226 expect(state.createSurface).toHaveBeenCalledTimes(2);
227 expect(container.querySelector("textarea")).toBe(original.input);
228 expect(disposeOriginal).not.toHaveBeenCalled();
229 const split = await state.createSurface.mock.results[1]!.value;
230 const disposeSplit = vi.spyOn(split, "dispose");
231 original.focus();
232 key("keyup", { key: "d", code: "KeyD", ctrlKey: true });
233 key("keyup", { key: "Control", code: "ControlLeft" });
234​
235 key("keydown", { key: "b", code: "KeyB" });
236 composer.focus();
237 original.focus();
238 key("keydown", { key: "b", code: "KeyB", repeat: true });
239 key("keyup", { key: "b", code: "KeyB" });
240​
241 key("keydown", { key: "c", code: "KeyC" });
242 await render(["original"]);
243 expect(state.createSurface).toHaveBeenCalledTimes(2);
244 expect(container.querySelector("textarea")).toBe(original.input);
245 expect(disposeOriginal).not.toHaveBeenCalled();
246 expect(disposeSplit).toHaveBeenCalledOnce();
247 original.focus();
248 key("keyup", { key: "c", code: "KeyC" });
249 expect(output).toEqual([
250 ["\x1b[57442;5u", "\x1b[57442;1:3u", "\x1b[98u", "\x1b[98;1:3u", "\x1b[99u", "\x1b[99;1:3u"],
251 [],
252 ]);
253 } finally {
254 window.removeEventListener("keydown", consumeShortcut, { capture: true });
255 composer.remove();
256 }
257});