diff --git a/.changeset/composer-sent-file-reads.md b/.changeset/composer-sent-file-reads.md new file mode 100644 index 0000000000..9baecb0f91 --- /dev/null +++ b/.changeset/composer-sent-file-reads.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-ui-react": minor +"@schlessera/brain-ui-sdk": minor +--- + +Sent composer originals now show what the agent read of them (#3155). A sent row reads `not read yet`, `read p. 1–3`, `read`, `partly read p. 1–3`, `read stopped at 1.0 KB`, `no text found · may be scanned`, `couldn't read: password-protected` or `damaged file`, `couldn't read`, `original changed since sending`, or `no reader for this kind of file`. The state comes only from the host's read records (#3589): a session's records are fetched when its view opens and after each reconnect, and each new read updates its row from an `attachment_read` frame. Pages read across several turns are combined. Until the host's records arrive, and on a host without `attachmentReads`, a row claims neither "read" nor "not read yet". + +`BrainUiClient` now declares `attachmentReads` in its `client_hello`, so its consumers can receive `attachment_read` frames. `serverMessageSchema` already parses them. diff --git a/docs/decisions/answer-delivery.md b/docs/decisions/answer-delivery.md index e9ed010f1a..6ee9f0649a 100644 --- a/docs/decisions/answer-delivery.md +++ b/docs/decisions/answer-delivery.md @@ -234,7 +234,7 @@ Before this, the terminal frame replaced an unanswered card with a dismissed stub, and its draft went with the controls. Now the card stays the editable question under a prompt that says the turn ended or timed out (`const [endedDismissed`, -`packages/ui-react/src/components/chat/message-bubble.tsx:608-626`). Its +`packages/ui-react/src/components/chat/message-bubble.tsx:632-650`). Its Submit sends no frame to the ended request. It records the answer locally as a `closed`/`ended` delivery, so the card shows the shipped Not delivered footer with Copy answer and Send as message (R1). Send as message is the only @@ -320,7 +320,7 @@ in both themes, using the keyboard. The late stored-principal race has one native `ask_user` representative. All four ChatPage adapters enter `submitAnswer`; the first host frame calls `answers.connected()` without selecting an answer kind (`answersReady = true`, -`packages/ui-react/src/ws-client/account.ts:76-77`). The shared restore path must +`packages/ui-react/src/ws-client/account.ts:79-80`). The shared restore path must preserve that newer principal. Repeating this browser race for list, rank and form adds no separate startup path. Their online and offline/reload native cases remain: input adapters, `answerFrame` serialization and host dispatch diff --git a/docs/decisions/chat-attachments.md b/docs/decisions/chat-attachments.md index b040d3268b..8d2cce6d45 100644 --- a/docs/decisions/chat-attachments.md +++ b/docs/decisions/chat-attachments.md @@ -298,9 +298,22 @@ originals, on a host that advertises `composerFiles`: prove it (#1112, #1150, #1018) remove that capability from the real host's hello so they keep proving it. The drop-and-reconnect suite (#1013) runs the generic path against the real host. -- **Sent rows claim no read.** A sent message lists its originals by name, - kind and size. The read records are not delivered to clients yet (#3589), - so a row shows neither *read* nor *not read yet*. +- **Sent rows say what was read, from the records only.** A sent message + lists its originals by name, kind and size, and the host's read records + (#3589) add the design's §8.4 read state. The client declares + `attachmentReads`, reads a session's records when its view opens and after + each hello, and appends each `attachment_read` frame. Three choices the + records force: + - **Scopes combine.** Pages or bytes read across several calls are joined, + so a later range never hides an earlier one. A failure shows only when + nothing was read, and a changed original always shows. + - **What a record cannot say is not said.** A record keeps an outcome and a + scope, not `pagesWithoutText` or a failure's reason. A partial PDF read is + *partly read p. 1–3* rather than *3 of 12 pages had text*, and a failed + one is *couldn't read* rather than *took too long*. + - **Unknown is not unread.** Until a session's records arrive, or on a host + without `attachmentReads`, a row claims neither *read* nor *not read yet*. + An image never reads as *not read yet*: it reaches the agent as a frame. The rejected options were offered in the rulings above: diff --git a/docs/decisions/design-kit/follow-ups.md b/docs/decisions/design-kit/follow-ups.md index 4034674d8f..df5251327b 100644 --- a/docs/decisions/design-kit/follow-ups.md +++ b/docs/decisions/design-kit/follow-ups.md @@ -45,7 +45,7 @@ does a replayed session show? last call that parses is lifted to the answer's closing row, after the text and the share menu. At its call position `groupParts` draws nothing (`payload?.block.kind === "suggestions"`, - `packages/ui-react/src/components/chat/message-bubble.tsx:293`), and shares + `packages/ui-react/src/components/chat/message-bubble.tsx:317`), and shares and prints leave it out. This also amends D37 §8's "chips while live, `FeedbackRow` later": #41 closed as not planned, so the closing row is suggestions or nothing. diff --git a/docs/integration-contract.md b/docs/integration-contract.md index da5466c515..39b922f788 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -188,7 +188,8 @@ declared the same flag as one new `attachment_read` frame. `ServerMessage` gains that variant; a client without the flag never receives it. Nothing of either reaches a provider. See [the wire component](integration-contract/wire.md#attachment-reads-additive-0450-3589) and [the HTTP API](http-api.md#attachment-reads-additive-0450-3589). This -ships in a minor. +ships in a minor. The SDK's `BrainUiClient` now declares the flag in its +`client_hello`, and the React package shows the records on sent rows (#3155). ## Reading a chat deletion's outcome (additive, #3455) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 85a2c1c060..d9041249a8 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -2005,6 +2005,15 @@ The SDK publishes `ATTACHMENT_READS_CAPABILITY`, `AttachmentReadEntry`, `serverAttachmentReadSchema` and `sessionAttachmentReadsResponseSchema` schemas; `serverMessageSchema` accepts the new frame. +**The first-party client declares it (0.45.0, #3155).** `BrainUiClient`'s +`client_hello` declares `attachmentReads: true`, so a consumer of the SDK +client can receive `attachment_read` frames; `serverMessageSchema` already +parses them, and a consumer that ignores unknown frame types is unaffected. +`@schlessera/brain-ui-react` reads a session's records when its view opens and +after each hello, appends each frame, and derives a sent row's read state only +from those records. Until a session's records arrive, a sent row claims neither +"read" nor "not read yet". + ### Explicit chat deletion (additive, #3230) diff --git a/docs/process/theme-parity.md b/docs/process/theme-parity.md index 38940588b3..3da5bef24f 100644 --- a/docs/process/theme-parity.md +++ b/docs/process/theme-parity.md @@ -254,7 +254,7 @@ The suffix geometry checks compare the recovered drawing to that case's own baseline; they do not assert an absolute theme-specific message size. Both responsive branches still execute with the actual consumer stylesheet. The user path in (`MessageBubble`, -`packages/ui-react/src/components/chat/message-bubble.tsx:66-173`) uses +`packages/ui-react/src/components/chat/message-bubble.tsx:87-194`) uses (`UserTurn`, `packages/ui-react/src/components/chat/transcript-turn.tsx:61-69`) and the kit's user bubble. Its consumer padding, text wrapping and header layout do not branch on theme; the consumer `.chat-message-body` rule likewise diff --git a/packages/ui-react/src/components/chat/message-bubble.tsx b/packages/ui-react/src/components/chat/message-bubble.tsx index 4530028e39..f56c0de7fe 100644 --- a/packages/ui-react/src/components/chat/message-bubble.tsx +++ b/packages/ui-react/src/components/chat/message-bubble.tsx @@ -4,7 +4,7 @@ import { AttachmentRow } from "@schlessera/brain-ui-kit"; import { attachmentRowProps, trackRowProps } from "../../lib/track-attachment.js"; import { HandoffCard } from "./handoff-links.js"; import { AskUserFormExchangeCard } from "./ask-user-form-card.js"; -import type { AskUserFormAnswers } from "@schlessera/brain-ui-sdk/protocol"; +import type { AskUserFormAnswers, AttachmentFile, AttachmentReadEntry } from "@schlessera/brain-ui-sdk/protocol"; import { useBrainUiRoot } from "../../root-context.js"; import { memo, useEffect, useRef, useState, type ReactNode } from "react"; import { useStore } from "zustand"; @@ -63,6 +63,27 @@ import { useChatStore } from "../../stores/chat-store.js"; * user bubble, thinking disclosure, the streaming dot — is * `transcript-turn.tsx`, on the kit. */ +const NO_READS: Record = {}; +const NO_FILE_READS: AttachmentReadEntry[] = []; + +/** + * A sent message's composer originals (#3155), each with what the agent read + * of it. Reads are the host's records for the session in view (#3589); until + * they arrive, or on a host without them, the rows claim nothing about + * reading. Its own subscription, so a read re-renders only these rows. + */ +function SentFiles({ files }: { files: AttachmentFile[] }) { + const root = useBrainUiRoot(); + const sessionId = useStore(root.stores.chat, (s) => s.activeSessionId); + const reads = useStore(root.stores.attachmentReads, (s) => + s.supported && sessionId && s.loaded[sessionId] ? s.reads[sessionId] ?? NO_READS : null); + return ( +
+ {files.map((file) => )} +
+ ); +} + export const MessageBubble = memo(function MessageBubble({ message, onToolApproval, @@ -148,7 +169,7 @@ export const MessageBubble = memo(function MessageBubble({ {spoken && message.content && {linkifyPaths(message.content)}} {!!message.files?.length &&
{message.files.map(file => )}
} - {!!message.attachmentFiles?.length &&
{message.attachmentFiles.map(file => )}
} + {!!message.attachmentFiles?.length && } {!spoken && message.content && (
{linkifyPaths(message.content)} diff --git a/packages/ui-react/src/hooks/websocket-handlers/connection.ts b/packages/ui-react/src/hooks/websocket-handlers/connection.ts index 27a1b42e08..51e2693dbf 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/connection.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/connection.ts @@ -49,8 +49,8 @@ export const connectionFrameHandlers = { // Browser invalidation is #3231's: this client does not declare // `chatDeletion`, so the host never sends it this frame. chat_retired: () => {}, - // Sent-row read states are #3155's: this client does not declare - // `attachmentReads`, so the host never sends it this frame. + // Sent-row read states (#3155): the account's read client takes the frame + // beside the demux, so nothing here touches a transcript. attachment_read: () => {}, conversation_opened: () => {}, conversation_closed: () => {}, diff --git a/packages/ui-react/src/lib/attachment-reads.ts b/packages/ui-react/src/lib/attachment-reads.ts new file mode 100644 index 0000000000..79370fc71c --- /dev/null +++ b/packages/ui-react/src/lib/attachment-reads.ts @@ -0,0 +1,70 @@ +import { ATTACHMENT_READS_CAPABILITY, type ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { sessionAttachmentReadsResponseSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { BrainUiServices } from "../root.js"; + +/** How long one reads request may take before it counts as no answer. */ +const READS_CALL_TIMEOUT_MS = 15_000; + +/** + * Delivers the host's attachment read records to the root's store (#3155, + * #3589). A session's reads are fetched when its view opens and again after + * each hello, since frames sent while the socket was down are gone; reads + * recorded during a live turn arrive as `attachment_read` frames. Until a + * session's answer arrives its sent rows claim nothing about reading. + * + * Reads only: nothing here sends a message or starts work. + */ +export function createAttachmentReadClient(root: Pick) { + const store = root.stores.attachmentReads; + let disposed = false; + /** Bumped by every hello, so an answer from an older connection is dropped. */ + let epoch = 0; + const inFlight = new Set(); + + async function load(sessionId: string): Promise { + if (disposed || !store.getState().supported || inFlight.has(sessionId)) return; + const asked = epoch; + inFlight.add(sessionId); + try { + const res = await root.request(`${root.apiBase()}/sessions/${encodeURIComponent(sessionId)}/attachment-reads`, { + cache: "no-store", + signal: AbortSignal.timeout(READS_CALL_TIMEOUT_MS), + }); + if (!res.ok) return; + const parsed = sessionAttachmentReadsResponseSchema.safeParse(await res.json().catch(() => undefined)); + if (!parsed.success || parsed.data.sessionId !== sessionId) return; + if (disposed || asked !== epoch) return; + store.getState().replace(sessionId, parsed.data.reads); + } catch { + // No answer: the rows keep claiming nothing, and the next view or hello asks again. + } finally { + inFlight.delete(sessionId); + } + } + + const active = () => root.stores.chat.getState().activeSessionId; + const unsubscribe = root.stores.chat.subscribe((state, previous) => { + const id = state.activeSessionId; + if (id && id !== previous.activeSessionId && !store.getState().loaded[id]) void load(id); + }); + + return { + hello(msg: Extract): void { + if (disposed) return; + epoch++; + store.getState().reset(); + store.getState().setSupported(msg.capabilities?.[ATTACHMENT_READS_CAPABILITY] === true); + const id = active(); + if (id) void load(id); + }, + frame(msg: ServerMessage): void { + if (disposed || msg.type !== "attachment_read" || !store.getState().supported) return; + store.getState().add(msg.sessionId, msg.read); + }, + dispose(): void { + disposed = true; + unsubscribe(); + store.getState().reset(); + }, + }; +} diff --git a/packages/ui-react/src/lib/track-attachment.ts b/packages/ui-react/src/lib/track-attachment.ts index 1b0ad33307..286940acf3 100644 --- a/packages/ui-react/src/lib/track-attachment.ts +++ b/packages/ui-react/src/lib/track-attachment.ts @@ -1,5 +1,5 @@ import type { AttachmentRowProps } from "@schlessera/brain-ui-kit"; -import type { AttachmentFile, SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; +import type { AttachmentFile, AttachmentReadEntry, SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; import { trackBytes } from "./track-uploads.js"; import { fileKindLabel } from "./attachment-queue.js"; @@ -20,18 +20,79 @@ export function trackRowProps(file: SharedFileMeta): AttachmentRowProps { return { kind: "doc", label, meta, tone: "neutral", actionIcon: "" }; } +/** Merged inclusive ranges, ascending. */ +function union(ranges: [number, number][]): [number, number][] { + const out: [number, number][] = []; + for (const [a, b] of [...ranges].sort((x, y) => x[0] - y[0])) { + const last = out.at(-1); + if (last && a <= last[1] + 1) last[1] = Math.max(last[1], b); + else out.push([a, b]); + } + return out; +} + +const pageList = (ranges: [number, number][]) => ranges.map(([a, b]) => (a === b ? `${a}` : `${a}\u2013${b}`)).join(", "); + /** - * A sent composer original (#3155): its name, kind and size, and nothing - * about its contents. Which parts the agent read is recorded by the host - * (`attachment_reads`) but not delivered to clients yet (#3589), so a sent - * row claims neither "read" nor "not read yet". + * What the host's read records say about one sent original (design §8.4, + * rev 3 §6), or null when nothing was read. Only recorded reads count: a + * file's kind or reader never yields "read". Successful scopes are combined + * across calls, so a later page range never hides an earlier one; a failure + * shows only when nothing was read, and a changed original always shows. */ -export function attachmentRowProps(file: AttachmentFile): AttachmentRowProps { - if (file.kind === "track" && file.track && !file.trackRejected) return trackRowProps({ ...file.track, incomingName: file.incomingName ?? file.track.incomingName }); +export function readCopy(entries: readonly AttachmentReadEntry[]): { text: string; tone: AttachmentRowProps["tone"] } | null { + if (entries.length === 0) return null; + if (entries.at(-1)!.outcome === "changed") return { text: "original changed since sending", tone: "amber" }; + const done = entries.filter((e) => (e.outcome === "read" || e.outcome === "partial") && e.scope); + if (done.length > 0) { + const allRead = done.every((e) => e.outcome === "read"); + const pages = done.flatMap((e) => (e.scope && "pages" in e.scope ? [e.scope] : [])); + if (pages.length > 0) { + const covered = union(pages.map((s) => s.pages)); + const count = Math.max(...pages.map((s) => s.pageCount)); + const whole = covered.length === 1 && covered[0]![0] <= 1 && covered[0]![1] >= count; + // A partial PDF read had blank pages or was cut short; which, the record does not say. + if (!allRead) return { text: `partly read p. ${pageList(covered)}`, tone: "amber" }; + return { text: whole ? "read" : `read p. ${pageList(covered)}`, tone: "teal" }; + } + const spans = done.flatMap((e) => (e.scope && "bytes" in e.scope ? [e.scope] : [])); + const total = Math.max(...spans.map((s) => s.totalBytes)); + // Byte scopes end exclusive; as inclusive ranges, two adjacent calls join. + const covered = union(spans.map((s) => [s.bytes[0], s.bytes[1] - 1])); + if (covered.length === 1 && covered[0]![0] === 0 && covered[0]![1] >= total - 1) return { text: "read", tone: "teal" }; + const head = covered[0]![0] === 0 ? covered[0]![1] + 1 : 0; + return { text: head > 0 ? `read stopped at ${trackBytes(head)}` : "partly read", tone: "amber" }; + } + switch (entries.at(-1)!.outcome) { + case "no_text": return { text: "no text found \u00b7 may be scanned", tone: "amber" }; + case "encrypted": return { text: "couldn't read: password-protected", tone: "amber" }; + case "malformed": return { text: "couldn't read: damaged file", tone: "amber" }; + // A record keeps the outcome, not the reason, so the row names none. + case "failed": return { text: "couldn't read", tone: "amber" }; + case "unavailable": return { text: "no reader for this kind of file", tone: "neutral" }; + default: return null; + } +} + +/** + * A sent composer original (#3155): its name, kind and size, and what the + * agent read of it. `reads` is that file's recorded reads (#3589), or + * 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 { + 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 }); + if (!read) return row; + return { ...row, meta: [...(Array.isArray(row.meta) ? row.meta : row.meta ? [row.meta] : []), read.text], tone: read.tone }; + } const label = file.incomingName || file.name || "Unnamed file"; const size = Number.isFinite(file.bytes) && file.bytes >= 0 ? trackBytes(file.bytes) : undefined; const kind = file.trackRejected ? "Text" : fileKindLabel(file); - const meta = [[kind, size, "sent"].filter(Boolean).join(" · ")]; - if (file.reader === "none") meta.push("No reader for this kind of file here."); - return { kind: file.kind === "image" ? "image" : "doc", label, meta, tone: "neutral", actionIcon: "" }; + const readable = file.reader === "pdf" || file.reader === "text" || file.reader === "track"; + const state = read?.text ?? (reads && readable ? "not read yet" : reads && file.reader === "none" ? "no reader for this kind of file" : "sent"); + const meta = [[file.reader === "none" && reads ? undefined : kind, size, state].filter(Boolean).join(" \u00b7 ")]; + if (file.reader === "none" && !reads) meta.push("No reader for this kind of file here."); + return { kind: file.kind === "image" ? "image" : "doc", label, meta, tone: read?.tone ?? "neutral", actionIcon: "" }; } diff --git a/packages/ui-react/src/stores/attachment-read-state.ts b/packages/ui-react/src/stores/attachment-read-state.ts new file mode 100644 index 0000000000..f13585cef0 --- /dev/null +++ b/packages/ui-react/src/stores/attachment-read-state.ts @@ -0,0 +1,58 @@ +import { createStore } from "zustand/vanilla"; +import type { AttachmentReadEntry } from "@schlessera/brain-ui-sdk/protocol"; + +/** + * What the agent read of each sent composer original, per session (#3155, + * #3589). The host is the only source: a session's reads arrive from + * `GET /api/sessions/:id/attachment-reads` when its view opens, and each + * later read as one `attachment_read` frame. Nothing here is inferred from a + * file's kind or reader, so a sent row says "read" only on a recorded read. + * + * Held outside the transcript buffers, like follow-ups: a history replace must + * not erase reads, and an evicted buffer must not lose them. + */ +export interface AttachmentReadState { + /** Whether this host delivers reads; without it a sent row claims nothing. */ + supported: boolean; + /** sessionId → fileId → that file's recorded reads, oldest first. */ + reads: Record>; + /** Sessions whose route answer has arrived since the last hello. */ + loaded: Record; + setSupported(supported: boolean): void; + /** The route's answer replaces what was known; frames that raced it are kept. */ + replace(sessionId: string, reads: AttachmentReadEntry[]): void; + /** One frame: appended once, by its identity. */ + add(sessionId: string, read: AttachmentReadEntry): void; + /** A new connection, principal or account: nothing known carries over. */ + reset(): void; +} + +const same = (a: AttachmentReadEntry, b: AttachmentReadEntry) => + a.fileId === b.fileId && a.turnId === b.turnId && a.at === b.at && a.outcome === b.outcome; + +function byFile(entries: AttachmentReadEntry[]): Record { + const out: Record = {}; + for (const entry of [...entries].sort((a, b) => a.at - b.at)) (out[entry.fileId] ??= []).push(entry); + return out; +} + +export function createAttachmentReadStore() { + return createStore()((set) => ({ + supported: false, + reads: {}, + loaded: {}, + setSupported: (supported) => set((s) => (s.supported === supported ? s : { supported })), + replace: (sessionId, entries) => set((s) => { + const known = Object.values(s.reads[sessionId] ?? {}).flat(); + const merged = [...entries, ...known.filter((k) => !entries.some((e) => same(e, k)))]; + return { reads: { ...s.reads, [sessionId]: byFile(merged) }, loaded: { ...s.loaded, [sessionId]: true } }; + }), + add: (sessionId, read) => set((s) => { + const files = s.reads[sessionId] ?? {}; + const current = files[read.fileId] ?? []; + if (current.some((e) => same(e, read))) return s; + return { reads: { ...s.reads, [sessionId]: { ...files, [read.fileId]: [...current, read].sort((a, b) => a.at - b.at) } } }; + }), + reset: () => set({ reads: {}, loaded: {} }), + })); +} diff --git a/packages/ui-react/src/stores/create-stores.ts b/packages/ui-react/src/stores/create-stores.ts index 0bd4a36c68..122adff823 100644 --- a/packages/ui-react/src/stores/create-stores.ts +++ b/packages/ui-react/src/stores/create-stores.ts @@ -18,6 +18,7 @@ import { createVoiceStore } from "../voice/voice-state.js"; import { createTrackerStore } from "./tracker-state.js"; import { createSessionListStore } from "./session-list-state.js"; import { createDraftStore } from "./draft-state.js"; +import { createAttachmentReadStore, type AttachmentReadState } from "./attachment-read-state.js"; import type { StoreEnvironment } from "./store-environment.js"; export function createBrainStores(env: StoreEnvironment) { @@ -42,6 +43,8 @@ export function createBrainStores(env: StoreEnvironment) { share: createShareStore(), handoff, followUp: createFollowUpStore(), + /** What the agent read of each sent composer original (#3155, #3589). */ + attachmentReads: createAttachmentReadStore() satisfies StoreApi, voice: createVoiceStore(env), trackers: createTrackerStore(env), // The list is where handoff links live (#61): every answer indexes them. diff --git a/packages/ui-react/src/ws-client/account.ts b/packages/ui-react/src/ws-client/account.ts index 8c1a455f60..0b3dfbc2ab 100644 --- a/packages/ui-react/src/ws-client/account.ts +++ b/packages/ui-react/src/ws-client/account.ts @@ -6,6 +6,7 @@ import { REFUSAL_ATTEMPTS } from "../lib/connection-issue.js"; import { createAnswerDelivery } from "../lib/answer-delivery/manager.js"; import { createTrackerClient } from "../lib/tracker-client.js"; import { createDraftClient } from "../lib/draft-client.js"; +import { createAttachmentReadClient } from "../lib/attachment-reads.js"; const authLifecycles = new WeakMap(); /** @internal Called only after the gate removes protected views. */ @@ -59,6 +60,8 @@ export function createAccountServices( trackers: createTrackerClient(root), /** Every session's own composer draft, kept on the host when it can (D52 §5, #951). */ drafts: makeDrafts(), + /** What the agent read of sent composer originals (#3155, #3589). Reads only. */ + attachmentReads: createAttachmentReadClient(root), /** * The first frame of a connection settles what its host supports: a hello, * or anything else from a host too old to send one. Only then can queued @@ -84,13 +87,14 @@ export function createAccountServices( services.answers.disconnected(); }, dispose(): void { - services.answers.dispose(); services.trackers.dispose(); services.drafts.dispose(); services.safety.dispose(); + services.answers.dispose(); services.trackers.dispose(); services.drafts.dispose(); services.safety.dispose(); services.attachmentReads.dispose(); }, restore(): void { services.answers = makeAnswers(); void services.answers.start(); services.safety = createSafetyClient(root,message=>deps.send(message)); services.trackers = createTrackerClient(root); services.drafts = makeDrafts(); + services.attachmentReads = createAttachmentReadClient(root); }, }; return services; diff --git a/packages/ui-react/src/ws-client/inbound.ts b/packages/ui-react/src/ws-client/inbound.ts index b9642552d9..862c4b9be3 100644 --- a/packages/ui-react/src/ws-client/inbound.ts +++ b/packages/ui-react/src/ws-client/inbound.ts @@ -197,14 +197,14 @@ export function createInbound(root: BrainUiServices, deps: InboundDeps) { // After the demux, so a draft that just became this session is already // the session in view and is not mistaken for unwatched work. if (msg.type === "server_hello") { - deps.services.trackers.hello(msg); deps.services.drafts.hello(msg); + deps.services.trackers.hello(msg); deps.services.drafts.hello(msg); deps.services.attachmentReads.hello(msg); // Resume reports even an empty queue. Revalidate retained background // pills too; the selected session already reattaches on connection. for (const sessionId of Object.keys(root.stores.followUp.getState().pending)) { if (sessionId !== root.stores.chat.getState().activeSessionId) deps.send({ type: "session_resume", sessionId }); } } - else deps.services.trackers.frame(msg); + else { deps.services.trackers.frame(msg); deps.services.attachmentReads.frame(msg); } deps.services.frameSeen(); } diff --git a/packages/ui-react/tests/attachment-reads.test.ts b/packages/ui-react/tests/attachment-reads.test.ts new file mode 100644 index 0000000000..8133471c7e --- /dev/null +++ b/packages/ui-react/tests/attachment-reads.test.ts @@ -0,0 +1,137 @@ +/** + * Sent-row read states (#3155, design §8.4 sent rows, rev 3 §6): what a row + * says comes only from the host's read records (#3589), never from a file's + * kind or reader, and the reads client delivers those records per session. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import type { AttachmentFile, AttachmentReadEntry } from "@schlessera/brain-ui-sdk/protocol"; +import { attachmentRowProps, readCopy } from "../src/lib/track-attachment.js"; +import { createAttachmentReadStore } from "../src/stores/attachment-read-state.js"; +import { createAttachmentReadClient } from "../src/lib/attachment-reads.js"; +import { createBrainUiRoot } from "../src/root.js"; + +const PERMIT: AttachmentFile = { + fileId: "00000000-0000-4000-8000-000000000001", name: "ithaca-permit.pdf", path: ".brain-ui/attachments/00000000-0000-4000-8000-000000000001/ithaca-permit.pdf", + mediaType: "application/pdf", bytes: 2_516_582, sha256: "a".repeat(64), kind: "pdf", reader: "pdf", +}; +const CREW: AttachmentFile = { ...PERMIT, fileId: "00000000-0000-4000-8000-000000000002", name: "crew-list.txt", mediaType: "text/plain", bytes: 1_843, kind: "text", reader: "text" }; +const SIRENS: AttachmentFile = { ...PERMIT, fileId: "00000000-0000-4000-8000-000000000003", name: "sirens.m4a", mediaType: "audio/mp4", bytes: 3_250_000, kind: "binary", reader: "none" }; + +let at = 1_783_836_720_000; +const pdf = (outcome: AttachmentReadEntry["outcome"], pages?: [number, number], pageCount = 12): AttachmentReadEntry => + ({ fileId: PERMIT.fileId, turnId: `turn-${at}`, outcome, scope: pages ? { pages, pageCount } : null, at: at++ }); +const text = (outcome: AttachmentReadEntry["outcome"], bytes?: [number, number], totalBytes = 1_843): AttachmentReadEntry => + ({ fileId: CREW.fileId, turnId: `turn-${at}`, outcome, scope: bytes ? { bytes, totalBytes } : null, at: at++ }); +const meta = (file: AttachmentFile, reads?: AttachmentReadEntry[]) => (attachmentRowProps(file, reads).meta as string[])[0]; + +describe("readCopy", () => { + test("no record is no claim", () => expect(readCopy([])).toBeNull()); + test("a whole PDF read in one call reads as read, a range names its pages", () => { + expect(readCopy([pdf("read", [1, 12])])).toEqual({ text: "read", tone: "teal" }); + expect(readCopy([pdf("read", [1, 3])])).toEqual({ text: "read p. 1–3", tone: "teal" }); + }); + test("later ranges join earlier ones instead of hiding them", () => { + expect(readCopy([pdf("read", [1, 3]), pdf("read", [4, 6])])!.text).toBe("read p. 1–6"); + expect(readCopy([pdf("read", [1, 2]), pdf("read", [9, 9])])!.text).toBe("read p. 1–2, 9"); + expect(readCopy([pdf("read", [1, 6]), pdf("read", [7, 12])])!.text).toBe("read"); + }); + test("a partial PDF read never reads as read", () => { + expect(readCopy([pdf("partial", [1, 3])])).toEqual({ text: "partly read p. 1–3", tone: "amber" }); + }); + test("text reads by byte range: whole, cut short, and continued to the end", () => { + expect(readCopy([text("read", [0, 1_843])])).toEqual({ text: "read", tone: "teal" }); + expect(readCopy([text("partial", [0, 1_024])])).toEqual({ text: "read stopped at 1.0 KB", tone: "amber" }); + expect(readCopy([text("partial", [0, 1_024]), text("read", [1_024, 1_843])])!.text).toBe("read"); + }); + test("failures show only when nothing was read, and say what the record knows", () => { + expect(readCopy([pdf("no_text", [1, 3])])!.text).toBe("no text found · may be scanned"); + expect(readCopy([pdf("encrypted")])!.text).toBe("couldn't read: password-protected"); + expect(readCopy([pdf("malformed")])!.text).toBe("couldn't read: damaged file"); + expect(readCopy([pdf("failed")])!.text, "the record has no reason, so none is named").toBe("couldn't read"); + expect(readCopy([pdf("unavailable")])).toEqual({ text: "no reader for this kind of file", tone: "neutral" }); + expect(readCopy([pdf("read", [1, 3]), pdf("failed")])!.text, "an earlier read still stands").toBe("read p. 1–3"); + }); + test("a changed original always shows, even after reads", () => { + expect(readCopy([pdf("read", [1, 12]), pdf("changed")])).toEqual({ text: "original changed since sending", tone: "amber" }); + }); +}); + +describe("attachmentRowProps", () => { + test("without records the row claims neither read nor not read yet", () => { + expect(meta(PERMIT)).toBe("PDF · 2.4 MB · sent"); + expect(meta(SIRENS)).toBe("Binary · 3.1 MB · sent".replace("Binary", attachmentRowProps(SIRENS).meta![0]!.split(" · ")[0]!)); + }); + test("with records, an unread readable file is not read yet and an unreadable one has no reader", () => { + expect(meta(PERMIT, [])).toBe("PDF · 2.4 MB · not read yet"); + expect(meta(CREW, [])).toBe("Text · 1.8 KB · not read yet"); + expect(meta(SIRENS, [])).toBe("3.1 MB · no reader for this kind of file"); + }); + test("a recorded read drives the meta and tone", () => { + const row = attachmentRowProps(PERMIT, [pdf("read", [1, 3])]); + expect(row.meta).toEqual(["PDF · 2.4 MB · read p. 1–3"]); + expect(row.tone).toBe("teal"); + }); + test("an image never reads as not read yet", () => { + expect(meta({ ...PERMIT, kind: "image", reader: "image", mediaType: "image/jpeg" }, [])).toMatch(/ · sent$/); + }); +}); + +describe("reads client", () => { + const SESSION = "odysseus-ithaca"; + const roots: { dispose(): void }[] = []; + afterEach(() => { for (const r of roots.splice(0)) r.dispose(); }); + function rig(answer: (url: string) => Promise) { + const root = createBrainUiRoot({ storage: null }); + roots.push(root); + const chat = root.stores.chat; + const attachmentReads = createAttachmentReadStore(); + const asked: string[] = []; + const client = createAttachmentReadClient({ + stores: { chat, attachmentReads } as never, + apiBase: () => "/api", + request: async (url) => { asked.push(url); return answer(url); }, + }); + const hello = (attachmentReads_: boolean) => client.hello({ type: "server_hello", protocolRev: 5, capabilities: attachmentReads_ ? { attachmentReads: true } : {} } as never); + return { chat, store: attachmentReads, client, asked, hello }; + } + test("a host without the capability is never asked, and rows stay without a claim", async () => { + const r = rig(async () => Response.json({})); + r.chat.getState().setActiveSession(SESSION); + r.hello(false); + await Bun.sleep(0); + expect(r.asked).toEqual([]); + expect(r.store.getState().loaded[SESSION]).toBeUndefined(); + }); + test("the session in view is read once per hello; a frame adds a read once", async () => { + const r = rig(async () => Response.json({ sessionId: SESSION, reads: [pdf("read", [1, 3])] })); + r.chat.getState().setActiveSession(SESSION); + r.hello(true); + await Bun.sleep(0); await Bun.sleep(0); + expect(r.asked).toEqual([`/api/sessions/${SESSION}/attachment-reads`]); + expect(r.store.getState().loaded[SESSION]).toBe(true); + const later = pdf("read", [4, 6]); + r.client.frame({ type: "attachment_read", sessionId: SESSION, read: later }); + r.client.frame({ type: "attachment_read", sessionId: SESSION, read: later }); + expect(r.store.getState().reads[SESSION]![PERMIT.fileId]).toHaveLength(2); + }); + test("an answer from before a new hello is dropped; the new connection asks again", async () => { + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + let n = 0; + const r = rig(async () => { if (n++ === 0) await gate; return Response.json({ sessionId: SESSION, reads: n === 1 ? [pdf("read", [1, 1])] : [] }); }); + r.chat.getState().setActiveSession(SESSION); + r.hello(true); + r.hello(true); + release(); + for (let i = 0; i < 5; i++) await Bun.sleep(0); + expect(r.store.getState().reads[SESSION]?.[PERMIT.fileId]).toBeUndefined(); + }); + test("opening another session reads that one", async () => { + const r = rig(async (url) => Response.json({ sessionId: decodeURIComponent(url.split("/")[3]!), reads: [] })); + r.hello(true); + r.chat.getState().setActiveSession("odysseus-aeolus"); + await Bun.sleep(0); await Bun.sleep(0); + expect(r.asked).toEqual(["/api/sessions/odysseus-aeolus/attachment-reads"]); + expect(r.store.getState().loaded["odysseus-aeolus"]).toBe(true); + }); +}); diff --git a/packages/ui-react/tests/browser/sent-attachments.layout.tsx b/packages/ui-react/tests/browser/sent-attachments.layout.tsx index 3d1782552c..053fc75cb5 100644 --- a/packages/ui-react/tests/browser/sent-attachments.layout.tsx +++ b/packages/ui-react/tests/browser/sent-attachments.layout.tsx @@ -66,3 +66,65 @@ for (const width of [320,1280]) for (const theme of ["dark","light"]) { expect(host.textContent).toContain('1 image');expect(host.querySelectorAll('img,[data-kit-attachment-row]')).toHaveLength(0); }); } + +/** + * Sent composer originals (#3155): each row says what the host recorded the + * agent reading (#3589), from the session's reads route and its live frames. + * The real root, its reads client and MessageBubble; the host is a fixture + * answering the route. No key, no network. + */ +const ORIGINALS = (() => { + const id = (n: number) => `00000000-0000-4000-8000-00000000000${n}`; + const base = (n: number, name: string) => ({ fileId: id(n), name, path: `.brain-ui/attachments/${id(n)}/${name}`, sha256: String(n).repeat(64) }); + return [ + { ...base(1, "ithaca-permit-harbour-fees-and-mooring-rules.pdf"), mediaType: "application/pdf", bytes: 2_516_582, kind: "pdf", reader: "pdf" }, + { ...base(2, "crew-list.txt"), mediaType: "text/plain", bytes: 1_843, kind: "text", reader: "text" }, + { ...base(3, "sirens.m4a"), mediaType: "audio/mp4", bytes: 3_250_000, kind: "binary", reader: "none" }, + { ...base(4, "aeolus-ledger.pdf"), mediaType: "application/pdf", bytes: 655_360, kind: "pdf", reader: "pdf" }, + ] as const; +})(); +for (const width of [320,1280]) for (const theme of ["dark","light"]) { + test(`${theme} ${width}: sent originals show recorded reads, update in place from a frame, and claim nothing before the host answers`, async () => { + outer = await commands.formViewport(width,900); await page.viewport(width,900); document.documentElement.dataset.theme = theme; + const SESSION = "odysseus-ithaca"; + const asked: string[] = []; + let answer!: () => void; + const answered = new Promise((resolve) => { answer = resolve; }); + const at = Date.parse("2026-07-12T06:14:00Z"); + root = createBrainUiRoot({ storage:null, request: async url => { + asked.push(new URL(String(url), "http://fixture.invalid").pathname); + if (!String(url).includes("/attachment-reads")) throw new Error("only the reads route is fixtured"); + await answered; + return Response.json({ sessionId: SESSION, reads: [ + { fileId: ORIGINALS[0].fileId, turnId: "turn-1", outcome: "read", scope: { pages: [1, 3], pageCount: 12 }, at }, + { fileId: ORIGINALS[3].fileId, turnId: "turn-1", outcome: "encrypted", scope: null, at: at + 1 }, + ] }); + } }); + root.stores.chat.getState().setActiveSession(SESSION); + root.connection.handleServerMessage({ type: "server_hello", protocolRev: 5, capabilities: { composerFiles: true, attachmentReads: true } }); + root.connection.handleServerMessage({ type:"session_history",sessionId:SESSION,messages:[{role:"user",content:"Which harbour fees does the permit list?",toolCalls:[],attachmentFiles:[...ORIGINALS]}] }); + host = document.createElement("div"); host.style.cssText=`width:${Math.min(width,720)}px;background:var(--bk-color-canvas);color:var(--bk-color-ink)`; document.body.append(host); renderer=createRoot(host); + flushSync(() => renderer!.render()); + const rows = () => [...host!.querySelectorAll("[data-sent-files] [data-kit-attachment-row]")].map((row) => row.textContent ?? ""); + expect(asked).toEqual([`/api/sessions/${SESSION}/attachment-reads`]); + // Before the host answers, no row claims read or not read yet. + expect(rows()).toHaveLength(4); + for (const row of rows()) expect(row).not.toMatch(/not read yet|\bread\b|couldn't read/); + answer(); + await expect.poll(() => rows()[0]).toContain("PDF · 2.4 MB · read p. 1–3"); + expect(rows()[1]).toContain("Text · 1.8 KB · not read yet"); + expect(rows()[2]).toContain("3.1 MB · no reader for this kind of file"); + expect(rows()[3]).toContain("PDF · 640.0 KB · couldn't read: password-protected"); + // A later turn's read arrives as a frame and updates its row in place. + root.connection.handleServerMessage({ type: "attachment_read", sessionId: SESSION, read: { fileId: ORIGINALS[1].fileId, turnId: "turn-2", outcome: "partial", scope: { bytes: [0, 1_024], totalBytes: 1_843 }, at: at + 2 } }); + await expect.poll(() => rows()[1]).toContain("Text · 1.8 KB · read stopped at 1.0 KB"); + for (const row of host.querySelectorAll("[data-sent-files] [data-kit-attachment-row]")) { + for (const line of row.querySelectorAll("b,span")) expect(line.scrollWidth, "complete label/metadata fits").toBeLessThanOrEqual(line.clientWidth + 1); + } + expect(asked, "one read of the route, no other request").toHaveLength(1); + await expect.poll(()=>getComputedStyle(host!.querySelector('[data-kit-attachment-row]')!.closest('.py-4')!).opacity).toBe("1"); + await commands.formViewport(width,Math.ceil(host.scrollHeight)+32); await page.viewport(width,Math.ceil(host.scrollHeight)+32); + await page.screenshot({element:host,path:`../../.vitest-attachments/sent-attachments/originals-${theme}-${width}.png`}); + }); +} diff --git a/packages/ui-sdk/src/client/ws-client.ts b/packages/ui-sdk/src/client/ws-client.ts index 233bde64e8..2359bf93dd 100644 --- a/packages/ui-sdk/src/client/ws-client.ts +++ b/packages/ui-sdk/src/client/ws-client.ts @@ -26,7 +26,7 @@ * Bun and Node 22+ all provide. State belongs to the consumer; this owns the * socket. */ -import { ACTIVITY_COMPUTE_CAPABILITY, ASK_RECEIPTS_CAPABILITY, FOLLOW_UP_QUEUE_CAPABILITY, SESSION_SAFETY_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV } from "../protocol.js"; +import { ACTIVITY_COMPUTE_CAPABILITY, ASK_RECEIPTS_CAPABILITY, ATTACHMENT_READS_CAPABILITY, FOLLOW_UP_QUEUE_CAPABILITY, SESSION_SAFETY_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV } from "../protocol.js"; import type { ClientMessage, ServerMessage } from "../protocol.js"; import { parseServerMessage } from "../schemas.js"; @@ -252,7 +252,7 @@ export class BrainUiClient { JSON.stringify({ type: "client_hello", protocolRev: PROTOCOL_REV, - capabilities: { [SESSION_SAFETY_CAPABILITY]: true, [ASK_RECEIPTS_CAPABILITY]: true, [FOLLOW_UP_QUEUE_CAPABILITY]: true, toolResolution: true, sessionDialogue: true, [ACTIVITY_COMPUTE_CAPABILITY]: true }, + capabilities: { [SESSION_SAFETY_CAPABILITY]: true, [ASK_RECEIPTS_CAPABILITY]: true, [FOLLOW_UP_QUEUE_CAPABILITY]: true, toolResolution: true, sessionDialogue: true, [ACTIVITY_COMPUTE_CAPABILITY]: true, [ATTACHMENT_READS_CAPABILITY]: true }, }) ); } catch { diff --git a/packages/ui-sdk/tests/ws-client-liveness.test.ts b/packages/ui-sdk/tests/ws-client-liveness.test.ts index b047cdb93a..0512b80210 100644 --- a/packages/ui-sdk/tests/ws-client-liveness.test.ts +++ b/packages/ui-sdk/tests/ws-client-liveness.test.ts @@ -123,7 +123,7 @@ function harness(capabilities: Record = { liveness: true, askRe describe("the client hello", () => { test("declares receipt support", () => { const { sockets, client } = harness(); - expect(sockets[0]!.frames("client_hello")[0].capabilities).toEqual({ askReceipts: true, followUpQueue: true, toolResolution: true, sessionDialogue: true, activityCompute: true, sessionSafetyHistory: true }); + expect(sockets[0]!.frames("client_hello")[0].capabilities).toEqual({ askReceipts: true, followUpQueue: true, toolResolution: true, sessionDialogue: true, activityCompute: true, attachmentReads: true, sessionSafetyHistory: true }); client.close(); }); }); diff --git a/packages/ui-sdk/tests/ws-client.test.ts b/packages/ui-sdk/tests/ws-client.test.ts index 0ad33f5e1e..da6f6dc950 100644 --- a/packages/ui-sdk/tests/ws-client.test.ts +++ b/packages/ui-sdk/tests/ws-client.test.ts @@ -365,7 +365,7 @@ describe("the client hello", () => { protocolRev: PROTOCOL_REV, // Rev 5 (#910): this client reads ask-answer receipts. #1002: and // pending follow-up reports. #3177: retained-dialogue history frames. - capabilities: { sessionSafetyHistory: true, askReceipts: true, followUpQueue: true, toolResolution: true, sessionDialogue: true, activityCompute: true }, + capabilities: { sessionSafetyHistory: true, askReceipts: true, followUpQueue: true, toolResolution: true, sessionDialogue: true, activityCompute: true, attachmentReads: true }, }); }); }); @@ -414,5 +414,5 @@ const legacyHostCapabilities: Record[]=[{}, {multiSession:true}, for(const capabilities of legacyHostCapabilities)test("client dialogue support does not fabricate an old host capability "+JSON.stringify(capabilities),()=>{ const {client,socket}=setup({});socket.deliver({type:"server_hello",protocolRev:PROTOCOL_REV,capabilities}); expect(client.capabilities).toEqual(capabilities); - expect(JSON.parse(socket.sent[0])).toEqual({type:"client_hello",protocolRev:PROTOCOL_REV,capabilities:{sessionSafetyHistory:true,askReceipts:true,followUpQueue:true,toolResolution:true,sessionDialogue:true,activityCompute:true}}); + expect(JSON.parse(socket.sent[0])).toEqual({type:"client_hello",protocolRev:PROTOCOL_REV,capabilities:{sessionSafetyHistory:true,askReceipts:true,followUpQueue:true,toolResolution:true,sessionDialogue:true,activityCompute:true,attachmentReads:true}}); }); diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index f76ca6bc9a..eacaa6c5a3 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -7,11 +7,13 @@ import type {BrowserImporters} from "./bound-browser-runtime-inputs"; // These two consumers import/re-export runStateForFrame only. They never // acquire the mutable chat handler map. Any consumer edit requires re-audit. const helperConsumers:Record={ + // Re-audited for #3155: hello and every other frame also reach the account's + // attachment-reads client beside the trackers; still only runStateForFrame. // Re-audited for #3604: safety frames route to their separate host-evidence // driver before demux; this consumer still imports only runStateForFrame. // Re-audited when #1362 moved inbound routing out of connection.ts: only // runStateForFrame is imported; it never acquires or mutates chatFrameHandlers. - "packages/ui-react/src/ws-client/inbound.ts":"b66c9fc53d5fdf3418f290331d2cdbf4d8a24d4f7767fbcf152a5ccd79041a8d", + "packages/ui-react/src/ws-client/inbound.ts":"b9a95fc0d8bcb82723fd93aa17faa492702dc4bbc747abb4a11d02f41c99e7c5", "packages/ui-react/src/hooks/use-websocket.ts":"6edd8b289fa4dcf7f0a512ce1275bd9e9c70661ce5630e22503b4b1d888cf557" }; // Re-audited for #3155: chat.ts only gained `attachmentFiles` in its history @@ -44,11 +46,12 @@ const declarations=[ "source": "0de9131781f27ba26a4469640e849170b9e063ed1d595a90361ac815128b617f" }, // Re-audited for #3589: the added attachment_read handler is a no-op - // that reads no runtime input, like chat_retired. + // that reads no runtime input, like chat_retired. Re-audited for #3155: + // only its comment changed; the reads client takes the frame instead. { "owner": "packages/ui-react/src/hooks/websocket-handlers/connection.ts", "name": "connectionFrameHandlers", - "source": "847362ebc5510a0dbede9bbbe50cedfdf03346685efe2286238f6be445ece2fe" + "source": "c3a9fa4ce4132cf1d659ee6e59087c82cc980d468e377addae5bbdc0fcadd244" }, { "owner": "packages/ui-react/src/hooks/websocket-handlers/handoff.ts",