Open History to see the last commit
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 pullRequests: [] as ThreadPullRequestLink[],
29}));
30
31vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
32 ...(await original()),
33 useAtomQueryRunner: (() => state.search) as never,
34}));
35vi.mock(import("../state/use-atom-command"), async (original) => {
36 const { threadEnvironment } = await import("../state/threads");
37 return {
38 ...(await original()),
39 useAtomCommand: ((command: unknown) =>
40 command === threadEnvironment.linkPullRequest
41 ? state.link
42 : command === threadEnvironment.unlinkPullRequest
43 ? state.unlink
44 : state.openEditor) as never,
45 };
46});
47vi.mock(import("../state/session"), async (original) => {
48 const { useSyncExternalStore } = await import("react");
49 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
50 id !== null &&
51 (scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
52 return {
53 ...(await original()),
54 readEnvironmentScope,
55 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
56 useSyncExternalStore(
57 (listener) => {
58 state.listeners.add(listener);
59 return () => state.listeners.delete(listener);
60 },
61 () => readEnvironmentScope(id, scope),
62 ),
63 };
64});
65vi.mock(import("../state/server"), async (original) => {
66 const actual = await original();
67 const { Atom } = await import("effect/reactivity");
68 const config = Atom.make(() => serverConfig);
69 return {
70 ...actual,
71 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
72 environmentServerConfigsAtom: Atom.make(
73 () => new Map([[threadRef.environmentId, serverConfig]]),
74 ) as never,
75 };
76});
77vi.mock(import("../state/entities"), async (original) => ({
78 ...(await original()),
79 readThreadShell: (() => ({ pullRequests: state.pullRequests })) as never,
80 useProjects: (() => [{ id: projectId, environmentId: threadRef.environmentId }]) as never,
81}));
82vi.mock(import("../remoteOpen"), async (original) => ({
83 ...(await original()),
84 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
85}));
86vi.mock(import("../hooks/useLocalStorage"), async (original) => ({
87 ...(await original()),
88 useLocalStorage: (() => ["vscode", vi.fn()]) as never,
89 getLocalStorageItem: (() => "vscode") as never,
90}));
91vi.mock(import("../localApi"), async (original) => ({
92 ...(await original()),
93 readLocalApi: () =>
94 ({
95 contextMenu: { show: state.choose },
96 shell: { openExternal: state.openExternal },
97 }) as never,
98}));
99vi.mock(import("../env"), async (original) => ({ ...(await original()), isElectron: true }));
100vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({
101 ...(await original()),
102 resolvePullRequestPreviewTarget: () => null,
103 findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
104}));
105
106import ChatMarkdown from "./ChatMarkdown";
107import { MarkdownFileLink } from "./chat/MarkdownFileLink";
108
109const threadRef = {
110 environmentId: EnvironmentId.make("selected"),
111 threadId: ThreadId.make("thread"),
112};
113const projectId = ProjectId.make("project");
114const linkedPullRequest: ThreadPullRequestLink = {
115 host: "github.com",
116 repository: "example/repo",
117 number: 42,
118 url: "https://github.com/example/repo/pull/42",
119 source: "manual",
120 linkedAt: "2026-09-08T00:00:00.000Z",
121 snapshot: null,
122 stack: null,
123};
124const serverConfig = {
125 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
126 shellRevealInFileManager: true,
127 shellRevealInFileManagerKind: "xdg-open",
128 environment: { platform: { os: "linux" }, capabilities: {} },
129};
130
131function setup() {
132 using stack = new DisposableStack();
133 state.allowed = true;
134 state.listeners.clear();
135 state.pullRequests = [];
136 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
137 state.link.mockReset().mockResolvedValue(AsyncResult.success(undefined));
138 state.unlink.mockReset().mockResolvedValue(AsyncResult.success(undefined));
139 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
140 state.choose.mockReset().mockResolvedValue(null);
141 state.openFile.mockReset();
142 state.openExternal.mockReset().mockResolvedValue(undefined);
143 state.copy.mockReset().mockResolvedValue(undefined);
144 const { openFile } = useRightPanelStore.getState();
145 useRightPanelStore.setState({ openFile: state.openFile });
146 stack.defer(() => useRightPanelStore.setState({ openFile }));
147 stack.use(vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy));
148 stack.use(
149 vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
150 const item = items[0]!;
151 await state.copy(await (await item.getType("text/plain")).text());
152 }),
153 );
154 return stack.move();
155}
156
157async function renderMarkdown(text: string) {
158 const screen = await render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
159 const anchor = () => screen.container.querySelector("a")!;
160 return Object.assign(screen, {
161 anchor,
162 openContextMenu: () =>
163 act(async () => {
164 anchor().dispatchEvent(
165 new MouseEvent("contextmenu", {
166 bubbles: true,
167 cancelable: true,
168 clientX: 10,
169 clientY: 10,
170 }),
171 );
172 }),
173 });
174}
175
176function offeredActions() {
177 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
178}
179
180async function setAllowed(allowed: boolean) {
181 await act(async () => {
182 state.allowed = allowed;
183 for (const listener of state.listeners) listener();
184 });
185}
186
187it("removes host actions after revocation while keeping file preview and copying", async () => {
188 using _setup = setup();
189 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
190 await screen.openContextMenu();
191 expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
192 await setAllowed(false);
193 state.choose.mockResolvedValue("copy-full");
194 await screen.openContextMenu();
195 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
196 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
197 await act(async () => screen.anchor().click());
198 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
199 expect(state.openEditor).not.toHaveBeenCalled();
200});
201
202it.each(["[Docs](https://example.com/docs)", "[Readme](docs/readme.md)"])(
203 "tells the native menu for %s whether the keyboard opened it",
204 async (text) => {
205 using _setup = setup();
206 await using screen = await renderMarkdown(text);
207 screen.anchor().focus();
208 await userEvent.keyboard("{Shift>}{F10}{/Shift}");
209 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("keyboard"));
210 await userEvent.click(screen.anchor(), { button: "right" });
211 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse"));
212 },
213);
214
215it("does not launch an editor after revocation during a native context menu", async () => {
216 using _setup = setup();
217 let choose: (action: string) => void = () => {
218 throw new Error("Menu not opened");
219 };
220 state.choose.mockImplementationOnce(
221 () =>
222 new Promise<string>((resolve) => {
223 choose = resolve;
224 }),
225 );
226 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
227 await screen.openContextMenu();
228 expect(offeredActions()).toContain("open");
229 await act(async () => {
230 state.allowed = false;
231 choose("open");
232 });
233 expect(state.openEditor).not.toHaveBeenCalled();
234});
235
236it("does not reveal a file after revocation during its workspace lookup", async () => {
237 using _setup = setup();
238 let finishLookup: () => void = () => {
239 throw new Error("Lookup not started");
240 };
241 state.search.mockImplementationOnce(
242 () =>
243 new Promise((resolve) => {
244 finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
245 }),
246 );
247 state.choose.mockResolvedValue("reveal");
248 await using screen = await renderMarkdown("[Readme](readme.md)");
249 await screen.openContextMenu();
250 expect(state.search).toHaveBeenCalledOnce();
251 await act(async () => {
252 state.allowed = false;
253 finishLookup();
254 });
255 expect(state.openEditor).not.toHaveBeenCalled();
256});
257
258it.each(["link-to-thread", "unlink-from-thread"])(
259 "rechecks %s after a native context menu returns",
260 async (action) => {
261 using _setup = setup();
262 state.pullRequests = action === "unlink-from-thread" ? [linkedPullRequest] : [];
263 const command = action === "link-to-thread" ? state.link : state.unlink;
264 let choose: (action: string) => void = () => {
265 throw new Error("Menu not opened");
266 };
267 state.choose.mockImplementationOnce(
268 () =>
269 new Promise<string>((resolve) => {
270 choose = resolve;
271 }),
272 );
273 await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
274 await screen.openContextMenu();
275 expect(offeredActions()).toContain(action);
276 await act(async () => {
277 state.allowed = false;
278 choose(action);
279 });
280 expect(command).not.toHaveBeenCalled();
281
282 await setAllowed(true);
283 state.choose.mockResolvedValue(action);
284 await screen.openContextMenu();
285 await vi.waitFor(() =>
286 expect(command).toHaveBeenCalledExactlyOnceWith({
287 environmentId: threadRef.environmentId,
288 input: expect.objectContaining({
289 threadId: threadRef.threadId,
290 repository: "example/repo",
291 number: 42,
292 }),
293 }),
294 );
295 },
296);
297
298it("preserves keyboard activation of a file-options button", async () => {
299 using _setup = setup();
300 await using screen = await render(
301 <MarkdownFileLink
302 environmentId={null}
303 href="readme.md"
304 targetPath="readme.md"
305 iconPath="readme.md"
306 workspaceRelativePath="readme.md"
307 panelPath={null}
308 label="Readme"
309 copyMarkdown="[Readme](readme.md)"
310 theme="dark"
311 onOpenInPanel={vi.fn()}
312 resolveDragPath={async () => "/work/readme.md"}
313 resolveCopyPaths={async () => ({ relativePath: "readme.md", fullPath: "/work/readme.md" })}
314 openInEditorMenuLabel="Open in editor"
315 />,
316 );
317 const button = screen.container.querySelector("button")!;
318 button.focus();
319 for (const key of ["{Enter}", " "]) {
320 await userEvent.keyboard(key);
321 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("keyboard"));
322 state.choose.mockClear();
323 }
324 await userEvent.click(button);
325 await vi.waitFor(() => expect(state.choose.mock.lastCall?.[2]).toBe("mouse"));
326});
327
328it("opens an editor link over the desktop bridge on a click and on a middle-click", async () => {
329 using _setup = setup();
330 const href = "vscode://file/work/docs/readme.md:3";
331 await using screen = await renderMarkdown(`[Open in editor](${href})`);
332 for (const [type, button] of [
333 ["click", 0],
334 ["auxclick", 1],
335 ] as const) {
336 const event = new MouseEvent(type, { bubbles: true, cancelable: true, button });
337 await act(async () => screen.anchor().dispatchEvent(event));
338 expect(event.defaultPrevented).toBe(true);
339 expect(state.openExternal).toHaveBeenLastCalledWith(href);
340 }
341 expect(state.openExternal).toHaveBeenCalledTimes(2);
342});