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 1b90624379..a6aa19eed5 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 5c4ff907da..f648d4c178 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -160,6 +160,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 6954e49947..9693e44bbb 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 f958453f1c..b0931cdd97 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 d5c8c9bf64..c7cd6de67e 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. */ @@ -96,7 +107,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; @@ -269,7 +280,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 80585552ff..d873d60edd 100644 --- a/packages/ui-react/src/components/chat/composer.tsx +++ b/packages/ui-react/src/components/chat/composer.tsx @@ -35,6 +35,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"; @@ -244,6 +245,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(() => { @@ -481,18 +492,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(); @@ -520,11 +536,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; @@ -606,10 +621,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; @@ -666,8 +683,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. @@ -790,6 +807,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 {}; } @@ -812,12 +831,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"; } @@ -1089,7 +1109,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
-