From a50ada6827e41892dd4740708ea41eaeef0d7f94 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 9 Nov 2026 15:21:34 +0000 Subject: [PATCH] CONTRACT: feat(ui-react): upload every image as its original, with a frame that names it (#3155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a host with composer files, a picked, pasted, dropped or camera image is uploaded as its exact bytes through POST /api/drafts/:draftId/files, like every other file, and binds to the draft as an original (fileIds, snapshot fileIds, attachmentRefs). Once the host stores it as kind image with reader image, the composer derives the inline frame it always prepared (fileToAttachment) from those bytes, or after a reload from GET /api/attachments/:fileId, and sends it with ChatImageAttachment.fileId naming the original. The host charges the pair once. Frames are page state (lib/image-frames.ts), never draft content, so a draft with images now sends through an outgoing snapshot; dispatch waits for its frames. Frames go inline in file order within MAX_IMAGES_PER_MESSAGE and MAX_TOTAL_IMAGE_BYTES, after any legacy image; past that, or with no frame, the original goes alone and its chip says "not shown inline" (design §8.4). Preview URLs are revoked once no draft, snapshot or send names the original. Legacy draft images and hosts without composer files keep the inline path. A sent image's row makes no read claim. Runtime fixtures count image originals as images, and the parallel-sessions scripted backend now records the attachment block a real backend keeps. Co-Authored-By: Claude Opus 5.5 --- .changeset/composer-image-originals.md | 5 + docs/decisions/chat-attachments.md | 40 ++- docs/integration-contract.md | 3 + docs/integration-contract/wire.md | 14 + docs/plans/chat-history-deletion.md | 2 +- docs/process/test-waits.md | 4 +- .../src/components/chat/composer-view.tsx | 15 +- .../ui-react/src/components/chat/composer.tsx | 67 ++-- .../src/components/chat/file-chip.tsx | 8 +- packages/ui-react/src/lib/attachment-queue.ts | 14 +- packages/ui-react/src/lib/draft-client.ts | 27 +- packages/ui-react/src/lib/draft-files.ts | 18 +- packages/ui-react/src/lib/image-frames.ts | 183 +++++++++++ packages/ui-react/src/lib/track-attachment.ts | 5 +- .../tests/auth-expiry-runtime.test.ts | 8 +- .../composer-image-originals.offline.tsx | 306 ++++++++++++++++++ .../connection-continuity-runtime.test.ts | 24 +- packages/ui-react/tests/draft-runtime.test.ts | 8 +- .../tests/fixtures/auth-expiry-client.ts | 7 +- .../fixtures/connection-continuity-client.tsx | 2 +- .../tests/fixtures/draft-runtime-client.ts | 4 +- .../tests/fixtures/local-work-client.ts | 4 +- .../fixtures/parallel-sessions-client.tsx | 4 +- .../tests/parallel-sessions-runtime.test.ts | 12 +- packages/ui-react/tests/snapshot-host.ts | 28 +- 25 files changed, 733 insertions(+), 79 deletions(-) create mode 100644 .changeset/composer-image-originals.md create mode 100644 packages/ui-react/src/lib/image-frames.ts create mode 100644 packages/ui-react/tests/browser/composer-image-originals.offline.tsx diff --git a/.changeset/composer-image-originals.md b/.changeset/composer-image-originals.md new file mode 100644 index 0000000000..2e147dc09a --- /dev/null +++ b/.changeset/composer-image-originals.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-react": minor +--- + +On a host with composer files, a picked, pasted, dropped or camera image is now uploaded as its exact original through the same route as every other file (#3155). The host's detection names it an image, and the composer derives the inline frame from that original, as before. Sent with the message, the frame names its original (`ChatImageAttachment.fileId`), so the agent gets the image to see and the real file to open, charged once. An image past the per-message frame budget, or one no frame can be made of, is sent as its original only and says `not shown inline`. Image originals bind to the draft like other files, so a draft with images now sends through an outgoing snapshot and comes back after a reload. Legacy draft images of existing drafts, and every image on a host without composer files, keep the old inline path. A sent image's row makes no claim about reading. diff --git a/docs/decisions/chat-attachments.md b/docs/decisions/chat-attachments.md index 8d45123444..9c11cc85eb 100644 --- a/docs/decisions/chat-attachments.md +++ b/docs/decisions/chat-attachments.md @@ -265,11 +265,36 @@ originals, on a host that advertises `composerFiles`: Photo library or Camera. A phone keeps both beside Files. The Files input has no `accept`, and paste and drop feed the same pipeline. A host without `composerFiles` keeps the old menu and D52's tab-only track queue. -- **One route for everything but images.** Every file that is not an image +- **One route for everything, images included.** Every file, an image too, goes to `POST /api/drafts/:draftId/files` as its raw bytes. The client - never routes by MIME type or extension; detection is the host's. Images - keep their existing frame processing. They do not upload an original yet, - so the image half of "a real file for every attachment" is still open. + never routes by MIME type or extension; detection is the host's. +- **An image is an original plus a derived frame.** Once the host stores a + file as `kind: "image"` with `reader: "image"`, the composer prepares the + frame it always did (`fileToAttachment`) from the bytes just uploaded, or, + after a reload, from the original read back (`GET + /api/attachments/:fileId`). The frame is page state: drafts, snapshots and + saves name only the original, so a draft with images sends through a + snapshot and survives reload like any other. The message carries the + original in `attachmentRefs` and the frame with `fileId` naming it, and the + host charges the pair once. Choices this forces: + - **The frame budget is per message, in file order.** Frames go inline + while `MAX_IMAGES_PER_MESSAGE` and `MAX_TOTAL_IMAGE_BYTES` allow, after + any legacy inline image. Past them, or when no frame can be made (too + small, undecodable, still too large after downscaling), the original goes + alone and its chip says *not shown inline*, with *Your agent gets the file + but not a preview.* An image whose frame is still being made holds Send, + and those after it wait with it, so the placement never changes under a + send. + - **An image chip waits for storage.** Until the host has stored it, an + image is a queued file with the queue's honest states (uploading, + checking, failed, refused). Its thumbnail appears only once it is stored. + - **Legacy images stay readable.** A saved draft that already holds legacy + draft images keeps them as inline frames and keeps the tab-local send, + because a snapshot cannot hold one. A host without composer files keeps + the inline-only path. + - **A sent image claims no reading.** Its row is the original's kind and + size; a read record for an image is not shown. The transcript draws the + frame it sent. - **A queue item keeps one key for its whole life.** The idempotency key is minted once per item. A lost answer becomes `unknown`, never "not stored". It is uploaded again with the same key once on reconnect, or through @@ -296,9 +321,10 @@ originals, on a host that advertises `composerFiles`: else `dispatched`. Its uploads leave the composer with it, and each stored one joins the snapshot's files in a save. Once all are stored it moves to `dispatched`, and the `chat_message` goes once, with its own text and - files, under a revision that holds it. A draft with legacy inline images, - or a host without the limit, keeps the tab-local path, because a snapshot - cannot hold an inline image. + files, under a revision that holds it, and the frames of its image + originals once they are made. A draft with legacy inline images, or a host + without the limit, keeps the tab-local path, because a snapshot cannot hold + an inline image. - **Acceptance drops it here at once.** The host releases an accepted snapshot in place, without a revision (#3733). So the client removes it from both its list and its copy of the host's before the next save, and diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 7e5a76788a..4fef9c42b8 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -142,6 +142,9 @@ directs. The new environment input is `BRAIN_UI_ATTACHMENT_POOL_BYTES`. See [the wire component](integration-contract/wire.md#composer-file-attachments-additive-0450-3153), [the HTTP API](http-api.md#composer-file-attachments-additive-0450-3153) and [package API](integration-contract/package-api.md#composer-file-attachments-additive-0450-3153). +On such a host the React package uploads images as originals too and sends +each frame with `ChatImageAttachment.fileId` naming its original (#3155); a +legacy draft image and a host without the flag keep the inline-only path. ## Outgoing snapshot list (additive, 0.45.0, #3588) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 0729a6cb44..046ad743fc 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -1979,6 +1979,20 @@ D52's tab-only track path. is two saves: the old snapshot moves to `returned`, then is left out in the save that creates its successor under a new `snapshotId` and `requestId`. A host without the limit field keeps D52's tab-local path. +- **Images are originals too (additive, #3155).** On a host with + `composerFiles`, `@schlessera/brain-ui-react` uploads every image as its + exact bytes through `POST /api/drafts/:draftId/files`, never through the + legacy draft image route, and binds it as any other file (`fileIds`, + snapshot `fileIds`, `attachmentRefs`). For each original the host stored as + `kind: "image"` with `reader: "image"`, the client sends the frame it has + always prepared, with `ChatImageAttachment.fileId` naming that original, in + the same message's `attachments`. Frames go in file order while + `MAX_IMAGES_PER_MESSAGE` and `MAX_TOTAL_IMAGE_BYTES` allow; past them, or + when no frame can be made, the original is sent without one. After a + reload the frame is made again from `GET /api/attachments/:fileId`. The + frame's shape and the host's rules are unchanged. Legacy draft images of an + existing draft, and a host without `composerFiles`, keep the inline-only + path. The SDK publishes `COMPOSER_FILES_CAPABILITY`, `ATTACHMENT_DIR`, `ATTACHMENT_MAX_FILES`, `ATTACHMENT_MAX_FILE_BYTES`, diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 51b601a105..a4144f3fa7 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -294,7 +294,7 @@ Concrete entry points include `readSessionRecovery` and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:100-110`; `prepareHandoff`, `packages/ui-server/src/ws/handoff.ts:273-285`). Draft autosave belongs to `createDraftClient` (`createDraftClient`, -`packages/ui-react/src/lib/draft-client.ts:53-65`); browser reloadable work belongs +`packages/ui-react/src/lib/draft-client.ts:54-66`); browser reloadable work belongs to `createLocalWork` (`createLocalWork`, `packages/ui-react/src/lib/local-work.ts:227-245`). The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`, with one handler per frame under `ws/handlers/`; gating its resume handler alone would leave HTTP, background readers and provider startup open. diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index fe19294975..94322c9efb 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -317,8 +317,8 @@ requires it; host/network failure maxima and retry intervals are not sleeps to be added to these windows. For real IME start and commit, input also arms the **800 ms host debounce** -(`SAVE_DELAY_MS`, `packages/ui-react/src/lib/draft-client.ts:35-37`; -`schedule`, `packages/ui-react/src/lib/draft-client.ts:79-83`). The native horizon +(`SAVE_DELAY_MS`, `packages/ui-react/src/lib/draft-client.ts:36-38`; +`schedule`, `packages/ui-react/src/lib/draft-client.ts:80-84`). The native horizon is 1000 ms: that 800 ms opportunity plus 200 ms (25%) dispatch/IO/render headroom and the original two frames. The parallel 250 ms device debounce is inside this horizon. The final exact committed draft still has to reach the host. Returning diff --git a/packages/ui-react/src/components/chat/composer-view.tsx b/packages/ui-react/src/components/chat/composer-view.tsx index 0526a943a2..ac5376c53e 100644 --- a/packages/ui-react/src/components/chat/composer-view.tsx +++ b/packages/ui-react/src/components/chat/composer-view.tsx @@ -36,6 +36,17 @@ interface ComposerAttachment { name: string; } +/** + * A stored original in the composer (#3155). `image` is set for an image + * original: whether its frame goes inline with the message (design §8.4), and + * the frame's thumbnail once it is made. + */ +interface ComposerStoredFile { + file: AttachmentFile; + detached: boolean; + image?: { placement: "inline" | "not_inline" | "pending"; previewUrl?: string }; +} + interface ComposerProvider { label: string; /** The model is fixed for this conversation; effort remains editable. */ @@ -92,7 +103,7 @@ export interface ComposerViewProps { * originals the host stored. `detached` marks one this draft's id cannot * bind. Shown only with `onPickFiles`. */ - files?: { queued: readonly QueuedFile[]; stored: readonly { file: AttachmentFile; detached: boolean }[] }; + files?: { queued: readonly QueuedFile[]; stored: readonly ComposerStoredFile[] }; onRemoveQueuedFile?: (id: string) => void; onRetryQueuedFile?: (id: string) => void; onRemoveStoredFile?: (fileId: string) => void; @@ -268,7 +279,7 @@ export function ComposerView(p: ComposerViewProps) { {fileCount > 0 && files &&
{files.queued.map((item, i) => removeAndRefocus(i, () => p.onRemoveQueuedFile?.(item.id))} onRetry={() => p.onRetryQueuedFile?.(item.id)} />)} - {files.stored.map((entry, i) => removeAndRefocus(files.queued.length + i, () => p.onRemoveStoredFile?.(entry.file.fileId))} />)}
} diff --git a/packages/ui-react/src/components/chat/composer.tsx b/packages/ui-react/src/components/chat/composer.tsx index 6efd6f447c..bc05e1789d 100644 --- a/packages/ui-react/src/components/chat/composer.tsx +++ b/packages/ui-react/src/components/chat/composer.tsx @@ -34,6 +34,7 @@ import { takeComposerTextAsAnswer } from "./ask-user-typed.js"; import { trackPending, trackReady } from "../../lib/track-uploads.js"; import { trackKey, tracksFor } from "../../lib/draft-tracks.js"; import { filesFor } from "../../lib/draft-files.js"; +import { ensureFrame, frameOf, framesFor, isFramedImage, placeFrames, subscribeFrames } from "../../lib/image-frames.js"; import { queuedBlocking, queuedPending } from "../../lib/attachment-queue.js"; import { bindableFiles, draftFiles as draftFilesOf, draftSnapshots, type ComposerSnapshot, type DraftFile } from "../../stores/draft-state.js"; import { focusOldestSnapshot } from "./outgoing-snapshots.js"; @@ -243,6 +244,16 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const hasSettledTurn = useChatStore((s) => activeChat(s).messages.some((m) => m.role === "assistant" && !m.isStreaming)); const handoffEntry = useHandoffEntry(sessionId, hasSettledTurn); const wsStatus = useConnectionStore((s) => s.wsStatus); + // Image originals' frames (#3155): page state the chips and Send read. + const [frameVersion, updateFrames] = useReducer((n: number) => n + 1, 0); + useEffect(() => subscribeFrames(root, updateFrames), [root]); + // A restored image original has no frame in this page yet: it is made from + // the original the host keeps, again after a failed read once reconnected. + useEffect(() => { + if (wsStatus !== "connected") return; + for (const f of draftFiles) if (f.lineage === draftId) ensureFrame(root, f.file); + }, [root, draftFiles, draftId, wsStatus]); + const framePlacement = placeFrames(draftFiles.filter((f) => f.lineage === draftId).map((f) => f.file), (id) => frameOf(root, id), attachments); // The browser's own word on the network, for the draft indicator's offline state (#3155). const [browserOnline, setBrowserOnline] = useState(() => typeof navigator === "undefined" || navigator.onLine !== false); useEffect(() => { @@ -472,18 +483,23 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void let target = draftId; const owner = sessionId; const incoming = Array.from(files); - const list = incoming.filter(file => file.type.startsWith("image/")); - const others = incoming.filter(file => !file.type.startsWith("image/")); const heldFiles = root.stores.drafts.getState().drafts[target]?.files ?? NO_FILES; - // With composer files every other file is uploaded unfiltered and the host - // decides what it is (#3155); an older host keeps the tab-only track queue. - const trackErrors = filesOn - ? fileQueue.add(others, target, { - count: attachmentsOf(target).length + list.length + heldFiles.length, + // With composer files every file, images included, is uploaded unfiltered + // as its exact original, and the host decides what it is (#3155). An image + // gets its inline frame once the host has stored it as one. Legacy inline + // images of a saved draft still count toward the envelope. + if (filesOn) { + setAttachErrors(fileQueue.add(incoming, target, { + count: attachmentsOf(target).length + heldFiles.length, bytes: attachmentsOf(target).reduce((sum, image) => sum + image.bytes, 0) + heldFiles.reduce((sum, f) => sum + f.file.bytes, 0), - }, fileLimits) - : trackUploads.add(others, attachmentsOf(target).length + list.length, - attachmentsOf(target).reduce((sum, image) => sum + image.bytes, 0)); + }, fileLimits)); + return; + } + // An older host: images become inline frames only, and the rest the tab-only track queue. + const list = incoming.filter(file => file.type.startsWith("image/")); + const others = incoming.filter(file => !file.type.startsWith("image/")); + const trackErrors = trackUploads.add(others, attachmentsOf(target).length + list.length, + attachmentsOf(target).reduce((sum, image) => sum + image.bytes, 0)); if (list.length === 0) { setAttachErrors(trackErrors); return; } const authEpoch = root.authLock.epoch(); @@ -511,11 +527,10 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void ...current, ...fresh, ]); - const otherFiles = root.stores.drafts.getState().drafts[target]?.files ?? NO_FILES; - const otherCount = trackUploads.files.length + fileQueue.files.length + otherFiles.length; - let combinedBytes = trackUploads.files.reduce((sum, track) => sum + (track.meta?.bytes ?? track.file.size), 0) - + fileQueue.files.reduce((sum, item) => sum + item.file.size, 0) + otherFiles.reduce((sum, f) => sum + f.file.bytes, 0); - const maxFiles = fileLimits?.maxFiles ?? SHARE_MAX_FILES; + // Only an older host reaches here: no composer files, so the tab's tracks are the rest of the envelope. + const otherCount = trackUploads.files.length; + let combinedBytes = trackUploads.files.reduce((sum, track) => sum + (track.meta?.bytes ?? track.file.size), 0); + const maxFiles = SHARE_MAX_FILES; const accepted = imageAccepted.filter((image, index) => { combinedBytes += image.bytes; return index + otherCount < maxFiles && combinedBytes <= SHARE_MAX_TOTAL_BYTES; @@ -597,10 +612,12 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void } if (text) setLastPrompt(text); - const messageAttachments = attachments.map((a) => ({ + // Image originals travel with their frames, after any legacy inline image (#3155). + const frames = framesFor(root, currentFiles.map((f) => f.file), attachments) ?? { attachments: [], previews: [] }; + const messageAttachments = [...attachments.map((a) => ({ previewUrl: a.previewUrl, mediaType: a.attachment.mediaType, - })); + })), ...frames.previews]; const chat = root.stores.chat.getState(); const source = reviewText.trim() ? "voice-dictate" : "typed"; const requestId = chatRequestAck ? crypto.randomUUID() : undefined; @@ -657,8 +674,8 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void // The originals the saved revision binds; the host resolves each against // that revision (`draftRef`), so they are sent only with one (#3153). ...(currentFiles.length ? { attachmentRefs: currentFiles.map((f) => ({ kind: "attachment" as const, fileId: f.file.fileId })) } : {}), - attachments: attachments.length > 0 - ? attachments.map((a) => a.attachment) + attachments: attachments.length + frames.attachments.length > 0 + ? [...attachments.map((a) => a.attachment), ...frames.attachments] : undefined, // Measured per send, not once per session: the same tab can rotate, // move to an external display, or be installed as a PWA mid-conversation. @@ -781,6 +798,8 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void if (d.conflict) return { blocked: "Your draft is kept. Choose which version to keep before sending its files." }; // Sent only from an acknowledged revision: the message names it. if (!(d.host !== null && d.host.edit === d.edit)) return { pending: true }; + // An image's frame still being made: the message carries it, so it waits. + if (!framesFor(root, bindableFiles(d).map((f) => f.file), d.attachments)) return { pending: true }; return {}; } @@ -803,12 +822,13 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void submitHeldDraft.current(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [heldSend, tracks, queuedFiles, draftClean, draftFailure, draftFiles, wsStatus]); + }, [heldSend, tracks, queuedFiles, draftClean, draftFailure, draftFiles, wsStatus, frameVersion]); /** What a held send waits for, in the hint row. */ function heldHint(): string { const files = tracks.filter(trackPending).length + queuedFiles.filter(queuedPending).length; if (files > 0) return `sends when ${files} file${files === 1 ? " finishes" : "s finish"}`; + if ([...framePlacement.values()].includes("pending")) return "sends when its image previews are ready"; return "sends when the draft with its files is saved"; } @@ -1055,7 +1075,12 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void if (trackUploads.files.length === 0 && !current?.text && !current?.attachments.length) focusField(); }} onRetryTrack={id => trackUploads.retry(id)} - files={filesOn ? { queued: queuedFiles, stored: draftFiles.map((f) => ({ file: f.file, detached: f.lineage !== draftId })) } : undefined} + files={filesOn ? { queued: queuedFiles, stored: draftFiles.map((f) => { + const frame = frameOf(root, f.file.fileId); + const placement = f.lineage === draftId && isFramedImage(f.file) ? framePlacement.get(f.file.fileId) : undefined; + return { file: f.file, detached: f.lineage !== draftId, + ...(placement ? { image: { placement, ...(frame?.state === "ready" ? { previewUrl: frame.previewUrl } : {}) } } : {}) }; + }) } : undefined} onRemoveQueuedFile={(id) => fileQueue.remove(id)} onRetryQueuedFile={(id) => fileQueue.retry(id)} onRemoveStoredFile={(fileId) => { diff --git a/packages/ui-react/src/components/chat/file-chip.tsx b/packages/ui-react/src/components/chat/file-chip.tsx index 3bcae204fa..58b9da3066 100644 --- a/packages/ui-react/src/components/chat/file-chip.tsx +++ b/packages/ui-react/src/components/chat/file-chip.tsx @@ -20,6 +20,8 @@ export function FileChip(p: { stored?: AttachmentFile; /** A stored original this draft's id cannot bind (it came from another draft id). */ detached?: boolean; + /** An image original: whether its frame goes inline, and its thumbnail once made. */ + image?: { placement: "inline" | "not_inline" | "pending"; previewUrl?: string }; onRemove: () => void; onRetry?: () => void; }) { @@ -27,14 +29,16 @@ export function FileChip(p: { const size = trackBytes(p.queued?.file.size ?? p.stored?.bytes ?? 0); const copy = p.detached ? { status: "not attached", detail: "It belongs to an earlier version of this draft. Choose it again to attach it." } - : p.queued ? queuedFileCopy(p.queued) : storedFileCopy(p.stored!); + : p.queued ? queuedFileCopy(p.queued) : storedFileCopy(p.stored!, p.image?.placement); const kind = p.stored ? fileKindLabel(p.stored) : "file"; const state = p.queued?.state ?? (p.detached ? "detached" : "stored"); const retry = p.queued && (p.queued.state === "failed" || p.queued.state === "unknown") && p.onRetry; return
-