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

use-thread-outbox-drain.ts

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