Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions apps/mobile/src/features/home/threadActionFailure.test.ts
Original file line number Diff line number Diff line change
@@ -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 });
});
});
40 changes: 40 additions & 0 deletions apps/mobile/src/features/home/threadActionFailure.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>): 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 };
}
163 changes: 158 additions & 5 deletions apps/mobile/src/features/home/useThreadListActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -44,17 +47,17 @@ 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", () => ({
impactAsync: async () => {},
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", () => ({
Expand All @@ -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",
}));
Expand Down Expand Up @@ -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);
},
Expand All @@ -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");
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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,
Expand Down Expand Up @@ -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<void>();
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<void>((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<void>((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({
Expand Down
Loading
Loading