Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-thread-outbox-drain.ts

1,338 lines51.9 KB

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