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

useThreadActionMenu.test.ts

217 lines7.0 KB

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 };
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();
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 runtime: null,
62 latestRun: state.latestRun,
63 }),
64 useProjects: () => [{ id: "project", environmentId: "secondary" }],
65}));
66vi.mock("../state/threadHandoff", () => ({
67 openThreadHandoffDialog: () => {},
68 readCanMoveThreads: () => false,
69}));
70vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" }));
71vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } }));
72vi.mock("../state/use-atom-command", () => ({
73 useAtomCommand: () => async () => {
74 recordEffect("metadata");
75 return AsyncResult.success(undefined);
76 },
77}));
78vi.mock("../localApi", () => ({
79 readLocalApi: () => ({
80 contextMenu: { show: state.show, close: () => {} },
81 dialogs: {
82 confirm: async () => {
83 recordEffect("confirm");
84 return false;
85 },
86 },
87 }),
88}));
89vi.mock("@t3tools/client-runtime/state/project-grouping", () => ({
90 deriveLogicalProjectKeyFromSettings: () => "project",
91 derivePhysicalProjectKey: () => "project",
92 selectProjectGroupingSettings: () => ({}),
93}));
94vi.mock("../sidebarProjectGrouping", () => ({
95 buildPhysicalToLogicalProjectKeyMap: () => new Map(),
96}));
97vi.mock("../uiStateStore", () => ({
98 useUiStateStore: (select: (store: unknown) => unknown) =>
99 select({
100 markThreadUnread: () => recordEffect("mark-unread"),
101 }),
102}));
103vi.mock("../components/ui/toast", () => ({
104 stackedThreadToast: (toast: unknown) => toast,
105 toastManager: { add: () => state.completed.resolve() },
106}));
107vi.mock("../components/Sidebar.snooze", () => ({
108 resolveSnoozePresets: () => [
109 { id: "hour", label: "In 1 hour", whenLabel: "3 PM", snoozedUntil: "2099-01-01T00:00:00Z" },
110 ],
111 snoozeWakeDescription: () => "later",
112}));
113vi.mock("./useCopyToClipboard", () => ({
114 useCopyToClipboard: () => ({ copyToClipboard: () => recordEffect("copy") }),
115}));
116vi.mock("./useHandleNewThread", () => ({
117 useNewThreadHandler: () => async () => recordEffect("draft"),
118}));
119vi.mock("./useSettings", () => ({
120 useClientSettings: (select: (settings: unknown) => unknown) =>
121 select({
122 confirmThreadDelete: true,
123 confirmThreadArchive: true,
124 timestampFormat: "12-hour",
125 }),
126}));
127vi.mock("./useThreadActions", () => ({
128 canTurnThreadIntoProject: () => false,
129 useThreadActions: () =>
130 Object.fromEntries(
131 [
132 "markThreadUnread",
133 "settleThread",
134 "unsettleThread",
135 "snoozeThread",
136 "unsnoozeThread",
137 "pinThread",
138 "confirmAndUnpinThread",
139 "archiveThread",
140 "deleteThread",
141 ].map((action) => [
142 action,
143 async () => {
144 recordEffect(action === "markThreadUnread" ? "mark-unread" : action);
145 return AsyncResult.success(undefined);
146 },
147 ]),
148 ),
149}));
150​
151import { useThreadActionMenu } from "./useThreadActionMenu";
152​
153const target = {
154 environmentId: EnvironmentId.make("secondary"),
155 threadId: ThreadId.make("thread"),
156};
157const position = { x: 10, y: 20 };
158const createMenu = (options: { readonly onFind?: (threadRef: typeof target) => void } = {}) =>
159 useThreadActionMenu({
160 threadRef: target,
161 projectCwd: "/project",
162 onStartRename: () => recordEffect("rename"),
163 onFind: options.onFind,
164 canShareWithGuest: false,
165 });
166​
167beforeEach(() => {
168 state.granted = new Set(["primary"]);
169 state.effects = [];
170 state.latestRun = null;
171 state.completed = deferred<void>();
172 state.show.mockReset().mockResolvedValue(null);
173});
174​
175describe("thread menu permissions", () => {
176 it.each(["rename", "regenerate-title", "delete", "pin", "settle", "archive"] as const)(
177 "%s rechecks after the native menu closes",
178 async (action) => {
179 state.granted.add("secondary");
180 const choice = deferred<ThreadActionMenuId | null>();
181 state.show.mockReturnValue(choice.promise);
182 createMenu().openMenu(position);
183 state.granted.delete("secondary");
184 choice.resolve(action);
185 await state.completed.promise;
186 expect(state.effects).toEqual([]);
187 },
188 );
189​
190 it("offers find only to a header that can open it, without task permission", async () => {
191 createMenu().openMenu(position);
192 expect(state.show.mock.calls[0]![0].some((item) => item.id === "find")).toBe(false);
193 state.show.mockResolvedValue("find");
194 const onFind = vi.fn(() => recordEffect("find"));
195 createMenu({ onFind }).openMenu(position);
196 await state.completed.promise;
197 const items = state.show.mock.calls[1]![0];
198 expect(items[0]).toMatchObject({ id: "find", label: "Find in thread" });
199 expect(items[0]?.disabled).not.toBe(true);
200 expect(state.effects).toEqual(["find"]);
201 expect(onFind).toHaveBeenCalledExactlyOnceWith(target);
202 });
203});
204​
205describe("thread menu mark unread", () => {
206 it.each([
207 ["completed", true],
208 ["interrupted", false],
209 ["cancelled", false],
210 ] as const)("a %s latest run offers Mark unread: %s", (status, offered) => {
211 // A stopped run never shows Done, so marking it unread would change nothing.
212 state.latestRun = { status, completedAt: "2026-01-01T00:00:00.000Z" };
213 createMenu().openMenu(position);
214 const items = state.show.mock.calls[0]![0];
215 expect(items.some((item) => item.id === "mark-unread")).toBe(offered);
216 });
217});