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 135cf4e1d85a7..3b78eb794ecc0 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -19,6 +19,8 @@ const state = vi.hoisted(() => ({ dropBusy: false, holdingRows: false, failedAction: null as string | null, + failureMessage: "Server rejected action", + forgotten: [] as { environmentId: string; threadId: string }[], titleOutcome: null as ThreadTitleRegenerationOutcome | null, archivedRefreshes: [] as string[], onArchivedRefresh: undefined as (() => void) | undefined, @@ -32,6 +34,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, @@ -44,8 +47,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", () => ({ @@ -53,8 +56,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", () => ({ @@ -67,6 +70,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/presentation", () => ({ connectedEnvironmentIdsAtom: "connected-environments", })); @@ -172,7 +179,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(action === "regenerateTitle" ? state.titleOutcome : undefined); }, @@ -183,6 +190,7 @@ vi.mock("../../state/threads", () => ({ import { appAtomRegistry } from "../../state/atom-registry"; import { composerDraftsAtom } from "../../state/use-composer-drafts"; import { dismissThreadUndoNotice, readThreadUndoNotice } from "./thread-undo-notice"; +import * as ThreadUndoNotice from "./thread-undo-notice"; import { useThreadListActions } from "./useThreadListActions"; const primaryEnvironmentId = EnvironmentId.make("primary"); @@ -213,6 +221,8 @@ const mutationCases = [ beforeEach(() => { state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; state.failedAction = null; + state.failureMessage = "Server rejected action"; + state.forgotten = []; state.titleOutcome = null; state.archivedRefreshes = []; state.onArchivedRefresh = undefined; @@ -483,6 +493,7 @@ describe("thread action undo", () => { const thread = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z", pinOrderKey: "m", + unsettledAt: "2026-09-01T00:00:00.000Z", snoozedUntil: "2099-01-01T09:00:00.000Z", }); expect(await useThreadListActions().settleThread(thread)).toBe(true); @@ -496,6 +507,11 @@ describe("thread action undo", () => { "pin", "snooze", ]); + expect(state.requests[1]?.input).toEqual({ + threadId: thread.id, + reason: "user", + restoreUnsettledAt: thread.unsettledAt, + }); expect(state.requests[2]?.input).toEqual({ threadId: thread.id, orderKey: "m" }); expect(state.requests[3]?.input).toEqual({ threadId: thread.id, @@ -639,6 +655,143 @@ 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.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 }]; + const noticeShown = Promise.withResolvers(); + const showNotice = ThreadUndoNotice.showThreadUndoNotice; + using _notice = vi + .spyOn(ThreadUndoNotice, "showThreadUndoNotice") + .mockImplementation((notice) => { + showNotice(notice); + noticeShown.resolve(); + }); + pressButton("Try again"); + await noticeShown.promise; + await readThreadUndoNotice()!.undo(); + + 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", + 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) => { + 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( + 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"; + 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; + const refreshed = new Promise((resolve) => (state.onArchivedRefresh = resolve)); + pressButton("Unarchive"); + await refreshed; + 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; + const retried = new Promise((resolve) => (state.afterRequest = resolve)); + pressButton("Try again"); + await retried; + 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 8a70854e5b2c3..fc5feac61a5cb 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -10,6 +10,7 @@ import * as Haptics from "expo-haptics"; import { msg } from "gt-react-native"; import { useRef } from "react"; +import { classifyThreadActionFailure } from "./threadActionFailure"; import { withThreadDismissal } from "./thread-dismissal"; import * as Dialog from "../../components/ui/Dialog"; import { m } from "../../i18n/messages"; @@ -17,6 +18,7 @@ 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 { connectedEnvironmentIdsAtom } from "../../state/presentation"; import { readEnvironmentScope } from "../../state/session"; @@ -66,12 +68,67 @@ const ACTION_FAILURES: Record = { unsettle: msg("The thread could not be 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; +/** 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( + m(msg("Thread no longer exists")), + m( + msg( + "“{title}” is no longer on its server. It was probably deleted on another device, and this list is showing an old copy.", + { title: thread.title }, + ), + ), + run === null + ? [{ text: m(msg("OK")), style: "cancel" }] + : [ + { text: m(msg("Keep")), style: "cancel" }, + { + text: m(msg("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; + } + if (failure.kind === "archived" && action !== "unarchive" && run !== null) { + Dialog.alert( + m(msg("Thread is archived")), + m( + msg( + "“{title}” is archived, so it is already out of your active list. Unarchive it first, then try again.", + { title: thread.title }, + ), + ), + [ + { text: m(msg("OK")), style: "cancel" }, + { text: m(msg("Unarchive")), onPress: () => run("unarchive") }, + ], + ); + return; } - return m(ACTION_FAILURES[action]); + Dialog.alert( + actionFailureTitle(action), + failure.message ?? m(ACTION_FAILURES[action]), + run === null + ? [{ text: m(msg("OK")), style: "cancel" }] + : [ + { text: m(msg("OK")), style: "cancel" }, + { text: m(msg("Try again")), onPress: () => run(action) }, + ], + ); } function selectionHaptic(): void { @@ -105,6 +162,8 @@ function liveThread(thread: EnvironmentThreadShell): EnvironmentThreadShell { ); } +type ThreadActionRerun = (action: ThreadListAction, thread: EnvironmentThreadShell) => void; + function useThreadActionExecutor( onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void, ) { @@ -119,6 +178,8 @@ function useThreadActionExecutor( action: ThreadListAction, thread: EnvironmentThreadShell, onStarted?: () => void, + // null disables retries of individual steps in compound actions. + rerun?: ThreadActionRerun | null, restoreUnsettledAt?: string | null, ) => { if (!checkThreadOperationPermission(thread, actionFailureTitle(action))) return false; @@ -184,7 +245,19 @@ 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) => { + // 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; } if (action === "archive" || action === "delete") { @@ -281,7 +354,15 @@ export function useThreadListActions(): { async (step) => { switch (step.action) { case "unsettle": - return unsettleThread(thread, step.restoreUnsettledAt); + return ( + (await executeAction( + "unsettle", + thread, + undefined, + null, + step.restoreUnsettledAt, + )) === true + ); case "unsnooze": return unsnoozeThread(thread); case "pin": @@ -334,11 +415,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(); @@ -458,7 +545,7 @@ export function useThreadListActions(): { const unsettleThread = async ( thread: EnvironmentThreadShell, restoreUnsettledAt?: string | null, - ) => (await executeAction("unsettle", thread, undefined, restoreUnsettledAt)) === true; + ) => (await executeAction("unsettle", thread, undefined, undefined, restoreUnsettledAt)) === true; const pinThread = async (thread: EnvironmentThreadShell, restoreOrderKey?: string) => { if (!checkThreadOperationPermission(thread, m(msg("Could not pin thread")))) return false; if (!environmentConfigLoaded(thread.environmentId)) { @@ -763,7 +850,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; } } diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c9d43d96b3eb8..582fd4dc30d73 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2185,6 +2185,13 @@ "dcd7e72ead76533b": "Der Thread konnte nicht gelöscht werden.", "afb5eb54a2643091": "Der Thread konnte nicht erledigt werden.", "13b137607230126c": "Der Erledigt-Status des Threads konnte nicht aufgehoben werden.", + "67c90a9f94b73ef2": "Der Thread existiert nicht mehr", + "f83b638464f6a067": "„{title}“ ist nicht mehr auf dem Server vorhanden. Der Thread wurde wahrscheinlich auf einem anderen Gerät gelöscht, und diese Liste zeigt eine alte Kopie an.", + "65ca6ca43f7d2d66": "Behalten", + "f43211959325e616": "Aus Liste entfernen", + "68a1ffe66a9d3330": "Der Thread ist archiviert", + "6b578df5f3cd53f2": "„{title}“ ist archiviert und daher bereits aus deiner aktiven Liste entfernt. Hebe zuerst die Archivierung auf und versuche es dann erneut.", + "8e944f7583a727fd": "Wiederherstellen", "4280b0624ccaaf5f": "Thread konnte nicht archiviert werden", "2c9ce2503676e8f4": "Thread konnte nicht wiederhergestellt werden", "8284fdcae84900d1": "Thread konnte nicht erledigt werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 7a89a1cf37c22..4445ff5d60c29 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2185,6 +2185,13 @@ "dcd7e72ead76533b": "The thread could not be deleted.", "afb5eb54a2643091": "The thread could not be settled.", "13b137607230126c": "The thread could not be un-settled.", + "67c90a9f94b73ef2": "Thread no longer exists", + "f83b638464f6a067": "“{title}” is no longer on its server. It was probably deleted on another device, and this list is showing an old copy.", + "65ca6ca43f7d2d66": "Keep", + "f43211959325e616": "Remove from list", + "68a1ffe66a9d3330": "Thread is archived", + "6b578df5f3cd53f2": "“{title}” is archived, so it is already out of your active list. Unarchive it first, then try again.", + "8e944f7583a727fd": "Unarchive", "4280b0624ccaaf5f": "Could not archive thread", "2c9ce2503676e8f4": "Could not unarchive thread", "8284fdcae84900d1": "Could not settle thread", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 288dbfc7da2cf..6e93637133966 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2185,6 +2185,13 @@ "dcd7e72ead76533b": "No se pudo eliminar el hilo.", "afb5eb54a2643091": "No se pudo resolver el hilo.", "13b137607230126c": "No se pudo quitar el hilo de resueltos.", + "67c90a9f94b73ef2": "El hilo ya no existe", + "f83b638464f6a067": "«{title}» ya no está en su servidor. Probablemente se eliminó en otro dispositivo y esta lista muestra una copia antigua.", + "65ca6ca43f7d2d66": "Conservar", + "f43211959325e616": "Quitar de la lista", + "68a1ffe66a9d3330": "El hilo está archivado", + "6b578df5f3cd53f2": "«{title}» está archivado, por lo que ya no aparece en tu lista activa. Desarchívalo primero y vuelve a intentarlo.", + "8e944f7583a727fd": "Desarchivar", "4280b0624ccaaf5f": "No se pudo archivar el hilo", "2c9ce2503676e8f4": "No se pudo desarchivar el hilo", "8284fdcae84900d1": "No se pudo resolver el hilo", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 28ec2284fca74..454dd0e86b731 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2185,6 +2185,13 @@ "dcd7e72ead76533b": "Le fil n’a pas pu être supprimé.", "afb5eb54a2643091": "Le fil n’a pas pu être clos.", "13b137607230126c": "Le fil n’a pas pu être rouvert.", + "67c90a9f94b73ef2": "Le fil n’existe plus", + "f83b638464f6a067": "« {title} » n’est plus sur son serveur. Il a probablement été supprimé sur un autre appareil et cette liste affiche une ancienne copie.", + "65ca6ca43f7d2d66": "Conserver", + "f43211959325e616": "Retirer de la liste", + "68a1ffe66a9d3330": "Le fil est archivé", + "6b578df5f3cd53f2": "« {title} » est archivé et ne figure donc plus dans votre liste active. Désarchivez-le d’abord, puis réessayez.", + "8e944f7583a727fd": "Désarchiver", "4280b0624ccaaf5f": "Impossible d’archiver le fil", "2c9ce2503676e8f4": "Impossible de désarchiver le fil", "8284fdcae84900d1": "Impossible de clore le fil", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index f6741fdb8b775..ef0c587f3e22a 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2184,6 +2184,13 @@ "dcd7e72ead76533b": "スレッドを削除できませんでした。", "afb5eb54a2643091": "スレッドを対応済みにできませんでした。", "13b137607230126c": "スレッドの対応済みを解除できませんでした。", + "67c90a9f94b73ef2": "スレッドはもう存在しません", + "f83b638464f6a067": "「{title}」はサーバー上に存在しません。別のデバイスで削除された可能性があり、このリストには古いコピーが表示されています。", + "65ca6ca43f7d2d66": "保持", + "f43211959325e616": "リストから削除", + "68a1ffe66a9d3330": "スレッドはアーカイブされています", + "6b578df5f3cd53f2": "「{title}」はアーカイブされているため、アクティブなリストには表示されません。まずアーカイブを解除してから、もう一度お試しください。", + "8e944f7583a727fd": "アーカイブ解除", "4280b0624ccaaf5f": "スレッドをアーカイブできませんでした", "2c9ce2503676e8f4": "スレッドのアーカイブを解除できませんでした", "8284fdcae84900d1": "スレッドを対応済みにできませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index b1ef20ba0f347..fc8102bf9cd3f 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2186,6 +2186,13 @@ "dcd7e72ead76533b": "스레드를 삭제할 수 없습니다.", "afb5eb54a2643091": "스레드를 정리할 수 없습니다.", "13b137607230126c": "스레드 정리를 취소할 수 없습니다.", + "67c90a9f94b73ef2": "스레드가 더 이상 존재하지 않습니다", + "f83b638464f6a067": "“{title}”이(가) 더 이상 서버에 없습니다. 다른 기기에서 삭제되었을 수 있으며, 이 목록에는 이전 사본이 표시되고 있습니다.", + "65ca6ca43f7d2d66": "유지", + "f43211959325e616": "목록에서 제거", + "68a1ffe66a9d3330": "스레드가 보관되었습니다", + "6b578df5f3cd53f2": "“{title}”이(가) 보관되어 이미 활성 목록에서 제외되었습니다. 먼저 보관을 해제한 후 다시 시도하세요.", + "8e944f7583a727fd": "보관 해제", "4280b0624ccaaf5f": "스레드를 보관할 수 없습니다", "2c9ce2503676e8f4": "스레드 보관을 해제할 수 없습니다", "8284fdcae84900d1": "스레드를 정리할 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index b40494fca3885..e90a5721a4825 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2185,6 +2185,13 @@ "dcd7e72ead76533b": "Não foi possível excluir a thread.", "afb5eb54a2643091": "Não foi possível concluir a thread.", "13b137607230126c": "Não foi possível reabrir a thread.", + "67c90a9f94b73ef2": "A thread não existe mais", + "f83b638464f6a067": "“{title}” não está mais no servidor. Ela provavelmente foi excluída em outro dispositivo, e esta lista está mostrando uma cópia antiga.", + "65ca6ca43f7d2d66": "Manter", + "f43211959325e616": "Remover da lista", + "68a1ffe66a9d3330": "A thread está arquivada", + "6b578df5f3cd53f2": "“{title}” está arquivada, então já está fora da sua lista ativa. Desarquive-a primeiro e tente novamente.", + "8e944f7583a727fd": "Desarquivar", "4280b0624ccaaf5f": "Não foi possível arquivar a thread", "2c9ce2503676e8f4": "Não foi possível desarquivar a thread", "8284fdcae84900d1": "Não foi possível concluir a thread", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index cadf07e57eda9..2be7bdf435861 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2233,6 +2233,13 @@ "dcd7e72ead76533b": "Не удалось удалить тред.", "afb5eb54a2643091": "Не удалось отметить тред разобранным.", "13b137607230126c": "Не удалось вернуть тред из разобранных.", + "67c90a9f94b73ef2": "Тред больше не существует", + "f83b638464f6a067": "«{title}» больше нет на сервере. Вероятно, тред был удалён на другом устройстве, а в этом списке отображается старая копия.", + "65ca6ca43f7d2d66": "Оставить", + "f43211959325e616": "Убрать из списка", + "68a1ffe66a9d3330": "Тред в архиве", + "6b578df5f3cd53f2": "«{title}» находится в архиве и уже не отображается в списке активных тредов. Сначала разархивируйте его, затем повторите попытку.", + "8e944f7583a727fd": "Разархивировать", "4280b0624ccaaf5f": "Не удалось архивировать тред", "2c9ce2503676e8f4": "Не удалось разархивировать тред", "8284fdcae84900d1": "Не удалось отметить тред разобранным", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 3a0273aef36fd..9290d21afb5e3 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2185,6 +2185,13 @@ "dcd7e72ead76533b": "Tråden kunde inte tas bort.", "afb5eb54a2643091": "Tråden kunde inte markeras som klar.", "13b137607230126c": "Tråden kunde inte markeras som ej klar.", + "67c90a9f94b73ef2": "Tråden finns inte längre", + "f83b638464f6a067": "”{title}” finns inte längre på servern. Den har förmodligen tagits bort på en annan enhet, och den här listan visar en gammal kopia.", + "65ca6ca43f7d2d66": "Behåll", + "f43211959325e616": "Ta bort från listan", + "68a1ffe66a9d3330": "Tråden är arkiverad", + "6b578df5f3cd53f2": "”{title}” är arkiverad och finns därför inte längre i din aktiva lista. Avarkivera den först och försök sedan igen.", + "8e944f7583a727fd": "Avarkivera", "4280b0624ccaaf5f": "Kunde inte arkivera tråden", "2c9ce2503676e8f4": "Kunde inte avarkivera tråden", "8284fdcae84900d1": "Kunde inte markera tråden som klar", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f1c394c60c606..0e7ed99fdb359 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2188,6 +2188,13 @@ "dcd7e72ead76533b": "无法删除该会话。", "afb5eb54a2643091": "无法收尾该会话。", "13b137607230126c": "无法取消收尾该会话。", + "67c90a9f94b73ef2": "会话已不存在", + "f83b638464f6a067": "“{title}”已不在其服务器上。它可能已在另一台设备上被删除,而此列表显示的是旧副本。", + "65ca6ca43f7d2d66": "保留", + "f43211959325e616": "从列表中移除", + "68a1ffe66a9d3330": "会话已归档", + "6b578df5f3cd53f2": "“{title}”已归档,因此已不在你的活动列表中。请先取消归档,然后重试。", + "8e944f7583a727fd": "取消归档", "4280b0624ccaaf5f": "无法归档会话", "2c9ce2503676e8f4": "无法取消归档会话", "8284fdcae84900d1": "无法收尾会话", 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.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 bf2013aef5398..beac88cade9b5 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, @@ -61,7 +62,10 @@ const steadyShells = createSteadyShellAtoms({ export const steadyShellsHoldingAtom = steadyShells.holdingAtom; export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, - snapshotAtom: steadyShells.snapshotAtom, + // 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; export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({