Skip to content

Commit c6ffee9

Browse files
refactor(web): share thread Undo claims and toast lifecycle
1 parent 8a31fca commit c6ffee9

8 files changed

Lines changed: 235 additions & 97 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import { AsyncResult } from "effect/unstable/reactivity";
2+
import * as Cause from "effect/Cause";
3+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
4+
5+
import { toastManager } from "../components/ui/toast";
6+
import { showUndoToast } from "./showUndoToast";
7+
import * as ThreadUndo from "./threadUndo";
8+
9+
afterEach(() => vi.restoreAllMocks());
10+
11+
function setup() {
12+
const add = vi.spyOn(toastManager, "add").mockReturnValue("undo-toast");
13+
const close = vi.spyOn(toastManager, "close").mockImplementation(() => {});
14+
const undo = vi.fn(async () => AsyncResult.success(undefined));
15+
const claim = ThreadUndo.begin("pin", "env/thread");
16+
const options = {
17+
title: "Thread unpinned",
18+
description: "Thread",
19+
failureTitle: "Restore failed",
20+
undo,
21+
claim,
22+
};
23+
return { add, close, undo, claim, options };
24+
}
25+
26+
function click(add: ReturnType<typeof setup>["add"], index = 0) {
27+
const handler = add.mock.calls[index]?.[0].actionProps?.onClick;
28+
if (!handler) throw new Error("Undo action is missing");
29+
return handler({} as Parameters<typeof handler>[0]);
30+
}
31+
32+
describe("showUndoToast", () => {
33+
it("ignores a stale toast and lets the latest action run only once", async () => {
34+
const { add, close, undo, options } = setup();
35+
showUndoToast(options);
36+
ThreadUndo.invalidate("pin", "env/thread");
37+
showUndoToast({ ...options, claim: ThreadUndo.begin("pin", "env/thread") });
38+
await click(add);
39+
expect(undo).not.toHaveBeenCalled();
40+
await click(add, 1);
41+
await click(add, 1);
42+
expect(undo).toHaveBeenCalledOnce();
43+
expect(close).toHaveBeenCalledExactlyOnceWith("undo-toast");
44+
});
45+
46+
it("releases the claim on close and rejects a later click", async () => {
47+
const { add, undo, claim, options } = setup();
48+
showUndoToast(options);
49+
add.mock.calls[0]?.[0].onClose?.();
50+
expect(claim.isCurrent()).toBe(false);
51+
await click(add);
52+
expect(undo).not.toHaveBeenCalled();
53+
});
54+
55+
it("does not show a toast for a late completion after a newer action", () => {
56+
const { add, options } = setup();
57+
ThreadUndo.invalidate("pin", "env/thread");
58+
showUndoToast(options);
59+
expect(add).not.toHaveBeenCalled();
60+
});
61+
62+
it("reports a failed restore and releases its claim", async () => {
63+
const { add, claim, options } = setup();
64+
showUndoToast({
65+
...options,
66+
undo: async () => AsyncResult.failure(Cause.fail(new Error("offline"))),
67+
});
68+
await click(add);
69+
expect(add).toHaveBeenLastCalledWith(
70+
expect.objectContaining({ type: "error", title: "Restore failed", description: "offline" }),
71+
);
72+
expect(claim.isCurrent()).toBe(false);
73+
});
74+
75+
it("reports a rejected restore promise", async () => {
76+
const { add, options } = setup();
77+
showUndoToast({
78+
...options,
79+
undo: async () => {
80+
throw new Error("disconnected");
81+
},
82+
});
83+
await click(add);
84+
expect(add).toHaveBeenLastCalledWith(
85+
expect.objectContaining({ type: "error", description: "disconnected" }),
86+
);
87+
});
88+
89+
it("does not report interrupted restores as errors", async () => {
90+
const { add, options } = setup();
91+
showUndoToast({ ...options, undo: async () => AsyncResult.failure(Cause.interrupt()) });
92+
await click(add);
93+
expect(add).toHaveBeenCalledOnce();
94+
});
95+
});
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import {
2+
type AtomCommandResult,
3+
isAtomCommandInterrupted,
4+
squashAtomCommandFailure,
5+
} from "@t3tools/client-runtime/state/runtime";
6+
7+
import { stackedThreadToast, toastManager } from "../components/ui/toast";
8+
import type * as ThreadUndo from "./threadUndo";
9+
10+
/** Shows a single-use Undo while its thread action still owns the claim. */
11+
export function showUndoToast({
12+
title,
13+
description,
14+
undo,
15+
failureTitle,
16+
claim,
17+
}: {
18+
title: string;
19+
description: string | undefined;
20+
undo: () => Promise<AtomCommandResult<unknown, unknown>>;
21+
failureTitle: string;
22+
claim: ReturnType<typeof ThreadUndo.begin>;
23+
}) {
24+
if (!claim.isCurrent()) return;
25+
let undoStarted = false;
26+
const reportFailure = (error: unknown) => {
27+
toastManager.add(
28+
stackedThreadToast({
29+
type: "error",
30+
title: failureTitle,
31+
description: error instanceof Error ? error.message : "An error occurred.",
32+
}),
33+
);
34+
};
35+
const toastId = toastManager.add({
36+
...stackedThreadToast({
37+
type: "success",
38+
title,
39+
description,
40+
timeout: 5_000,
41+
actionProps: {
42+
children: "Undo",
43+
onClick: async () => {
44+
if (undoStarted || !claim.isCurrent()) return;
45+
undoStarted = true;
46+
claim.finish();
47+
toastManager.close(toastId);
48+
try {
49+
const result = await undo();
50+
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
51+
reportFailure(squashAtomCommandFailure(result));
52+
}
53+
} catch (error) {
54+
reportFailure(error);
55+
}
56+
},
57+
},
58+
}),
59+
onClose: claim.finish,
60+
});
61+
}

‎apps/web/src/hooks/threadPinAction.test.ts‎

Lines changed: 0 additions & 35 deletions
This file was deleted.

‎apps/web/src/hooks/threadPinAction.ts‎

Lines changed: 0 additions & 20 deletions
This file was deleted.
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
3+
import * as ThreadUndo from "./threadUndo";
4+
5+
describe("thread action ownership", () => {
6+
it("keeps claims for different action kinds independent", () => {
7+
const pin = ThreadUndo.begin("pin", "env/shared");
8+
const archive = ThreadUndo.begin("archive", "env/shared");
9+
ThreadUndo.invalidate("pin", "env/shared");
10+
expect(pin.isCurrent()).toBe(false);
11+
expect(archive.isCurrent()).toBe(true);
12+
archive.finish();
13+
});
14+
15+
it("does not revive the first Undo after a later pin and unpin", () => {
16+
const firstUnpin = ThreadUndo.begin("pin", "env/thread");
17+
ThreadUndo.invalidate("pin", "env/thread");
18+
const secondUnpin = ThreadUndo.begin("pin", "env/thread");
19+
expect(firstUnpin.isCurrent()).toBe(false);
20+
expect(secondUnpin.isCurrent()).toBe(true);
21+
firstUnpin.finish();
22+
expect(secondUnpin.isCurrent()).toBe(true);
23+
secondUnpin.finish();
24+
expect(firstUnpin.isCurrent()).toBe(false);
25+
});
26+
27+
it("rejects a late unpin completion after a newer pin started", () => {
28+
const pendingUnpin = ThreadUndo.begin("pin", "env/late");
29+
ThreadUndo.invalidate("pin", "env/late");
30+
expect(pendingUnpin.isCurrent()).toBe(false);
31+
});
32+
33+
it("expires an Undo without invalidating another environment or thread", () => {
34+
const first = ThreadUndo.begin("pin", "one/thread");
35+
const otherEnvironment = ThreadUndo.begin("pin", "two/thread");
36+
const otherThread = ThreadUndo.begin("pin", "one/other");
37+
first.finish();
38+
expect(first.isCurrent()).toBe(false);
39+
expect(otherEnvironment.isCurrent()).toBe(true);
40+
expect(otherThread.isCurrent()).toBe(true);
41+
otherEnvironment.finish();
42+
otherThread.finish();
43+
});
44+
});

‎apps/web/src/hooks/threadUndo.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Shared across hook instances so sidebar, header and menu actions invalidate each other.
2+
const currentActions = new Map<string, symbol>();
3+
4+
/** Claims one kind of thread action; a later claim of that kind expires its Undo. */
5+
export function begin(kind: string, threadKey: string) {
6+
const key = JSON.stringify([kind, threadKey]);
7+
const token = Symbol();
8+
currentActions.set(key, token);
9+
const isCurrent = () => currentActions.get(key) === token;
10+
return {
11+
isCurrent,
12+
finish: () => {
13+
if (isCurrent()) currentActions.delete(key);
14+
},
15+
};
16+
}
17+
18+
/** Expires only this action kind, leaving unrelated thread actions intact. */
19+
export function invalidate(kind: string, threadKey: string) {
20+
currentActions.delete(JSON.stringify([kind, threadKey]));
21+
}

‎apps/web/src/hooks/useThreadActions.ts‎

Lines changed: 12 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,7 @@ import {
44
scopeThreadRef,
55
scopedThreadKey,
66
} from "@t3tools/client-runtime/environment";
7-
import {
8-
isAtomCommandInterrupted,
9-
settlePromise,
10-
squashAtomCommandFailure,
11-
} from "@t3tools/client-runtime/state/runtime";
7+
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
128
import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
139
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
1410
import * as Cause from "effect/Cause";
@@ -43,7 +39,8 @@ import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
4339
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
4440
import { stackedThreadToast, toastManager } from "../components/ui/toast";
4541
import { useClientSettings } from "./useSettings";
46-
import * as ThreadPinAction from "./threadPinAction";
42+
import * as ThreadUndo from "./threadUndo";
43+
import { showUndoToast } from "./showUndoToast";
4744
import { useAtomCommand } from "../state/use-atom-command";
4845

4946
export class ThreadArchiveBlockedError extends Schema.TaggedError<ThreadArchiveBlockedError>()(
@@ -578,7 +575,7 @@ export function useThreadActions() {
578575
const orderKey = readEnvironmentSupportsPinReorder(target.environmentId)
579576
? (opts.orderKey ?? topOfPinnedRunOrderKey())
580577
: undefined;
581-
ThreadPinAction.invalidate(scopedThreadKey(target));
578+
ThreadUndo.invalidate("pin", scopedThreadKey(target));
582579
return pinThreadMutation({
583580
environmentId: target.environmentId,
584581
input: {
@@ -604,45 +601,18 @@ export function useThreadActions() {
604601
}
605602
const thread = readThreadShell(target);
606603
const orderKey = thread?.pinOrderKey ?? undefined;
607-
const action = ThreadPinAction.begin(scopedThreadKey(target));
604+
const action = ThreadUndo.begin("pin", scopedThreadKey(target));
608605
const result = await unpinThreadMutation({
609606
environmentId: target.environmentId,
610607
input: { threadId: target.threadId },
611608
});
612609
if (result._tag === "Success" && action.isCurrent()) {
613-
let undoStarted = false;
614-
// Reuses the app's Base UI toast action: https://base-ui.com/react/components/toast
615-
const toastId = toastManager.add({
616-
...stackedThreadToast({
617-
type: "success",
618-
title: "Thread unpinned",
619-
description: thread?.title,
620-
timeout: 5_000,
621-
actionProps: {
622-
children: "Undo",
623-
onClick: () => {
624-
if (undoStarted || !action.isCurrent()) return;
625-
undoStarted = true;
626-
toastManager.close(toastId);
627-
void pinThread(target, orderKey === undefined ? {} : { orderKey }).then(
628-
(undone) => {
629-
if (undone._tag === "Failure" && !isAtomCommandInterrupted(undone)) {
630-
const error = squashAtomCommandFailure(undone);
631-
toastManager.add(
632-
stackedThreadToast({
633-
type: "error",
634-
title: "Failed to undo unpin",
635-
description:
636-
error instanceof Error ? error.message : "An error occurred.",
637-
}),
638-
);
639-
}
640-
},
641-
);
642-
},
643-
},
644-
}),
645-
onClose: action.finish,
610+
showUndoToast({
611+
title: "Thread unpinned",
612+
description: thread?.title,
613+
claim: action,
614+
undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }),
615+
failureTitle: "Failed to undo unpin",
646616
});
647617
} else {
648618
action.finish();
@@ -687,7 +657,7 @@ export function useThreadActions() {
687657
),
688658
);
689659
}
690-
ThreadPinAction.invalidate(scopedThreadKey(target));
660+
ThreadUndo.invalidate("pin", scopedThreadKey(target));
691661
return reorderPinnedThreadMutation({
692662
environmentId: target.environmentId,
693663
input: { threadId: target.threadId, orderKey },

‎docs/user/thread-sidebar.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ worktree**, each background submission creates its own worktree.
2424

2525
Pin a thread from its menu to keep it above your active work.
2626

27+
On web and desktop, unpinning offers Undo for five seconds to restore the thread's pinned position.
28+
2729
On web and desktop, you can also drag files from your computer onto any thread row:
2830
the thread opens and the files are attached in its composer, ready for
2931
your next message. The same per-message file limits apply as when attaching

0 commit comments

Comments
 (0)