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

useThreadActions.permissions.test.ts

459 lines17.2 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ProjectId,
6 ThreadId,
7 type ScopedThreadRef,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { AsyncResult } from "effect/reactivity";
11import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
12​
13import { scopedThreadKey } from "@t3tools/client-runtime/environment";
14import { useDiffPanelStore } from "../diffPanelStore";
15import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../previewMiniPlayerStore";
16import { useRightPanelStore } from "../rightPanelStore";
17​
18function deferred<T>() {
19 let resolve!: (value: T) => void;
20 const promise = new Promise<T>((complete) => {
21 resolve = complete;
22 });
23 return { promise, resolve };
25​
26const state = vi.hoisted(() => ({
27 serverConfig: { shellThreadFamilies: false },
28 familyLookupFails: false,
29 scopes: new Map<string, Set<string>>(),
30 threads: [] as {
31 environmentId: EnvironmentId;
32 id: ThreadId;
33 projectId: ProjectId;
34 title: string;
35 worktreePath: string | null;
36 lineage: { parentThreadId: ThreadId | null; sideChat?: boolean };
37 session: { status: "ready" | "stopped" } | null;
38 latestTurn: null;
39 }[],
40 familyThreads: [] as {
41 id: ThreadId;
42 lineage: { parentThreadId: ThreadId | null; sideChat?: boolean };
43 }[],
44 requests: [] as { action: string; environmentId: string; input: { threadId?: string } }[],
45 localEffects: [] as string[],
46 confirm: vi.fn<(message: string) => Promise<boolean>>(),
47 toasts: [] as string[],
48 afterRequest: undefined as ((action: string) => void) | undefined,
49 sessionLookupFails: false,
50}));
51​
52vi.mock("react", () => ({
53 useCallback: (callback: unknown) => callback,
54 useMemo: (factory: () => unknown) => factory(),
55 useRef: (current: unknown) => ({ current }),
56}));
57vi.mock("@tanstack/react-router", () => ({
58 useRouter: () => ({ state: { location: { href: "/" }, matches: [] }, navigate: async () => {} }),
59}));
60vi.mock("../state/session", () => ({
61 environmentSession: { sessionStateAtom: "session" },
62 readEnvironmentScope: (environmentId: string, scope: string) =>
63 state.scopes.get(environmentId)?.has(scope) === true,
64}));
65vi.mock("../state/use-atom-command", () => ({
66 useAtomCommand:
67 (action: string) =>
68 async (request: { environmentId: string; input: { threadId?: string } }) => {
69 state.requests.push({ action, ...request });
70 const scope =
71 action === "removeWorktree" ? AuthSourceControlWriteScope : AuthOrchestrationOperateScope;
72 if (!state.scopes.get(request.environmentId)?.has(scope)) {
73 return AsyncResult.failure(Cause.fail(new Error("Server denied the request")));
74 }
75 state.afterRequest?.(action);
76 return AsyncResult.success(undefined);
77 },
78}));
79vi.mock("../state/use-atom-query-runner", () => ({
80 useAtomQueryRunner: (family: unknown) => async (environmentId: string) =>
81 family === "threadFamily"
82 ? state.familyLookupFails
83 ? AsyncResult.failure(Cause.fail(new Error("Family lookup failed")))
84 : AsyncResult.success({ threads: state.familyThreads })
85 : state.sessionLookupFails
86 ? AsyncResult.failure(Cause.fail(new Error("Session lookup failed")))
87 : AsyncResult.success({
88 authenticated: true,
89 scopes: [...(state.scopes.get(environmentId) ?? [])],
90 auth: { serverUpdateScope: "environment:maintain" },
91 }),
92}));
93vi.mock("../state/orchestration", () => ({
94 orchestrationEnvironment: { threadFamily: "threadFamily" },
95}));
96vi.mock("../state/server", async (importOriginal) => {
97 const actual = await importOriginal<typeof import("../state/server")>();
98 const { Atom } = await import("effect/reactivity");
99 return {
100 ...actual,
101 environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.serverConfig]])),
102 };
103});
104vi.mock("../state/threads", () => ({
105 threadEnvironment: Object.fromEntries(
106 [
107 "archive",
108 "unarchive",
109 "delete",
110 "settle",
111 "unsettle",
112 "pin",
113 "unpin",
114 "reorderPin",
115 "snooze",
116 "unsnooze",
117 "stopSession",
118 ].map((action) => [action, action]),
119 ),
120}));
121vi.mock("../state/vcs", () => ({
122 vcsEnvironment: { removeWorktree: "removeWorktree", refreshStatus: "refreshStatus" },
123}));
124vi.mock("../state/entities", () => ({
125 readEnvironmentServerConfigLoaded: () => true,
126 readThreadShell: (ref: ScopedThreadRef) =>
127 state.threads.find(
128 (thread) => thread.environmentId === ref.environmentId && thread.id === ref.threadId,
129 ) ?? null,
130 readThreadShells: () => state.threads,
131 readEnvironmentThreadRefs: (environmentId: EnvironmentId) =>
132 state.threads
133 .filter((thread) => thread.environmentId === environmentId)
134 .map((thread) => ({ environmentId, threadId: thread.id })),
135 readProject: () => ({ workspaceRoot: "/project" }),
136}));
137vi.mock("../components/Sidebar.logic", () => ({
138 getFallbackThreadIdAfterDelete: () => null,
139 pinOrderKeyBetween: () => "a",
140}));
141vi.mock("../composerDraftStore", () => ({
142 useComposerDraftStore: (select: (store: unknown) => unknown) =>
143 select({
144 clearDraftThread: (ref: ScopedThreadRef) =>
145 state.localEffects.push(`clear-draft:${ref.threadId}`),
146 clearProjectDraftThreadById: () => state.localEffects.push("clear-project-draft"),
147 }),
148}));
149vi.mock("../terminalUiStateStore", () => ({
150 useTerminalUiStateStore: (select: (store: unknown) => unknown) =>
151 select({
152 clearTerminalUiState: () => state.localEffects.push("clear-terminal-ui"),
153 }),
154}));
155vi.mock("../uiStateStore", () => ({
156 useUiStateStore: (select: (store: unknown) => unknown) =>
157 select({
158 markThreadVisited: () => state.localEffects.push("mark-visited"),
159 }),
160}));
161vi.mock("../lib/archivedThreadsState", () => ({
162 refreshArchivedThreadsForEnvironment: () => state.localEffects.push("refresh-archive"),
163}));
164vi.mock("../lib/composerDraftUploads", () => ({
165 releaseComposerDraftUploads: (ref: ScopedThreadRef) =>
166 state.localEffects.push(`release-uploads:${ref.threadId}`),
167}));
168vi.mock("../localApi", () => ({
169 readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),
170}));
171vi.mock("../threadRoutes", () => ({
172 resolveThreadRouteRef: () => null,
173 buildThreadRouteParams: (ref: ScopedThreadRef) => ref,
174}));
175vi.mock("../components/ui/toast", () => ({
176 stackedThreadToast: (toast: unknown) => toast,
177 toastManager: {
178 add: (toast: { title?: string }) => {
179 if (toast.title) state.toasts.push(toast.title);
180 },
181 },
182}));
183vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => async () => {} }));
184vi.mock("./useSettings", () => ({
185 useClientSettings: (select: (settings: unknown) => unknown) =>
186 select({
187 sidebarThreadSortOrder: "createdAt",
188 confirmThreadDelete: true,
189 confirmThreadUnpin: true,
190 }),
191}));
192​
193import { useThreadActions } from "./useThreadActions";
194​
195function seedThreadPanelState(ref: ScopedThreadRef) {
196 useRightPanelStore.getState().show(ref);
197 useDiffPanelStore.getState().selectGitScope(ref, "branch");
198 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab"));
200​
201function threadPanelStatePresence(ref: ScopedThreadRef) {
202 const key = scopedThreadKey(ref);
203 return {
204 rightPanel: key in useRightPanelStore.getState().byThreadKey,
205 diffPanel: key in useDiffPanelStore.getState().byThreadKey,
206 miniPlayer: key in usePreviewMiniPlayerStore.getState().byThreadKey,
207 };
209const panelStateKept = { rightPanel: true, diffPanel: true, miniPlayer: true };
210const panelStateCleared = { rightPanel: false, diffPanel: false, miniPlayer: false };
211​
212const primary = EnvironmentId.make("primary");
213const secondary = EnvironmentId.make("secondary");
214const target = { environmentId: secondary, threadId: ThreadId.make("thread") };
215type ThreadActions = ReturnType<typeof useThreadActions>;
216const operations = [
217 {
218 name: "archive",
219 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.archiveThread(ref),
220 },
221 {
222 name: "unarchive",
223 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unarchiveThread(ref),
224 },
225 {
226 name: "settle",
227 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.settleThread(ref),
228 },
229 {
230 name: "unsettle",
231 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsettleThread(ref),
232 },
233 {
234 name: "snooze",
235 run: (actions: ThreadActions, ref: ScopedThreadRef) =>
236 actions.snoozeThread(ref, "2099-01-01T00:00:00Z"),
237 },
238 {
239 name: "unsnooze",
240 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsnoozeThread(ref),
241 },
242 { name: "pin", run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.pinThread(ref) },
243 {
244 name: "unpin",
245 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unpinThread(ref),
246 },
247 {
248 name: "reorderPin",
249 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.reorderPinnedThread(ref, "b"),
250 },
251] as const;
252​
253beforeEach(() => {
254 state.serverConfig.shellThreadFamilies = false;
255 state.familyLookupFails = false;
256 state.familyThreads = [];
257 state.scopes = new Map([
258 [primary, new Set([AuthOrchestrationOperateScope])],
259 [secondary, new Set<string>()],
260 ]);
261 state.threads = [
262 {
263 environmentId: secondary,
264 id: target.threadId,
265 projectId: ProjectId.make("project"),
266 title: "Thread",
267 worktreePath: null,
268 lineage: { parentThreadId: null },
269 session: null,
270 latestTurn: null,
271 },
272 ];
273 state.requests = [];
274 state.localEffects = [];
275 state.confirm.mockReset().mockResolvedValue(true);
276 state.toasts = [];
277 state.afterRequest = undefined;
278 state.sessionLookupFails = false;
279 useRightPanelStore.setState(useRightPanelStore.getInitialState(), true);
280 useDiffPanelStore.setState(useDiffPanelStore.getInitialState(), true);
281 usePreviewMiniPlayerStore.setState(usePreviewMiniPlayerStore.getInitialState(), true);
282});
283​
284describe("thread action permissions", () => {
285 it.each(operations)("$name requires the target environment's grant", async ({ run }) => {
286 const result = await run(useThreadActions(), target);
287 expect(result._tag).toBe("Failure");
288 expect(state.requests).toEqual([]);
289 expect(state.localEffects).toEqual([]);
290 });
291​
292 it.each(operations)("$name rechecks a retained callback after revocation", async ({ run }) => {
293 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
294 const actions = useThreadActions();
295 state.scopes.get(secondary)!.clear();
296 await run(actions, target);
297 expect(state.requests).toEqual([]);
298 });
299​
300 it.each(operations)(
301 "$name works after the target gains only task permission",
302 async ({ name, run }) => {
303 const actions = useThreadActions();
304 state.scopes.get(primary)!.clear();
305 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
306 expect((await run(actions, target))._tag).toBe("Success");
307 expect(state.requests).toEqual([
308 expect.objectContaining({ action: name, environmentId: secondary }),
309 ]);
310 },
311 );
312​
313 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
314 "%s blocks a forbidden confirmation",
315 async (action) => {
316 await useThreadActions()[action](target);
317 expect(state.confirm).not.toHaveBeenCalled();
318 expect(state.requests).toEqual([]);
319 },
320 );
321​
322 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
323 "%s rechecks after the confirmation",
324 async (action) => {
325 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
326 const confirmation = deferred<boolean>();
327 state.confirm.mockReturnValue(confirmation.promise);
328 const result = useThreadActions()[action](target);
329 expect(state.confirm).toHaveBeenCalledOnce();
330 state.scopes.get(secondary)!.clear();
331 confirmation.resolve(true);
332 await result;
333 expect(state.requests).toEqual([]);
334 expect(state.localEffects).toEqual([]);
335 },
336 );
337​
338 it("names an archived thread in its delete confirmation and preserves it on cancel", async () => {
339 state.threads = [];
340 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
341 state.confirm.mockResolvedValue(false);
342 await useThreadActions().confirmAndDeleteThread(target, "Archived release notes");
343 expect(state.confirm).toHaveBeenCalledWith(
344 expect.stringContaining('Delete thread "Archived release notes"?'),
345 { variant: "destructive" },
346 );
347 expect(state.requests).toEqual([]);
348 });
349​
350 it("deletes an archived thread only with its own environment's grant", async () => {
351 state.serverConfig.shellThreadFamilies = true;
352 state.familyThreads = [
353 {
354 id: ThreadId.make("side-chat"),
355 lineage: { parentThreadId: target.threadId, sideChat: true },
356 },
357 { id: ThreadId.make("fork"), lineage: { parentThreadId: target.threadId } },
358 {
359 id: ThreadId.make("other-side-chat"),
360 lineage: { parentThreadId: ThreadId.make("other-parent"), sideChat: true },
361 },
362 ];
363 state.threads = [];
364 seedThreadPanelState(target);
365 const actions = useThreadActions();
366 await actions.deleteThread(target);
367 expect(state.requests).toEqual([]);
368 expect(threadPanelStatePresence(target)).toEqual(panelStateKept);
369 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
370 expect((await actions.deleteThread(target))._tag).toBe("Success");
371 expect(state.requests).toEqual([
372 expect.objectContaining({ action: "delete", environmentId: secondary }),
373 ]);
374 expect(threadPanelStatePresence(target)).toEqual(panelStateCleared);
375 expect(state.localEffects).toEqual([
376 "release-uploads:thread",
377 "clear-draft:thread",
378 "release-uploads:side-chat",
379 "clear-draft:side-chat",
380 "refresh-archive",
381 "clear-terminal-ui",
382 ]);
383 expect(state.localEffects).not.toContain("clear-draft:fork");
384 expect(state.localEffects).not.toContain("clear-draft:other-side-chat");
385​
386 // The family read only finds drafts to clear; it never blocks the delete.
387 state.familyLookupFails = true;
388 state.requests = [];
389 state.localEffects = [];
390 expect((await actions.deleteThread(target))._tag).toBe("Success");
391 expect(state.requests).toEqual([
392 expect.objectContaining({ action: "delete", environmentId: secondary }),
393 ]);
394 expect(state.localEffects).toContain("clear-draft:thread");
395 });
396​
397 it("stops before delete and local cleanup when permission is revoked during session stop", async () => {
398 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
399 state.threads[0]!.session = { status: "ready" };
400 state.afterRequest = () => state.scopes.get(secondary)!.clear();
401 seedThreadPanelState(target);
402 expect((await useThreadActions().deleteThread(target))._tag).toBe("Failure");
403 expect(state.requests.map((request) => request.action)).toEqual(["stopSession"]);
404 expect(state.localEffects).toEqual([]);
405 expect(threadPanelStatePresence(target)).toEqual(panelStateKept);
406 });
407​
408 it.each([
409 { reason: "without source-control permission", sessionLookupFails: false },
410 { reason: "when the permission lookup fails", sessionLookupFails: true },
411 ])("deletes a worktree thread and keeps its worktree $reason", async ({ sessionLookupFails }) => {
412 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
413 state.threads[0]!.worktreePath = "/worktrees/thread";
414 state.sessionLookupFails = sessionLookupFails;
415 seedThreadPanelState(target);
416 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
417 expect(state.confirm).not.toHaveBeenCalled();
418 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
419 expect(state.localEffects).toContain("clear-terminal-ui");
420 expect(threadPanelStatePresence(target)).toEqual(panelStateCleared);
421 });
422​
423 it("clears the drafts of the side chats deleted with it", async () => {
424 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
425 const parent = state.threads[0]!;
426 state.threads.push(
427 {
428 ...parent,
429 id: ThreadId.make("side-chat"),
430 lineage: { parentThreadId: parent.id, sideChat: true },
431 },
432 { ...parent, id: ThreadId.make("fork"), lineage: { parentThreadId: parent.id } },
433 );
434 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
435 expect(state.localEffects).toEqual(
436 expect.arrayContaining(["release-uploads:side-chat", "clear-draft:side-chat"]),
437 );
438 expect(state.localEffects).not.toContain("clear-draft:fork");
439 });
440​
441 it("does not request worktree removal after its grant is revoked during delete", async () => {
442 state.scopes
443 .get(secondary)!
444 .add(AuthOrchestrationOperateScope)
445 .add(AuthSourceControlWriteScope);
446 state.threads[0]!.worktreePath = "/worktrees/thread";
447 state.afterRequest = () => state.scopes.get(secondary)!.delete(AuthSourceControlWriteScope);
448 const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
449 try {
450 const result = await useThreadActions().deleteThread(target);
451 expect(result._tag).toBe("Success");
452 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
453 expect(state.toasts).toContain("Failed to delete worktree");
454 expect(state.localEffects).toContain("clear-terminal-ui");
455 } finally {
456 consoleError.mockRestore();
457 }
458 });
459});