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

ChatMarkdown.permissions.browser.test.tsx

272 lines9.2 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("@t3tools/client-runtime/change-request-links"), async (original) => ({
99 ...(await original()),
100 resolvePullRequestPreviewTarget: () => null,
101 findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
102}));
103​
104import ChatMarkdown from "./ChatMarkdown";
105​
106const threadRef = {
107 environmentId: EnvironmentId.make("selected"),
108 threadId: ThreadId.make("thread"),
109};
110const linkedPullRequest: ThreadLinkedPullRequest = {
111 projectId: ProjectId.make("project"),
112 repository: "example/repo",
113 number: 42,
114 url: "https://github.com/example/repo/pull/42",
115};
116const serverConfig = {
117 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
118 shellRevealInFileManager: true,
119 shellRevealInFileManagerKind: "xdg-open",
120 environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
121};
122​
123function setup() {
124 using stack = new DisposableStack();
125 state.allowed = true;
126 state.listeners.clear();
127 state.linkedPullRequest = null;
128 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
129 state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
130 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
131 state.choose.mockReset().mockResolvedValue(null);
132 state.openFile.mockReset();
133 state.openExternal.mockReset().mockResolvedValue(undefined);
134 state.copy.mockReset().mockResolvedValue(undefined);
135 const { openFile } = useRightPanelStore.getState();
136 useRightPanelStore.setState({ openFile: state.openFile });
137 stack.defer(() => useRightPanelStore.setState({ openFile }));
138 stack.use(vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy));
139 stack.use(
140 vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
141 const item = items[0]!;
142 await state.copy(await (await item.getType("text/plain")).text());
143 }),
144 );
145 return stack.move();
147​
148async function renderMarkdown(text: string) {
149 const screen = await render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
150 const anchor = () => screen.container.querySelector("a")!;
151 return Object.assign(screen, {
152 anchor,
153 openContextMenu: () =>
154 act(async () => {
155 anchor().dispatchEvent(
156 new MouseEvent("contextmenu", {
157 bubbles: true,
158 cancelable: true,
159 clientX: 10,
160 clientY: 10,
161 }),
162 );
163 }),
164 });
166​
167function offeredActions() {
168 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
170​
171async function setAllowed(allowed: boolean) {
172 await act(async () => {
173 state.allowed = allowed;
174 for (const listener of state.listeners) listener();
175 });
177​
178it("removes host actions after revocation while keeping file preview and copying", async () => {
179 using _setup = setup();
180 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
181 await screen.openContextMenu();
182 expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
183 await setAllowed(false);
184 state.choose.mockResolvedValue("copy-full");
185 await screen.openContextMenu();
186 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
187 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
188 await act(async () => screen.anchor().click());
189 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
190 expect(state.openEditor).not.toHaveBeenCalled();
191});
192​
193it("does not launch an editor after revocation during a native context menu", async () => {
194 using _setup = setup();
195 let choose: (action: string) => void = () => {
196 throw new Error("Menu not opened");
197 };
198 state.choose.mockImplementationOnce(
199 () =>
200 new Promise<string>((resolve) => {
201 choose = resolve;
202 }),
203 );
204 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
205 await screen.openContextMenu();
206 expect(offeredActions()).toContain("open");
207 await act(async () => {
208 state.allowed = false;
209 choose("open");
210 });
211 expect(state.openEditor).not.toHaveBeenCalled();
212});
213​
214it("does not reveal a file after revocation during its workspace lookup", async () => {
215 using _setup = setup();
216 let finishLookup: () => void = () => {
217 throw new Error("Lookup not started");
218 };
219 state.search.mockImplementationOnce(
220 () =>
221 new Promise((resolve) => {
222 finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
223 }),
224 );
225 state.choose.mockResolvedValue("reveal");
226 await using screen = await renderMarkdown("[Readme](readme.md)");
227 await screen.openContextMenu();
228 expect(state.search).toHaveBeenCalledOnce();
229 await act(async () => {
230 state.allowed = false;
231 finishLookup();
232 });
233 expect(state.openEditor).not.toHaveBeenCalled();
234});
235​
236it.each(["link-to-thread", "unlink-from-thread"])(
237 "rechecks %s after a native context menu returns",
238 async (action) => {
239 using _setup = setup();
240 state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
241 let choose: (action: string) => void = () => {
242 throw new Error("Menu not opened");
243 };
244 state.choose.mockImplementationOnce(
245 () =>
246 new Promise<string>((resolve) => {
247 choose = resolve;
248 }),
249 );
250 await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
251 await screen.openContextMenu();
252 expect(offeredActions()).toContain(action);
253 await act(async () => {
254 state.allowed = false;
255 choose(action);
256 });
257 expect(state.updateMetadata).not.toHaveBeenCalled();
258​
259 await setAllowed(true);
260 state.choose.mockResolvedValue(action);
261 await screen.openContextMenu();
262 await vi.waitFor(() =>
263 expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
264 environmentId: threadRef.environmentId,
265 input: {
266 threadId: threadRef.threadId,
267 linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
268 },
269 }),
270 );
271 },
272);