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
-
+ {p.image?.previewUrl && p.image.placement === "inline" && !p.detached
+ ?
+ :
}
{name}
{copy.status}
diff --git a/packages/ui-react/src/lib/attachment-queue.ts b/packages/ui-react/src/lib/attachment-queue.ts
index 9ff138bd78..de5bd0479d 100644
--- a/packages/ui-react/src/lib/attachment-queue.ts
+++ b/packages/ui-react/src/lib/attachment-queue.ts
@@ -76,8 +76,12 @@ const KIND_LABEL: Record
= { pdf: "PDF", text: "
/** A stored original's kind, as the chip and the sent row name it. */
export const fileKindLabel = (file: Pick): string => KIND_LABEL[file.kind] ?? "File";
-/** What a stored original's chip says, and why (design §8.4). Stored is never read. */
-export function storedFileCopy(file: AttachmentFile): { status: string; detail?: string } {
+/**
+ * What a stored original's chip says, and why (design §8.4). Stored is never
+ * read. `frame` places an image original: inline with the message, past the
+ * frame budget (or with no frame to show), or with its frame still being made.
+ */
+export function storedFileCopy(file: AttachmentFile, frame?: "inline" | "not_inline" | "pending"): { status: string; detail?: string } {
const size = trackBytes(file.bytes);
if (file.trackRejected) return { status: "Text · not a usable track", detail: "Stored as text. Track tools won't use it." };
if (file.kind === "track" && file.track) {
@@ -86,7 +90,11 @@ export function storedFileCopy(file: AttachmentFile): { status: string; detail?:
if (file.reader === "pdf" || file.reader === "text") {
return { status: `${fileKindLabel(file)} · ${size} · not read yet`, detail: "Your agent opens it when it needs the contents." };
}
- if (file.reader === "image") return { status: `${fileKindLabel(file)} · ${size}` };
+ if (file.reader === "image") {
+ if (frame === "not_inline") return { status: `${fileKindLabel(file)} · ${size} · not shown inline`, detail: "Your agent gets the file but not a preview." };
+ if (frame === "pending") return { status: `${fileKindLabel(file)} · ${size} · preparing preview…` };
+ return { status: `${fileKindLabel(file)} · ${size}` };
+ }
return { status: `${size} · no reader here`, detail: "Your agent has the file and can refer to it, but can't read this kind of file here." };
}
diff --git a/packages/ui-react/src/lib/draft-client.ts b/packages/ui-react/src/lib/draft-client.ts
index 85f3fcee57..5c4c9afd0e 100644
--- a/packages/ui-react/src/lib/draft-client.ts
+++ b/packages/ui-react/src/lib/draft-client.ts
@@ -6,6 +6,7 @@ import { detectClientEnvironment } from "./client-environment.js";
import { restorationOf } from "../stores/chat-state.js";
import type { PendingAttachment } from "./image-attachments.js";
import { moveTracks, removeTracks, trackKey } from "./draft-tracks.js";
+import { ensureFrame, framesFor, subscribeFrames } from "./image-frames.js";
/** How long a Check again may wait for the host before it counts as unreachable. */
const CHECK_TIMEOUT_MS = 10_000;
@@ -363,7 +364,13 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
}
const now = drafts.getState().drafts[draftId]!;
for (const s of draftSnapshots(now)) {
- if (s.state === "dispatched" && s.dispatch === "due" && !s.retiring && hostState(now, s)?.state === "dispatched" && !drafts.getState().sends[s.requestId]) dispatch(now, s);
+ if (s.state === "dispatched" && s.dispatch === "due" && !s.retiring && hostState(now, s)?.state === "dispatched" && !drafts.getState().sends[s.requestId]) {
+ // Its images' frames go with it (#3155): it waits for them, and a frame's settling advances it.
+ const known = s.files.flatMap((f) => f.file ? [f.file] : []);
+ for (const file of known) ensureFrame(root, file);
+ const frames = framesFor(root, known);
+ if (frames) dispatch(now, s, frames);
+ }
}
}
@@ -373,13 +380,15 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
}
/** Send a dispatched snapshot's message: its text, its files, and a revision that holds it. */
- function dispatch(d: ComposerDraft, s: ComposerSnapshot) {
+ function dispatch(d: ComposerDraft, s: ComposerSnapshot, frames: NonNullable>) {
const draftRef = { draftId: d.draftId, revision: d.host!.revision };
- const { draftRef: _r, attachmentRefs: _a, draftId: _c, ...template } = s.message ?? frameFor(d, s);
+ const { draftRef: _r, attachmentRefs: _a, draftId: _c, attachments: _f, ...template } = s.message ?? frameFor(d, s);
const fileIds = s.files.map((f) => f.fileId);
const message: Extract = {
...template, type: "chat_message", text: s.text, requestId: s.requestId, draftRef,
...(fileIds.length ? { attachmentRefs: fileIds.map((fileId) => ({ kind: "attachment" as const, fileId })) } : {}),
+ // Each image original's frame, naming it (`ChatImageAttachment.fileId`).
+ ...(frames.attachments.length ? { attachments: frames.attachments } : {}),
};
const attachmentFiles = s.files.flatMap((f) => f.file ? [{ file: f.file, lineage: d.draftId }] : []);
drafts.getState().patchSnapshot(d.draftId, s.snapshotId, { dispatch: "sent" }, true);
@@ -394,9 +403,9 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
const streaming = buffer?.isStreaming ?? false;
const source = message.source ?? "typed";
if (streaming && key !== null && root.stores.connection.getState().followUpQueue) {
- root.stores.followUp.getState().addLocal(key, { requestId: s.requestId, text: s.text, source, ...(message.thinkingLevel !== undefined ? { thinkingLevel: message.thinkingLevel } : {}), queuedAt: Date.now() });
+ root.stores.followUp.getState().addLocal(key, { requestId: s.requestId, text: s.text, source, ...(frames.previews.length ? { attachments: frames.previews } : {}), ...(message.thinkingLevel !== undefined ? { thinkingLevel: message.thinkingLevel } : {}), queuedAt: Date.now() });
} else {
- c.addUserMessage(key, s.text, source, undefined, { requestId: s.requestId, ...(message.thinkingLevel !== undefined ? { thinkingLevel: message.thinkingLevel } : {}) },
+ c.addUserMessage(key, s.text, source, frames.previews.length ? frames.previews : undefined, { requestId: s.requestId, ...(message.thinkingLevel !== undefined ? { thinkingLevel: message.thinkingLevel } : {}) },
undefined, attachmentFiles.length ? attachmentFiles.map((f) => f.file) : undefined);
}
if (!streaming) c.startAssistantMessage(key, undefined, s.requestId);
@@ -544,8 +553,11 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
const c = chat.getState();
const buffer = key === null ? c.draft : c.buffers[key];
if (buffer?.messages.some((m) => m.role === "user" && m.requestId === send.requestId)) return;
+ // Image originals' frames are the message's own (#3155), drawn from the frame it sent.
+ const framed = (send.message.attachments ?? []).filter((a) => a.fileId).map((a) => ({ previewUrl: `data:${a.mediaType};base64,${a.data}`, mediaType: a.mediaType }));
+ const previews = [...send.attachments.map((a) => ({ previewUrl: a.previewUrl, mediaType: a.attachment.mediaType })), ...framed];
c.addUserMessage(key, send.text, send.message.source,
- send.attachments.length ? send.attachments.map((a) => ({ previewUrl: a.previewUrl, mediaType: a.attachment.mediaType })) : undefined,
+ previews.length ? previews : undefined,
{ requestId: send.requestId, ...(send.message.thinkingLevel !== undefined ? { thinkingLevel: send.message.thinkingLevel } : {}) },
send.files?.length ? send.files : undefined,
send.attachmentFiles?.length ? send.attachmentFiles.map((f) => f.file) : undefined);
@@ -620,6 +632,8 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
if (state.activeSessionId !== prev.activeSessionId || state.pendingDraftId !== prev.pendingDraftId || restorationOf(state) !== restorationOf(prev)) advanceAll();
});
function advanceAll() { if (drafts.getState().snapshotsOn) for (const id of Object.keys(drafts.getState().drafts)) advanceSnapshots(id); }
+ // A frame a due snapshot waited for has settled.
+ const unsubscribeFrames = subscribeFrames(root, () => { if (!disposed) advanceAll(); });
/**
* The queue-full notice (#3155) clears when this tab frees a slot, and
@@ -907,6 +921,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt
if (refreshRetry) clearTimeout(refreshRetry.timer);
orphanRetries.clear();
unsubscribeDrafts();
+ unsubscribeFrames();
unsubscribeConnection();
unsubscribeView();
if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisible);
diff --git a/packages/ui-react/src/lib/draft-files.ts b/packages/ui-react/src/lib/draft-files.ts
index c64291bdce..63cb9ab200 100644
--- a/packages/ui-react/src/lib/draft-files.ts
+++ b/packages/ui-react/src/lib/draft-files.ts
@@ -2,6 +2,7 @@ import type { AttachmentFile } from "@schlessera/brain-ui-sdk/protocol";
import type { BrainUiServices } from "../root.js";
import { apiBaseFor } from "./backend.js";
import { createAttachmentQueue, queuedPending, type AttachmentQueue, type QueuedFile } from "./attachment-queue.js";
+import { disposeFrames, ensureFrame } from "./image-frames.js";
/**
* One root's generic upload queues, per composer view (#3155).
@@ -40,18 +41,22 @@ function guardLeaving(reg: Registry) {
}
}
-/** The stored original joins its draft, or the held snapshot it belongs to: the next save binds it. */
+/**
+ * The stored original joins its draft, or the held snapshot it belongs to:
+ * the next save binds it. An image's frame is then made from the very bytes
+ * that were uploaded.
+ */
function storedInto(root: BrainUiServices, sessionId: string | null, item: QueuedFile, file: AttachmentFile) {
const draftId = item.draftId;
const drafts = root.stores.drafts.getState();
if (item.snapshotId) {
drafts.snapshotStored(drafts.resolveId(draftId), item.snapshotId, item.id, file);
- return;
+ } else {
+ const { draftId: target } = drafts.resolveTarget(draftId, sessionId);
+ const current = drafts.drafts[target]?.files ?? [];
+ if (!current.some((f) => f.file.fileId === file.fileId)) drafts.edit(draftId, sessionId, { files: [...current, { file, lineage: draftId }] });
}
- const { draftId: target } = drafts.resolveTarget(draftId, sessionId);
- const current = drafts.drafts[target]?.files ?? [];
- if (current.some((f) => f.file.fileId === file.fileId)) return;
- drafts.edit(draftId, sessionId, { files: [...current, { file, lineage: draftId }] });
+ ensureFrame(root, file, item.file);
}
export function filesFor(root: BrainUiServices, key: string, sessionId: string | null): Entry {
@@ -115,6 +120,7 @@ export function uploadingNames(root: BrainUiServices): Array<{ draftId: string;
/** The root is going: every upload is aborted, and none starts another. */
export function disposeFiles(root: BrainUiServices): void {
+ disposeFrames(root);
const reg = registries.get(root.stores);
if (!reg) return;
for (const entry of reg.entries.values()) entry.queue.dispose();
diff --git a/packages/ui-react/src/lib/image-frames.ts b/packages/ui-react/src/lib/image-frames.ts
new file mode 100644
index 0000000000..239db57057
--- /dev/null
+++ b/packages/ui-react/src/lib/image-frames.ts
@@ -0,0 +1,183 @@
+import { MAX_IMAGES_PER_MESSAGE, MAX_TOTAL_IMAGE_BYTES, type AttachmentFile, type ChatImageAttachment } from "@schlessera/brain-ui-sdk/protocol";
+import type { BrainUiServices } from "../root.js";
+import { fileToAttachment, type PendingAttachment } from "./image-attachments.js";
+
+/**
+ * Inline frames of image originals (#3155, design §8.4 and §10).
+ *
+ * On a host with composer files an image is an original like any other: the
+ * generic queue uploads its exact bytes and the host's detection names it an
+ * image. The frame the model sees is derived from that original, as
+ * `fileToAttachment` always prepared it, and carries the original's `fileId`
+ * (`ChatImageAttachment.fileId`), so the host charges the pair once.
+ *
+ * A frame is page state, never draft content: drafts, snapshots and saves
+ * name only the original. It is derived from the picked bytes when the host
+ * stores them, or, after a reload, from the original read back
+ * (`GET /api/attachments/:fileId`). Its preview URL is this registry's and is
+ * revoked once no draft, snapshot or send of the root names the original.
+ */
+type ImageFrame =
+ /** Being derived: a send that would carry it waits. */
+ | { state: "pending" }
+ | { state: "ready"; attachment: ChatImageAttachment; previewUrl: string; bytes: number }
+ /** No frame can be made (an undecodable, too small or too large image): the original goes alone. */
+ | { state: "none"; reason: string }
+ /** The original could not be read back. Asked again on the next `ensureFrame`. */
+ | { state: "failed" };
+
+type Registry = { frames: Map; listeners: Set<() => void> };
+
+const registries = new WeakMap();
+
+/** Whether a stored original gets a frame: the host's detection, never a name or MIME hint. */
+export const isFramedImage = (file: Pick): boolean => file.kind === "image" && file.reader === "image";
+
+function registry(root: BrainUiServices): Registry {
+ let reg = registries.get(root.stores);
+ if (!reg) {
+ const created: Registry = { frames: new Map(), listeners: new Set() };
+ // Preview cleanup: an original nothing names any more takes its frame with it.
+ root.stores.drafts.subscribe(() => sweep(root, created));
+ registries.set(root.stores, created);
+ reg = created;
+ }
+ return reg;
+}
+
+function notify(reg: Registry) { for (const l of reg.listeners) l(); }
+
+/** Every original a draft, a snapshot or a send of the root still names. */
+function referenced(root: BrainUiServices): Set {
+ const state = root.stores.drafts.getState();
+ const ids = new Set();
+ for (const d of Object.values(state.drafts)) {
+ for (const f of d.files ?? []) ids.add(f.file.fileId);
+ for (const s of d.snapshots ?? []) for (const f of s.files) ids.add(f.fileId);
+ }
+ for (const s of Object.values(state.sends)) for (const f of s.attachmentFiles ?? []) ids.add(f.file.fileId);
+ return ids;
+}
+
+function sweep(root: BrainUiServices, reg: Registry) {
+ if (reg.frames.size === 0) return;
+ const live = referenced(root);
+ let changed = false;
+ for (const [id, frame] of reg.frames) {
+ if (live.has(id)) continue;
+ if (frame.state === "ready") URL.revokeObjectURL(frame.previewUrl);
+ reg.frames.delete(id);
+ changed = true;
+ }
+ if (changed) notify(reg);
+}
+
+/** The frame of an original, if this page has one or is making one. */
+export function frameOf(root: BrainUiServices, fileId: string): ImageFrame | undefined {
+ return registries.get(root.stores)?.frames.get(fileId);
+}
+
+/** Calls back whenever a frame starts, settles or goes. */
+export function subscribeFrames(root: BrainUiServices, fn: () => void): () => void {
+ const reg = registry(root);
+ reg.listeners.add(fn);
+ return () => { reg.listeners.delete(fn); };
+}
+
+/**
+ * Derive the frame of an image original once: from `source` (the bytes just
+ * picked) or else from the original the host keeps. A failed read is asked
+ * again on the next call; a settled frame is never derived twice.
+ */
+export function ensureFrame(root: BrainUiServices, file: AttachmentFile, source?: Blob): void {
+ if (!isFramedImage(file)) return;
+ const reg = registry(root);
+ const existing = reg.frames.get(file.fileId);
+ if (existing && existing.state !== "failed") return;
+ const pending: ImageFrame = { state: "pending" };
+ reg.frames.set(file.fileId, pending);
+ notify(reg);
+ void (async () => {
+ let next: ImageFrame;
+ try {
+ let blob = source;
+ if (!blob) {
+ const response = await root.request(`${root.apiBase()}/attachments/${encodeURIComponent(file.fileId)}`);
+ if (!response.ok) throw Error(`status ${response.status}`);
+ blob = await response.blob();
+ }
+ const picked = new File([blob], file.incomingName || file.name, { type: blob.type || file.mediaType });
+ const result = await fileToAttachment(picked);
+ next = "error" in result
+ ? { state: "none", reason: result.error }
+ : { state: "ready", attachment: { ...result.attachment, fileId: file.fileId }, previewUrl: result.previewUrl, bytes: result.bytes };
+ } catch {
+ next = { state: "failed" };
+ }
+ // Disposed, swept or replaced meanwhile: this result is no one's.
+ if (reg.frames.get(file.fileId) !== pending) {
+ if (next.state === "ready") URL.revokeObjectURL(next.previewUrl);
+ return;
+ }
+ reg.frames.set(file.fileId, next);
+ notify(reg);
+ })();
+}
+
+/** The root is going, or its account locked: every preview is released. */
+export function disposeFrames(root: BrainUiServices): void {
+ const reg = registries.get(root.stores);
+ if (!reg) return;
+ for (const frame of reg.frames.values()) if (frame.state === "ready") URL.revokeObjectURL(frame.previewUrl);
+ // Listeners stay: a view still mounted hears frames made after an unlock.
+ reg.frames.clear();
+ notify(reg);
+}
+
+/** Where an image original stands for one message. */
+type FramePlacement = "inline" | "not_inline" | "pending";
+
+/**
+ * Which image originals travel with their frame (design §8.4). In order,
+ * after the draft's legacy inline images, a frame goes inline while the
+ * per-message image count and total frame bytes allow; past that budget, and
+ * for an image no frame could be made of, the original goes alone. An image
+ * whose frame is still being made is `pending`, and holds what comes after
+ * it, so the placement never changes under a send.
+ */
+export function placeFrames(
+ images: readonly AttachmentFile[],
+ frame: (fileId: string) => ImageFrame | undefined,
+ legacy: readonly Pick[] = [],
+): Map {
+ const placed = new Map();
+ let count = legacy.length;
+ let bytes = legacy.reduce((sum, a) => sum + a.bytes, 0);
+ let waiting = false;
+ for (const file of images) {
+ if (!isFramedImage(file)) continue;
+ const f = frame(file.fileId);
+ if (waiting || !f || f.state === "pending") { placed.set(file.fileId, "pending"); waiting = true; continue; }
+ if (f.state !== "ready" || count >= MAX_IMAGES_PER_MESSAGE || bytes + f.bytes > MAX_TOTAL_IMAGE_BYTES) { placed.set(file.fileId, "not_inline"); continue; }
+ count++;
+ bytes += f.bytes;
+ placed.set(file.fileId, "inline");
+ }
+ return placed;
+}
+
+/**
+ * The frames a message sends for these originals, each with its `fileId`,
+ * or null while any is still being made. `previews` are data URLs the
+ * transcript may keep: the registry's own URLs go with the original.
+ */
+export function framesFor(root: BrainUiServices, files: readonly AttachmentFile[], legacy: readonly Pick[] = []): { attachments: ChatImageAttachment[]; previews: { previewUrl: string; mediaType: ChatImageAttachment["mediaType"] }[] } | null {
+ const placed = placeFrames(files, (id) => frameOf(root, id), legacy);
+ if ([...placed.values()].includes("pending")) return null;
+ const attachments: ChatImageAttachment[] = [];
+ for (const file of files) {
+ const f = frameOf(root, file.fileId);
+ if (placed.get(file.fileId) === "inline" && f?.state === "ready") attachments.push(f.attachment);
+ }
+ return { attachments, previews: attachments.map((a) => ({ previewUrl: `data:${a.mediaType};base64,${a.data}`, mediaType: a.mediaType })) };
+}
diff --git a/packages/ui-react/src/lib/track-attachment.ts b/packages/ui-react/src/lib/track-attachment.ts
index 286940acf3..f089e65bb4 100644
--- a/packages/ui-react/src/lib/track-attachment.ts
+++ b/packages/ui-react/src/lib/track-attachment.ts
@@ -80,7 +80,10 @@ export function readCopy(entries: readonly AttachmentReadEntry[]): { text: strin
* undefined while they are unknown (an older host, or the session's records
* not arrived yet): then the row claims neither "read" nor "not read yet".
*/
-export function attachmentRowProps(file: AttachmentFile, reads?: readonly AttachmentReadEntry[]): AttachmentRowProps {
+export function attachmentRowProps(file: AttachmentFile, recorded?: readonly AttachmentReadEntry[]): AttachmentRowProps {
+ // An image reaches the agent as its frame and its original, never through a
+ // reader: its row makes no claim about reading (#3155).
+ const reads = file.kind === "image" ? undefined : recorded;
const read = reads ? readCopy(reads) : null;
if (file.kind === "track" && file.track && !file.trackRejected) {
const row = trackRowProps({ ...file.track, incomingName: file.incomingName ?? file.track.incomingName });
diff --git a/packages/ui-react/tests/auth-expiry-runtime.test.ts b/packages/ui-react/tests/auth-expiry-runtime.test.ts
index fd3fcd6c6a..9eb34f48e2 100644
--- a/packages/ui-react/tests/auth-expiry-runtime.test.ts
+++ b/packages/ui-react/tests/auth-expiry-runtime.test.ts
@@ -539,7 +539,13 @@ describe.skipIf(!executablePath)("auth producer and identity races (#1018)",()=>
expect(await fixture(page,f=>f.text())).toBe("");
await page.waitForTimeout(400); await loginForm(page); await ready(page);
expect(await field(page).inputValue(),"saved text survives the delayed image callback").toBe(DRAFT);
- expect(await fixture(page,f=>f.images())).toEqual([]);
+ // This host keeps composer files (#3155): the image's original was stored and
+ // bound before the lock, so it is the host's draft content and comes back as
+ // that original. Its frame, decoded late, never became draft content.
+ const back=await fixture(page,f=>f.images());
+ expect(back,"only the stored original, no late frame").toHaveLength(1);
+ expect(back[0]).toMatchObject({mediaType:"image/png",name:"shroud.png"});
+ expect(back[0]!.data,"an original by its record, not a frame's base64").toMatch(/^[0-9a-f-]{36}:[0-9a-f]{64}:\d+$/);
} finally {await context.close();}
},120_000);
test("on a host without composer files, track-only New chat restores the same unbound composer identity",async()=>{
diff --git a/packages/ui-react/tests/browser/composer-image-originals.offline.tsx b/packages/ui-react/tests/browser/composer-image-originals.offline.tsx
new file mode 100644
index 0000000000..9c3fda33c3
--- /dev/null
+++ b/packages/ui-react/tests/browser/composer-image-originals.offline.tsx
@@ -0,0 +1,306 @@
+///
+/**
+ * Image originals in Chromium (#3155, design §6.1, §8.4 and §10). On a host
+ * with composer files an image is uploaded as its exact original through the
+ * neutral route, like every other file, and the inline frame the model sees
+ * is derived from it and names it (`ChatImageAttachment.fileId`).
+ *
+ * The real Composer, snapshot bubbles and draft client run against the
+ * fixture host in `../snapshot-host.ts` (#3153's and #3588's rules in
+ * memory; PNG and JPEG signatures detect as images). `hostRefuses` restates
+ * the rules ui-server's `resolveAttachmentRefs` and `chat-message` handler
+ * apply to the frame, so a message the real host would refuse fails here.
+ * Real canvas PNGs, native File, DataTransfer and change events. No key, no
+ * network.
+ */
+import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
+import { commands, page, userEvent } from "vitest/browser";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { MAX_IMAGES_PER_MESSAGE, MAX_IMAGE_BYTES, MAX_TOTAL_IMAGE_BYTES, type ClientMessage } from "@schlessera/brain-ui-sdk/protocol";
+import { Composer } from "../../src/components/chat/composer.js";
+import { OutgoingSnapshots } from "../../src/components/chat/outgoing-snapshots.js";
+import { BrainUiProvider } from "../../src/root-context.js";
+import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js";
+import { SESSION, snapshotHost, type SnapshotHost } from "../snapshot-host.js";
+
+class FixtureSocket {
+ static last: FixtureSocket | undefined;
+ readyState = 0;
+ onopen: (() => void) | null = null;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+ onclose: ((event: CloseEvent) => void) | null = null;
+ onerror = null;
+ sent: string[] = [];
+ constructor() { FixtureSocket.last = this; }
+ send(raw: string) { this.sent.push(raw); }
+ close() { this.readyState = 3; }
+ open() { this.readyState = 1; this.onopen?.(); }
+ deliver(frame: unknown) { flushSync(() => this.onmessage?.({ data: JSON.stringify(frame) } as MessageEvent)); }
+}
+
+const scenes: { host: HTMLDivElement; renderer: Root; root: BrainUiRoot; disposed: boolean }[] = [];
+let styles: HTMLStyleElement;
+let viewport: { width: number; height: number };
+beforeAll(async () => {
+ viewport = { width: window.innerWidth, height: window.innerHeight };
+ styles = document.createElement("style");
+ styles.textContent = await commands.formConsumerStyles();
+ document.head.append(styles);
+});
+/** The offline lane has no network, so `navigator.onLine` is false; the fixture host is reachable. Restored whole. */
+let onLine: PropertyDescriptor | undefined | null = null;
+function emulateOnline() {
+ if (onLine === null) onLine = Object.getOwnPropertyDescriptor(navigator, "onLine");
+ Object.defineProperty(navigator, "onLine", { configurable: true, get: () => true });
+}
+function restoreOnline() {
+ if (onLine === null) return;
+ if (onLine) Object.defineProperty(navigator, "onLine", onLine);
+ else Reflect.deleteProperty(navigator, "onLine");
+ onLine = null;
+}
+afterEach(() => {
+ for (const s of scenes.splice(0)) if (!s.disposed) { flushSync(() => s.renderer.unmount()); s.root.dispose(); s.host.remove(); }
+ vi.unstubAllGlobals();
+ restoreOnline();
+});
+afterAll(async () => { styles.remove(); await page.viewport(viewport.width, viewport.height); });
+
+const LIMITS = { maxTextBytes: 65_536, maxDraftBytes: 8_388_608, maxDrafts: 100, maxTotalBytes: 268_435_456 };
+
+/** `snapshots: false` is a host without the snapshot list: the composer's tab-local send. */
+async function mount(fixture: SnapshotHost, { snapshots = true } = {}) {
+ await page.viewport(1280, 900);
+ emulateOnline();
+ const root = createBrainUiRoot({ storage: null, request: fixture.request });
+ vi.stubGlobal("WebSocket", FixtureSocket);
+ root.stores.chat.getState().setActiveSession(SESSION);
+ root.connection.connect();
+ const socket = FixtureSocket.last!;
+ flushSync(() => socket.open());
+ socket.deliver({
+ type: "server_hello", protocolRev: 5,
+ capabilities: { sessionDrafts: true, chatRequestAck: true, composerFiles: true, sessionRecovery: true },
+ attachmentLimits: { maxFiles: 10, maxFileBytes: 25_000_000, maxTotalBytes: 50_000_000, poolBytes: 1_073_741_824 },
+ sessionDraftLimits: snapshots ? { ...LIMITS, maxOutgoingSnapshots: 10 } : LIMITS,
+ });
+ socket.deliver({ type: "session_info", sessionId: SESSION, isNew: false });
+ socket.deliver({ type: "session_history", sessionId: SESSION, messages: [] });
+ socket.deliver({ type: "status", sessionId: SESSION, status: "idle" });
+ const host = document.createElement("div"); document.body.append(host);
+ const renderer = createRoot(host);
+ const scene = { host, renderer, root, disposed: false };
+ scenes.push(scene);
+ flushSync(() => renderer.render(
+
+ root.connection.send(msg)} />
+ ));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const field = () => host.querySelector("[data-composer] textarea")!;
+ const sendButton = () => host.querySelector('[data-composer] [aria-label^="Send"]')!;
+ const chips = () => [...host.querySelectorAll("[data-file-chip]")];
+ const chip = (name: string) => chips().find((c) => c.getAttribute("aria-label")?.startsWith(`${name},`));
+ const status = (name: string) => chip(name)?.querySelector("[data-file-status]")?.textContent ?? null;
+ const thumbnail = (name: string) => chip(name)?.querySelector("img[data-file-thumbnail]") ?? null;
+ const bubbles = () => [...host.querySelectorAll("[data-outgoing-snapshot]")];
+ const messages = () => socket.sent.map((raw) => JSON.parse(raw) as ClientMessage).filter((f): f is Extract => f.type === "chat_message");
+ const draft = () => { const s = root.stores.drafts.getState(); return s.drafts[s.idFor(SESSION)]; };
+ const saved = () => { const d = draft(); return !!d && d.host !== null && d.host.edit === d.edit; };
+ const reload = () => { flushSync(() => renderer.unmount()); root.dispose(); host.remove(); scene.disposed = true; };
+ return { root, host, socket, field, sendButton, chips, chip, status, thumbnail, bubbles, messages, draft, saved, reload };
+}
+type Scene = Awaited>;
+
+function pickFiles(s: Scene, files: File[]) {
+ const input = s.host.querySelector("input[data-files-input]")!;
+ const transfer = new DataTransfer(); for (const file of files) transfer.items.add(file);
+ input.files = transfer.files; input.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
+/** A real PNG drawn on a canvas, with a little noise so each one is distinct. */
+async function png(name: string, color: string, edge = 96) {
+ const canvas = document.createElement("canvas"); canvas.width = canvas.height = edge;
+ const ctx = canvas.getContext("2d")!; ctx.fillStyle = color; ctx.fillRect(0, 0, edge, edge);
+ ctx.fillStyle = "#fff"; ctx.fillRect(edge / 4, edge / 4, edge / 8, edge / 8);
+ const blob = await new Promise((resolve) => canvas.toBlob((b) => resolve(b!), "image/png"));
+ return new File([blob], name, { type: "image/png" });
+}
+const bytesOf = async (file: Blob) => [...new Uint8Array(await file.arrayBuffer())];
+const decoded = (b64: string) => Math.floor((b64.length * 3) / 4) - (b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0);
+
+/**
+ * What ui-server refuses before a backend runs (`resolveAttachmentRefs`,
+ * `packages/ui-server/src/attachments/resolve.ts`; `handleChatMessageFrame`,
+ * `packages/ui-server/src/ws/handlers/chat-message.ts`; `validateAttachments`,
+ * `packages/ui-server/src/ws/attachments.ts`), or null when it would run it.
+ */
+function hostRefuses(fixture: SnapshotHost, msg: Extract): string | null {
+ const frames = msg.attachments ?? [];
+ if (frames.length > MAX_IMAGES_PER_MESSAGE) return "Too many images attached";
+ let frameBytes = 0;
+ for (const f of frames) { const n = decoded(f.data); if (n > MAX_IMAGE_BYTES) return "Image is too large"; frameBytes += n; }
+ if (frameBytes > MAX_TOTAL_IMAGE_BYTES) return "Attached images are too large";
+ const refs = (msg.attachmentRefs ?? []).map((r) => r.fileId);
+ if (refs.length && !msg.draftRef) return "Attached files need the saved draft they were uploaded to.";
+ for (const id of frames.flatMap((f) => f.fileId ? [f.fileId] : [])) {
+ if (!refs.includes(id) || fixture.files.get(id)?.kind !== "image") return "An image names an original the message does not attach.";
+ }
+ for (const id of refs) if (fixture.files.get(id)?.draftId !== msg.draftRef!.draftId) return "An attached file does not belong to this draft.";
+ const unlinked = frames.filter((f) => !f.fileId);
+ const bytes = refs.reduce((n, id) => n + fixture.files.get(id)!.bytes, 0) + unlinked.reduce((n, f) => n + decoded(f.data), 0);
+ if (refs.length + unlinked.length > 10 || bytes > 50_000_000) return "Attached files exceed the message limits.";
+ return null;
+}
+
+test("a picked image uploads its exact original to the neutral route, and the send carries the original and a frame that names it", async () => {
+ const fixture = snapshotHost();
+ const s = await mount(fixture);
+ await userEvent.fill(s.field(), "Is this the harbour at Ithaca?");
+ const harbour = await png("harbour.png", "#2a6f97");
+ pickFiles(s, [harbour]);
+ await expect.poll(() => fixture.uploads.length, { timeout: 5_000 }).toBe(1);
+ expect(fixture.uploads[0]!.name).toBe("harbour.png");
+ expect(fixture.calls.some((c) => /\/drafts\/[^/]+\/attachments/.test(c)), "no legacy draft image upload").toBe(false);
+ await expect.poll(() => s.thumbnail("harbour.png")?.src ?? null, { timeout: 5_000 }).toMatch(/^blob:/);
+ const fileId = s.draft()!.files![0]!.file.fileId;
+ expect(await bytesOf(new Blob([fixture.storedBytes(fileId)! as Uint8Array])), "stored byte for byte").toEqual(await bytesOf(harbour));
+ expect(s.status("harbour.png")).toMatch(/^Image · \d+(\.\d+)? (B|KB) *$/);
+ for (const c of s.chips()) expect(c.textContent ?? "").not.toMatch(/\b(readable|processed|decoded|saved|not read yet)\b/i);
+ expect(s.draft()!.attachments, "no legacy inline image in the draft").toHaveLength(0);
+ await expect.poll(() => s.saved(), { timeout: 5_000 }).toBe(true);
+ expect(fixture.saves.at(-1)!.body.fileIds).toEqual([fileId]);
+ s.sendButton().click();
+ await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1);
+ const msg = s.messages()[0]!;
+ expect(msg.attachmentRefs).toEqual([{ kind: "attachment", fileId }]);
+ expect(msg.attachments, "one frame, linked to its original").toHaveLength(1);
+ expect(msg.attachments![0]!.fileId).toBe(fileId);
+ expect(msg.attachments![0]!.mediaType).toBe("image/jpeg");
+ expect(hostRefuses(fixture, msg)).toBeNull();
+ // The snapshot that sent it held the original, not a frame.
+ expect(fixture.saves.some((x) => x.body.snapshots?.some((snap) => snap.fileIds.includes(fileId))), "the snapshot holds the image").toBe(true);
+ fixture.accept(msg);
+ s.socket.deliver({ type: "session_info", sessionId: SESSION, isNew: false, requestId: msg.requestId });
+ const sent = s.root.stores.chat.getState().buffers[SESSION]!.messages.find((m) => m.role === "user")!;
+ expect(sent.attachments?.map((a) => a.previewUrl.slice(0, 16)), "the sent row keeps its picture").toEqual(["data:image/jpeg;"]);
+ expect(sent.attachmentFiles?.map((f) => f.fileId)).toEqual([fileId]);
+});
+
+test("past the frame budget an image is sent as its original only, with the §8.4 copy", async () => {
+ const fixture = snapshotHost();
+ const s = await mount(fixture);
+ await userEvent.fill(s.field(), "Five views of the strait.");
+ const views = await Promise.all(["#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"].map((c, i) => png(`strait-${i + 1}.png`, c)));
+ pickFiles(s, views);
+ await expect.poll(() => s.draft()?.files?.length ?? 0, { timeout: 5_000 }).toBe(5);
+ await expect.poll(() => s.chips().filter((c) => c.querySelector("img[data-file-thumbnail]")).length, { timeout: 5_000 }).toBe(MAX_IMAGES_PER_MESSAGE);
+ const order = s.draft()!.files!.map((f) => f.file);
+ const last = order.at(-1)!;
+ const name = last.incomingName || last.name;
+ expect(s.status(name)).toMatch(/^Image · .+ · not shown inline$/);
+ expect(s.chip(name)!.querySelector("[data-file-detail]")!.textContent).toBe("Your agent gets the file but not a preview.");
+ expect(s.chip(name)!.getAttribute("aria-label")).toMatch(/, Image, .+, Image · .+ · not shown inline$/);
+ await expect.poll(() => s.saved(), { timeout: 5_000 }).toBe(true);
+ s.sendButton().click();
+ await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1);
+ const msg = s.messages()[0]!;
+ expect(msg.attachmentRefs!.map((r) => r.fileId), "every original is sent").toEqual(order.map((f) => f.fileId));
+ expect(msg.attachments!.map((a) => a.fileId), "four frames, in order, the fifth left out").toEqual(order.slice(0, MAX_IMAGES_PER_MESSAGE).map((f) => f.fileId));
+ expect(hostRefuses(fixture, msg)).toBeNull();
+});
+
+test("Send while an image uploads holds a snapshot, and once stored it sends once with its frame", async () => {
+ const fixture = snapshotHost();
+ const s = await mount(fixture);
+ const release = fixture.holdUploads();
+ await userEvent.fill(s.field(), "The view from the headland.");
+ pickFiles(s, [await png("headland.png", "#6d597a")]);
+ await expect.poll(() => fixture.uploads.length).toBe(1);
+ await expect.poll(() => s.status("headland.png")).toBe("uploading…");
+ s.sendButton().click();
+ await expect.poll(() => s.bubbles().length).toBe(1);
+ expect(s.chips(), "the upload is the snapshot's now").toHaveLength(0);
+ const id = s.draft()!.draftId;
+ await expect.poll(() => fixture.snapshotsOf(id)[0]?.state, { timeout: 5_000 }).toBe("held");
+ expect(s.messages(), "nothing sent while the original uploads").toHaveLength(0);
+ release();
+ await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1);
+ const msg = s.messages()[0]!;
+ const held = fixture.snapshotsOf(id)[0]!;
+ expect(msg.requestId).toBe(held.requestId);
+ expect(held.fileIds).toHaveLength(1);
+ expect(msg.attachmentRefs).toEqual([{ kind: "attachment", fileId: held.fileIds[0] }]);
+ expect(msg.attachments?.map((a) => a.fileId), "its frame names the held original").toEqual(held.fileIds);
+ expect(hostRefuses(fixture, msg)).toBeNull();
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(s.messages(), "sent once").toHaveLength(1);
+});
+
+test("a refused image blocks Send until removed, and a failed one retries under its key", async () => {
+ const fixture = snapshotHost();
+ const s = await mount(fixture);
+ await userEvent.fill(s.field(), "Two sketches of the Cyclops' cave.");
+ fixture.refuseNextUpload();
+ pickFiles(s, [await png("cave-1.png", "#3d405b")]);
+ await expect.poll(() => s.status("cave-1.png"), { timeout: 5_000 }).toBe("not stored · no space");
+ expect(s.chip("cave-1.png")!.textContent).toContain("This host's attachment space is full. Nothing was removed to make room.");
+ s.sendButton().click();
+ await expect.poll(() => s.host.textContent ?? "").toContain("Retry or remove the file that wasn't stored before sending.");
+ expect(s.messages()).toHaveLength(0);
+ s.chip("cave-1.png")!.querySelector('[aria-label="Remove cave-1.png"]')!.click();
+ fixture.failNextUpload();
+ pickFiles(s, [await png("cave-2.png", "#81b29a")]);
+ await expect.poll(() => s.status("cave-2.png"), { timeout: 5_000 }).toBe("upload failed");
+ const retry = s.chip("cave-2.png")!.querySelector('[aria-label="Retry cave-2.png"]')!;
+ retry.click();
+ await expect.poll(() => s.thumbnail("cave-2.png")?.src ?? null, { timeout: 5_000 }).toMatch(/^blob:/);
+ const tries = fixture.uploads.filter((u) => u.name === "cave-2.png");
+ expect(tries).toHaveLength(2);
+ expect(tries[1]!.key, "the retry is the same upload").toBe(tries[0]!.key);
+ await expect.poll(() => s.saved(), { timeout: 5_000 }).toBe(true);
+ s.sendButton().click();
+ await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1);
+ const msg = s.messages()[0]!;
+ expect(msg.attachmentRefs).toHaveLength(1);
+ expect(msg.attachments?.map((a) => a.fileId)).toEqual(msg.attachmentRefs!.map((r) => r.fileId));
+ expect(hostRefuses(fixture, msg)).toBeNull();
+});
+
+test("after a reload an acknowledged image is restored from its original, with its thumbnail, and sends with its frame", async () => {
+ const fixture = snapshotHost();
+ const first = await mount(fixture);
+ await userEvent.fill(first.field(), "Penelope's loom, as I left it.");
+ const loom = await png("loom.png", "#9c6644");
+ pickFiles(first, [loom]);
+ await expect.poll(() => first.thumbnail("loom.png")?.src ?? null, { timeout: 5_000 }).toMatch(/^blob:/);
+ await expect.poll(() => first.saved(), { timeout: 5_000 }).toBe(true);
+ const fileId = first.draft()!.files![0]!.file.fileId;
+ first.reload();
+ const s = await mount(fixture);
+ await expect.poll(() => s.field()?.value, { timeout: 5_000 }).toBe("Penelope's loom, as I left it.");
+ await expect.poll(() => s.thumbnail("loom.png")?.src ?? null, { timeout: 5_000 }).toMatch(/^blob:/);
+ expect(fixture.calls, "the frame was made from the original the host keeps").toContain(`GET /api/attachments/${fileId}`);
+ s.sendButton().click();
+ await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1);
+ const msg = s.messages()[0]!;
+ expect(msg.attachmentRefs).toEqual([{ kind: "attachment", fileId }]);
+ expect(msg.attachments?.map((a) => a.fileId)).toEqual([fileId]);
+ expect(hostRefuses(fixture, msg)).toBeNull();
+});
+
+test("on a host without the snapshot list the composer's own send carries the original and its frame", async () => {
+ const fixture = snapshotHost();
+ const s = await mount(fixture, { snapshots: false });
+ await userEvent.fill(s.field(), "The ram I rode out of the cave.");
+ const ram = await png("ram.png", "#bc6c25");
+ pickFiles(s, [ram]);
+ s.sendButton().click();
+ await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1);
+ const msg = s.messages()[0]!;
+ const fileId = msg.attachmentRefs![0]!.fileId;
+ expect(await bytesOf(new Blob([fixture.storedBytes(fileId)! as Uint8Array]))).toEqual(await bytesOf(ram));
+ expect(msg.attachments?.map((a) => a.fileId)).toEqual([fileId]);
+ expect(fixture.saves.every((x) => !x.body.snapshots?.length), "no snapshot on this host").toBe(true);
+ expect(hostRefuses(fixture, msg)).toBeNull();
+});
diff --git a/packages/ui-react/tests/connection-continuity-runtime.test.ts b/packages/ui-react/tests/connection-continuity-runtime.test.ts
index 084986f220..0b0e047b19 100644
--- a/packages/ui-react/tests/connection-continuity-runtime.test.ts
+++ b/packages/ui-react/tests/connection-continuity-runtime.test.ts
@@ -450,9 +450,11 @@ async function prepareScene(context: BrowserContext, cell: Cell): Promise
await context.route("**/*", (route) => new URL(route.request().url()).origin === origin ? route.continue() : route.abort());
// The host keeps composer originals (composerFiles), so the track goes to the
// neutral composer route as a generic file and the host detects it (#3155).
+ // Images go there too, as their originals; only the track's upload is held.
await context.route("**/api/drafts/*/files", (route) => {
- net.uploads++;
- if (net.holdTracks) net.held.push(route);
+ const track = decodeURIComponent(route.request().headers()["x-file-name"] ?? "") === TRACK_NAME;
+ if (track) net.uploads++;
+ if (track && net.holdTracks) net.held.push(route);
else void route.continue();
});
// Forward the real socket, with an explicit network delay for queue frames.
@@ -533,10 +535,10 @@ async function prepareScene(context: BrowserContext, cell: Cell): Promise
await page.locator('input[type="file"][accept="image/*"]:not([capture])').setInputFiles({ name: "sail.png", mimeType: "image/png", buffer: SAIL });
await until(page, "p.draft().images === 1");
await page.locator("input[data-files-input]").setInputFiles({ name: TRACK_NAME, mimeType: "application/geo+json", buffer: TRACK });
- await page.waitForFunction(() => /uploading/.test(document.querySelector("[data-file-chip]")?.getAttribute("aria-label") ?? ""));
+ await page.waitForFunction(() => /uploading/.test(document.querySelector('[data-file-chip][aria-label^="ithaca-to-pylos-coastal-route-day-3.geojson,"]')?.getAttribute("aria-label") ?? ""));
// The host holds the words and the image; with the track still uploading
// the draft indicator never calls the draft saved (#3155): it waits.
- await hostUntil((d) => d.some((x) => x.sessionId === A && x.attachmentCount === 1 && x.preview === draft));
+ await hostUntil((d) => d.some((x) => x.sessionId === A && (x.attachmentCount ?? 0) + (x.fileCount ?? 0) === 1 && x.preview === draft));
await page.locator('[data-draft-save="queued"]').waitFor();
// The reader scrolls up, away from both ends, with the mouse wheel.
@@ -649,7 +651,7 @@ function measure(page: Page): Promise {
selectionEnd: field.selectionEnd,
replaced: marks.nodes.filter((n) => !n.isConnected).length,
previews: [...document.querySelectorAll("[data-composer] img")].map((img) => (img as HTMLImageElement).src),
- track: document.querySelector("[data-file-chip]")?.getAttribute("aria-label") ?? "",
+ track: document.querySelector('[data-file-chip][aria-label^="ithaca-to-pylos-coastal-route-day-3.geojson,"]')?.getAttribute("aria-label") ?? "",
pills: [...document.querySelectorAll('[data-row-half="right"] [data-pill]')].map((pill) => pill.textContent ?? ""),
transcriptPreviews: [...column.querySelectorAll("img")].map((img) => img.src),
replacedImages: marks.images.filter((img) => !img.isConnected).length,
@@ -665,7 +667,7 @@ async function drop(s: Pick, preparation: "sc
// of the drop: the order that cannot hide a failure behind a pause.
const uploading = s.net.held.splice(0);
for (const route of uploading) await route.abort("connectionreset").catch(() => {});
- if (uploading.length) await s.page.waitForFunction(() => !/uploading/.test(document.querySelector("[data-file-chip]")?.getAttribute("aria-label") ?? ""));
+ if (uploading.length) await s.page.waitForFunction(() => !/uploading/.test(document.querySelector('[data-file-chip][aria-label^="ithaca-to-pylos-coastal-route-day-3.geojson,"]')?.getAttribute("aria-label") ?? ""));
await probe(s.page, p => p.backoff.pause());
server!.stop(true);
const beforeOffline = await connectivity(s.page);
@@ -1115,7 +1117,8 @@ describe.skipIf(!executablePath)("repeated connection drops in the mounted app",
expect(base.pills, "a real pending follow-up is guarded").toHaveLength(1);
expect(base.pills[0]).toContain("Then bind me to the");
expect(base.transcriptPreviews, "a sent image body is guarded").toHaveLength(1);
- expect(base.transcriptPreviews[0]).toStartWith("blob:");
+ // An image original's sent row draws the frame it sent (#3155).
+ expect(base.transcriptPreviews[0]).toStartWith("data:image/jpeg;base64,");
}
log.push({ cycle, phase: "before", ...base });
@@ -1152,8 +1155,8 @@ describe.skipIf(!executablePath)("repeated connection drops in the mounted app",
// original identity/layout assertions. Recovery's preceding 500ms
// window and every drop/final/IME window remain independent.
await finishRender(page);
- if (cycle === 10) await page.waitForFunction(() => /km/.test(document.querySelector("[data-file-chip]")?.getAttribute("aria-label") ?? ""));
- else await page.waitForFunction(() => /uploading/.test(document.querySelector("[data-file-chip]")?.getAttribute("aria-label") ?? ""));
+ if (cycle === 10) await page.waitForFunction(() => /km/.test(document.querySelector('[data-file-chip][aria-label^="ithaca-to-pylos-coastal-route-day-3.geojson,"]')?.getAttribute("aria-label") ?? ""));
+ else await page.waitForFunction(() => /uploading/.test(document.querySelector('[data-file-chip][aria-label^="ithaca-to-pylos-coastal-route-day-3.geojson,"]')?.getAttribute("aria-label") ?? ""));
expect(net.uploads, `cycle ${cycle}: the upload resumed after reconnect`).toBe(uploadsBefore + 1);
const after = await measure(page);
log.push({ cycle, phase: "after", ...after });
@@ -1165,7 +1168,8 @@ describe.skipIf(!executablePath)("repeated connection drops in the mounted app",
expect(net.sent.slice(sentBefore).filter((t) => t === "chat_message"), "reconnecting sent no chat message").toEqual([]);
expect(net.sent.slice(sentBefore).length, "the spy saw the page's frames").toBeGreaterThan(0);
expect(await page.evaluate(() => (window as unknown as { __events: Array<{ type: string }> }).__events.map((e) => e.type)), "nothing blurred the field").toEqual([]);
- await hostUntil((d) => d.some((x) => x.sessionId === A && x.attachmentCount === 1 && x.preview === draft));
+ // The image and, now that it finished, the track: both stored originals (#3155).
+ await hostUntil((d) => d.some((x) => x.sessionId === A && (x.attachmentCount ?? 0) + (x.fileCount ?? 0) === 2 && x.preview === draft));
await finishRecoveredTurn(s, cell);
// #2932: a backend result is not host settlement. Hold B at that real
// boundary; the following IME scene retains its original tracker check.
diff --git a/packages/ui-react/tests/draft-runtime.test.ts b/packages/ui-react/tests/draft-runtime.test.ts
index 0490e9c6a4..a5b5ab7e60 100644
--- a/packages/ui-react/tests/draft-runtime.test.ts
+++ b/packages/ui-react/tests/draft-runtime.test.ts
@@ -242,11 +242,11 @@ describe.skipIf(!executablePath)("mounted per-session drafts", () => {
await release(first);
await until(a.page, `f.lastAssistant() === "Phorcys' harbour, under the olive tree."`);
- // An image joins it; the host stores the bytes before it says saved.
+ // An image joins it as its stored original (#3155); the host binds it before it says saved.
await a.page.locator('input[type="file"][accept="image/*"]:not([capture])').setInputFiles({ name: "harbour.png", mimeType: "image/png", buffer: HARBOUR });
await until(a.page, "f.view().images === 1");
await a.page.locator('[data-draft-save="saved"]').waitFor();
- await hostUntil((d) => d.some((x) => x.sessionId === session && x.attachmentCount === 1));
+ await hostUntil((d) => d.some((x) => x.sessionId === session && x.fileCount === 1 && !x.attachmentCount));
await expectHarbourImage(a.page);
// New chat: an empty composer, the session's draft kept.
@@ -338,7 +338,9 @@ describe.skipIf(!executablePath)("mounted per-session drafts", () => {
await until(a.page, `f.sends().some(send => !${JSON.stringify(saved.priorRequests)}.includes(send.requestId) && send.state === "accepted")`);
const accepted = (await fixture(a.page, (f) => f.sends())).filter(send => !saved.priorRequests.includes(send.requestId));
expect(accepted).toHaveLength(1);
- expect(accepted[0]?.draftRef).toEqual({ draftId: saved.view.draftId, revision: saved.view.revision! });
+ // The draft holds an image original, so Send is a snapshot (#3155): it is
+ // written in the one save that clears the composer, and the message names that revision.
+ expect(accepted[0]?.draftRef).toEqual({ draftId: saved.view.draftId, revision: saved.view.revision! + 1 });
await hostUntil((d) => !d.some((x) => x.sessionId === session) && prompts.filter((p) => p === offline).length >= 1);
expect((await hostDrafts()).some((x) => x.sessionId === session)).toBe(false);
expect(await composer(a.page).inputValue()).toBe("");
diff --git a/packages/ui-react/tests/fixtures/auth-expiry-client.ts b/packages/ui-react/tests/fixtures/auth-expiry-client.ts
index 3e5ce3b1da..d64fad2caa 100644
--- a/packages/ui-react/tests/fixtures/auth-expiry-client.ts
+++ b/packages/ui-react/tests/fixtures/auth-expiry-client.ts
@@ -65,8 +65,11 @@ Object.assign(window, {
return chat.activeSessionId ? chat.buffers[chat.activeSessionId]?.messages.length ?? 0 : 0;
},
text: () => draft()?.text ?? "",
- images: () => (draft()?.attachments ?? []).map((a) => ({ data: a.attachment.data, mediaType: a.attachment.mediaType, name: a.name })),
- allImages: () => Object.values(root.stores.drafts.getState().drafts).flatMap((d) => d.attachments.map((a) => ({ data: a.attachment.data, name: a.name }))),
+ // Legacy inline images by their frame; image originals (#3155) by the stored record that names their bytes.
+ images: () => [...(draft()?.attachments ?? []).map((a) => ({ data: a.attachment.data, mediaType: a.attachment.mediaType, name: a.name })),
+ ...(draft()?.files ?? []).filter((f) => f.file.kind === "image").map((f) => ({ data: `${f.file.fileId}:${f.file.sha256}:${f.file.bytes}`, mediaType: f.file.mediaType, name: f.file.incomingName || f.file.name }))],
+ allImages: () => Object.values(root.stores.drafts.getState().drafts).flatMap((d) => [...d.attachments.map((a) => ({ data: a.attachment.data, name: a.name })),
+ ...(d.files ?? []).filter((f) => f.file.kind === "image").map((f) => ({ data: f.file.fileId, name: f.file.incomingName || f.file.name }))]),
reviewText: () => root.stores.voice.getState().reviewText,
/** The review card's text, as a finished dictation leaves it (no microphone in CI). */
review: (text: string) => root.stores.voice.getState().setReviewText(text),
diff --git a/packages/ui-react/tests/fixtures/connection-continuity-client.tsx b/packages/ui-react/tests/fixtures/connection-continuity-client.tsx
index c604e0ca7c..0c9558b8d6 100644
--- a/packages/ui-react/tests/fixtures/connection-continuity-client.tsx
+++ b/packages/ui-react/tests/fixtures/connection-continuity-client.tsx
@@ -190,7 +190,7 @@ try {
draft: () => {
const drafts = root.stores.drafts.getState();
const d = drafts.drafts[drafts.idFor(root.stores.chat.getState().activeSessionId)];
- return { text: d?.text ?? "", images: d?.attachments.length ?? 0, sessionId: d?.sessionId ?? null };
+ return { text: d?.text ?? "", images: (d?.attachments.length ?? 0) + (d?.files ?? []).filter((f) => f.file.kind === "image").length, sessionId: d?.sessionId ?? null };
},
},
});
diff --git a/packages/ui-react/tests/fixtures/draft-runtime-client.ts b/packages/ui-react/tests/fixtures/draft-runtime-client.ts
index 01d995ed16..df727b4225 100644
--- a/packages/ui-react/tests/fixtures/draft-runtime-client.ts
+++ b/packages/ui-react/tests/fixtures/draft-runtime-client.ts
@@ -21,7 +21,7 @@ const view = () => {
const drafts = root.stores.drafts.getState();
const id = drafts.idFor(root.stores.chat.getState().activeSessionId);
const d = drafts.drafts[id];
- return { draftId: id, text: d?.text ?? "", images: d?.attachments.length ?? 0, revision: d?.host?.revision ?? null, conflict: Boolean(d?.conflict) };
+ return { draftId: id, text: d?.text ?? "", images: (d?.attachments.length ?? 0) + (d?.files ?? []).filter((f) => f.file.kind === "image").length, revision: d?.host?.revision ?? null, conflict: Boolean(d?.conflict) };
};
Object.assign(window, {
@@ -30,7 +30,7 @@ Object.assign(window, {
supported: () => root.stores.drafts.getState().supported,
activeSessionId: () => root.stores.chat.getState().activeSessionId,
view,
- unbound: () => Object.values(root.stores.drafts.getState().drafts).filter((d) => d.sessionId === null && (d.text || d.attachments.length)).map((d) => d.text),
+ unbound: () => Object.values(root.stores.drafts.getState().drafts).filter((d) => d.sessionId === null && (d.text || d.attachments.length || d.files?.length)).map((d) => d.text),
sends: () => Object.values(root.stores.drafts.getState().sends).map((s) => ({ requestId: s.requestId, state: s.state, draftRef: s.draftRef })),
lastAssistant: () => {
const chat = root.stores.chat.getState();
diff --git a/packages/ui-react/tests/fixtures/local-work-client.ts b/packages/ui-react/tests/fixtures/local-work-client.ts
index a1e3225ee7..ff16677b5a 100644
--- a/packages/ui-react/tests/fixtures/local-work-client.ts
+++ b/packages/ui-react/tests/fixtures/local-work-client.ts
@@ -31,7 +31,9 @@ Object.assign(window, {
return chat.activeSessionId ? chat.buffers[chat.activeSessionId]?.messages.length ?? 0 : 0;
},
text: () => draft()?.text ?? "",
- images: () => (draft()?.attachments ?? []).map((a) => ({ data: a.attachment.data, mediaType: a.attachment.mediaType, name: a.name })),
+ // Legacy inline images by their frame; image originals (#3155) by the stored record that names their bytes.
+ images: () => [...(draft()?.attachments ?? []).map((a) => ({ data: a.attachment.data, mediaType: a.attachment.mediaType, name: a.name })),
+ ...(draft()?.files ?? []).filter((f) => f.file.kind === "image").map((f) => ({ data: `${f.file.fileId}:${f.file.sha256}:${f.file.bytes}`, mediaType: f.file.mediaType, name: f.file.incomingName || f.file.name }))],
reviewText: () => root.stores.voice.getState().reviewText,
/** The review card's text, as a finished dictation leaves it (no microphone in CI). */
review: (text: string) => root.stores.voice.getState().setReviewText(text),
diff --git a/packages/ui-react/tests/fixtures/parallel-sessions-client.tsx b/packages/ui-react/tests/fixtures/parallel-sessions-client.tsx
index 87d0854bea..4330ed8911 100644
--- a/packages/ui-react/tests/fixtures/parallel-sessions-client.tsx
+++ b/packages/ui-react/tests/fixtures/parallel-sessions-client.tsx
@@ -85,9 +85,9 @@ Object.assign(window, {
draft: () => {
const drafts = root.stores.drafts.getState();
const d = drafts.drafts[drafts.idFor(root.stores.chat.getState().activeSessionId)];
- return { text: d?.text ?? "", images: d?.attachments.length ?? 0, sessionId: d?.sessionId ?? null };
+ return { text: d?.text ?? "", images: (d?.attachments.length ?? 0) + (d?.files ?? []).filter((f) => f.file.kind === "image").length, sessionId: d?.sessionId ?? null };
},
- unbound: () => Object.values(root.stores.drafts.getState().drafts).filter((d) => d.sessionId === null && (d.text || d.attachments.length)).map((d) => d.text),
+ unbound: () => Object.values(root.stores.drafts.getState().drafts).filter((d) => d.sessionId === null && (d.text || d.attachments.length || d.files?.length)).map((d) => d.text),
/** The messages of a session's buffer, as roles and text. */
transcript: (sessionId: string | null) => {
const chat = root.stores.chat.getState();
diff --git a/packages/ui-react/tests/parallel-sessions-runtime.test.ts b/packages/ui-react/tests/parallel-sessions-runtime.test.ts
index 3221089fa4..98338b81a3 100644
--- a/packages/ui-react/tests/parallel-sessions-runtime.test.ts
+++ b/packages/ui-react/tests/parallel-sessions-runtime.test.ts
@@ -131,7 +131,10 @@ function scriptedBackend(): AgentBackend {
bridge.emit({ type: "session_info", sessionId, isNew: !resumed });
const transcript = transcripts.get(sessionId) ?? [];
transcripts.set(sessionId, transcript);
- transcript.push({ role: "user", content: prompt, toolCalls: [] });
+ // The transcript keeps the composer originals' block a real backend
+ // records (#3153): replay strips it only once it reproduces byte for byte.
+ const attachments = /\n\n\n[\s\S]*?\n<\/brain-attachments>/.exec(contextPrompt)?.[0] ?? "";
+ transcript.push({ role: "user", content: prompt + attachments, toolCalls: [] });
const kind = prompt.split(":")[0]!;
const finish = (text: string, outcome: "success" | "error") => {
transcript.push({ role: "assistant", content: text, toolCalls: [] });
@@ -681,7 +684,7 @@ describe.skipIf(!executablePath)("mounted parallel sessions", () => {
await a.page.locator('input[type="file"][accept="image/*"]:not([capture])').setInputFiles({ name: "sail.png", mimeType: "image/png", buffer: SAIL });
await until(a.page, "p.draft().images === 1");
await a.page.locator('[data-draft-save="saved"]').waitFor();
- await hostUntil((d) => d.some((x) => x.sessionId === A && x.attachmentCount === 1 && x.preview === draftA));
+ await hostUntil((d) => d.some((x) => x.sessionId === A && (x.attachmentCount ?? 0) + (x.fileCount ?? 0) === 1 && x.preview === draftA));
// Leaving A mid-stream: an empty composer, A tracked as running, and
// neither a confirmation nor an abort.
@@ -737,6 +740,7 @@ describe.skipIf(!executablePath)("mounted parallel sessions", () => {
await until(a.page, `p.activeSessionId() === ${JSON.stringify(A)}`);
await until(a.page, `p.draft().text === ${JSON.stringify(draftA)} && p.draft().images === 1`);
expect(await composer(a.page).inputValue(), "A's words are back").toBe(draftA);
+ await a.page.locator("[data-composer] img").first().waitFor();
expect(await a.page.locator("[data-composer] img").count(), "and A's image").toBe(1);
await a.page.waitForTimeout(300);
expect(await probe(a.page, (p) => p.views().find((v) => v.sessionId === p.activeSessionId())?.cleared), "selecting A cleared nothing").toBe(false);
@@ -1179,6 +1183,8 @@ describe.skipIf(!executablePath)("mounted parallel sessions", () => {
const holdsA = async (page: Page, where: string) => {
await until(page, `p.draft().text === ${JSON.stringify(draftA)} && p.draft().images === 1`);
expect(await composer(page).inputValue(), `A's words after ${where}`).toBe(draftA);
+ // A restored image original's thumbnail is its frame, made again from the original the host keeps (#3155).
+ await page.locator("[data-composer] img").first().waitFor();
expect(await page.locator("[data-composer] img").count(), `A's image after ${where}`).toBe(1);
};
/** Goes to a destination that unmounts the composer, and back to Chat. */
@@ -1202,7 +1208,7 @@ describe.skipIf(!executablePath)("mounted parallel sessions", () => {
await a.page.locator('[data-draft-save="saved"]').waitFor();
// The draft indicator's summary (#3155): this exact text and its image.
expect(await a.page.locator("[data-draft-save]").getAttribute("data-draft-summary")).toMatch(/^Draft saved \d\d:\d\d: this text and 1 file\.$/);
- await hostUntil((d) => d.some((x) => x.sessionId === A && x.preview === draftA && x.attachmentCount === 1));
+ await hostUntil((d) => d.some((x) => x.sessionId === A && x.preview === draftA && (x.attachmentCount ?? 0) + (x.fileCount ?? 0) === 1));
// New chat by the visible control: empty, and the letter is its own draft.
await newChat(run, a.page);
diff --git a/packages/ui-react/tests/snapshot-host.ts b/packages/ui-react/tests/snapshot-host.ts
index 6b67ee14e3..afa06cc62c 100644
--- a/packages/ui-react/tests/snapshot-host.ts
+++ b/packages/ui-react/tests/snapshot-host.ts
@@ -13,7 +13,9 @@ import type { AttachmentFile, ClientMessage, Draft, DraftSnapshot, DraftSnapshot
* returned; a held one may change its files; only a returned one may be
* left out.
* - Originals: one per upload, minted for one draft (lineage), the same
- * `fileId` for a repeated `Idempotency-Key`. References are kept per file
+ * `fileId` for a repeated `Idempotency-Key`. PNG and JPEG signatures make
+ * an `image` (the bytes decide, as the host's detection), and
+ * `GET /api/attachments/:fileId` serves a referenced original's exact bytes. References are kept per file
* (`draft`, `outgoing`, `message`), and a file whose last reference goes
* is stamped `unreferencedSince`; nothing here ever unlinks a file.
* - A save repeated under its `Idempotency-Key` gets the first answer
@@ -54,7 +56,10 @@ export function snapshotHost(options: { limit?: number } = {}) {
const now = () => ++clock;
let uploadGate: Promise | null = null;
let saveGate: Promise | null = null;
- let failNext: "refuse" | null = null;
+ let failNext: "refuse" | "fail" | null = null;
+ /** Each stored original's exact bytes, as `GET /api/attachments/:fileId` serves them. */
+ const stored = new Map();
+ const isImage = (b: Uint8Array) => (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) ? "image/png" : (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) ? "image/jpeg" : null;
const json = (body: unknown, status = 200) => Response.json(body, { status });
function setRefs(kind: "draft" | "outgoing", draftId: string, ids: readonly string[]) {
@@ -112,6 +117,14 @@ export function snapshotHost(options: { limit?: number } = {}) {
return json({ sessionId, backendId: "claude", revision: recovery.revision,
latest: { requestId: recovery.latestRequestId, turnId: recovery.latestRequestId ? "turn-ithaca" : null, state: recovery.latestRequestId ? "running" : "unknown", outcome: null, startedAt: null, endedAt: null }, pending: [] });
}
+ const original = /\/attachments\/([^/]+)$/.exec(path);
+ if (original && method === "GET") {
+ const fileId = decodeURIComponent(original[1]!);
+ const bytes = stored.get(fileId);
+ // Any live reference authorizes a read; an unreferenced file reads as absent.
+ if (!bytes || !(refs.get(fileId)?.size)) return json({ error: "ATTACHMENT_NOT_FOUND", message: "" }, 404);
+ return new Response(bytes as Uint8Array, { status: 200, headers: { "Content-Type": files.get(fileId)!.mediaType } });
+ }
const upload = /\/drafts\/([^/]+)\/files$/.exec(path);
if (upload) {
const draftId = decodeURIComponent(upload[1]!);
@@ -121,15 +134,20 @@ export function snapshotHost(options: { limit?: number } = {}) {
uploads.push({ draftId, key, name });
if (uploadGate) await uploadGate;
if (failNext === "refuse") { failNext = null; return json({ error: "ATTACHMENT_CAPACITY", message: "", limit: 1, bound: "pool" }, 507); }
+ if (failNext === "fail") { failNext = null; return json({ error: "INTERNAL", message: "" }, 500); }
let fileId = keys.get(`${draftId}:${key}`);
if (!fileId) {
fileId = `00000000-0000-4000-8000-${String(++seq).padStart(12, "0")}`;
keys.set(`${draftId}:${key}`, fileId);
const sha256 = fileId.replace(/-/g, "").padEnd(64, "0");
const p = `.brain-ui/attachments/${fileId}/${name}`;
- files.set(fileId, name.endsWith(".pdf")
+ const image = isImage(bytes);
+ files.set(fileId, image
+ ? { fileId, name, path: p, bytes: bytes.byteLength, sha256, draftId, mediaType: image, kind: "image", reader: "image" }
+ : name.endsWith(".pdf")
? { fileId, name, path: p, bytes: bytes.byteLength, sha256, draftId, mediaType: "application/pdf", kind: "pdf", reader: "pdf" }
: { fileId, name, path: p, bytes: bytes.byteLength, sha256, draftId, mediaType: "text/plain", kind: "text", reader: "text" });
+ stored.set(fileId, bytes);
// An upload not yet bound: the 1-hour clock, from the host's own refs.
unreferencedSince.set(fileId, now());
}
@@ -238,6 +256,10 @@ export function snapshotHost(options: { limit?: number } = {}) {
return release;
},
refuseNextUpload() { failNext = "refuse"; },
+ /** The next upload is answered 500: not stored, and retrying is safe. */
+ failNextUpload() { failNext = "fail"; },
+ /** The exact bytes stored for an original. */
+ storedBytes: (fileId: string) => stored.get(fileId),
/** Store every save, then drop its answer, until set back. */
loseSaveAnswers(value = true) { loseSaves = value; },
/**