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 reorderActive: vi.fn(),
22}));
23const router = vi.hoisted(() => {
24 const listeners = new Set<(event: { action: { type: string } }) => void>();
25 return {
26 navigate: vi.fn(async () => {}),
27 state: { location: { href: "/" }, matches: [{ params: {} as Record<string, string> }] },
28 history: {
29 listeners,
30 subscribe: (listener: (event: { action: { type: string } }) => void) => {
31 listeners.add(listener);
32 return () => listeners.delete(listener);
33 },
34 },
35 };
36});
37vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
38vi.mock("../state/session", async (original) => ({
39 ...(await original<typeof import("../state/session")>()),
40 readEnvironmentScope: () => true,
41}));
42vi.mock("react", async (original) => ({
43 ...(await original<typeof import("react")>()),
44 useCallback: (callback: unknown) => callback,
45 useMemo: (create: () => unknown) => create(),
46 useRef: (value: unknown) => ({ current: value }),
47}));
48vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));
49vi.mock("./useSettings", () => ({ useClientSettings: () => false }));
50vi.mock("./useHandleNewThread", () => ({
51 useNewThreadHandler: () => async () => {
52 router.state.location.href = "/draft/project";
53 },
54}));
55vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));
56vi.mock("../lib/composerDraftUploads", () => ({ releaseComposerDraftUploads: vi.fn() }));
57vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));
58vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));
59vi.mock("../lib/announce", () => ({ announce: vi.fn(), cancelAnnouncement: vi.fn() }));
60vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));
61const threadShell = vi.hoisted(() => ({
62 title: "Thread",
63 pinOrderKey: "a0" as string | null,
64 pinnedAt: null as string | null,
65 activeOrderKey: null as string | null,
66 unsettledAt: null as string | null,
67 snoozedUntil: null as string | null,
68 projectId: "project",
69 environmentId: "undo-env",
70 session: null,
71}));
72// Archived rows have no loaded shell, so deleting one takes the unresolved path.
73const shellLoaded = vi.hoisted(() => ({ current: true }));
74vi.mock("../state/entities", async (original) => ({
75 ...(await original<typeof import("../state/entities")>()),
76 readEnvironmentServerConfigLoaded: () => true,
77 readThreadShell: () => (shellLoaded.current ? threadShell : null),
78}));
79vi.mock("../state/use-atom-command", () => ({
80 useAtomCommand: (command: unknown) => {
81 switch (command) {
82 case threadEnvironment.pin:
83 return commands.pin;
84 case threadEnvironment.unpin:
85 return commands.unpin;
86 case threadEnvironment.archive:
87 return commands.archive;
88 case threadEnvironment.unarchive:
89 return commands.unarchive;
90 case threadEnvironment.delete:
91 return commands.delete;
92 case threadEnvironment.settle:
93 return commands.settle;
94 case threadEnvironment.unsettle:
95 return commands.unsettle;
96 case threadEnvironment.snooze:
97 return commands.snooze;
98 case threadEnvironment.unsnooze:
99 return commands.unsnooze;
100 case threadEnvironment.reorderActive:
101 return commands.reorderActive;
102 default:
103 return vi.fn();
104 }
105 },
106}));
107
108const target = {
109 environmentId: EnvironmentId.make("undo-env"),
110 threadId: ThreadId.make("thread"),
111};
112function currentUndo() {
113 const notice = useThreadUndoNotice.getState().notice;
114 expect(notice).not.toBeNull();
115 return notice!.undo;
116}
117
118beforeEach(() => {
119 vi.useFakeTimers();
120 for (const command of Object.values(commands)) {
121 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
122 }
123 router.navigate.mockClear();
124 router.state.location.href = "/";
125 router.state.matches[0]!.params = {};
126 threadShell.pinOrderKey = "a0";
127 threadShell.pinnedAt = null;
128 threadShell.activeOrderKey = null;
129 threadShell.unsettledAt = null;
130 threadShell.snoozedUntil = null;
131 shellLoaded.current = true;
132});
133afterEach(() => {
134 vi.runAllTimers();
135 vi.useRealTimers();
136 vi.restoreAllMocks();
137});
138
139describe("concurrent thread action Undo", () => {
140 it.each([
141 ["settleThread", "settle", "unsettle", "Settled"],
142 ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
143 ["unpinThread", "unpin", "pin", "Unpinned"],
144 ["archiveThread", "archive", "unarchive", "Archived"],
145 ] as const)(
146 "%s retains one undo for concurrent successful requests",
147 async (handler, action, inverse, notice) => {
148 const actions = useThreadActions();
149 const run = () =>
150 handler === "snoozeThread"
151 ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
152 : actions[handler](target);
153 await Promise.all([run(), run()]);
154 expect(commands[action]).toHaveBeenCalledTimes(2);
155 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
156 await currentUndo()();
157 expect(commands[inverse]).toHaveBeenCalledOnce();
158 },
159 );
160});
161
162describe("pin", () => {
163 it("announces that the thread was pinned", async () => {
164 vi.mocked(announce).mockClear();
165 await useThreadActions().pinThread(target);
166 expect(announce).toHaveBeenCalledExactlyOnceWith("Pinned 1 thread");
167 });
168});
169
170describe("unpin Undo", () => {
171 it("restores the original snooze after restoring the pin", async () => {
172 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
173 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
174 await useThreadActions().unpinThread(target);
175 vi.mocked(announce).mockClear();
176 await currentUndo()();
177 expect(announce).not.toHaveBeenCalledWith("Pinned 1 thread");
178 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
179 environmentId: target.environmentId,
180 input: { threadId: target.threadId, orderKey: "a0" },
181 });
182 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
183 environmentId: target.environmentId,
184 input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
185 });
186 expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
187 commands.snooze.mock.invocationCallOrder[0]!,
188 );
189 });
190
191 it("restores a pin saved without an order key in its place instead of at the top", async () => {
192 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
193 threadShell.pinOrderKey = null;
194 await useThreadActions().unpinThread(target);
195 await currentUndo()();
196 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
197 environmentId: target.environmentId,
198 input: { threadId: target.threadId },
199 });
200 });
201
202 it("restores the pin without an already expired snooze", async () => {
203 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
204 threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
205 await useThreadActions().unpinThread(target);
206 await currentUndo()();
207 expect(commands.pin).toHaveBeenCalledOnce();
208 expect(commands.snooze).not.toHaveBeenCalled();
209 });
210
211 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
212 const sidebar = useThreadActions();
213 const header = useThreadActions();
214 await sidebar.unpinThread(target);
215 const staleUndo = currentUndo();
216 await header.pinThread(target, { orderKey: "a1" });
217 await header.unpinThread(target);
218 const latestUndo = currentUndo();
219 await staleUndo();
220 expect(commands.pin).toHaveBeenCalledTimes(1);
221 await latestUndo();
222 expect(commands.pin).toHaveBeenCalledTimes(2);
223 expect(commands.pin).toHaveBeenLastCalledWith({
224 environmentId: target.environmentId,
225 input: { threadId: target.threadId, orderKey: "a0" },
226 });
227 await latestUndo();
228 expect(commands.pin).toHaveBeenCalledTimes(2);
229 });
230});
231
232describe("archive Undo", () => {
233 it("unarchives and returns to the thread when archiving left it", async () => {
234 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
235 router.state.matches[0]!.params = {
236 environmentId: target.environmentId,
237 threadId: target.threadId,
238 };
239 const actions = useThreadActions();
240 await actions.archiveThread(target);
241 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 });
242 expect(add).not.toHaveBeenCalled();
243 await currentUndo()();
244 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
245 environmentId: target.environmentId,
246 input: { threadId: target.threadId },
247 });
248 expect(router.navigate).toHaveBeenCalledWith(
249 expect.objectContaining({
250 to: "/$environmentId/$threadId",
251 params: { environmentId: target.environmentId, threadId: target.threadId },
252 }),
253 );
254 });
255});
256
257describe("archive navigation", () => {
258 it.each([
259 { destination: "/undo-env/thread", expected: "/draft/project" },
260 { destination: "/undo-env/other-thread", expected: "/undo-env/other-thread" },
261 { destination: "/settings", expected: "/settings" },
262 ])("ends at $expected after opening $destination while archiving", async (route) => {
263 router.state.location.href = "/undo-env/thread";
264 router.state.matches[0]!.params = {
265 environmentId: target.environmentId,
266 threadId: target.threadId,
267 };
268 let finishArchive!: () => void;
269 commands.archive.mockReturnValue(
270 new Promise((resolve) => {
271 finishArchive = () => resolve({ _tag: "Success", value: undefined });
272 }),
273 );
274 const archived = useThreadActions().archiveThread(target);
275 router.state.location.href = route.destination;
276 finishArchive();
277 expect((await archived)._tag).toBe("Success");
278 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived" });
279 expect(router.state.location.href).toBe(route.expected);
280 });
281});
282
283describe("delete navigation", () => {
284 it.each([
285 { type: "REPLACE", by: "the app's missing-thread redirect", fallsBack: true },
286 { type: "PUSH", by: "the user opening another thread", fallsBack: false },
287 ])("falls back: $fallsBack after $by while deleting", async ({ type, fallsBack }) => {
288 router.state.matches[0]!.params = {
289 environmentId: target.environmentId,
290 threadId: target.threadId,
291 };
292 commands.delete.mockImplementation(async () => {
293 for (const listener of router.history.listeners) listener({ action: { type } });
294 return { _tag: "Success", value: undefined };
295 });
296 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
297 expect(router.navigate).toHaveBeenCalledTimes(fallsBack ? 1 : 0);
298 expect(router.history.listeners.size).toBe(0);
299 });
300});
301
302describe("settle and snooze Undo", () => {
303 it("un-settles from the notice and expires the Undo after a manual un-settle", async () => {
304 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
305 const actions = useThreadActions();
306 await actions.settleThread(target);
307 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 });
308 expect(add).not.toHaveBeenCalled();
309 const undo = currentUndo();
310 await actions.unsettleThread(target);
311 await undo();
312 expect(commands.unsettle).toHaveBeenCalledOnce();
313 });
314
315 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
316 const snoozedUntil = "2030-01-01T09:00:00.000Z";
317 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
318 threadShell.snoozedUntil = snoozedUntil;
319 const actions = useThreadActions();
320 await actions.settleThread(target);
321 await currentUndo()();
322 expect(commands.unsettle).toHaveBeenCalledOnce();
323 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
324 environmentId: target.environmentId,
325 input: { threadId: target.threadId, orderKey: "a0" },
326 });
327 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
328 environmentId: target.environmentId,
329 input: { threadId: target.threadId, snoozedUntil },
330 });
331 });
332
333 it("puts a manually ordered thread back in its active position", async () => {
334 threadShell.activeOrderKey = "b5";
335 await useThreadActions().settleThread(target);
336 await currentUndo()();
337 expect(commands.unsettle).toHaveBeenCalledOnce();
338 expect(commands.reorderActive).toHaveBeenCalledExactlyOnceWith({
339 environmentId: target.environmentId,
340 input: { threadId: target.threadId, orderKey: "b5" },
341 });
342 expect(commands.unsettle.mock.invocationCallOrder[0]).toBeLessThan(
343 commands.reorderActive.mock.invocationCallOrder[0]!,
344 );
345 });
346
347 it("puts an automatically ordered thread back at its Active anchor", async () => {
348 threadShell.unsettledAt = "2026-01-02T00:00:00.000Z";
349 await useThreadActions().settleThread(target);
350 await currentUndo()();
351 expect(commands.unsettle).toHaveBeenCalledExactlyOnceWith({
352 environmentId: target.environmentId,
353 input: {
354 threadId: target.threadId,
355 reason: "user",
356 restoreUnsettledAt: "2026-01-02T00:00:00.000Z",
357 },
358 });
359 expect(commands.reorderActive).not.toHaveBeenCalled();
360 });
361
362 it("stops settle restoration if restoring the pin fails", async () => {
363 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
364 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
365 commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
366 vi.spyOn(toastManager, "add").mockReturnValue("toast");
367 await useThreadActions().settleThread(target);
368 await currentUndo()();
369 expect(commands.unsettle).toHaveBeenCalledOnce();
370 expect(commands.pin).toHaveBeenCalledOnce();
371 expect(commands.snooze).not.toHaveBeenCalled();
372 });
373
374 describe("a settle still waiting to sync", () => {
375 const snoozedUntil = "2030-01-01T09:00:00.000Z";
376 const cancelledOnDevice = { _tag: "Success", value: { sequence: 0, cancelledOnDevice: true } };
377
378 it("re-snoozes a thread whose queued snooze the settle replaced", async () => {
379 // Snoozed offline: the queued snooze shows the thread snoozed.
380 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
381 threadShell.snoozedUntil = snoozedUntil;
382 await useThreadActions().settleThread(target);
383 // The settle replaced the queued snooze; cancelling it leaves the thread unsnoozed.
384 threadShell.snoozedUntil = null;
385 commands.unsettle.mockResolvedValue(cancelledOnDevice);
386 await currentUndo()();
387 expect(commands.pin).not.toHaveBeenCalled();
388 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
389 environmentId: target.environmentId,
390 input: { threadId: target.threadId, snoozedUntil },
391 });
392 });
393
394 it("leaves a snooze the environment still holds alone", async () => {
395 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
396 threadShell.snoozedUntil = snoozedUntil;
397 await useThreadActions().settleThread(target);
398 commands.unsettle.mockResolvedValue(cancelledOnDevice);
399 await currentUndo()();
400 expect(commands.pin).not.toHaveBeenCalled();
401 expect(commands.snooze).not.toHaveBeenCalled();
402 });
403 });
404
405 it("expires an older unpin Undo when the thread is settled", async () => {
406 const actions = useThreadActions();
407 await actions.unpinThread(target);
408 const staleUnpinUndo = currentUndo();
409 await actions.settleThread(target);
410 await staleUnpinUndo();
411 expect(commands.pin).not.toHaveBeenCalled();
412 });
413
414 // regression: #12972 the sidebar undo notice must reverse a snooze
415 it("wakes the thread from the snooze notice", async () => {
416 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
417 const actions = useThreadActions();
418 await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
419 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
420 expect(add).not.toHaveBeenCalled();
421 await currentUndo()();
422 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
423 environmentId: target.environmentId,
424 input: { threadId: target.threadId, reason: "user" },
425 });
426 });
427});
428
429describe("archive and delete Undo expiry", () => {
430 const otherThread = { environmentId: target.environmentId, threadId: ThreadId.make("other") };
431 const otherEnvironment = {
432 environmentId: EnvironmentId.make("other-env"),
433 threadId: target.threadId,
434 };
435 const failure = { _tag: "Failure", cause: Cause.fail(new Error("Request failed")) };
436
437 describe.each(["archiveThread", "deleteThread"] as const)("%s", (lifecycle) => {
438 it.each([
439 ["settleThread", "unsettle"],
440 ["snoozeThread", "unsnooze"],
441 ["unpinThread", "pin"],
442 ] as const)(
443 "expires an earlier %s Undo for that thread only, across hook instances",
444 async (handler, inverse) => {
445 const sidebar = useThreadActions();
446 const header = useThreadActions();
447 for (const ref of [otherThread, otherEnvironment, target]) {
448 await (handler === "snoozeThread"
449 ? sidebar.snoozeThread(ref, "2099-01-01T09:00:00.000Z")
450 : sidebar[handler](ref));
451 }
452 const staleUndo = currentUndo();
453 await header[lifecycle](target);
454 await staleUndo();
455 expect(commands[inverse]).toHaveBeenCalledTimes(2);
456 expect(commands[inverse]).not.toHaveBeenCalledWith(
457 expect.objectContaining({
458 environmentId: target.environmentId,
459 input: expect.objectContaining({ threadId: target.threadId }),
460 }),
461 );
462 },
463 );
464
465 it("keeps the earlier Undo when the request fails", async () => {
466 const actions = useThreadActions();
467 await actions.settleThread(target);
468 commands[lifecycle === "archiveThread" ? "archive" : "delete"].mockResolvedValue(failure);
469 await actions[lifecycle](target);
470 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled" });
471 await currentUndo()();
472 expect(commands.unsettle).toHaveBeenCalledOnce();
473 });
474 });
475
476 it.each([true, false])(
477 "expires the Archived Undo when deleting with shell loaded: %s",
478 async (loaded) => {
479 const actions = useThreadActions();
480 await actions.archiveThread(target);
481 const staleUndo = currentUndo();
482 shellLoaded.current = loaded;
483 await actions.deleteThread(target);
484 expect(useThreadUndoNotice.getState().notice).toBeNull();
485 await staleUndo();
486 expect(commands.unarchive).not.toHaveBeenCalled();
487 },
488 );
489});