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

ChatMarkdown.permissions.browser.test.tsx

412 lines14.8 KB

1import {
2 AuthOrchestrationOperateScope,
3 EnvironmentId,
4 ProjectId,
5 ThreadId,
6 type AuthEnvironmentScope,
7 type EditorId,
8 type ThreadPullRequestLink,
9} from "@t3tools/contracts";
10import { AsyncResult } from "effect/reactivity";
11import { expect, it, vi } from "vite-plus/test";
12import { userEvent } from "vite-plus/test/browser";
13​
14import { act, render } from "../../test/render";
15import { useRightPanelStore } from "../rightPanelStore";
16​
17const state = vi.hoisted(() => ({
18 allowed: true,
19 listeners: new Set<() => void>(),
20 openEditor: vi.fn(),
21 link: vi.fn(),
22 unlink: vi.fn(),
23 search: vi.fn(),
24 choose: vi.fn(),
25 openFile: vi.fn(),
26 openExternal: vi.fn(),
27 copy: vi.fn(),
28 download: vi.fn(),
29 pullRequests: [] as ThreadPullRequestLink[],
30}));
31​
32vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
33 ...(await original()),
34 useAtomQueryRunner: (() => state.search) as never,
35}));
36vi.mock(import("../state/use-atom-command"), async (original) => {
37 const { threadEnvironment } = await import("../state/threads");
38 return {
39 ...(await original()),
40 useAtomCommand: ((command: unknown) =>
41 command === threadEnvironment.linkPullRequest
42 ? state.link
43 : command === threadEnvironment.unlinkPullRequest
44 ? state.unlink
45 : state.openEditor) as never,
46 };
47});
48vi.mock(import("../state/session"), async (original) => {
49 const { useSyncExternalStore } = await import("react");
50 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
51 id !== null &&
52 (scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
53 return {
54 ...(await original()),
55 readEnvironmentScope,
56 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
57 useSyncExternalStore(
58 (listener) => {
59 state.listeners.add(listener);
60 return () => state.listeners.delete(listener);
61 },
62 () => readEnvironmentScope(id, scope),
63 ),
64 };
65});
66vi.mock(import("../state/server"), async (original) => {
67 const actual = await original();
68 const { Atom } = await import("effect/reactivity");
69 const config = Atom.make(() => serverConfig);
70 return {
71 ...actual,
72 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
73 environmentServerConfigsAtom: Atom.make(
74 () => new Map([[threadRef.environmentId, serverConfig]]),
75 ) as never,
76 };
77});
78vi.mock(import("../state/entities"), async (original) => ({
79 ...(await original()),
80 readThreadShell: (() => ({ pullRequests: state.pullRequests })) as never,
81 useProjects: (() => [{ id: projectId, environmentId: threadRef.environmentId }]) as never,
82}));
83vi.mock(import("../remoteOpen"), async (original) => ({
84 ...(await original()),
85 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
86}));
87vi.mock(import("../hooks/useLocalStorage"), async (original) => ({
88 ...(await original()),
89 useLocalStorage: (() => ["vscode", vi.fn()]) as never,
90 getLocalStorageItem: (() => "vscode") as never,
91}));
92vi.mock(import("../localApi"), async (original) => ({
93 ...(await original()),
94 readLocalApi: () =>
95 ({
96 contextMenu: { show: state.choose },
97 shell: { openExternal: state.openExternal },
98 }) as never,
99}));
100vi.mock(import("../hooks/useFileMetadata"), async (original) => ({
101 ...(await original()),
102 useFileMetadata: ((_id: unknown, path: string) =>
103 path.includes("user.ts")
104 ? null
105 : { kind: path.includes("src") ? "directory" : "file" }) as never,
106}));
107vi.mock(import("./files/useFileDownload"), () => ({ useFileDownload: () => state.download }));
108vi.mock(import("../env"), async (original) => ({ ...(await original()), isElectron: true }));
109// Desktop can forward this environment's ports: it runs on another machine.
110vi.mock(import("../state/portForwards"), async (original) => ({
111 ...(await original()),
112 canForwardPorts: () => true,
113 useForwardLocality: () => "remote" as const,
114 usePortForwards: () => [],
115 forwardPort: (async (environmentId: string, remotePort: number) => ({
116 environmentId,
117 remotePort,
118 localPort: 45000,
119 })) as never,
120}));
121vi.mock(import("../state/environments"), async (original) => ({
122 ...(await original()),
123 useEnvironment: (() => ({
124 connection: { phase: "connected" },
125 entry: { target: { _tag: "BearerConnectionTarget", connectionId: "saved:remote" } },
126 serverConfig: null,
127 })) as never,
128}));
129vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({
130 ...(await original()),
131 resolvePullRequestPreviewTarget: () => null,
132 findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
133}));
134​
135import ChatMarkdown from "./ChatMarkdown";
136import { MarkdownFileLink } from "./chat/MarkdownFileLink";
137​
138const threadRef = {
139 environmentId: EnvironmentId.make("selected"),
140 threadId: ThreadId.make("thread"),
141};
142const projectId = ProjectId.make("project");
143const linkedPullRequest: ThreadPullRequestLink = {
144 host: "github.com",
145 repository: "example/repo",
146 number: 42,
147 url: "https://github.com/example/repo/pull/42",
148 source: "manual",
149 linkedAt: "2026-09-08T00:00:00.000Z",
150 snapshot: null,
151 stack: null,
152};
153const serverConfig = {
154 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
155 shellRevealInFileManager: true,
156 shellRevealInFileManagerKind: "xdg-open",
157 environment: { platform: { os: "linux" }, capabilities: {} },
158};
159​
160function setup() {
161 using stack = new DisposableStack();
162 state.allowed = true;
163 state.listeners.clear();
164 state.pullRequests = [];
165 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
166 state.link.mockReset().mockResolvedValue(AsyncResult.success(undefined));
167 state.unlink.mockReset().mockResolvedValue(AsyncResult.success(undefined));
168 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
169 state.choose.mockReset().mockResolvedValue(null);
170 state.openFile.mockReset();
171 state.openExternal.mockReset().mockResolvedValue(undefined);
172 state.copy.mockReset().mockResolvedValue(undefined);
173 state.download.mockReset();
174 const { openFile } = useRightPanelStore.getState();
175 useRightPanelStore.setState({ openFile: state.openFile });
176 stack.defer(() => useRightPanelStore.setState({ openFile }));
177 stack.use(vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy));
178 stack.use(
179 vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
180 const item = items[0]!;
181 await state.copy(await (await item.getType("text/plain")).text());
182 }),
183 );
184 return stack.move();
186​
187async function renderMarkdown(text: string) {
188 const screen = await render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
189 const anchor = () => screen.container.querySelector("a")!;
190 return Object.assign(screen, {
191 anchor,
192 openContextMenu: () =>
193 act(async () => {
194 anchor().dispatchEvent(
195 new MouseEvent("contextmenu", {
196 bubbles: true,
197 cancelable: true,
198 clientX: 10,
199 clientY: 10,
200 }),
201 );
202 }),
203 });
205​
206function offeredActions() {
207 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
209​
210async function setAllowed(allowed: boolean) {
211 await act(async () => {
212 state.allowed = allowed;
213 for (const listener of state.listeners) listener();
214 });
216​
217it("removes host actions after revocation while keeping file preview and copying", async () => {
218 using _setup = setup();
219 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
220 await screen.openContextMenu();
221 expect(offeredActions()).toEqual(["open", "reveal", "download", "copy-relative", "copy-full"]);
222 await setAllowed(false);
223 state.choose.mockResolvedValue("download");
224 await screen.openContextMenu();
225 expect(offeredActions()).toEqual(["download", "copy-relative", "copy-full"]);
226 expect(state.download).toHaveBeenCalledWith("/work", expect.any(Promise));
227 await expect(state.download.mock.lastCall![1]).resolves.toBe("/work/docs/readme.md");
228 state.choose.mockResolvedValue("copy-full");
229 await screen.openContextMenu();
230 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
231 await act(async () => screen.anchor().click());
232 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
233 expect(state.openEditor).not.toHaveBeenCalled();
234});
235​
236it("offers download unless the link is a known folder", async () => {
237 using _setup = setup();
238 await using folder = await renderMarkdown("[Source](./src)");
239 await folder.openContextMenu();
240 expect(offeredActions()).not.toContain("download");
241 // A bare name the workspace lookup resolves elsewhere has no metadata at its literal path.
242 await using basename = await renderMarkdown("[user.ts](user.ts)");
243 await basename.openContextMenu();
244 expect(offeredActions()).toContain("download");
245});
246​
247it.each(["[Docs](https://example.com/docs)", "[Readme](docs/readme.md)"])(
248 "tells the native menu for %s whether the keyboard opened it",
249 async (text) => {
250 using _setup = setup();
251 await using screen = await renderMarkdown(text);
252 screen.anchor().focus();
253 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
254 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("keyboard"));
255 await userEvent.click(screen.anchor(), { button: "right" });
256 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse"));
257 },
258);
259​
260it("does not launch an editor after revocation during a native context menu", async () => {
261 using _setup = setup();
262 let choose: (action: string) => void = () => {
263 throw new Error("Menu not opened");
264 };
265 state.choose.mockImplementationOnce(
266 () =>
267 new Promise<string>((resolve) => {
268 choose = resolve;
269 }),
270 );
271 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
272 await screen.openContextMenu();
273 expect(offeredActions()).toContain("open");
274 await act(async () => {
275 state.allowed = false;
276 choose("open");
277 });
278 expect(state.openEditor).not.toHaveBeenCalled();
279});
280​
281it("does not reveal a file after revocation during its workspace lookup", async () => {
282 using _setup = setup();
283 let finishLookup: () => void = () => {
284 throw new Error("Lookup not started");
285 };
286 state.search.mockImplementationOnce(
287 () =>
288 new Promise((resolve) => {
289 finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
290 }),
291 );
292 state.choose.mockResolvedValue("reveal");
293 await using screen = await renderMarkdown("[Readme](readme.md)");
294 await screen.openContextMenu();
295 expect(state.search).toHaveBeenCalledOnce();
296 await act(async () => {
297 state.allowed = false;
298 finishLookup();
299 });
300 expect(state.openEditor).not.toHaveBeenCalled();
301});
302​
303it.each(["link-to-thread", "unlink-from-thread"])(
304 "rechecks %s after a native context menu returns",
305 async (action) => {
306 using _setup = setup();
307 state.pullRequests = action === "unlink-from-thread" ? [linkedPullRequest] : [];
308 const command = action === "link-to-thread" ? state.link : state.unlink;
309 let choose: (action: string) => void = () => {
310 throw new Error("Menu not opened");
311 };
312 state.choose.mockImplementationOnce(
313 () =>
314 new Promise<string>((resolve) => {
315 choose = resolve;
316 }),
317 );
318 await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
319 await screen.openContextMenu();
320 expect(offeredActions()).toContain(action);
321 await act(async () => {
322 state.allowed = false;
323 choose(action);
324 });
325 expect(command).not.toHaveBeenCalled();
326​
327 await setAllowed(true);
328 state.choose.mockResolvedValue(action);
329 await screen.openContextMenu();
330 await vi.waitFor(() =>
331 expect(command).toHaveBeenCalledExactlyOnceWith({
332 environmentId: threadRef.environmentId,
333 input: expect.objectContaining({
334 threadId: threadRef.threadId,
335 repository: "example/repo",
336 number: 42,
337 }),
338 }),
339 );
340 },
341);
342​
343it("preserves keyboard activation of a file-options button", async () => {
344 using _setup = setup();
345 await using screen = await render(
346 <MarkdownFileLink
347 environmentId={null}
348 href="readme.md"
349 targetPath="readme.md"
350 iconPath="readme.md"
351 workspaceRelativePath="readme.md"
352 panelPath={null}
353 label="Readme"
354 copyMarkdown="[Readme](readme.md)"
355 theme="dark"
356 onOpenInPanel={vi.fn()}
357 resolveDragPath={async () => "/work/readme.md"}
358 resolveCopyPaths={async () => ({ relativePath: "readme.md", fullPath: "/work/readme.md" })}
359 openInEditorMenuLabel="Open in editor"
360 />,
361 );
362 const button = screen.container.querySelector("button")!;
363 button.focus();
364 for (const key of ["{Enter}", " "]) {
365 await userEvent.keyboard(key);
366 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("keyboard"));
367 state.choose.mockClear();
368 }
369 await userEvent.click(button);
370 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse"));
371});
372​
373it("opens an editor link over the desktop bridge on a click and on a middle-click", async () => {
374 using _setup = setup();
375 const href = "vscode://file/work/docs/readme.md:3";
376 await using screen = await renderMarkdown(`[Open in editor](${href})`);
377 for (const [type, button] of [
378 ["click", 0],
379 ["auxclick", 1],
380 ] as const) {
381 const event = new MouseEvent(type, { bubbles: true, cancelable: true, button });
382 await act(async () => screen.anchor().dispatchEvent(event));
383 expect(event.defaultPrevented).toBe(true);
384 expect(state.openExternal).toHaveBeenLastCalledWith(href);
385 }
386 expect(state.openExternal).toHaveBeenCalledTimes(2);
387});
388​
389it("cancels middle-click navigation on a file link chip", async () => {
390 using _setup = setup();
391 await using screen = await renderMarkdown("[Readme](readme.md)");
392 const middle = new MouseEvent("auxclick", { bubbles: true, cancelable: true, button: 1 });
393 await act(async () => screen.anchor().dispatchEvent(middle));
394 expect(middle.defaultPrevented).toBe(true);
395});
396​
397it("opens a remote environment's localhost link in the system browser through a forward", async () => {
398 using _setup = setup();
399 await using screen = await renderMarkdown("[App](http://localhost:3000/docs?x=1#top)");
400 // Keeps the test page from following the link; React's handlers run before this.
401 const stopNavigation = (event: Event) => event.preventDefault();
402 window.addEventListener("click", stopNavigation);
403 try {
404 await userEvent.click(screen.anchor(), { modifiers: ["ControlOrMeta"] });
405 } finally {
406 window.removeEventListener("click", stopNavigation);
407 }
408 await vi.waitFor(() =>
409 expect(state.openExternal).toHaveBeenCalledWith("http://localhost:45000/docs?x=1#top"),
410 );
411 expect(state.openExternal).not.toHaveBeenCalledWith("http://localhost:3000/docs?x=1#top");
412});