@devries-cameron20 / t3code-1 / commits / 6efe9a088e
Fork 0

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

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

maria committed Oct 21, 2026 at 00:05 UTC 6efe9a088eb37e06df24af2012b11d6463e8864f
12 files changed +583 -72
apps/mobile/src/features/home/HomeRouteScreen.tsx
+2
@@ -1,3 +1,4 @@
1 +import { ThreadUndoNotice } from "./ThreadUndoNotice";
2 import { Toolbar } from "../../components/ui/Toolbar";
3 import { use } from "react";
4 import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
@@ -306,6 +307,7 @@ export function HomeRouteScreen() {
307 selectedProjectKey={selectedProjectKey}
308 threads={threads}
309 />
310 + <ThreadUndoNotice visible={visible} />
311 </>
312 </AndroidHomeFabLayout>
313 );
apps/mobile/src/features/home/ThreadUndoNotice.tsx new
+29
@@ -0,0 +1,29 @@
1 +import { View } from "react-native";
2 +import { useSafeAreaInsets } from "react-native-safe-area-context";
3 +import { Toast } from "../../components/ui/Toast";
4 +import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";
5 +import { dismissThreadUndoNotice, useThreadUndoNotice } from "./thread-undo-notice";
6 +
7 +export function ThreadUndoNotice(props: { readonly visible: boolean }) {
8 + const notice = useThreadUndoNotice();
9 + const insets = useSafeAreaInsets();
10 + if (!props.visible || notice === null) return null;
11 + return (
12 + <View
13 + className="absolute inset-x-3 z-[100]"
14 + style={{ top: insets.top + APP_BAR_HEIGHT + 8 }}
15 + pointerEvents="box-none"
16 + >
17 + <Toast
18 + message={`${notice.action} thread`}
19 + action={{
20 + label: "Undo",
21 + onPress: () => {
22 + void notice.undo();
23 + },
24 + }}
25 + onDismiss={dismissThreadUndoNotice}
26 + />
27 + </View>
28 + );
29 +}
apps/mobile/src/features/home/thread-undo-notice.ts new
+56
@@ -0,0 +1,56 @@
1 +import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
2 +import { useSyncExternalStore } from "react";
3 +
4 +type UndoNotice = {
5 + readonly action: "Settled" | "Snoozed" | "Unpinned";
6 + readonly claim: ReturnType<typeof ThreadUndo.begin>;
7 + readonly undo: () => Promise<void>;
8 +};
9 +
10 +let notice: UndoNotice | null = null;
11 +let expiry: ReturnType<typeof setTimeout> | undefined;
12 +const listeners = new Set<() => void>();
13 +
14 +function notify() {
15 + for (const listener of listeners) listener();
16 +}
17 +
18 +export function readThreadUndoNotice() {
19 + return notice;
20 +}
21 +
22 +export function dismissThreadUndoNotice() {
23 + const previous = notice;
24 + notice = null;
25 + clearTimeout(expiry);
26 + previous?.claim.finish();
27 + notify();
28 +}
29 +
30 +ThreadUndo.subscribe(() => {
31 + if (notice !== null && !notice.claim.isCurrent()) dismissThreadUndoNotice();
32 +});
33 +
34 +export function showThreadUndoNotice(options: UndoNotice) {
35 + if (!options.claim.isCurrent()) return;
36 + dismissThreadUndoNotice();
37 + notice = {
38 + ...options,
39 + undo: async () => {
40 + if (notice?.claim !== options.claim || !options.claim.isCurrent()) return;
41 + dismissThreadUndoNotice();
42 + await options.undo();
43 + },
44 + };
45 + notify();
46 + expiry = setTimeout(dismissThreadUndoNotice, 5_000);
47 +}
48 +
49 +export function useThreadUndoNotice() {
50 + return useSyncExternalStore((listener) => {
51 + listeners.add(listener);
52 + return () => {
53 + listeners.delete(listener);
54 + };
55 + }, readThreadUndoNotice);
56 +}
apps/mobile/src/features/home/useThreadListActions.test.ts
+207 -3
@@ -5,6 +5,7 @@ import {
5 EnvironmentId,
6 ProjectId,
7 ProviderInstanceId,
8 + RunId,
9 ThreadId,
10 } from "@t3tools/contracts";
11 import * as Cause from "effect/Cause";
@@ -14,12 +15,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
15 const state = vi.hoisted(() => ({
16 pendingOrder: null as object | null,
17 dropBusy: false,
18 + failedAction: null as string | null,
19 + archivedRefreshes: [] as string[],
20 scopes: new Map<string, Set<string>>(),
21 shells: [] as EnvironmentThreadShell[],
22 requests: [] as {
23 action: string;
24 environmentId: string;
22 - input: { threadId: string; orderKey?: string };
25 + input: { threadId: string; orderKey?: string; snoozedUntil?: string; reason?: string };
26 }[],
27 dialogs: [] as { onConfirm: () => void }[],
28 alerts: [] as {
@@ -49,7 +52,9 @@ vi.mock("../../components/ui/Dialog", () => ({
52 confirm: (dialog: { onConfirm: () => void }) => state.dialogs.push(dialog),
53 }));
54 vi.mock("../archive/useArchivedThreadSnapshots", () => ({
52 - refreshArchivedThreadsForEnvironment: () => {},
55 + refreshArchivedThreadsForEnvironment: (environmentId: string) => {
56 + state.archivedRefreshes.push(environmentId);
57 + },
58 }));
59 vi.mock("../../state/session", () => ({
60 readEnvironmentScope: (environmentId: string, scope: string) =>
@@ -133,6 +138,8 @@ vi.mock("../../state/threads", () => ({
138 if (!state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope)) {
139 return AsyncResult.failure(Cause.fail(new Error("Thread operation denied")));
140 }
141 + if (action === state.failedAction)
142 + return AsyncResult.failure(Cause.fail(new Error("Server rejected action")));
143 state.afterRequest?.();
144 return AsyncResult.success(undefined);
145 },
@@ -140,6 +147,7 @@ vi.mock("../../state/threads", () => ({
147 ),
148 }));
149
150 +import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice";
151 import { useArchivedThreadListActions, useThreadListActions } from "./useThreadListActions";
152
153 const primaryEnvironmentId = EnvironmentId.make("primary");
@@ -168,6 +176,8 @@ const mutationCases = [
176 ] as const;
177
178 beforeEach(() => {
179 + state.failedAction = null;
180 + state.archivedRefreshes = [];
181 state.pendingOrder = null;
182 state.dropBusy = false;
183 state.scopes = new Map([
@@ -181,7 +191,11 @@ beforeEach(() => {
191 state.afterRequest = undefined;
192 });
193
184 -afterEach(() => vi.unstubAllEnvs());
194 +afterEach(() => {
195 + dismissThreadUndoNotice();
196 + vi.useRealTimers();
197 + vi.unstubAllEnvs();
198 +});
199
200 describe("thread list operation permissions", () => {
201 it.each(mutationCases)(
@@ -315,3 +329,193 @@ describe("pinned thread operation permissions", () => {
329 expect(state.requests).toHaveLength(1);
330 });
331 });
332 +
333 +describe("thread action undo", () => {
334 + it.each([
335 + ["settleThread", "settle", "Settled", "unsettle"],
336 + ["snoozeThread", "snooze", "Snoozed", "unsnooze"],
337 + ] as const)(
338 + "%s keeps the successful request's undo when a duplicate is rejected",
339 + async (handler, action, notice, inverse) => {
340 + const actions = useThreadListActions();
341 + const thread = makeThread();
342 + const first = actions[handler](thread, "2099-01-01T09:00:00.000Z");
343 +
344 + expect(await actions[handler](thread, "2099-01-01T09:00:00.000Z")).toBe(false);
345 + expect(await first).toBe(true);
346 + expect(state.requests.map(({ action }) => action)).toEqual([action]);
347 + expect(readThreadUndoNotice()?.action).toBe(notice);
348 + await readThreadUndoNotice()!.undo();
349 + expect(state.requests.map(({ action }) => action)).toEqual([action, inverse]);
350 + },
351 + );
352 +
353 + it("keeps the latest unpin undo after concurrent unpin requests", async () => {
354 + const actions = useThreadListActions();
355 + const thread = makeThread();
356 + expect(await Promise.all([actions.unpinThread(thread), actions.unpinThread(thread)])).toEqual([
357 + true,
358 + true,
359 + ]);
360 + expect(readThreadUndoNotice()?.action).toBe("Unpinned");
361 + await readThreadUndoNotice()!.undo();
362 + expect(state.requests.map(({ action }) => action)).toEqual(["unpin", "unpin", "pin"]);
363 + });
364 +
365 + it("rejects a concurrent archive request without sending another mutation", async () => {
366 + const actions = useThreadListActions();
367 + const thread = makeThread();
368 + const first = actions.archiveThread(thread);
369 + expect(await actions.archiveThread(thread)).toBe(false);
370 + expect(await first).toBe(true);
371 + expect(state.requests.map(({ action }) => action)).toEqual(["archive"]);
372 + expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]);
373 + });
374 +
375 + it("restores pin placement and snooze after settling, only once", async () => {
376 + const thread = makeThread({
377 + pinnedAt: "2026-09-02T00:00:00.000Z",
378 + pinOrderKey: "m",
379 + snoozedUntil: "2099-01-01T09:00:00.000Z",
380 + });
381 + expect(await useThreadListActions().settleThread(thread)).toBe(true);
382 + const undo = readThreadUndoNotice()!.undo;
383 + expect(readThreadUndoNotice()?.action).toBe("Settled");
384 + await undo();
385 + await undo();
386 + expect(state.requests.map(({ action }) => action)).toEqual([
387 + "settle",
388 + "unsettle",
389 + "pin",
390 + "snooze",
391 + ]);
392 + expect(state.requests[2]?.input).toEqual({ threadId: thread.id, orderKey: "m" });
393 + expect(state.requests[3]?.input).toEqual({
394 + threadId: thread.id,
395 + snoozedUntil: thread.snoozedUntil,
396 + });
397 + expect(readThreadUndoNotice()).toBeNull();
398 + });
399 +
400 + it("wakes a snoozed thread through the undo action", async () => {
401 + const thread = makeThread();
402 + await useThreadListActions().snoozeThread(thread, "2099-01-01T09:00:00.000Z");
403 + expect(readThreadUndoNotice()?.action).toBe("Snoozed");
404 + await readThreadUndoNotice()!.undo();
405 + expect(state.requests.at(-1)).toMatchObject({
406 + action: "unsnooze",
407 + environmentId: thread.environmentId,
408 + input: { threadId: thread.id, reason: "user" },
409 + });
410 + });
411 +
412 + it.each([null, "2099-01-01T09:00:00.000Z", "2000-01-01T09:00:00.000Z"])(
413 + "restores an unpinned thread's previous position and unexpired snooze (%s)",
414 + async (snoozedUntil) => {
415 + const thread = makeThread({
416 + pinnedAt: "2026-09-02T00:00:00.000Z",
417 + pinOrderKey: "m",
418 + snoozedUntil,
419 + });
420 + await useThreadListActions().unpinThread(thread);
421 + expect(readThreadUndoNotice()?.action).toBe("Unpinned");
422 + await readThreadUndoNotice()!.undo();
423 + const restoresSnooze = snoozedUntil != null && Date.parse(snoozedUntil) > Date.now();
424 + expect(state.requests.map(({ action }) => action)).toEqual(
425 + restoresSnooze ? ["unpin", "pin", "snooze"] : ["unpin", "pin"],
426 + );
427 + expect(state.requests[1]).toMatchObject({
428 + action: "pin",
429 + input: { threadId: thread.id, orderKey: "m" },
430 + });
431 + if (restoresSnooze) {
432 + expect(state.requests[2]).toMatchObject({
433 + action: "snooze",
434 + environmentId: thread.environmentId,
435 + input: { threadId: thread.id, snoozedUntil },
436 + });
437 + }
438 + },
439 + );
440 +
441 + it("does not restore snooze if undoing an unpin fails", async () => {
442 + const thread = makeThread({
443 + pinnedAt: "2026-09-02T00:00:00.000Z",
444 + snoozedUntil: "2099-01-01T09:00:00.000Z",
445 + });
446 + await useThreadListActions().unpinThread(thread);
447 + state.failedAction = "pin";
448 + await readThreadUndoNotice()!.undo();
449 + expect(state.requests.map(({ action }) => action)).toEqual(["unpin", "pin"]);
450 + });
451 +
452 + it("invalidates a retained undo when another hook pins the thread", async () => {
453 + const thread = makeThread();
454 + await useThreadListActions().unpinThread(thread);
455 + const undo = readThreadUndoNotice()!.undo;
456 + await useThreadListActions().pinThread(thread);
457 + await undo();
458 + expect(state.requests.map(({ action }) => action)).toEqual(["unpin", "pin"]);
459 + expect(readThreadUndoNotice()).toBeNull();
460 + });
461 +
462 + it("does not offer undo for a failed action", async () => {
463 + state.failedAction = "settle";
464 + expect(await useThreadListActions().settleThread(makeThread())).toBe(false);
465 + expect(readThreadUndoNotice()).toBeNull();
466 + });
467 +
468 + it("stops restoring after a failed inverse command", async () => {
469 + const thread = makeThread({
470 + pinnedAt: "2026-09-02T00:00:00.000Z",
471 + snoozedUntil: "2099-01-01T09:00:00.000Z",
472 + });
473 + await useThreadListActions().settleThread(thread);
474 + state.failedAction = "unsettle";
475 + await readThreadUndoNotice()!.undo();
476 + expect(state.requests.map(({ action }) => action)).toEqual(["settle", "unsettle"]);
477 + expect(state.alerts.at(-1)?.title).toBe("Could not un-settle thread");
478 + });
479 +
480 + it("rechecks the destination permission before undoing", async () => {
481 + await useThreadListActions().unpinThread(makeThread());
482 + state.scopes.get(primaryEnvironmentId)!.clear();
483 + await readThreadUndoNotice()!.undo();
484 + expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]);
485 + });
486 +
487 + it("expires undo after five seconds", async () => {
488 + vi.useFakeTimers();
489 + await useThreadListActions().unpinThread(makeThread());
490 + const undo = readThreadUndoNotice()!.undo;
491 + vi.advanceTimersByTime(5_000);
492 + expect(readThreadUndoNotice()).toBeNull();
493 + await undo();
494 + expect(state.requests.map(({ action }) => action)).toEqual(["unpin"]);
495 + });
496 +
497 + it("refreshes the archive after archiving on a settlement-capable server", async () => {
498 + await useThreadListActions().archiveThread(makeThread());
499 + expect(state.requests.map(({ action }) => action)).toEqual(["archive"]);
500 + expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]);
501 + });
502 +});
503 +
504 +describe("thread archive guard", () => {
505 + it("keeps active provider runs out of the archive", async () => {
506 + const thread = makeThread({
507 + runtime: {
508 + status: "running",
509 + activeRunId: RunId.make("active-run"),
510 + providerInstanceId: ProviderInstanceId.make("codex"),
511 + providerName: "codex",
512 + lastError: null,
513 + updatedAt: "2026-09-02T00:00:00.000Z",
514 + },
515 + });
516 + expect(await useThreadListActions().archiveThread(thread)).toBe(false);
517 + expect(state.requests).toEqual([]);
518 + expect(state.archivedRefreshes).toEqual([]);
519 + expect(state.alerts.at(-1)?.title).toBe("Could not archive thread");
520 + });
521 +});
apps/mobile/src/features/home/useThreadListActions.ts
+100 -7
@@ -1,5 +1,7 @@
1 import type { ThreadMoveDestination } from "../threads/threadOrder";
2 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3 +import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
4 +import { showThreadUndoNotice } from "./thread-undo-notice";
5 import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
6 import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
@@ -125,7 +127,11 @@ function useThreadActionExecutor(
127 const unsettleMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false });
128 const inFlightThreadKeys = useRef(new Set<string>());
129
128 - const executeAction = async (action: ThreadListAction, thread: EnvironmentThreadShell) => {
130 + const executeAction = async (
131 + action: ThreadListAction,
132 + thread: EnvironmentThreadShell,
133 + onStarted?: () => void,
134 + ) => {
135 if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false;
136 const key = scopedThreadKey(thread.environmentId, thread.id);
137 if (inFlightThreadKeys.current.has(key)) {
@@ -152,6 +158,11 @@ function useThreadActionExecutor(
158 );
159 return false;
160 }
161 + if (action === "unsettle") ThreadUndo.invalidate("settle", key);
162 + if (action === "archive" || action === "delete") {
163 + for (const kind of ["settle", "snooze", "pin"]) ThreadUndo.invalidate(kind, key);
164 + }
165 + onStarted?.();
166 const result = await withThreadDismissal(
167 key,
168 async () =>
@@ -214,7 +225,7 @@ function confirmThreadDeletion(
225 }
226
227 export function useThreadListActions(): {
217 - readonly archiveThread: (thread: EnvironmentThreadShell) => void;
228 + readonly archiveThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
229 readonly confirmDeleteThread: (thread: EnvironmentThreadShell) => void;
230 readonly settleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
231 readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
@@ -247,11 +258,73 @@ export function useThreadListActions(): {
258 const snoozeInFlightThreadKeys = useRef(new Set<string>());
259 const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
260
250 - const archiveThread = (thread: EnvironmentThreadShell) => {
251 - void executeAction("archive", thread);
261 + const archiveThread = (thread: EnvironmentThreadShell) => executeAction("archive", thread);
262 + const offerUndo = (
263 + thread: EnvironmentThreadShell,
264 + action: "Settled" | "Snoozed" | "Unpinned",
265 + claim: ReturnType<typeof ThreadUndo.begin>,
266 + plan: ThreadUndo.ThreadUndoPlan,
267 + ) =>
268 + showThreadUndoNotice({
269 + action,
270 + claim,
271 + undo: async () => {
272 + try {
273 + await ThreadUndo.executeThreadUndo(
274 + plan,
275 + async (step) => {
276 + switch (step.action) {
277 + case "unsettle":
278 + return unsettleThread(thread);
279 + case "unsnooze":
280 + return unsnoozeThread(thread);
281 + case "pin":
282 + return pinThread(thread, step.orderKey);
283 + case "snooze": {
284 + const failureTitle =
285 + action === "Unpinned" ? "Could not undo unpin" : "Could not undo settle";
286 + if (!checkThreadOperationPermission(thread, failureTitle)) return false;
287 + const result = await snoozeMutation({
288 + environmentId: thread.environmentId,
289 + input: { threadId: thread.id, snoozedUntil: step.snoozedUntil },
290 + });
291 + if (result._tag === "Failure") {
292 + const error = Cause.squash(result.cause);
293 + Dialog.alert(
294 + "Could not restore snooze",
295 + error instanceof Error ? error.message : "The thread could not be snoozed.",
296 + );
297 + return false;
298 + }
299 + return true;
300 + }
301 + }
302 + },
303 + (result) => result,
304 + );
305 + } catch (error) {
306 + Dialog.alert(
307 + "Could not undo thread action",
308 + error instanceof Error ? error.message : "Try again.",
309 + );
310 + }
311 + },
312 + });
313 + const settleThread = async (thread: EnvironmentThreadShell) => {
314 + const key = scopedThreadKey(thread.environmentId, thread.id);
315 + const plan = ThreadUndo.planThreadUndo("settle", thread);
316 + let claim: ReturnType<typeof ThreadUndo.begin> | undefined;
317 + const succeeded = await executeAction("settle", thread, () => {
318 + ThreadUndo.invalidate("pin", key);
319 + ThreadUndo.invalidate("snooze", key);
320 + claim = ThreadUndo.begin("settle", key);
321 + });
322 + if (claim) {
323 + if (succeeded) offerUndo(thread, "Settled", claim, plan);
324 + else claim.finish();
325 + }
326 + return succeeded;
327 };
253 - const settleThread = async (thread: EnvironmentThreadShell) =>
254 - (await executeAction("settle", thread)) === true;
328 const snoozeThread = async (thread: EnvironmentThreadShell, snoozedUntil: string) => {
329 if (!checkThreadOperationPermission(thread, "Could not snooze thread")) return false;
330 const key = scopedThreadKey(thread.environmentId, thread.id);
@@ -280,6 +353,7 @@ export function useThreadListActions(): {
353 }
354
355 selectionHaptic();
356 + const claim = ThreadUndo.begin("snooze", key);
357 const result = await withThreadDismissal(
358 key,
359 () =>
@@ -293,6 +367,7 @@ export function useThreadListActions(): {
367 (result) => result._tag === "Success",
368 );
369 if (result._tag === "Failure") {
370 + claim.finish();
371 const error = Cause.squash(result.cause);
372 Dialog.alert(
373 "Could not snooze thread",
@@ -302,6 +377,7 @@ export function useThreadListActions(): {
377 );
378 return false;
379 }
380 + offerUndo(thread, "Snoozed", claim, ThreadUndo.planThreadUndo("snooze"));
381 return true;
382 })();
383 snoozeInFlightThreadKeys.current.delete(key);
@@ -324,6 +400,7 @@ export function useThreadListActions(): {
400 }
401
402 selectionHaptic();
403 + ThreadUndo.invalidate("snooze", key);
404 const result = await withThreadDismissal(
405 key,
406 () =>
@@ -350,7 +427,7 @@ export function useThreadListActions(): {
427 };
428 const unsettleThread = async (thread: EnvironmentThreadShell) =>
429 (await executeAction("unsettle", thread)) === true;
353 - const pinThread = async (thread: EnvironmentThreadShell) => {
430 + const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => {
431 if (!checkThreadOperationPermission(thread, "Could not pin thread")) return false;
432 if (!environmentSupportsPinning(thread.environmentId)) {
433 Dialog.alert(
@@ -372,6 +449,13 @@ export function useThreadListActions(): {
449 }
450 orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
451 }
452 + orderKey = environmentSupportsPinReorder(thread.environmentId)
453 + ? (restoreOrderKey ?? orderKey)
454 + : undefined;
455 + ThreadUndo.invalidate("pin", scopedThreadKey(thread.environmentId, thread.id));
456 + // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
457 + ThreadUndo.invalidate("settle", scopedThreadKey(thread.environmentId, thread.id));
458 + ThreadUndo.invalidate("snooze", scopedThreadKey(thread.environmentId, thread.id));
459 const result = await pinMutation({
460 environmentId: thread.environmentId,
461 input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
@@ -398,11 +482,14 @@ export function useThreadListActions(): {
482 return false;
483 }
484 selectionHaptic();
485 + const plan = ThreadUndo.planThreadUndo("unpin", thread);
486 + const claim = ThreadUndo.begin("pin", scopedThreadKey(thread.environmentId, thread.id));
487 const result = await unpinMutation({
488 environmentId: thread.environmentId,
489 input: { threadId: thread.id },
490 });
491 if (result._tag === "Failure") {
492 + claim.finish();
493 const error = Cause.squash(result.cause);
494 Dialog.alert(
495 "Could not unpin thread",
@@ -412,6 +499,7 @@ export function useThreadListActions(): {
499 );
500 return false;
501 }
502 + offerUndo(thread, "Unpinned", claim, plan);
503 return true;
504 };
505 const setThreadAutoSettle = async (thread: EnvironmentThreadShell, enabled: boolean) => {
@@ -614,6 +702,10 @@ export function useThreadListActions(): {
702 const orderKey = assignments.find(
703 ({ id }) => id === scopedThreadKey(thread.environmentId, thread.id),
704 )?.orderKey;
705 + // Same as pinThread: older Unpinned, Settled, or Snoozed undos would fight this pin.
706 + ThreadUndo.invalidate("pin", scopedThreadKey(thread.environmentId, thread.id));
707 + ThreadUndo.invalidate("settle", scopedThreadKey(thread.environmentId, thread.id));
708 + ThreadUndo.invalidate("snooze", scopedThreadKey(thread.environmentId, thread.id));
709 const result = await pinMutation({
710 environmentId: thread.environmentId,
711 input: { threadId: thread.id, ...(orderKey === undefined ? {} : { orderKey }) },
@@ -640,6 +732,7 @@ export function useThreadListActions(): {
732 const target = shellByKey.get(assignment.id);
733 if (target === undefined) continue;
734 if (!checkThreadOperationPermission(target, "Could not move thread")) return false;
735 + ThreadUndo.invalidate("pin", scopedThreadKey(target.environmentId, target.id));
736 const result = await reorder({
737 environmentId: target.environmentId,
738 input: { threadId: target.id, orderKey: assignment.orderKey },
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+3
@@ -1,3 +1,4 @@
1 +import { ThreadUndoNotice } from "../home/ThreadUndoNotice";
2 import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
3 import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping";
4 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
@@ -797,6 +798,7 @@ function ThreadNavigationSidebarPane(
798 />
799 </GestureDetector>
800 </SwipeableScrollGateProvider>
801 + <ThreadUndoNotice visible={props.visible} />
802 </View>
803 </>
804 );
@@ -931,6 +933,7 @@ function ThreadNavigationSidebarPane(
933 </View>
934 </View>
935 )}
936 + <ThreadUndoNotice visible={props.visible} />
937 </View>
938 );
939 }
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+4
@@ -748,6 +748,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
748 ...arrangementMenuItems,
749 ...titleMenuItems,
750 ...autoSettleMenuItems,
751 + LEGACY_MENU_ACTIONS[0]!,
752 { id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
753 ],
754 [arrangementMenuItems, autoSettleMenuItems, snoozePresetActions, titleMenuItems],
@@ -758,6 +759,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
759 ...arrangementMenuItems,
760 ...titleMenuItems,
761 ...autoSettleMenuItems,
762 + LEGACY_MENU_ACTIONS[0]!,
763 ...CARD_MENU_ACTIONS.slice(1),
764 ],
765 [arrangementMenuItems, autoSettleMenuItems, titleMenuItems],
@@ -770,6 +772,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
772 ),
773 ...titleMenuItems,
774 ...autoSettleMenuItems,
775 + LEGACY_MENU_ACTIONS[0]!,
776 SLIM_MENU_ACTIONS[1]!,
777 ],
778 [arrangementMenuItems, autoSettleMenuItems, titleMenuItems],
@@ -779,6 +782,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
782 SNOOZED_MENU_ACTIONS[0]!,
783 ...titleMenuItems,
784 ...autoSettleMenuItems,
785 + LEGACY_MENU_ACTIONS[0]!,
786 SNOOZED_MENU_ACTIONS[1]!,
787 ],
788 [autoSettleMenuItems, titleMenuItems],
apps/web/src/hooks/threadUndo.ts
+1 -36
@@ -1,36 +1 @@
1 -// Shared across hook instances so sidebar, header and menu actions invalidate each other.
2 -const currentActions = new Map<string, symbol>();
3 -const listeners = new Set<() => void>();
4 -
5 -export function subscribe(listener: () => void) {
6 - listeners.add(listener);
7 - return () => {
8 - listeners.delete(listener);
9 - };
10 -}
11 -
12 -function notify() {
13 - for (const listener of listeners) listener();
14 -}
15 -
16 -export function begin(kind: string, threadKey: string) {
17 - const key = JSON.stringify([kind, threadKey]);
18 - const token = Symbol();
19 - currentActions.set(key, token);
20 - notify();
21 - const isCurrent = () => currentActions.get(key) === token;
22 - return {
23 - isCurrent,
24 - finish: () => {
25 - if (isCurrent()) {
26 - currentActions.delete(key);
27 - notify();
28 - }
29 - },
30 - };
31 -}
32 -
33 -export function invalidate(kind: string, threadKey: string) {
34 - currentActions.delete(JSON.stringify([kind, threadKey]));
35 - notify();
36 -}
1 +export * from "@t3tools/client-runtime/state/thread-undo";
apps/web/src/hooks/useThreadActions.ts
+32 -26
@@ -650,6 +650,9 @@ export function useThreadActions() {
650 ? (opts.orderKey ?? topOfPinnedRunOrderKey())
651 : undefined;
652 ThreadUndo.invalidate("pin", scopedThreadKey(target));
653 + // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
654 + ThreadUndo.invalidate("settle", scopedThreadKey(target));
655 + ThreadUndo.invalidate("snooze", scopedThreadKey(target));
656 return pinThreadMutation({
657 environmentId: target.environmentId,
658 input: {
@@ -671,7 +674,7 @@ export function useThreadActions() {
674 );
675 }
676 const thread = readThreadShell(target);
674 - const orderKey = thread?.pinOrderKey ?? undefined;
677 + const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
678 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
679 const result = await unpinThreadMutation({
680 environmentId: target.environmentId,
@@ -681,7 +684,7 @@ export function useThreadActions() {
684 showThreadUndoNotice({
685 action: "Unpinned",
686 claim: action,
684 - undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }),
687 + undo: () => runUndoPlan(target, undoPlan),
688 failureTitle: "Failed to undo unpin",
689 });
690 } else {
@@ -705,11 +708,7 @@ export function useThreadActions() {
708 const wokeAt = resolved
709 ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
710 : null;
708 - // Settling also drops the pin and the snooze server-side, so Undo
709 - // has to put those back as well.
710 - const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null;
711 - const wasPinned = resolved?.thread.pinnedAt != null;
712 - const snoozedUntil = resolved?.thread.snoozedUntil ?? null;
711 + const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
712 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
713 // treats either as a promotion that un-settles; settling supersedes them.
714 ThreadUndo.invalidate("pin", scopedThreadKey(target));
@@ -729,24 +728,7 @@ export function useThreadActions() {
728 showThreadUndoNotice({
729 action: "Settled",
730 claim: action,
732 - undo: async () => {
733 - const unsettled = await unsettleThread(target);
734 - if (unsettled._tag !== "Success") return unsettled;
735 - if (wasPinned) {
736 - const pinned = await pinThread(
737 - target,
738 - pinOrderKey == null ? {} : { orderKey: pinOrderKey },
739 - );
740 - if (pinned._tag !== "Success") return pinned;
741 - }
742 - if (snoozedUntil !== null) {
743 - return snoozeThreadMutation({
744 - environmentId: target.environmentId,
745 - input: { threadId: target.threadId, snoozedUntil },
746 - });
747 - }
748 - return unsettled;
749 - },
731 + undo: () => runUndoPlan(target, undoPlan),
732 failureTitle: "Failed to undo settle",
733 });
734 return result;
@@ -858,12 +840,36 @@ export function useThreadActions() {
840 showThreadUndoNotice({
841 action: "Snoozed",
842 claim: action,
861 - undo: () => unsnoozeThread(target),
843 + undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
844 failureTitle: "Failed to wake thread",
845 });
846 return result;
847 };
848
849 + const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) =>
850 + ThreadUndo.executeThreadUndo(
851 + plan,
852 + async (step) => {
853 + switch (step.action) {
854 + case "unsettle":
855 + return unsettleThread(target);
856 + case "unsnooze":
857 + return unsnoozeThread(target);
858 + case "pin":
859 + return pinThread(
860 + target,
861 + step.orderKey === undefined ? {} : { orderKey: step.orderKey },
862 + );
863 + case "snooze":
864 + return snoozeThreadMutation({
865 + environmentId: target.environmentId,
866 + input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
867 + });
868 + }
869 + },
870 + (result) => result._tag === "Success",
871 + );
872 +
873 const confirmAndDeleteThread = async (target: ScopedThreadRef) => {
874 const permissionFailure = threadOperationFailure(target);
875 if (permissionFailure) return permissionFailure;
apps/web/src/hooks/useThreadActions.undo.test.ts
+63
@@ -1,4 +1,5 @@
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";
@@ -106,7 +107,57 @@ afterEach(() => {
107 vi.restoreAllMocks();
108 });
109
110 +describe("concurrent thread action Undo", () => {
111 + it.each([
112 + ["settleThread", "settle", "unsettle", "Settled"],
113 + ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
114 + ["unpinThread", "unpin", "pin", "Unpinned"],
115 + ["archiveThread", "archive", "unarchive", "Archived"],
116 + ] as const)(
117 + "%s retains one undo for concurrent successful requests",
118 + async (handler, action, inverse, notice) => {
119 + const actions = useThreadActions();
120 + const run = () =>
121 + handler === "snoozeThread"
122 + ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
123 + : actions[handler](target);
124 + await Promise.all([run(), run()]);
125 + expect(commands[action]).toHaveBeenCalledTimes(2);
126 + expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
127 + await currentUndo()();
128 + expect(commands[inverse]).toHaveBeenCalledOnce();
129 + },
130 + );
131 +});
132 +
133 describe("unpin Undo", () => {
134 + it("restores the original snooze after restoring the pin", async () => {
135 + threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
136 + threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
137 + await useThreadActions().unpinThread(target);
138 + await currentUndo()();
139 + expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
140 + environmentId: target.environmentId,
141 + input: { threadId: target.threadId, orderKey: "a0" },
142 + });
143 + expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
144 + environmentId: target.environmentId,
145 + input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
146 + });
147 + expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
148 + commands.snooze.mock.invocationCallOrder[0]!,
149 + );
150 + });
151 +
152 + it("restores the pin without an already expired snooze", async () => {
153 + threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
154 + threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
155 + await useThreadActions().unpinThread(target);
156 + await currentUndo()();
157 + expect(commands.pin).toHaveBeenCalledOnce();
158 + expect(commands.snooze).not.toHaveBeenCalled();
159 + });
160 +
161 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
162 const sidebar = useThreadActions();
163 const header = useThreadActions();
@@ -198,6 +249,18 @@ describe("settle and snooze Undo", () => {
249 });
250 });
251
252 + it("stops settle restoration if restoring the pin fails", async () => {
253 + threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
254 + threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
255 + commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
256 + vi.spyOn(toastManager, "add").mockReturnValue("toast");
257 + await useThreadActions().settleThread(target);
258 + await currentUndo()();
259 + expect(commands.unsettle).toHaveBeenCalledOnce();
260 + expect(commands.pin).toHaveBeenCalledOnce();
261 + expect(commands.snooze).not.toHaveBeenCalled();
262 + });
263 +
264 it("expires an older unpin Undo when the thread is settled", async () => {
265 const actions = useThreadActions();
266 await actions.unpinThread(target);
packages/client-runtime/package.json
+4
@@ -319,6 +319,10 @@
319 "types": "./src/state/threadSubagents.ts",
320 "default": "./src/state/threadSubagents.ts"
321 },
322 + "./state/thread-undo": {
323 + "types": "./src/state/threadUndo.ts",
324 + "default": "./src/state/threadUndo.ts"
325 + },
326 "./state/thread-settled": {
327 "types": "./src/state/threadSettled.ts",
328 "default": "./src/state/threadSettled.ts"
packages/client-runtime/src/state/threadUndo.ts new
+82
@@ -0,0 +1,82 @@
1 +// Shared across hook instances so sidebar, header and menu actions invalidate each other.
2 +const currentActions = new Map<string, symbol>();
3 +const listeners = new Set<() => void>();
4 +
5 +export function subscribe(listener: () => void) {
6 + listeners.add(listener);
7 + return () => {
8 + listeners.delete(listener);
9 + };
10 +}
11 +
12 +function notify() {
13 + for (const listener of listeners) listener();
14 +}
15 +
16 +export function begin(kind: string, threadKey: string) {
17 + const key = JSON.stringify([kind, threadKey]);
18 + const token = Symbol();
19 + currentActions.set(key, token);
20 + notify();
21 + const isCurrent = () => currentActions.get(key) === token;
22 + return {
23 + isCurrent,
24 + finish: () => {
25 + if (isCurrent()) {
26 + currentActions.delete(key);
27 + notify();
28 + }
29 + },
30 + };
31 +}
32 +
33 +export function invalidate(kind: string, threadKey: string) {
34 + currentActions.delete(JSON.stringify([kind, threadKey]));
35 + notify();
36 +}
37 +
38 +export type ThreadUndoStep =
39 + | { readonly action: "unsettle" }
40 + | { readonly action: "unsnooze" }
41 + | { readonly action: "pin"; readonly orderKey?: string }
42 + | { readonly action: "snooze"; readonly snoozedUntil: string };
43 +
44 +export type ThreadUndoPlan = readonly [ThreadUndoStep, ...ThreadUndoStep[]];
45 +
46 +export function planThreadUndo(
47 + action: "settle" | "snooze" | "unpin",
48 + thread?: {
49 + readonly pinnedAt?: string | null;
50 + readonly pinOrderKey?: string | null;
51 + readonly snoozedUntil?: string | null;
52 + } | null,
53 +): ThreadUndoPlan {
54 + if (action === "snooze") return [{ action: "unsnooze" }];
55 + const pin: ThreadUndoStep = {
56 + action: "pin",
57 + ...(thread?.pinOrderKey != null ? { orderKey: thread.pinOrderKey } : {}),
58 + };
59 + // Pinning clears snooze on the server; restore it after restoring pin placement.
60 + const snooze =
61 + thread?.snoozedUntil != null
62 + ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil }]
63 + : [];
64 + if (action === "unpin") return [pin, ...snooze];
65 + return [{ action: "unsettle" }, ...(thread?.pinnedAt != null ? [pin] : []), ...snooze];
66 +}
67 +
68 +export async function executeThreadUndo<Result>(
69 + plan: ThreadUndoPlan,
70 + execute: (step: ThreadUndoStep) => Promise<Result>,
71 + succeeded: (result: Result) => boolean,
72 +): Promise<Result> {
73 + let result = await execute(plan[0]);
74 + for (const step of plan.slice(1)) {
75 + if (!succeeded(result)) return result;
76 + // A snooze can expire before Undo runs, and the server rejects an expired restore.
77 + // @effect-diagnostics-next-line globalDate:off
78 + if (step.action === "snooze" && Date.parse(step.snoozedUntil) <= Date.now()) continue;
79 + result = await execute(step);
80 + }
81 + return result;
82 +}