Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 EnvironmentId,
4 ProjectId,
5 ThreadId,
6 type AuthEnvironmentScope,
7 type EditorId,
8 type ThreadLinkedPullRequest,
9} from "@t3tools/contracts";
10import { AsyncResult } from "effect/reactivity";
11import { act } from "react";
12import { createRoot, type Root } from "react-dom/client";
13import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
14
15import { useRightPanelStore } from "../rightPanelStore";
16
17const state = vi.hoisted(() => ({
18 allowed: true,
19 listeners: new Set<() => void>(),
20 openEditor: vi.fn(),
21 updateMetadata: vi.fn(),
22 search: vi.fn(),
23 choose: vi.fn(),
24 openFile: vi.fn(),
25 openExternal: vi.fn(),
26 copy: vi.fn(),
27 linkedPullRequest: null as ThreadLinkedPullRequest | null,
28}));
29
30vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
31 ...(await original()),
32 useAtomQueryRunner: (() => state.search) as never,
33}));
34vi.mock(import("../state/use-atom-command"), async (original) => {
35 const { threadEnvironment } = await import("../state/threads");
36 return {
37 ...(await original()),
38 useAtomCommand: ((command: unknown) =>
39 command === threadEnvironment.updateMetadata
40 ? state.updateMetadata
41 : state.openEditor) as never,
42 };
43});
44vi.mock(import("../state/session"), async (original) => {
45 const { useSyncExternalStore } = await import("react");
46 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
47 id !== null &&
48 (scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
49 return {
50 ...(await original()),
51 readEnvironmentScope,
52 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
53 useSyncExternalStore(
54 (listener) => {
55 state.listeners.add(listener);
56 return () => state.listeners.delete(listener);
57 },
58 () => readEnvironmentScope(id, scope),
59 ),
60 };
61});
62// Atoms derived from the server config run in the real registry over this config.
63vi.mock(import("../state/server"), async (original) => {
64 const actual = await original();
65 const { Atom } = await import("effect/reactivity");
66 const config = Atom.make(() => serverConfig);
67 return {
68 ...actual,
69 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
70 environmentServerConfigsAtom: Atom.make(
71 () => new Map([[threadRef.environmentId, serverConfig]]),
72 ) as never,
73 };
74});
75vi.mock(import("../state/entities"), async (original) => ({
76 ...(await original()),
77 readThreadShell: (() => ({ linkedPullRequest: state.linkedPullRequest })) as never,
78 useProjects: (() => [
79 { id: linkedPullRequest.projectId, environmentId: threadRef.environmentId },
80 ]) 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("~/lib/openPullRequestLink"), async (original) => ({
100 ...(await original()),
101 resolvePullRequestPreviewTarget: () => null,
102 findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
103 matchesLinkedPullRequestUrl: (candidate: ThreadLinkedPullRequest, href: string) =>
104 candidate.url === href,
105 parseChangeRequestUrl: ((href: string) =>
106 href === linkedPullRequest.url
107 ? {
108 host: "github.com",
109 repository: linkedPullRequest.repository,
110 number: linkedPullRequest.number,
111 }
112 : null) as never,
113}));
114
115import ChatMarkdown from "./ChatMarkdown";
116
117const threadRef = {
118 environmentId: EnvironmentId.make("selected"),
119 threadId: ThreadId.make("thread"),
120};
121const linkedPullRequest: ThreadLinkedPullRequest = {
122 projectId: ProjectId.make("project"),
123 repository: "example/repo",
124 number: 42,
125 url: "https://github.com/example/repo/pull/42",
126};
127const serverConfig = {
128 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
129 shellRevealInFileManager: true,
130 shellRevealInFileManagerKind: "xdg-open",
131 environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
132};
133const roots: Root[] = [];
134let container: HTMLDivElement;
135
136beforeEach(() => {
137 state.allowed = true;
138 state.listeners.clear();
139 state.linkedPullRequest = null;
140 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
141 state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
142 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
143 state.choose.mockReset().mockResolvedValue(null);
144 state.openFile.mockReset();
145 state.openExternal.mockReset().mockResolvedValue(undefined);
146 state.copy.mockReset().mockResolvedValue(undefined);
147 useRightPanelStore.setState({ openFile: state.openFile });
148 vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy);
149 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
150});
151
152afterEach(async () => {
153 for (const root of roots.splice(0)) await act(async () => root.unmount());
154 document.body.replaceChildren();
155 vi.restoreAllMocks();
156 vi.unstubAllGlobals();
157});
158
159async function renderMarkdown(text: string) {
160 container = document.body.appendChild(document.createElement("div"));
161 const root = createRoot(container);
162 roots.push(root);
163 await act(async () =>
164 root.render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />),
165 );
166}
167
168function anchor() {
169 return container.querySelector("a")!;
170}
171
172async function openContextMenu() {
173 await act(async () => {
174 anchor().dispatchEvent(
175 new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }),
176 );
177 });
178}
179
180function offeredActions() {
181 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
182}
183
184async function setAllowed(allowed: boolean) {
185 await act(async () => {
186 state.allowed = allowed;
187 for (const listener of state.listeners) listener();
188 });
189}
190
191it("removes host actions after revocation while keeping file preview and copying", async () => {
192 await renderMarkdown("[Readme](docs/readme.md)");
193 await openContextMenu();
194 expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
195 await setAllowed(false);
196 state.choose.mockResolvedValue("copy-full");
197 await openContextMenu();
198 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
199 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
200 await act(async () => anchor().click());
201 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
202 expect(state.openEditor).not.toHaveBeenCalled();
203});
204
205it("does not launch an editor after revocation during a native context menu", async () => {
206 let choose: (action: string) => void = () => {
207 throw new Error("Menu not opened");
208 };
209 state.choose.mockImplementationOnce(
210 () =>
211 new Promise<string>((resolve) => {
212 choose = resolve;
213 }),
214 );
215 await renderMarkdown("[Readme](docs/readme.md)");
216 await openContextMenu();
217 expect(offeredActions()).toContain("open");
218 await act(async () => {
219 state.allowed = false;
220 choose("open");
221 });
222 expect(state.openEditor).not.toHaveBeenCalled();
223});
224
225it("does not reveal a file after revocation during its workspace lookup", async () => {
226 let finishLookup: () => void = () => {
227 throw new Error("Lookup not started");
228 };
229 state.search.mockImplementationOnce(
230 () =>
231 new Promise((resolve) => {
232 finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
233 }),
234 );
235 state.choose.mockResolvedValue("reveal");
236 await renderMarkdown("[Readme](readme.md)");
237 await openContextMenu();
238 expect(state.search).toHaveBeenCalledOnce();
239 await act(async () => {
240 state.allowed = false;
241 finishLookup();
242 });
243 expect(state.openEditor).not.toHaveBeenCalled();
244});
245
246it.each([false, true])(
247 "keeps PR links usable without offering metadata edits (linked=%s)",
248 async (linked) => {
249 state.allowed = false;
250 state.linkedPullRequest = linked ? linkedPullRequest : null;
251 state.choose.mockResolvedValue("open-external");
252 await renderMarkdown(`[Review](${linkedPullRequest.url})`);
253 await openContextMenu();
254 expect(offeredActions()).toEqual(["open-external", "copy-link"]);
255 await vi.waitFor(() => expect(state.openExternal).toHaveBeenCalledWith(linkedPullRequest.url));
256 expect(state.updateMetadata).not.toHaveBeenCalled();
257 },
258);
259
260it.each(["link-to-thread", "unlink-from-thread"])(
261 "rechecks %s after a native context menu returns",
262 async (action) => {
263 state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
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 renderMarkdown(`[Review](${linkedPullRequest.url})`);
274 await openContextMenu();
275 expect(offeredActions()).toContain(action);
276 await act(async () => {
277 state.allowed = false;
278 choose(action);
279 });
280 expect(state.updateMetadata).not.toHaveBeenCalled();
281
282 await setAllowed(true);
283 state.choose.mockResolvedValue(action);
284 await openContextMenu();
285 await vi.waitFor(() =>
286 expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
287 environmentId: threadRef.environmentId,
288 input: {
289 threadId: threadRef.threadId,
290 linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
291 },
292 }),
293 );
294 },
295);