feat: images upload the moment you attach them #6276
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 3 commits into
main fromt3code/support-arbitrary-attachmentsopened 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
- packages/contracts/src/assets.ts lines 78 to 87OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -38,0 +67,21 @@67+ attachmentId: AttachmentIdSchema,68+ relativeUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),69+ expiresAt: Schema.Number,70+});71+export type AttachmentCreateUploadUrlResult = typeof AttachmentCreateUploadUrlResult.Type;72+73+export const AttachmentDeleteInput = Schema.Struct({74+ attachmentId: AttachmentIdSchema,75+});76+export type AttachmentDeleteInput = typeof AttachmentDeleteInput.Type;77+78+export class AttachmentUploadRequestError extends Schema.TaggedErrorClass<AttachmentUploadRequestError>()(79+ "AttachmentUploadRequestError",80+ {81+ detail: Schema.String,82+ },83+) {84+ override get message(): string {85+ return this.detail;86+ }87+}apps/server/src/orchestration/Normalizer.ts lines 122 to 130Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -147,19 +119,11 @@147119 });148120 }149121150- yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(151- Effect.mapError(152- () =>153- new OrchestrationDispatchCommandError({154- message: `Failed to create attachment directory for '${attachment.name}'.`,155- }),156- ),157- );158- yield* fileSystem.writeFile(attachmentPath, bytes).pipe(122+ const stats = yield* fileSystem.stat(claimPlan.currentPath).pipe(159123 Effect.mapError(160124 () =>161125 new OrchestrationDispatchCommandError({162- message: `Failed to persist attachment '${attachment.name}'.`,126+ message: `Attachment '${attachment.name}' cannot be sent: attachment not found (removed or expired).`,163127 }),164128 ),165129 );
- apps/web/src/components/chat/ChatComposer.tsx line 2108Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2109,20 +2095 @@2109- if (!written) {2110- toastManager.add({2111- type: "error",2112- title: "Could not stash this prompt",2113- description:2114- "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",2115- data: { hideCopyButton: true },2116- });2117- return;2118- }2119- // Written but only into the in-memory fallback (localStorage blocked):2120- // the entry is visible and restorable this session, so proceed with the2121- // clear, but say it won't survive a reload.2122- if (!durable) {2123- toastManager.add({2124- type: "warning",2125- title: "Stashed prompt will not survive a reload",2126- description:2127- "Browser storage is unavailable, so this stash is kept in memory only for this session.",2128- data: { hideCopyButton: true },2095+ const attachments: PersistedComposerImageAttachment[] = [];apps/server/src/attachmentStore.ts line 199Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -88,0 +179,21 @@179+ const uuid = parseAttachmentUuid(input.attachmentId);180+ if (!uuid) {181+ return { ok: false, reason: "invalid attachment id" };182+ }183+ const threadSegment = toSafeThreadAttachmentSegment(input.threadId);184+ if (!threadSegment) {185+ return { ok: false, reason: "invalid thread id" };186+ }187+ const currentPath = findAttachmentPathByUuid({ attachmentsDir: input.attachmentsDir, uuid });188+ if (!currentPath) {189+ return { ok: false, reason: "attachment not found (removed or expired)" };190+ }191+ const fileName = NodePath.basename(currentPath);192+ const currentId = parseAttachmentIdFromRelativePath(fileName);193+ const currentSegment = currentId ? parseThreadSegmentFromAttachmentId(currentId) : null;194+ if (!currentSegment) {195+ return { ok: false, reason: "attachment file name is malformed" };196+ }197+ const extension = NodePath.extname(fileName);198+ const finalId = `${threadSegment}-${uuid}`;199+ if (currentSegment === threadSegment) {apps/web/src/components/ChatView.tsx line 5221Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5189,6 +5183,16 @@51895183 }51905184 }519151855192- const turnAttachmentsResult = await settlePromise(() => turnAttachmentsPromise);5193- if (failure === null && turnAttachmentsResult._tag === "Failure") {5194- failure = turnAttachmentsResult;5186+ // Attachments ride the turn as id references to bytes that uploaded the5187+ // moment they were attached. The composer blocks sending while an upload5188+ // is in flight, but the preview "pick and send" gesture attaches and sends5189+ // in one step, so wait for anything still running here.5190+ const settledUploads = await awaitAttachmentUploads(5191+ composerImagesSnapshot.map((image) => image.id),5192+ );5193+ const sendableImages = composerImagesSnapshot.map((image) => {5194+ const settledUpload = settledUploads.get(image.id);5195+ return settledUpload ? { ...image, upload: settledUpload } : image;5196+ });5197+ const turnAttachments = readyAttachmentRefs(sendableImages);5198+ const unsentImageNames = sendableImagesapps/web/src/lib/attachmentUploadQueue.ts line 321Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +246,21 @@246+ }247+}248+249+/** Re-runs a failed (or environment-stale) upload with the File still in memory. */250+export function retryAttachmentUpload(input: {251+ target: ComposerThreadTarget;252+ environmentId: EnvironmentId;253+ image: ComposerImageAttachment;254+}): void {255+ cancelAttachmentUpload(input.image.id);256+ startAttachmentUpload(input);257+}258+259+/**260+ * Resolves once every listed image has settled, keyed by image id. The send261+ * button is disabled while uploads run, but the preview-annotation "pick and262+ * send" path attaches and sends in one gesture, so it has to wait here — and263+ * it needs the settled states, because the draft it read them from is already264+ * cleared by then.265+ */266+export async function awaitAttachmentUploads(apps/web/src/components/ChatView.tsx line 4970Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4944,7 +4945,9 @@49444945 hasSendableContent,49454946 } = deriveComposerSendState({49464947 prompt: promptForSend,4947- imageCount: composerImages.length,4948+ // Only uploaded attachments count: an image still in flight (or failed)4949+ // is not sendable content, and the composer blocks the send anyway.4950+ imageCount: summarizeAttachmentUploads(composerImages).ready,49484951 terminalContexts: composerTerminalContexts,49494952 elementContextCount:49504953 composerElementContexts.length +apps/web/src/components/chat/ChatComposer.tsx line 1510Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1450,6 +1497,10 @@14501497 }, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);1451149814521499 // ------------------------------------------------------------------1453- // Image persist effect1500+ // Attachment environment retargeting14541501 // ------------------------------------------------------------------1502+ // The bytes live in exactly one environment. When a draft is pointed at a1503+ // different one, an attachment we still hold the File for is silently1504+ // re-uploaded; one restored after a reload has no File to re-send, so it1505+ // fails and has to be removed.14551506 useEffect(() => {
- apps/web/src/components/chat/ChatComposer.tsx line 2152Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -2141,8 +2125,13 @@2141- if (evicted) {2142- toastManager.add({2143- type: "warning",2144- title: "Oldest stashed prompt discarded",2145- description: `The stash holds ${MAX_STASH_ENTRIES} prompts; the oldest was removed to make room.`,2146- data: { hideCopyButton: true },2147- });2148- }2125+ // Clearing the composer is only safe once the write actually landed.2126+ // If it was rejected (quota) the store has already rolled itself back,2127+ // so leave the composer untouched rather than making it the second2128+ // casualty of a reload.2129+ if (!written) {2130+ toastManager.add({2131+ type: "error",2132+ title: "Could not stash this prompt",2133+ description:2134+ "Browser storage rejected the write, so the composer was left as-is. Free up site data and try again.",2135+ data: { hideCopyButton: true },2136+ });2137+ return;apps/web/src/components/ChatView.tsx line 5268Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -5235,4 +5249,4 @@52355249 messageId: messageIdForSend,52365250 role: "user",52375251 text: outgoingMessageText,5238- attachments: turnAttachmentsResult.value,5252+ attachments: turnAttachments,apps/web/src/composerDraftStore.ts line 1133Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1093,16 +1106,18 @@10931106 typeof name !== "string" ||10941107 typeof mimeType !== "string" ||10951108 typeof sizeBytes !== "number" ||10961109 !Number.isFinite(sizeBytes) ||1097- typeof dataUrl !== "string" ||1110+ typeof environmentId !== "string" ||10981111 id.length === 0 ||1099- dataUrl.length === 01112+ attachmentId.length === 0 ||1113+ environmentId.length === 011001114 ) {11011115 return null;11021116 }11031117 return {11041118 id,1119+ attachmentId,11051120 name,11061121 mimeType,11071122 sizeBytes,1108- dataUrl,1123+ environmentId,apps/web/src/lib/attachmentUploadQueue.ts line 312Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +237,21 @@237+238+/**239+ * Drops an image from the composer's point of view: cancels an in-flight240+ * upload, and releases the server copy when the upload already landed.241+ */242+export function releaseComposerAttachment(image: ComposerImageAttachment): void {243+ cancelAttachmentUpload(image.id);244+ if (image.upload.status === "ready") {245+ deleteAttachment(image.upload.environmentId, image.upload.attachmentId);246+ }247+}248+249+/** Re-runs a failed (or environment-stale) upload with the File still in memory. */250+export function retryAttachmentUpload(input: {251+ target: ComposerThreadTarget;252+ environmentId: EnvironmentId;253+ image: ComposerImageAttachment;254+}): void {255+ cancelAttachmentUpload(input.image.id);256+ startAttachmentUpload(input);257+}apps/mobile/src/features/threads/NewTaskDraftScreen.tsx line 615Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -693,3 +696,6 @@693696 if (result.images.length > 0) {694697 flow.appendAttachments(result.images);695698 }699+ if (result.error) {700+ setPendingConnectionError(result.error);701+ }
- apps/web/src/components/chat/ChatComposer.tsx line 1512OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1450,11 +1498,15 @@14501498 }, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);1451149914521500 // ------------------------------------------------------------------1453- // Image persist effect1501+ // Attachment environment retargeting14541502 // ------------------------------------------------------------------1503+ // The bytes live in exactly one environment. When a draft is pointed at a1504+ // different one, an attachment we still hold the File for is silently1505+ // re-uploaded (releasing the old environment's copy first, so nothing1506+ // orphans there). One restored after a reload has no File to re-send; its1507+ // ready state is left intact and the mismatch is rendered and send-gated1508+ // as a derived condition, so switching back recovers it.14551509 useEffect(() => {1456- let cancelled = false;1457- void (async () => {1458- if (composerImages.length === 0) {1459- clearComposerDraftPersistedAttachments(composerDraftTarget);1460- return;1510+ for (const image of composerImages) {1511+ if (resolveAttachmentEnvironmentAction(image, environmentId) === "reupload") {1512+ releaseComposerAttachment(image);apps/server/src/assets/AttachmentUpload.ts line 167Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +141,21 @@141+ } satisfies StoreUploadResult;142+ }143+ const config = yield* ServerConfig.ServerConfig;144+ const extension = inferImageExtension({ mimeType: claims.mimeType });145+ const relativePath = `${claims.attachmentId}${extension}`;146+ const finalPath = resolveAttachmentRelativePath({147+ attachmentsDir: config.attachmentsDir,148+ relativePath,149+ });150+ const partPath = resolveAttachmentRelativePath({151+ attachmentsDir: config.attachmentsDir,152+ relativePath: `${relativePath}.part`,153+ });154+ if (!finalPath || !partPath) {155+ return { ok: false, status: 500, detail: "Failed to resolve attachment path." };156+ }157+ const fileSystem = yield* FileSystem.FileSystem;158+ const path = yield* Path.Path;159+ const writeResult = yield* Effect.gen(function* () {160+ yield* fileSystem.makeDirectory(path.dirname(finalPath), { recursive: true });161+ yield* fileSystem.writeFile(partPath, bytes);@@ -5206,7 +5200,8 @@52065200 }52075201 }520852025209- const turnAttachmentsResult = await settlePromise(() => turnAttachmentsPromise);5210- if (failure === null && turnAttachmentsResult._tag === "Failure") {5211- failure = turnAttachmentsResult;5212- }5203+ // Attachments ride the turn as id references to bytes that uploaded the5204+ // moment they were attached. The composer blocks sending while an upload5205+ // is in flight, but the preview "pick and send" gesture attaches and sends5206+ // in one step, so wait for anything still running here.5207+ const settledUploads = await awaitAttachmentUploads(
- apps/web/src/lib/attachmentUploadQueue.ts line 136Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +98,21 @@98+ xhr.open("POST", url, true);99+ xhr.setRequestHeader("Content-Type", mimeType);100+ xhr.upload.addEventListener("progress", (event) => {101+ if (event.lengthComputable && event.total > 0) {102+ onProgress(event.loaded / event.total);103+ }104+ });105+ xhr.addEventListener("load", () => {106+ if (xhr.status >= 200 && xhr.status < 300) {107+ resolve("ok");108+ return;109+ }110+ reject(new Error(`Upload rejected (${xhr.status})`));111+ });112+ xhr.addEventListener("abort", () => resolve("aborted"));113+ xhr.addEventListener("error", () => reject(new Error("Upload failed")));114+ xhr.addEventListener("timeout", () => reject(new Error("Upload timed out")));115+ xhr.send(file);116+ });117+ return { done, abort: () => xhr.abort() };118+}apps/web/src/components/ChatView.tsx line 4967Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -4961,4 +4962,6 @@49614962 hasSendableContent,49624963 } = deriveComposerSendState({49634964 prompt: promptForSend,4964- imageCount: composerImages.length,4965+ // Only uploaded attachments count: an image still in flight (or failed)4966+ // is not sendable content, and the composer blocks the send anyway.4967+ imageCount: summarizeAttachmentUploads(composerImages, environmentId).ready,apps/mobile/src/lib/composerImages.ts line 164OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -138,3 +159,6 @@138159 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;139160140161 if (await clipboard.hasImageAsync()) {162+ if (!IMAGE_ATTACH_ENABLED) {163+ return { images: [], text: null, error: IMAGE_ATTACH_UNAVAILABLE_MESSAGE };164+ }
t3dotgg(GitHub profile, opens in a new tab) closed this
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:
bf950256-a9a4-410e-98ba-2154f6f01183You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share