Skip to content
TypeScript

fix(mobile): restore archive and thread action undo (#21401)

maria6efe9a088eb3
diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx
index e15b861b341..8ab642eb44f 100644
--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx
+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx
@@ -1,3 +1,4 @@
+import { ThreadUndoNotice } from "./ThreadUndoNotice";
import { Toolbar } from "../../components/ui/Toolbar";
import { use } from "react";
import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
@@ -306,6 +307,7 @@ export function HomeRouteScreen() {
selectedProjectKey={selectedProjectKey}
threads={threads}
/>
+ <ThreadUndoNotice visible={visible} />
</>
</AndroidHomeFabLayout>
);
diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
new file mode 100644
index 00000000000..578dc356e6e
--- /dev/null
+++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx
@@ -0,0 +1,29 @@
+import { View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { Toast } from "../../components/ui/Toast";
+import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";
+import { dismissThreadUndoNotice, useThreadUndoNotice } from "./thread-undo-notice";
+
+export function ThreadUndoNotice(props: { readonly visible: boolean }) {
+ const notice = useThreadUndoNotice();
+ const insets = useSafeAreaInsets();
+ if (!props.visible || notice === null) return null;
+ return (
+ <View
+ className="absolute inset-x-3 z-[100]"
+ style={{ top: insets.top + APP_BAR_HEIGHT + 8 }}
+ pointerEvents="box-none"
+ >
+ <Toast
+ message={`${notice.action} thread`}
+ action={{
+ label: "Undo",
+ onPress: () => {
+ void notice.undo();
+ },
+ }}
+ onDismiss={dismissThreadUndoNotice}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/home/thread-undo-notice.ts b/apps/mobile/src/features/home/thread-undo-notice.ts
new file mode 100644
index 00000000000..5fa1385297a
--- /dev/null
+++ b/apps/mobile/src/features/home/thread-undo-notice.ts
@@ -0,0 +1,56 @@
+import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
+import { useSyncExternalStore } from "react";
+
+type UndoNotice = {
+ readonly action: "Settled" | "Snoozed" | "Unpinned";
+ readonly claim: ReturnType<typeof ThreadUndo.begin>;
+ readonly undo: () => Promise<void>;
+};
+
+let notice: UndoNotice | null = null;
+let expiry: ReturnType<typeof setTimeout> | undefined;
+const listeners = new Set<() => void>();
+
+function notify() {
+ for (const listener of listeners) listener();
+}
+
+export function readThreadUndoNotice() {
+ return notice;
+}
+
+export function dismissThreadUndoNotice() {
+ const previous = notice;
+ notice = null;
+ clearTimeout(expiry);
+ previous?.claim.finish();
+ notify();
+}
+
+ThreadUndo.subscribe(() => {
+ if (notice !== null && !notice.claim.isCurrent()) dismissThreadUndoNotice();
+});
+
+export function showThreadUndoNotice(options: UndoNotice) {
+ if (!options.claim.isCurrent()) return;
+ dismissThreadUndoNotice();
+ notice = {
+ ...options,
+ undo: async () => {
+ if (notice?.claim !== options.claim || !options.claim.isCurrent()) return;
+ dismissThreadUndoNotice();
+ await options.undo();
+ },
+ };
+ notify();
+ expiry = setTimeout(dismissThreadUndoNotice, 5_000);
+}
+
+export function useThreadUndoNotice() {
+ return useSyncExternalStore((listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ }, readThreadUndoNotice);
+}
diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts
index 93b3ef3cb4a..f82cffe3810 100644
--- a/apps/mobile/src/features/home/useThreadListActions.test.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts
@@ -5,6 +5,7 @@ import {
EnvironmentId,
ProjectId,
ProviderInstanceId,
+ RunId,
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -14,12 +15,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
const state = vi.hoisted(() => ({
pendingOrder: null as object | null,
dropBusy: false,
+ failedAction: null as string | null,
+ archivedRefreshes: [] as string[],
scopes: new Map<string, Set<string>>(),
shells: [] as EnvironmentThreadShell[],
requests: [] as {
action: string;
environmentId: string;
- input: { threadId: string; orderKey?: string };
+ input: { threadId: string; orderKey?: string; snoozedUntil?: string; reason?: string };
}[],
dialogs: [] as { onConfirm: () => void }[],
alerts: [] as {
@@ -49,7 +52,9 @@ vi.mock("../../components/ui/Dialog", () => ({
confirm: (dialog: { onConfirm: () => void }) => state.dialogs.push(dialog),
}));
vi.mock("../archive/useArchivedThreadSnapshots", () => ({
- refreshArchivedThreadsForEnvironment: () => {},
+ refreshArchivedThreadsForEnvironment: (environmentId: string) => {
+ state.archivedRefreshes.push(environmentId);
+ },
}));
vi.mock("../../state/session", () => ({
readEnvironmentScope: (environmentId: string, scope: string) =>
@@ -133,6 +138,8 @@ vi.mock("../../state/threads", () => ({
if (!state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope)) {
return AsyncResult.failure(Cause.fail(new Error("Thread operation denied")));
}
+ if (action === state.failedAction)
+ return AsyncResult.failure(Cause.fail(new Error("Server rejected action")));
state.afterRequest?.();
return AsyncResult.success(undefined);
},
@@ -140,6 +147,7 @@ vi.mock("../../state/threads", () => ({
),
}));
+import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice";
import { useArchivedThreadListActions, useThreadListActions } from "./useThreadListActions";
const primaryEnvironmentId = EnvironmentId.make("primary");
@@ -168,6 +176,8 @@ const mutationCases = [
] as const;
beforeEach(() => {
+ state.failedAction = null;
+ state.archivedRefreshes = [];
state.pendingOrder = null;
state.dropBusy = false;
state.scopes = new Map([
@@ -181,7 +191,11 @@ beforeEach(() => {
state.afterRequest = undefined;
});
-afterEach(() => vi.unstubAllEnvs());
+afterEach(() => {
+ dismissThreadUndoNotice();
+ vi.useRealTimers();
+ vi.unstubAllEnvs();
+});
describe("thread list operation permissions", () => {
it.each(mutationCases)(
@@ -315,3 +329,193 @@ describe("pinned thread operation permissions", () => {
expect(state.requests).toHaveLength(1);
});
});
+
+describe("thread action undo", () => {
+ it.each([
+ ["settleThread", "settle", "Settled", "unsettle"],
+ ["snoozeThread", "snooze", "Snoozed", "unsnooze"],
+ ] as const)(
+ "%s keeps the successful request's undo when a duplicate is rejected",
+ async (handler, action, notice, inverse) => {
+ const actions = useThreadListActions();
+ const thread = makeThread();
+ const first = actions[handler](thread, "2099-01-01T09:00:00.000Z");
+
+ expect(await actions[handler](thread, "2099-01-01T09:00:00.000Z")).toBe(false);
+ expect(await first).toBe(true);
+ expect(state.requests.map(({ action }) => action)).toEqual([action]);
+ expect(readThreadUndoNotice()?.action).toBe(notice);
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.map(({ action }) => action)).toEqual([action, inverse]);
+ },
+ );
+
+ it("keeps the latest unpin undo after concurrent unpin requests", async () => {
+ const actions = useThreadListActions();
+ const thread = makeThread();
+ expect(await Promise.all([actions.unpinThread(thread), actions.unpinThread(thread)])).toEqual([
+ true,
+ true,
+ ]);
+ expect(readThreadUndoNotice()?.action).toBe("Unpinned");
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.map(({ action }) => action)).toEqual(["unpin", "unpin", "pin"]);
+ });
+
+ it("rejects a concurrent archive request without sending another mutation", async () => {
+ const actions = useThreadListActions();
+ const thread = makeThread();
+ const first = actions.archiveThread(thread);
+ expect(await actions.archiveThread(thread)).toBe(false);
+ expect(await first).toBe(true);
+ expect(state.requests.map(({ action }) => action)).toEqual(["archive"]);
+ expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]);
+ });
+
+ it("restores pin placement and snooze after settling, only once", async () => {
+ const thread = makeThread({
+ pinnedAt: "2026-09-02T00:00:00.000Z",
+ pinOrderKey: "m",
+ snoozedUntil: "2099-01-01T09:00:00.000Z",
+ });
+ expect(await useThreadListActions().settleThread(thread)).toBe(true);
+ const undo = readThreadUndoNotice()!.undo;
+ expect(readThreadUndoNotice()?.action).toBe("Settled");
+ await undo();
+ await undo();
+ expect(state.requests.map(({ action }) => action)).toEqual([
+ "settle",
+ "unsettle",
+ "pin",
+ "snooze",
+ ]);
+ expect(state.requests[2]?.input).toEqual({ threadId: thread.id, orderKey: "m" });
+ expect(state.requests[3]?.input).toEqual({
+ threadId: thread.id,
+ snoozedUntil: thread.snoozedUntil,
+ });
+ expect(readThreadUndoNotice()).toBeNull();
+ });
+
+ it("wakes a snoozed thread through the undo action", async () => {
+ const thread = makeThread();
+ await useThreadListActions().snoozeThread(thread, "2099-01-01T09:00:00.000Z");
+ expect(readThreadUndoNotice()?.action).toBe("Snoozed");
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.at(-1)).toMatchObject({
+ action: "unsnooze",
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id, reason: "user" },
+ });
+ });
+
+ it.each([null, "2099-01-01T09:00:00.000Z", "2000-01-01T09:00:00.000Z"])(
+ "restores an unpinned thread's previous position and unexpired snooze (%s)",
+ async (snoozedUntil) => {
+ const thread = makeThread({
+ pinnedAt: "2026-09-02T00:00:00.000Z",
+ pinOrderKey: "m",
+ snoozedUntil,
+ });
+ await useThreadListActions().unpinThread(thread);
+ expect(readThreadUndoNotice()?.action).toBe("Unpinned");
+ await readThreadUndoNotice()!.undo();
+ const restoresSnooze = snoozedUntil != null && Date.parse(snoozedUntil) > Date.now();
+ expect(state.requests.map(({ action }) => action)).toEqual(
+ restoresSnooze ? ["unpin", "pin", "snooze"] : ["unpin", "pin"],
+ );
+ expect(state.requests[1]).toMatchObject({
+ action: "pin",
+ input: { threadId: thread.id, orderKey: "m" },
+ });
+ if (restoresSnooze) {
+ expect(state.requests[2]).toMatchObject({
+ action: "snooze",
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id, snoozedUntil },
+ });
+ }
+ },
+ );
+
+ it("does not restore snooze if undoing an unpin fails", async () => {
+ const thread = makeThread({
+ pinnedAt: "2026-09-02T00:00:00.000Z",
+ snoozedUntil: "2099-01-01T09:00:00.000Z",
+ });
+ await useThreadListActions().unpinThread(thread);
+ state.failedAction = "pin";
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.map(({ action }) => action)).toEqual(["unpin", "pin"]);
+ });
+
+ it("invalidates a retained undo when another hook pins the thread", async () => {
+ const thread = makeThread();
+ await useThreadListActions().unpinThread(thread);
+ const undo = readThreadUndoNotice()!.undo;
+ await useThreadListActions().pinThread(thread);
+ await undo();
+ expect(state.requests.map(({ action }) => action)).toEqual(["unpin", "pin"]);
+ expect(readThreadUndoNotice()).toBeNull();
+ });
+
+ it("does not offer undo for a failed action", async () => {
+ state.failedAction = "settle";
+ expect(await useThreadListActions().settleThread(makeThread())).toBe(false);
+ expect(readThreadUndoNotice()).toBeNull();
+ });
+
+ it("stops restoring after a failed inverse command", async () => {
+ const thread = makeThread({
+ pinnedAt: "2026-09-02T00:00:00.000Z",
+ snoozedUntil: "2099-01-01T09:00:00.000Z",
+ });
+ await useThreadListActions().settleThread(thread);
+ state.failedAction = "unsettle";
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.map(({ action }) => action)).toEqual(["settle", "unsettle"]);
+ expect(state.alerts.at(-1)?.title).toBe("Could not un-settle thread");
+ });
+
+ it("rechecks the destination permission before undoing", async () => {
+ await useThreadListActions().unpinThread(makeThread());
+ state.scopes.get(primaryEnvironmentId)!.clear();
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]);
+ });
+
+ it("expires undo after five seconds", async () => {
+ vi.useFakeTimers();
+ await useThreadListActions().unpinThread(makeThread());
+ const undo = readThreadUndoNotice()!.undo;
+ vi.advanceTimersByTime(5_000);
+ expect(readThreadUndoNotice()).toBeNull();
+ await undo();
+ expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]);
+ });
+
+ it("refreshes the archive after archiving on a settlement-capable server", async () => {
+ await useThreadListActions().archiveThread(makeThread());
+ expect(state.requests.map(({ action }) => action)).toEqual(["archive"]);
+ expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]);
+ });
+});
+
+describe("thread archive guard", () => {
+ it("keeps active provider runs out of the archive", async () => {
+ const thread = makeThread({
+ runtime: {
+ status: "running",
+ activeRunId: RunId.make("active-run"),
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ providerName: "codex",
+ lastError: null,
+ updatedAt: "2026-09-02T00:00:00.000Z",
+ },
+ });
+ expect(await useThreadListActions().archiveThread(thread)).toBe(false);
+ expect(state.requests).toEqual([]);
+ expect(state.archivedRefreshes).toEqual([]);
+ expect(state.alerts.at(-1)?.title).toBe("Could not archive thread");
+ });
+});
diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts
index 4ca0fc56140..837887a73d6 100644
--- a/apps/mobile/src/features/home/useThreadListActions.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.ts
@@ -1,5 +1,7 @@
import type { ThreadMoveDestination } from "../threads/threadOrder";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
+import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
+import { showThreadUndoNotice } from "./thread-undo-notice";
import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -125,7 +127,11 @@ function useThreadActionExecutor(
const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
const inFlightThreadKeys = useRef(new Set<string>());
- const executeAction = async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
+ const executeAction = async (
+ action: ThreadListAction,
+ thread: EnvironmentThreadShell,
+ onStarted?: () => void,
+ ) => {
if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
if (inFlightThreadKeys.current.has(key)) {
@@ -152,6 +158,11 @@ function useThreadActionExecutor(
);
return false;
}
+ if (action === "unsettle") ThreadUndo.invalidate("settle", key);
+ if (action === "archive" || action === "delete") {
+ for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key);
+ }
+ onStarted?.();
const result = await withThreadDismissal(
key,
async () =>
@@ -214,7 +225,7 @@ function confirmThreadDeletion(
}
export function useThreadListActions(): {
- readonly archiveThread: (thread: EnvironmentThreadShell) => void;
+ readonly archiveThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
@@ -247,11 +258,73 @@ export function useThreadListActions(): {
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
- const archiveThread = (thread: EnvironmentThreadShell) => {
- void executeAction("archive", thread);
+ const archiveThread = (thread: EnvironmentThreadShell) => executeAction("archive", thread);
+ const offerUndo = (
+ thread: EnvironmentThreadShell,
+ action: "Settled" | "Snoozed" | "Unpinned",
+ claim: ReturnType<typeof ThreadUndo.begin>,
+ plan: ThreadUndo.ThreadUndoPlan,
+ ) =>
+ showThreadUndoNotice({
+ action,
+ claim,
+ undo: async () => {
+ try {
+ await ThreadUndo.executeThreadUndo(
+ plan,
+ async (step) => {
+ switch (step.action) {
+ case "unsettle":
+ return unsettleThread(thread);
+ case "unsnooze":
+ return unsnoozeThread(thread);
+ case "pin":
+ return pinThread(thread, step.orderKey);
+ case "snooze": {
+ const failureTitle =
+ action === "Unpinned" ? "Could not undo unpin" : "Could not undo settle";
+ if (!checkThreadOperationPermission(thread, failureTitle)) return false;
+ const result = await snoozeMutation({
+ environmentId: thread.environmentId,
+ input: { threadId: thread.id, snoozedUntil: step.snoozedUntil },
+ });
+ if (result._tag === "Failure") {
+ const error = Cause.squash(result.cause);
+ Dialog.alert(
+ "Could not restore snooze",
+ error instanceof Error ? error.message : "The thread could not be snoozed.",
+ );
+ return false;
+ }
+ return true;
+ }
+ }
+ },
+ (result) => result,
+ );
+ } catch (error) {
+ Dialog.alert(
+ "Could not undo thread action",
+ error instanceof Error ? error.message : "Try again.",
+ );
+ }
+ },
+ });
+ const settleThread = async (thread: EnvironmentThreadShell) => {
+ const key = scopedThreadKey(thread.environmentId, thread.id);
+ const plan = ThreadUndo.planThreadUndo("settle", thread);
+ let claim: ReturnType<typeof ThreadUndo.begin> | undefined;
+ const succeeded = await executeAction("settle", thread, () => {
+ ThreadUndo.invalidate("pin", key);
+ ThreadUndo.invalidate("snooze", key);
+ claim = ThreadUndo.begin("settle", key);
+ });
+ if (claim) {
+ if (succeeded) offerUndo(thread, "Settled", claim, plan);
+ else claim.finish();
+ }
+ return succeeded;
};
- const settleThread = async (thread: EnvironmentThreadShell) =>
- (await executeAction("settle", thread)) === true;
const snoozeThread = async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;
const key = scopedThreadKey(thread.environmentId, thread.id);
@@ -280,6 +353,7 @@ export function useThreadListActions(): {
}
selectionHaptic();
+ const claim = ThreadUndo.begin("snooze", key);
const result = await withThreadDismissal(
key,
() =>
@@ -293,6 +367,7 @@ export function useThreadListActions(): {
(result) => result._tag === "Success",
);
if (result._tag === "Failure") {
+ claim.finish();
const error = Cause.squash(result.cause);
Dialog.alert(
"Could not snooze thread",
@@ -302,6 +377,7 @@ export function useThreadListActions(): {
);
return false;
}
+ offerUndo(thread, "Snoozed", claim, ThreadUndo.planThreadUndo("snooze"));
return true;
})();
snoozeInFlightThreadKeys.current.delete(key);
@@ -324,6 +400,7 @@ export function useThreadListActions(): {
}
selectionHaptic();
+ ThreadUndo.invalidate("snooze", key);
const result = await withThreadDismissal(
key,
() =>
@@ -350,7 +427,7 @@ export function useThreadListActions(): {
};
const unsettleThread = async (thread: EnvironmentThreadShell) =>
(await executeAction("unsettle", thread)) === true;
- const pinThread = async (thread: EnvironmentThreadShell) => {
+ const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => {
if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
if (!environmentSupportsPinning(thread.environmentId)) {
Dialog.alert(
@@ -372,6 +449,13 @@ export function useThreadListActions(): {
}
orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
}
+ orderKey = environmentSupportsPinReorder(thread.environmentId)
+ ? (restoreOrderKey ?? orderKey)
+ : undefined;
+ ThreadUndo.invalidate("pin", scopedThreadKey(thread.environmentId, thread.id));
+ // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
+ ThreadUndo.invalidate("settle", scopedThreadKey(thread.environmentId, thread.id));
+ ThreadUndo.invalidate("snooze", scopedThreadKey(thread.environmentId, thread.id));
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
@@ -398,11 +482,14 @@ export function useThreadListActions(): {
return false;
}
selectionHaptic();
+ const plan = ThreadUndo.planThreadUndo("unpin", thread);
+ const claim = ThreadUndo.begin("pin", scopedThreadKey(thread.environmentId, thread.id));
const result = await unpinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
+ claim.finish();
const error = Cause.squash(result.cause);
Dialog.alert(
"Could not unpin thread",
@@ -412,6 +499,7 @@ export function useThreadListActions(): {
);
return false;
}
+ offerUndo(thread, "Unpinned", claim, plan);
return true;
};
const setThreadAutoSettle = async (thread: EnvironmentThreadShell, enabled: boolean) => {
@@ -614,6 +702,10 @@ export function useThreadListActions(): {
const orderKey = assignments.find(
({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),
)?.orderKey;
+ // Same as pinThread: older Unpinned, Settled, or Snoozed undos would fight this pin.
+ ThreadUndo.invalidate("pin", scopedThreadKey(thread.environmentId, thread.id));
+ ThreadUndo.invalidate("settle", scopedThreadKey(thread.environmentId, thread.id));
+ ThreadUndo.invalidate("snooze", scopedThreadKey(thread.environmentId, thread.id));
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },
@@ -640,6 +732,7 @@ export function useThreadListActions(): {
const target = shellByKey.get(assignment.id);
if (target === undefined) continue;
if (!checkThreadOperationPermission(target, "Could not move thread")) return false;
+ ThreadUndo.invalidate("pin", scopedThreadKey(target.environmentId, target.id));
const result = await reorder({
environmentId: target.environmentId,
input: { threadId: target.id, orderKey: assignment.orderKey },
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index e454e6ec91c..739efd50788 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -1,3 +1,4 @@
+import { ThreadUndoNotice } from "../home/ThreadUndoNotice";
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
@@ -797,6 +798,7 @@ function ThreadNavigationSidebarPane(
/>
</GestureDetector>
</SwipeableScrollGateProvider>
+ <ThreadUndoNotice visible={props.visible} />
</View>
</>
);
@@ -931,6 +933,7 @@ function ThreadNavigationSidebarPane(
</View>
</View>
)}
+ <ThreadUndoNotice visible={props.visible} />
</View>
);
}
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index f49e96381d7..c23d60a5dc9 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -748,6 +748,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
...arrangementMenuItems,
...titleMenuItems,
...autoSettleMenuItems,
+ LEGACY_MENU_ACTIONS[0]!,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[arrangementMenuItems, autoSettleMenuItems, snoozePresetActions, titleMenuItems],
@@ -758,6 +759,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
...arrangementMenuItems,
...titleMenuItems,
...autoSettleMenuItems,
+ LEGACY_MENU_ACTIONS[0]!,
...CARD_MENU_ACTIONS.slice(1),
],
[arrangementMenuItems, autoSettleMenuItems, titleMenuItems],
@@ -770,6 +772,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
),
...titleMenuItems,
...autoSettleMenuItems,
+ LEGACY_MENU_ACTIONS[0]!,
SLIM_MENU_ACTIONS[1]!,
],
[arrangementMenuItems, autoSettleMenuItems, titleMenuItems],
@@ -779,6 +782,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
SNOOZED_MENU_ACTIONS[0]!,
...titleMenuItems,
...autoSettleMenuItems,
+ LEGACY_MENU_ACTIONS[0]!,
SNOOZED_MENU_ACTIONS[1]!,
],
[autoSettleMenuItems, titleMenuItems],
diff --git a/apps/web/src/hooks/threadUndo.ts b/apps/web/src/hooks/threadUndo.ts
index 52c7390db70..975d7de5458 100644
--- a/apps/web/src/hooks/threadUndo.ts
+++ b/apps/web/src/hooks/threadUndo.ts
@@ -1,36 +1 @@
-// Shared across hook instances so sidebar, header and menu actions invalidate each other.
-const currentActions = new Map<string, symbol>();
-const listeners = new Set<() => void>();
-
-export function subscribe(listener: () => void) {
- listeners.add(listener);
- return () => {
- listeners.delete(listener);
- };
-}
-
-function notify() {
- for (const listener of listeners) listener();
-}
-
-export function begin(kind: string, threadKey: string) {
- const key = JSON.stringify([kind, threadKey]);
- const token = Symbol();
- currentActions.set(key, token);
- notify();
- const isCurrent = () => currentActions.get(key) === token;
- return {
- isCurrent,
- finish: () => {
- if (isCurrent()) {
- currentActions.delete(key);
- notify();
- }
- },
- };
-}
-
-export function invalidate(kind: string, threadKey: string) {
- currentActions.delete(JSON.stringify([kind, threadKey]));
- notify();
-}
+export * from "@t3tools/client-runtime/state/thread-undo";
diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts
index 1c2f1f0f0a3..08d1a80ca0c 100644
--- a/apps/web/src/hooks/useThreadActions.ts
+++ b/apps/web/src/hooks/useThreadActions.ts
@@ -650,6 +650,9 @@ export function useThreadActions() {
? (opts.orderKey ?? topOfPinnedRunOrderKey())
: undefined;
ThreadUndo.invalidate("pin", scopedThreadKey(target));
+ // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
+ ThreadUndo.invalidate("settle", scopedThreadKey(target));
+ ThreadUndo.invalidate("snooze", scopedThreadKey(target));
return pinThreadMutation({
environmentId: target.environmentId,
input: {
@@ -671,7 +674,7 @@ export function useThreadActions() {
);
}
const thread = readThreadShell(target);
- const orderKey = thread?.pinOrderKey ?? undefined;
+ const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
const action = ThreadUndo.begin("pin", scopedThreadKey(target));
const result = await unpinThreadMutation({
environmentId: target.environmentId,
@@ -681,7 +684,7 @@ export function useThreadActions() {
showThreadUndoNotice({
action: "Unpinned",
claim: action,
- undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }),
+ undo: () => runUndoPlan(target, undoPlan),
failureTitle: "Failed to undo unpin",
});
} else {
@@ -705,11 +708,7 @@ export function useThreadActions() {
const wokeAt = resolved
? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
: null;
- // Settling also drops the pin and the snooze server-side, so Undo
- // has to put those back as well.
- const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null;
- const wasPinned = resolved?.thread.pinnedAt != null;
- const snoozedUntil = resolved?.thread.snoozedUntil ?? null;
+ const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
// An older unpin/snooze Undo would re-pin or re-snooze, and the server
// treats either as a promotion that un-settles; settling supersedes them.
ThreadUndo.invalidate("pin", scopedThreadKey(target));
@@ -729,24 +728,7 @@ export function useThreadActions() {
showThreadUndoNotice({
action: "Settled",
claim: action,
- undo: async () => {
- const unsettled = await unsettleThread(target);
- if (unsettled._tag !== "Success") return unsettled;
- if (wasPinned) {
- const pinned = await pinThread(
- target,
- pinOrderKey == null ? {} : { orderKey: pinOrderKey },
- );
- if (pinned._tag !== "Success") return pinned;
- }
- if (snoozedUntil !== null) {
- return snoozeThreadMutation({
- environmentId: target.environmentId,
- input: { threadId: target.threadId, snoozedUntil },
- });
- }
- return unsettled;
- },
+ undo: () => runUndoPlan(target, undoPlan),
failureTitle: "Failed to undo settle",
});
return result;
@@ -858,12 +840,36 @@ export function useThreadActions() {
showThreadUndoNotice({
action: "Snoozed",
claim: action,
- undo: () => unsnoozeThread(target),
+ undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
failureTitle: "Failed to wake thread",
});
return result;
};
+ const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) =>
+ ThreadUndo.executeThreadUndo(
+ plan,
+ async (step) => {
+ switch (step.action) {
+ case "unsettle":
+ return unsettleThread(target);
+ case "unsnooze":
+ return unsnoozeThread(target);
+ case "pin":
+ return pinThread(
+ target,
+ step.orderKey === undefined ? {} : { orderKey: step.orderKey },
+ );
+ case "snooze":
+ return snoozeThreadMutation({
+ environmentId: target.environmentId,
+ input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
+ });
+ }
+ },
+ (result) => result._tag === "Success",
+ );
+
const confirmAndDeleteThread = async (target: ScopedThreadRef) => {
const permissionFailure = threadOperationFailure(target);
if (permissionFailure) return permissionFailure;
diff --git a/apps/web/src/hooks/useThreadActions.undo.test.ts b/apps/web/src/hooks/useThreadActions.undo.test.ts
index 9950911bee3..1133b4eb83b 100644
--- a/apps/web/src/hooks/useThreadActions.undo.test.ts
+++ b/apps/web/src/hooks/useThreadActions.undo.test.ts
@@ -1,4 +1,5 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { useThreadActions } from "./useThreadActions";
@@ -106,7 +107,57 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe("concurrent thread action Undo", () => {
+ it.each([
+ ["settleThread", "settle", "unsettle", "Settled"],
+ ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
+ ["unpinThread", "unpin", "pin", "Unpinned"],
+ ["archiveThread", "archive", "unarchive", "Archived"],
+ ] as const)(
+ "%s retains one undo for concurrent successful requests",
+ async (handler, action, inverse, notice) => {
+ const actions = useThreadActions();
+ const run = () =>
+ handler === "snoozeThread"
+ ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
+ : actions[handler](target);
+ await Promise.all([run(), run()]);
+ expect(commands[action]).toHaveBeenCalledTimes(2);
+ expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
+ await currentUndo()();
+ expect(commands[inverse]).toHaveBeenCalledOnce();
+ },
+ );
+});
+
describe("unpin Undo", () => {
+ it("restores the original snooze after restoring the pin", async () => {
+ threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
+ threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
+ await useThreadActions().unpinThread(target);
+ await currentUndo()();
+ expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
+ environmentId: target.environmentId,
+ input: { threadId: target.threadId, orderKey: "a0" },
+ });
+ expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
+ environmentId: target.environmentId,
+ input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
+ });
+ expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
+ commands.snooze.mock.invocationCallOrder[0]!,
+ );
+ });
+
+ it("restores the pin without an already expired snooze", async () => {
+ threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
+ threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
+ await useThreadActions().unpinThread(target);
+ await currentUndo()();
+ expect(commands.pin).toHaveBeenCalledOnce();
+ expect(commands.snooze).not.toHaveBeenCalled();
+ });
+
it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
const sidebar = useThreadActions();
const header = useThreadActions();
@@ -198,6 +249,18 @@ describe("settle and snooze Undo", () => {
});
});
+ it("stops settle restoration if restoring the pin fails", async () => {
+ threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
+ threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
+ commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
+ vi.spyOn(toastManager, "add").mockReturnValue("toast");
+ await useThreadActions().settleThread(target);
+ await currentUndo()();
+ expect(commands.unsettle).toHaveBeenCalledOnce();
+ expect(commands.pin).toHaveBeenCalledOnce();
+ expect(commands.snooze).not.toHaveBeenCalled();
+ });
+
it("expires an older unpin Undo when the thread is settled", async () => {
const actions = useThreadActions();
await actions.unpinThread(target);
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 728dd45816a..cb03114c8f4 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -319,6 +319,10 @@
"types": "./src/state/threadSubagents.ts",
"default": "./src/state/threadSubagents.ts"
},
+ "./state/thread-undo": {
+ "types": "./src/state/threadUndo.ts",
+ "default": "./src/state/threadUndo.ts"
+ },
"./state/thread-settled": {
"types": "./src/state/threadSettled.ts",
"default": "./src/state/threadSettled.ts"
diff --git a/packages/client-runtime/src/state/threadUndo.ts b/packages/client-runtime/src/state/threadUndo.ts
new file mode 100644
index 00000000000..c9a8ac402be
--- /dev/null
+++ b/packages/client-runtime/src/state/threadUndo.ts
@@ -0,0 +1,82 @@
+// Shared across hook instances so sidebar, header and menu actions invalidate each other.
+const currentActions = new Map<string, symbol>();
+const listeners = new Set<() => void>();
+
+export function subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+function notify() {
+ for (const listener of listeners) listener();
+}
+
+export function begin(kind: string, threadKey: string) {
+ const key = JSON.stringify([kind, threadKey]);
+ const token = Symbol();
+ currentActions.set(key, token);
+ notify();
+ const isCurrent = () => currentActions.get(key) === token;
+ return {
+ isCurrent,
+ finish: () => {
+ if (isCurrent()) {
+ currentActions.delete(key);
+ notify();
+ }
+ },
+ };
+}
+
+export function invalidate(kind: string, threadKey: string) {
+ currentActions.delete(JSON.stringify([kind, threadKey]));
+ notify();
+}
+
+export type ThreadUndoStep =
+ | { readonly action: "unsettle" }
+ | { readonly action: "unsnooze" }
+ | { readonly action: "pin"; readonly orderKey?: string }
+ | { readonly action: "snooze"; readonly snoozedUntil: string };
+
+export type ThreadUndoPlan = readonly [ThreadUndoStep, ...ThreadUndoStep[]];
+
+export function planThreadUndo(
+ action: "settle" | "snooze" | "unpin",
+ thread?: {
+ readonly pinnedAt?: string | null;
+ readonly pinOrderKey?: string | null;
+ readonly snoozedUntil?: string | null;
+ } | null,
+): ThreadUndoPlan {
+ if (action === "snooze") return [{ action: "unsnooze" }];
+ const pin: ThreadUndoStep = {
+ action: "pin",
+ ...(thread?.pinOrderKey != null ? { orderKey: thread.pinOrderKey } : {}),
+ };
+ // Pinning clears snooze on the server; restore it after restoring pin placement.
+ const snooze =
+ thread?.snoozedUntil != null
+ ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil }]
+ : [];
+ if (action === "unpin") return [pin, ...snooze];
+ return [{ action: "unsettle" }, ...(thread?.pinnedAt != null ? [pin] : []), ...snooze];
+}
+
+export async function executeThreadUndo<Result>(
+ plan: ThreadUndoPlan,
+ execute: (step: ThreadUndoStep) => Promise<Result>,
+ succeeded: (result: Result) => boolean,
+): Promise<Result> {
+ let result = await execute(plan[0]);
+ for (const step of plan.slice(1)) {
+ if (!succeeded(result)) return result;
+ // A snooze can expire before Undo runs, and the server rejects an expired restore.
+ // @effect-diagnostics-next-line globalDate:off
+ if (step.action === "snooze" && Date.parse(step.snoozedUntil) <= Date.now()) continue;
+ result = await execute(step);
+ }
+ return result;
+}