Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 EnvironmentId,
4 ThreadId,
5 type ContextMenuItem,
6} from "@t3tools/contracts";
7import { AsyncResult } from "effect/reactivity";
8import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10import type { ThreadActionMenuId } from "../components/threadActionMenu.logic";
11
12function deferred<T>() {
13 let resolve!: (value: T) => void;
14 const promise = new Promise<T>((complete) => {
15 resolve = complete;
16 });
17 return { promise, resolve };
18}
19
20const state = vi.hoisted(() => ({
21 granted: new Set<string>(),
22 effects: [] as string[],
23 latestRun: null as { readonly status: string; readonly completedAt: string | null } | null,
24 completed: deferred<void>(),
25 show: vi.fn<
26 (
27 items: ReadonlyArray<ContextMenuItem<ThreadActionMenuId>>,
28 position: { x: number; y: number },
29 ) => Promise<ThreadActionMenuId | null>
30 >(),
31}));
32
33function recordEffect(action: string) {
34 state.effects.push(action);
35 state.completed.resolve();
36}
37
38vi.mock("../components/CustomSnoozeDialog", () => ({ requestCustomSnooze: vi.fn() }));
39vi.mock("react", () => ({
40 useCallback: (callback: unknown) => callback,
41 useMemo: (factory: () => unknown) => factory(),
42}));
43vi.mock("@tanstack/react-router", () => ({
44 useRouter: () => ({ navigate: async () => recordEffect("project-settings") }),
45}));
46vi.mock("../state/session", () => ({
47 readEnvironmentScope: (environmentId: string, scope: string) =>
48 scope === AuthOrchestrationOperateScope && state.granted.has(environmentId),
49 readEnvironmentScopeDenied: (environmentId: string) => !state.granted.has(environmentId),
50}));
51vi.mock("../state/entities", () => ({
52 readEnvironmentServerConfigLoaded: () => true,
53 readEnvironmentSupportsAutoSettleOptOut: () => true,
54 readThreadShell: () => ({
55 id: "thread",
56 environmentId: "secondary",
57 projectId: "project",
58 title: "Thread",
59 branch: "main",
60 worktreePath: null,
61 lineage: { relationshipToParent: null },
62 runtime: null,
63 latestRun: state.latestRun,
64 }),
65 useProjects: () => [{ id: "project", environmentId: "secondary" }],
66}));
67vi.mock("../state/threadWorkspace", () => ({
68 openThreadWorkspaceDialog: () => recordEffect("move-workspace"),
69 readCanMoveThreadWorkspace: (environmentId: string) => state.granted.has(environmentId),
70}));
71vi.mock("../state/threadHandoff", () => ({
72 openThreadHandoffDialog: () => {},
73 readCanMoveThreads: () => false,
74}));
75vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" }));
76vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } }));
77vi.mock("../state/use-atom-command", () => ({
78 useAtomCommand: () => async () => {
79 recordEffect("metadata");
80 return AsyncResult.success(undefined);
81 },
82}));
83vi.mock("../localApi", () => ({
84 readLocalApi: () => ({
85 contextMenu: { show: state.show, close: () => {} },
86 dialogs: {
87 confirm: async () => {
88 recordEffect("confirm");
89 return false;
90 },
91 },
92 }),
93}));
94vi.mock("@t3tools/client-runtime/state/project-grouping", () => ({
95 deriveLogicalProjectKeyFromSettings: () => "project",
96 derivePhysicalProjectKey: () => "project",
97 selectProjectGroupingSettings: () => ({}),
98}));
99vi.mock("../sidebarProjectGrouping", () => ({
100 buildPhysicalToLogicalProjectKeyMap: () => new Map(),
101}));
102vi.mock("../uiStateStore", () => ({
103 useUiStateStore: (select: (store: unknown) => unknown) =>
104 select({
105 markThreadUnread: () => recordEffect("mark-unread"),
106 }),
107}));
108vi.mock("../components/ui/toast", () => ({
109 stackedThreadToast: (toast: unknown) => toast,
110 toastManager: { add: () => state.completed.resolve() },
111}));
112vi.mock("../components/Sidebar.snooze", () => ({
113 resolveSnoozePresets: () => [
114 { id: "hour", label: "In 1 hour", whenLabel: "3 PM", snoozedUntil: "2099-01-01T00:00:00Z" },
115 ],
116 snoozeWakeDescription: () => "later",
117}));
118vi.mock("./useCopyToClipboard", () => ({
119 useCopyToClipboard: () => ({ copyToClipboard: () => recordEffect("copy") }),
120}));
121vi.mock("./useHandleNewThread", () => ({
122 useNewThreadHandler: () => async () => recordEffect("draft"),
123}));
124vi.mock("./useSettings", () => ({
125 useClientSettings: (select: (settings: unknown) => unknown) =>
126 select({
127 confirmThreadDelete: true,
128 confirmThreadArchive: true,
129 timestampFormat: "12-hour",
130 }),
131}));
132vi.mock("./useThreadActions", () => ({
133 canTurnThreadIntoProject: () => false,
134 useThreadActions: () =>
135 Object.fromEntries(
136 [
137 "markThreadUnread",
138 "settleThread",
139 "unsettleThread",
140 "snoozeThread",
141 "unsnoozeThread",
142 "pinThread",
143 "confirmAndUnpinThread",
144 "archiveThread",
145 "deleteThread",
146 ].map((action) => [
147 action,
148 async () => {
149 recordEffect(action === "markThreadUnread" ? "mark-unread" : action);
150 return AsyncResult.success(undefined);
151 },
152 ]),
153 ),
154}));
155
156import { useThreadActionMenu } from "./useThreadActionMenu";
157
158const target = {
159 environmentId: EnvironmentId.make("secondary"),
160 threadId: ThreadId.make("thread"),
161};
162const position = { x: 10, y: 20 };
163const createMenu = (options: { readonly onFind?: (threadRef: typeof target) => void } = {}) =>
164 useThreadActionMenu({
165 threadRef: target,
166 projectCwd: "/project",
167 onStartRename: () => recordEffect("rename"),
168 onFind: options.onFind,
169 canShareWithGuest: false,
170 });
171
172beforeEach(() => {
173 state.granted = new Set(["primary"]);
174 state.effects = [];
175 state.latestRun = null;
176 state.completed = deferred<void>();
177 state.show.mockReset().mockResolvedValue(null);
178});
179
180describe("thread menu permissions", () => {
181 it.each([
182 "rename",
183 "regenerate-title",
184 "delete",
185 "pin",
186 "settle",
187 "archive",
188 "move-workspace",
189 ] as const)("%s rechecks after the native menu closes", async (action) => {
190 state.granted.add("secondary");
191 const choice = deferred<ThreadActionMenuId | null>();
192 state.show.mockReturnValue(choice.promise);
193 createMenu().openMenu(position);
194 state.granted.delete("secondary");
195 choice.resolve(action);
196 await state.completed.promise;
197 expect(state.effects).toEqual([]);
198 });
199
200 it("offers find only to a header that can open it, without task permission", async () => {
201 createMenu().openMenu(position);
202 expect(state.show.mock.calls[0]![0].some((item) => item.id === "find")).toBe(false);
203 state.show.mockResolvedValue("find");
204 const onFind = vi.fn(() => recordEffect("find"));
205 createMenu({ onFind }).openMenu(position);
206 await state.completed.promise;
207 const items = state.show.mock.calls[1]![0];
208 expect(items[0]).toMatchObject({ id: "find", label: "Find in thread" });
209 expect(items[0]?.disabled).not.toBe(true);
210 expect(state.effects).toEqual(["find"]);
211 expect(onFind).toHaveBeenCalledExactlyOnceWith(target);
212 });
213});
214
215describe("thread menu mark unread", () => {
216 it.each([
217 ["completed", true],
218 ["interrupted", false],
219 ["cancelled", false],
220 ] as const)("a %s latest run offers Mark unread: %s", (status, offered) => {
221 // A stopped run never shows Done, so marking it unread would change nothing.
222 state.latestRun = { status, completedAt: "2026-01-01T00:00:00.000Z" };
223 createMenu().openMenu(position);
224 const items = state.show.mock.calls[0]![0];
225 expect(items.some((item) => item.id === "mark-unread")).toBe(offered);
226 });
227});