Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/composer-sent-file-reads.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions docs/decisions/answer-delivery.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
19 changes: 16 additions & 3 deletions docs/decisions/chat-attachments.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/design-kit/follow-ups.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
9 changes: 9 additions & 0 deletions docs/integration-contract/wire.md
Original file line number Diff line number Diff line change
Expand Up @@ -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".

<a id="explicit-chat-deletion-additive-3230"></a>

### Explicit chat deletion (additive, #3230)
Expand Down
2 changes: 1 addition & 1 deletion docs/process/theme-parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 23 additions & 2 deletions packages/ui-react/src/components/chat/message-bubble.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string, AttachmentReadEntry[]> = {};
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 (
<div className="grid gap-2" data-sent-files="">
{files.map((file) => <AttachmentRow key={file.fileId} {...attachmentRowProps(file, reads ? reads[file.fileId] ?? NO_FILE_READS : undefined)} />)}
</div>
);
}

export const MessageBubble = memo(function MessageBubble({
message,
onToolApproval,
Expand Down Expand Up @@ -148,7 +169,7 @@ export const MessageBubble = memo(function MessageBubble({
{spoken && message.content && <span className="chat-message-body whitespace-pre-wrap">{linkifyPaths(message.content)}</span>}
<UserAttachments message={message} />
{!!message.files?.length && <div className="grid gap-2">{message.files.map(file => <AttachmentRow key={file.path} {...trackRowProps(file)} />)}</div>}
{!!message.attachmentFiles?.length && <div className="grid gap-2" data-sent-files="">{message.attachmentFiles.map(file => <AttachmentRow key={file.fileId} {...attachmentRowProps(file)} />)}</div>}
{!!message.attachmentFiles?.length && <SentFiles files={message.attachmentFiles} />}
{!spoken && message.content && (
<div className="chat-message-body text-sm leading-relaxed text-foreground whitespace-pre-wrap">
{linkifyPaths(message.content)}
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-react/src/hooks/websocket-handlers/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: () => {},
Expand Down
70 changes: 70 additions & 0 deletions packages/ui-react/src/lib/attachment-reads.ts
Original file line number Diff line number Diff line change
@@ -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<BrainUiServices, "stores" | "apiBase" | "request">) {
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<string>();

async function load(sessionId: string): Promise<void> {
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<ServerMessage, { type: "server_hello" }>): 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();
},
};
}
81 changes: 71 additions & 10 deletions packages/ui-react/src/lib/track-attachment.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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: "" };
}
Loading
Loading