Skip to content

Commit 6efe9a0

Browse files
authored
fix(mobile): restore archive and thread action undo (pingdotgg#21401)
1 parent f16251f commit 6efe9a0

12 files changed

Lines changed: 583 additions & 72 deletions

‎apps/mobile/src/features/home/HomeRouteScreen.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ThreadUndoNotice } from "./ThreadUndoNotice";
12
import { Toolbar } from "../../components/ui/Toolbar";
23
import { use } from "react";
34
import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
@@ -306,6 +307,7 @@ export function HomeRouteScreen() {
306307
selectedProjectKey={selectedProjectKey}
307308
threads={threads}
308309
/>
310+
<ThreadUndoNotice visible={visible} />
309311
</>
310312
</AndroidHomeFabLayout>
311313
);
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 207 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
EnvironmentId,
66
ProjectId,
77
ProviderInstanceId,
8+
RunId,
89
ThreadId,
910
} from "@t3tools/contracts";
1011
import * as Cause from "effect/Cause";
@@ -14,12 +15,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
1415
const state = vi.hoisted(() => ({
1516
pendingOrder: null as object | null,
1617
dropBusy: false,
18+
failedAction: null as string | null,
19+
archivedRefreshes: [] as string[],
1720
scopes: new Map<string, Set<string>>(),
1821
shells: [] as EnvironmentThreadShell[],
1922
requests: [] as {
2023
action: string;
2124
environmentId: string;
22-
input: { threadId: string; orderKey?: string };
25+
input: { threadId: string; orderKey?: string; snoozedUntil?: string; reason?: string };
2326
}[],
2427
dialogs: [] as { onConfirm: () => void }[],
2528
alerts: [] as {
@@ -49,7 +52,9 @@ vi.mock("../../components/ui/Dialog", () => ({
4952
confirm: (dialog: { onConfirm: () => void }) => state.dialogs.push(dialog),
5053
}));
5154
vi.mock("../archive/useArchivedThreadSnapshots", () => ({
52-
refreshArchivedThreadsForEnvironment: () => {},
55+
refreshArchivedThreadsForEnvironment: (environmentId: string) => {
56+
state.archivedRefreshes.push(environmentId);
57+
},
5358
}));
5459
vi.mock("../../state/session", () => ({
5560
readEnvironmentScope: (environmentId: string, scope: string) =>
@@ -133,13 +138,16 @@ vi.mock("../../state/threads", () => ({
133138
if (!state.scopes.get(request.environmentId)?.has(AuthOrchestrationOperateScope)) {
134139
return AsyncResult.failure(Cause.fail(new Error("Thread operation denied")));
135140
}
141+
if (action === state.failedAction)
142+
return AsyncResult.failure(Cause.fail(new Error("Server rejected action")));
136143
state.afterRequest?.();
137144
return AsyncResult.success(undefined);
138145
},
139146
]),
140147
),
141148
}));
142149

150+
import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice";
143151
import { useArchivedThreadListActions, useThreadListActions } from "./useThreadListActions";
144152

145153
const primaryEnvironmentId = EnvironmentId.make("primary");
@@ -168,6 +176,8 @@ const mutationCases = [
168176
] as const;
169177

170178
beforeEach(() => {
179+
state.failedAction = null;
180+
state.archivedRefreshes = [];
171181
state.pendingOrder = null;
172182
state.dropBusy = false;
173183
state.scopes = new Map([
@@ -181,7 +191,11 @@ beforeEach(() => {
181191
state.afterRequest = undefined;
182192
});
183193

184-
afterEach(() => vi.unstubAllEnvs());
194+
afterEach(() => {
195+
dismissThreadUndoNotice();
196+
vi.useRealTimers();
197+
vi.unstubAllEnvs();
198+
});
185199

186200
describe("thread list operation permissions", () => {
187201
it.each(mutationCases)(
@@ -315,3 +329,193 @@ describe("pinned thread operation permissions", () => {
315329
expect(state.requests).toHaveLength(1);
316330
});
317331
});
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+
});

0 commit comments

Comments
 (0)