The best way to control Claude Code, Codex and more from any computer or phone

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