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

ChatMarkdown.permissions.test.tsx

299 lines10.5 KB

1import {
2 AuthOrchestrationOperateScope,
3 EnvironmentId,
4 ProjectId,
5 ThreadId,
6 type AuthEnvironmentScope,
7 type EditorId,
8 type ThreadLinkedPullRequest,
9} from "@t3tools/contracts";
10import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
11import { AsyncResult } from "effect/reactivity";
12import { cloneElement, type ReactElement, type ReactNode } from "react";
13import { act, create, type ReactTestRenderer } from "react-test-renderer";
14import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
15​
16const state = vi.hoisted(() => ({
17 allowed: true,
18 listeners: new Set<() => void>(),
19 openEditor: vi.fn(),
20 updateMetadata: vi.fn(),
21 search: vi.fn(),
22 choose: vi.fn(),
23 openFile: vi.fn(),
24 openExternal: vi.fn(),
25 copy: vi.fn(),
26 toast: vi.fn(),
27 linkedPullRequest: null as ThreadLinkedPullRequest | null,
28}));
29​
30vi.mock("@effect/atom-react", () => ({ useAtomValue: () => serverConfig }));
31vi.mock("../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
32vi.mock("../hooks/useSettings", () => ({
33 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
34 useClientSettings: (select?: (value: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
35 select ? select(DEFAULT_CLIENT_SETTINGS) : DEFAULT_CLIENT_SETTINGS,
36}));
37vi.mock("./ui/tooltip", () => ({
38 Tooltip: ({ children }: { children: ReactNode }) => children,
39 TooltipTrigger: ({ render, children }: { render: ReactElement; children?: ReactNode }) =>
40 children === undefined ? render : cloneElement(render, undefined, children),
41 TooltipPopup: () => null,
42}));
43vi.mock("./chat/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
44vi.mock("./ui/toast", () => ({
45 toastManager: { add: state.toast },
46 stackedThreadToast: (value: unknown) => value,
47}));
48vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.search }));
49vi.mock("../state/use-atom-command", () => ({
50 useAtomCommand: (command: string) =>
51 command === "updateMetadata" ? state.updateMetadata : state.openEditor,
52}));
53vi.mock("../state/session", async () => {
54 const { useSyncExternalStore } = await import("react");
55 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
56 id !== null &&
57 (scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
58 return {
59 // Asset atoms read these at module scope; the markdown tests only exercise
60 // the task grant.
61 environmentSession: {
62 sessionStateAtom: () => ({}),
63 preparedConnectionValueAtom: () => ({}),
64 },
65 readEnvironmentScope,
66 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
67 useSyncExternalStore(
68 (listener) => {
69 state.listeners.add(listener);
70 return () => state.listeners.delete(listener);
71 },
72 () => readEnvironmentScope(id, scope),
73 ),
74 usePreparedConnection: () => ({ _tag: "None" }),
75 };
76});
77vi.mock("../state/server", () => ({
78 serverEnvironment: { configValueAtom: () => "config" },
79}));
80vi.mock("../state/threads", () => ({
81 threadEnvironment: { updateMetadata: "updateMetadata" },
82}));
83vi.mock("../state/entities", () => ({
84 readEnvironmentSupportsServerBrowser: () => false,
85 useServerConfigs: () => new Map([[threadRef.environmentId, serverConfig]]),
86 readThreadShell: () => ({ linkedPullRequest: state.linkedPullRequest }),
87 useProjects: () => [{ id: linkedPullRequest.projectId, environmentId: threadRef.environmentId }],
88}));
89vi.mock("../rightPanelStore", () => ({
90 useRightPanelStore: { getState: () => ({ openFile: state.openFile }) },
91}));
92vi.mock("../remoteOpen", () => ({
93 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }),
94}));
95vi.mock("../hooks/useLocalStorage", () => ({
96 useLocalStorage: () => ["vscode", vi.fn()],
97 getLocalStorageItem: () => "vscode",
98 setLocalStorageItem: vi.fn(),
99}));
100vi.mock("../hooks/useCopyToClipboard", () => ({
101 writeTextToClipboard: state.copy,
102 useCopyToClipboard: () => ({ copyToClipboard: state.copy, isCopied: false }),
103}));
104vi.mock("../localApi", () => ({
105 readLocalApi: () => ({
106 contextMenu: { show: state.choose },
107 shell: { openExternal: state.openExternal },
108 }),
109}));
110vi.mock("~/lib/openPullRequestLink", () => ({
111 resolvePullRequestPreviewTarget: () => null,
112 findProjectForChangeRequest: (projects: readonly { id: ProjectId }[]) => projects[0],
113 matchesLinkedPullRequestUrl: (candidate: ThreadLinkedPullRequest, href: string) =>
114 candidate.url === href,
115 parseChangeRequestUrl: (href: string) =>
116 href === linkedPullRequest.url
117 ? {
118 host: "github.com",
119 repository: linkedPullRequest.repository,
120 number: linkedPullRequest.number,
121 }
122 : null,
123 useOpenChangeRequestLink: () => vi.fn(),
124}));
125​
126import ChatMarkdown from "./ChatMarkdown";
127​
128const threadRef = {
129 environmentId: EnvironmentId.make("selected"),
130 threadId: ThreadId.make("thread"),
131};
132const linkedPullRequest: ThreadLinkedPullRequest = {
133 projectId: ProjectId.make("project"),
134 repository: "example/repo",
135 number: 42,
136 url: "https://github.com/example/repo/pull/42",
137};
138const serverConfig = {
139 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
140 shellRevealInFileManager: true,
141 shellRevealInFileManagerKind: "xdg-open",
142 environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
143};
144let renderer: ReactTestRenderer | undefined;
145​
146beforeEach(() => {
147 state.allowed = true;
148 state.listeners.clear();
149 state.linkedPullRequest = null;
150 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
151 state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
152 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
153 state.choose.mockReset().mockResolvedValue(null);
154 state.openFile.mockReset();
155 state.openExternal.mockReset().mockResolvedValue(undefined);
156 state.copy.mockReset().mockResolvedValue(undefined);
157 state.toast.mockReset();
158 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
159 vi.stubGlobal("window", {});
160 vi.stubGlobal("navigator", { clipboard: { writeText: state.copy } });
161});
162​
163afterEach(async () => {
164 await act(async () => renderer?.unmount());
165 renderer = undefined;
166 vi.unstubAllGlobals();
167});
168​
169async function renderMarkdown(text: string) {
170 await act(async () => {
171 renderer = create(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
172 });
174​
175function menuEvent() {
176 return { preventDefault: vi.fn(), stopPropagation: vi.fn(), clientX: 10, clientY: 10 };
178​
179function anchor() {
180 return renderer!.root.findByType("a");
182​
183async function openContextMenu() {
184 await act(async () => anchor().props.onContextMenu(menuEvent()));
186​
187function offeredActions() {
188 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
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 act(async () => {
196 state.allowed = false;
197 for (const listener of state.listeners) listener();
198 });
199 state.choose.mockResolvedValue("copy-full");
200 await openContextMenu();
201 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
202 expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md");
203 await act(async () => anchor().props.onClick(menuEvent()));
204 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
205 expect(state.openEditor).not.toHaveBeenCalled();
206});
207​
208it("does not launch an editor after revocation during a native context menu", async () => {
209 let choose: (action: string) => void = () => {
210 throw new Error("Menu not opened");
211 };
212 state.choose.mockImplementationOnce(
213 () =>
214 new Promise<string>((resolve) => {
215 choose = resolve;
216 }),
217 );
218 await renderMarkdown("[Readme](docs/readme.md)");
219 await openContextMenu();
220 expect(offeredActions()).toContain("open");
221 await act(async () => {
222 state.allowed = false;
223 choose("open");
224 });
225 expect(state.openEditor).not.toHaveBeenCalled();
226});
227​
228it("does not reveal a file after revocation during its workspace lookup", async () => {
229 let finishLookup: () => void = () => {
230 throw new Error("Lookup not started");
231 };
232 state.search.mockImplementationOnce(
233 () =>
234 new Promise((resolve) => {
235 finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
236 }),
237 );
238 state.choose.mockResolvedValue("reveal");
239 await renderMarkdown("[Readme](readme.md)");
240 await openContextMenu();
241 expect(state.search).toHaveBeenCalledOnce();
242 await act(async () => {
243 state.allowed = false;
244 finishLookup();
245 });
246 expect(state.openEditor).not.toHaveBeenCalled();
247});
248​
249it.each([false, true])(
250 "keeps PR links usable without offering metadata edits (linked=%s)",
251 async (linked) => {
252 state.allowed = false;
253 state.linkedPullRequest = linked ? linkedPullRequest : null;
254 state.choose.mockResolvedValue("open-external");
255 await renderMarkdown(`[Review](${linkedPullRequest.url})`);
256 await openContextMenu();
257 expect(offeredActions()).toEqual(["open-external", "copy-link"]);
258 expect(state.openExternal).toHaveBeenCalledWith(linkedPullRequest.url);
259 expect(state.updateMetadata).not.toHaveBeenCalled();
260 },
261);
262​
263it.each(["link-to-thread", "unlink-from-thread"])(
264 "rechecks %s after a native context menu returns",
265 async (action) => {
266 state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
267 let choose: (action: string) => void = () => {
268 throw new Error("Menu not opened");
269 };
270 state.choose.mockImplementationOnce(
271 () =>
272 new Promise<string>((resolve) => {
273 choose = resolve;
274 }),
275 );
276 await renderMarkdown(`[Review](${linkedPullRequest.url})`);
277 await openContextMenu();
278 expect(offeredActions()).toContain(action);
279 await act(async () => {
280 state.allowed = false;
281 choose(action);
282 });
283 expect(state.updateMetadata).not.toHaveBeenCalled();
284​
285 await act(async () => {
286 state.allowed = true;
287 for (const listener of state.listeners) listener();
288 });
289 state.choose.mockResolvedValue(action);
290 await openContextMenu();
291 expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
292 environmentId: threadRef.environmentId,
293 input: {
294 threadId: threadRef.threadId,
295 linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
296 },
297 });
298 },
299);