Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(mobile): preserve drafts after storage read failures (#213)

Leo5b59149ebf39
diff --git a/apps/mobile/src/state/thread-outbox-manager.ts b/apps/mobile/src/state/thread-outbox-manager.ts
index f6a20ccff..60d20bdb3 100644
--- a/apps/mobile/src/state/thread-outbox-manager.ts
+++ b/apps/mobile/src/state/thread-outbox-manager.ts
@@ -7,7 +7,7 @@ import {
groupQueuedThreadMessages,
type QueuedThreadMessage,
} from "./thread-outbox-model";
-import type { ThreadOutboxStorage } from "./thread-outbox-storage";
+import type { ThreadOutboxLoadResult, ThreadOutboxStorage } from "./thread-outbox-storage";
export class ThreadOutboxManagerError extends Schema.TaggedErrorClass<ThreadOutboxManagerError>()(
"ThreadOutboxManagerError",
@@ -46,7 +46,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
((message: string, error: unknown) => {
console.warn(message, error);
});
- let loadPromise: Promise<void> | null = null;
+ let loadPromise: Promise<boolean> | null = null;
let mutationQueue: Promise<void> = Promise.resolve();
const serialize = <A>(mutation: () => Promise<A>): Promise<A> => {
@@ -58,6 +58,28 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
return result;
};
+ const reportUnreadOutboxRecords = (persisted: ThreadOutboxLoadResult): void => {
+ for (const unread of persisted.unreadRecords) {
+ warn("[thread-outbox] left unreadable persisted message on disk", unread);
+ }
+ };
+
+ const requireCompleteOutboxLoad = (
+ persisted: ThreadOutboxLoadResult,
+ environmentId: EnvironmentId,
+ ): ReadonlyArray<QueuedThreadMessage> => {
+ if (persisted.unreadRecords.length > 0) {
+ throw new ThreadOutboxManagerError({
+ operation: "clear-environment-load",
+ environmentId,
+ threadId: null,
+ messageId: null,
+ cause: persisted.unreadRecords,
+ });
+ }
+ return persisted.messages;
+ };
+
const currentMessages = (): ReadonlyArray<QueuedThreadMessage> =>
flattenQueuedThreadMessages(options.registry.get(queuedMessagesByThreadKeyAtom));
@@ -65,13 +87,21 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
options.registry.set(queuedMessagesByThreadKeyAtom, groupQueuedThreadMessages(messages));
};
- const load = (): Promise<void> => {
+ const load = (): Promise<boolean> => {
if (loadPromise !== null) {
return loadPromise;
}
loadPromise = serialize(async () => {
- const persistedMessages = await options.storage.load();
- setMessages([...persistedMessages, ...currentMessages()]);
+ const persisted = await options.storage.load();
+ reportUnreadOutboxRecords(persisted);
+ setMessages([...persisted.messages, ...currentMessages()]);
+ // A mixed load is not complete. Drop the cache so a later load, such as
+ // drain after reconnect, can hydrate a file that becomes readable.
+ if (persisted.unreadRecords.length > 0) {
+ loadPromise = null;
+ return false;
+ }
+ return true;
}).catch((cause) => {
loadPromise = null;
warn(
@@ -84,6 +114,7 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
cause,
}),
);
+ return false;
});
return loadPromise;
};
@@ -173,20 +204,17 @@ export function createThreadOutboxManager(options: ThreadOutboxManagerOptions) {
const clearEnvironment = (environmentId: EnvironmentId): Promise<void> =>
serialize(async () => {
const persisted = await options.storage.load().catch((cause) => {
- warn(
- "[thread-outbox] failed to load messages while clearing environment",
- new ThreadOutboxManagerError({
- operation: "clear-environment-load",
- environmentId,
- threadId: null,
- messageId: null,
- cause,
- }),
- );
- return [];
+ throw new ThreadOutboxManagerError({
+ operation: "clear-environment-load",
+ environmentId,
+ threadId: null,
+ messageId: null,
+ cause,
+ });
});
+ const readable = requireCompleteOutboxLoad(persisted, environmentId);
const allMessages = flattenQueuedThreadMessages(
- groupQueuedThreadMessages([...persisted, ...currentMessages()]),
+ groupQueuedThreadMessages([...readable, ...currentMessages()]),
);
const removedMessageIds = new Set<MessageId>();
diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts
index eede50697..952a470a2 100644
--- a/apps/mobile/src/state/thread-outbox-model.ts
+++ b/apps/mobile/src/state/thread-outbox-model.ts
@@ -196,18 +196,40 @@ function errorMessage(error: unknown): string | null {
return typeof error === "string" ? error : null;
}
+/**
+ * Only a failure the server actually decided (`OrchestrationDispatchCommandError`,
+ * or an authorization rejection) means the payload itself is bad. The other
+ * typed failures a queued send can hit are transport-shaped: a socket that
+ * dropped mid-request (`RpcClientError` wrapping a Socket read/write/close
+ * reason), or an environment that is not connected or not registered. Those
+ * are matched by tag, not by message text, because a `SocketReadError` message
+ * is just "An error occurred during Read". A wrong answer here restores the
+ * pending task into a draft and it disappears from the list.
+ */
export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
- if (
- typeof error === "object" &&
- error !== null &&
- "_tag" in error &&
- error._tag === "ConnectionTransientError"
- ) {
- return true;
+ if (typeof error === "object" && error !== null && "_tag" in error) {
+ switch (error._tag) {
+ case "OrchestrationDispatchCommandError":
+ case "EnvironmentAuthorizationError":
+ return false;
+ case "ConnectionTransientError":
+ case "RpcClientError":
+ case "EnvironmentRpcUnavailableError":
+ case "EnvironmentNotRegisteredError":
+ return true;
+ default:
+ break;
+ }
}
return isTransportConnectionErrorMessage(errorMessage(error));
}
+const THREAD_OUTBOX_HYDRATION_RETRY_DELAYS_MS = [250, 1_000, 4_000] as const;
+
+export function threadOutboxHydrationRetryDelayMs(attempt: number): number | null {
+ return THREAD_OUTBOX_HYDRATION_RETRY_DELAYS_MS[attempt] ?? null;
+}
+
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
export type ThreadOutboxFailureAction = "retry" | "discard";
diff --git a/apps/mobile/src/state/thread-outbox-storage.ts b/apps/mobile/src/state/thread-outbox-storage.ts
index ab0853f7d..9e39f647d 100644
--- a/apps/mobile/src/state/thread-outbox-storage.ts
+++ b/apps/mobile/src/state/thread-outbox-storage.ts
@@ -44,12 +44,21 @@ export class ThreadOutboxStorageError extends Schema.TaggedErrorClass<ThreadOutb
}
}
+export interface ThreadOutboxLoadResult {
+ readonly messages: ReadonlyArray<QueuedThreadMessage>;
+ readonly unreadRecords: ReadonlyArray<ThreadOutboxStorageError>;
+}
+
export interface ThreadOutboxStorage {
- readonly load: () => Promise<ReadonlyArray<QueuedThreadMessage>>;
+ readonly load: () => Promise<ThreadOutboxLoadResult>;
readonly write: (message: QueuedThreadMessage) => Promise<void>;
readonly remove: (message: QueuedThreadMessage) => Promise<void>;
}
+export function emptyThreadOutboxLoadResult(): ThreadOutboxLoadResult {
+ return { messages: [], unreadRecords: [] };
+}
+
function messageFileName(messageId: MessageId): string {
return `${encodeURIComponent(messageId)}.json`;
}
@@ -69,6 +78,7 @@ async function getMessageFile(messageId: MessageId) {
export const expoThreadOutboxStorage: ThreadOutboxStorage = {
load: async () => {
const messages: QueuedThreadMessage[] = [];
+ const unreadRecords: ThreadOutboxStorageError[] = [];
try {
const { File } = await import("expo-file-system");
const directory = await getOutboxDirectory();
@@ -80,8 +90,9 @@ export const expoThreadOutboxStorage: ThreadOutboxStorage = {
try {
messages.push(decodeQueuedThreadMessage(JSON.parse(await entry.text()) as unknown));
} catch (cause) {
- console.warn(
- "[thread-outbox] ignored invalid persisted message",
+ // Leave the file on disk. Cleanup must see that ownership is
+ // incomplete, while delivery can still hydrate readable messages.
+ unreadRecords.push(
new ThreadOutboxStorageError({
operation: "read-message",
environmentId: null,
@@ -103,7 +114,7 @@ export const expoThreadOutboxStorage: ThreadOutboxStorage = {
cause,
});
}
- return messages;
+ return { messages, unreadRecords };
},
write: async (message) => {
const fileName = messageFileName(message.messageId);
diff --git a/apps/mobile/src/state/thread-outbox.test.ts b/apps/mobile/src/state/thread-outbox.test.ts
index b12ad2dc5..a8f12443c 100644
--- a/apps/mobile/src/state/thread-outbox.test.ts
+++ b/apps/mobile/src/state/thread-outbox.test.ts
@@ -1,17 +1,53 @@
import { describe, expect, it } from "@effect/vitest";
+import { EnvironmentNotRegisteredError } from "@t3tools/client-runtime/connection";
+import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
+import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";
import {
CommandId,
+ EnvironmentAuthorizationError,
EnvironmentId,
MessageId,
+ OrchestrationDispatchCommandError,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
+import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
+import * as Socket from "effect/unstable/socket/Socket";
+import { onTestFinished, vi } from "vite-plus/test";
+
+const outboxFiles = vi.hoisted(() => new Map<string, string | Error>());
+
+vi.mock("expo-file-system", () => {
+ class File {
+ constructor(readonly name: string) {}
+
+ async text(): Promise<string> {
+ const contents = outboxFiles.get(this.name);
+ if (contents instanceof Error) throw contents;
+ if (contents === undefined) throw new Error("Missing file");
+ return contents;
+ }
+ }
+
+ return {
+ File,
+ Directory: class {
+ create() {}
+
+ list() {
+ return Array.from(outboxFiles.keys(), (name) => new File(name));
+ }
+ },
+ Paths: { document: "/documents" },
+ };
+});
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
+ flattenQueuedThreadMessages,
groupQueuedThreadMessages,
isQueuedThreadCreationSendable,
modelSelectionsEqual,
@@ -19,11 +55,17 @@ import {
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
+ threadOutboxHydrationRetryDelayMs,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
} from "./thread-outbox-model";
import { createThreadOutboxManager, ThreadOutboxManagerError } from "./thread-outbox-manager";
-import type { ThreadOutboxStorage } from "./thread-outbox-storage";
+import {
+ emptyThreadOutboxLoadResult,
+ expoThreadOutboxStorage,
+ ThreadOutboxStorageError,
+ type ThreadOutboxStorage,
+} from "./thread-outbox-storage";
function queuedMessage(input: {
readonly environmentId?: string;
@@ -43,6 +85,258 @@ function queuedMessage(input: {
}
describe("thread outbox", () => {
+ it.each(["read", "json", "schema"] as const)(
+ "hydrates valid queued messages after a record %s failure and keeps the unread file",
+ async (failure) => {
+ onTestFinished(() => outboxFiles.clear());
+ const first = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+ const second = queuedMessage({
+ messageId: "message-2",
+ createdAt: "2026-06-08T10:00:02.000Z",
+ });
+ const corruptContents =
+ failure === "read"
+ ? new Error("storage unavailable")
+ : failure === "json"
+ ? "{"
+ : JSON.stringify({ ...second, schemaVersion: 999 });
+ outboxFiles.set("message-1.json", JSON.stringify(encodeQueuedThreadMessage(first)));
+ outboxFiles.set("message-2.json", corruptContents);
+
+ const loaded = await expoThreadOutboxStorage.load();
+ expect(loaded.messages).toEqual([first]);
+ expect(loaded.unreadRecords).toMatchObject([
+ { operation: "read-message", fileName: "message-2.json" },
+ ]);
+ expect(outboxFiles.get("message-2.json")).toBe(corruptContents);
+
+ outboxFiles.set("message-2.json", JSON.stringify(encodeQueuedThreadMessage(second)));
+ await expect(expoThreadOutboxStorage.load()).resolves.toEqual({
+ messages: [first, second],
+ unreadRecords: [],
+ });
+ },
+ );
+
+ it("publishes readable queued messages while reporting unread records", async () => {
+ const registry = AtomRegistry.make();
+ onTestFinished(() => registry.dispose());
+ const readable = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+ const unread = new ThreadOutboxStorageError({
+ operation: "read-message",
+ environmentId: null,
+ threadId: null,
+ messageId: null,
+ fileName: "message-2.json",
+ cause: new Error("storage unavailable"),
+ });
+ const warnings: Array<{ message: string; error: unknown }> = [];
+ const manager = createThreadOutboxManager({
+ registry,
+ warn: (message, error) => warnings.push({ message, error }),
+ storage: {
+ load: async () => ({ messages: [readable], unreadRecords: [unread] }),
+ write: async () => undefined,
+ remove: async () => undefined,
+ },
+ });
+
+ await expect(manager.load()).resolves.toBe(false);
+
+ expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
+ "environment-1:thread-1": [readable],
+ });
+ expect(warnings).toEqual([
+ { message: "[thread-outbox] left unreadable persisted message on disk", error: unread },
+ ]);
+ });
+
+ it("retries a mixed load so a later-readable record can join the drain queue", async () => {
+ const registry = AtomRegistry.make();
+ onTestFinished(() => registry.dispose());
+ const first = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+ const second = queuedMessage({
+ messageId: "message-2",
+ createdAt: "2026-06-08T10:00:02.000Z",
+ });
+ const unread = new ThreadOutboxStorageError({
+ operation: "read-message",
+ environmentId: null,
+ threadId: null,
+ messageId: null,
+ fileName: "message-2.json",
+ cause: new Error("{"),
+ });
+ let loadCalls = 0;
+ const manager = createThreadOutboxManager({
+ registry,
+ warn: () => {},
+ storage: {
+ load: async () => {
+ loadCalls += 1;
+ if (loadCalls === 1) {
+ return { messages: [first], unreadRecords: [unread] };
+ }
+ return { messages: [first, second], unreadRecords: [] };
+ },
+ write: async () => undefined,
+ remove: async () => undefined,
+ },
+ });
+
+ await expect(manager.load()).resolves.toBe(false);
+ expect(
+ flattenQueuedThreadMessages(registry.get(manager.queuedMessagesByThreadKeyAtom)),
+ ).toEqual([first]);
+ expect(loadCalls).toBe(1);
+
+ await expect(manager.load()).resolves.toBe(true);
+ expect(loadCalls).toBe(2);
+ expect(
+ flattenQueuedThreadMessages(registry.get(manager.queuedMessagesByThreadKeyAtom)),
+ ).toEqual([first, second]);
+
+ await expect(manager.load()).resolves.toBe(true);
+ expect(loadCalls).toBe(2);
+ });
+
+ it("makes a readable pending task visible to drain after a mixed valid/corrupt load", async () => {
+ onTestFinished(() => outboxFiles.clear());
+ const registry = AtomRegistry.make();
+ onTestFinished(() => registry.dispose());
+ const pendingTask = {
+ ...queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ }),
+ text: "Retry the upload worker",
+ creation: {
+ projectId: ProjectId.make("project-1"),
+ workspaceMode: "local" as const,
+ branch: null,
+ worktreePath: null,
+ },
+ };
+ outboxFiles.set("message-1.json", JSON.stringify(encodeQueuedThreadMessage(pendingTask)));
+ outboxFiles.set("message-2.json", "{");
+
+ const manager = createThreadOutboxManager({
+ registry,
+ warn: () => {},
+ storage: expoThreadOutboxStorage,
+ });
+ await manager.load();
+
+ const visible = flattenQueuedThreadMessages(
+ registry.get(manager.queuedMessagesByThreadKeyAtom),
+ );
+ expect(visible).toEqual([pendingTask]);
+ expect(
+ resolveThreadOutboxDeliveryAction({
+ isCreation: true,
+ threadExists: false,
+ shellStatus: "live",
+ environmentConnected: true,
+ threadBusy: false,
+ }),
+ ).toBe("send");
+ expect(outboxFiles.get("message-2.json")).toBe("{");
+ expect(outboxFiles.has("message-1.json")).toBe(true);
+
+ await expect(manager.clearEnvironment(pendingTask.environmentId)).rejects.toMatchObject({
+ operation: "clear-environment-load",
+ });
+ expect(outboxFiles.get("message-2.json")).toBe("{");
+ expect(JSON.parse(outboxFiles.get("message-1.json") as string)).toMatchObject({
+ messageId: pendingTask.messageId,
+ text: pendingTask.text,
+ });
+ });
+
+ it("preserves queued messages when environment cleanup cannot read the outbox", async () => {
+ const registry = AtomRegistry.make();
+ onTestFinished(() => registry.dispose());
+ const message = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+ const stored = new Map<MessageId, QueuedThreadMessage>();
+ const manager = createThreadOutboxManager({
+ registry,
+ warn: () => {},
+ storage: {
+ load: async () => {
+ throw new Error("storage unavailable");
+ },
+ write: async (entry) => {
+ stored.set(entry.messageId, entry);
+ },
+ remove: async (entry) => {
+ stored.delete(entry.messageId);
+ },
+ },
+ });
+ await manager.enqueue(message);
+
+ await expect(manager.clearEnvironment(message.environmentId)).rejects.toMatchObject({
+ operation: "clear-environment-load",
+ });
+ expect([...stored.values()]).toEqual([message]);
+ expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
+ "environment-1:thread-1": [message],
+ });
+ });
+
+ it("preserves queued messages when environment cleanup sees an unread outbox record", async () => {
+ const registry = AtomRegistry.make();
+ onTestFinished(() => registry.dispose());
+ const message = queuedMessage({
+ messageId: "message-1",
+ createdAt: "2026-06-08T10:00:01.000Z",
+ });
+ const unread = new ThreadOutboxStorageError({
+ operation: "read-message",
+ environmentId: null,
+ threadId: null,
+ messageId: null,
+ fileName: "message-2.json",
+ cause: new Error("{"),
+ });
+ const stored = new Map<MessageId, QueuedThreadMessage>();
+ const manager = createThreadOutboxManager({
+ registry,
+ warn: () => {},
+ storage: {
+ load: async () => ({ messages: [message], unreadRecords: [unread] }),
+ write: async (entry) => {
+ stored.set(entry.messageId, entry);
+ },
+ remove: async (entry) => {
+ stored.delete(entry.messageId);
+ },
+ },
+ });
+ await manager.enqueue(message);
+
+ await expect(manager.clearEnvironment(message.environmentId)).rejects.toMatchObject({
+ operation: "clear-environment-load",
+ cause: [unread],
+ });
+ expect([...stored.values()]).toEqual([message]);
+ expect(registry.get(manager.queuedMessagesByThreadKeyAtom)).toEqual({
+ "environment-1:thread-1": [message],
+ });
+ });
+
it("groups messages by scoped thread and preserves creation order", () => {
const later = queuedMessage({
messageId: "message-2",
@@ -137,7 +431,7 @@ describe("thread outbox", () => {
const manager = createThreadOutboxManager({
registry,
storage: {
- load: async () => [],
+ load: async () => emptyThreadOutboxLoadResult(),
write: async () => undefined,
remove: async () => undefined,
},
@@ -184,7 +478,7 @@ describe("thread outbox", () => {
if (loadCalls === 1) {
await initialLoadBlocked;
}
- return [...stored.values()];
+ return { messages: [...stored.values()], unreadRecords: [] };
},
write: async () => undefined,
remove: async (candidate) => {
@@ -220,7 +514,7 @@ describe("thread outbox", () => {
load: async () => {
loadCalls += 1;
if (loadCalls === 1) throw loadCause;
- return [];
+ return emptyThreadOutboxLoadResult();
},
write: async () => undefined,
remove: async () => undefined,
@@ -253,7 +547,7 @@ describe("thread outbox", () => {
const removalCause = new Error("remove failed");
let failRemoval = true;
const storage: ThreadOutboxStorage = {
- load: async () => [...stored.values()],
+ load: async () => ({ messages: [...stored.values()], unreadRecords: [] }),
write: async (message) => {
stored.set(message.messageId, message);
},
@@ -303,7 +597,7 @@ describe("thread outbox", () => {
const manager = createThreadOutboxManager({
registry,
storage: {
- load: async () => [],
+ load: async () => emptyThreadOutboxLoadResult(),
write: async () => writeBlocked,
remove: async () => undefined,
},
@@ -332,7 +626,7 @@ describe("thread outbox", () => {
const manager = createThreadOutboxManager({
registry,
storage: {
- load: async () => [],
+ load: async () => emptyThreadOutboxLoadResult(),
write: async () => {
throw writeCause;
},
@@ -367,7 +661,7 @@ describe("thread outbox", () => {
const manager = createThreadOutboxManager({
registry,
storage: {
- load: async () => [],
+ load: async () => emptyThreadOutboxLoadResult(),
write: async () => {
if (failNextWrite) {
failNextWrite = false;
@@ -404,7 +698,7 @@ describe("thread outbox", () => {
const manager = createThreadOutboxManager({
registry,
storage: {
- load: async () => [],
+ load: async () => emptyThreadOutboxLoadResult(),
write: async () => undefined,
remove: async () => undefined,
},
@@ -428,7 +722,7 @@ describe("thread outbox", () => {
const registry = AtomRegistry.make();
const stored = new Map<MessageId, QueuedThreadMessage>();
const storage: ThreadOutboxStorage = {
- load: async () => [...stored.values()],
+ load: async () => ({ messages: [...stored.values()], unreadRecords: [] }),
write: async (message) => {
stored.set(message.messageId, message);
},
@@ -600,6 +894,66 @@ describe("thread outbox", () => {
}),
).toBe(true);
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
+ expect(
+ shouldRetryThreadOutboxDelivery(
+ new OrchestrationDispatchCommandError({ message: "Thread no longer exists" }),
+ ),
+ ).toBe(false);
+ expect(
+ shouldRetryThreadOutboxDelivery(
+ new EnvironmentAuthorizationError({
+ message: "Missing scope",
+ requiredScope: "orchestration:operate",
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("bounds incomplete outbox hydration retries", () => {
+ expect([0, 1, 2, 3].map(threadOutboxHydrationRetryDelayMs)).toEqual([250, 1_000, 4_000, null]);
+ });
+
+ // A pending task created offline drains the moment the phone reconnects,
+ // which is exactly when the socket is most likely to drop again. Every way a
+ // request can fail in flight must retry; a restore turns the pending task
+ // into a draft and it disappears from the list.
+ it("retries every in-flight transport failure by tag, not by message text", () => {
+ const socketReasons = [
+ new Socket.SocketReadError({ cause: new Error("The network connection was lost.") }),
+ new Socket.SocketWriteError({ cause: new Error("Broken pipe") }),
+ new Socket.SocketCloseError({ code: 1006 }),
+ new Socket.SocketOpenError({ kind: "Timeout", cause: new Error("timeout") }),
+ ];
+ for (const reason of socketReasons) {
+ const error = new RpcClientError.RpcClientError({ reason });
+ expect(isTransportConnectionErrorMessage(error.message)).toBe(
+ reason._tag === "SocketCloseError" || reason._tag === "SocketOpenError",
+ );
+ expect(shouldRetryThreadOutboxDelivery(error)).toBe(true);
+ }
+ expect(
+ shouldRetryThreadOutboxDelivery(
+ new RpcClientError.RpcClientError({
+ reason: new RpcClientError.RpcClientDefect({
+ message: "Error decoding message",
+ cause: new Error("Unexpected end of JSON input"),
+ }),
+ }),
+ ),
+ ).toBe(true);
+ expect(
+ shouldRetryThreadOutboxDelivery(
+ new EnvironmentRpcUnavailableError({
+ environmentId: "environment-1",
+ message: "Home is not connected.",
+ }),
+ ),
+ ).toBe(true);
+ expect(
+ shouldRetryThreadOutboxDelivery(
+ new EnvironmentNotRegisteredError({ environmentId: EnvironmentId.make("environment-1") }),
+ ),
+ ).toBe(true);
});
it("retains queued messages when settings synchronization fails before startTurn", () => {
diff --git a/apps/mobile/src/state/thread-outbox.ts b/apps/mobile/src/state/thread-outbox.ts
index 1de1f8da6..c0b41e459 100644
--- a/apps/mobile/src/state/thread-outbox.ts
+++ b/apps/mobile/src/state/thread-outbox.ts
@@ -23,8 +23,8 @@ export async function flushThreadOutbox(): Promise<void> {
await flushThreadOutboxWrites();
}
-export function ensureThreadOutboxLoaded(): void {
- void threadOutboxManager.load();
+export function ensureThreadOutboxLoaded(): Promise<boolean> {
+ return threadOutboxManager.load();
}
export function enqueueThreadOutboxMessage(message: QueuedThreadMessage): Promise<void> {
diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts
index 8dbddfe1f..fd5c408a2 100644
--- a/apps/mobile/src/state/use-composer-drafts.test.ts
+++ b/apps/mobile/src/state/use-composer-drafts.test.ts
@@ -3,7 +3,8 @@ import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { vi } from "vite-plus/test";
const composerDraftFileMocks = vi.hoisted(() => {
- let document = "";
+ let document = JSON.stringify({ schemaVersion: 1, drafts: {} });
+ let readError: Error | null = null;
let writeError: Error | null = null;
let releaseRead: (() => void) | null = null;
let readBarrier = Promise.resolve();
@@ -24,6 +25,9 @@ const composerDraftFileMocks = vi.hoisted(() => {
setDocument(value: unknown) {
document = JSON.stringify(value);
},
+ setReadError(error: Error | null) {
+ readError = error;
+ },
setWriteError(error: Error | null) {
writeError = error;
},
@@ -40,6 +44,7 @@ const composerDraftFileMocks = vi.hoisted(() => {
async text() {
await readBarrier;
+ if (readError) throw readError;
return document;
}
@@ -72,6 +77,7 @@ import {
getComposerDraftSnapshot,
mergeComposerDraftContentState,
removeComposerDraftsForEnvironment,
+ resetComposerDraftsLoadState,
restoreComposerDraftSnapshotState,
setComposerDraftText,
} from "./use-composer-drafts";
@@ -82,6 +88,11 @@ const DRAFT: ComposerDraft = {
};
afterEach(() => {
+ vi.useRealTimers();
+ resetComposerDraftsLoadState();
+ composerDraftFileMocks.setDocument({ schemaVersion: 1, drafts: {} });
+ composerDraftFileMocks.setReadError(null);
+ composerDraftFileMocks.setWriteError(null);
appAtomRegistry.set(composerDraftsAtom, {});
});
@@ -421,6 +432,24 @@ describe("mobile composer drafts", () => {
});
});
+ it("waits for an edit queued behind the flush drain sentinel", async () => {
+ vi.useFakeTimers();
+ const draftKey = "environment-1:thread-1";
+ await flushComposerDrafts();
+
+ setComposerDraftText(draftKey, "first edit");
+ vi.advanceTimersByTime(200);
+ const flushing = flushComposerDrafts();
+
+ setComposerDraftText(draftKey, "latest edit");
+ vi.advanceTimersByTime(200);
+ await flushing;
+
+ expect(JSON.parse(composerDraftFileMocks.getDocument())).toMatchObject({
+ drafts: { [draftKey]: { text: "latest edit" } },
+ });
+ });
+
it("propagates a flush write failure instead of resolving as saved", async () => {
const draftKey = "environment-1:thread-1";
setComposerDraftText(draftKey, "unsaved");
@@ -432,4 +461,45 @@ describe("mobile composer drafts", () => {
composerDraftFileMocks.setWriteError(null);
}
});
+
+ it.each(["read", "decode"] as const)(
+ "preserves saved drafts when the draft %s fails",
+ async (failure) => {
+ vi.useFakeTimers();
+ composerDraftFileMocks.setDocument({
+ schemaVersion: failure === "decode" ? 999 : 1,
+ drafts: { "environment-1:saved": DRAFT },
+ });
+ const original = composerDraftFileMocks.getDocument();
+ if (failure === "read") {
+ composerDraftFileMocks.setReadError(new Error("storage unavailable"));
+ }
+
+ setComposerDraftText("environment-1:new", "Keep my new edits too");
+ await expect(flushComposerDrafts()).rejects.toMatchObject({ operation: failure });
+
+ expect(composerDraftFileMocks.getDocument()).toBe(original);
+ },
+ );
+
+ it("retries a failed debounced read on final flush without dropping saved drafts or new edits", async () => {
+ vi.useFakeTimers();
+ composerDraftFileMocks.setDocument({
+ schemaVersion: 1,
+ drafts: { "environment-1:saved": DRAFT },
+ });
+ const original = composerDraftFileMocks.getDocument();
+ composerDraftFileMocks.setReadError(new Error("storage unavailable"));
+ setComposerDraftText("environment-1:new", "New edits");
+ await vi.advanceTimersByTimeAsync(200);
+ expect(composerDraftFileMocks.getDocument()).toBe(original);
+
+ composerDraftFileMocks.setReadError(null);
+ await flushComposerDrafts();
+
+ expect(JSON.parse(composerDraftFileMocks.getDocument()).drafts).toEqual({
+ "environment-1:saved": DRAFT,
+ "environment-1:new": { text: "New edits", attachments: [] },
+ });
+ });
});
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index 7dbea2359..3991cc873 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -104,8 +104,21 @@ export const composerDraftsAtom = Atom.make<Record<string, ComposerDraft>>({}).p
let loadPromise: Promise<void> | null = null;
let persistTimer: ReturnType<typeof setTimeout> | null = null;
+let persistRetryNeeded = false;
+let persistRevision = 0;
const persistenceQueue = new SerializedAsyncQueue();
+/** Resets module-level state between test runs. */
+export function resetComposerDraftsLoadState(): void {
+ loadPromise = null;
+ persistRetryNeeded = false;
+ persistRevision = 0;
+ if (persistTimer !== null) {
+ clearTimeout(persistTimer);
+ persistTimer = null;
+ }
+}
+
function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
if (!draft) {
return EMPTY_DRAFT;
@@ -162,16 +175,12 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
operation = "decode";
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
} catch (cause) {
- console.warn(
- "[composer-drafts] ignored persisted draft failure",
- new ComposerDraftPersistenceError({
- operation,
- directory: COMPOSER_DRAFTS_DIRECTORY,
- fileName: COMPOSER_DRAFTS_FILE,
- cause,
- }),
- );
- return {};
+ throw new ComposerDraftPersistenceError({
+ operation,
+ directory: COMPOSER_DRAFTS_DIRECTORY,
+ fileName: COMPOSER_DRAFTS_FILE,
+ cause,
+ });
}
}
@@ -200,42 +209,69 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
}
}
-async function savePersistedComposerDrafts(drafts: Record<string, ComposerDraft>): Promise<void> {
- try {
- await persistenceQueue.run(() => writePersistedComposerDrafts(drafts));
- } catch (error) {
- console.warn("[composer-drafts] failed to persist drafts", error);
- // Draft persistence is best-effort; in-memory drafts still keep working.
- }
-}
-
/**
* Lands any debounced or in-flight draft write before the JS runtime is torn
* down (app update restart), so the freshest draft state survives it. A write
* failure propagates so the caller can decide whether the restart may proceed.
*/
export async function flushComposerDrafts(): Promise<void> {
+ // Never land a pre-hydration snapshot: persisted state must merge into the
+ // atoms first, or this write would clobber disk with partial data.
+ ensureComposerDraftsLoaded();
+ if (loadPromise !== null) {
+ await loadPromise;
+ }
// An edit during an awaited write schedules another debounced write, so
// keep landing snapshots until no debounce is pending after a queue drain.
- do {
- while (persistTimer !== null) {
- clearTimeout(persistTimer);
+ for (;;) {
+ const revisionToFlush = persistRevision;
+ while (persistTimer !== null || persistRetryNeeded) {
+ if (persistTimer !== null) clearTimeout(persistTimer);
persistTimer = null;
- await persistenceQueue.run(() =>
- writePersistedComposerDrafts(appAtomRegistry.get(composerDraftsAtom)),
- );
+ persistRetryNeeded = false;
+ try {
+ await persistenceQueue.run(() =>
+ writePersistedComposerDrafts(appAtomRegistry.get(composerDraftsAtom)),
+ );
+ } catch (error) {
+ persistRetryNeeded = true;
+ throw error;
+ }
}
+ // Draining also waits for an already-fired debounce whose write is still
+ // gated behind its own hydration await inside the queue.
await persistenceQueue.run(() => Promise.resolve());
- } while (persistTimer !== null);
+ // An edit can schedule its debounce while the drain sentinel is waiting
+ // behind an older write. Its revision changes immediately, before that
+ // later write enters the queue, so repeat until that edit is durable too.
+ if (persistRevision === revisionToFlush && persistTimer === null && !persistRetryNeeded) {
+ return;
+ }
+ }
}
-function schedulePersistComposerDrafts(drafts: Record<string, ComposerDraft>): void {
+function schedulePersistComposerDrafts(): void {
+ persistRevision += 1;
if (persistTimer !== null) {
clearTimeout(persistTimer);
}
persistTimer = setTimeout(() => {
persistTimer = null;
- void savePersistedComposerDrafts(drafts);
+ // The write enters the serialization queue before waiting on hydration,
+ // so flushComposerDrafts' queue drain cannot resolve ahead of it.
+ void persistenceQueue.run(async () => {
+ try {
+ await waitForComposerDraftsLoaded();
+ await writePersistedComposerDrafts(appAtomRegistry.get(composerDraftsAtom));
+ persistRetryNeeded = false;
+ } catch (error) {
+ // A failed debounce has no timer left. A later final flush must retry
+ // these edits after persisted ownership can be read safely.
+ persistRetryNeeded = true;
+ console.warn("[composer-drafts] failed to persist drafts", error);
+ // Draft persistence is best-effort; in-memory drafts still keep working.
+ }
+ });
}, PERSIST_DEBOUNCE_MS);
}
@@ -243,29 +279,41 @@ export function ensureComposerDraftsLoaded(): void {
if (loadPromise !== null) {
return;
}
- loadPromise = loadPersistedComposerDrafts()
- .then((persistedDrafts) => {
- if (Object.keys(persistedDrafts).length === 0) {
- return;
- }
- const current = appAtomRegistry.get(composerDraftsAtom);
- appAtomRegistry.set(composerDraftsAtom, {
- ...persistedDrafts,
- ...current,
- });
- })
- .catch((cause) => {
- console.warn(
- "[composer-drafts] failed to hydrate drafts",
- new ComposerDraftPersistenceError({
- operation: "hydrate",
- directory: COMPOSER_DRAFTS_DIRECTORY,
- fileName: COMPOSER_DRAFTS_FILE,
- cause,
- }),
- );
- // Draft loading is best-effort; in-memory drafts still keep working.
+ const loading = loadPersistedComposerDrafts().then((persistedDrafts) => {
+ if (Object.keys(persistedDrafts).length === 0) {
+ return;
+ }
+ const current = appAtomRegistry.get(composerDraftsAtom);
+ appAtomRegistry.set(composerDraftsAtom, {
+ ...persistedDrafts,
+ ...current,
});
+ });
+ loadPromise = loading;
+ // Handle fire-and-forget hook loads without swallowing failures from the
+ // write and cleanup callers that await this same promise. A later call retries.
+ void loading.catch((cause) => {
+ if (loadPromise === loading) loadPromise = null;
+ console.warn(
+ "[composer-drafts] failed to hydrate drafts",
+ cause instanceof ComposerDraftPersistenceError
+ ? cause
+ : new ComposerDraftPersistenceError({
+ operation: "hydrate",
+ directory: COMPOSER_DRAFTS_DIRECTORY,
+ fileName: COMPOSER_DRAFTS_FILE,
+ cause,
+ }),
+ );
+ });
+}
+
+/** Wait until persisted drafts have been merged into the in-memory composer state. */
+export async function waitForComposerDraftsLoaded(): Promise<void> {
+ ensureComposerDraftsLoaded();
+ if (loadPromise !== null) {
+ await loadPromise;
+ }
}
function updateComposerDrafts(
@@ -277,7 +325,7 @@ function updateComposerDrafts(
return;
}
appAtomRegistry.set(composerDraftsAtom, next);
- schedulePersistComposerDrafts(next);
+ schedulePersistComposerDrafts();
}
export function setComposerDraftText(draftKey: string, value: string): void {
@@ -470,10 +518,7 @@ export async function copyComposerDraftContentIfEmpty(
sourceDraftKey: string,
targetDraftKey: string,
): Promise<void> {
- ensureComposerDraftsLoaded();
- if (loadPromise !== null) {
- await loadPromise;
- }
+ await waitForComposerDraftsLoaded();
updateComposerDrafts((current) =>
copyComposerDraftContentState(current, sourceDraftKey, targetDraftKey),
);
@@ -545,10 +590,7 @@ export async function mergeComposerDraftContent(
draftKey: string,
content: ComposerDraftContent,
): Promise<{ readonly skippedAttachmentCount: number }> {
- ensureComposerDraftsLoaded();
- if (loadPromise !== null) {
- await loadPromise;
- }
+ await waitForComposerDraftsLoaded();
if (persistTimer !== null) {
clearTimeout(persistTimer);
persistTimer = null;
@@ -580,10 +622,7 @@ export async function restoreComposerDraftSnapshot(
draftKey: string,
snapshot: ComposerDraft,
): Promise<void> {
- ensureComposerDraftsLoaded();
- if (loadPromise !== null) {
- await loadPromise;
- }
+ await waitForComposerDraftsLoaded();
if (persistTimer !== null) {
clearTimeout(persistTimer);
persistTimer = null;
@@ -630,10 +669,7 @@ export function removeComposerDraftsForEnvironment(
}
export async function clearComposerDraftsEnvironment(environmentId: EnvironmentId): Promise<void> {
- ensureComposerDraftsLoaded();
- if (loadPromise !== null) {
- await loadPromise;
- }
+ await waitForComposerDraftsLoaded();
const next = removeComposerDraftsForEnvironment(
appAtomRegistry.get(composerDraftsAtom),
diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts
index d346d9b89..e7159a7e7 100644
--- a/apps/mobile/src/state/use-thread-outbox-drain.ts
+++ b/apps/mobile/src/state/use-thread-outbox-drain.ts
@@ -32,6 +32,7 @@ import {
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
+ threadOutboxHydrationRetryDelayMs,
threadOutboxRetryDelayMs,
type QueuedThreadCreation,
type QueuedThreadMessage,
@@ -107,9 +108,13 @@ export function useThreadOutboxDrain(): void {
const retryAttemptRef = useRef(new Map<MessageId, number>());
const retryNotBeforeRef = useRef(new Map<MessageId, number>());
const retryTimersRef = useRef(new Map<MessageId, ReturnType<typeof setTimeout>>());
+ const connectedEnvironmentKey = connectedEnvironments
+ .filter((environment) => environment.connectionState === "connected")
+ .map((environment) => environment.environmentId)
+ .sort()
+ .join("\n");
useEffect(() => {
- ensureThreadOutboxLoaded();
return () => {
for (const timer of retryTimersRef.current.values()) {
clearTimeout(timer);
@@ -118,6 +123,30 @@ export function useThreadOutboxDrain(): void {
};
}, []);
+ useEffect(() => {
+ let active = true;
+ let retryTimer: ReturnType<typeof setTimeout> | null = null;
+ let retryAttempt = 0;
+
+ const hydrate = (): void => {
+ void ensureThreadOutboxLoaded().then((complete) => {
+ if (complete || !active || connectedEnvironmentKey.length === 0) return;
+ const delayMs = threadOutboxHydrationRetryDelayMs(retryAttempt);
+ retryAttempt += 1;
+ if (delayMs === null) return;
+ retryTimer = setTimeout(hydrate, delayMs);
+ });
+ };
+
+ // Retry a mixed valid/corrupt read for a short bounded window while the
+ // environment stays connected. Connection-set changes restart the window.
+ hydrate();
+ return () => {
+ active = false;
+ if (retryTimer !== null) clearTimeout(retryTimer);
+ };
+ }, [connectedEnvironmentKey]);
+
const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => {
const reportFailure = (
commandResult: AtomCommandResult<unknown, unknown>,
diff --git a/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.md
index 51e88768c..0dd18cd19 100644
--- a/docs/internals/connection-runtime.md
+++ b/docs/internals/connection-runtime.md
@@ -133,6 +133,13 @@ Platform layers adapt operating-system capabilities. They do not implement
connection policy. `EnvironmentOwnedDataCleanup` is part of this contract: on
removal the registry clears its cache and calls the platform implementation, so
web clears composer drafts and mobile clears drafts plus the thread outbox.
+Mobile draft loads fail closed: a read or decode error does not look like an
+empty store. Outbox hydration publishes readable queued messages and leaves
+unreadable files on disk with diagnostics. Environment cleanup still stops if
+any outbox record cannot be read, so unread attachment owners are not deleted.
+Queued delivery retries tagged transport failures (`RpcClientError`, disconnected
+or unregistered environments) and only restores a pending task after a server
+command or authorization rejection.
## Source Boundaries
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 64172eaa4..0e24087de 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -3,6 +3,12 @@
Messages can contain up to 120,000 characters. Akeru keeps an oversized draft in the composer and
shows how many characters you must remove. Shorten the draft or send it as several messages.
+On mobile, unsent drafts and queued messages stay on the device. If Akeru cannot read a draft store,
+it leaves the saved work in place instead of treating it as empty. Readable queued messages still
+send after reconnect. An unreadable queued-message file stays on the device until it can be read. A
+send that fails because the connection dropped stays queued and retries when the environment is
+reachable again.
+
## Attach images
On servers with direct uploads, an image starts uploading when you add it. Akeru enables **Send**