@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 446 lines 16.9 KB
Raw
1 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import * as Cause from "effect/Cause";
3 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5 import { useThreadActions } from "./useThreadActions";
6 import { threadEnvironment } from "../state/threads";
7 import { toastManager } from "../components/ui/toast";
8 import { useThreadUndoNotice } from "./showThreadUndoNotice";
9 import { announce } from "../lib/announce";
10
11 const 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 }));
23 const 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 });
37 vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
38 vi.mock("../state/session", async (original) => ({
39 ...(await original<typeof import("../state/session")>()),
40 readEnvironmentScope: () => true,
41 }));
42 vi.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 }));
48 vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));
49 vi.mock("./useSettings", () => ({ useClientSettings: () => false }));
50 vi.mock("./useHandleNewThread", () => ({
51 useNewThreadHandler: () => async () => {
52 router.state.location.href = "/draft/project";
53 },
54 }));
55 vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));
56 vi.mock("../lib/composerDraftUploads", () => ({ releaseComposerDraftUploads: vi.fn() }));
57 vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));
58 vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));
59 vi.mock("../lib/announce", () => ({ announce: vi.fn(), cancelAnnouncement: vi.fn() }));
60 vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));
61 const threadShell = vi.hoisted(() => ({
62 title: "Thread",
63 pinOrderKey: "a0",
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.
73 const shellLoaded = vi.hoisted(() => ({ current: true }));
74 vi.mock("../state/entities", async (original) => ({
75 ...(await original<typeof import("../state/entities")>()),
76 readEnvironmentServerConfigLoaded: () => true,
77 readThreadShell: () => (shellLoaded.current ? threadShell : null),
78 }));
79 vi.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
108 const target = {
109 environmentId: EnvironmentId.make("undo-env"),
110 threadId: ThreadId.make("thread"),
111 };
112 function currentUndo() {
113 const notice = useThreadUndoNotice.getState().notice;
114 expect(notice).not.toBeNull();
115 return notice!.undo;
116 }
117
118 beforeEach(() => {
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.pinnedAt = null;
127 threadShell.activeOrderKey = null;
128 threadShell.unsettledAt = null;
129 threadShell.snoozedUntil = null;
130 shellLoaded.current = true;
131 });
132 afterEach(() => {
133 vi.runAllTimers();
134 vi.useRealTimers();
135 vi.restoreAllMocks();
136 });
137
138 describe("concurrent thread action Undo", () => {
139 it.each([
140 ["settleThread", "settle", "unsettle", "Settled"],
141 ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
142 ["unpinThread", "unpin", "pin", "Unpinned"],
143 ["archiveThread", "archive", "unarchive", "Archived"],
144 ] as const)(
145 "%s retains one undo for concurrent successful requests",
146 async (handler, action, inverse, notice) => {
147 const actions = useThreadActions();
148 const run = () =>
149 handler === "snoozeThread"
150 ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
151 : actions[handler](target);
152 await Promise.all([run(), run()]);
153 expect(commands[action]).toHaveBeenCalledTimes(2);
154 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
155 await currentUndo()();
156 expect(commands[inverse]).toHaveBeenCalledOnce();
157 },
158 );
159 });
160
161 describe("pin", () => {
162 it("announces that the thread was pinned", async () => {
163 vi.mocked(announce).mockClear();
164 await useThreadActions().pinThread(target);
165 expect(announce).toHaveBeenCalledExactlyOnceWith("Pinned 1 thread");
166 });
167 });
168
169 describe("unpin Undo", () => {
170 it("restores the original snooze after restoring the pin", async () => {
171 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
172 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
173 await useThreadActions().unpinThread(target);
174 vi.mocked(announce).mockClear();
175 await currentUndo()();
176 expect(announce).not.toHaveBeenCalledWith("Pinned 1 thread");
177 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
178 environmentId: target.environmentId,
179 input: { threadId: target.threadId, orderKey: "a0" },
180 });
181 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
182 environmentId: target.environmentId,
183 input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
184 });
185 expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
186 commands.snooze.mock.invocationCallOrder[0]!,
187 );
188 });
189
190 it("restores the pin without an already expired snooze", async () => {
191 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
192 threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
193 await useThreadActions().unpinThread(target);
194 await currentUndo()();
195 expect(commands.pin).toHaveBeenCalledOnce();
196 expect(commands.snooze).not.toHaveBeenCalled();
197 });
198
199 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
200 const sidebar = useThreadActions();
201 const header = useThreadActions();
202 await sidebar.unpinThread(target);
203 const staleUndo = currentUndo();
204 await header.pinThread(target, { orderKey: "a1" });
205 await header.unpinThread(target);
206 const latestUndo = currentUndo();
207 await staleUndo();
208 expect(commands.pin).toHaveBeenCalledTimes(1);
209 await latestUndo();
210 expect(commands.pin).toHaveBeenCalledTimes(2);
211 expect(commands.pin).toHaveBeenLastCalledWith({
212 environmentId: target.environmentId,
213 input: { threadId: target.threadId, orderKey: "a0" },
214 });
215 await latestUndo();
216 expect(commands.pin).toHaveBeenCalledTimes(2);
217 });
218 });
219
220 describe("archive Undo", () => {
221 it("unarchives and returns to the thread when archiving left it", async () => {
222 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
223 router.state.matches[0]!.params = {
224 environmentId: target.environmentId,
225 threadId: target.threadId,
226 };
227 const actions = useThreadActions();
228 await actions.archiveThread(target);
229 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 });
230 expect(add).not.toHaveBeenCalled();
231 await currentUndo()();
232 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
233 environmentId: target.environmentId,
234 input: { threadId: target.threadId },
235 });
236 expect(router.navigate).toHaveBeenCalledWith(
237 expect.objectContaining({
238 to: "/$environmentId/$threadId",
239 params: { environmentId: target.environmentId, threadId: target.threadId },
240 }),
241 );
242 });
243 });
244
245 describe("archive navigation", () => {
246 it.each([
247 { destination: "/undo-env/thread", expected: "/draft/project" },
248 { destination: "/undo-env/other-thread", expected: "/undo-env/other-thread" },
249 { destination: "/settings", expected: "/settings" },
250 ])("ends at $expected after opening $destination while archiving", async (route) => {
251 router.state.location.href = "/undo-env/thread";
252 router.state.matches[0]!.params = {
253 environmentId: target.environmentId,
254 threadId: target.threadId,
255 };
256 let finishArchive!: () => void;
257 commands.archive.mockReturnValue(
258 new Promise((resolve) => {
259 finishArchive = () => resolve({ _tag: "Success", value: undefined });
260 }),
261 );
262 const archived = useThreadActions().archiveThread(target);
263 router.state.location.href = route.destination;
264 finishArchive();
265 expect((await archived)._tag).toBe("Success");
266 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived" });
267 expect(router.state.location.href).toBe(route.expected);
268 });
269 });
270
271 describe("delete navigation", () => {
272 it.each([
273 { type: "REPLACE", by: "the app's missing-thread redirect", fallsBack: true },
274 { type: "PUSH", by: "the user opening another thread", fallsBack: false },
275 ])("falls back: $fallsBack after $by while deleting", async ({ type, fallsBack }) => {
276 router.state.matches[0]!.params = {
277 environmentId: target.environmentId,
278 threadId: target.threadId,
279 };
280 commands.delete.mockImplementation(async () => {
281 for (const listener of router.history.listeners) listener({ action: { type } });
282 return { _tag: "Success", value: undefined };
283 });
284 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
285 expect(router.navigate).toHaveBeenCalledTimes(fallsBack ? 1 : 0);
286 expect(router.history.listeners.size).toBe(0);
287 });
288 });
289
290 describe("settle and snooze Undo", () => {
291 it("un-settles from the notice and expires the Undo after a manual un-settle", async () => {
292 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
293 const actions = useThreadActions();
294 await actions.settleThread(target);
295 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 });
296 expect(add).not.toHaveBeenCalled();
297 const undo = currentUndo();
298 await actions.unsettleThread(target);
299 await undo();
300 expect(commands.unsettle).toHaveBeenCalledOnce();
301 });
302
303 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
304 const snoozedUntil = "2030-01-01T09:00:00.000Z";
305 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
306 threadShell.snoozedUntil = snoozedUntil;
307 const actions = useThreadActions();
308 await actions.settleThread(target);
309 await currentUndo()();
310 expect(commands.unsettle).toHaveBeenCalledOnce();
311 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
312 environmentId: target.environmentId,
313 input: { threadId: target.threadId, orderKey: "a0" },
314 });
315 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
316 environmentId: target.environmentId,
317 input: { threadId: target.threadId, snoozedUntil },
318 });
319 });
320
321 it("puts a manually ordered thread back in its active position", async () => {
322 threadShell.activeOrderKey = "b5";
323 await useThreadActions().settleThread(target);
324 await currentUndo()();
325 expect(commands.unsettle).toHaveBeenCalledOnce();
326 expect(commands.reorderActive).toHaveBeenCalledExactlyOnceWith({
327 environmentId: target.environmentId,
328 input: { threadId: target.threadId, orderKey: "b5" },
329 });
330 expect(commands.unsettle.mock.invocationCallOrder[0]).toBeLessThan(
331 commands.reorderActive.mock.invocationCallOrder[0]!,
332 );
333 });
334
335 it("puts an automatically ordered thread back at its Active anchor", async () => {
336 threadShell.unsettledAt = "2026-01-02T00:00:00.000Z";
337 await useThreadActions().settleThread(target);
338 await currentUndo()();
339 expect(commands.unsettle).toHaveBeenCalledExactlyOnceWith({
340 environmentId: target.environmentId,
341 input: {
342 threadId: target.threadId,
343 reason: "user",
344 restoreUnsettledAt: "2026-01-02T00:00:00.000Z",
345 },
346 });
347 expect(commands.reorderActive).not.toHaveBeenCalled();
348 });
349
350 it("stops settle restoration if restoring the pin fails", async () => {
351 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
352 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
353 commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
354 vi.spyOn(toastManager, "add").mockReturnValue("toast");
355 await useThreadActions().settleThread(target);
356 await currentUndo()();
357 expect(commands.unsettle).toHaveBeenCalledOnce();
358 expect(commands.pin).toHaveBeenCalledOnce();
359 expect(commands.snooze).not.toHaveBeenCalled();
360 });
361
362 it("expires an older unpin Undo when the thread is settled", async () => {
363 const actions = useThreadActions();
364 await actions.unpinThread(target);
365 const staleUnpinUndo = currentUndo();
366 await actions.settleThread(target);
367 await staleUnpinUndo();
368 expect(commands.pin).not.toHaveBeenCalled();
369 });
370
371 // regression: #12972 the sidebar undo notice must reverse a snooze
372 it("wakes the thread from the snooze notice", async () => {
373 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
374 const actions = useThreadActions();
375 await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
376 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
377 expect(add).not.toHaveBeenCalled();
378 await currentUndo()();
379 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
380 environmentId: target.environmentId,
381 input: { threadId: target.threadId, reason: "user" },
382 });
383 });
384 });
385
386 describe("archive and delete Undo expiry", () => {
387 const otherThread = { environmentId: target.environmentId, threadId: ThreadId.make("other") };
388 const otherEnvironment = {
389 environmentId: EnvironmentId.make("other-env"),
390 threadId: target.threadId,
391 };
392 const failure = { _tag: "Failure", cause: Cause.fail(new Error("Request failed")) };
393
394 describe.each(["archiveThread", "deleteThread"] as const)("%s", (lifecycle) => {
395 it.each([
396 ["settleThread", "unsettle"],
397 ["snoozeThread", "unsnooze"],
398 ["unpinThread", "pin"],
399 ] as const)(
400 "expires an earlier %s Undo for that thread only, across hook instances",
401 async (handler, inverse) => {
402 const sidebar = useThreadActions();
403 const header = useThreadActions();
404 for (const ref of [otherThread, otherEnvironment, target]) {
405 await (handler === "snoozeThread"
406 ? sidebar.snoozeThread(ref, "2099-01-01T09:00:00.000Z")
407 : sidebar[handler](ref));
408 }
409 const staleUndo = currentUndo();
410 await header[lifecycle](target);
411 await staleUndo();
412 expect(commands[inverse]).toHaveBeenCalledTimes(2);
413 expect(commands[inverse]).not.toHaveBeenCalledWith(
414 expect.objectContaining({
415 environmentId: target.environmentId,
416 input: expect.objectContaining({ threadId: target.threadId }),
417 }),
418 );
419 },
420 );
421
422 it("keeps the earlier Undo when the request fails", async () => {
423 const actions = useThreadActions();
424 await actions.settleThread(target);
425 commands[lifecycle === "archiveThread" ? "archive" : "delete"].mockResolvedValue(failure);
426 await actions[lifecycle](target);
427 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled" });
428 await currentUndo()();
429 expect(commands.unsettle).toHaveBeenCalledOnce();
430 });
431 });
432
433 it.each([true, false])(
434 "expires the Archived Undo when deleting with shell loaded: %s",
435 async (loaded) => {
436 const actions = useThreadActions();
437 await actions.archiveThread(target);
438 const staleUndo = currentUndo();
439 shellLoaded.current = loaded;
440 await actions.deleteThread(target);
441 expect(useThreadUndoNotice.getState().notice).toBeNull();
442 await staleUndo();
443 expect(commands.unarchive).not.toHaveBeenCalled();
444 },
445 );
446 });