The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): queued messages are delivered by an app service, not a render loop (#25678)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 16:58 UTC
a7caea34abc09a48d11d00f9957586a7cf3d628f
9 files changed
+923
-770
apps/mobile/src/App.tsx
+10
-5
@@ -1,4 +1,6 @@
1
import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
2
+import { installComposerAttachmentUploads } from "./state/composer-attachment-uploads";
3
+import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
4
import * as Linking from "expo-linking";
5
import * as SplashScreen from "expo-splash-screen";
6
import { useEffect } from "react";
@@ -86,11 +88,14 @@ const navigationRef = createNavigationContainerRef();
88
89
declare const module: { readonly hot?: FoundationHotModule } | undefined;
90
89
-const disposePermissionUpdateNotice = installPermissionUpdateNotice();
90
-disposeOnFoundationReplace(
91
- typeof module === "undefined" ? undefined : module.hot,
92
- disposePermissionUpdateNotice,
93
-);
91
+const appServiceDisposers = [
92
+ installPermissionUpdateNotice(),
93
+ installThreadOutboxDelivery(),
94
+ installComposerAttachmentUploads(),
95
+];
96
+disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
97
+ for (const dispose of appServiceDisposers) dispose();
98
+});
99
100
function SplashScreenCoordinator() {
101
const { isReady } = useAppearancePreferences();
apps/mobile/src/Stack.tsx
-10
@@ -149,8 +149,6 @@ import { deriveLayout } from "./lib/layout";
149
import { useNativeLayoutMetrics } from "./native/native-layout-metrics";
150
import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
151
import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface";
152
-import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
153
-import { useComposerAttachmentUploadWorker } from "./state/composer-attachment-uploads";
152
import {
153
selectWorkspaceDetail,
154
workspaceDetailRouter,
@@ -485,13 +483,6 @@ function workspaceLocationFromState(state: NavigationState) {
483
};
484
}
485
488
-// Isolate subscriptions so streaming updates cannot re-render RootStackLayout and every screen.
489
-function ThreadOutboxDrainWorker() {
490
- useThreadOutboxDrain();
491
- useComposerAttachmentUploadWorker();
492
- return null;
493
-}
494
-
486
function RootStackLayout(props: {
487
readonly children: React.ReactNode;
488
readonly state: NavigationState;
@@ -546,7 +537,6 @@ function RootStackLayout(props: {
537
routePendingTaskId={routePendingTaskId}
538
>
539
<HardwareKeyboardCommandProvider pathname={pathname}>
549
- <ThreadOutboxDrainWorker />
540
<ShowcaseCaptureCoordinator pathname={pathname} />
541
<SettingsEnvironmentFilterProvider open={settingsOpen}>
542
<WorkspaceConnectionStatusProvider>
apps/mobile/src/state/composer-attachment-uploads.test.ts
+19
-24
@@ -19,20 +19,9 @@ const native = vi.hoisted(() => ({
19
remove: Symbol("remove"),
20
transfer:
21
vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(),
22
- effects: [] as Array<() => void | (() => void)>,
23
- queueRef: {
24
- current: null as ReturnType<
25
- typeof import("../lib/composerAttachmentUploadQueue").createComposerAttachmentUploadQueue
26
- > | null,
27
- },
22
}));
23
24
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
31
-vi.mock("react", async (importOriginal) => ({
32
- ...(await importOriginal<typeof import("react")>()),
33
- useEffect: (effect: () => void | (() => void)) => native.effects.push(effect),
34
- useRef: () => native.queueRef,
35
-}));
25
vi.mock("@effect/atom-react", () => ({
26
useAtomValue: (atom: Parameters<typeof appAtomRegistry.get>[0]) => appAtomRegistry.get(atom),
27
}));
@@ -111,6 +100,8 @@ vi.mock("./entities", () => ({
100
useServerConfigs: () => new Map([["environment-1", config]]),
101
useThreadShells: () => [],
102
}));
103
+vi.mock("./projects", () => ({ environmentProjects: {} }));
104
+vi.mock("./workspace", () => ({ workspaceConnections: {} }));
105
vi.mock("./server", async () => {
106
const { Atom } = await import("effect/reactivity");
107
return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } };
@@ -173,14 +164,9 @@ vi.mock("./use-thread-outbox", async () => {
164
dispatchingQueuedMessageIdAtom: Atom.make<Record<string, string>>({}).pipe(Atom.keepAlive),
165
useThreadOutboxMessages: () =>
166
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
176
- useThreadOutboxShellStatuses: () => new Map(),
167
+ threadOutboxShellStatusesAtom: Atom.make(new Map()),
168
};
169
});
179
-vi.mock("./use-remote-environment-registry", () => ({
180
- useRemoteConnectionStatus: () => ({
181
- connectedEnvironments: [{ environmentId: "environment-1", connectionState: "connected" }],
182
- }),
183
-}));
170
171
import {
172
composerAttachmentUploadBlockReason,
@@ -188,10 +174,12 @@ import {
174
composerAttachmentUploadKey,
175
} from "../lib/composerAttachmentUploadQueue";
176
import type { DraftComposerAttachment } from "../lib/composerImages";
177
+import { Atom } from "effect/reactivity";
178
import { appAtomRegistry } from "./atom-registry";
179
import {
180
+ composerAttachmentUploadRequests,
181
composerAttachmentUploadsAtom,
194
- useComposerAttachmentUploadWorker,
182
+ createComposerAttachmentUploadWorker,
183
} from "./composer-attachment-uploads";
184
import {
185
enqueueThreadOutboxMessage,
@@ -200,7 +188,7 @@ import {
188
} from "./thread-outbox";
189
import type { QueuedThreadMessage } from "./thread-outbox-model";
190
import * as drafts from "./use-composer-drafts";
203
-import { prepareQueuedMessageAttachments } from "./use-thread-outbox-drain";
191
+import { prepareQueuedMessageAttachments } from "./threadOutboxDelivery";
192
193
const environmentId = EnvironmentId.make("environment-1");
194
const draftKey = "environment-1:thread-1";
@@ -217,12 +205,19 @@ const image: DraftComposerAttachment = {
205
};
206
let disposeWorker: (() => void) | undefined;
207
208
+const requestsAtom = Atom.make((get) =>
209
+ composerAttachmentUploadRequests({
210
+ drafts: get(drafts.composerDraftUploadSourcesAtom),
211
+ queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
212
+ connectedEnvironmentIds: new Set([environmentId]),
213
+ operableEnvironmentIds: new Set([environmentId]),
214
+ serverConfigs: new Map([[environmentId, config]]),
215
+ }),
216
+);
217
+
218
function worker() {
221
- native.effects = [];
222
- useComposerAttachmentUploadWorker();
223
- disposeWorker = native.effects[0]!() ?? undefined;
224
- const queue = native.queueRef.current!;
225
- native.effects[1]!();
219
+ const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom);
220
+ disposeWorker = dispose;
221
return queue;
222
}
223
apps/mobile/src/state/composer-attachment-uploads.ts
+128
-87
@@ -2,11 +2,13 @@ import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime
2
import { useAtomValue } from "@effect/atom-react";
3
import { AuthOrchestrationOperateScope, type EnvironmentId } from "@t3tools/contracts";
4
import { Atom, AsyncResult } from "effect/reactivity";
5
-import { useEffect, useRef } from "react";
5
6
import { prepareTurnAttachments } from "../lib/attachmentUpload";
7
import { retainComposerAttachmentFileForPreview } from "../lib/composerAttachmentPreviewRetention";
9
-import { isFileBackedComposerAttachment } from "../lib/composerImages";
8
+import {
9
+ isFileBackedComposerAttachment,
10
+ type DraftComposerAttachment,
11
+} from "../lib/composerImages";
12
import {
13
composerAttachmentUploadKey,
14
composerDraftEnvironmentId,
@@ -15,19 +17,19 @@ import {
17
type ComposerAttachmentUploadState,
18
} from "../lib/composerAttachmentUploadQueue";
19
import { appAtomRegistry } from "./atom-registry";
18
-import { useServerConfigs } from "./entities";
20
+import { environmentServerConfigsAtom } from "./server";
21
import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbox";
20
-import { useThreadOutboxMessages } from "./use-thread-outbox";
22
import {
23
ComposerDraftPersistenceError,
24
+ type ComposerDraft,
25
composerDraftsAtom,
26
composerDraftUploadSourcesAtom,
27
ensureComposerDraftsLoaded,
28
flushComposerDrafts,
29
setComposerDraftAttachmentUpload,
30
} from "./use-composer-drafts";
29
-import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
30
-import { readEnvironmentScope, useEnvironmentsWithScope } from "./session";
31
+import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session";
32
+import { workspaceConnections } from "./workspace";
33
34
export {
35
composerAttachmentUploadBlockReason,
@@ -56,91 +58,130 @@ export function retryComposerAttachmentUpload(environmentId: EnvironmentId, atta
58
uploadQueue?.retry(environmentId, attachmentId);
59
}
60
59
-export function useComposerAttachmentUploadWorker() {
60
- const drafts = useAtomValue(composerDraftUploadSourcesAtom);
61
- const queuedMessages = useThreadOutboxMessages();
62
- const serverConfigs = useServerConfigs();
63
- const { connectedEnvironments } = useRemoteConnectionStatus();
64
- const operableEnvironments = useEnvironmentsWithScope(
65
- connectedEnvironments,
66
- AuthOrchestrationOperateScope,
61
+type ComposerAttachmentUploadRequest = {
62
+ readonly environmentId: EnvironmentId;
63
+ readonly attachment: DraftComposerAttachment;
64
+};
65
+
66
+export function composerAttachmentUploadRequests(input: {
67
+ readonly drafts: Readonly<Record<string, Pick<ComposerDraft, "attachments" | "project">>>;
68
+ readonly queuedMessagesByThreadKey: Parameters<typeof flattenQueuedThreadMessages>[0];
69
+ readonly connectedEnvironmentIds: ReadonlySet<EnvironmentId>;
70
+ readonly operableEnvironmentIds: ReadonlySet<EnvironmentId>;
71
+ readonly serverConfigs: ReadonlyMap<
72
+ EnvironmentId,
73
+ Parameters<typeof canUploadComposerAttachment>[1]
74
+ >;
75
+}): ReadonlyArray<ComposerAttachmentUploadRequest> {
76
+ const queued = flattenQueuedThreadMessages(input.queuedMessagesByThreadKey);
77
+ return Object.entries(input.drafts).flatMap(([key, draft]) => {
78
+ const environmentId = composerDraftEnvironmentId(key, queued, draft);
79
+ if (
80
+ environmentId === null ||
81
+ !input.connectedEnvironmentIds.has(environmentId) ||
82
+ !input.operableEnvironmentIds.has(environmentId)
83
+ )
84
+ return [];
85
+ return draft.attachments
86
+ .filter((attachment) =>
87
+ canUploadComposerAttachment(attachment, input.serverConfigs.get(environmentId)),
88
+ )
89
+ .map((attachment) => ({ environmentId, attachment }));
90
+ });
91
+}
92
+
93
+// Each connected environment's session is read here so a granted or revoked
94
+// operate scope re-syncs the queue.
95
+const composerAttachmentUploadRequestsAtom = Atom.make((get) => {
96
+ const connected = get(workspaceConnections.environmentsAtom).filter(
97
+ (environment) => environment.connectionState === "connected",
98
);
68
- const queueRef = useRef<ReturnType<typeof createComposerAttachmentUploadQueue> | null>(null);
99
+ const operableEnvironmentIds = new Set<EnvironmentId>();
100
+ for (const { environmentId } of connected) {
101
+ if (
102
+ sessionHasScope(
103
+ get(environmentSession.sessionStateAtom(environmentId)),
104
+ AuthOrchestrationOperateScope,
105
+ )
106
+ ) {
107
+ operableEnvironmentIds.add(environmentId);
108
+ }
109
+ }
110
+ return composerAttachmentUploadRequests({
111
+ drafts: get(composerDraftUploadSourcesAtom),
112
+ queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
113
+ connectedEnvironmentIds: new Set(connected.map((environment) => environment.environmentId)),
114
+ operableEnvironmentIds,
115
+ serverConfigs: get(environmentServerConfigsAtom),
116
+ });
117
+}).pipe(Atom.withLabel("mobile:composer-attachment-upload-requests"));
118
70
- useEffect(() => {
71
- ensureComposerDraftsLoaded();
72
- const queue = createComposerAttachmentUploadQueue({
73
- onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states),
74
- upload: async ({ environmentId, attachment }, signal, onProgress) => {
75
- const release = isFileBackedComposerAttachment(attachment)
76
- ? retainComposerAttachmentFileForPreview(attachment)
77
- : undefined;
78
- const prepared = await settlePromise(() =>
79
- prepareTurnAttachments({
80
- environmentId,
81
- attachments: [attachment],
82
- supportsImageUploads: true,
83
- signal,
84
- onUploadProgress: (_, progress) => onProgress(progress),
85
- persistUploadedReferences: async ([uploaded]) => {
86
- if (signal.aborted || !uploaded) return "abandon";
87
- const queued = flattenQueuedThreadMessages(
88
- appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
89
- );
90
- let retained = false;
91
- for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
92
- if (
93
- composerDraftEnvironmentId(key, queued, draft) === environmentId &&
94
- draft.attachments.some((candidate) => candidate.id === attachment.id)
95
- ) {
96
- retained = setComposerDraftAttachmentUpload(key, uploaded) || retained;
97
- }
119
+/**
120
+ * Uploads draft attachments to their environment as soon as it is connected and
121
+ * operable. The queue follows the requests atom for its whole lifetime.
122
+ */
123
+export function createComposerAttachmentUploadWorker(
124
+ requestsAtom: Atom.Atom<
125
+ ReadonlyArray<ComposerAttachmentUploadRequest>
126
+ > = composerAttachmentUploadRequestsAtom,
127
+) {
128
+ ensureComposerDraftsLoaded();
129
+ const queue = createComposerAttachmentUploadQueue({
130
+ onChange: (states) => appAtomRegistry.set(composerAttachmentUploadsAtom, states),
131
+ upload: async ({ environmentId, attachment }, signal, onProgress) => {
132
+ const release = isFileBackedComposerAttachment(attachment)
133
+ ? retainComposerAttachmentFileForPreview(attachment)
134
+ : undefined;
135
+ const prepared = await settlePromise(() =>
136
+ prepareTurnAttachments({
137
+ environmentId,
138
+ attachments: [attachment],
139
+ supportsImageUploads: true,
140
+ signal,
141
+ onUploadProgress: (_, progress) => onProgress(progress),
142
+ persistUploadedReferences: async ([uploaded]) => {
143
+ if (signal.aborted || !uploaded) return "abandon";
144
+ const queued = flattenQueuedThreadMessages(
145
+ appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
146
+ );
147
+ let retained = false;
148
+ for (const [key, draft] of Object.entries(appAtomRegistry.get(composerDraftsAtom))) {
149
+ if (
150
+ composerDraftEnvironmentId(key, queued, draft) === environmentId &&
151
+ draft.attachments.some((candidate) => candidate.id === attachment.id)
152
+ ) {
153
+ retained = setComposerDraftAttachmentUpload(key, uploaded) || retained;
154
}
99
- if (!retained) return "abandon";
100
- // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads.
101
- await flushComposerDrafts().catch((error: unknown) => {
102
- if (!(error instanceof ComposerDraftPersistenceError)) throw error;
103
- console.warn("[composer-attachments] could not save the uploaded reference", error);
104
- });
105
- return "persisted";
106
- },
107
- }),
108
- );
109
- release?.();
110
- if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared);
111
- return prepared.value.status === "ready";
112
- },
113
- });
114
- queueRef.current = queue;
115
- uploadQueue = queue;
116
- return () => {
155
+ }
156
+ if (!retained) return "abandon";
157
+ // Draft-save failure only costs re-upload after restart; the outbox saves references independently, so preserve accepted uploads.
158
+ await flushComposerDrafts().catch((error: unknown) => {
159
+ if (!(error instanceof ComposerDraftPersistenceError)) throw error;
160
+ console.warn("[composer-attachments] could not save the uploaded reference", error);
161
+ });
162
+ return "persisted";
163
+ },
164
+ }),
165
+ );
166
+ release?.();
167
+ if (AsyncResult.isFailure(prepared)) throw squashAtomCommandFailure(prepared);
168
+ return prepared.value.status === "ready";
169
+ },
170
+ });
171
+ uploadQueue = queue;
172
+ const unsubscribe = appAtomRegistry.subscribe(requestsAtom, (requests) => queue.sync(requests), {
173
+ immediate: true,
174
+ });
175
+ return {
176
+ queue,
177
+ dispose: () => {
178
+ unsubscribe();
179
queue.dispose();
180
if (uploadQueue === queue) uploadQueue = null;
119
- queueRef.current = null;
120
- };
121
- }, []);
181
+ },
182
+ };
183
+}
184
123
- useEffect(() => {
124
- const queued = flattenQueuedThreadMessages(queuedMessages);
125
- const connected = new Set(
126
- connectedEnvironments
127
- .filter((environment) => environment.connectionState === "connected")
128
- .map((environment) => environment.environmentId),
129
- );
130
- const requests = Object.entries(drafts).flatMap(([key, draft]) => {
131
- const environmentId = composerDraftEnvironmentId(key, queued, draft);
132
- if (
133
- environmentId === null ||
134
- !connected.has(environmentId) ||
135
- !operableEnvironments.has(environmentId)
136
- )
137
- return [];
138
- return draft.attachments
139
- .filter((attachment) =>
140
- canUploadComposerAttachment(attachment, serverConfigs.get(environmentId)),
141
- )
142
- .map((attachment) => ({ environmentId, attachment }));
143
- });
144
- queueRef.current?.sync(requests);
145
- }, [connectedEnvironments, drafts, operableEnvironments, queuedMessages, serverConfigs]);
185
+export function installComposerAttachmentUploads(): () => void {
186
+ return createComposerAttachmentUploadWorker().dispose;
187
}
apps/mobile/src/state/session.ts
+1
-1
@@ -17,7 +17,7 @@ export const environmentSession = createEnvironmentSessionAtoms(connectionAtomRu
17
18
const EMPTY_SESSION_STATE_ATOM = Atom.make(AsyncResult.initial<AuthSessionState>());
19
20
-function sessionHasScope(
20
+export function sessionHasScope(
21
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
22
scope: AuthEnvironmentScope,
23
): boolean {
apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts
renamed
+139
-55
@@ -13,15 +13,21 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
13
import type { QueuedThreadMessage } from "./thread-outbox-model";
14
15
const state = vi.hoisted(() => ({
16
- grantedEnvironments: new Set<string>(),
16
draftText: "Keep this draft separate",
17
cleanups: [] as Array<() => void>,
18
+ delivery: null as {
19
+ readonly drain: () => void;
20
+ readonly dispose: () => void;
21
+ } | null,
22
start: vi.fn(),
23
metadata: vi.fn(),
24
runtime: vi.fn(),
25
interaction: vi.fn(),
26
prepare: vi.fn(),
27
checkout: vi.fn(),
28
+ modelUnavailable: vi.fn(() => false),
29
+ familyMount: vi.fn(() => () => {}),
30
+ threadShells: null as unknown as Atom.Writable<ReadonlyArray<unknown>>,
31
manager: null as unknown as ReturnType<
32
typeof import("./thread-outbox-manager").createThreadOutboxManager
33
>,
@@ -34,42 +40,53 @@ const state = vi.hoisted(() => ({
40
session: null,
41
},
42
config: {
43
+ shellThreadFamilies: false,
44
providers: [{ instanceId: "codex", driver: "codex" }],
45
environment: { capabilities: {} },
46
},
47
}));
41
-vi.mock("react", () => ({
42
- useCallback: <A>(callback: A) => callback,
43
- useEffect: (effect: () => void | (() => void)) => {
44
- const cleanup = effect();
45
- if (cleanup) state.cleanups.push(cleanup);
46
- },
47
- useRef: <A>(value: A) => ({ current: value }),
48
- useState: <A>(initial: A) => [initial, vi.fn()],
49
-}));
48
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
51
-vi.mock("@effect/atom-react", async () => {
49
+vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
50
+ ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
51
+ runAtomCommand: (_registry: unknown, command: (input: unknown) => unknown, input: unknown) =>
52
+ command(input),
53
+}));
54
+vi.mock("./session", async () => {
55
+ const { Atom } = await import("effect/reactivity");
56
const { appAtomRegistry } = await import("./atom-registry");
53
- return { useAtomValue: <A>(atom: Atom.Atom<A>) => appAtomRegistry.get(atom) };
57
+ // A session's state is reduced to whether it grants the operate scope.
58
+ const sessionStateAtom = Atom.family((_id: string) => Atom.make(false).pipe(Atom.keepAlive));
59
+ const sessionHasScope = (granted: boolean, scope: string) =>
60
+ granted && scope === AuthOrchestrationOperateScope;
61
+ return {
62
+ environmentSession: { sessionStateAtom },
63
+ sessionHasScope,
64
+ readEnvironmentScope: (environmentId: string, scope: string) =>
65
+ sessionHasScope(appAtomRegistry.get(sessionStateAtom(environmentId)), scope),
66
+ };
67
+});
68
+vi.mock("./projects", async () => {
69
+ const { Atom } = await import("effect/reactivity");
70
+ return { environmentProjects: { projectsAtom: Atom.make([]) } };
71
+});
72
+vi.mock("./workspace", async () => {
73
+ const { Atom } = await import("effect/reactivity");
74
+ return {
75
+ workspaceConnections: {
76
+ environmentsAtom: Atom.make([{ environmentId: "secondary", connectionState: "connected" }]),
77
+ },
78
+ };
79
});
55
-vi.mock("./session", () => ({
56
- readEnvironmentScope: (environmentId: string, scope: string) =>
57
- scope === AuthOrchestrationOperateScope && state.grantedEnvironments.has(environmentId),
58
- useEnvironmentsWithScope: () => state.grantedEnvironments,
59
-}));
60
-vi.mock("./entities", () => ({
61
- useProjects: () => [],
62
- useThreadShells: () => [state.thread],
63
- useServerConfigs: () => new Map([["secondary", state.config]]),
64
-}));
80
vi.mock("./server", async () => {
81
const { Atom } = await import("effect/reactivity");
82
return {
83
serverEnvironment: { configValueAtom: Atom.family((_id: string) => Atom.make(state.config)) },
84
+ environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.config]])),
85
};
86
});
87
vi.mock("./threads", async () => {
72
- const { Atom } = await import("effect/reactivity");
88
+ const { Atom, AsyncResult } = await import("effect/reactivity");
89
+ state.threadShells = Atom.make<ReadonlyArray<unknown>>([state.thread]).pipe(Atom.keepAlive);
90
return {
91
threadEnvironment: {
92
startTurn: state.start,
@@ -77,21 +94,19 @@ vi.mock("./threads", async () => {
94
setRuntimeMode: state.runtime,
95
setInteractionMode: state.interaction,
96
},
80
- environmentThreadShells: { threadShellsAtom: Atom.make([state.thread]) },
81
- environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) },
97
+ environmentThreadShells: { threadShellsAtom: state.threadShells },
98
+ threadFamilies: {
99
+ mount: state.familyMount,
100
+ familyAtom: () => Atom.make(AsyncResult.success({})),
101
+ refresh: vi.fn(),
102
+ },
103
+ environmentThreadDetails: { threadAtom: () => Atom.make(null) },
104
};
105
});
84
-vi.mock("./use-atom-command", () => ({ useAtomCommand: <A>(command: A) => command }));
106
vi.mock("./git", () => ({ gitEnvironment: { preparePullRequestThread: state.checkout } }));
86
-vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: () => false }));
107
+vi.mock("../lib/modelOptions", () => ({ isModelSelectionUnavailable: state.modelUnavailable }));
108
vi.mock("../lib/uuid", () => ({ uuidv4: () => "uuid", randomHex: () => "abcd" }));
109
vi.mock("../lib/attachmentUpload", () => ({ prepareTurnAttachments: state.prepare }));
89
-vi.mock("./use-remote-environment-registry", () => ({
90
- setPendingConnectionError: vi.fn(),
91
- useRemoteConnectionStatus: () => ({
92
- connectedEnvironments: [{ environmentId: "secondary", connectionState: "connected" }],
93
- }),
94
-}));
110
vi.mock("./thread-outbox", async () => {
111
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
112
const { appAtomRegistry } = await import("./atom-registry");
@@ -118,13 +133,10 @@ vi.mock("./thread-outbox-removal", () => ({
133
}));
134
vi.mock("./use-thread-outbox", async () => {
135
const { Atom } = await import("effect/reactivity");
121
- const { appAtomRegistry } = await import("./atom-registry");
122
- await import("./thread-outbox");
136
return {
137
editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
138
dispatchingQueuedMessageIdAtom: Atom.make<MessageId | null>(null).pipe(Atom.keepAlive),
126
- useThreadOutboxMessages: () => appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom),
127
- useThreadOutboxShellStatuses: () => new Map([["secondary", "live"]]),
139
+ threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])),
140
};
141
});
142
vi.mock("./use-composer-drafts", async () => {
@@ -146,8 +158,9 @@ vi.mock("./use-composer-drafts", async () => {
158
});
159
160
import { appAtomRegistry } from "./atom-registry";
149
-import { dispatchingQueuedMessageIdAtom } from "./use-thread-outbox";
150
-import { useThreadOutboxDrain } from "./use-thread-outbox-drain";
161
+import { environmentSession } from "./session";
162
+import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom } from "./use-thread-outbox";
163
+import { createThreadOutboxDelivery } from "./threadOutboxDelivery";
164
165
const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMessage => ({
166
environmentId: EnvironmentId.make("secondary"),
@@ -162,20 +175,46 @@ const message = (overrides: Partial<QueuedThreadMessage> = {}): QueuedThreadMess
175
const remaining = () =>
176
Object.values(appAtomRegistry.get(state.manager.queuedMessagesByThreadKeyAtom)).flat();
177
178
+function setOperateGrant(environmentId: string, granted: boolean): void {
179
+ // The mocked session atom holds the grant itself (see the ./session mock).
180
+ const sessionAtom = environmentSession.sessionStateAtom(EnvironmentId.make(environmentId));
181
+ appAtomRegistry.set(sessionAtom as unknown as Atom.Writable<boolean>, granted);
182
+}
183
+
184
function runDrain() {
185
const settled = Promise.withResolvers<void>();
186
const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
187
if (id === null) settled.resolve();
188
});
170
- useThreadOutboxDrain();
189
+ startDelivery();
190
return settled.promise.finally(release);
191
}
192
193
+/** Starts the service once per test; later calls run another drain pass. */
194
+function startDelivery(): void {
195
+ if (state.delivery !== null) {
196
+ state.delivery.drain();
197
+ return;
198
+ }
199
+ const delivery = createThreadOutboxDelivery();
200
+ state.delivery = delivery;
201
+ state.cleanups.push(() => {
202
+ delivery.dispose();
203
+ state.delivery = null;
204
+ });
205
+}
206
+
207
beforeEach(() => {
175
- state.grantedEnvironments = new Set(["primary"]);
208
+ setOperateGrant("primary", true);
209
+ setOperateGrant("secondary", false);
210
state.draftText = "Keep this draft separate";
211
+ state.config.shellThreadFamilies = false;
212
+ state.modelUnavailable.mockReset().mockReturnValue(false);
213
+ state.familyMount.mockReset().mockReturnValue(() => {});
214
+ appAtomRegistry.set(state.threadShells, [state.thread]);
215
appAtomRegistry.set(state.manager.queuedMessagesByThreadKeyAtom, {});
216
appAtomRegistry.set(dispatchingQueuedMessageIdAtom, null);
217
+ appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
218
for (const command of [
219
state.start,
220
state.metadata,
@@ -214,7 +253,7 @@ describe("queued PR checkout", () => {
253
};
254
255
it("waits for the provider's PR checkout and launches in that worktree", async () => {
217
- state.grantedEnvironments.add("secondary");
256
+ setOperateGrant("secondary", true);
257
await state.manager.enqueue(queuedPullRequest());
258
const started = Promise.withResolvers<void>();
259
const checkout =
@@ -243,7 +282,7 @@ describe("queued PR checkout", () => {
282
});
283
284
it("keeps the PR source queued on a transport failure without starting the agent", async () => {
246
- state.grantedEnvironments.add("secondary");
285
+ setOperateGrant("secondary", true);
286
const queued = queuedPullRequest();
287
await state.manager.enqueue(queued);
288
state.checkout.mockResolvedValueOnce(
@@ -255,11 +294,11 @@ describe("queued PR checkout", () => {
294
});
295
296
it("stops launch if operation access is revoked while checking out the PR", async () => {
258
- state.grantedEnvironments.add("secondary");
297
+ setOperateGrant("secondary", true);
298
const queued = queuedPullRequest();
299
await state.manager.enqueue(queued);
300
state.checkout.mockImplementationOnce(async () => {
262
- state.grantedEnvironments.delete("secondary");
301
+ setOperateGrant("secondary", false);
302
return AsyncResult.success(preparedCheckout);
303
});
304
await runDrain();
@@ -268,7 +307,7 @@ describe("queued PR checkout", () => {
307
});
308
309
it("does not launch a stale task edited while the PR checkout was running", async () => {
271
- state.grantedEnvironments.add("secondary");
310
+ setOperateGrant("secondary", true);
311
const queued = queuedPullRequest();
312
await state.manager.enqueue(queued);
313
const edited = { ...queued, text: "Updated instructions" };
@@ -289,18 +328,63 @@ describe("queued task operation access", () => {
328
it("parks a connected read-only target, then delivers its unchanged queue after a grant", async () => {
329
const queued = message();
330
await state.manager.enqueue(queued);
292
- useThreadOutboxDrain();
331
+ startDelivery();
332
expect(state.start).not.toHaveBeenCalled();
333
expect(state.prepare).not.toHaveBeenCalled();
334
expect(remaining()).toEqual([queued]);
296
- state.grantedEnvironments.add("secondary");
335
+ setOperateGrant("secondary", true);
336
+ await runDrain();
337
+ expect(state.start).toHaveBeenCalledOnce();
338
+ expect(remaining()).toEqual([]);
339
+ });
340
+
341
+ it("backs off instead of redelivering at once when a delivery hits a defect", async () => {
342
+ setOperateGrant("secondary", true);
343
+ const queued = message();
344
+ await state.manager.enqueue(queued);
345
+ // Awaited steps catch their own failures, so a defect in the delivery's own code is what
346
+ // rejects a delivery.
347
+ state.modelUnavailable.mockImplementationOnce(() => {
348
+ throw new TypeError("Cannot read properties of undefined");
349
+ });
350
await runDrain();
351
+ expect(state.modelUnavailable).toHaveBeenCalledOnce();
352
+ expect(state.prepare).not.toHaveBeenCalled();
353
+ expect(state.start).not.toHaveBeenCalled();
354
+ expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull();
355
+ expect(remaining()).toEqual([queued]);
356
+ });
357
+
358
+ it("starts one delivery when mounting a thread family changes the rows mid-pass", async () => {
359
+ setOperateGrant("secondary", true);
360
+ state.config.shellThreadFamilies = true;
361
+ const subAgentThread = { ...state.thread, id: "sub-agent" };
362
+ // A cached family merges its rows into the shell list as soon as it is mounted.
363
+ state.familyMount.mockImplementationOnce(() => {
364
+ appAtomRegistry.set(state.threadShells, [state.thread, subAgentThread]);
365
+ return () => {};
366
+ });
367
+ const queued = message({ threadId: ThreadId.make("sub-agent") });
368
+ startDelivery();
369
+ appAtomRegistry.set(editingQueuedMessageIdsAtom, { [queued.messageId]: true });
370
+ await state.manager.enqueue(queued);
371
+ using confirm = vi.spyOn(state.manager, "confirmQueued");
372
+ const delivered = Promise.withResolvers<void>();
373
+ const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => {
374
+ if (id === null) delivered.resolve();
375
+ });
376
+ // Ending the edit wakes the drain through a registry notification, the path on which the
377
+ // mount's synchronous row change notifies the drain again mid-pass.
378
+ appAtomRegistry.set(editingQueuedMessageIdsAtom, {});
379
+ expect(state.familyMount).toHaveBeenCalledOnce();
380
+ expect(confirm).toHaveBeenCalledOnce();
381
+ await delivered.promise.finally(release);
382
expect(state.start).toHaveBeenCalledOnce();
383
expect(remaining()).toEqual([]);
384
});
385
386
it("stops the remaining settings and turn commands when an earlier update loses access", async () => {
303
- state.grantedEnvironments.add("secondary");
387
+ setOperateGrant("secondary", true);
388
const queued = message({
389
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "different-model" },
390
runtimeMode: "approval-required",
@@ -308,7 +392,7 @@ describe("queued task operation access", () => {
392
});
393
await state.manager.enqueue(queued);
394
state.runtime.mockImplementationOnce(async () => {
311
- state.grantedEnvironments.delete("secondary");
395
+ setOperateGrant("secondary", false);
396
return AsyncResult.success(undefined);
397
});
398
await runDrain();
@@ -325,7 +409,7 @@ describe("queued task operation access", () => {
409
])(
410
"preserves a rejected queue but removes an accepted turn after access loss (new task: $isCreation, accepted: $accepted)",
411
async ({ isCreation, accepted }) => {
328
- state.grantedEnvironments.add("secondary");
412
+ setOperateGrant("secondary", true);
413
const queued = message(
414
isCreation
415
? {
@@ -350,7 +434,7 @@ describe("queued task operation access", () => {
434
});
435
const drained = runDrain();
436
await started.promise;
353
- state.grantedEnvironments.delete("secondary");
437
+ setOperateGrant("secondary", false);
438
delivery.resolve(
439
accepted
440
? AsyncResult.success(undefined)
@@ -361,7 +445,7 @@ describe("queued task operation access", () => {
445
expect(remaining()).toEqual(accepted ? [] : [queued]);
446
expect(state.draftText).toBe("Keep this draft separate");
447
if (!accepted) {
364
- state.grantedEnvironments.add("secondary");
448
+ setOperateGrant("secondary", true);
449
await runDrain();
450
expect(state.start).toHaveBeenCalledTimes(2);
451
expect(remaining()).toEqual([]);
@@ -378,7 +462,7 @@ describe("queued task operation access", () => {
462
])(
463
"keeps the message queued after upload revocation (new task: $isCreation, upload fails: $uploadFails)",
464
async ({ isCreation, uploadFails }) => {
381
- state.grantedEnvironments.add("secondary");
465
+ setOperateGrant("secondary", true);
466
const queued = message(
467
isCreation
468
? {
@@ -396,7 +480,7 @@ describe("queued task operation access", () => {
480
);
481
await state.manager.enqueue(queued);
482
state.prepare.mockImplementationOnce(async ({ attachments }) => {
399
- state.grantedEnvironments.delete("secondary");
483
+ setOperateGrant("secondary", false);
484
if (uploadFails) throw new Error("This connection cannot upload attachments.");
485
return {
486
status: "ready",
apps/mobile/src/state/threadOutboxDelivery.test.ts
renamed
+38
-18
@@ -13,6 +13,9 @@ import type { PreparedTurnAttachments } from "../lib/attachmentUpload";
13
14
const harness = vi.hoisted(() => ({
15
canOperate: true,
16
+ threadProjection: null as unknown as import("effect/reactivity").Atom.Writable<{
17
+ readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> };
18
+ } | null>,
19
manager: null as unknown as ReturnType<
20
typeof import("./thread-outbox-manager").createThreadOutboxManager
21
>,
@@ -76,11 +79,9 @@ vi.mock("../lib/attachmentUpload", () => ({
79
prepareTurnAttachments: harness.prepareTurnAttachments,
80
}));
81
79
-vi.mock("./entities", () => ({
80
- useProjects: () => [],
81
- useServerConfigs: () => new Map(),
82
- useThreadShells: () => [],
83
-}));
82
+vi.mock("./projects", () => ({ environmentProjects: {} }));
83
+
84
+vi.mock("./workspace", () => ({ workspaceConnections: {} }));
85
86
vi.mock("./server", async () => {
87
const { Atom } = await import("effect/reactivity");
@@ -91,34 +92,30 @@ vi.mock("./git", () => ({ gitEnvironment: {} }));
92
93
vi.mock("./threads", async () => {
94
const { Atom } = await import("effect/reactivity");
95
+ harness.threadProjection = Atom.make<{
96
+ readonly projection: { readonly messages: ReadonlyArray<{ readonly id: string }> };
97
+ } | null>(null).pipe(Atom.keepAlive);
98
return {
99
threadEnvironment: {},
96
- environmentThreadDetails: { threadAtom: Atom.family((_key: unknown) => Atom.make(null)) },
100
+ environmentThreadDetails: { threadAtom: () => harness.threadProjection },
101
};
102
});
103
100
-vi.mock("./use-atom-command", () => ({
101
- useAtomCommand: () => async () => undefined,
102
-}));
103
-
104
vi.mock("./session", () => ({
105
+ environmentSession: {},
106
readEnvironmentScope: () => harness.canOperate,
106
- useEnvironmentsWithScope: () => new Set(),
107
+ sessionHasScope: () => harness.canOperate,
108
}));
109
110
vi.mock("./use-thread-outbox", async () => {
111
const { Atom } = await import("effect/reactivity");
112
return {
113
editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
113
- useThreadOutboxMessages: () => ({}),
114
- useThreadOutboxShellStatuses: () => new Map(),
114
+ dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive),
115
+ threadOutboxShellStatusesAtom: Atom.make(new Map()),
116
};
117
});
118
118
-vi.mock("./use-remote-environment-registry", () => ({
119
- useRemoteConnectionStatus: () => ({ connectedEnvironments: [] }),
120
-}));
121
-
119
vi.mock("./thread-outbox", async () => {
120
const { createThreadOutboxManager } = await import("./thread-outbox-manager");
121
const { appAtomRegistry } = await import("./atom-registry");
@@ -154,7 +151,7 @@ import {
151
recoverEditedCreationAfterDelivery,
152
removeAcknowledgedExistingThreadMessage,
153
restoreRejectedQueuedMessage,
157
-} from "./use-thread-outbox-drain";
154
+} from "./threadOutboxDelivery";
155
156
function queuedMessage(input: {
157
readonly messageId: string;
@@ -207,6 +204,7 @@ function remainingMessages(): ReadonlyArray<QueuedThreadMessage> {
204
205
beforeEach(() => {
206
appAtomRegistry.set(acknowledgedThreadMessagesAtom, []);
207
+ appAtomRegistry.set(harness.threadProjection, null);
208
harness.canOperate = true;
209
harness.draftFile.setDocument({ schemaVersion: 1, drafts: {} });
210
});
@@ -332,6 +330,28 @@ describe("thread outbox attachment preparation", () => {
330
});
331
332
describe("thread outbox drain delivery cleanup", () => {
333
+ it("drops echoed acknowledged rows at the next delivery without subscribing to the thread", async () => {
334
+ const first = queuedMessage({ messageId: "awaiting-echo", text: "Delivered" });
335
+ const second = queuedMessage({ messageId: "next-delivery", text: "Also delivered" });
336
+ await harness.manager.enqueue(first);
337
+ await harness.manager.enqueue(second);
338
+
339
+ await expect(
340
+ completeQueuedMessageDelivery(first, harness.manager.revisionOf(first.messageId)),
341
+ ).resolves.toBe("removed");
342
+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]);
343
+
344
+ appAtomRegistry.set(harness.threadProjection, {
345
+ projection: { messages: [{ id: "unrelated" }, { id: first.messageId }] },
346
+ });
347
+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([first]);
348
+
349
+ await expect(
350
+ completeQueuedMessageDelivery(second, harness.manager.revisionOf(second.messageId)),
351
+ ).resolves.toBe("removed");
352
+ expect(appAtomRegistry.get(acknowledgedThreadMessagesAtom)).toEqual([second]);
353
+ });
354
+
355
it("removes an acknowledged outbox item even when the sign-out archive write fails", async () => {
356
const message = queuedMessage({ messageId: "archive-write-failure", text: "Delivered" });
357
await harness.manager.enqueue(message);
apps/mobile/src/state/threadOutboxDelivery.ts
renamed
+587
-565
@@ -1,12 +1,15 @@
1
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import * as Dialog from "../components/ui/Dialog";
3
-import { useAtomValue } from "@effect/atom-react";
3
import {
4
threadRuntimeIsActive,
5
type EnvironmentProject,
6
type EnvironmentThreadShell,
7
} from "@t3tools/client-runtime/state/shell";
9
-import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
8
+import {
9
+ type AtomCommand,
10
+ type AtomCommandResult,
11
+ runAtomCommand,
12
+} from "@t3tools/client-runtime/state/runtime";
13
import { threadFamilyRead, type ThreadFamilyRead } from "@t3tools/client-runtime/state/threads";
14
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
15
import {
@@ -15,12 +18,12 @@ import {
18
DEFAULT_PROVIDER_INTERACTION_MODE,
19
DEFAULT_RUNTIME_MODE,
20
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
21
+ type EnvironmentId,
22
type MessageId,
23
} from "@t3tools/contracts";
24
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
25
import * as Cause from "effect/Cause";
22
-import { AsyncResult } from "effect/reactivity";
23
-import { useCallback, useEffect, useRef, useState } from "react";
26
+import { AsyncResult, Atom } from "effect/reactivity";
27
28
import { createDebugLogger } from "../lib/debugLog";
29
import { scopedThreadKey } from "../lib/scopedEntities";
@@ -38,15 +41,15 @@ import {
41
} from "./acknowledged-thread-messages";
42
import { appAtomRegistry } from "./atom-registry";
43
import { restoredNewTaskDraftKey } from "./new-task-draft-key";
41
-import { useProjects, useServerConfigs, useThreadShells } from "./entities";
44
import {
45
clearPendingThreadCreationOutcome,
46
pendingThreadCreationOutcomesAtom,
47
recordPendingThreadCreationOutcome,
48
} from "./pending-thread-creation";
47
-import { serverEnvironment } from "./server";
49
+import { environmentProjects } from "./projects";
50
+import { environmentServerConfigsAtom, serverEnvironment } from "./server";
51
import { gitEnvironment } from "./git";
49
-import { readEnvironmentScope, useEnvironmentsWithScope } from "./session";
52
+import { environmentSession, readEnvironmentScope, sessionHasScope } from "./session";
53
import {
54
confirmThreadOutboxMessageQueued,
55
threadOutboxManager,
@@ -81,15 +84,13 @@ import {
84
updateComposerDraftSettings,
85
waitForComposerDraftsLoaded,
86
} from "./use-composer-drafts";
84
-import { useAtomCommand } from "./use-atom-command";
87
import {
88
dispatchingQueuedMessageIdAtom,
89
editingQueuedMessageIdsAtom,
88
- useThreadOutboxMessages,
89
- useThreadOutboxShellStatuses,
90
+ threadOutboxShellStatusesAtom,
91
} from "./use-thread-outbox";
92
import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
92
-import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
93
+import { workspaceConnections } from "./workspace";
94
95
const threadOutboxDebug = createDebugLogger("thread-outbox");
96
@@ -571,459 +572,308 @@ async function preserveUploadedAttachmentsForEditor(
572
}
573
}
574
574
-export function useThreadOutboxDrain(): void {
575
- const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
576
- const preparePullRequest = useAtomCommand(gitEnvironment.preparePullRequestThread, {
577
- reportFailure: false,
578
- });
579
- const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
580
- reportFailure: false,
581
- });
582
- const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
583
- reportFailure: false,
584
- });
585
- const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
586
- const editingQueuedMessageIds = useAtomValue(editingQueuedMessageIdsAtom);
587
- const queuedMessagesByThreadKey = useThreadOutboxMessages();
588
- const shellStatuses = useThreadOutboxShellStatuses();
589
- const threads = useThreadShells();
590
- const creationOutcomes = useAtomValue(pendingThreadCreationOutcomesAtom);
591
- const projects = useProjects();
592
- const serverConfigs = useServerConfigs();
593
- const { connectedEnvironments } = useRemoteConnectionStatus();
594
- const operableEnvironments = useEnvironmentsWithScope(
575
+// Everything a drain pass decides from. Each queued environment's session is
576
+// read here so a granted or revoked operate scope re-runs the drain.
577
+const deliveryInputsAtom = Atom.make((get) => {
578
+ const connectedEnvironments = get(workspaceConnections.environmentsAtom);
579
+ const operableEnvironments = new Set<EnvironmentId>();
580
+ for (const { environmentId } of connectedEnvironments) {
581
+ if (
582
+ sessionHasScope(
583
+ get(environmentSession.sessionStateAtom(environmentId)),
584
+ AuthOrchestrationOperateScope,
585
+ )
586
+ ) {
587
+ operableEnvironments.add(environmentId);
588
+ }
589
+ }
590
+ return {
591
+ dispatchingQueuedMessageId: get(dispatchingQueuedMessageIdAtom),
592
+ editingQueuedMessageIds: get(editingQueuedMessageIdsAtom),
593
+ queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
594
+ shellStatuses: get(threadOutboxShellStatusesAtom),
595
+ threads: get(environmentThreadShells.threadShellsAtom),
596
+ projects: get(environmentProjects.projectsAtom),
597
+ serverConfigs: get(environmentServerConfigsAtom),
598
connectedEnvironments,
596
- AuthOrchestrationOperateScope,
597
- );
598
- const [retryTick, setRetryTick] = useState(0);
599
- const retryAttemptRef = useRef(new Map<MessageId, number>());
600
- const retryNotBeforeRef = useRef(new Map<MessageId, number>());
601
- const retryTimersRef = useRef(new Map<MessageId, ReturnType<typeof setTimeout>>());
602
- const acknowledgedExistingThreadMessageIdsRef = useRef(new Set<MessageId>());
603
- // Targets the shell may have left out hold their thread family until they leave the queue, so
604
- // the row stays readable through dispatch.
605
- const familyMountsRef = useRef(new Map<MessageId, () => void>());
606
- useEffect(
607
- () => () => {
608
- for (const release of familyMountsRef.current.values()) release();
609
- familyMountsRef.current.clear();
610
- },
611
- [],
612
- );
613
- const blockedRecoverySubscriptionsRef = useRef(
614
- new Map<
615
- MessageId,
616
- { readonly message: QueuedThreadMessage; readonly unsubscribe: () => void }
617
- >(),
618
- );
599
+ operableEnvironments,
600
+ };
601
+}).pipe(Atom.withLabel("mobile:thread-outbox:delivery-inputs"));
602
620
- const scheduleQueuedMessageRetry = useCallback((messageId: MessageId) => {
621
- const retryAttempt = (retryAttemptRef.current.get(messageId) ?? 0) + 1;
622
- retryAttemptRef.current.set(messageId, retryAttempt);
623
- const retryDelayMs = threadOutboxRetryDelayMs(retryAttempt);
624
- retryNotBeforeRef.current.set(messageId, Date.now() + retryDelayMs);
625
- const pendingTimer = retryTimersRef.current.get(messageId);
626
- if (pendingTimer !== undefined) {
627
- clearTimeout(pendingTimer);
628
- }
629
- const retryTimer = setTimeout(() => {
630
- retryTimersRef.current.delete(messageId);
631
- setRetryTick((current) => current + 1);
632
- }, retryDelayMs);
633
- retryTimersRef.current.set(messageId, retryTimer);
634
- }, []);
603
+// Read through the shell atom, not once: the shell often lands before the
604
+// outcome is recorded, and that entry must still be collected when it does.
605
+const settledCreationOutcomeKeysAtom = Atom.make((get): ReadonlyArray<string> => {
606
+ const outcomes = get(pendingThreadCreationOutcomesAtom);
607
+ const threads = get(environmentThreadShells.threadShellsAtom);
608
+ return Object.entries(outcomes).flatMap(([threadKey, outcome]) =>
609
+ outcome.kind === "delivered" &&
610
+ threads.some(
611
+ (thread) =>
612
+ scopedThreadKey(thread.environmentId, thread.id) === threadKey &&
613
+ (thread.latestRun !== null ||
614
+ thread.runtime?.status === "failed" ||
615
+ thread.runtime?.status === "cancelled" ||
616
+ thread.runtime?.status === "interrupted"),
617
+ )
618
+ ? [threadKey]
619
+ : [],
620
+ );
621
+}).pipe(Atom.withLabel("mobile:thread-outbox:settled-creation-outcomes"));
622
636
- const restoreQueuedMessage = useCallback(
637
- async (queuedMessage: QueuedThreadMessage, message: string): Promise<boolean> => {
638
- const result = await restoreRejectedQueuedMessage(queuedMessage, message);
639
- if (result !== "blocked") {
640
- return result !== "retry";
641
- }
623
+const runDeliveryCommand = <W, A, E>(
624
+ command: AtomCommand<W, A, E>,
625
+ input: W,
626
+): Promise<AtomCommandResult<A, E>> =>
627
+ runAtomCommand(appAtomRegistry, command, input, { reportFailure: false });
628
643
- if (!blockedRecoverySubscriptionsRef.current.has(queuedMessage.messageId)) {
644
- const draftKey = recoveryDraftKey(queuedMessage);
645
- const editorDraftKey = queuedMessage.creation
646
- ? `pending-task:${queuedMessage.messageId}`
647
- : null;
648
- const currentDrafts = appAtomRegistry.get(composerDraftsAtom);
649
- const blockedAttachments = currentDrafts[draftKey]?.attachments;
650
- const editorAttachments =
651
- editorDraftKey === null ? undefined : currentDrafts[editorDraftKey]?.attachments;
652
- const unsubscribe = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) => {
653
- if (
654
- drafts[draftKey]?.attachments === blockedAttachments &&
655
- (editorDraftKey === null || drafts[editorDraftKey]?.attachments === editorAttachments)
656
- ) {
657
- return;
658
- }
659
- const active = blockedRecoverySubscriptionsRef.current.get(queuedMessage.messageId);
660
- if (!active) {
661
- return;
662
- }
663
- blockedRecoverySubscriptionsRef.current.delete(queuedMessage.messageId);
664
- active.unsubscribe();
665
- setRetryTick((current) => current + 1);
666
- });
667
- blockedRecoverySubscriptionsRef.current.set(queuedMessage.messageId, {
668
- message: queuedMessage,
669
- unsubscribe,
670
- });
671
- }
672
- return true;
629
+function reportCommandFailure(
630
+ queuedMessage: QueuedThreadMessage,
631
+ commandResult: AtomCommandResult<unknown, unknown>,
632
+ stage: ThreadOutboxCommandStage,
633
+): { readonly action: "retry" | "restore"; readonly message: string } | null {
634
+ if (!AsyncResult.isFailure(commandResult)) {
635
+ return null;
636
+ }
637
+ const error = Cause.squash(commandResult.cause);
638
+ const action = logThreadOutboxDeliveryFailure({
639
+ stage,
640
+ error,
641
+ interrupted: Cause.hasInterruptsOnly(commandResult.cause),
642
+ context: {
643
+ environmentId: queuedMessage.environmentId,
644
+ threadId: queuedMessage.threadId,
645
+ messageId: queuedMessage.messageId,
646
+ cause: commandResult.cause,
647
},
674
- [],
675
- );
648
+ });
649
+ return {
650
+ action,
651
+ message: error instanceof Error ? error.message : "The message could not be sent.",
652
+ };
653
+}
654
677
- useEffect(() => {
678
- let mounted = true;
679
- const load = async () => {
680
- if ((await threadOutboxManager.load()) || !mounted) return;
681
- Dialog.alert(
682
- "Some queued messages could not be loaded",
683
- "Unreadable records and attachment files are still saved. Other messages can still be sent.",
684
- [
685
- { text: "Dismiss", style: "cancel" },
686
- { text: "Retry", onPress: () => void load() },
687
- ],
688
- );
689
- };
690
- void load();
691
- return () => {
692
- mounted = false;
693
- for (const timer of retryTimersRef.current.values()) {
694
- clearTimeout(timer);
695
- }
696
- retryTimersRef.current.clear();
697
- for (const blocked of blockedRecoverySubscriptionsRef.current.values()) {
698
- blocked.unsubscribe();
699
- }
700
- blockedRecoverySubscriptionsRef.current.clear();
701
- };
702
- }, []);
655
+interface ThreadOutboxRetry {
656
+ readonly attempt: number;
657
+ readonly notBefore: number;
658
+ readonly timer: ReturnType<typeof setTimeout>;
659
+}
660
704
- const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => {
705
- const reportFailure = (
706
- commandResult: AtomCommandResult<unknown, unknown>,
707
- stage: ThreadOutboxCommandStage,
708
- ): { readonly action: "retry" | "restore"; readonly message: string } | null => {
709
- if (!AsyncResult.isFailure(commandResult)) {
710
- return null;
711
- }
712
- const error = Cause.squash(commandResult.cause);
713
- const action = logThreadOutboxDeliveryFailure({
714
- stage,
715
- error,
716
- interrupted: Cause.hasInterruptsOnly(commandResult.cause),
717
- context: {
718
- environmentId: queuedMessage.environmentId,
719
- threadId: queuedMessage.threadId,
720
- messageId: queuedMessage.messageId,
721
- cause: commandResult.cause,
722
- },
723
- });
724
- return {
725
- action,
726
- message: error instanceof Error ? error.message : "The message could not be sent.",
727
- };
728
- };
729
- return { reportFailure };
730
- }, []);
661
+/**
662
+ * Delivers queued thread messages one at a time. A drain pass runs whenever its inputs
663
+ * change (outbox, locks, shells, projects, configs, connections, scopes) and when a retry
664
+ * backoff expires. `dispatchingQueuedMessageIdAtom` is the single in-flight slot; clearing
665
+ * it re-runs the drain for the next message.
666
+ */
667
+export function createThreadOutboxDelivery(): {
668
+ readonly drain: () => void;
669
+ readonly dispose: () => void;
670
+} {
671
+ let disposed = false;
672
+ const retries = new Map<MessageId, ThreadOutboxRetry>();
673
+ // Existing-thread turns the server accepted but whose outbox removal has
674
+ // not landed; the next pass retries only the removal, never the send.
675
+ const acknowledgedExistingThreadMessageIds = new Set<MessageId>();
676
+ // Targets the shell may have left out hold their thread family until they leave the queue, so
677
+ // the row stays readable through dispatch.
678
+ const familyMounts = new Map<MessageId, () => void>();
679
+ const blockedRecoveries = new Map<
680
+ MessageId,
681
+ { readonly message: QueuedThreadMessage; readonly unsubscribe: () => void }
682
+ >();
683
732
- const sendQueuedMessage = useCallback(
733
- async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
734
- const hasAccess = () =>
735
- readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope);
736
- if (!hasAccess()) return true;
737
- const serverConfig = appAtomRegistry.get(
738
- serverEnvironment.configValueAtom(queuedMessage.environmentId),
739
- );
740
- if (!serverConfig) return false;
741
- const settings = resolveQueuedThreadSettings(queuedMessage, thread, serverConfig.providers);
742
- if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, thread.projectId)) {
743
- const { title, detail } = describeUnavailableModelSelection(
744
- serverConfig,
745
- settings.modelSelection,
746
- thread.projectId,
747
- );
748
- return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
749
- }
750
- const { reportFailure } = makeDeliveryHelpers(queuedMessage);
684
+ const retryNotBefore = (messageId: MessageId): number => retries.get(messageId)?.notBefore ?? 0;
685
752
- if (settings.runtimeMode !== thread.runtimeMode) {
753
- if (!hasAccess()) return true;
754
- const runtimeResult = await setThreadRuntimeMode({
755
- environmentId: queuedMessage.environmentId,
756
- input: {
757
- commandId: settingsCommandId(queuedMessage, "runtime-mode"),
758
- threadId: queuedMessage.threadId,
759
- runtimeMode: settings.runtimeMode,
760
- createdAt: queuedMessage.createdAt,
761
- },
762
- });
763
- if (AsyncResult.isFailure(runtimeResult)) {
764
- reportFailure(runtimeResult, "settings-sync");
765
- return false;
766
- }
767
- }
686
+ const scheduleRetry = (messageId: MessageId): void => {
687
+ if (disposed) return;
688
+ const previous = retries.get(messageId);
689
+ if (previous !== undefined) clearTimeout(previous.timer);
690
+ const attempt = (previous?.attempt ?? 0) + 1;
691
+ const delayMs = threadOutboxRetryDelayMs(attempt);
692
+ retries.set(messageId, {
693
+ attempt,
694
+ notBefore: Date.now() + delayMs,
695
+ timer: setTimeout(drain, delayMs),
696
+ });
697
+ };
698
769
- if (settings.interactionMode !== thread.interactionMode) {
770
- if (!hasAccess()) return true;
771
- const interactionResult = await setThreadInteractionMode({
772
- environmentId: queuedMessage.environmentId,
773
- input: {
774
- commandId: settingsCommandId(queuedMessage, "interaction-mode"),
775
- threadId: queuedMessage.threadId,
776
- interactionMode: settings.interactionMode,
777
- createdAt: queuedMessage.createdAt,
778
- },
779
- });
780
- if (AsyncResult.isFailure(interactionResult)) {
781
- reportFailure(interactionResult, "settings-sync");
782
- return false;
783
- }
784
- }
699
+ const clearRetry = (messageId: MessageId): void => {
700
+ const retry = retries.get(messageId);
701
+ if (retry === undefined) return;
702
+ clearTimeout(retry.timer);
703
+ retries.delete(messageId);
704
+ };
705
786
- let prepared: PreparedTurnAttachments;
787
- let persistedMessage: QueuedThreadMessage;
788
- let deliveryRevision: number;
789
- if (!hasAccess()) return true;
790
- try {
791
- const preparedResult = await prepareQueuedMessageAttachments(
792
- queuedMessage,
793
- serverConfig.environment.capabilities.attachmentUploads === true,
794
- );
795
- if (preparedResult.status === "abandoned") {
796
- return true;
797
- }
798
- prepared = preparedResult.prepared;
799
- persistedMessage = preparedResult.persistedMessage;
800
- deliveryRevision = preparedResult.deliveryRevision;
801
- if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
802
- await preserveUploadedAttachmentsForEditor(
803
- queuedMessage,
804
- preparedResult.persistedMessage,
805
- );
806
- return true;
807
- }
808
- } catch (error) {
809
- if (!hasAccess()) return true;
810
- logThreadOutboxUploadFailure(queuedMessage, error);
811
- if (!shouldRetryThreadOutboxDelivery(error)) {
812
- return restoreQueuedMessage(
813
- queuedMessage,
814
- error instanceof Error ? error.message : "An attachment could not upload.",
815
- );
816
- }
817
- return false;
818
- }
819
- if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
820
- return true;
706
+ // A delivery that throws backs off like any failure. Releasing the slot
707
+ // without a retry would re-run the drain straight into the same message.
708
+ const settle = (messageId: MessageId, delivery: Promise<boolean>): void => {
709
+ void delivery
710
+ .then(
711
+ (sent) => (sent ? clearRetry(messageId) : scheduleRetry(messageId)),
712
+ (error: unknown) => {
713
+ console.warn("[thread-outbox] queued message delivery threw", { messageId, error });
714
+ scheduleRetry(messageId);
715
+ },
716
+ )
717
+ .finally(() => finishDispatchingQueuedMessage(messageId));
718
+ };
719
+
720
+ // An over-cap draft blocks recovery until the user changes its attachments;
721
+ // parking on the draft avoids hammering the restore with backoff retries.
722
+ const restoreQueuedMessage = async (
723
+ queuedMessage: QueuedThreadMessage,
724
+ message: string,
725
+ ): Promise<boolean> => {
726
+ const result = await restoreRejectedQueuedMessage(queuedMessage, message);
727
+ if (result !== "blocked") {
728
+ return result !== "retry";
729
+ }
730
+ if (disposed || blockedRecoveries.has(queuedMessage.messageId)) {
731
+ return true;
732
+ }
733
+ const draftKey = recoveryDraftKey(queuedMessage);
734
+ const editorDraftKey = queuedMessage.creation
735
+ ? `pending-task:${queuedMessage.messageId}`
736
+ : null;
737
+ const currentDrafts = appAtomRegistry.get(composerDraftsAtom);
738
+ const blockedAttachments = currentDrafts[draftKey]?.attachments;
739
+ const editorAttachments =
740
+ editorDraftKey === null ? undefined : currentDrafts[editorDraftKey]?.attachments;
741
+ const unsubscribe = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) => {
742
+ if (
743
+ drafts[draftKey]?.attachments === blockedAttachments &&
744
+ (editorDraftKey === null || drafts[editorDraftKey]?.attachments === editorAttachments)
745
+ ) {
746
+ return;
747
}
822
- const currentConfig = appAtomRegistry.get(
823
- serverEnvironment.configValueAtom(queuedMessage.environmentId),
824
- );
825
- if (!currentConfig) return false;
826
- if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, thread.projectId)) {
827
- const { title, detail } = describeUnavailableModelSelection(
828
- currentConfig,
829
- settings.modelSelection,
830
- thread.projectId,
831
- );
832
- return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`);
748
+ const active = blockedRecoveries.get(queuedMessage.messageId);
749
+ if (!active) {
750
+ return;
751
}
834
- const sendSettings = resolveQueuedThreadSettings(
835
- queuedMessage,
836
- settings,
837
- currentConfig.providers,
752
+ blockedRecoveries.delete(queuedMessage.messageId);
753
+ active.unsubscribe();
754
+ drain();
755
+ });
756
+ blockedRecoveries.set(queuedMessage.messageId, { message: queuedMessage, unsubscribe });
757
+ return true;
758
+ };
759
+
760
+ const sendQueuedMessage = async (
761
+ queuedMessage: QueuedThreadMessage,
762
+ thread: EnvironmentThreadShell,
763
+ ): Promise<boolean> => {
764
+ const hasAccess = () =>
765
+ readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope);
766
+ if (!hasAccess()) return true;
767
+ const serverConfig = appAtomRegistry.get(
768
+ serverEnvironment.configValueAtom(queuedMessage.environmentId),
769
+ );
770
+ if (!serverConfig) return false;
771
+ const settings = resolveQueuedThreadSettings(queuedMessage, thread, serverConfig.providers);
772
+ if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, thread.projectId)) {
773
+ const { title, detail } = describeUnavailableModelSelection(
774
+ serverConfig,
775
+ settings.modelSelection,
776
+ thread.projectId,
777
);
778
+ return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
779
+ }
780
+
781
+ if (settings.runtimeMode !== thread.runtimeMode) {
782
if (!hasAccess()) return true;
840
- const deliveryResult = await startTurn({
783
+ const runtimeResult = await runDeliveryCommand(threadEnvironment.setRuntimeMode, {
784
environmentId: queuedMessage.environmentId,
785
input: {
843
- commandId: queuedMessage.commandId,
844
- creationSource: "mobile",
786
+ commandId: settingsCommandId(queuedMessage, "runtime-mode"),
787
threadId: queuedMessage.threadId,
846
- message: {
847
- messageId: queuedMessage.messageId,
848
- role: "user",
849
- ...serializeComposerMessageForServer(
850
- queuedMessage.text,
851
- uploadedComposerContext(
852
- queuedMessage.context,
853
- queuedMessage.attachments,
854
- prepared.attachments,
855
- ),
856
- currentConfig.environment.capabilities.inlineMessageContext === true,
857
- ),
858
- attachments: prepared.attachments,
859
- },
860
- modelSelection: sendSettings.modelSelection,
861
- titleSeed: deriveThreadTitleSeed({
862
- text: queuedMessage.text,
863
- attachments: queuedMessage.attachments,
864
- }),
865
- runtimeMode: sendSettings.runtimeMode,
866
- interactionMode: sendSettings.interactionMode,
788
+ runtimeMode: settings.runtimeMode,
789
createdAt: queuedMessage.createdAt,
868
- dispatchMode: queuedMessage.dispatchMode ?? "start",
790
},
791
});
871
- if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
872
- const failure = reportFailure(deliveryResult, "start-turn");
873
- if (failure?.action === "retry") {
792
+ if (AsyncResult.isFailure(runtimeResult)) {
793
+ reportCommandFailure(queuedMessage, runtimeResult, "settings-sync");
794
return false;
795
}
876
- if (failure?.action === "restore") {
877
- return restoreQueuedMessage(persistedMessage, failure.message);
878
- }
879
- acknowledgedExistingThreadMessageIdsRef.current.add(persistedMessage.messageId);
880
- const delivered =
881
- (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";
882
- if (delivered) {
883
- acknowledgedExistingThreadMessageIdsRef.current.delete(persistedMessage.messageId);
884
- }
885
- return delivered;
886
- },
887
- [
888
- makeDeliveryHelpers,
889
- setThreadInteractionMode,
890
- setThreadRuntimeMode,
891
- startTurn,
892
- restoreQueuedMessage,
893
- ],
894
- );
796
+ }
797
896
- const sendQueuedCreation = useCallback(
897
- async (
898
- queuedMessage: QueuedThreadMessage,
899
- creation: QueuedThreadCreation,
900
- projectCwd: string,
901
- ) => {
902
- const hasAccess = () =>
903
- readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope);
798
+ if (settings.interactionMode !== thread.interactionMode) {
799
if (!hasAccess()) return true;
905
- const modelSelection = queuedMessage.modelSelection;
906
- if (modelSelection === undefined) {
800
+ const interactionResult = await runDeliveryCommand(threadEnvironment.setInteractionMode, {
801
+ environmentId: queuedMessage.environmentId,
802
+ input: {
803
+ commandId: settingsCommandId(queuedMessage, "interaction-mode"),
804
+ threadId: queuedMessage.threadId,
805
+ interactionMode: settings.interactionMode,
806
+ createdAt: queuedMessage.createdAt,
807
+ },
808
+ });
809
+ if (AsyncResult.isFailure(interactionResult)) {
810
+ reportCommandFailure(queuedMessage, interactionResult, "settings-sync");
811
return false;
812
}
909
- const serverConfig = appAtomRegistry.get(
910
- serverEnvironment.configValueAtom(queuedMessage.environmentId),
911
- );
912
- if (!serverConfig) return false;
913
- const settings = resolveQueuedThreadSettings(
813
+ }
814
+
815
+ let prepared: PreparedTurnAttachments;
816
+ let persistedMessage: QueuedThreadMessage;
817
+ let deliveryRevision: number;
818
+ if (!hasAccess()) return true;
819
+ try {
820
+ const preparedResult = await prepareQueuedMessageAttachments(
821
queuedMessage,
915
- {
916
- modelSelection,
917
- runtimeMode: DEFAULT_RUNTIME_MODE,
918
- interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
919
- },
920
- serverConfig.providers,
822
+ serverConfig.environment.capabilities.attachmentUploads === true,
823
);
922
- if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, creation.projectId)) {
923
- const { title, detail } = describeUnavailableModelSelection(
924
- serverConfig,
925
- settings.modelSelection,
926
- creation.projectId,
927
- );
928
- return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
929
- }
930
- let prepared: PreparedTurnAttachments;
931
- let persistedMessage: QueuedThreadMessage;
932
- let deliveryRevision: number;
933
- try {
934
- const preparedResult = await prepareQueuedMessageAttachments(
935
- queuedMessage,
936
- serverConfig.environment.capabilities.attachmentUploads === true,
937
- );
938
- if (preparedResult.status === "abandoned") {
939
- return true;
940
- }
941
- prepared = preparedResult.prepared;
942
- persistedMessage = preparedResult.persistedMessage;
943
- deliveryRevision = preparedResult.deliveryRevision;
944
- if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
945
- await preserveUploadedAttachmentsForEditor(
946
- queuedMessage,
947
- preparedResult.persistedMessage,
948
- );
949
- return true;
950
- }
951
- } catch (error) {
952
- if (!hasAccess()) return true;
953
- logThreadOutboxUploadFailure(queuedMessage, error);
954
- if (!shouldRetryThreadOutboxDelivery(error)) {
955
- return restoreQueuedMessage(
956
- queuedMessage,
957
- error instanceof Error ? error.message : "An attachment could not upload.",
958
- );
959
- }
960
- return false;
824
+ if (preparedResult.status === "abandoned") {
825
+ return true;
826
}
962
- if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
827
+ prepared = preparedResult.prepared;
828
+ persistedMessage = preparedResult.persistedMessage;
829
+ deliveryRevision = preparedResult.deliveryRevision;
830
+ if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
831
+ await preserveUploadedAttachmentsForEditor(queuedMessage, preparedResult.persistedMessage);
832
return true;
833
}
965
- const currentConfig = appAtomRegistry.get(
966
- serverEnvironment.configValueAtom(queuedMessage.environmentId),
967
- );
968
- if (!currentConfig) return false;
969
- if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, creation.projectId)) {
970
- const { title, detail } = describeUnavailableModelSelection(
971
- currentConfig,
972
- settings.modelSelection,
973
- creation.projectId,
834
+ } catch (error) {
835
+ if (!hasAccess()) return true;
836
+ logThreadOutboxUploadFailure(queuedMessage, error);
837
+ if (!shouldRetryThreadOutboxDelivery(error)) {
838
+ return restoreQueuedMessage(
839
+ queuedMessage,
840
+ error instanceof Error ? error.message : "An attachment could not upload.",
841
);
975
- return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`);
842
}
977
- const sendSettings = resolveQueuedThreadSettings(
978
- queuedMessage,
979
- settings,
980
- currentConfig.providers,
843
+ return false;
844
+ }
845
+ if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
846
+ return true;
847
+ }
848
+ const currentConfig = appAtomRegistry.get(
849
+ serverEnvironment.configValueAtom(queuedMessage.environmentId),
850
+ );
851
+ if (!currentConfig) return false;
852
+ if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, thread.projectId)) {
853
+ const { title, detail } = describeUnavailableModelSelection(
854
+ currentConfig,
855
+ settings.modelSelection,
856
+ thread.projectId,
857
);
982
- if (!hasAccess()) return true;
983
- const { reportFailure } = makeDeliveryHelpers(queuedMessage);
984
- let workspace = creation;
985
- if (creation.pullRequestReference) {
986
- const checkout = await preparePullRequest({
987
- environmentId: queuedMessage.environmentId,
988
- input: { cwd: projectCwd, reference: creation.pullRequestReference, mode: "worktree" },
989
- });
990
- if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) || !hasAccess())
991
- return true;
992
- const failure = reportFailure(checkout, "start-turn");
993
- if (failure?.action === "retry") return false;
994
- if (failure?.action === "restore")
995
- return restoreQueuedMessage(persistedMessage, failure.message);
996
- if (!AsyncResult.isSuccess(checkout)) return false;
997
- if (!checkout.value.worktreePath || !checkout.value.isOnPullRequestHead) {
998
- const { shortLabel } = (
999
- sourceControlClients.findByChangeRequestUrl(creation.pullRequestReference) ??
1000
- sourceControlClients.get(undefined)
1001
- ).changeRequest;
1002
- return restoreQueuedMessage(
1003
- persistedMessage,
1004
- `The ${shortLabel} worktree has local changes and could not update to the ${shortLabel} head. Resolve them before trying again.`,
1005
- );
1006
- }
1007
- workspace = {
1008
- ...creation,
1009
- workspaceMode: "local",
1010
- branch: checkout.value.branch,
1011
- worktreePath: checkout.value.worktreePath,
1012
- startFromOrigin: false,
1013
- };
1014
- }
1015
- const deliveryResult = await startTurn({
1016
- environmentId: queuedMessage.environmentId,
1017
- input: buildProjectThreadStartTurnInput({
1018
- projectId: creation.projectId,
1019
- projectCwd,
1020
- threadId: queuedMessage.threadId,
1021
- commandId: queuedMessage.commandId,
858
+ return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`);
859
+ }
860
+ const sendSettings = resolveQueuedThreadSettings(
861
+ queuedMessage,
862
+ settings,
863
+ currentConfig.providers,
864
+ );
865
+ if (!hasAccess()) return true;
866
+ const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, {
867
+ environmentId: queuedMessage.environmentId,
868
+ input: {
869
+ commandId: queuedMessage.commandId,
870
+ creationSource: "mobile",
871
+ threadId: queuedMessage.threadId,
872
+ message: {
873
messageId: queuedMessage.messageId,
1023
- createdAt: queuedMessage.createdAt,
1024
- titleText: queuedMessage.text,
874
+ role: "user",
875
...serializeComposerMessageForServer(
1026
- queuedMessage.text.trim(),
876
+ queuedMessage.text,
877
uploadedComposerContext(
878
queuedMessage.context,
879
queuedMessage.attachments,
@@ -1031,58 +881,235 @@ export function useThreadOutboxDrain(): void {
881
),
882
currentConfig.environment.capabilities.inlineMessageContext === true,
883
),
1034
- uploadedAttachments: prepared.attachments,
1035
- modelSelection: sendSettings.modelSelection,
1036
- runtimeMode: sendSettings.runtimeMode,
1037
- interactionMode: sendSettings.interactionMode,
1038
- workspaceMode: workspace.workspaceMode,
1039
- branch: workspace.branch,
1040
- worktreePath: workspace.worktreePath,
1041
- startFromOrigin: workspace.startFromOrigin ?? false,
1042
- worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
884
+ attachments: prepared.attachments,
885
+ },
886
+ modelSelection: sendSettings.modelSelection,
887
+ titleSeed: deriveThreadTitleSeed({
888
+ text: queuedMessage.text,
889
+ attachments: queuedMessage.attachments,
890
}),
1044
- });
1045
- if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
1046
- const failure = reportFailure(deliveryResult, "start-turn");
1047
- if (failure?.action === "retry") {
1048
- return false;
891
+ runtimeMode: sendSettings.runtimeMode,
892
+ interactionMode: sendSettings.interactionMode,
893
+ createdAt: queuedMessage.createdAt,
894
+ dispatchMode: queuedMessage.dispatchMode ?? "start",
895
+ },
896
+ });
897
+ if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
898
+ const failure = reportCommandFailure(queuedMessage, deliveryResult, "start-turn");
899
+ if (failure?.action === "retry") {
900
+ return false;
901
+ }
902
+ if (failure?.action === "restore") {
903
+ return restoreQueuedMessage(persistedMessage, failure.message);
904
+ }
905
+ acknowledgedExistingThreadMessageIds.add(persistedMessage.messageId);
906
+ const delivered =
907
+ (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";
908
+ if (delivered) {
909
+ acknowledgedExistingThreadMessageIds.delete(persistedMessage.messageId);
910
+ }
911
+ return delivered;
912
+ };
913
+
914
+ const sendQueuedCreation = async (
915
+ queuedMessage: QueuedThreadMessage,
916
+ creation: QueuedThreadCreation,
917
+ projectCwd: string,
918
+ ): Promise<boolean> => {
919
+ const hasAccess = () =>
920
+ readEnvironmentScope(queuedMessage.environmentId, AuthOrchestrationOperateScope);
921
+ if (!hasAccess()) return true;
922
+ const modelSelection = queuedMessage.modelSelection;
923
+ if (modelSelection === undefined) {
924
+ return false;
925
+ }
926
+ const serverConfig = appAtomRegistry.get(
927
+ serverEnvironment.configValueAtom(queuedMessage.environmentId),
928
+ );
929
+ if (!serverConfig) return false;
930
+ const settings = resolveQueuedThreadSettings(
931
+ queuedMessage,
932
+ {
933
+ modelSelection,
934
+ runtimeMode: DEFAULT_RUNTIME_MODE,
935
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
936
+ },
937
+ serverConfig.providers,
938
+ );
939
+ if (isModelSelectionUnavailable(serverConfig, settings.modelSelection, creation.projectId)) {
940
+ const { title, detail } = describeUnavailableModelSelection(
941
+ serverConfig,
942
+ settings.modelSelection,
943
+ creation.projectId,
944
+ );
945
+ return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
946
+ }
947
+ let prepared: PreparedTurnAttachments;
948
+ let persistedMessage: QueuedThreadMessage;
949
+ let deliveryRevision: number;
950
+ try {
951
+ const preparedResult = await prepareQueuedMessageAttachments(
952
+ queuedMessage,
953
+ serverConfig.environment.capabilities.attachmentUploads === true,
954
+ );
955
+ if (preparedResult.status === "abandoned") {
956
+ return true;
957
}
1050
- if (failure?.action === "restore") {
958
+ prepared = preparedResult.prepared;
959
+ persistedMessage = preparedResult.persistedMessage;
960
+ deliveryRevision = preparedResult.deliveryRevision;
961
+ if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
962
+ await preserveUploadedAttachmentsForEditor(queuedMessage, preparedResult.persistedMessage);
963
+ return true;
964
+ }
965
+ } catch (error) {
966
+ if (!hasAccess()) return true;
967
+ logThreadOutboxUploadFailure(queuedMessage, error);
968
+ if (!shouldRetryThreadOutboxDelivery(error)) {
969
+ return restoreQueuedMessage(
970
+ queuedMessage,
971
+ error instanceof Error ? error.message : "An attachment could not upload.",
972
+ );
973
+ }
974
+ return false;
975
+ }
976
+ if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
977
+ return true;
978
+ }
979
+ const currentConfig = appAtomRegistry.get(
980
+ serverEnvironment.configValueAtom(queuedMessage.environmentId),
981
+ );
982
+ if (!currentConfig) return false;
983
+ if (isModelSelectionUnavailable(currentConfig, settings.modelSelection, creation.projectId)) {
984
+ const { title, detail } = describeUnavailableModelSelection(
985
+ currentConfig,
986
+ settings.modelSelection,
987
+ creation.projectId,
988
+ );
989
+ return restoreQueuedMessage(persistedMessage, `${title}. ${detail}`);
990
+ }
991
+ const sendSettings = resolveQueuedThreadSettings(
992
+ queuedMessage,
993
+ settings,
994
+ currentConfig.providers,
995
+ );
996
+ if (!hasAccess()) return true;
997
+ let workspace = creation;
998
+ if (creation.pullRequestReference) {
999
+ const checkout = await runDeliveryCommand(gitEnvironment.preparePullRequestThread, {
1000
+ environmentId: queuedMessage.environmentId,
1001
+ input: { cwd: projectCwd, reference: creation.pullRequestReference, mode: "worktree" },
1002
+ });
1003
+ if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision) || !hasAccess())
1004
+ return true;
1005
+ const failure = reportCommandFailure(queuedMessage, checkout, "start-turn");
1006
+ if (failure?.action === "retry") return false;
1007
+ if (failure?.action === "restore")
1008
return restoreQueuedMessage(persistedMessage, failure.message);
1009
+ if (!AsyncResult.isSuccess(checkout)) return false;
1010
+ if (!checkout.value.worktreePath || !checkout.value.isOnPullRequestHead) {
1011
+ const { shortLabel } = (
1012
+ sourceControlClients.findByChangeRequestUrl(creation.pullRequestReference) ??
1013
+ sourceControlClients.get(undefined)
1014
+ ).changeRequest;
1015
+ return restoreQueuedMessage(
1016
+ persistedMessage,
1017
+ `The ${shortLabel} worktree has local changes and could not update to the ${shortLabel} head. Resolve them before trying again.`,
1018
+ );
1019
}
1053
- recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage });
1054
- const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision);
1055
- if (outcome === "edited") {
1056
- if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
1057
- return true;
1058
- }
1059
- return recoverEditedCreationAfterDelivery(persistedMessage);
1020
+ workspace = {
1021
+ ...creation,
1022
+ workspaceMode: "local",
1023
+ branch: checkout.value.branch,
1024
+ worktreePath: checkout.value.worktreePath,
1025
+ startFromOrigin: false,
1026
+ };
1027
+ }
1028
+ const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, {
1029
+ environmentId: queuedMessage.environmentId,
1030
+ input: buildProjectThreadStartTurnInput({
1031
+ projectId: creation.projectId,
1032
+ projectCwd,
1033
+ threadId: queuedMessage.threadId,
1034
+ commandId: queuedMessage.commandId,
1035
+ messageId: queuedMessage.messageId,
1036
+ createdAt: queuedMessage.createdAt,
1037
+ titleText: queuedMessage.text,
1038
+ ...serializeComposerMessageForServer(
1039
+ queuedMessage.text.trim(),
1040
+ uploadedComposerContext(
1041
+ queuedMessage.context,
1042
+ queuedMessage.attachments,
1043
+ prepared.attachments,
1044
+ ),
1045
+ currentConfig.environment.capabilities.inlineMessageContext === true,
1046
+ ),
1047
+ uploadedAttachments: prepared.attachments,
1048
+ modelSelection: sendSettings.modelSelection,
1049
+ runtimeMode: sendSettings.runtimeMode,
1050
+ interactionMode: sendSettings.interactionMode,
1051
+ workspaceMode: workspace.workspaceMode,
1052
+ branch: workspace.branch,
1053
+ worktreePath: workspace.worktreePath,
1054
+ startFromOrigin: workspace.startFromOrigin ?? false,
1055
+ worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
1056
+ }),
1057
+ });
1058
+ if (AsyncResult.isFailure(deliveryResult) && !hasAccess()) return true;
1059
+ const failure = reportCommandFailure(queuedMessage, deliveryResult, "start-turn");
1060
+ if (failure?.action === "retry") {
1061
+ return false;
1062
+ }
1063
+ if (failure?.action === "restore") {
1064
+ return restoreQueuedMessage(persistedMessage, failure.message);
1065
+ }
1066
+ recordPendingThreadCreationOutcome({ kind: "delivered", message: persistedMessage });
1067
+ const outcome = await completeQueuedMessageDelivery(persistedMessage, deliveryRevision);
1068
+ if (outcome === "edited") {
1069
+ if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
1070
+ return true;
1071
}
1061
- return outcome === "removed";
1062
- },
1063
- [makeDeliveryHelpers, preparePullRequest, restoreQueuedMessage, startTurn],
1064
- );
1072
+ return recoverEditedCreationAfterDelivery(persistedMessage);
1073
+ }
1074
+ return outcome === "removed";
1075
+ };
1076
1066
- // Subscribe to outcomes; they may arrive after the last shell update, leaving read-once entries uncollected.
1067
- useEffect(() => {
1068
- for (const [threadKey, outcome] of Object.entries(creationOutcomes)) {
1069
- if (
1070
- outcome.kind === "delivered" &&
1071
- threads.some(
1072
- (thread) =>
1073
- scopedThreadKey(thread.environmentId, thread.id) === threadKey &&
1074
- (thread.latestRun !== null ||
1075
- thread.runtime?.status === "failed" ||
1076
- thread.runtime?.status === "cancelled" ||
1077
- thread.runtime?.status === "interrupted"),
1078
- )
1079
- ) {
1080
- clearPendingThreadCreationOutcome(threadKey);
1081
- }
1077
+ // A pass writes atoms the pass reads (family mounts, the dispatch slot), and the registry
1078
+ // notifies subscribers synchronously, so drain() can be called from inside a pass. That call
1079
+ // only asks for another pass; a nested pass would decide from inputs the outer one is still
1080
+ // acting on and could start a second delivery.
1081
+ let draining = false;
1082
+ let drainRequested = false;
1083
+ function drain(): void {
1084
+ if (disposed) return;
1085
+ if (draining) {
1086
+ drainRequested = true;
1087
+ return;
1088
+ }
1089
+ draining = true;
1090
+ try {
1091
+ do {
1092
+ if (disposed) return;
1093
+ drainRequested = false;
1094
+ drainPass();
1095
+ } while (drainRequested);
1096
+ } finally {
1097
+ draining = false;
1098
}
1083
- }, [creationOutcomes, threads]);
1099
+ }
1100
1085
- useEffect(() => {
1101
+ function drainPass(): void {
1102
+ const {
1103
+ dispatchingQueuedMessageId,
1104
+ editingQueuedMessageIds,
1105
+ queuedMessagesByThreadKey,
1106
+ shellStatuses,
1107
+ threads,
1108
+ projects,
1109
+ serverConfigs,
1110
+ connectedEnvironments,
1111
+ operableEnvironments,
1112
+ } = appAtomRegistry.get(deliveryInputsAtom);
1113
if (dispatchingQueuedMessageId !== null) {
1114
return;
1115
}
@@ -1092,15 +1119,15 @@ export function useThreadOutboxDrain(): void {
1119
.flat()
1120
.map((message) => message.messageId),
1121
);
1095
- for (const messageId of acknowledgedExistingThreadMessageIdsRef.current) {
1122
+ for (const messageId of acknowledgedExistingThreadMessageIds) {
1123
if (!queuedMessageIds.has(messageId)) {
1097
- acknowledgedExistingThreadMessageIdsRef.current.delete(messageId);
1124
+ acknowledgedExistingThreadMessageIds.delete(messageId);
1125
}
1126
}
1100
- for (const [messageId, release] of familyMountsRef.current) {
1127
+ for (const [messageId, release] of familyMounts) {
1128
if (!queuedMessageIds.has(messageId)) {
1129
release();
1103
- familyMountsRef.current.delete(messageId);
1130
+ familyMounts.delete(messageId);
1131
}
1132
}
1133
@@ -1109,48 +1136,36 @@ export function useThreadOutboxDrain(): void {
1136
if (!nextQueuedMessage) {
1137
continue;
1138
}
1139
+ const messageId = nextQueuedMessage.messageId;
1140
if (
1141
nextQueuedMessage.creation === undefined &&
1114
- acknowledgedExistingThreadMessageIdsRef.current.has(nextQueuedMessage.messageId)
1142
+ acknowledgedExistingThreadMessageIds.has(messageId)
1143
) {
1116
- if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
1144
+ if (retryNotBefore(messageId) > Date.now()) {
1145
continue;
1146
}
1119
- beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
1120
- void removeAcknowledgedExistingThreadMessage(
1121
- nextQueuedMessage,
1122
- acknowledgedExistingThreadMessageIdsRef.current,
1123
- )
1124
- .then((removed) => {
1125
- if (!removed) {
1126
- scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1127
- return;
1128
- }
1129
- retryAttemptRef.current.delete(nextQueuedMessage.messageId);
1130
- retryNotBeforeRef.current.delete(nextQueuedMessage.messageId);
1131
- const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);
1132
- if (pendingTimer !== undefined) {
1133
- clearTimeout(pendingTimer);
1134
- retryTimersRef.current.delete(nextQueuedMessage.messageId);
1135
- }
1136
- })
1137
- .finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId));
1147
+ beginDispatchingQueuedMessage(messageId);
1148
+ settle(
1149
+ messageId,
1150
+ removeAcknowledgedExistingThreadMessage(
1151
+ nextQueuedMessage,
1152
+ acknowledgedExistingThreadMessageIds,
1153
+ ),
1154
+ );
1155
return;
1156
}
1140
- if (editingQueuedMessageIds[nextQueuedMessage.messageId]) {
1157
+ if (editingQueuedMessageIds[messageId]) {
1158
continue;
1159
}
1143
- const blockedRecovery = blockedRecoverySubscriptionsRef.current.get(
1144
- nextQueuedMessage.messageId,
1145
- );
1160
+ const blockedRecovery = blockedRecoveries.get(messageId);
1161
if (blockedRecovery) {
1162
if (blockedRecovery.message === nextQueuedMessage) {
1163
continue;
1164
}
1150
- blockedRecoverySubscriptionsRef.current.delete(nextQueuedMessage.messageId);
1165
+ blockedRecoveries.delete(messageId);
1166
blockedRecovery.unsubscribe();
1167
}
1153
- if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
1168
+ if (retryNotBefore(messageId) > Date.now()) {
1169
continue;
1170
}
1171
@@ -1173,8 +1188,8 @@ export function useThreadOutboxDrain(): void {
1188
) {
1189
// The family keeps the row readable through dispatch once it loads; the current shell
1190
// generation's read decides whether the thread is gone.
1176
- if (!familyMountsRef.current.has(nextQueuedMessage.messageId)) {
1177
- familyMountsRef.current.set(
1191
+ if (!familyMounts.has(nextQueuedMessage.messageId)) {
1192
+ familyMounts.set(
1193
nextQueuedMessage.messageId,
1194
threadFamilies.mount(
1195
appAtomRegistry,
@@ -1189,8 +1204,8 @@ export function useThreadOutboxDrain(): void {
1204
),
1205
);
1206
if (familyRead === "settled") {
1192
- // The rows from this render can lag the family that just settled; decide from the
1193
- // merged rows as they are now.
1207
+ // The rows read at the start of this pass can lag the family that just settled;
1208
+ // decide from the merged rows as they are now.
1209
thread = findThread(
1210
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
1211
nextQueuedMessage,
@@ -1218,7 +1233,7 @@ export function useThreadOutboxDrain(): void {
1233
familyRead !== "settled"
1234
) {
1235
// An empty family read changes no merged row, so nothing else would wake the drain.
1221
- scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1236
+ scheduleRetry(messageId);
1237
continue;
1238
}
1239
if (deliveryAction === "send" && !operableEnvironments.has(nextQueuedMessage.environmentId)) {
@@ -1240,28 +1255,20 @@ export function useThreadOutboxDrain(): void {
1255
continue;
1256
}
1257
if (dispatchStep.step === "retry") {
1243
- scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1258
+ scheduleRetry(messageId);
1259
continue;
1260
}
1261
if (dispatchStep.step === "restore") {
1262
const attachmentError = dispatchStep.reason;
1248
- beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
1249
- void confirmThreadOutboxMessageQueued(nextQueuedMessage)
1250
- .then((queued) => {
1251
- if (
1252
- !queued ||
1253
- appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]
1254
- ) {
1255
- return true;
1256
- }
1257
- return restoreQueuedMessage(nextQueuedMessage, attachmentError);
1258
- })
1259
- .then((restored) => {
1260
- if (!restored) {
1261
- scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1262
- }
1263
- })
1264
- .finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId));
1263
+ beginDispatchingQueuedMessage(messageId);
1264
+ settle(
1265
+ messageId,
1266
+ confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) =>
1267
+ !queued || appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId]
1268
+ ? true
1269
+ : restoreQueuedMessage(nextQueuedMessage, attachmentError),
1270
+ ),
1271
+ );
1272
return;
1273
}
1274
const creationProjectCwd =
@@ -1279,7 +1286,7 @@ export function useThreadOutboxDrain(): void {
1286
}
1287
}
1288
1282
- beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
1289
+ beginDispatchingQueuedMessage(messageId);
1290
const removeQueuedMessage = (warning: string) =>
1291
removeThreadOutboxMessage(nextQueuedMessage).then(
1292
() => true,
@@ -1287,7 +1294,7 @@ export function useThreadOutboxDrain(): void {
1294
console.warn(warning, {
1295
environmentId: nextQueuedMessage.environmentId,
1296
threadId: nextQueuedMessage.threadId,
1290
- messageId: nextQueuedMessage.messageId,
1297
+ messageId,
1298
error,
1299
});
1300
return false;
@@ -1299,7 +1306,7 @@ export function useThreadOutboxDrain(): void {
1306
return true;
1307
}
1308
// Re-check editor ownership after confirmation; return true to defer without failure backoff.
1302
- if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
1309
+ if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[messageId]) {
1310
return true;
1311
}
1312
if (deliveryAction === "send") {
@@ -1307,13 +1314,12 @@ export function useThreadOutboxDrain(): void {
1314
appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
1315
nextQueuedMessage,
1316
);
1310
- const liveThreadBusy = threadRuntimeIsActive(liveThread?.runtime);
1317
const liveDeliveryAction = resolveThreadOutboxDeliveryAction({
1318
isCreation: creation !== undefined,
1319
threadExists: liveThread !== undefined,
1320
shellStatus,
1321
environmentConnected: environment?.connectionState === "connected",
1316
- threadBusy: liveThreadBusy,
1322
+ threadBusy: threadRuntimeIsActive(liveThread?.runtime),
1323
});
1324
if (liveDeliveryAction !== "send") {
1325
return true;
@@ -1332,41 +1338,57 @@ export function useThreadOutboxDrain(): void {
1338
? sendQueuedMessage(nextQueuedMessage, thread)
1339
: Promise.resolve(false);
1340
});
1335
- void delivery
1336
- .then((sent) => {
1337
- if (sent) {
1338
- retryAttemptRef.current.delete(nextQueuedMessage.messageId);
1339
- retryNotBeforeRef.current.delete(nextQueuedMessage.messageId);
1340
- const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);
1341
- if (pendingTimer !== undefined) {
1342
- clearTimeout(pendingTimer);
1343
- retryTimersRef.current.delete(nextQueuedMessage.messageId);
1344
- }
1345
- return;
1346
- }
1347
-
1348
- scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1349
- })
1350
- .finally(() => {
1351
- finishDispatchingQueuedMessage(nextQueuedMessage.messageId);
1352
- });
1341
+ settle(messageId, delivery);
1342
return;
1343
}
1355
- }, [
1356
- connectedEnvironments,
1357
- dispatchingQueuedMessageId,
1358
- editingQueuedMessageIds,
1359
- operableEnvironments,
1360
- projects,
1361
- queuedMessagesByThreadKey,
1362
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retryTick re-runs the drain when a retry timer fires.
1363
- retryTick,
1364
- restoreQueuedMessage,
1365
- scheduleQueuedMessageRetry,
1366
- sendQueuedCreation,
1367
- sendQueuedMessage,
1368
- serverConfigs,
1369
- shellStatuses,
1370
- threads,
1371
- ]);
1344
+ }
1345
+
1346
+ const stopDraining = appAtomRegistry.subscribe(deliveryInputsAtom, drain, { immediate: true });
1347
+ const stopCollectingOutcomes = appAtomRegistry.subscribe(
1348
+ settledCreationOutcomeKeysAtom,
1349
+ (threadKeys) => {
1350
+ for (const threadKey of threadKeys) clearPendingThreadCreationOutcome(threadKey);
1351
+ },
1352
+ { immediate: true },
1353
+ );
1354
+
1355
+ return {
1356
+ drain,
1357
+ dispose: () => {
1358
+ disposed = true;
1359
+ stopDraining();
1360
+ stopCollectingOutcomes();
1361
+ for (const retry of retries.values()) clearTimeout(retry.timer);
1362
+ retries.clear();
1363
+ for (const blocked of blockedRecoveries.values()) blocked.unsubscribe();
1364
+ blockedRecoveries.clear();
1365
+ for (const release of familyMounts.values()) release();
1366
+ familyMounts.clear();
1367
+ },
1368
+ };
1369
+}
1370
+
1371
+function loadThreadOutbox(isActive: () => boolean): void {
1372
+ void threadOutboxManager.load().then((loaded) => {
1373
+ if (loaded || !isActive()) return;
1374
+ Dialog.alert(
1375
+ "Some queued messages could not be loaded",
1376
+ "Unreadable records and attachment files are still saved. Other messages can still be sent.",
1377
+ [
1378
+ { text: "Dismiss", style: "cancel" },
1379
+ { text: "Retry", onPress: () => loadThreadOutbox(isActive) },
1380
+ ],
1381
+ );
1382
+ });
1383
+}
1384
+
1385
+/** App-lifetime: loads the persisted outbox and delivers queued messages. */
1386
+export function installThreadOutboxDelivery(): () => void {
1387
+ let active = true;
1388
+ loadThreadOutbox(() => active);
1389
+ const delivery = createThreadOutboxDelivery();
1390
+ return () => {
1391
+ active = false;
1392
+ delivery.dispose();
1393
+ };
1394
}
apps/mobile/src/state/use-thread-outbox.ts
+1
-5
@@ -7,7 +7,7 @@ import { appAtomRegistry } from "./atom-registry";
7
import { environmentShell } from "./shell";
8
import { threadOutboxManager } from "./thread-outbox";
9
10
-const threadOutboxShellStatusesAtom = Atom.make(
10
+export const threadOutboxShellStatusesAtom = Atom.make(
11
(get): ReadonlyMap<EnvironmentId, EnvironmentShellStatus> => {
12
const statuses = new Map<EnvironmentId, EnvironmentShellStatus>();
13
for (const queue of Object.values(get(threadOutboxManager.queuedMessagesByThreadKeyAtom))) {
@@ -68,7 +68,3 @@ export const queuedThreadKeysAtom = Atom.make((get): ReadonlySet<string> => {
68
export function useQueuedThreadKeys(): ReadonlySet<string> {
69
return useAtomValue(queuedThreadKeysAtom);
70
}
71
-
72
-export function useThreadOutboxShellStatuses() {
73
- return useAtomValue(threadOutboxShellStatusesAtom);
74
-}