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