From f1b07791c39f57b1d1fdaa481e10fa5e4c0c4bd2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:50:23 +1100 Subject: [PATCH 1/5] fix(mobile): settling a deleted thread explains why and offers Remove from list When a thread list action failed because the server no longer has the thread, the dialog showed raw server text such as "No orchestration projection exists for thread ..." with only OK, and the stale row stayed. Classify the failure and show what the user can do: a missing thread offers Remove from list (hidden until the next authoritative snapshot), an archived thread offers Unarchive, and other failures keep the server's reason with Try again. Undo steps never offer a partial retry. Co-Authored-By: Claude Opus 5.5 --- .../features/home/threadActionFailure.test.ts | 42 +++++++ .../src/features/home/threadActionFailure.ts | 40 ++++++ .../home/useThreadListActions.test.ts | 119 +++++++++++++++++- .../src/features/home/useThreadListActions.ts | 99 +++++++++++++-- .../src/state/forgotten-threads.test.ts | 69 ++++++++++ apps/mobile/src/state/forgotten-threads.ts | 69 ++++++++++ apps/mobile/src/state/threads.ts | 3 +- 7 files changed, 423 insertions(+), 18 deletions(-) create mode 100644 apps/mobile/src/features/home/threadActionFailure.test.ts create mode 100644 apps/mobile/src/features/home/threadActionFailure.ts create mode 100644 apps/mobile/src/state/forgotten-threads.test.ts create mode 100644 apps/mobile/src/state/forgotten-threads.ts diff --git a/apps/mobile/src/features/home/threadActionFailure.test.ts b/apps/mobile/src/features/home/threadActionFailure.test.ts new file mode 100644 index 0000000000000..e24c9f52e50ef --- /dev/null +++ b/apps/mobile/src/features/home/threadActionFailure.test.ts @@ -0,0 +1,42 @@ +import * as Cause from "effect/Cause"; +import { describe, expect, it } from "vite-plus/test"; + +import { classifyThreadActionFailure } from "./threadActionFailure"; + +const failure = (error: unknown) => classifyThreadActionFailure(Cause.fail(error)); + +describe("classifyThreadActionFailure", () => { + it("recognizes a thread the server has no projection for", () => { + expect(failure(new Error("No orchestration projection exists for thread mcp:b101.")).kind).toBe( + "missing", + ); + }); + + it("recognizes a deleted thread", () => { + expect(failure(new Error("Thread abc is deleted.")).kind).toBe("missing"); + }); + + it("recognizes an archived thread", () => { + expect(failure(new Error("Thread abc is archived.")).kind).toBe("archived"); + expect(failure(new Error("Thread abc is already archived.")).kind).toBe("other"); + }); + + it("prefers the dispatch error's detail over its message", () => { + expect( + failure({ + _tag: "OrchestrationV2DispatchCommandError", + message: "Failed to dispatch orchestration V2 command", + detail: "Thread abc is deleted.", + }), + ).toEqual({ kind: "missing", message: "Thread abc is deleted." }); + }); + + it("keeps other reasons and tolerates errors without text", () => { + expect(failure(new Error("The server database is busy."))).toEqual({ + kind: "other", + message: "The server database is busy.", + }); + expect(failure(new Error(" "))).toEqual({ kind: "other", message: null }); + expect(failure("plain")).toEqual({ kind: "other", message: null }); + }); +}); diff --git a/apps/mobile/src/features/home/threadActionFailure.ts b/apps/mobile/src/features/home/threadActionFailure.ts new file mode 100644 index 0000000000000..7c9a5aeb1849b --- /dev/null +++ b/apps/mobile/src/features/home/threadActionFailure.ts @@ -0,0 +1,40 @@ +import * as Cause from "effect/Cause"; + +/** + * Why the server rejected a thread list action, when that changes what the user can do next. + * "missing": the server has no such thread, so the row is a stale copy. + * "archived": the thread is archived, so it is already out of the active list. + */ +export type ThreadActionFailureKind = "missing" | "archived" | "other"; + +export interface ThreadActionFailure { + readonly kind: ThreadActionFailureKind; + readonly message: string | null; +} + +// The server's own wording (orchestration-v2 Orchestrator and ProjectionStore). It reaches the +// client as the dispatch error's detail, and older servers send the same text. +const MISSING_THREAD_PATTERNS = [ + /^No orchestration projection exists for thread /, + / is deleted\.$/, +]; +const ARCHIVED_THREAD_PATTERN = /^Thread .+ is archived\.$/; + +function failureMessage(error: unknown): string | null { + if (typeof error !== "object" || error === null) return null; + const { detail, message } = error as { detail?: unknown; message?: unknown }; + for (const text of [detail, message]) { + if (typeof text === "string" && text.trim().length > 0) return text.trim(); + } + return null; +} + +export function classifyThreadActionFailure(cause: Cause.Cause): ThreadActionFailure { + const message = failureMessage(Cause.squash(cause)); + if (message === null) return { kind: "other", message }; + if (MISSING_THREAD_PATTERNS.some((pattern) => pattern.test(message))) { + return { kind: "missing", message }; + } + if (ARCHIVED_THREAD_PATTERN.test(message)) return { kind: "archived", message }; + return { kind: "other", message }; +} diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index ec0f6a14558dd..6ae0c92a2c9dd 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -16,6 +16,8 @@ const state = vi.hoisted(() => ({ pendingOrder: null as object | null, dropBusy: false, failedAction: null as string | null, + failureMessage: "Server rejected action", + forgotten: [] as { environmentId: string; threadId: string }[], archivedRefreshes: [] as string[], scopes: new Map>(), shells: [] as EnvironmentThreadShell[], @@ -27,6 +29,7 @@ const state = vi.hoisted(() => ({ dialogs: [] as { onConfirm: () => void }[], alerts: [] as { title: string; + message: string; buttons?: { text: string; onPress?: () => void }[]; }[], afterRequest: undefined as (() => void) | undefined, @@ -38,8 +41,8 @@ vi.mock("react", () => ({ })); vi.mock("react-native", () => ({ Alert: { - alert: (title: string, _message: string, buttons?: { text: string; onPress?: () => void }[]) => - state.alerts.push({ title, buttons }), + alert: (title: string, message: string, buttons?: { text: string; onPress?: () => void }[]) => + state.alerts.push({ title, message, buttons }), }, })); vi.mock("expo-haptics", () => ({ @@ -47,8 +50,8 @@ vi.mock("expo-haptics", () => ({ ImpactFeedbackStyle: { Light: "light" }, })); vi.mock("../../components/ui/Dialog", () => ({ - alert: (title: string, _message: string, buttons?: { text: string; onPress?: () => void }[]) => - state.alerts.push({ title, buttons }), + alert: (title: string, message: string, buttons?: { text: string; onPress?: () => void }[]) => + state.alerts.push({ title, message, buttons }), confirm: (dialog: { onConfirm: () => void }) => state.dialogs.push(dialog), })); vi.mock("../archive/useArchivedThreadSnapshots", () => ({ @@ -60,6 +63,10 @@ vi.mock("../../state/session", () => ({ readEnvironmentScope: (environmentId: string, scope: string) => state.scopes.get(environmentId)?.has(scope) === true, })); +vi.mock("../../state/forgotten-threads", () => ({ + forgetThread: (environmentId: string, threadId: string) => + state.forgotten.push({ environmentId, threadId }), +})); vi.mock("../../state/server", () => ({ environmentServerConfigsAtom: "server-configs", })); @@ -142,7 +149,7 @@ vi.mock("../../state/threads", () => ({ return AsyncResult.failure(Cause.fail(new Error("Thread operation denied"))); } if (action === state.failedAction) - return AsyncResult.failure(Cause.fail(new Error("Server rejected action"))); + return AsyncResult.failure(Cause.fail(new Error(state.failureMessage))); state.afterRequest?.(); return AsyncResult.success(undefined); }, @@ -180,6 +187,8 @@ const mutationCases = [ beforeEach(() => { state.failedAction = null; + state.failureMessage = "Server rejected action"; + state.forgotten = []; state.archivedRefreshes = []; state.pendingOrder = null; state.dropBusy = false; @@ -463,6 +472,106 @@ describe("thread action undo", () => { }); }); +describe("thread action failure dialog", () => { + const pressButton = (text: string) => + state.alerts + .at(-1) + ?.buttons?.find((button) => button.text === text) + ?.onPress?.(); + + it("explains a thread its server no longer has and removes it from the list", async () => { + state.failedAction = "settle"; + state.failureMessage = "No orchestration projection exists for thread mcp:gone."; + + expect(await useThreadListActions().settleThread(makeThread())).toBe(false); + + const alert = state.alerts.at(-1)!; + expect(alert.title).toBe("Thread no longer exists"); + expect(alert.message).not.toContain("orchestration projection"); + expect(alert.buttons?.map(({ text }) => text)).toEqual(["Keep", "Remove from list"]); + expect(state.forgotten).toEqual([]); + pressButton("Remove from list"); + expect(state.forgotten).toEqual([{ environmentId: primaryEnvironmentId, threadId: "thread" }]); + }); + + it("reloads the archive when removing a missing archived thread", async () => { + state.failedAction = "settle"; + state.failureMessage = "Thread thread is deleted."; + + await useThreadListActions().settleThread( + makeThread({ archivedAt: "2026-09-02T00:00:00.000Z" }), + ); + pressButton("Remove from list"); + + expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]); + }); + + it("keeps Undo when a retried settle succeeds", async () => { + const thread = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" }); + state.failedAction = "settle"; + + await useThreadListActions().settleThread(thread); + state.failedAction = null; + pressButton("Try again"); + await vi.waitFor(() => expect(readThreadUndoNotice()).not.toBeNull()); + await readThreadUndoNotice()!.undo(); + + expect(state.requests.map(({ action }) => action)).toEqual([ + "settle", + "settle", + "unsettle", + "pin", + ]); + }); + + it("offers no partial retry when an Undo step fails", async () => { + await useThreadListActions().settleThread(makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" })); + state.failedAction = "unsettle"; + await readThreadUndoNotice()!.undo(); + + expect(state.alerts.at(-1)?.title).toBe("Could not un-settle thread"); + expect(state.alerts.at(-1)?.buttons?.map(({ text }) => text)).toEqual(["OK"]); + }); + + it("treats a deleted thread as missing", async () => { + state.failedAction = "settle"; + state.failureMessage = "Thread thread is deleted."; + + await useThreadListActions().settleThread(makeThread()); + + expect(state.alerts.at(-1)?.title).toBe("Thread no longer exists"); + }); + + it("offers to unarchive an archived thread", async () => { + state.failedAction = "settle"; + state.failureMessage = "Thread thread is archived."; + + await useThreadListActions().settleThread(makeThread()); + + expect(state.alerts.at(-1)?.title).toBe("Thread is archived"); + state.failedAction = null; + pressButton("Unarchive"); + await vi.waitFor(() => + expect(state.requests.map(({ action }) => action)).toEqual(["settle", "unarchive"]), + ); + }); + + it("keeps the server's reason for other failures and can try again", async () => { + state.failedAction = "settle"; + + await useThreadListActions().settleThread(makeThread()); + + const alert = state.alerts.at(-1)!; + expect(alert.title).toBe("Could not settle thread"); + expect(alert.message).toBe("Server rejected action"); + state.failedAction = null; + pressButton("Try again"); + await vi.waitFor(() => + expect(state.requests.map(({ action }) => action)).toEqual(["settle", "settle"]), + ); + }); +}); + describe("thread archive guard", () => { it("keeps active provider runs out of the archive", async () => { const thread = makeThread({ diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 3ba684bdff174..b89518917057a 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -8,12 +8,14 @@ import * as Cause from "effect/Cause"; import * as Haptics from "expo-haptics"; import { useRef } from "react"; +import { classifyThreadActionFailure } from "./threadActionFailure"; import { withThreadDismissal } from "./thread-dismissal"; import * as Dialog from "../../components/ui/Dialog"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots"; import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort"; import { appAtomRegistry } from "../../state/atom-registry"; +import { forgetThread } from "../../state/forgotten-threads"; import { environmentServerConfigsAtom } from "../../state/server"; import { readEnvironmentScope } from "../../state/session"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; @@ -90,12 +92,63 @@ const ACTION_VERBS: Record = { unsettle: "un-settled", }; -function actionFailureMessage(action: ThreadListAction, cause: Cause.Cause): string { - const error = Cause.squash(cause); - if (error instanceof Error && error.message.trim().length > 0) { - return error.message; +const ACTION_INFINITIVES: Record = { + archive: "archive", + unarchive: "unarchive", + delete: "delete", + settle: "settle", + unsettle: "un-settle", +}; + +/** Explains a rejected action and offers what the user can do about it. */ +function showActionFailure( + action: ThreadListAction, + thread: EnvironmentThreadShell, + cause: Cause.Cause, + run: ((action: ThreadListAction) => void) | null, +): void { + const failure = classifyThreadActionFailure(cause); + if (failure.kind === "missing") { + Dialog.alert( + "Thread no longer exists", + `“${thread.title}” is no longer on its server, so it can't be ${ACTION_VERBS[action]}. It was probably deleted on another device, and this list is showing an old copy.`, + [ + { text: "Keep", style: "cancel" }, + { + text: "Remove from list", + style: "destructive", + onPress: () => { + forgetThread(thread.environmentId, thread.id); + // Archive rows come from the server's archived snapshot, which reloads without it. + if (thread.archivedAt != null) + refreshArchivedThreadsForEnvironment(thread.environmentId); + }, + }, + ], + ); + return; } - return `The thread could not be ${ACTION_VERBS[action]}.`; + if (failure.kind === "archived" && action !== "unarchive" && run !== null) { + Dialog.alert( + "Thread is archived", + `“${thread.title}” is archived, so it is already out of your active list. Unarchive it first to ${ACTION_INFINITIVES[action]} it.`, + [ + { text: "OK", style: "cancel" }, + { text: "Unarchive", onPress: () => run("unarchive") }, + ], + ); + return; + } + Dialog.alert( + actionFailureTitle(action), + failure.message ?? `The thread could not be ${ACTION_VERBS[action]}.`, + run === null + ? [{ text: "OK", style: "cancel" }] + : [ + { text: "OK", style: "cancel" }, + { text: "Try again", onPress: () => run(action) }, + ], + ); } function selectionHaptic(): void { @@ -116,6 +169,8 @@ function checkThreadOperationPermission(thread: EnvironmentThreadShell, title: s return false; } +type ThreadActionRerun = (action: ThreadListAction, thread: EnvironmentThreadShell) => void; + function useThreadActionExecutor( onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void, ) { @@ -130,6 +185,10 @@ function useThreadActionExecutor( action: ThreadListAction, thread: EnvironmentThreadShell, onStarted?: () => void, + // Sends the dialog's retry or Unarchive through the caller's full handler, so Undo + // bookkeeping such as settle's still runs; without it the bare executor runs them. + // null offers no retry: an Undo step retried alone would skip the rest of its plan. + rerun?: ThreadActionRerun | null, ) => { if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false; const key = scopedThreadKey(thread.environmentId, thread.id); @@ -187,7 +246,17 @@ function useThreadActionExecutor( (result) => result._tag === "Success", ); if (result._tag === "Failure") { - Dialog.alert(actionFailureTitle(action), actionFailureMessage(action, result.cause)); + showActionFailure( + action, + thread, + result.cause, + rerun === null + ? null + : (next) => { + if (rerun) rerun(next, thread); + else void executeAction(next, thread); + }, + ); return false; } if (action === "archive" || action === "unarchive" || action === "delete") { @@ -273,7 +342,7 @@ export function useThreadListActions(): { async (step) => { switch (step.action) { case "unsettle": - return unsettleThread(thread); + return (await executeAction("unsettle", thread, undefined, null)) === true; case "unsnooze": return unsnoozeThread(thread); case "pin": @@ -312,11 +381,17 @@ export function useThreadListActions(): { const key = scopedThreadKey(thread.environmentId, thread.id); const plan = ThreadUndo.planThreadUndo("settle", thread); let claim: ReturnType | undefined; - const succeeded = await executeAction("settle", thread, () => { - ThreadUndo.invalidate("pin", key); - ThreadUndo.invalidate("snooze", key); - claim = ThreadUndo.begin("settle", key); - }); + const succeeded = await executeAction( + "settle", + thread, + () => { + ThreadUndo.invalidate("pin", key); + ThreadUndo.invalidate("snooze", key); + claim = ThreadUndo.begin("settle", key); + }, + (next, target) => + void (next === "settle" ? settleThread(target) : executeAction(next, target)), + ); if (claim) { if (succeeded) offerUndo(thread, "Settled", claim, plan); else claim.finish(); diff --git a/apps/mobile/src/state/forgotten-threads.test.ts b/apps/mobile/src/state/forgotten-threads.test.ts new file mode 100644 index 0000000000000..e0fc616f97b26 --- /dev/null +++ b/apps/mobile/src/state/forgotten-threads.test.ts @@ -0,0 +1,69 @@ +import type { EnvironmentShellState } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, type OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +const shellStates = vi.hoisted(() => new Map()); +const catalog = vi.hoisted(() => ({ atom: null as unknown })); + +vi.mock("./shell", () => ({ + environmentShell: { + stateValueAtom: (environmentId: string) => shellStates.get(environmentId), + }, +})); + +vi.mock("../connection/catalog", async () => { + const { Atom } = await import("effect/reactivity"); + catalog.atom = Atom.make({ isReady: true, entries: new Map() }).pipe(Atom.keepAlive); + return { environmentCatalog: { catalogValueAtom: catalog.atom } }; +}); + +import { appAtomRegistry } from "./atom-registry"; +import { forgetThread, withoutForgottenThreads } from "./forgotten-threads"; + +const environmentId = EnvironmentId.make("forgotten-threads-env"); +const kept = ThreadId.make("kept"); +const gone = ThreadId.make("gone"); + +const shellState = Atom.make({ generation: 0 } as EnvironmentShellState).pipe(Atom.keepAlive); +shellStates.set(environmentId, shellState); +const snapshot = Atom.make({ + threads: [{ id: kept }, { id: gone }], +} as unknown as OrchestrationV2ShellSnapshot).pipe(Atom.keepAlive); +const visible = withoutForgottenThreads(() => snapshot)(environmentId); +const visibleIds = () => appAtomRegistry.get(visible)?.threads.map((thread) => thread.id); +const catalogAtom = catalog.atom as Atom.Writable<{ + isReady: boolean; + entries: Map; +}>; +appAtomRegistry.set(catalogAtom, { isReady: true, entries: new Map([[environmentId, {}]]) }); +const setGeneration = (generation: number) => + appAtomRegistry.set(shellState, { generation } as EnvironmentShellState); + +describe("withoutForgottenThreads", () => { + it("hides a forgotten thread until the shell generation changes, and only once", () => { + const unmount = appAtomRegistry.mount(visible); + expect(visibleIds()).toEqual([kept, gone]); + + forgetThread(environmentId, gone); + expect(visibleIds()).toEqual([kept]); + + setGeneration(7); + expect(visibleIds()).toEqual([kept, gone]); + + // A rebuilt shell returns to cached generation 0; the expired entry must stay expired. + setGeneration(0); + expect(visibleIds()).toEqual([kept, gone]); + unmount(); + }); + + it("expires a forgotten thread when its environment is removed", () => { + const unmount = appAtomRegistry.mount(visible); + forgetThread(environmentId, gone); + expect(visibleIds()).toEqual([kept]); + + appAtomRegistry.set(catalogAtom, { isReady: true, entries: new Map() }); + expect(visibleIds()).toEqual([kept, gone]); + unmount(); + }); +}); diff --git a/apps/mobile/src/state/forgotten-threads.ts b/apps/mobile/src/state/forgotten-threads.ts new file mode 100644 index 0000000000000..b395f6a6eef1d --- /dev/null +++ b/apps/mobile/src/state/forgotten-threads.ts @@ -0,0 +1,69 @@ +import type { EnvironmentId, OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { environmentCatalog } from "../connection/catalog"; +import { appAtomRegistry } from "./atom-registry"; +import { environmentShell } from "./shell"; + +/** + * Threads their server says it no longer has, hidden from the lists until the environment's + * shell generation next changes. The next authoritative snapshot (or a rebuilt shell) decides + * again, so a thread the server still lists comes back instead of staying hidden forever. + */ +const forgottenThreadsAtom = Atom.make>>( + new Map(), +).pipe(Atom.keepAlive, Atom.withLabel("forgotten-threads")); + +function updateForgotten( + environmentId: EnvironmentId, + change: (threads: Set) => void, +): void { + const current = appAtomRegistry.get(forgottenThreadsAtom); + const threads = new Set(current.get(environmentId)); + change(threads); + const next = new Map(current); + if (threads.size === 0) next.delete(environmentId); + else next.set(environmentId, threads); + appAtomRegistry.set(forgottenThreadsAtom, next); +} + +export function forgetThread(environmentId: EnvironmentId, threadId: ThreadId): void { + if (appAtomRegistry.get(forgottenThreadsAtom).get(environmentId)?.has(threadId)) return; + const shellState = environmentShell.stateValueAtom(environmentId); + const { generation } = appAtomRegistry.get(shellState); + updateForgotten(environmentId, (threads) => threads.add(threadId)); + let expired = false; + const expire = () => { + if (expired) return; + expired = true; + unsubscribeShell(); + unsubscribeCatalog(); + updateForgotten(environmentId, (threads) => threads.delete(threadId)); + }; + // Any generation change expires the entry for good: cached shells reuse generation 0, so + // comparing numbers later could hide the thread again after a rebuild. + const unsubscribeShell = appAtomRegistry.subscribe(shellState, (state) => { + if (state.generation !== generation) expire(); + }); + // A removed environment's shell stops emitting, so its entries expire with it. + const unsubscribeCatalog = appAtomRegistry.subscribe( + environmentCatalog.catalogValueAtom, + (catalog) => { + if (catalog.isReady && !catalog.entries.has(environmentId)) expire(); + }, + ); +} + +export function withoutForgottenThreads( + snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom, +) { + return Atom.family((environmentId: EnvironmentId) => + Atom.make((get): OrchestrationV2ShellSnapshot | null => { + const snapshot = get(snapshotAtom(environmentId)); + const forgotten = get(forgottenThreadsAtom).get(environmentId); + if (snapshot === null || forgotten === undefined) return snapshot; + const threads = snapshot.threads.filter((thread) => !forgotten.has(thread.id)); + return threads.length === snapshot.threads.length ? snapshot : { ...snapshot, threads }; + }).pipe(Atom.withLabel(`visible-shell-snapshot:${environmentId}`)), + ); +} diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index 28cb2f88c0d61..afe78093137b4 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -18,6 +18,7 @@ import { environmentCatalog } from "../connection/catalog"; import { connectionAtomRuntime } from "../connection/runtime"; import { scopedThreadKey } from "../lib/scopedEntities"; import { appAtomRegistry } from "./atom-registry"; +import { withoutForgottenThreads } from "./forgotten-threads"; import { pendingThreadCreationOutcomesAtom, selectThreadCreationDetail, @@ -43,7 +44,7 @@ export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( ); export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, - snapshotAtom: threadEnvironment.snapshotAtom, + snapshotAtom: withoutForgottenThreads(threadEnvironment.snapshotAtom), }); /** Keeps the subagent tree under `rootThreadId` in the thread list while the caller shows it. */ From 79847d9d419b15a469d6ae010ec6eea9fa91c8e5 Mon Sep 17 00:00:00 2001 From: SAPHID Date: Sat, 31 Oct 2026 06:55:38 +0000 Subject: [PATCH 2/5] fix(mobile): avoid partial retry after a failed undo --- .../home/useThreadListActions.test.ts | 22 ++++++++++----- .../src/features/home/useThreadListActions.ts | 28 ++++++++++--------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 1020c076da1ba..63394d3db619f 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -602,14 +602,22 @@ describe("thread action failure dialog", () => { ]); }); - it("offers no partial retry when an Undo step fails", async () => { - await useThreadListActions().settleThread(makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" })); - state.failedAction = "unsettle"; - await readThreadUndoNotice()!.undo(); + it.each(["Server rejected action", "Thread thread is deleted."])( + "offers no partial retry when an Undo step fails: %s", + async (message) => { + await useThreadListActions().settleThread( + makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" }), + ); + state.failedAction = "unsettle"; + state.failureMessage = message; + await readThreadUndoNotice()!.undo(); - expect(state.alerts.at(-1)?.title).toBe("Could not un-settle thread"); - expect(state.alerts.at(-1)?.buttons?.map(({ text }) => text)).toEqual(["OK"]); - }); + expect(state.alerts.at(-1)?.title).toBe( + message.includes("deleted") ? "Thread no longer exists" : "Could not un-settle thread", + ); + expect(state.alerts.at(-1)?.buttons?.map(({ text }) => text)).toEqual(["OK"]); + }, + ); it("treats a deleted thread as missing", async () => { state.failedAction = "settle"; diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index d60fe3e858b0e..3a623e95a99ed 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -79,19 +79,21 @@ function showActionFailure( Dialog.alert( "Thread no longer exists", `“${thread.title}” is no longer on its server, so it can't be ${ACTION_VERBS[action]}. It was probably deleted on another device, and this list is showing an old copy.`, - [ - { text: "Keep", style: "cancel" }, - { - text: "Remove from list", - style: "destructive", - onPress: () => { - forgetThread(thread.environmentId, thread.id); - // Archive rows come from the server's archived snapshot, which reloads without it. - if (thread.archivedAt != null) - refreshArchivedThreadsForEnvironment(thread.environmentId); - }, - }, - ], + run === null + ? [{ text: "OK", style: "cancel" }] + : [ + { text: "Keep", style: "cancel" }, + { + text: "Remove from list", + style: "destructive", + onPress: () => { + forgetThread(thread.environmentId, thread.id); + // Archive rows come from the server's archived snapshot, which reloads without it. + if (thread.archivedAt != null) + refreshArchivedThreadsForEnvironment(thread.environmentId); + }, + }, + ], ); return; } From 977af4d58cc89022073b4b1504f48ce160f1e11b Mon Sep 17 00:00:00 2001 From: SAPHID Date: Sat, 31 Oct 2026 10:37:19 +0000 Subject: [PATCH 3/5] fix(mobile): prevent partial retry of a failed thread move --- .../home/useThreadListActions.test.ts | 19 +++++++++++++++++++ .../src/features/home/useThreadListActions.ts | 5 +++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 63394d3db619f..3af86cd28be6e 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -602,6 +602,25 @@ describe("thread action failure dialog", () => { ]); }); + it.each(["Server rejected action", "Thread thread is deleted."])( + "offers no partial retry when a move step fails: %s", + async (message) => { + const thread = makeThread({ settledOverride: "settled" }); + state.shells = [thread]; + state.failedAction = "unsettle"; + state.failureMessage = message; + expect( + await useThreadListActions().moveThread(thread, { + targetId: null, + section: "active", + placement: "before", + }), + ).toBe(false); + expect(state.requests.map(({ action }) => action)).toEqual(["unsettle"]); + expect(state.alerts.at(-1)?.buttons?.map(({ text }) => text)).toEqual(["OK"]); + }, + ); + it.each(["Server rejected action", "Thread thread is deleted."])( "offers no partial retry when an Undo step fails: %s", async (message) => { diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 3a623e95a99ed..819b2c2a4d5fa 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -156,7 +156,7 @@ function useThreadActionExecutor( onStarted?: () => void, // Sends the dialog's retry or Unarchive through the caller's full handler, so Undo // bookkeeping such as settle's still runs; without it the bare executor runs them. - // null offers no retry: an Undo step retried alone would skip the rest of its plan. + // null offers no retry: retrying one compound step would skip the rest of its plan. rerun?: ThreadActionRerun | null, ) => { if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false; @@ -742,7 +742,8 @@ export function useThreadListActions(): { } } else { if (lifecycle.unpin && !(await unpinThread(thread))) return false; - if (lifecycle.unsettle && !(await unsettleThread(thread))) return false; + if (lifecycle.unsettle && !(await executeAction("unsettle", thread, undefined, null))) + return false; if (lifecycle.unsnooze && !(await unsnoozeThread(thread))) return false; } } From 350581ae38624fce4461bea811832f93ec332418 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:17:55 +1100 Subject: [PATCH 4/5] fix(mobile): removed threads leave held lists, and retries act on the live row Main's steady lists can hold an older snapshot while an environment replays, so Remove from list now filters what they show. A retry or Unarchive from the failure dialog reads the live row, like main's other list actions. Co-Authored-By: Claude Opus 5.5 --- .../home/useThreadListActions.test.ts | 34 ++++++++++--------- .../src/features/home/useThreadListActions.ts | 6 ++-- apps/mobile/src/state/threads.ts | 5 +-- 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 246f487ac375e..c763d4a0fa79b 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -639,23 +639,25 @@ describe("thread action failure dialog", () => { expect(state.archivedRefreshes).toEqual([primaryEnvironmentId]); }); - it("keeps Undo when a retried settle succeeds", async () => { - const thread = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" }); - state.failedAction = "settle"; - - await useThreadListActions().settleThread(thread); - state.failedAction = null; - pressButton("Try again"); - await vi.waitFor(() => expect(readThreadUndoNotice()).not.toBeNull()); - await readThreadUndoNotice()!.undo(); + it.each([ + ["still pinned", "2026-09-02T00:00:00.000Z", ["settle", "settle", "unsettle", "pin"]], + ["unpinned elsewhere", null, ["settle", "settle", "unsettle"]], + ] as const)( + "keeps Undo for the live row when a retried settle succeeds: %s", + async (_, pinnedAt, requests) => { + const thread = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z" }); + state.failedAction = "settle"; + + await useThreadListActions().settleThread(thread); + state.failedAction = null; + state.shells = [{ ...thread, pinnedAt }]; + pressButton("Try again"); + await vi.waitFor(() => expect(readThreadUndoNotice()).not.toBeNull()); + await readThreadUndoNotice()!.undo(); - expect(state.requests.map(({ action }) => action)).toEqual([ - "settle", - "settle", - "unsettle", - "pin", - ]); - }); + expect(state.requests.map(({ action }) => action)).toEqual(requests); + }, + ); it.each(["Server rejected action", "Thread thread is deleted."])( "offers no partial retry when a move step fails: %s", diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index e420080259433..e1cb69d8b24dd 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -242,8 +242,10 @@ function useThreadActionExecutor( rerun === null ? null : (next) => { - if (rerun) rerun(next, thread); - else void executeAction(next, thread); + // The dialog can stay open while the row changes elsewhere. + const current = liveThread(thread); + if (rerun) rerun(next, current); + else void executeAction(next, current); }, ); return false; diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index c149b7f2f7750..d87ab6f7b9367 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -51,7 +51,7 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ }); const steadyShells = createSteadyShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, - snapshotAtom: visibleThreadSnapshotAtom, + snapshotAtom: threadEnvironment.snapshotAtom, shellStateAtom: environmentShell.stateValueAtom, rowActionsAtom: threadEnvironment.rowActionsAtom, connectionStateAtom: environmentCatalog.stateAtom, @@ -63,7 +63,8 @@ const steadyShells = createSteadyShellAtoms({ export const steadyShellsHoldingAtom = steadyShells.holdingAtom; export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, - snapshotAtom: steadyShells.snapshotAtom, + // Filtered after the hold, which can keep showing an older snapshot that still has the row. + snapshotAtom: withoutForgottenThreads(steadyShells.snapshotAtom), hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, }).navigationThreadShellsAtom; export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ From 8eae5dea3f047c7dca403f7c66d5da3fe8b57b25 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:22:01 +1100 Subject: [PATCH 5/5] fix(mobile): preserve queued messages when hiding stale threads Keep complete thread shells for existence checks and filter only navigation lists. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/state/threads.test.ts | 64 ++++++++++++++++++++++++--- apps/mobile/src/state/threads.ts | 7 +-- 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/apps/mobile/src/state/threads.test.ts b/apps/mobile/src/state/threads.test.ts index 8cdb476e427e2..9ad739f29a72f 100644 --- a/apps/mobile/src/state/threads.test.ts +++ b/apps/mobile/src/state/threads.test.ts @@ -6,19 +6,44 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import { makeRawThreadShell } from "../test-fixtures"; import { appAtomRegistry } from "./atom-registry"; +import { forgetThread } from "./forgotten-threads"; import { pendingThreadCreationOutcomesAtom } from "./pending-thread-creation"; import { threadOutboxManager } from "./thread-outbox"; import type { QueuedThreadMessage } from "./thread-outbox-model"; -import { startOpeningEnvironmentThread } from "./threads"; +import { + environmentThreadShells, + startOpeningEnvironmentThread, + steadyNavigationThreadShellsAtom, +} from "./threads"; const loads = vi.hoisted(() => [] as string[]); +const fixtures = vi.hoisted(() => ({ snapshotAtom: null as unknown })); vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} })); -vi.mock("../connection/catalog", () => ({ environmentCatalog: {} })); -vi.mock("./shell", () => ({ environmentShell: {} })); +vi.mock("../connection/catalog", async () => { + const { AsyncResult, Atom } = await import("effect/reactivity"); + const catalogValueAtom = Atom.make({ + isReady: true, + entries: new Map([["environment-1", { enabled: true }]]), + }).pipe(Atom.keepAlive); + const connectionAtom = Atom.make(AsyncResult.initial()); + return { environmentCatalog: { catalogValueAtom, stateAtom: () => connectionAtom } }; +}); +vi.mock("./shell", async () => { + const { Atom } = await import("effect/reactivity"); + const shellState = Atom.make({ status: "live", generation: 1 }).pipe(Atom.keepAlive); + return { environmentShell: { stateValueAtom: () => shellState } }; +}); +vi.mock("./server", async () => { + const { Atom } = await import("effect/reactivity"); + const noHiddenTags = Atom.make(null); + return { serverEnvironment: { hiddenThreadTagsAtom: () => noHiddenTags } }; +}); vi.mock("@t3tools/client-runtime/state/threads", async (importOriginal) => { const { Atom } = await import("effect/reactivity"); const stateAtom = Atom.family((key: string) => @@ -27,13 +52,18 @@ vi.mock("@t3tools/client-runtime/state/threads", async (importOriginal) => { return null; }), ); + const snapshotAtom = Atom.make(null).pipe(Atom.keepAlive); + fixtures.snapshotAtom = snapshotAtom; + const noRowActions = Atom.make(0); return { ...(await importOriginal()), createThreadFamilyAtoms: () => ({}), createOlderSettledThreadAtoms: () => ({}), - createThreadEnvironmentAtoms: () => ({}), + createThreadEnvironmentAtoms: () => ({ + snapshotAtom: () => snapshotAtom, + rowActionsAtom: () => noRowActions, + }), createEnvironmentThreadDetailAtoms: () => ({}), - createEnvironmentThreadShellAtoms: () => ({}), createEnvironmentThreadStateAtoms: () => ({ stateAtom: (environmentId: string, threadId: string) => stateAtom(`${environmentId}:${threadId}`), @@ -108,3 +138,27 @@ describe("startOpeningEnvironmentThread", () => { expect(loads).toEqual([threadKey, `${environmentId}:${otherThreadId}`]); }); }); + +describe("Remove from list", () => { + it("hides the thread from lists but keeps it where queued messages look it up", () => { + const kept = makeRawThreadShell({ id: ThreadId.make("kept") }); + const removed = makeRawThreadShell({ id: ThreadId.make("removed") }); + appAtomRegistry.set(fixtures.snapshotAtom as Atom.Writable, { + snapshotSequence: 1, + threads: [kept, removed], + }); + const ids = (atom: Atom.Atom>) => + appAtomRegistry.get(atom).map((thread) => thread.id); + const unmountList = appAtomRegistry.mount(steadyNavigationThreadShellsAtom); + const unmountShells = appAtomRegistry.mount(environmentThreadShells.threadShellsAtom); + expect(ids(steadyNavigationThreadShellsAtom)).toEqual([kept.id, removed.id]); + + forgetThread(environmentId, removed.id); + + expect(ids(steadyNavigationThreadShellsAtom)).toEqual([kept.id]); + // The outbox deletes queued messages for a thread missing from these shells. + expect(ids(environmentThreadShells.threadShellsAtom)).toEqual([kept.id, removed.id]); + unmountShells(); + unmountList(); + }); +}); diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index d87ab6f7b9367..beac88cade9b5 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -43,10 +43,9 @@ export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAt export const environmentThreadDetails = createEnvironmentThreadDetailAtoms( environmentThreads.stateAtom, ); -const visibleThreadSnapshotAtom = withoutForgottenThreads(threadEnvironment.snapshotAtom); export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, - snapshotAtom: visibleThreadSnapshotAtom, + snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, }); const steadyShells = createSteadyShellAtoms({ @@ -63,7 +62,9 @@ const steadyShells = createSteadyShellAtoms({ export const steadyShellsHoldingAtom = steadyShells.holdingAtom; export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, - // Filtered after the hold, which can keep showing an older snapshot that still has the row. + // Only lists drop threads removed from the list: the outbox reads environmentThreadShells and + // deletes queued messages for a thread it is missing. Filtered after the hold, which can keep + // showing an older snapshot that still has the row. snapshotAtom: withoutForgottenThreads(steadyShells.snapshotAtom), hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, }).navigationThreadShellsAtom;