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

ChatMarkdown.permissions.browser.test.tsx

282 lines9.6 KB

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 { expect, it, vi } from "vite-plus/test";
12​
13import { act, render } from "../../test/render";
14import { useRightPanelStore } from "../rightPanelStore";
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 linkedPullRequest: null as ThreadLinkedPullRequest | null,
27}));
28​
29vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
30 ...(await original()),
31 useAtomQueryRunner: (() => state.search) as never,
32}));
33vi.mock(import("../state/use-atom-command"), async (original) => {
34 const { threadEnvironment } = await import("../state/threads");
35 return {
36 ...(await original()),
37 useAtomCommand: ((command: unknown) =>
38 command === threadEnvironment.updateMetadata
39 ? state.updateMetadata
40 : state.openEditor) as never,
41 };
42});
43vi.mock(import("../state/session"), async (original) => {
44 const { useSyncExternalStore } = await import("react");
45 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
46 id !== null &&
47 (scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
48 return {
49 ...(await original()),
50 readEnvironmentScope,
51 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
52 useSyncExternalStore(
53 (listener) => {
54 state.listeners.add(listener);
55 return () => state.listeners.delete(listener);
56 },
57 () => readEnvironmentScope(id, scope),
58 ),
59 };
60});
61// Atoms derived from the server config run in the real registry over this config.
62vi.mock(import("../state/server"), async (original) => {
63 const actual = await original();
64 const { Atom } = await import("effect/reactivity");
65 const config = Atom.make(() => serverConfig);
66 return {
67 ...actual,
68 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
69 environmentServerConfigsAtom: Atom.make(
70 () => new Map([[threadRef.environmentId, serverConfig]]),
71 ) as never,
72 };
73});
74vi.mock(import("../state/entities"), async (original) => ({
75 ...(await original()),
76 readThreadShell: (() => ({ linkedPullRequest: state.linkedPullRequest })) as never,
77 useProjects: (() => [
78 { id: linkedPullRequest.projectId, environmentId: threadRef.environmentId },
79 ]) as never,
80}));
81vi.mock(import("../remoteOpen"), async (original) => ({
82 ...(await original()),
83 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
84}));
85vi.mock(import("../hooks/useLocalStorage"), async (original) => ({
86 ...(await original()),
87 useLocalStorage: (() => ["vscode", vi.fn()]) as never,
88 getLocalStorageItem: (() => "vscode") as never,
89}));
90vi.mock(import("../localApi"), async (original) => ({
91 ...(await original()),
92 readLocalApi: () =>
93 ({
94 contextMenu: { show: state.choose },
95 shell: { openExternal: state.openExternal },
96 }) as never,
97}));
98vi.mock(import("~/lib/openPullRequestLink"), async (original) => ({
99 ...(await original()),
100 resolvePullRequestPreviewTarget: () => null,
101 findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
102 matchesLinkedPullRequestUrl: (candidate: ThreadLinkedPullRequest, href: string) =>
103 candidate.url === href,
104 parseChangeRequestUrl: ((href: string) =>
105 href === linkedPullRequest.url
106 ? {
107 host: "github.com",
108 repository: linkedPullRequest.repository,
109 number: linkedPullRequest.number,
110 }
111 : null) as never,
112}));
113​
114import ChatMarkdown from "./ChatMarkdown";
115​
116const threadRef = {
117 environmentId: EnvironmentId.make("selected"),
118 threadId: ThreadId.make("thread"),
119};
120const linkedPullRequest: ThreadLinkedPullRequest = {
121 projectId: ProjectId.make("project"),
122 repository: "example/repo",
123 number: 42,
124 url: "https://github.com/example/repo/pull/42",
125};
126const serverConfig = {
127 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
128 shellRevealInFileManager: true,
129 shellRevealInFileManagerKind: "xdg-open",
130 environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
131};
132​
133function setup() {
134 using stack = new DisposableStack();
135 state.allowed = true;
136 state.listeners.clear();
137 state.linkedPullRequest = null;
138 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
139 state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
140 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
141 state.choose.mockReset().mockResolvedValue(null);
142 state.openFile.mockReset();
143 state.openExternal.mockReset().mockResolvedValue(undefined);
144 state.copy.mockReset().mockResolvedValue(undefined);
145 const { openFile } = useRightPanelStore.getState();
146 useRightPanelStore.setState({ openFile: state.openFile });
147 stack.defer(() => useRightPanelStore.setState({ openFile }));
148 stack.use(vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy));
149 stack.use(
150 vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
151 const item = items[0]!;
152 await state.copy(await (await item.getType("text/plain")).text());
153 }),
154 );
155 return stack.move();
157​
158async function renderMarkdown(text: string) {
159 const screen = await render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
160 const anchor = () => screen.container.querySelector("a")!;
161 return Object.assign(screen, {
162 anchor,
163 openContextMenu: () =>
164 act(async () => {
165 anchor().dispatchEvent(
166 new MouseEvent("contextmenu", {
167 bubbles: true,
168 cancelable: true,
169 clientX: 10,
170 clientY: 10,
171 }),
172 );
173 }),
174 });
176​
177function offeredActions() {
178 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
180​
181async function setAllowed(allowed: boolean) {
182 await act(async () => {
183 state.allowed = allowed;
184 for (const listener of state.listeners) listener();
185 });
187​
188it("removes host actions after revocation while keeping file preview and copying", async () => {
189 using _setup = setup();
190 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
191 await screen.openContextMenu();
192 expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
193 await setAllowed(false);
194 state.choose.mockResolvedValue("copy-full");
195 await screen.openContextMenu();
196 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
197 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
198 await act(async () => screen.anchor().click());
199 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
200 expect(state.openEditor).not.toHaveBeenCalled();
201});
202​
203it("does not launch an editor after revocation during a native context menu", async () => {
204 using _setup = setup();
205 let choose: (action: string) => void = () => {
206 throw new Error("Menu not opened");
207 };
208 state.choose.mockImplementationOnce(
209 () =>
210 new Promise<string>((resolve) => {
211 choose = resolve;
212 }),
213 );
214 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
215 await screen.openContextMenu();
216 expect(offeredActions()).toContain("open");
217 await act(async () => {
218 state.allowed = false;
219 choose("open");
220 });
221 expect(state.openEditor).not.toHaveBeenCalled();
222});
223​
224it("does not reveal a file after revocation during its workspace lookup", async () => {
225 using _setup = setup();
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 using screen = await renderMarkdown("[Readme](readme.md)");
237 await screen.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(["link-to-thread", "unlink-from-thread"])(
247 "rechecks %s after a native context menu returns",
248 async (action) => {
249 using _setup = setup();
250 state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
251 let choose: (action: string) => void = () => {
252 throw new Error("Menu not opened");
253 };
254 state.choose.mockImplementationOnce(
255 () =>
256 new Promise<string>((resolve) => {
257 choose = resolve;
258 }),
259 );
260 await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
261 await screen.openContextMenu();
262 expect(offeredActions()).toContain(action);
263 await act(async () => {
264 state.allowed = false;
265 choose(action);
266 });
267 expect(state.updateMetadata).not.toHaveBeenCalled();
268​
269 await setAllowed(true);
270 state.choose.mockResolvedValue(action);
271 await screen.openContextMenu();
272 await vi.waitFor(() =>
273 expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
274 environmentId: threadRef.environmentId,
275 input: {
276 threadId: threadRef.threadId,
277 linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
278 },
279 }),
280 );
281 },
282);