Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 threadRuntimeIsActive,
4 type EnvironmentProject,
5 type EnvironmentThreadShell,
6} from "@t3tools/client-runtime/state/shell";
7import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
8import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
9import {
10 CommandId,
11 DEFAULT_PROVIDER_INTERACTION_MODE,
12 DEFAULT_RUNTIME_MODE,
13 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
14 type MessageId,
15} from "@t3tools/contracts";
16import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
17import * as Cause from "effect/Cause";
18import { AsyncResult } from "effect/reactivity";
19import { useCallback, useEffect, useRef, useState } from "react";
20import { Alert } from "react-native";
21
22import { createDebugLogger } from "../lib/debugLog";
23import { scopedThreadKey } from "../lib/scopedEntities";
24import { buildProjectThreadStartTurnInput } from "../lib/projectThreadStartTurn";
25import { serializeComposerMessageForServer, uploadedComposerContext } from "../lib/composerContext";
26import { prepareTurnAttachments, type PreparedTurnAttachments } from "../lib/attachmentUpload";
27import { randomHex } from "../lib/uuid";
28import { isModelSelectionUnavailable } from "../lib/modelOptions";
29import {
30 retainAcknowledgedThreadMessage,
31 forgetAcknowledgedThreadMessage,
32} from "./acknowledged-thread-messages";
33import { appAtomRegistry } from "./atom-registry";
34import { restoredNewTaskDraftKey } from "./new-task-draft-key";
35import { useProjects, useServerConfigs, useThreadShells } from "./entities";
36import {
37 clearPendingThreadCreationOutcome,
38 pendingThreadCreationOutcomesAtom,
39 recordPendingThreadCreationOutcome,
40} from "./pending-thread-creation";
41import { serverEnvironment } from "./server";
42import {
43 confirmThreadOutboxMessageQueued,
44 threadOutboxManager,
45 threadOutboxRevision,
46 updateThreadOutboxMessage,
47} from "./thread-outbox";
48import { removeThreadOutboxMessage } from "./thread-outbox-removal";
49import {
50 isQueuedThreadCreationSendable,
51 resolveThreadOutboxDeliveryAction,
52 resolveThreadOutboxDispatchStep,
53 resolveThreadOutboxFailureAction,
54 resolveQueuedThreadSettings,
55 shouldRetryThreadOutboxDelivery,
56 threadOutboxRetryDelayMs,
57 type QueuedThreadCreation,
58 type QueuedThreadMessage,
59 type ThreadOutboxCommandStage,
60 type ThreadOutboxFailureAction,
61} from "./thread-outbox-model";
62import { environmentThreadShells, threadEnvironment } from "./threads";
63import {
64 appendComposerDraftAttachments,
65 composerDraftsAtom,
66 flushComposerDrafts,
67 type ComposerDraft,
68 getComposerDraftSnapshot,
69 mergeComposerDraftContent,
70 replaceComposerDraftAttachments,
71 removeDeliveredCloudQueuedMessage,
72 undoComposerDraftMerge,
73 updateComposerDraftSettings,
74 waitForComposerDraftsLoaded,
75} from "./use-composer-drafts";
76import { useAtomCommand } from "./use-atom-command";
77import {
78 dispatchingQueuedMessageIdAtom,
79 editingQueuedMessageIdsAtom,
80 useThreadOutboxMessages,
81 useThreadOutboxShellStatuses,
82} from "./use-thread-outbox";
83import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
84import { useRemoteConnectionStatus } from "./use-remote-environment-registry";
85
86// Ordinary offline behavior (a socket dropping mid-request, a retryable
87// attachment upload failure) must not spam `console.warn` on every backoff
88// retry; it goes to the filterable `[t3-thread-outbox]` debug log instead.
89// Failures the server decided stay on `console.warn`.
90const threadOutboxDebug = createDebugLogger("thread-outbox");
91
92/**
93 * On the queued-request path (settings sync, startTurn) the RPC client
94 * reports ordinary transport drops as the raw socket/worker reason tags, and
95 * reserves `RpcClientDefect` for client-side protocol violations and decoding
96 * failures — unlike the shared config-subscription stream, which
97 * deliberately re-wraps transport causes under that tag. Defects still retry,
98 * but they are not ordinary offline behavior and must not hide behind the
99 * offline debug log.
100 */
101function isRpcClientDecodeDefect(error: unknown): boolean {
102 if (
103 typeof error !== "object" ||
104 error === null ||
105 !("_tag" in error) ||
106 error._tag !== "RpcClientError"
107 ) {
108 return false;
109 }
110 const reason: unknown = (error as { readonly reason?: unknown }).reason;
111 return (
112 typeof reason === "object" &&
113 reason !== null &&
114 "_tag" in reason &&
115 reason._tag === "RpcClientDefect"
116 );
117}
118
119function isOrdinaryThreadOutboxTransportFailure(error: unknown): boolean {
120 return shouldRetryThreadOutboxDelivery(error) && !isRpcClientDecodeDefect(error);
121}
122
123/**
124 * Logs one queued-message delivery failure and returns the retry-or-restore
125 * decision for the caller. Ordinary transport retries — what an offline
126 * device or a flapping socket produces on every backoff attempt — go to the
127 * debug log. Server-decided failures warn. Settings-sync failures always
128 * resolve to a retry even when the server rejected the command, so the
129 * error, not the resolved action, must decide the log level there; routing
130 * every retry to debug could hide a permanently rejected update forever.
131 */
132function logThreadOutboxDeliveryFailure(input: {
133 readonly stage: ThreadOutboxCommandStage;
134 readonly error: unknown;
135 readonly interrupted: boolean;
136 readonly context: Record<string, unknown>;
137}): ThreadOutboxFailureAction {
138 const action = resolveThreadOutboxFailureAction({
139 stage: input.stage,
140 error: input.error,
141 interrupted: input.interrupted,
142 });
143 const details = { ...input.context, stage: input.stage, action };
144 const ordinaryTransportRetry =
145 action === "retry" &&
146 !isRpcClientDecodeDefect(input.error) &&
147 (input.interrupted ||
148 input.stage !== "settings-sync" ||
149 shouldRetryThreadOutboxDelivery(input.error));
150 if (ordinaryTransportRetry) {
151 threadOutboxDebug.log("queued message delivery failed", details);
152 } else {
153 console.warn("[thread-outbox] queued message delivery failed", details);
154 }
155 return action;
156}
157
158/** Attachment uploads retry like delivery: transport failures are ordinary offline noise. */
159function logThreadOutboxUploadFailure(queuedMessage: QueuedThreadMessage, error: unknown): void {
160 const context = {
161 environmentId: queuedMessage.environmentId,
162 threadId: queuedMessage.threadId,
163 messageId: queuedMessage.messageId,
164 };
165 if (isOrdinaryThreadOutboxTransportFailure(error)) {
166 threadOutboxDebug.log("attachment upload failed; retrying", { ...context, error });
167 } else {
168 console.warn("[thread-outbox] failed to upload attachments", { ...context, error });
169 }
170}
171
172function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void {
173 appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId);
174}
175
176function finishDispatchingQueuedMessage(queuedMessageId: MessageId): void {
177 const current = appAtomRegistry.get(dispatchingQueuedMessageIdAtom);
178 appAtomRegistry.set(dispatchingQueuedMessageIdAtom, current === queuedMessageId ? null : current);
179}
180
181function findThread(
182 threads: ReadonlyArray<EnvironmentThreadShell>,
183 message: QueuedThreadMessage,
184): EnvironmentThreadShell | undefined {
185 return threads.find(
186 (candidate) =>
187 candidate.environmentId === message.environmentId && candidate.id === message.threadId,
188 );
189}
190
191function findCreationProject(
192 projects: ReadonlyArray<EnvironmentProject>,
193 message: QueuedThreadMessage,
194): EnvironmentProject | undefined {
195 return projects.find(
196 (candidate) =>
197 candidate.environmentId === message.environmentId &&
198 candidate.id === message.creation?.projectId,
199 );
200}
201
202function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
203 return CommandId.make(`${message.commandId}:${setting}`);
204}
205
206/**
207 * Uploads a queued message's attachments and persists the uploaded ids back
208 * onto the queued message. The revision-checked update means an edit accepted
209 * while the bytes uploaded wins: this attempt abandons and the next drain pass
210 * re-reads the message.
211 * `deliveryRevision` is the revision of the payload this attempt will send,
212 * used for the delivery removal's compare-and-set.
213 */
214export async function prepareQueuedMessageAttachments(
215 queuedMessage: QueuedThreadMessage,
216 supportsImageUploads = false,
217): Promise<
218 | {
219 readonly status: "ready";
220 readonly prepared: PreparedTurnAttachments;
221 readonly persistedMessage: QueuedThreadMessage;
222 readonly deliveryRevision: number;
223 }
224 | { readonly status: "abandoned" }
225> {
226 if (!(await confirmThreadOutboxMessageQueued(queuedMessage))) {
227 return { status: "abandoned" };
228 }
229 const revision = threadOutboxRevision(queuedMessage.messageId);
230 if (!isQueuedMessagePayloadCurrent(queuedMessage, revision)) {
231 return { status: "abandoned" };
232 }
233 let persistedMessage = queuedMessage;
234 let deliveryRevision = revision;
235 const result = await prepareTurnAttachments({
236 environmentId: queuedMessage.environmentId,
237 attachments: queuedMessage.attachments,
238 supportsImageUploads,
239 persistUploadedReferences: async (draftAttachments) => {
240 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
241 return "abandon";
242 }
243 const updatedMessage = { ...queuedMessage, attachments: draftAttachments };
244 if (!(await updateThreadOutboxMessage(updatedMessage, revision))) {
245 return "abandon";
246 }
247 persistedMessage = updatedMessage;
248 deliveryRevision = revision + 1;
249 return "persisted";
250 },
251 });
252 if (
253 result.status === "abandoned" ||
254 !isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)
255 ) {
256 return { status: "abandoned" };
257 }
258 return { status: "ready", prepared: result, persistedMessage, deliveryRevision };
259}
260
261function isQueuedMessagePayloadCurrent(
262 message: QueuedThreadMessage,
263 expectedRevision: number,
264): boolean {
265 return (
266 threadOutboxRevision(message.messageId) === expectedRevision &&
267 Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))
268 .flat()
269 .some((candidate) => candidate === message)
270 );
271}
272
273/**
274 * Removes a delivered message from the outbox. The revision and editor checks
275 * preserve a creation payload when its pending-task editor owns newer work.
276 * The outcome tells the caller whether removal completed, ownership changed,
277 * or storage cleanup failed. Exported for tests.
278 */
279export async function completeQueuedMessageDelivery(
280 queuedMessage: QueuedThreadMessage,
281 deliveryRevision: number,
282): Promise<"removed" | "edited" | "failed"> {
283 // The server took it after all: an error left by an earlier failed recovery
284 // of this same message no longer applies.
285 clearThreadComposerError(
286 scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId),
287 queuedMessage.messageId,
288 );
289 try {
290 await removeDeliveredCloudQueuedMessage(queuedMessage).catch((error) => {
291 console.warn("[thread-outbox] could not update sign-out snapshot after delivery", {
292 messageId: queuedMessage.messageId,
293 error,
294 });
295 });
296 // The editor may have taken the entry while startTurn was in flight; its
297 // unsaved edits have not bumped the revision yet, so the CAS alone would
298 // let removal win and the editor would lose them once it saves.
299 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
300 return "edited";
301 }
302 retainAcknowledgedThreadMessage(queuedMessage);
303 // Removal also releases the message's local attachment files.
304 const removed = await removeThreadOutboxMessage(
305 queuedMessage,
306 deliveryRevision,
307 () => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId],
308 );
309 if (!removed) {
310 forgetAcknowledgedThreadMessage(queuedMessage);
311 // Losing the cleanup race to a user edit is an expected outcome the
312 // caller handles by keeping the newer message; it is not a warning.
313 threadOutboxDebug.log("delivered message was edited before cleanup", {
314 environmentId: queuedMessage.environmentId,
315 threadId: queuedMessage.threadId,
316 messageId: queuedMessage.messageId,
317 });
318 return "edited";
319 }
320 return "removed";
321 } catch (error) {
322 forgetAcknowledgedThreadMessage(queuedMessage);
323 console.warn("[thread-outbox] failed to remove delivered queued message", {
324 environmentId: queuedMessage.environmentId,
325 threadId: queuedMessage.threadId,
326 messageId: queuedMessage.messageId,
327 error,
328 });
329 return "failed";
330 }
331}
332
333/** Retries local cleanup for an existing-thread send acknowledged in this drain lifetime. */
334export async function removeAcknowledgedExistingThreadMessage(
335 queuedMessage: QueuedThreadMessage,
336 acknowledgedMessageIds: Set<MessageId>,
337): Promise<boolean> {
338 try {
339 await removeDeliveredCloudQueuedMessage(queuedMessage).catch((error) => {
340 console.warn("[thread-outbox] could not update sign-out snapshot after delivery", {
341 messageId: queuedMessage.messageId,
342 error,
343 });
344 });
345 const removed = await removeThreadOutboxMessage(queuedMessage);
346 if (removed) {
347 acknowledgedMessageIds.delete(queuedMessage.messageId);
348 }
349 return removed;
350 } catch (error) {
351 console.warn("[thread-outbox] failed to remove acknowledged queued message", {
352 environmentId: queuedMessage.environmentId,
353 threadId: queuedMessage.threadId,
354 messageId: queuedMessage.messageId,
355 error,
356 });
357 return false;
358 }
359}
360
361/**
362 * A creation delivered its startTurn but an edit won the cleanup race, so the
363 * edited payload is still queued. The next drain would see the created thread
364 * and take the creation "remove" path, silently discarding the edit; hand the
365 * edited content to the new thread's composer instead and remove the entry.
366 * Returns true when recovery is complete or an open editor owns the next
367 * action, and false when the drain should retry with backoff.
368 * Exported for tests; the drain is the only production caller.
369 */
370export async function recoverEditedCreationAfterDelivery(
371 queuedMessage: QueuedThreadMessage,
372): Promise<boolean> {
373 const kept = Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))
374 .flat()
375 .find((candidate) => candidate.messageId === queuedMessage.messageId);
376 if (!kept) {
377 return true;
378 }
379 const keptRevision = threadOutboxRevision(kept.messageId);
380 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
381 return true;
382 }
383 const draftKey = scopedThreadKey(kept.environmentId, kept.threadId);
384 try {
385 // Merge before removing: the draft's reference keeps the removal sweep
386 // from deleting the attachment files. allowOverflow mirrors the
387 // send-failure restore; the send path refuses over-cap drafts, so the
388 // state stays recoverable.
389 await mergeComposerDraftContent(draftKey, {
390 text: kept.text,
391 context: kept.context,
392 attachments: [],
393 });
394 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
395 return true;
396 }
397 if (threadOutboxRevision(kept.messageId) !== keptRevision) {
398 return false;
399 }
400 const existingAttachmentIds = new Set(
401 getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),
402 );
403 appendComposerDraftAttachments(
404 draftKey,
405 kept.attachments.filter((attachment) => !existingAttachmentIds.has(attachment.id)),
406 { allowOverflow: true },
407 );
408 // Only settings the queued message actually carries: spreading explicit
409 // undefined would clear choices the user already made on the draft.
410 updateComposerDraftSettings(draftKey, {
411 ...(kept.modelSelection !== undefined ? { modelSelection: kept.modelSelection } : {}),
412 ...(kept.runtimeMode !== undefined ? { runtimeMode: kept.runtimeMode } : {}),
413 ...(kept.interactionMode !== undefined ? { interactionMode: kept.interactionMode } : {}),
414 });
415 // The append only schedules a debounced write; the queue entry is the
416 // only durable copy until the draft lands, so flush before removing.
417 await flushComposerDrafts();
418 } catch (error) {
419 // Keep the entry queued. The drain retries with backoff, and the merge is
420 // idempotent so content that persisted before the failure is not repeated.
421 console.warn("[thread-outbox] could not hand an edited pending task to the composer", error);
422 return false;
423 }
424 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId]) {
425 return true;
426 }
427 try {
428 return await removeThreadOutboxMessage(
429 kept,
430 keptRevision,
431 () => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[kept.messageId],
432 );
433 } catch (error) {
434 console.warn("[thread-outbox] could not remove recovered pending task", error);
435 return false;
436 }
437}
438
439/** Exported for tests; the drain is the only production caller. */
440export async function restoreRejectedQueuedMessage(
441 queuedMessage: QueuedThreadMessage,
442 message: string,
443): Promise<"restored" | "deferred" | "blocked" | "retry"> {
444 const draftKey = recoveryDraftKey(queuedMessage);
445 const threadKey = scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId);
446 // Set once the merge publishes, cleared once the queued message is removed.
447 // The catch below uses it to take the merged content back out, so a retry
448 // after a mid-recovery failure cannot append the recovered text again.
449 let rollback: { readonly snapshot: ComposerDraft; readonly merged: ComposerDraft } | null = null;
450 try {
451 if (
452 appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] ||
453 !(await confirmThreadOutboxMessageQueued(queuedMessage)) ||
454 appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]
455 ) {
456 return "deferred";
457 }
458 // The confirmation above checked this exact payload is what is queued, so
459 // the current revision guards the removal at the end against an edit
460 // accepted while this recovery ran.
461 const revision = threadOutboxRevision(queuedMessage.messageId);
462
463 await waitForComposerDraftsLoaded();
464 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
465 return "deferred";
466 }
467 const originalDraft = getComposerDraftSnapshot(draftKey);
468 const existingAttachmentIds = new Set(
469 originalDraft.attachments.map((attachment) => attachment.id),
470 );
471 const addedAttachmentCount = queuedMessage.attachments.filter(
472 (attachment) => !existingAttachmentIds.has(attachment.id),
473 ).length;
474 if (existingAttachmentIds.size + addedAttachmentCount > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
475 setThreadComposerError(
476 threadKey,
477 `Remove attachments from the draft before restoring this message. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
478 queuedMessage.messageId,
479 );
480 return "blocked";
481 }
482
483 // Shown before the merge publishes the text, so a resend of that text,
484 // which can happen while this recovery still awaits persistence, clears
485 // it. Withdrawn below wherever the recovery backs out.
486 const withdrawError = () => clearThreadComposerError(threadKey, queuedMessage.messageId);
487 if (!queuedMessage.creation) {
488 setThreadComposerError(threadKey, message, queuedMessage.messageId);
489 }
490 let mergedDraft: ComposerDraft;
491 try {
492 stampRecoveryDraftProject(queuedMessage, draftKey);
493 await mergeComposerDraftContent(draftKey, {
494 text: queuedMessage.text,
495 context: queuedMessage.context,
496 attachments: queuedMessage.attachments,
497 });
498 } finally {
499 // Snapshots for the rollbacks below: undoComposerDraftMerge restores
500 // the original draft only while it is untouched, and otherwise takes
501 // out just what this recovery inserted so edits typed during the awaits
502 // survive. Captured in a finally because mergeComposerDraftContent
503 // publishes before its persistence await: even its failure leaves the
504 // merged content in the draft.
505 mergedDraft = getComposerDraftSnapshot(draftKey);
506 rollback = { snapshot: originalDraft, merged: mergedDraft };
507 }
508 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
509 withdrawError();
510 await undoComposerDraftMerge(draftKey, originalDraft, mergedDraft);
511 return "deferred";
512 }
513 updateComposerDraftSettings(draftKey, {
514 ...(queuedMessage.modelSelection ? { modelSelection: queuedMessage.modelSelection } : {}),
515 ...(queuedMessage.runtimeMode ? { runtimeMode: queuedMessage.runtimeMode } : {}),
516 ...(queuedMessage.interactionMode ? { interactionMode: queuedMessage.interactionMode } : {}),
517 ...(queuedMessage.creation
518 ? {
519 workspaceSelection: {
520 mode: queuedMessage.creation.workspaceMode,
521 branch: queuedMessage.creation.branch,
522 worktreePath: queuedMessage.creation.worktreePath,
523 ...(queuedMessage.creation.startFromOrigin !== undefined
524 ? { startFromOrigin: queuedMessage.creation.startFromOrigin }
525 : {}),
526 },
527 }
528 : {}),
529 });
530 const restoredDraft = getComposerDraftSnapshot(draftKey);
531 rollback = { snapshot: originalDraft, merged: restoredDraft };
532 await flushComposerDrafts();
533 if (
534 appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] ||
535 !(await confirmThreadOutboxMessageQueued(queuedMessage)) ||
536 appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]
537 ) {
538 withdrawError();
539 await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft);
540 return "deferred";
541 }
542 // Revision-checked: an edit that landed after the confirmation above
543 // must not be deleted with the pre-edit payload this recovery restored.
544 if (
545 !(await removeThreadOutboxMessage(
546 queuedMessage,
547 revision,
548 () => !appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId],
549 ))
550 ) {
551 withdrawError();
552 await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft);
553 return "deferred";
554 }
555 // The queued message is gone; from here the draft owns the content and
556 // must never be rolled back.
557 rollback = null;
558 if (queuedMessage.creation) {
559 // The failure card shows the reason, so an error left by an earlier
560 // failed attempt at this recovery no longer applies.
561 withdrawError();
562 // The thread screen for this creation is likely open; it reads the
563 // outcome to offer reopening the restored draft, and shows the reason.
564 recordPendingThreadCreationOutcome({
565 kind: "failed",
566 message: queuedMessage,
567 reason: message,
568 });
569 }
570 return "restored";
571 } catch (error) {
572 if (rollback !== null) {
573 // Take the recovered content back out (keeping edits typed since) so
574 // the retry's merge starts clean instead of appending a duplicate. The
575 // in-memory rollback lands even when its own persistence write fails.
576 await undoComposerDraftMerge(draftKey, rollback.snapshot, rollback.merged).catch(
577 (undoError) => {
578 console.warn("[thread-outbox] failed to persist a recovery rollback", undoError);
579 },
580 );
581 }
582 console.warn("[thread-outbox] failed to restore an undeliverable message", error);
583 setThreadComposerError(
584 threadKey,
585 error instanceof Error ? error.message : "The unsent message could not be restored.",
586 queuedMessage.messageId,
587 );
588 return "retry";
589 }
590}
591
592/**
593 * A rejected creation becomes its own new-task draft rather than merging into
594 * whatever the user is typing for that project. The key derives from the
595 * message id so a retry after a mid-recovery failure lands on the same draft
596 * instead of minting another.
597 */
598function recoveryDraftKey(queuedMessage: QueuedThreadMessage): string {
599 return queuedMessage.creation
600 ? restoredNewTaskDraftKey(queuedMessage.messageId)
601 : scopedThreadKey(queuedMessage.environmentId, queuedMessage.threadId);
602}
603
604function stampRecoveryDraftProject(queuedMessage: QueuedThreadMessage, draftKey: string): void {
605 if (!queuedMessage.creation) {
606 return;
607 }
608 updateComposerDraftSettings(draftKey, {
609 project: {
610 environmentId: queuedMessage.environmentId,
611 projectId: queuedMessage.creation.projectId,
612 createdAt: queuedMessage.createdAt,
613 },
614 });
615}
616
617async function preserveUploadedAttachmentsForEditor(
618 originalMessage: QueuedThreadMessage,
619 uploadedMessage: QueuedThreadMessage,
620): Promise<void> {
621 if (!originalMessage.creation) {
622 return;
623 }
624
625 const draftKey = `pending-task:${originalMessage.messageId}`;
626 const draft = getComposerDraftSnapshot(draftKey);
627 const uploadedById = new Map(
628 uploadedMessage.attachments.map((attachment) => [attachment.id, attachment] as const),
629 );
630 let changed = false;
631 const nextAttachments = draft.attachments.map((attachment) => {
632 const uploaded = uploadedById.get(attachment.id);
633 if (
634 !uploaded?.uploadedAttachmentId ||
635 uploaded.uploadEnvironmentId !== originalMessage.environmentId ||
636 (attachment.uploadedAttachmentId === uploaded.uploadedAttachmentId &&
637 attachment.uploadEnvironmentId === uploaded.uploadEnvironmentId)
638 ) {
639 return attachment;
640 }
641 changed = true;
642 return {
643 ...attachment,
644 uploadedAttachmentId: uploaded.uploadedAttachmentId,
645 uploadEnvironmentId: uploaded.uploadEnvironmentId,
646 };
647 });
648 if (changed) {
649 replaceComposerDraftAttachments(draftKey, nextAttachments);
650 await flushComposerDrafts();
651 }
652}
653
654export function useThreadOutboxDrain(): void {
655 const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
656 const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
657 reportFailure: false,
658 });
659 const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
660 reportFailure: false,
661 });
662 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
663 const editingQueuedMessageIds = useAtomValue(editingQueuedMessageIdsAtom);
664 const queuedMessagesByThreadKey = useThreadOutboxMessages();
665 const shellStatuses = useThreadOutboxShellStatuses();
666 const threads = useThreadShells();
667 const creationOutcomes = useAtomValue(pendingThreadCreationOutcomesAtom);
668 const projects = useProjects();
669 const serverConfigs = useServerConfigs();
670 const { connectedEnvironments } = useRemoteConnectionStatus();
671 const [retryTick, setRetryTick] = useState(0);
672 const retryAttemptRef = useRef(new Map<MessageId, number>());
673 const retryNotBeforeRef = useRef(new Map<MessageId, number>());
674 const retryTimersRef = useRef(new Map<MessageId, ReturnType<typeof setTimeout>>());
675 const acknowledgedExistingThreadMessageIdsRef = useRef(new Set<MessageId>());
676 const blockedRecoverySubscriptionsRef = useRef(
677 new Map<
678 MessageId,
679 { readonly message: QueuedThreadMessage; readonly unsubscribe: () => void }
680 >(),
681 );
682
683 const scheduleQueuedMessageRetry = useCallback((messageId: MessageId) => {
684 const retryAttempt = (retryAttemptRef.current.get(messageId) ?? 0) + 1;
685 retryAttemptRef.current.set(messageId, retryAttempt);
686 const retryDelayMs = threadOutboxRetryDelayMs(retryAttempt);
687 retryNotBeforeRef.current.set(messageId, Date.now() + retryDelayMs);
688 const pendingTimer = retryTimersRef.current.get(messageId);
689 if (pendingTimer !== undefined) {
690 clearTimeout(pendingTimer);
691 }
692 const retryTimer = setTimeout(() => {
693 retryTimersRef.current.delete(messageId);
694 setRetryTick((current) => current + 1);
695 }, retryDelayMs);
696 retryTimersRef.current.set(messageId, retryTimer);
697 }, []);
698
699 const restoreQueuedMessage = useCallback(
700 async (queuedMessage: QueuedThreadMessage, message: string): Promise<boolean> => {
701 const result = await restoreRejectedQueuedMessage(queuedMessage, message);
702 if (result !== "blocked") {
703 return result !== "retry";
704 }
705
706 if (!blockedRecoverySubscriptionsRef.current.has(queuedMessage.messageId)) {
707 const draftKey = recoveryDraftKey(queuedMessage);
708 const editorDraftKey = queuedMessage.creation
709 ? `pending-task:${queuedMessage.messageId}`
710 : null;
711 const currentDrafts = appAtomRegistry.get(composerDraftsAtom);
712 const blockedAttachments = currentDrafts[draftKey]?.attachments;
713 const editorAttachments =
714 editorDraftKey === null ? undefined : currentDrafts[editorDraftKey]?.attachments;
715 const unsubscribe = appAtomRegistry.subscribe(composerDraftsAtom, (drafts) => {
716 if (
717 drafts[draftKey]?.attachments === blockedAttachments &&
718 (editorDraftKey === null || drafts[editorDraftKey]?.attachments === editorAttachments)
719 ) {
720 return;
721 }
722 const active = blockedRecoverySubscriptionsRef.current.get(queuedMessage.messageId);
723 if (!active) {
724 return;
725 }
726 blockedRecoverySubscriptionsRef.current.delete(queuedMessage.messageId);
727 active.unsubscribe();
728 setRetryTick((current) => current + 1);
729 });
730 blockedRecoverySubscriptionsRef.current.set(queuedMessage.messageId, {
731 message: queuedMessage,
732 unsubscribe,
733 });
734 }
735 return true;
736 },
737 [],
738 );
739
740 useEffect(() => {
741 let mounted = true;
742 const load = async () => {
743 if ((await threadOutboxManager.load()) || !mounted) return;
744 Alert.alert(
745 "Some queued messages could not be loaded",
746 "Unreadable records and attachment files are still saved. Other messages can still be sent.",
747 [
748 { text: "Dismiss", style: "cancel" },
749 { text: "Retry", onPress: () => void load() },
750 ],
751 );
752 };
753 void load();
754 return () => {
755 mounted = false;
756 for (const timer of retryTimersRef.current.values()) {
757 clearTimeout(timer);
758 }
759 retryTimersRef.current.clear();
760 for (const blocked of blockedRecoverySubscriptionsRef.current.values()) {
761 blocked.unsubscribe();
762 }
763 blockedRecoverySubscriptionsRef.current.clear();
764 };
765 }, []);
766
767 const makeDeliveryHelpers = useCallback((queuedMessage: QueuedThreadMessage) => {
768 const reportFailure = (
769 commandResult: AtomCommandResult<unknown, unknown>,
770 stage: ThreadOutboxCommandStage,
771 ): { readonly action: "retry" | "restore"; readonly message: string } | null => {
772 if (!AsyncResult.isFailure(commandResult)) {
773 return null;
774 }
775 const error = Cause.squash(commandResult.cause);
776 const action = logThreadOutboxDeliveryFailure({
777 stage,
778 error,
779 interrupted: Cause.hasInterruptsOnly(commandResult.cause),
780 context: {
781 environmentId: queuedMessage.environmentId,
782 threadId: queuedMessage.threadId,
783 messageId: queuedMessage.messageId,
784 cause: commandResult.cause,
785 },
786 });
787 return {
788 action,
789 message: error instanceof Error ? error.message : "The message could not be sent.",
790 };
791 };
792 return { reportFailure };
793 }, []);
794
795 const sendQueuedMessage = useCallback(
796 async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
797 const serverConfig = appAtomRegistry.get(
798 serverEnvironment.configValueAtom(queuedMessage.environmentId),
799 );
800 if (!serverConfig) return false;
801 const settings = resolveQueuedThreadSettings(queuedMessage, thread, serverConfig.providers);
802 if (isModelSelectionUnavailable(serverConfig, settings.modelSelection)) {
803 return restoreQueuedMessage(
804 queuedMessage,
805 "Antigravity model unavailable. Set it up on web or desktop, or choose another model.",
806 );
807 }
808 const { reportFailure } = makeDeliveryHelpers(queuedMessage);
809
810 if (settings.runtimeMode !== thread.runtimeMode) {
811 const runtimeResult = await setThreadRuntimeMode({
812 environmentId: queuedMessage.environmentId,
813 input: {
814 commandId: settingsCommandId(queuedMessage, "runtime-mode"),
815 threadId: queuedMessage.threadId,
816 runtimeMode: settings.runtimeMode,
817 createdAt: queuedMessage.createdAt,
818 },
819 });
820 if (AsyncResult.isFailure(runtimeResult)) {
821 reportFailure(runtimeResult, "settings-sync");
822 return false;
823 }
824 }
825
826 if (settings.interactionMode !== thread.interactionMode) {
827 const interactionResult = await setThreadInteractionMode({
828 environmentId: queuedMessage.environmentId,
829 input: {
830 commandId: settingsCommandId(queuedMessage, "interaction-mode"),
831 threadId: queuedMessage.threadId,
832 interactionMode: settings.interactionMode,
833 createdAt: queuedMessage.createdAt,
834 },
835 });
836 if (AsyncResult.isFailure(interactionResult)) {
837 reportFailure(interactionResult, "settings-sync");
838 return false;
839 }
840 }
841
842 let prepared: PreparedTurnAttachments;
843 let persistedMessage: QueuedThreadMessage;
844 let deliveryRevision: number;
845 try {
846 const preparedResult = await prepareQueuedMessageAttachments(
847 queuedMessage,
848 serverConfig.environment.capabilities.attachmentUploads === true,
849 );
850 if (preparedResult.status === "abandoned") {
851 return true;
852 }
853 prepared = preparedResult.prepared;
854 persistedMessage = preparedResult.persistedMessage;
855 deliveryRevision = preparedResult.deliveryRevision;
856 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
857 await preserveUploadedAttachmentsForEditor(
858 queuedMessage,
859 preparedResult.persistedMessage,
860 );
861 return true;
862 }
863 } catch (error) {
864 logThreadOutboxUploadFailure(queuedMessage, error);
865 if (!shouldRetryThreadOutboxDelivery(error)) {
866 return restoreQueuedMessage(
867 queuedMessage,
868 error instanceof Error ? error.message : "An attachment could not upload.",
869 );
870 }
871 return false;
872 }
873 if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
874 return true;
875 }
876 const currentConfig = appAtomRegistry.get(
877 serverEnvironment.configValueAtom(queuedMessage.environmentId),
878 );
879 if (!currentConfig) return false;
880 if (isModelSelectionUnavailable(currentConfig, settings.modelSelection)) {
881 return restoreQueuedMessage(
882 persistedMessage,
883 "Antigravity model unavailable. Set it up on web or desktop, or choose another model.",
884 );
885 }
886 const sendSettings = resolveQueuedThreadSettings(
887 queuedMessage,
888 settings,
889 currentConfig.providers,
890 );
891 const deliveryResult = await startTurn({
892 environmentId: queuedMessage.environmentId,
893 input: {
894 commandId: queuedMessage.commandId,
895 creationSource: "mobile",
896 threadId: queuedMessage.threadId,
897 message: {
898 messageId: queuedMessage.messageId,
899 role: "user",
900 ...serializeComposerMessageForServer(
901 queuedMessage.text,
902 uploadedComposerContext(
903 queuedMessage.context,
904 queuedMessage.attachments,
905 prepared.attachments,
906 ),
907 currentConfig.environment.capabilities.inlineMessageContext === true,
908 ),
909 attachments: prepared.attachments,
910 },
911 modelSelection: sendSettings.modelSelection,
912 titleSeed: deriveThreadTitleSeed({
913 text: queuedMessage.text,
914 attachments: queuedMessage.attachments,
915 }),
916 runtimeMode: sendSettings.runtimeMode,
917 interactionMode: sendSettings.interactionMode,
918 createdAt: queuedMessage.createdAt,
919 // Rows written before follow-up behavior existed keep the previous
920 // delivery, which the server turns into a queued run when a turn is
921 // already active.
922 dispatchMode: queuedMessage.dispatchMode ?? "start",
923 },
924 });
925 const failure = reportFailure(deliveryResult, "start-turn");
926 if (failure?.action === "retry") {
927 return false;
928 }
929 if (failure?.action === "restore") {
930 return restoreQueuedMessage(persistedMessage, failure.message);
931 }
932 acknowledgedExistingThreadMessageIdsRef.current.add(persistedMessage.messageId);
933 const delivered =
934 (await completeQueuedMessageDelivery(persistedMessage, deliveryRevision)) === "removed";
935 if (delivered) {
936 acknowledgedExistingThreadMessageIdsRef.current.delete(persistedMessage.messageId);
937 }
938 return delivered;
939 },
940 [
941 makeDeliveryHelpers,
942 setThreadInteractionMode,
943 setThreadRuntimeMode,
944 startTurn,
945 restoreQueuedMessage,
946 ],
947 );
948
949 const sendQueuedCreation = useCallback(
950 async (
951 queuedMessage: QueuedThreadMessage,
952 creation: QueuedThreadCreation,
953 projectCwd: string,
954 ) => {
955 const modelSelection = queuedMessage.modelSelection;
956 if (modelSelection === undefined) {
957 return false;
958 }
959 const serverConfig = appAtomRegistry.get(
960 serverEnvironment.configValueAtom(queuedMessage.environmentId),
961 );
962 if (!serverConfig) return false;
963 const settings = resolveQueuedThreadSettings(
964 queuedMessage,
965 {
966 modelSelection,
967 runtimeMode: DEFAULT_RUNTIME_MODE,
968 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
969 },
970 serverConfig.providers,
971 );
972 if (isModelSelectionUnavailable(serverConfig, settings.modelSelection)) {
973 return restoreQueuedMessage(
974 queuedMessage,
975 "Antigravity model unavailable. Set it up on web or desktop, or choose another model.",
976 );
977 }
978 let prepared: PreparedTurnAttachments;
979 let persistedMessage: QueuedThreadMessage;
980 let deliveryRevision: number;
981 try {
982 const preparedResult = await prepareQueuedMessageAttachments(
983 queuedMessage,
984 serverConfig.environment.capabilities.attachmentUploads === true,
985 );
986 if (preparedResult.status === "abandoned") {
987 return true;
988 }
989 prepared = preparedResult.prepared;
990 persistedMessage = preparedResult.persistedMessage;
991 deliveryRevision = preparedResult.deliveryRevision;
992 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {
993 await preserveUploadedAttachmentsForEditor(
994 queuedMessage,
995 preparedResult.persistedMessage,
996 );
997 return true;
998 }
999 } catch (error) {
1000 logThreadOutboxUploadFailure(queuedMessage, error);
1001 if (!shouldRetryThreadOutboxDelivery(error)) {
1002 return restoreQueuedMessage(
1003 queuedMessage,
1004 error instanceof Error ? error.message : "An attachment could not upload.",
1005 );
1006 }
1007 return false;
1008 }
1009 if (!isQueuedMessagePayloadCurrent(persistedMessage, deliveryRevision)) {
1010 return true;
1011 }
1012 const currentConfig = appAtomRegistry.get(
1013 serverEnvironment.configValueAtom(queuedMessage.environmentId),
1014 );
1015 if (!currentConfig) return false;
1016 if (isModelSelectionUnavailable(currentConfig, settings.modelSelection)) {
1017 return restoreQueuedMessage(
1018 persistedMessage,
1019 "Antigravity model unavailable. Set it up on web or desktop, or choose another model.",
1020 );
1021 }
1022 const sendSettings = resolveQueuedThreadSettings(
1023 queuedMessage,
1024 settings,
1025 currentConfig.providers,
1026 );
1027 const deliveryResult = await startTurn({
1028 environmentId: queuedMessage.environmentId,
1029 input: buildProjectThreadStartTurnInput({
1030 projectId: creation.projectId,
1031 projectCwd,
1032 threadId: queuedMessage.threadId,
1033 commandId: queuedMessage.commandId,
1034 messageId: queuedMessage.messageId,
1035 createdAt: queuedMessage.createdAt,
1036 ...serializeComposerMessageForServer(
1037 queuedMessage.text.trim(),
1038 uploadedComposerContext(
1039 queuedMessage.context,
1040 queuedMessage.attachments,
1041 prepared.attachments,
1042 ),
1043 currentConfig.environment.capabilities.inlineMessageContext === true,
1044 ),
1045 uploadedAttachments: prepared.attachments,
1046 modelSelection: sendSettings.modelSelection,
1047 runtimeMode: sendSettings.runtimeMode,
1048 interactionMode: sendSettings.interactionMode,
1049 workspaceMode: creation.workspaceMode,
1050 branch: creation.branch,
1051 worktreePath: creation.worktreePath,
1052 startFromOrigin: creation.startFromOrigin ?? false,
1053 worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),
1054 }),
1055 });
1056 const { reportFailure } = makeDeliveryHelpers(queuedMessage);
1057 const failure = reportFailure(deliveryResult, "start-turn");
1058 if (failure?.action === "retry") {
1059 return false;
1060 }
1061 if (failure?.action === "restore") {
1062 return restoreQueuedMessage(persistedMessage, failure.message);
1063 }
1064 // Recorded before the queue entry goes so the thread screen never sees a
1065 // gap between the queued creation and the server's shell.
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 // The editor holds the entry with unsaved edits; merging the queue
1071 // payload now would duplicate the delivered turn. Once the editor
1072 // saves, the duplicate-creation removal below recovers the edits.
1073 return true;
1074 }
1075 // The thread exists now, so the next drain would remove the edited
1076 // payload as a duplicate creation. Hand it to the thread's composer.
1077 return recoverEditedCreationAfterDelivery(persistedMessage);
1078 }
1079 return outcome === "removed";
1080 },
1081 [makeDeliveryHelpers, restoreQueuedMessage, startTurn],
1082 );
1083
1084 // A creation outcome bridges setup until the server's shell has a turn.
1085 // Drop it once that happens so the map cannot grow for a whole session; a
1086 // failed outcome stays until its thread screen consumes it.
1087 // Subscribed, not read once: the shell often lands before the outcome is
1088 // recorded, and a non-reactive read would leave that entry uncollected
1089 // because `threads` never changes again.
1090 useEffect(() => {
1091 for (const [threadKey, outcome] of Object.entries(creationOutcomes)) {
1092 if (
1093 outcome.kind === "delivered" &&
1094 threads.some(
1095 (thread) =>
1096 scopedThreadKey(thread.environmentId, thread.id) === threadKey &&
1097 (thread.latestRun !== null ||
1098 thread.runtime?.status === "failed" ||
1099 thread.runtime?.status === "cancelled" ||
1100 thread.runtime?.status === "interrupted"),
1101 )
1102 ) {
1103 clearPendingThreadCreationOutcome(threadKey);
1104 }
1105 }
1106 }, [creationOutcomes, threads]);
1107
1108 useEffect(() => {
1109 if (dispatchingQueuedMessageId !== null) {
1110 return;
1111 }
1112
1113 const queuedMessageIds = new Set(
1114 Object.values(queuedMessagesByThreadKey)
1115 .flat()
1116 .map((message) => message.messageId),
1117 );
1118 for (const messageId of acknowledgedExistingThreadMessageIdsRef.current) {
1119 if (!queuedMessageIds.has(messageId)) {
1120 acknowledgedExistingThreadMessageIdsRef.current.delete(messageId);
1121 }
1122 }
1123
1124 for (const [threadKey, queuedMessages] of Object.entries(queuedMessagesByThreadKey)) {
1125 const nextQueuedMessage = queuedMessages[0];
1126 if (!nextQueuedMessage) {
1127 continue;
1128 }
1129 if (
1130 nextQueuedMessage.creation === undefined &&
1131 acknowledgedExistingThreadMessageIdsRef.current.has(nextQueuedMessage.messageId)
1132 ) {
1133 if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
1134 continue;
1135 }
1136 beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
1137 void removeAcknowledgedExistingThreadMessage(
1138 nextQueuedMessage,
1139 acknowledgedExistingThreadMessageIdsRef.current,
1140 )
1141 .then((removed) => {
1142 if (!removed) {
1143 scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1144 return;
1145 }
1146 retryAttemptRef.current.delete(nextQueuedMessage.messageId);
1147 retryNotBeforeRef.current.delete(nextQueuedMessage.messageId);
1148 const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);
1149 if (pendingTimer !== undefined) {
1150 clearTimeout(pendingTimer);
1151 retryTimersRef.current.delete(nextQueuedMessage.messageId);
1152 }
1153 })
1154 .finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId));
1155 return;
1156 }
1157 if (editingQueuedMessageIds[nextQueuedMessage.messageId]) {
1158 continue;
1159 }
1160 const blockedRecovery = blockedRecoverySubscriptionsRef.current.get(
1161 nextQueuedMessage.messageId,
1162 );
1163 if (blockedRecovery) {
1164 if (blockedRecovery.message === nextQueuedMessage) {
1165 continue;
1166 }
1167 blockedRecoverySubscriptionsRef.current.delete(nextQueuedMessage.messageId);
1168 blockedRecovery.unsubscribe();
1169 }
1170 if ((retryNotBeforeRef.current.get(nextQueuedMessage.messageId) ?? 0) > Date.now()) {
1171 continue;
1172 }
1173
1174 const thread = findThread(threads, nextQueuedMessage);
1175 if (thread && scopedThreadKey(thread.environmentId, thread.id) !== threadKey) {
1176 continue;
1177 }
1178
1179 const creation = nextQueuedMessage.creation;
1180 const environment = connectedEnvironments.find(
1181 (candidate) => candidate.environmentId === nextQueuedMessage.environmentId,
1182 );
1183 const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty";
1184 const deliveryAction = resolveThreadOutboxDeliveryAction({
1185 isCreation: creation !== undefined,
1186 threadExists: thread !== undefined,
1187 shellStatus,
1188 environmentConnected: environment?.connectionState === "connected",
1189 threadBusy: threadRuntimeIsActive(thread?.runtime),
1190 });
1191 // The delivery action resolves first; capability checks apply only to
1192 // a message that will send. Checking earlier would restore a
1193 // creation whose startTurn already made the thread as a duplicate draft
1194 // instead of removing it.
1195 const serverConfig = serverConfigs.get(nextQueuedMessage.environmentId);
1196 const dispatchStep = resolveThreadOutboxDispatchStep({
1197 deliveryAction,
1198 fileAttachments: nextQueuedMessage.attachments.filter(
1199 (attachment) => attachment.type === "file",
1200 ),
1201 serverConfig: serverConfig
1202 ? {
1203 maxFileUploadBytes:
1204 serverConfig.environment.capabilities.fileAttachments?.maxUploadBytes,
1205 }
1206 : null,
1207 });
1208 if (dispatchStep.step === "wait") {
1209 continue;
1210 }
1211 if (dispatchStep.step === "retry") {
1212 // The environment is connected but its config has not synced yet.
1213 // Back off and retry instead of parking the message forever.
1214 scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1215 continue;
1216 }
1217 if (dispatchStep.step === "restore") {
1218 const attachmentError = dispatchStep.reason;
1219 beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
1220 void confirmThreadOutboxMessageQueued(nextQueuedMessage)
1221 .then((queued) => {
1222 if (
1223 !queued ||
1224 appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]
1225 ) {
1226 return true;
1227 }
1228 return restoreQueuedMessage(nextQueuedMessage, attachmentError);
1229 })
1230 .then((restored) => {
1231 if (!restored) {
1232 scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1233 }
1234 })
1235 .finally(() => finishDispatchingQueuedMessage(nextQueuedMessage.messageId));
1236 return;
1237 }
1238 // The live project shell is preferred for the workspace path, with the
1239 // snapshot taken at enqueue time as the fallback so a task never dies
1240 // just because its project shell is not loaded.
1241 const creationProjectCwd =
1242 creation !== undefined
1243 ? (findCreationProject(projects, nextQueuedMessage)?.workspaceRoot ??
1244 creation.projectCwd ??
1245 null)
1246 : null;
1247 // An incomplete pending task (e.g. worktree mode without a branch) stays
1248 // queued until the user finishes it in the editor.
1249 if (deliveryAction === "send" && creation !== undefined) {
1250 if (!isQueuedThreadCreationSendable(nextQueuedMessage)) {
1251 continue;
1252 }
1253 if (creationProjectCwd === null && shellStatus !== "live") {
1254 continue;
1255 }
1256 }
1257
1258 beginDispatchingQueuedMessage(nextQueuedMessage.messageId);
1259 const removeQueuedMessage = (warning: string) =>
1260 removeThreadOutboxMessage(nextQueuedMessage).then(
1261 () => true,
1262 (error) => {
1263 console.warn(warning, {
1264 environmentId: nextQueuedMessage.environmentId,
1265 threadId: nextQueuedMessage.threadId,
1266 messageId: nextQueuedMessage.messageId,
1267 error,
1268 });
1269 return false;
1270 },
1271 );
1272 // Enqueues publish optimistically before their durable write settles.
1273 // Confirm the write landed (and the message wasn't rolled back) before
1274 // sending, so a failed write can never chase an already-delivered turn.
1275 const delivery = confirmThreadOutboxMessageQueued(nextQueuedMessage).then((queued) => {
1276 if (!queued) {
1277 // Rolled back by a failed write; nothing to deliver or retry.
1278 return true;
1279 }
1280 // The guards evaluated before the confirmation await are stale by now:
1281 // the user may have opened this message in the editor. Re-read that
1282 // guard and defer to the next drain pass (returning true skips the
1283 // failure/backoff path) rather than sending a payload being edited.
1284 if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[nextQueuedMessage.messageId]) {
1285 return true;
1286 }
1287 // The shell state is equally stale. Re-run the same delivery policy
1288 // against the live thread snapshot so a vanished thread or newly
1289 // created target defers, while busy existing threads can still steer.
1290 if (deliveryAction === "send") {
1291 const liveThread = findThread(
1292 appAtomRegistry.get(environmentThreadShells.threadShellsAtom),
1293 nextQueuedMessage,
1294 );
1295 const liveThreadBusy = threadRuntimeIsActive(liveThread?.runtime);
1296 const liveDeliveryAction = resolveThreadOutboxDeliveryAction({
1297 isCreation: creation !== undefined,
1298 threadExists: liveThread !== undefined,
1299 shellStatus,
1300 environmentConnected: environment?.connectionState === "connected",
1301 threadBusy: liveThreadBusy,
1302 });
1303 if (liveDeliveryAction !== "send") {
1304 return true;
1305 }
1306 }
1307 return deliveryAction === "remove"
1308 ? creation !== undefined
1309 ? // A creation entry that survived its delivery cleanup either
1310 // holds edits (recover them) or the delivered payload (a
1311 // recovered duplicate the user can delete). Restart loses any
1312 // in-memory distinction, and losing edits is the worse failure,
1313 // so recovery is unconditional here.
1314 recoverEditedCreationAfterDelivery(nextQueuedMessage)
1315 : removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread")
1316 : creation !== undefined
1317 ? creationProjectCwd !== null
1318 ? sendQueuedCreation(nextQueuedMessage, creation, creationProjectCwd)
1319 : removeQueuedMessage("[thread-outbox] dropped pending task for a missing project")
1320 : thread !== undefined
1321 ? sendQueuedMessage(nextQueuedMessage, thread)
1322 : Promise.resolve(false);
1323 });
1324 void delivery
1325 .then((sent) => {
1326 if (sent) {
1327 retryAttemptRef.current.delete(nextQueuedMessage.messageId);
1328 retryNotBeforeRef.current.delete(nextQueuedMessage.messageId);
1329 const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);
1330 if (pendingTimer !== undefined) {
1331 clearTimeout(pendingTimer);
1332 retryTimersRef.current.delete(nextQueuedMessage.messageId);
1333 }
1334 return;
1335 }
1336
1337 scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
1338 })
1339 .finally(() => {
1340 finishDispatchingQueuedMessage(nextQueuedMessage.messageId);
1341 });
1342 return;
1343 }
1344 }, [
1345 connectedEnvironments,
1346 dispatchingQueuedMessageId,
1347 editingQueuedMessageIds,
1348 projects,
1349 queuedMessagesByThreadKey,
1350 retryTick,
1351 restoreQueuedMessage,
1352 scheduleQueuedMessageRetry,
1353 sendQueuedCreation,
1354 sendQueuedMessage,
1355 serverConfigs,
1356 shellStatuses,
1357 threads,
1358 ]);
1359}