Open History to see the last commit
1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5import { useThreadActions } from "./useThreadActions";
6import { threadEnvironment } from "../state/threads";
7import { toastManager } from "../components/ui/toast";
8import { useThreadUndoNotice } from "./showThreadUndoNotice";
9import { announce } from "../lib/announce";
10
11const commands = vi.hoisted(() => ({
12 pin: vi.fn(),
13 unpin: vi.fn(),
14 archive: vi.fn(),
15 unarchive: vi.fn(),
16 delete: vi.fn(),
17 settle: vi.fn(),
18 unsettle: vi.fn(),
19 snooze: vi.fn(),
20 unsnooze: vi.fn(),
21}));
22const router = vi.hoisted(() => ({
23 navigate: vi.fn(async () => {}),
24 state: { location: { href: "/" }, matches: [{ params: {} as Record<string, string> }] },
25}));
26vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
27vi.mock("../state/session", async (original) => ({
28 ...(await original<typeof import("../state/session")>()),
29 readEnvironmentScope: () => true,
30}));
31vi.mock("react", async (original) => ({
32 ...(await original<typeof import("react")>()),
33 useCallback: (callback: unknown) => callback,
34 useMemo: (create: () => unknown) => create(),
35 useRef: (value: unknown) => ({ current: value }),
36}));
37vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));
38vi.mock("./useSettings", () => ({ useClientSettings: () => false }));
39vi.mock("./useHandleNewThread", () => ({
40 useNewThreadHandler: () => async () => {
41 router.state.location.href = "/draft/project";
42 },
43}));
44vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));
45vi.mock("../lib/composerDraftUploads", () => ({ releaseComposerDraftUploads: vi.fn() }));
46vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));
47vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));
48vi.mock("../lib/announce", () => ({ announce: vi.fn(), cancelAnnouncement: vi.fn() }));
49vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));
50const threadShell = vi.hoisted(() => ({
51 title: "Thread",
52 pinOrderKey: "a0",
53 pinnedAt: null as string | null,
54 snoozedUntil: null as string | null,
55 projectId: "project",
56 environmentId: "undo-env",
57 session: null,
58}));
59// Archived rows have no loaded shell, so deleting one takes the unresolved path.
60const shellLoaded = vi.hoisted(() => ({ current: true }));
61vi.mock("../state/entities", async (original) => ({
62 ...(await original<typeof import("../state/entities")>()),
63 readEnvironmentServerConfigLoaded: () => true,
64 readThreadShell: () => (shellLoaded.current ? threadShell : null),
65}));
66vi.mock("../state/use-atom-command", () => ({
67 useAtomCommand: (command: unknown) => {
68 switch (command) {
69 case threadEnvironment.pin:
70 return commands.pin;
71 case threadEnvironment.unpin:
72 return commands.unpin;
73 case threadEnvironment.archive:
74 return commands.archive;
75 case threadEnvironment.unarchive:
76 return commands.unarchive;
77 case threadEnvironment.delete:
78 return commands.delete;
79 case threadEnvironment.settle:
80 return commands.settle;
81 case threadEnvironment.unsettle:
82 return commands.unsettle;
83 case threadEnvironment.snooze:
84 return commands.snooze;
85 case threadEnvironment.unsnooze:
86 return commands.unsnooze;
87 default:
88 return vi.fn();
89 }
90 },
91}));
92
93const target = {
94 environmentId: EnvironmentId.make("undo-env"),
95 threadId: ThreadId.make("thread"),
96};
97function currentUndo() {
98 const notice = useThreadUndoNotice.getState().notice;
99 expect(notice).not.toBeNull();
100 return notice!.undo;
101}
102
103beforeEach(() => {
104 vi.useFakeTimers();
105 for (const command of Object.values(commands)) {
106 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
107 }
108 router.navigate.mockClear();
109 router.state.location.href = "/";
110 router.state.matches[0]!.params = {};
111 threadShell.pinnedAt = null;
112 threadShell.snoozedUntil = null;
113 shellLoaded.current = true;
114});
115afterEach(() => {
116 vi.runAllTimers();
117 vi.useRealTimers();
118 vi.restoreAllMocks();
119});
120
121describe("concurrent thread action Undo", () => {
122 it.each([
123 ["settleThread", "settle", "unsettle", "Settled"],
124 ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
125 ["unpinThread", "unpin", "pin", "Unpinned"],
126 ["archiveThread", "archive", "unarchive", "Archived"],
127 ] as const)(
128 "%s retains one undo for concurrent successful requests",
129 async (handler, action, inverse, notice) => {
130 const actions = useThreadActions();
131 const run = () =>
132 handler === "snoozeThread"
133 ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
134 : actions[handler](target);
135 await Promise.all([run(), run()]);
136 expect(commands[action]).toHaveBeenCalledTimes(2);
137 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
138 await currentUndo()();
139 expect(commands[inverse]).toHaveBeenCalledOnce();
140 },
141 );
142});
143
144describe("pin", () => {
145 it("announces that the thread was pinned", async () => {
146 vi.mocked(announce).mockClear();
147 await useThreadActions().pinThread(target);
148 expect(announce).toHaveBeenCalledExactlyOnceWith("Pinned 1 thread");
149 });
150});
151
152describe("unpin Undo", () => {
153 it("restores the original snooze after restoring the pin", async () => {
154 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
155 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
156 await useThreadActions().unpinThread(target);
157 vi.mocked(announce).mockClear();
158 await currentUndo()();
159 expect(announce).not.toHaveBeenCalledWith("Pinned 1 thread");
160 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
161 environmentId: target.environmentId,
162 input: { threadId: target.threadId, orderKey: "a0" },
163 });
164 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
165 environmentId: target.environmentId,
166 input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
167 });
168 expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
169 commands.snooze.mock.invocationCallOrder[0]!,
170 );
171 });
172
173 it("restores the pin without an already expired snooze", async () => {
174 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
175 threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
176 await useThreadActions().unpinThread(target);
177 await currentUndo()();
178 expect(commands.pin).toHaveBeenCalledOnce();
179 expect(commands.snooze).not.toHaveBeenCalled();
180 });
181
182 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
183 const sidebar = useThreadActions();
184 const header = useThreadActions();
185 await sidebar.unpinThread(target);
186 const staleUndo = currentUndo();
187 await header.pinThread(target, { orderKey: "a1" });
188 await header.unpinThread(target);
189 const latestUndo = currentUndo();
190 await staleUndo();
191 expect(commands.pin).toHaveBeenCalledTimes(1);
192 await latestUndo();
193 expect(commands.pin).toHaveBeenCalledTimes(2);
194 expect(commands.pin).toHaveBeenLastCalledWith({
195 environmentId: target.environmentId,
196 input: { threadId: target.threadId, orderKey: "a0" },
197 });
198 await latestUndo();
199 expect(commands.pin).toHaveBeenCalledTimes(2);
200 });
201});
202
203describe("archive Undo", () => {
204 it("unarchives and returns to the thread when archiving left it", async () => {
205 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
206 router.state.matches[0]!.params = {
207 environmentId: target.environmentId,
208 threadId: target.threadId,
209 };
210 const actions = useThreadActions();
211 await actions.archiveThread(target);
212 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 });
213 expect(add).not.toHaveBeenCalled();
214 await currentUndo()();
215 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
216 environmentId: target.environmentId,
217 input: { threadId: target.threadId },
218 });
219 expect(router.navigate).toHaveBeenCalledWith(
220 expect.objectContaining({
221 to: "/$environmentId/$threadId",
222 params: { environmentId: target.environmentId, threadId: target.threadId },
223 }),
224 );
225 });
226});
227
228describe("archive navigation", () => {
229 it.each([
230 { destination: "/undo-env/thread", expected: "/draft/project" },
231 { destination: "/undo-env/other-thread", expected: "/undo-env/other-thread" },
232 { destination: "/settings", expected: "/settings" },
233 ])("ends at $expected after opening $destination while archiving", async (route) => {
234 router.state.location.href = "/undo-env/thread";
235 router.state.matches[0]!.params = {
236 environmentId: target.environmentId,
237 threadId: target.threadId,
238 };
239 let finishArchive!: () => void;
240 commands.archive.mockReturnValue(
241 new Promise((resolve) => {
242 finishArchive = () => resolve({ _tag: "Success", value: undefined });
243 }),
244 );
245 const archived = useThreadActions().archiveThread(target);
246 router.state.location.href = route.destination;
247 finishArchive();
248 expect((await archived)._tag).toBe("Success");
249 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived" });
250 expect(router.state.location.href).toBe(route.expected);
251 });
252});
253
254describe("settle and snooze Undo", () => {
255 it("un-settles from the notice and expires the Undo after a manual un-settle", async () => {
256 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
257 const actions = useThreadActions();
258 await actions.settleThread(target);
259 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 });
260 expect(add).not.toHaveBeenCalled();
261 const undo = currentUndo();
262 await actions.unsettleThread(target);
263 await undo();
264 expect(commands.unsettle).toHaveBeenCalledOnce();
265 });
266
267 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
268 const snoozedUntil = "2030-01-01T09:00:00.000Z";
269 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
270 threadShell.snoozedUntil = snoozedUntil;
271 const actions = useThreadActions();
272 await actions.settleThread(target);
273 await currentUndo()();
274 expect(commands.unsettle).toHaveBeenCalledOnce();
275 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
276 environmentId: target.environmentId,
277 input: { threadId: target.threadId, orderKey: "a0" },
278 });
279 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
280 environmentId: target.environmentId,
281 input: { threadId: target.threadId, snoozedUntil },
282 });
283 });
284
285 it("stops settle restoration if restoring the pin fails", async () => {
286 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
287 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
288 commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
289 vi.spyOn(toastManager, "add").mockReturnValue("toast");
290 await useThreadActions().settleThread(target);
291 await currentUndo()();
292 expect(commands.unsettle).toHaveBeenCalledOnce();
293 expect(commands.pin).toHaveBeenCalledOnce();
294 expect(commands.snooze).not.toHaveBeenCalled();
295 });
296
297 it("expires an older unpin Undo when the thread is settled", async () => {
298 const actions = useThreadActions();
299 await actions.unpinThread(target);
300 const staleUnpinUndo = currentUndo();
301 await actions.settleThread(target);
302 await staleUnpinUndo();
303 expect(commands.pin).not.toHaveBeenCalled();
304 });
305
306 // regression: #12972 the sidebar undo notice must reverse a snooze
307 it("wakes the thread from the snooze notice", async () => {
308 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
309 const actions = useThreadActions();
310 await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
311 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
312 expect(add).not.toHaveBeenCalled();
313 await currentUndo()();
314 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
315 environmentId: target.environmentId,
316 input: { threadId: target.threadId, reason: "user" },
317 });
318 });
319});
320
321describe("archive and delete Undo expiry", () => {
322 const otherThread = { environmentId: target.environmentId, threadId: ThreadId.make("other") };
323 const otherEnvironment = {
324 environmentId: EnvironmentId.make("other-env"),
325 threadId: target.threadId,
326 };
327 const failure = { _tag: "Failure", cause: Cause.fail(new Error("Request failed")) };
328
329 describe.each(["archiveThread", "deleteThread"] as const)("%s", (lifecycle) => {
330 it.each([
331 ["settleThread", "unsettle"],
332 ["snoozeThread", "unsnooze"],
333 ["unpinThread", "pin"],
334 ] as const)(
335 "expires an earlier %s Undo for that thread only, across hook instances",
336 async (handler, inverse) => {
337 const sidebar = useThreadActions();
338 const header = useThreadActions();
339 for (const ref of [otherThread, otherEnvironment, target]) {
340 await (handler === "snoozeThread"
341 ? sidebar.snoozeThread(ref, "2099-01-01T09:00:00.000Z")
342 : sidebar[handler](ref));
343 }
344 const staleUndo = currentUndo();
345 await header[lifecycle](target);
346 await staleUndo();
347 expect(commands[inverse]).toHaveBeenCalledTimes(2);
348 expect(commands[inverse]).not.toHaveBeenCalledWith(
349 expect.objectContaining({
350 environmentId: target.environmentId,
351 input: expect.objectContaining({ threadId: target.threadId }),
352 }),
353 );
354 },
355 );
356
357 it("keeps the earlier Undo when the request fails", async () => {
358 const actions = useThreadActions();
359 await actions.settleThread(target);
360 commands[lifecycle === "archiveThread" ? "archive" : "delete"].mockResolvedValue(failure);
361 await actions[lifecycle](target);
362 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled" });
363 await currentUndo()();
364 expect(commands.unsettle).toHaveBeenCalledOnce();
365 });
366 });
367
368 it.each([true, false])(
369 "expires the Archived Undo when deleting with shell loaded: %s",
370 async (loaded) => {
371 const actions = useThreadActions();
372 await actions.archiveThread(target);
373 const staleUndo = currentUndo();
374 shellLoaded.current = loaded;
375 await actions.deleteThread(target);
376 expect(useThreadUndoNotice.getState().notice).toBeNull();
377 await staleUndo();
378 expect(commands.unarchive).not.toHaveBeenCalled();
379 },
380 );
381});