feat(mobile): pick, share, and receive files in threads #8237
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 26 commits into
main fromrefs/pull/8237/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labels📱 Native Change
- apps/mobile/src/state/use-composer-drafts.ts line 669OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -601,4 +664,6 @@601664 draftKey: string,602665 options?: { readonly clearWorkspaceSelection?: boolean },603666 ): void {667+ const previousAttachments = getComposerDraftSnapshot(draftKey).attachments;604668 updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey, options));669+ scheduleUnusedComposerAttachmentCleanup(previousAttachments);apps/mobile/src/state/use-thread-outbox-drain.ts line 179OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -87,0 +159,21 @@159+ }160+ const originalDraft = getComposerDraftSnapshot(draftKey);161+ const existingAttachmentIds = new Set(162+ originalDraft.attachments.map((attachment) => attachment.id),163+ );164+ const addedAttachmentCount = queuedMessage.attachments.filter(165+ (attachment) => !existingAttachmentIds.has(attachment.id),166+ ).length;167+ if (existingAttachmentIds.size + addedAttachmentCount > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {168+ setPendingConnectionError(169+ `Remove attachments from the draft before restoring this message. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,170+ );171+ return "blocked";172+ }173+174+ await mergeComposerDraftContent(draftKey, {175+ text: queuedMessage.text,176+ attachments: queuedMessage.attachments,177+ });178+ if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {179+ await restoreComposerDraftSnapshot(draftKey, originalDraft);apps/mobile/src/state/use-thread-outbox-drain.ts line 208OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -87,0 +188,21 @@188+ workspaceSelection: {189+ mode: queuedMessage.creation.workspaceMode,190+ branch: queuedMessage.creation.branch,191+ worktreePath: queuedMessage.creation.worktreePath,192+ ...(queuedMessage.creation.startFromOrigin !== undefined193+ ? { startFromOrigin: queuedMessage.creation.startFromOrigin }194+ : {}),195+ },196+ }197+ : {}),198+ });199+ await flushComposerDrafts();200+ if (201+ appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] ||202+ !(await confirmThreadOutboxMessageQueued(queuedMessage)) ||203+ appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]204+ ) {205+ await restoreComposerDraftSnapshot(draftKey, originalDraft);206+ return "deferred";207+ }208+ await removeThreadOutboxMessage(queuedMessage);apps/mobile/src/lib/composerImages.ts lines 114 to 114Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -29,0 +91,21 @@91+ }92+ } finally {93+ writer.close();94+ }95+ } finally {96+ reader.close();97+ }98+ } catch (error) {99+ if (destination.exists) {100+ destination.delete();101+ }102+ throw error;103+ }104+ return destination.uri;105+ }106+107+ if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {108+ throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));109+ }110+ try {111+ await source.copy(destination);
- apps/mobile/src/features/threads/NewTaskDraftScreen.tsx line 510OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -469,4 +501,10 @@469501 if (!shareImportMountedRef.current || activeShareImportTokenRef.current !== importToken) {470502 return;471503 }472- const warnings = [...incomingShare.warnings];504+ const retainedAttachmentIds = new Set(505+ getComposerDraftSnapshot(draftKey).attachments.map((attachment) => attachment.id),506+ );507+ const rejectedAttachments = incomingShare.attachments.filter(508+ (attachment) => !retainedAttachmentIds.has(attachment.id),509+ );510+ scheduleUnusedComposerAttachmentCleanup(rejectedAttachments);apps/mobile/src/state/thread-outbox-manager.ts line 195Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -145,3 +161,6 @@145161 cause,146162 });147163 }164+ if (staleOrMissing()) {165+ return false;166+ }
- apps/mobile/src/state/use-thread-composer-state.ts line 355Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -304,3 +305,19 @@304305 }305306 }, [composerDrafts, selectedThreadShell]);306307308+ const onPickDraftFiles = useCallback(async () => {309+ if (!selectedThreadShell) {310+ return;311+ }312+ const maxBytes =313+ selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments314+ ?.maxUploadBytes;315+ if (maxBytes === undefined) {316+ Alert.alert("Could not attach file", "This server does not support file attachments.");317+ return;318+ }319+320+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);321+ // pickComposerFiles clamps the advertised limit to the contract maximum.322+ const result = await pickComposerFiles({323+ existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,
- apps/mobile/src/state/use-thread-composer-state.ts line 340Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -304,3 +305,4 @@304305 }305306 }, [composerDrafts, selectedThreadShell]);306307308+ const onPickDraftFiles = useCallback(async () => {apps/mobile/src/lib/composerImages.ts line 227Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -29,0 +200,21 @@200+ try {201+ const fileUri = await persistComposerAttachmentFile(file.uri, file.name, maxBytes);202+ const storedSizeBytes = new File(fileUri).size ?? sizeBytes ?? 0;203+ if (storedSizeBytes <= 0) {204+ await removePersistedComposerAttachmentFile(fileUri);205+ error = `'${file.name}' is empty or could not be read.`;206+ continue;207+ }208+ if (storedSizeBytes > maxBytes) {209+ await removePersistedComposerAttachmentFile(fileUri);210+ error = fileAttachmentTooLargeMessage(file.name, maxBytes);211+ continue;212+ }213+ attachments.push({214+ id: uuidv4(),215+ type: "file",216+ name: file.name,217+ mimeType: file.type || "application/octet-stream",218+ sizeBytes: storedSizeBytes,219+ fileUri,220+ });
- apps/mobile/src/state/use-composer-drafts.ts lines 933 to 943Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -599,0 +719,21 @@719+ return restoreComposerDraftSnapshotState(current, draftKey, snapshot);720+ }721+ const insertedText = merged.text.startsWith(snapshot.text)722+ ? merged.text.slice(snapshot.text.length)723+ : "";724+ const snapshotAttachmentIds = new Set(snapshot.attachments.map((attachment) => attachment.id));725+ const insertedAttachmentIds = new Set(726+ merged.attachments727+ .filter((attachment) => !snapshotAttachmentIds.has(attachment.id))728+ .map((attachment) => attachment.id),729+ );730+ const draft = {731+ ...existing,732+ text:733+ insertedText.length > 0 && existing.text.endsWith(insertedText)734+ ? existing.text.slice(0, existing.text.length - insertedText.length)735+ : existing.text,736+ attachments: existing.attachments.filter(737+ (attachment) => !insertedAttachmentIds.has(attachment.id),738+ ),739+ };
- apps/mobile/src/features/sharing/incoming-share-model.ts line 367Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -160,0 +290,21 @@290+ }291+ continue;292+ }293+ if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {294+ warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));295+ if (persistedFileUri) {296+ await releaseOwnedFiles(input.fileReader, [persistedFileUri]);297+ }298+ continue;299+ }300+ if (persistedFileUri === undefined && input.fileReader.persistFile) {301+ persistedFileUri = await input.fileReader.persistFile(uri, name);302+ }303+ attachments.push({304+ id: `${input.id}:file:${index}`,305+ type: "file",306+ name,307+ mimeType,308+ sizeBytes,309+ fileUri: persistedFileUri ?? uri,310+ });
- apps/mobile/src/features/threads/ThreadFeed.tsx lines 277 to 277OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -204,0 +257,21 @@257+ _tag: "attachment",258+ attachmentId: attachment.id,259+ fileName: attachment.name,260+ mimeType: attachment.mimeType,261+ },262+ },263+ });264+ if (result._tag === "Failure") {265+ const error = squashAtomCommandFailure(result);266+ Alert.alert(267+ "Could not open attachment",268+ error instanceof Error ? error.message : "The attachment is unavailable.",269+ );270+ return;271+ }272+ const url = resolveAssetUrl(273+ preparedConnection.value.httpBaseUrl,274+ result.value.relativeUrl,275+ );276+ if (url !== null) {277+ await tryOpenExternalUrl(url, "file-preview");apps/mobile/src/state/use-thread-composer-state.ts line 293Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -264,6 +261,15 @@264- void mergeComposerDraftContent(threadKey, { text, attachments: [] });265- appendComposerDraftAttachments(threadKey, attachments);266- setPendingConnectionError(267- error instanceof Error ? error.message : "Failed to save the queued message.",268- );269- });261+ clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });262+ enqueuePromise.then(263+ () => {264+ // The queued message owns the files now; the sweep sees that and265+ // spares them. Deferred to here so a failed write cannot roll the266+ // message out of the queue mid-sweep and lose the bytes.267+ scheduleUnusedComposerAttachmentCleanup(attachments);268+ },269+ (error: unknown) => {270+ // Restore text via merge (idempotent) but attachments via the uncapped271+ // append: the merge path slots existing attachments first and truncates272+ // at the send limit, which would silently drop this message's images if273+ // the user attached new ones while the write was in flight.274+ void mergeComposerDraftContent(threadKey, { text, attachments: [] });275+ appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });apps/mobile/src/state/use-thread-composer-state.ts lines 339 to 339OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -306,0 +319,21 @@319+ if (!selectedThreadShell) {320+ return;321+ }322+ const maxBytes =323+ selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments324+ ?.maxUploadBytes;325+ if (maxBytes === undefined) {326+ Alert.alert("Could not attach file", "This server does not support file attachments.");327+ return;328+ }329+330+ const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);331+ // pickComposerFiles clamps the advertised limit to the contract maximum.332+ const result = await pickComposerFiles({333+ existingCount: composerDrafts[threadKey]?.attachments.length ?? 0,334+ maxBytes,335+ });336+ const rejectedCount = appendComposerDraftAttachments(threadKey, result.files);337+ if (result.error) {338+ Alert.alert("Could not attach file", result.error);339+ } else if (rejectedCount > 0) {apps/mobile/src/state/use-thread-outbox-drain.ts line 416OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -150,4 +412,5 @@150412 }151413152414 try {415+ // Removal also releases the message's local attachment files.153416 await removeThreadOutboxMessage(queuedMessage);apps/mobile/src/state/use-thread-composer-state.ts lines 71 to 71OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -65,4 +68,4 @@6568 const separator = existing.trim().length > 0 && !existing.endsWith("\n") ? "\n\n" : "";6669 setComposerDraftText(threadKey, `${existing}${separator}${input.text}`);6770 if (input.attachments && input.attachments.length > 0) {68- appendComposerDraftAttachments(threadKey, input.attachments);71+ appendComposerDraftAttachments(threadKey, input.attachments, { allowOverflow: true });apps/mobile/src/features/sharing/incoming-share-model.ts lines 306 to 309OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -160,0 +289,21 @@289+ await releaseOwnedFiles(input.fileReader, [persistedFileUri]);290+ }291+ continue;292+ }293+ if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {294+ warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES));295+ if (persistedFileUri) {296+ await releaseOwnedFiles(input.fileReader, [persistedFileUri]);297+ }298+ continue;299+ }300+ if (persistedFileUri === undefined && input.fileReader.persistFile) {301+ persistedFileUri = await input.fileReader.persistFile(uri, name);302+ // An Android content: source can under-report its size while still303+ // delivering more bytes. The stored copy is what uploads, so its304+ // measured size is what the attachment must record.305+ const storedSize = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;306+ if (storedSize !== null && storedSize > 0) {307+ sizeBytes = storedSize;308+ }309+ if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
- apps/mobile/src/features/sharing/IncomingShareProvider.tsx line 163Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -131,6 +153,11 @@131153 clearPayloads: clearSharedPayloads,132154 buildDraft: async ({ payloads, id, createdAt }) => {133155 const cleanupUris = new Set<string>();134- const resolvedPayloads = payloads.some((payload) => payload.shareType === "image")135- ? await resolvedPayloadsForImages()136- : [];156+ const persistedUris = new Set<string>();157+ const hasGenericFilePayload = payloads.some((payload) =>158+ ["file", "audio", "video"].includes(payload.shareType),159+ );160+ const resolvedPayloads =161+ !hasGenericFilePayload && payloads.some((payload) => payload.shareType === "image")162+ ? await resolvedPayloadsForFiles()163+ : [];apps/mobile/src/state/thread-outbox-removal.ts line 40OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+ expectedRevision?: number,21+): Promise<boolean> {22+ if (!(await threadOutboxManager.remove(message, expectedRevision))) {23+ return false;24+ }25+ scheduleUnusedComposerAttachmentCleanup(message.attachments);26+ return true;27+}28+29+/** Removes every queued message of an environment and releases their files. */30+export async function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise<void> {31+ // Load first so persisted-but-not-yet-hydrated messages contribute their32+ // attachments to the release set.33+ await threadOutboxManager.load();34+ const removedAttachments = flattenQueuedThreadMessages(35+ appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),36+ )37+ .filter((message) => message.environmentId === environmentId)38+ .flatMap((message) => message.attachments);39+ await threadOutboxManager.clearEnvironment(environmentId);40+ scheduleUnusedComposerAttachmentCleanup(removedAttachments);
- apps/mobile/src/state/use-thread-outbox-drain.ts line 435Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -87,0 +210,21 @@210+ appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId] ||211+ !(await confirmThreadOutboxMessageQueued(queuedMessage)) ||212+ appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]213+ ) {214+ await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft);215+ return "deferred";216+ }217+ // Revision-checked: an edit that landed after the confirmation above218+ // must not be deleted with the pre-edit payload this recovery restored.219+ if (!(await removeThreadOutboxMessage(queuedMessage, revision))) {220+ await undoComposerDraftMerge(draftKey, originalDraft, restoredDraft);221+ return "deferred";222+ }223+ setPendingConnectionError(message);224+ return "restored";225+ } catch (error) {226+ console.warn("[thread-outbox] failed to restore an undeliverable message", error);227+ setPendingConnectionError(228+ error instanceof Error ? error.message : "The unsent message could not be restored.",229+ );230+ return "retry";
- apps/mobile/src/features/threads/NewTaskDraftScreen.tsx line 738Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -621,0 +666,21 @@666+ async function handlePickFiles(): Promise<void> {667+ if (isComposerInteractionLocked) {668+ return;669+ }670+ const maxBytes =671+ selectedEnvironmentServerConfig?.environment.capabilities.fileAttachments?.maxUploadBytes;672+ if (maxBytes === undefined) {673+ Alert.alert("File attachments are not available on this server.");674+ return;675+ }676+ const result = await pickComposerFiles({677+ existingCount: flow.attachments.length,678+ maxBytes,679+ });680+ if (result.files.length > 0) {681+ flow.appendAttachments(result.files);682+ }683+ if (result.error) {684+ Alert.alert("Could not attach file", result.error);685+ }686+ }
- apps/mobile/src/state/use-thread-outbox-drain.ts line 173OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -87,0 +153,21 @@153+ * retry pass that delivers the newer payload instead of silently dropping it154+ * with the old one. Exported for tests.155+ */156+export async function completeQueuedMessageDelivery(157+ queuedMessage: QueuedThreadMessage,158+ deliveryRevision: number,159+): Promise<boolean> {160+ try {161+ // Removal also releases the message's local attachment files.162+ const removed = await removeThreadOutboxMessage(queuedMessage, deliveryRevision);163+ if (!removed) {164+ console.warn(165+ "[thread-outbox] delivered message was edited before cleanup; keeping the newer message",166+ {167+ environmentId: queuedMessage.environmentId,168+ threadId: queuedMessage.threadId,169+ messageId: queuedMessage.messageId,170+ },171+ );172+ }173+ return removed;apps/mobile/src/features/sharing/incoming-share-model.ts line 302Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -153,8 +245,20 @@153245 );154246 warnedAttachmentLimit = true;155247 }156248 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);157249 continue;158250 }159251160- const mimeType = (resolved?.contentMimeType ?? payload.mimeType ?? "image/png").toLowerCase();252+ const mimeType = (253+ resolved?.contentMimeType ??254+ payload.mimeType ??255+ (payload.shareType === "image" ? "image/png" : "application/octet-stream")256+ ).toLowerCase();257+ if (payload.shareType !== "image") {258+ // The patched native module never emits a blank display name, but keep259+ // the guard: an empty name would fail the attachment name contract.260+ const sharedFileName =261+ typeof payload.originalName === "string" && payload.originalName.trim().length > 0262+ ? payload.originalName263+ : undefined;264+ const name = resolved?.originalName ?? sharedFileName ?? fallbackName(uri, index, mimeType);
- apps/mobile/src/state/use-thread-outbox-drain.ts line 210OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -87,0 +190,21 @@190+ * edited payload is still queued. The next drain would see the created thread191+ * and take the creation "remove" path, silently discarding the edit; hand the192+ * edited content to the new thread's composer instead and remove the entry.193+ * Exported for tests; the drain is the only production caller.194+ */195+export async function recoverEditedCreationAfterDelivery(196+ queuedMessage: QueuedThreadMessage,197+): Promise<void> {198+ const kept = Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))199+ .flat()200+ .find((candidate) => candidate.messageId === queuedMessage.messageId);201+ if (!kept) {202+ return;203+ }204+ const draftKey = scopedThreadKey(kept.environmentId, kept.threadId);205+ // Merge before removing: the draft's reference keeps the removal sweep from206+ // deleting the attachment files. allowOverflow mirrors the send-failure207+ // restore; the send path refuses over-cap drafts, so the state stays208+ // recoverable.209+ await mergeComposerDraftContent(draftKey, { text: kept.text, attachments: [] });210+ appendComposerDraftAttachments(draftKey, kept.attachments, { allowOverflow: true });
- apps/mobile/src/features/threads/NewTaskDraftScreen.tsx line 556OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -503,5 +547,10 @@503547 setIsCancellingShareImport(true);504548 try {505549 if (needsDraftRestore) {550+ // The restore drops the share's merged-in attachments551+ // from the draft; with the inbox entry already consumed552+ // nothing references their files, so sweep them.553+ const mergedAttachments = getComposerDraftSnapshot(draftKey).attachments;506554 await restoreComposerDraftSnapshot(draftKey, draftBackup);507555 needsDraftRestore = false;556+ scheduleUnusedComposerAttachmentCleanup(mergedAttachments);apps/mobile/src/state/use-thread-outbox-drain.ts line 1074Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -391,16 +876,4 @@391876 return;392877 }393878394- const retryAttempt = (retryAttemptRef.current.get(nextQueuedMessage.messageId) ?? 0) + 1;395- retryAttemptRef.current.set(nextQueuedMessage.messageId, retryAttempt);396- const retryDelayMs = threadOutboxRetryDelayMs(retryAttempt);397- retryNotBeforeRef.current.set(nextQueuedMessage.messageId, Date.now() + retryDelayMs);398- const pendingTimer = retryTimersRef.current.get(nextQueuedMessage.messageId);399- if (pendingTimer !== undefined) {400- clearTimeout(pendingTimer);401- }402- const retryTimer = setTimeout(() => {403- retryTimersRef.current.delete(nextQueuedMessage.messageId);404- setRetryTick((current) => current + 1);405- }, retryDelayMs);406- retryTimersRef.current.set(nextQueuedMessage.messageId, retryTimer);879+ scheduleQueuedMessageRetry(nextQueuedMessage.messageId);
- apps/mobile/src/state/use-composer-drafts.ts line 574Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -314,9 +380,18 @@380+ * live state (callers may have counted before an await; the picker can race381+ * concurrent adds). Overflowed file attachments are released. Returns how many382+ * were rejected. Restore paths pass allowOverflow so a failed send never drops383+ * the message's own attachments.384+ */314385 export function appendComposerDraftAttachments(315386 draftKey: string,316- attachments: ReadonlyArray<DraftComposerImageAttachment>,317-): void {387+ attachments: ReadonlyArray<DraftComposerAttachment>,388+ options?: { readonly allowOverflow?: boolean },389+): number {318390 if (attachments.length === 0) {319- return;391+ return 0;320392 }393+ let rejected: ReadonlyArray<DraftComposerAttachment> = [];321394 updateComposerDrafts((current) => {322395 const existing = normalizeDraft(current[draftKey]);396+ const remaining = options?.allowOverflow397+ ? attachments.lengthapps/mobile/src/state/thread-outbox-removal.ts line 34OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+ * `expectedRevision` (from `threadOutboxRevision`) makes the removal a15+ * compare-and-set: when an edit was accepted since the revision was read, the16+ * newer message stays queued, nothing is released, and this returns false.17+ */18+export async function removeThreadOutboxMessage(19+ message: QueuedThreadMessage,20+ expectedRevision?: number,21+): Promise<boolean> {22+ if (!(await threadOutboxManager.remove(message, expectedRevision))) {23+ return false;24+ }25+ scheduleUnusedComposerAttachmentCleanup(message.attachments);26+ return true;27+}28+29+/** Removes every queued message of an environment and releases their files. */30+export async function clearThreadOutboxEnvironment(environmentId: EnvironmentId): Promise<void> {31+ // Load first so persisted-but-not-yet-hydrated messages contribute their32+ // attachments to the release set.33+ await threadOutboxManager.load();34+ const removedAttachments = flattenQueuedThreadMessages(docs/user/composer.md lines 13 to 16OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -10,5 +10,7 @@1010 can read, copy, or edit them by their file path.11111212 On web and desktop, attachments upload as soon as you add them. The send button becomes available13-after every upload finishes. Failed uploads can be retried or removed. On mobile, attachments are14-currently limited to images.13+after every upload finishes. Failed uploads can be retried or removed. On mobile, the **+** control14+offers Photos and Files, and you can share a file into T3 Code from any app through the system share15+sheet. Mobile uploads happen when the message sends, so queued messages keep their files until they16+deliver.
- apps/mobile/src/state/use-composer-drafts.ts line 263OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -231,0 +243,21 @@243+}244+245+export async function releaseUnusedComposerAttachmentFiles(246+ attachments: ReadonlyArray<DraftComposerAttachment>,247+): Promise<void> {248+ const candidates = new Set(249+ attachments250+ .filter((attachment) => attachment.type === "file")251+ .map((attachment) => attachment.fileUri),252+ );253+ if (candidates.size === 0) {254+ return;255+ }256+257+ // Persisted drafts must hydrate before the reference scan. On a cold start258+ // the atom is still empty, and every file a persisted draft owns would look259+ // unused. Hydrate before flushing so a pending pre-hydration write cannot260+ // land an incomplete snapshot either.261+ await waitForComposerDraftsLoaded();262+ await flushComposerDrafts();263+ await threadOutboxManager.load();apps/mobile/src/state/thread-outbox-manager.ts lines 230 to 230OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -165,6 +218,13 @@165218 cause,166219 });167220 }221+ if (revisionChanged()) {222+ // An enqueue replaced this message while the durable remove was in223+ // flight; its serialized write lands after this mutation and restores224+ // the disk entry. Keep the newer message published.225+ return false;226+ }168227 setMessages(169228 currentMessages().filter((candidate) => candidate.messageId !== message.messageId),170229 );230+ revisions.delete(message.messageId);apps/mobile/src/state/use-thread-outbox-drain.ts lines 224 to 225OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -87,0 +205,21 @@205+ * and take the creation "remove" path, silently discarding the edit; hand the206+ * edited content to the new thread's composer instead and remove the entry.207+ * Exported for tests; the drain is the only production caller.208+ */209+export async function recoverEditedCreationAfterDelivery(210+ queuedMessage: QueuedThreadMessage,211+): Promise<void> {212+ const kept = Object.values(appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom))213+ .flat()214+ .find((candidate) => candidate.messageId === queuedMessage.messageId);215+ if (!kept) {216+ return;217+ }218+ const draftKey = scopedThreadKey(kept.environmentId, kept.threadId);219+ try {220+ // Merge before removing: the draft's reference keeps the removal sweep221+ // from deleting the attachment files. allowOverflow mirrors the222+ // send-failure restore; the send path refuses over-cap drafts, so the223+ // state stays recoverable.224+ await mergeComposerDraftContent(draftKey, { text: kept.text, attachments: [] });225+ appendComposerDraftAttachments(draftKey, kept.attachments, { allowOverflow: true });apps/mobile/src/features/threads/new-task-flow-provider.tsx line 986OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -969,6 +979,8 @@969979 }970980971981 // update() rewrites the task only if it is still queued — a concurrent972- // delete or delivery wins, so the flush cannot resurrect it.973- void updateThreadOutboxMessage(message)982+ // delete or delivery wins, so the flush cannot resurrect it. The CAS983+ // revision keeps a dismissed session's stale payload from overwriting984+ // an edit accepted since this session took the task.985+ void updateThreadOutboxMessage(message, editingRevisionRef.current)974986 .then(() => {apps/mobile/src/state/use-thread-outbox-drain.ts line 730OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -277,4 +717,14 @@277717 worktreeBranchName: buildTemporaryWorktreeBranchName(randomHex),278718 }),279719 });280- return completeDelivery(deliveryResult);720+ const { reportFailure } = makeDeliveryHelpers(queuedMessage);721+ if (reportFailure(deliveryResult, "start-turn")) {722+ return false;723+ }724+ const outcome = await completeQueuedMessageDelivery(queuedMessage, deliveryRevision);725+ if (outcome === "edited") {726+ if (appAtomRegistry.get(editingQueuedMessageIdsAtom)[queuedMessage.messageId]) {727+ // The editor holds the entry with unsaved edits; merging the queue728+ // payload now would duplicate the delivered turn. Mark it so the729+ // eventual duplicate-creation removal recovers the saved edits.730+ creationsDeliveredWhileEditing.add(queuedMessage.messageId);
- apps/mobile/src/state/thread-outbox-removal.ts line 81Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +5,21 @@5+import { scheduleUnusedComposerAttachmentCleanup } from "./use-composer-drafts";6+7+/**8+ * The only way a queued message leaves the outbox. Removal also releases the9+ * message's local attachment files (via the reference-counting sweep, so a10+ * file still referenced by a draft or another queued message survives).11+ * Keeping release inside the removal call means no call site can forget it.12+ *13+ * `expectedRevision` (from `threadOutboxRevision`) makes the removal a14+ * compare-and-set: when an edit was accepted since the revision was read, the15+ * newer message stays queued, nothing is released, and this returns false.16+ */17+export async function removeThreadOutboxMessage(18+ message: QueuedThreadMessage,19+ expectedRevision?: number,20+): Promise<boolean> {21+ if (!(await threadOutboxManager.remove(message, expectedRevision))) {22+ return false;23+ }24+ scheduleUnusedComposerAttachmentCleanup(message.attachments);25+ return true;
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
d51fc70d-16a6-428e-9201-57b6bba5e435You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Warning
Your free Security trial is over. An organization admin can activate Security or dismiss this notice.
Comment `@coderabbitai help` to get the list of available commands.