Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentAuthorizationError,
5 EnvironmentId,
6 ProjectId,
7 ThreadId,
8 type ScopedThreadRef,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import { AsyncResult } from "effect/reactivity";
12import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
13
14function deferred<T>() {
15 let resolve!: (value: T) => void;
16 const promise = new Promise<T>((complete) => {
17 resolve = complete;
18 });
19 return { promise, resolve };
20}
21
22const state = vi.hoisted(() => ({
23 scopes: new Map<string, Set<string>>(),
24 threads: [] as {
25 environmentId: EnvironmentId;
26 id: ThreadId;
27 projectId: ProjectId;
28 title: string;
29 worktreePath: string | null;
30 session: { status: "ready" | "stopped" } | null;
31 latestTurn: null;
32 }[],
33 requests: [] as { action: string; environmentId: string; input: { threadId?: string } }[],
34 localEffects: [] as string[],
35 confirm: vi.fn<(message: string) => Promise<boolean>>(),
36 toasts: [] as string[],
37 afterRequest: undefined as ((action: string) => void) | undefined,
38 sessionLookupFails: false,
39}));
40
41vi.mock("react", () => ({
42 useCallback: (callback: unknown) => callback,
43 useMemo: (factory: () => unknown) => factory(),
44 useRef: (current: unknown) => ({ current }),
45}));
46vi.mock("@tanstack/react-router", () => ({
47 useRouter: () => ({ state: { matches: [] }, navigate: async () => {} }),
48}));
49vi.mock("../state/session", () => ({
50 environmentSession: { sessionStateAtom: "session" },
51 readEnvironmentScope: (environmentId: string, scope: string) =>
52 state.scopes.get(environmentId)?.has(scope) === true,
53}));
54vi.mock("../state/use-atom-command", () => ({
55 useAtomCommand:
56 (action: string) =>
57 async (request: { environmentId: string; input: { threadId?: string } }) => {
58 state.requests.push({ action, ...request });
59 const scope =
60 action === "removeWorktree" ? AuthSourceControlWriteScope : AuthOrchestrationOperateScope;
61 if (!state.scopes.get(request.environmentId)?.has(scope)) {
62 return AsyncResult.failure(Cause.fail(new Error("Server denied the request")));
63 }
64 state.afterRequest?.(action);
65 return AsyncResult.success(undefined);
66 },
67}));
68vi.mock("../state/use-atom-query-runner", () => ({
69 useAtomQueryRunner: () => async (environmentId: string) =>
70 state.sessionLookupFails
71 ? AsyncResult.failure(Cause.fail(new Error("Session lookup failed")))
72 : AsyncResult.success({
73 authenticated: true,
74 scopes: [...(state.scopes.get(environmentId) ?? [])],
75 auth: { serverUpdateScope: "environment:maintain" },
76 }),
77}));
78vi.mock("../state/threads", () => ({
79 threadEnvironment: Object.fromEntries(
80 [
81 "archive",
82 "unarchive",
83 "delete",
84 "settle",
85 "unsettle",
86 "pin",
87 "unpin",
88 "reorderPin",
89 "snooze",
90 "unsnooze",
91 "stopSession",
92 ].map((action) => [action, action]),
93 ),
94}));
95vi.mock("../state/vcs", () => ({
96 vcsEnvironment: { removeWorktree: "removeWorktree", refreshStatus: "refreshStatus" },
97}));
98vi.mock("../state/entities", () => ({
99 readEnvironmentSupportsPinning: () => true,
100 readEnvironmentSupportsPinReorder: () => true,
101 readEnvironmentSupportsSettlement: () => true,
102 readEnvironmentSupportsSnooze: () => true,
103 readThreadShell: (ref: ScopedThreadRef) =>
104 state.threads.find(
105 (thread) => thread.environmentId === ref.environmentId && thread.id === ref.threadId,
106 ) ?? null,
107 readThreadShells: () => state.threads,
108 readEnvironmentThreadRefs: (environmentId: EnvironmentId) =>
109 state.threads
110 .filter((thread) => thread.environmentId === environmentId)
111 .map((thread) => ({ environmentId, threadId: thread.id })),
112 readProject: () => ({ workspaceRoot: "/project" }),
113}));
114vi.mock("../components/Sidebar.logic", () => ({
115 getFallbackThreadIdAfterDelete: () => null,
116 pinOrderKeyBetween: () => "a",
117}));
118vi.mock("../composerDraftStore", () => ({
119 useComposerDraftStore: (select: (store: unknown) => unknown) =>
120 select({
121 clearDraftThread: () => state.localEffects.push("clear-draft"),
122 clearProjectDraftThreadById: () => state.localEffects.push("clear-project-draft"),
123 }),
124}));
125vi.mock("../terminalUiStateStore", () => ({
126 useTerminalUiStateStore: (select: (store: unknown) => unknown) =>
127 select({
128 clearTerminalUiState: () => state.localEffects.push("clear-terminal-ui"),
129 }),
130}));
131vi.mock("../uiStateStore", () => ({
132 useUiStateStore: (select: (store: unknown) => unknown) =>
133 select({
134 markThreadVisited: () => state.localEffects.push("mark-visited"),
135 }),
136}));
137vi.mock("../lib/archivedThreadsState", () => ({
138 refreshArchivedThreadsForEnvironment: () => state.localEffects.push("refresh-archive"),
139}));
140vi.mock("../lib/composerDraftUploads", () => ({
141 releaseComposerDraftUploads: () => state.localEffects.push("release-uploads"),
142}));
143vi.mock("../localApi", () => ({
144 readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),
145}));
146vi.mock("../threadRoutes", () => ({
147 resolveThreadRouteRef: () => null,
148 buildThreadRouteParams: (ref: ScopedThreadRef) => ref,
149}));
150vi.mock("../components/ui/toast", () => ({
151 stackedThreadToast: (toast: unknown) => toast,
152 toastManager: {
153 add: (toast: { title?: string }) => {
154 if (toast.title) state.toasts.push(toast.title);
155 },
156 },
157}));
158vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => async () => {} }));
159vi.mock("./useSettings", () => ({
160 useClientSettings: (select: (settings: unknown) => unknown) =>
161 select({
162 sidebarThreadSortOrder: "createdAt",
163 confirmThreadDelete: true,
164 confirmThreadUnpin: true,
165 }),
166}));
167
168import { useThreadActions } from "./useThreadActions";
169
170const primary = EnvironmentId.make("primary");
171const secondary = EnvironmentId.make("secondary");
172const target = { environmentId: secondary, threadId: ThreadId.make("thread") };
173type ThreadActions = ReturnType<typeof useThreadActions>;
174const operations = [
175 {
176 name: "archive",
177 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.archiveThread(ref),
178 },
179 {
180 name: "unarchive",
181 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unarchiveThread(ref),
182 },
183 {
184 name: "settle",
185 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.settleThread(ref),
186 },
187 {
188 name: "unsettle",
189 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsettleThread(ref),
190 },
191 {
192 name: "snooze",
193 run: (actions: ThreadActions, ref: ScopedThreadRef) =>
194 actions.snoozeThread(ref, "2099-01-01T00:00:00Z"),
195 },
196 {
197 name: "unsnooze",
198 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsnoozeThread(ref),
199 },
200 { name: "pin", run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.pinThread(ref) },
201 {
202 name: "unpin",
203 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unpinThread(ref),
204 },
205 {
206 name: "reorderPin",
207 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.reorderPinnedThread(ref, "b"),
208 },
209] as const;
210
211beforeEach(() => {
212 state.scopes = new Map([
213 [primary, new Set([AuthOrchestrationOperateScope])],
214 [secondary, new Set<string>()],
215 ]);
216 state.threads = [
217 {
218 environmentId: secondary,
219 id: target.threadId,
220 projectId: ProjectId.make("project"),
221 title: "Thread",
222 worktreePath: null,
223 session: null,
224 latestTurn: null,
225 },
226 ];
227 state.requests = [];
228 state.localEffects = [];
229 state.confirm.mockReset().mockResolvedValue(true);
230 state.toasts = [];
231 state.afterRequest = undefined;
232 state.sessionLookupFails = false;
233});
234
235describe("thread action permissions", () => {
236 it.each(operations)("$name requires the target environment's grant", async ({ run }) => {
237 const result = await run(useThreadActions(), target);
238 expect(result._tag).toBe("Failure");
239 expect(state.requests).toEqual([]);
240 expect(state.localEffects).toEqual([]);
241 });
242
243 it.each(operations)("$name rechecks a retained callback after revocation", async ({ run }) => {
244 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
245 const actions = useThreadActions();
246 state.scopes.get(secondary)!.clear();
247 await run(actions, target);
248 expect(state.requests).toEqual([]);
249 });
250
251 it.each(operations)(
252 "$name works after the target gains only task permission",
253 async ({ name, run }) => {
254 const actions = useThreadActions();
255 state.scopes.get(primary)!.clear();
256 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
257 expect((await run(actions, target))._tag).toBe("Success");
258 expect(state.requests).toEqual([
259 expect.objectContaining({ action: name, environmentId: secondary }),
260 ]);
261 },
262 );
263
264 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
265 "%s blocks a forbidden confirmation",
266 async (action) => {
267 await useThreadActions()[action](target);
268 expect(state.confirm).not.toHaveBeenCalled();
269 expect(state.requests).toEqual([]);
270 },
271 );
272
273 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
274 "%s rechecks after the confirmation",
275 async (action) => {
276 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
277 const confirmation = deferred<boolean>();
278 state.confirm.mockReturnValue(confirmation.promise);
279 const result = useThreadActions()[action](target);
280 expect(state.confirm).toHaveBeenCalledOnce();
281 state.scopes.get(secondary)!.clear();
282 confirmation.resolve(true);
283 await result;
284 expect(state.requests).toEqual([]);
285 expect(state.localEffects).toEqual([]);
286 },
287 );
288
289 it("identifies the missing task scope when thread deletion is denied", async () => {
290 const result = await useThreadActions().deleteThread(target);
291
292 expect(result._tag).toBe("Failure");
293 if (result._tag !== "Failure") throw new Error("Expected permission denial");
294 const error = Cause.squash<unknown>(result.cause);
295 expect(error).toBeInstanceOf(EnvironmentAuthorizationError);
296 expect(error).toMatchObject({ requiredScope: AuthOrchestrationOperateScope });
297 expect(state.requests).toEqual([]);
298 expect(state.localEffects).toEqual([]);
299 });
300
301 it("deletes an archived thread only with its own environment's grant", async () => {
302 state.threads = [];
303 const actions = useThreadActions();
304 await actions.deleteThread(target);
305 expect(state.requests).toEqual([]);
306 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
307 expect((await actions.deleteThread(target))._tag).toBe("Success");
308 expect(state.requests).toEqual([
309 expect.objectContaining({ action: "delete", environmentId: secondary }),
310 ]);
311 });
312
313 it("stops before delete and local cleanup when permission is revoked during session stop", async () => {
314 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
315 state.threads[0]!.session = { status: "ready" };
316 state.afterRequest = () => state.scopes.get(secondary)!.clear();
317 expect((await useThreadActions().deleteThread(target))._tag).toBe("Failure");
318 expect(state.requests.map((request) => request.action)).toEqual(["stopSession"]);
319 expect(state.localEffects).toEqual([]);
320 });
321
322 it.each([
323 { reason: "without source-control permission", sessionLookupFails: false },
324 { reason: "when the permission lookup fails", sessionLookupFails: true },
325 ])("deletes a worktree thread and keeps its worktree $reason", async ({ sessionLookupFails }) => {
326 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
327 state.threads[0]!.worktreePath = "/worktrees/thread";
328 state.sessionLookupFails = sessionLookupFails;
329 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
330 expect(state.confirm).not.toHaveBeenCalled();
331 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
332 expect(state.localEffects).toContain("clear-terminal-ui");
333 });
334
335 it("does not request worktree removal after its grant is revoked during delete", async () => {
336 state.scopes
337 .get(secondary)!
338 .add(AuthOrchestrationOperateScope)
339 .add(AuthSourceControlWriteScope);
340 state.threads[0]!.worktreePath = "/worktrees/thread";
341 state.afterRequest = () => state.scopes.get(secondary)!.delete(AuthSourceControlWriteScope);
342 const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
343 try {
344 const result = await useThreadActions().deleteThread(target);
345 expect(result._tag).toBe("Success");
346 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
347 expect(state.toasts).toContain("Failed to delete worktree");
348 expect(state.localEffects).toContain("clear-terminal-ui");
349 } finally {
350 consoleError.mockRestore();
351 }
352 });
353});