From 0ec44c46695a13e3b0edbab2ef10d9b5e8e9962e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 4 Nov 2026 22:59:56 +0100 Subject: [PATCH 1/3] CONTRACT: feat(ui-server): keep up to ten outgoing draft snapshots per chat with 409 DRAFT_OUTGOING_FULL (#3588) (#3593) Replace #3153's single outgoing slot with the G1 A snapshot list. A draft carries `snapshots` of { snapshotId, requestId, text, fileIds, state: held | returned | dispatched, createdAt }. The save that creates one counts every live snapshot of the chat (every live draft bound to the session) in the same immediate transaction and refuses the eleventh with 409 DRAFT_OUTGOING_FULL before any send. Cancel, upload failure, dispatch and a non-acceptance recovery edit in place and never need a slot. Acceptance releases only its own snapshot; only a returned snapshot may be deleted. `Draft.outgoing` and the single-slot write stay, additively, as a view of the newest held or unconfirmed snapshot. Migration 079 moves a saved slot into the list. SessionDraftLimits gains maxOutgoingSnapshots; DELETE that would drop a pending snapshot is 409 DRAFT_OUTGOING_PENDING; the save body bound rises to 4,390,912 bytes; the upload envelope no longer counts files the snapshots own. Refs #3588 Co-authored-by: Claude Opus 5.5 --- .changeset/outgoing-snapshot-list.md | 5 + api-report/ui-sdk.txt | 53 +++- docs/decisions/chat-attachments.md | 39 ++- docs/http-api.md | 65 ++++- docs/integration-contract.md | 14 + docs/integration-contract/wire.md | 15 +- docs/plans/chat-attachments.md | 36 ++- packages/ui-sdk/src/protocol.ts | 76 ++++- packages/ui-sdk/src/schemas.ts | 9 + .../migrations/079_outgoing_snapshots.sql | 18 ++ packages/ui-server/src/attachments/store.ts | 15 +- packages/ui-server/src/drafts/store.ts | 192 +++++++++++-- packages/ui-server/src/routes/drafts.ts | 32 ++- .../ui-server/tests/draft-snapshots.test.ts | 268 ++++++++++++++++++ 14 files changed, 773 insertions(+), 64 deletions(-) create mode 100644 .changeset/outgoing-snapshot-list.md create mode 100644 packages/ui-server/migrations/079_outgoing_snapshots.sql create mode 100644 packages/ui-server/tests/draft-snapshots.test.ts diff --git a/.changeset/outgoing-snapshot-list.md b/.changeset/outgoing-snapshot-list.md new file mode 100644 index 0000000000..6610d12858 --- /dev/null +++ b/.changeset/outgoing-snapshot-list.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- +Keep up to ten outgoing snapshots per chat instead of one (#3588). `Draft.snapshots` and `DraftSaveRequest.snapshots` carry each held, returned or unconfirmed send as `{ snapshotId, requestId, text, fileIds, state, createdAt }`. The save that creates one counts every live snapshot of the chat across its drafts, tabs and devices in the same transaction and refuses the eleventh with `409 DRAFT_OUTGOING_FULL`, before anything is sent; Cancel, an upload failure, dispatch and a recovery read edit a snapshot in place and never need a free slot. Accepting a message releases only its own snapshot, and only a returned snapshot can be deleted, which starts its files' seven-day clock. `SessionDraftLimits` advertises `maxOutgoingSnapshots`, a delete that would drop a held or unconfirmed snapshot is `409 DRAFT_OUTGOING_PENDING`, and the save body bound rises to 4,390,912 bytes. `Draft.outgoing` and the single-slot write keep working, and a slot saved earlier becomes the first snapshot. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 007ef54cf4..e0dc9a4ad6 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -175,6 +175,9 @@ export "." (./src/index.ts) type DraftRef type DraftSaveRequest type DraftSaveResponse + type DraftSnapshot + type DraftSnapshotState + type DraftSnapshotWrite type DraftSummary ENV_VARS FILE_SIZE_CAP_BYTES @@ -722,6 +725,9 @@ export "./client" (./src/client/index.ts) type DraftRef type DraftSaveRequest type DraftSaveResponse + type DraftSnapshot + type DraftSnapshotState + type DraftSnapshotWrite type DraftSummary FILE_SIZE_CAP_BYTES FIRST_PARTY_FAILURE_CLASSES @@ -1545,6 +1551,9 @@ export "./protocol" (./src/protocol.ts) type DraftRef type DraftSaveRequest type DraftSaveResponse + type DraftSnapshot + type DraftSnapshotState + type DraftSnapshotWrite type DraftSummary FILE_SIZE_CAP_BYTES FIRST_PARTY_FAILURE_CLASSES @@ -2311,6 +2320,9 @@ export "./server" (./src/server/index.ts) type DraftRef type DraftSaveRequest type DraftSaveResponse + type DraftSnapshot + type DraftSnapshotState + type DraftSnapshotWrite type DraftSummary EXEC_KILLER_ENV EXEC_WRAPPER_ENV @@ -7129,6 +7141,7 @@ signatures (every public export and the types it is made of) attachments: DraftAttachment[]; files?: AttachmentFile[]; outgoing?: DraftOutgoing | null; + snapshots?: DraftSnapshot[]; } DraftAttachment (packages/ui-sdk/src/protocol.ts) export interface DraftAttachment { @@ -7151,7 +7164,7 @@ signatures (every public export and the types it is made of) revision: number; } DraftErrorCode (packages/ui-sdk/src/protocol.ts) - export type DraftErrorCode = "DRAFT_CONFLICT" | "DRAFT_DELETED" | "DRAFT_TOO_LARGE" | "DRAFT_CAPACITY" | "DRAFT_NOT_FOUND" | "DRAFT_INVALID" | "DRAFT_PRECONDITION_REQUIRED" | "DRAFT_KEY_REUSED" | "DRAFT_NOT_ACCEPTED" | "DRAFT_CHAT_RETIRED"; + export type DraftErrorCode = "DRAFT_CONFLICT" | "DRAFT_DELETED" | "DRAFT_TOO_LARGE" | "DRAFT_CAPACITY" | "DRAFT_NOT_FOUND" | "DRAFT_INVALID" | "DRAFT_PRECONDITION_REQUIRED" | "DRAFT_KEY_REUSED" | "DRAFT_NOT_ACCEPTED" | "DRAFT_CHAT_RETIRED" | "DRAFT_OUTGOING_FULL" | "DRAFT_OUTGOING_PENDING"; DraftErrorResponse (packages/ui-sdk/src/protocol.ts) export type DraftErrorResponse = { error: "DRAFT_CONFLICT"; @@ -7189,6 +7202,14 @@ signatures (every public export and the types it is made of) } | { error: "DRAFT_CHAT_RETIRED"; message: string; + } | { + error: "DRAFT_OUTGOING_FULL"; + message: string; + limit: number; + } | { + error: "DRAFT_OUTGOING_PENDING"; + message: string; + current: Draft; }; DraftListResponse (packages/ui-sdk/src/protocol.ts) export interface DraftListResponse { @@ -7213,12 +7234,26 @@ signatures (every public export and the types it is made of) attachmentIds: string[]; fileIds?: string[]; outgoing?: DraftOutgoing | null; + snapshots?: DraftSnapshotWrite[]; } DraftSaveResponse (packages/ui-sdk/src/protocol.ts) export interface DraftSaveResponse { revision: number; updatedAt: number; } + DraftSnapshot (packages/ui-sdk/src/protocol.ts) + export interface DraftSnapshot { + snapshotId: string; + requestId: string; + text: string; + fileIds: string[]; + state: DraftSnapshotState; + createdAt: number; + } + DraftSnapshotState (packages/ui-sdk/src/protocol.ts) + export type DraftSnapshotState = "held" | "returned" | "dispatched"; + DraftSnapshotWrite (packages/ui-sdk/src/protocol.ts) + export type DraftSnapshotWrite = Omit; DraftSummary (packages/ui-sdk/src/protocol.ts) export interface DraftSummary { draftId: string; @@ -10936,6 +10971,7 @@ signatures (every public export and the types it is made of) maxDraftFiles?: number; maxDraftFileBytes?: number; maxDraftFilesBytes?: number; + maxOutgoingSnapshots?: number; } SessionHistoryMessage (packages/ui-sdk/src/protocol.ts) export interface SessionHistoryMessage { @@ -13559,6 +13595,18 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>>; revision: z.ZodNumber; sessionId: z.ZodNullable; + snapshots: z.ZodOptional; + requestId: z.ZodString; + snapshotId: z.ZodString; + state: z.ZodEnum<{ + dispatched: "dispatched"; + held: "held"; + returned: "returned"; + }>; + text: z.ZodString; + }, z.core.$loose>>>; text: z.ZodString; updatedAt: z.ZodNumber; }, z.core.$loose>; @@ -18607,6 +18655,7 @@ signatures (every public export and the types it is made of) maxDraftFiles: z.ZodOptional; maxDraftFilesBytes: z.ZodOptional; maxDrafts: z.ZodNumber; + maxOutgoingSnapshots: z.ZodOptional; maxTextBytes: z.ZodNumber; maxTotalBytes: z.ZodNumber; }, z.core.$loose>>>; @@ -19287,6 +19336,7 @@ signatures (every public export and the types it is made of) maxDraftFiles: z.ZodOptional; maxDraftFilesBytes: z.ZodOptional; maxDrafts: z.ZodNumber; + maxOutgoingSnapshots: z.ZodOptional; maxTextBytes: z.ZodNumber; maxTotalBytes: z.ZodNumber; }, z.core.$loose>>>; @@ -23309,6 +23359,7 @@ signatures (every public export and the types it is made of) maxDraftFiles: z.ZodOptional; maxDraftFilesBytes: z.ZodOptional; maxDrafts: z.ZodNumber; + maxOutgoingSnapshots: z.ZodOptional; maxTextBytes: z.ZodNumber; maxTotalBytes: z.ZodNumber; }, z.core.$loose>; diff --git a/docs/decisions/chat-attachments.md b/docs/decisions/chat-attachments.md index 2771876efd..cb3f5dea5d 100644 --- a/docs/decisions/chat-attachments.md +++ b/docs/decisions/chat-attachments.md @@ -115,8 +115,10 @@ The server side of admission, storage, ownership and cleanup, as the design's operational database beside the drafts, and every mutation runs on the draft store's write channel. A save, an acceptance and a sweep mark therefore see one serialized state. Reference owners are `draft` and - `outgoing` (both keyed by the draft id; a draft has at most one outgoing - snapshot) and `message` (keyed by the session id). The design's compound + `outgoing` (both keyed by the draft id) and `message` (keyed by the session + id). #3153 shipped one outgoing slot per draft; #3588 replaced it with the + list described below, and the `outgoing` owner now covers every file of the + draft's snapshots. The design's compound owner ids were simplified this way because a draft id may itself contain `:`, and one reference per session protects a file as well as one per turn. - **References on the wire.** A message names its originals in a new optional @@ -149,6 +151,39 @@ The server side of admission, storage, ownership and cleanup, as the design's - **Kept as before.** `/share`, `/track-upload`, staged-track references, inline images and D52's tab-only legacy track path behave as they did. +## What #3588 built + +The G1 A snapshot list +([ruling](https://github.com/schlessera/brain-kit/issues/3155#issuecomment-6591807939)), +replacing #3153's single slot: + +- **A column, not a table.** The list is one JSON column on the draft row + (`outgoing_snapshots`, migration 079), so a save checks and writes it in the + draft's own immediate transaction. Migration 079 turns a saved slot into the + first snapshot, with its request id as its `snapshotId`. The ruling rejected + a send-intent table. +- **A chat is its session.** The capacity count sums the snapshots of every + live draft bound to the same `sessionId`, which is what one chat's tabs and + devices share; a draft with no session is a chat of its own. Only a save + that adds a `snapshotId` is counted against the ten. +- **The whole list on every save.** `snapshots` replaces the draft's list + under `If-Match`, as `PUT` replaces the rest of the draft. The host refuses + any change but an allowed state move or a held snapshot's files, and refuses + to drop anything but a `returned` snapshot. The save body bound rose to + 4,390,912 bytes so ten snapshot texts fit at JSON's worst escapes. +- **Additive compatibility.** Retyping `outgoing` would break readers, so it + stays: `Draft.outgoing` shows the newest held or unconfirmed snapshot in the + old shape, and the old write creates or dispatches the snapshot of its + request, or removes the one it shows. +- **Nothing evicted by a send or a delete.** An acceptance that consumes a + draft still holding other snapshots keeps the row at the next revision with + an empty composer instead of a tombstone. A `DELETE` that would drop a held + or unconfirmed snapshot is `409 DRAFT_OUTGOING_PENDING`. +- **The composer keeps its envelope.** An upload's per-draft count now covers + the current revision and unbound uploads only. A snapshot's files are + checked against the per-message envelope when a save lists it, and stay in + the draft sub-limit and the pool. + ## What #3154 built The shared reader of the design's §7, with these concrete choices: diff --git a/docs/http-api.md b/docs/http-api.md index b669aa35f2..3d738c00e2 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -996,7 +996,8 @@ decoded bytes base64-encoded in `bytes`. **PUT /api/drafts/:draftId** takes `If-Match: ` (`0` creates), `Idempotency-Key` and the JSON body `{ sessionId: string | null, text, -attachmentIds: string[] }`, at most 512 KiB, and answers 200 `{ revision, +attachmentIds: string[] }`, at most 4,390,912 bytes (the composer's text and +ten snapshots' at JSON's six-byte escapes; 512 KiB before #3588), and answers 200 `{ revision, updatedAt }` only after the commit. A save cannot change `sessionId`; that is a conflict. An empty draft is deleted, not saved (400). **POST /api/drafts/:draftId/attachments** takes the raw image as the body, its type @@ -1061,9 +1062,11 @@ second copy. | 409 | `ATTACHMENT_KEY_REUSED` | the key named a different upload | | 503 | `busy` | three composer uploads are already running; retry | -`draftCount` and `draftFiles` count everything the draft's revision and -outgoing snapshot reference, plus uploads for the same draft that no save has -bound yet and that are under an hour old. The pool counts every recorded +`draftCount` and `draftFiles` count everything the draft's current revision +references, plus uploads for the same draft that no save has bound yet and +that are under an hour old. Files its outgoing snapshots own are not counted +(#3588): each snapshot is its own message, checked against the envelope when a +save lists it, and the newer composer revision keeps a whole envelope. The pool counts every recorded original in any state, every live reservation and the legacy draft images. Reservations are taken in one immediate transaction, so concurrent uploads cannot multiply the cap. At capacity nothing is removed to make room. @@ -1078,6 +1081,60 @@ original bytes together (413 `DRAFT_TOO_LARGE`, `bound` `draftCount` or `draftFiles`). The old `maxDraftBytes` ceiling bounds text and legacy images only. `GET` returns `files` (only files still stored) and `outgoing`. + + +#### Outgoing snapshot list (additive, 0.45.0, #3588) + +A draft keeps a list of outgoing snapshots instead of one slot, under the +maintainer's G1 A ruling on #3155. Each `DraftSnapshot` is `{ snapshotId, +requestId, text, fileIds, state: "held" | "returned" | "dispatched", createdAt +}`: a send that is held while its files upload, returned unsent, or dispatched +and not yet confirmed. The client mints `snapshotId`; the host stamps +`createdAt` at creation. `GET` returns them as `snapshots`, oldest first, and +omits the field when there are none. + +`PUT` takes the whole list as `snapshots` (each item without `createdAt`); +absent keeps it. Under the save's `If-Match` and `Idempotency-Key`: + +- **Create.** A `snapshotId` the draft does not hold creates a `held` or + `dispatched` snapshot; its `requestId` must be new to the draft. The save + counts every live snapshot of the chat — every live draft bound to the same + `sessionId`, whichever tab or device saved it, or this draft alone when it + has no session — in the same immediate transaction. If the result would + exceed `maxOutgoingSnapshots` (10, advertised in `SessionDraftLimits`), it + is 409 `{ error: "DRAFT_OUTGOING_FULL", message, limit }` and nothing is + stored. That save is the reservation: the client sends the message only + after it succeeds. An ordinary send with every file ready records a + `dispatched` snapshot the same way. +- **Edit in place.** A listed snapshot may move `held` → `returned` (Cancel, + or a file failed), `held` → `dispatched` (dispatch) or `dispatched` → + `returned` (a recovery read showed it was not accepted). A `held` one may + change its `fileIds` as its uploads are admitted. Its `requestId` and `text` + never change. These saves never need a free slot, even at 10 of 10. +- **Release.** Leaving a `returned` snapshot out deletes it: Edit, when its + text and files move into the composer revision of the same save, or + Delete…. Its files lose their snapshot reference, and those no longer + referenced start their seven-day clock. A `held` or `dispatched` snapshot + cannot be left out (400 `DRAFT_INVALID`); nothing is evicted, merged or + overwritten. Accepting the message whose `requestId` a snapshot carries + releases that snapshot alone, its files moving to the conversation in the + acceptance transaction. + +Every snapshot's files stay referenced, charged to the draft sub-limit and the +pool, and each snapshot is checked against the per-message envelope. When an +acceptance consumes a draft that still holds other snapshots, the draft is not +a tombstone: it stays at the next revision with an empty composer and those +snapshots. `DELETE` of a draft holding a `held` or `dispatched` snapshot is +409 `{ error: "DRAFT_OUTGOING_PENDING", message, current }`; its `returned` +snapshots go with it. + +The single-slot fields of #3153 keep working. `Draft.outgoing` shows the +newest `held` or `dispatched` snapshot in the old shape. A save's `outgoing` +object creates the snapshot of its `requestId` (with that id as `snapshotId`) +or edits it in place, and `null` removes the snapshot `outgoing` shows. A save +naming both `outgoing` and `snapshots` is 400. A draft saved with a slot +before migration 079 has that slot as its first snapshot. + ### `GET /api/attachments/:fileId` Streams one original up to 25,000,000 bytes, after checking its recorded size diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 316f887a14..4906ef3b32 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -75,6 +75,20 @@ directs. The new environment input is `BRAIN_UI_ATTACHMENT_POOL_BYTES`. See [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). +## Outgoing snapshot list (additive, 0.45.0, #3588) + +A draft keeps up to 10 outgoing snapshots per chat instead of #3153's one +slot: `Draft.snapshots?` and `DraftSaveRequest.snapshots?`, each snapshot +`{ snapshotId, requestId, text, fileIds, state: "held" | "returned" | +"dispatched", createdAt }`, and `SessionDraftLimits.maxOutgoingSnapshots`. +The save that creates one is refused with the new 409 `DRAFT_OUTGOING_FULL` +when the chat is full; a delete that would drop a held or unconfirmed one is +the new 409 `DRAFT_OUTGOING_PENDING`. `Draft.outgoing` and the single-slot +write keep their shape and meaning for one held or unconfirmed send. The save +body bound rises from 512 KiB to 4,390,912 bytes to carry ten snapshot texts. +See [the wire component](integration-contract/wire.md#composer-file-attachments-additive-0450-3153) +and [the HTTP API](http-api.md#outgoing-snapshot-list-additive-0450-3588). + ## Reading composer attachments on demand (additive, 0.45.0, #3154) Both first-party backends gain one host-executed bridge tool, `read_attachment` diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 12130c7fd6..02c9b19b42 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -1945,13 +1945,26 @@ D52's tab-only track path. `DraftSaveRequest` gains `fileIds?` and `outgoing?`, `Draft` gains `files?` and `outgoing?`, and `DraftSummary` gains `fileCount?`. The routes are in the [HTTP API](../http-api.md#composer-file-attachments-additive-0450-3153). +- **Outgoing snapshot list (additive, #3588).** `Draft.snapshots?` and + `DraftSaveRequest.snapshots?` carry up to 10 `DraftSnapshot`s per chat, + each `{ snapshotId, requestId, text, fileIds, state: "held" | "returned" | + "dispatched", createdAt }`. The save that creates one counts the chat's + live snapshots across its drafts, tabs and devices and is refused with 409 + `DRAFT_OUTGOING_FULL` at `SessionDraftLimits.maxOutgoingSnapshots` (10) + before any send; state changes edit a snapshot in place and are never + refused for capacity. Acceptance releases only the snapshot of its + `requestId`. `Draft.outgoing` keeps its shape and shows the newest held or + unconfirmed snapshot; the single-slot write still works. `DELETE` of a draft + holding a held or unconfirmed snapshot is 409 `DRAFT_OUTGOING_PENDING`. The + rules are in the [HTTP API](../http-api.md#outgoing-snapshot-list-additive-0450-3588). The SDK publishes `COMPOSER_FILES_CAPABILITY`, `ATTACHMENT_DIR`, `ATTACHMENT_MAX_FILES`, `ATTACHMENT_MAX_FILE_BYTES`, `ATTACHMENT_MAX_TOTAL_BYTES`, `ATTACHMENT_POOL_DEFAULT_BYTES`, `ATTACHMENT_UNBOUND_TTL_MS`, `ATTACHMENT_GRACE_MS`, the `ChatAttachmentReference`, `AttachmentKind`, `AttachmentReader`, -`AttachmentFile`, `AttachmentLimits`, `DraftOutgoing`, `AttachmentErrorCode` +`AttachmentFile`, `AttachmentLimits`, `DraftOutgoing`, `DraftSnapshot`, +`DraftSnapshotState`, `DraftSnapshotWrite`, `AttachmentErrorCode` and `AttachmentErrorResponse` types, and `attachmentFileSchema` and `attachmentLimitsSchema`. The governance `taint` event's `source` gains `chat_attachment`: reading under `.brain-ui/attachments/` taints the session diff --git a/docs/plans/chat-attachments.md b/docs/plans/chat-attachments.md index 4b4cd097c0..c585fd3373 100644 --- a/docs/plans/chat-attachments.md +++ b/docs/plans/chat-attachments.md @@ -312,7 +312,7 @@ attachment_files(file_id PK, draft_id, sha256, bytes, stored_name, incoming_name state: stored | deleting | missing attachment_refs(file_id, owner, owner_id, created_at) PK(file_id, owner, owner_id) owner: draft (owner_id = draftId; the current revision's binding) - outgoing(owner_id = draftId; the draft's one held or unconfirmed snapshot) + outgoing(owner_id = draftId; every file the draft's outgoing snapshots own) message (owner_id = sessionId; an accepted send) attachment_reservations(reservation_id PK, bytes, instance_id, created_at) attachment_reads(file_id, session_id, turn_id, outcome, scope_json, at) -- UI evidence only @@ -340,20 +340,34 @@ attachment_reads(file_id, session_id, turn_id, outcome, scope_json, at) -- UI `Draft` returns `files: AttachmentFile[]`. `saved` therefore covers the exact text, images and file bindings, as D52 requires. -**Outgoing snapshot.** `DraftSaveRequest` gains `outgoing?: { requestId; text; -fileIds; state: "held" | "dispatched" } | null`. There is at most one per -draft. The client writes it in the same save that clears the composer when -Send creates a held snapshot (#3155 D1), and keeps it while a send is -unconfirmed. It is the durable owner of that snapshot's files, so newer -revisions cannot orphan them. It survives reload, and a restored `held` -snapshot never sends on its own (#3155 correction 2). The client clears it on -Cancel, on Edit, or when Check proves the message was not accepted and the user -discards it. +**Outgoing snapshots.** Under the maintainer's G1 A ruling on #3155, a draft +keeps a list of snapshots rather than one slot (#3588). `Draft.snapshots?` and +`DraftSaveRequest.snapshots?` carry `{ snapshotId; requestId; text; fileIds; +state: "held" | "returned" | "dispatched"; createdAt }`, at most 10 per chat +across its drafts, tabs and devices (`SessionDraftLimits.maxOutgoingSnapshots`). +The save that **creates** a snapshot counts every live snapshot of the chat in +the same immediate transaction and refuses the eleventh with `409 +DRAFT_OUTGOING_FULL` before any send effect; that save is the reservation. The +client writes it in the same save that clears the composer when Send creates a +held snapshot (#3155 D1), and an ordinary all-ready send records a +`dispatched` one the same way. Cancel and upload failure (held → returned), +dispatch (held → dispatched) and a recovery read showing non-acceptance +(dispatched → returned) edit a snapshot in place and never need a free slot; a +held snapshot's files may grow as its uploads are admitted. A snapshot is +released only on confirmed acceptance, Edit into the composer revision or +Delete… of a `returned` one; nothing is evicted, merged or overwritten. Each +snapshot owns its files, so newer revisions cannot orphan them. It survives +reload, and a restored `held` snapshot never sends on its own (#3155 +correction 2). #3153's single `outgoing?` field stays as a view of the newest +held or unconfirmed snapshot, and its write still creates or dispatches the +snapshot of its `requestId`; the +[HTTP API](../http-api.md#outgoing-snapshot-list-additive-0450-3588) has the +rules. **Message.** On acceptance, the same transaction that settles the draft: 1. inserts `message` refs for the files the message named; -2. clears the outgoing snapshot whose `requestId` matches; +2. releases only the outgoing snapshot whose `requestId` matches; 3. consumes the draft revision under the existing rules. The `message` ref is written before the draft ref goes. That is how "unresolved diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index ef0df300ea..979ad0c9fd 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -499,6 +499,12 @@ export interface SessionDraftLimits { maxDraftFileBytes?: number; /** Most original bytes of one draft's or message's attachments together, images included (additive; #3153). */ maxDraftFilesBytes?: number; + /** + * Most live outgoing snapshots one chat keeps, across its drafts, tabs and + * devices (additive; #3588). Only a save that creates a snapshot is refused + * at this count, with `409 DRAFT_OUTGOING_FULL`. + */ + maxOutgoingSnapshots?: number; } /** The limits a host ships with (the #943 R2 ruling). */ @@ -510,6 +516,7 @@ export const SESSION_DRAFT_LIMITS: Readonly = Object.freeze( maxDraftFiles: 10, maxDraftFileBytes: 25_000_000, maxDraftFilesBytes: 50_000_000, + maxOutgoingSnapshots: 10, }); /** Names one saved revision of one draft. */ @@ -557,14 +564,24 @@ export interface Draft { attachments: DraftAttachment[]; /** File originals the saved revision binds, in its order (additive; #3153). */ files?: AttachmentFile[]; - /** The held or unconfirmed send of this draft, if one is saved (additive; #3153). */ + /** + * The newest `held` or `dispatched` snapshot of {@link Draft.snapshots}, in + * the single-slot shape #3153 shipped (additive; #3153). Absent when no + * snapshot is held or unconfirmed. Read `snapshots` for the whole list. + */ outgoing?: DraftOutgoing | null; + /** + * This draft's outgoing snapshots, oldest first (additive; #3588). Each is + * a send that is held, returned unsent or not yet confirmed, and owns its + * files. Absent when there are none. + */ + snapshots?: DraftSnapshot[]; } /** - * A draft's one durable outgoing snapshot (#3153): the exact text and files of - * a send that is held or not yet confirmed. It owns its files, so newer - * revisions cannot orphan them. A restored `held` snapshot never sends itself. + * The single-slot view of an outgoing snapshot (#3153), kept for clients that + * read and write `Draft.outgoing`. A restored `held` snapshot never sends + * itself. */ export interface DraftOutgoing { requestId: string; @@ -573,6 +590,30 @@ export interface DraftOutgoing { state: "held" | "dispatched"; } +/** Where an outgoing snapshot stands (#3588). */ +export type DraftSnapshotState = "held" | "returned" | "dispatched"; + +/** + * One durable outgoing snapshot (#3588): the exact text and files of one send + * that is held, returned unsent, or dispatched and not yet confirmed. It owns + * its files, so newer revisions cannot orphan them. A chat keeps at most + * `SessionDraftLimits.maxOutgoingSnapshots` of them across its drafts. + */ +export interface DraftSnapshot { + /** Client-minted; addresses the snapshot in every later save. */ + snapshotId: string; + /** The `chat_message.requestId` this snapshot sends, or sent, as. */ + requestId: string; + text: string; + fileIds: string[]; + state: DraftSnapshotState; + /** Host milliseconds since epoch of the save that created it. */ + createdAt: number; +} + +/** A snapshot as a save names it: the host stamps `createdAt`. */ +export type DraftSnapshotWrite = Omit; + export interface DraftListResponse { /** Every live draft, newest change first; bounded by `maxDrafts`. */ drafts: DraftSummary[]; @@ -590,8 +631,23 @@ export interface DraftSaveRequest { * keeps none. */ fileIds?: string[]; - /** Set (object), clear (null) or keep (absent) the outgoing snapshot (additive; #3153). */ + /** + * The single-slot write (additive; #3153): an object creates the snapshot + * of its `requestId`, or moves it from `held` to `dispatched`; null removes + * the snapshot `Draft.outgoing` shows. Absent keeps every snapshot. Not + * combined with `snapshots`. + */ outgoing?: DraftOutgoing | null; + /** + * The draft's whole snapshot list, oldest first (additive; #3588). Absent + * keeps it. A new `snapshotId` creates a `held` or `dispatched` snapshot + * and is refused with `409 DRAFT_OUTGOING_FULL` when its chat already holds + * `maxOutgoingSnapshots`. A listed one may move `held` to `returned` or + * `dispatched`, or `dispatched` to `returned`, and a `held` one may change + * its `fileIds`; nothing else of it changes. Only a `returned` snapshot may + * be left out, which deletes it. + */ + snapshots?: DraftSnapshotWrite[]; } export interface DraftSaveResponse { @@ -626,7 +682,9 @@ export type DraftErrorCode = | "DRAFT_PRECONDITION_REQUIRED" | "DRAFT_KEY_REUSED" | "DRAFT_NOT_ACCEPTED" - | "DRAFT_CHAT_RETIRED"; + | "DRAFT_CHAT_RETIRED" + | "DRAFT_OUTGOING_FULL" + | "DRAFT_OUTGOING_PENDING"; /** A draft route's failure body, discriminated by `error`. */ export type DraftErrorResponse = @@ -647,7 +705,11 @@ export type DraftErrorResponse = /** 409: no accepted message of that session carried this draft and request. */ | { error: "DRAFT_NOT_ACCEPTED"; message: string } /** 410 (additive, #3230): the draft's chat was deleted. Nothing was stored; save the local content as a new, unbound draft. */ - | { error: "DRAFT_CHAT_RETIRED"; message: string }; + | { error: "DRAFT_CHAT_RETIRED"; message: string } + /** 409 (additive, #3588): the chat already keeps `limit` outgoing snapshots. Nothing was stored; no send happened. */ + | { error: "DRAFT_OUTGOING_FULL"; message: string; limit: number } + /** 409 (additive, #3588): a delete would drop a `held` or `dispatched` snapshot. Nothing was removed. */ + | { error: "DRAFT_OUTGOING_PENDING"; message: string; current: Draft }; // ============================================================ // Session recovery (additive; #964, design D52 §4 and §6) diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index fe9135e05e..f571069a77 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1175,6 +1175,7 @@ export const sessionDraftLimitsSchema = z.looseObject({ maxDraftFiles: byteCount.optional(), maxDraftFileBytes: byteCount.optional(), maxDraftFilesBytes: byteCount.optional(), + maxOutgoingSnapshots: byteCount.optional(), }) satisfies z.ZodType; export const attachmentLimitsSchema = z.looseObject({ @@ -1235,6 +1236,14 @@ export const draftSchema = z.looseObject({ fileIds: z.array(z.string().regex(/^[a-f0-9-]{36}$/)).max(10), state: z.enum(["held", "dispatched"]), }).nullable().optional(), + snapshots: z.array(z.looseObject({ + snapshotId: id, + requestId: id, + text: z.string(), + fileIds: z.array(z.string().regex(/^[a-f0-9-]{36}$/)).max(10), + state: z.enum(["held", "returned", "dispatched"]), + createdAt: byteCount, + })).max(SESSION_DRAFT_LIMITS.maxOutgoingSnapshots ?? 10).optional(), }) satisfies z.ZodType; export const draftSaveResponseSchema = z.looseObject({ diff --git a/packages/ui-server/migrations/079_outgoing_snapshots.sql b/packages/ui-server/migrations/079_outgoing_snapshots.sql new file mode 100644 index 0000000000..1366467e4f --- /dev/null +++ b/packages/ui-server/migrations/079_outgoing_snapshots.sql @@ -0,0 +1,18 @@ +-- A draft keeps a list of outgoing snapshots instead of one slot (#3588, the +-- #3155 G1 A ruling): each is a held, returned or unconfirmed send with its +-- own id, text and files. A chat keeps at most ten of them across its drafts. +-- JSON array of DraftSnapshot, oldest first. +ALTER TABLE session_drafts ADD COLUMN outgoing_snapshots TEXT NOT NULL DEFAULT '[]'; + +-- The one slot a draft saved before becomes the first snapshot of its list. +-- Its id is its request id, which is how the single-slot write addresses it. +UPDATE session_drafts SET outgoing_snapshots = json_array(json_object( + 'snapshotId', json_extract(outgoing_json, '$.requestId'), + 'requestId', json_extract(outgoing_json, '$.requestId'), + 'text', json_extract(outgoing_json, '$.text'), + 'fileIds', json(json_extract(outgoing_json, '$.fileIds')), + 'state', json_extract(outgoing_json, '$.state'), + 'createdAt', updated_at)) + WHERE outgoing_json IS NOT NULL AND deleted_at IS NULL; + +ALTER TABLE session_drafts DROP COLUMN outgoing_json; diff --git a/packages/ui-server/src/attachments/store.ts b/packages/ui-server/src/attachments/store.ts index 3bfe79214f..42bf30e377 100644 --- a/packages/ui-server/src/attachments/store.ts +++ b/packages/ui-server/src/attachments/store.ts @@ -17,8 +17,8 @@ import type { AttachmentReadOutcome, AttachmentReadResult } from "@schlessera/br * acceptance and a sweep mark see one serialized state. * * Reference owners: `draft` (owner_id = draft id, the current revision's - * binding), `outgoing` (owner_id = draft id; a draft keeps at most one - * outgoing snapshot) and `message` (owner_id = session id). + * binding), `outgoing` (owner_id = draft id; every file any of the draft's + * outgoing snapshots owns) and `message` (owner_id = session id). */ export type AttachmentOwner = "draft" | "outgoing" | "message"; @@ -126,15 +126,18 @@ export function addRef(db: Database, fileId: string, owner: AttachmentOwner, own /** * The files counted against one draft's envelope at upload: everything its - * revision or outgoing snapshot references, plus uploads for it that no save - * has bound yet and that are still inside their one-hour window. So a burst - * of uploads cannot exceed the envelope before a save names them. + * current revision references, plus uploads for it that no save has bound yet + * and that are still inside their one-hour window. So a burst of uploads + * cannot exceed the envelope before a save names them. Files its outgoing + * snapshots own are not counted: each snapshot is its own message, checked + * against the envelope when a save lists it, and the newer composer revision + * keeps a whole envelope of its own (#3588). */ export function draftEnvelope(db: Database, draftId: string, at: number): { count: number; bytes: number } { const row = db.query( `SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b FROM attachment_files f WHERE f.draft_id = ?1 AND f.state = 'stored' AND ( - EXISTS (SELECT 1 FROM attachment_refs r WHERE r.file_id = f.file_id AND r.owner IN ('draft', 'outgoing') AND r.owner_id = ?1) + EXISTS (SELECT 1 FROM attachment_refs r WHERE r.file_id = f.file_id AND r.owner = 'draft' AND r.owner_id = ?1) OR (f.ever_referenced = 0 AND f.created_at >= ?2 AND NOT EXISTS (SELECT 1 FROM attachment_refs r WHERE r.file_id = f.file_id)))` ).get(draftId, at - ATTACHMENT_UNBOUND_TTL_MS) as { n: number; b: number }; diff --git a/packages/ui-server/src/drafts/store.ts b/packages/ui-server/src/drafts/store.ts index 3fd5cf1abc..354c72b6fe 100644 --- a/packages/ui-server/src/drafts/store.ts +++ b/packages/ui-server/src/drafts/store.ts @@ -9,6 +9,8 @@ import { type AttachmentErrorResponse, type AttachmentFile, type DraftOutgoing, + type DraftSnapshot, + type DraftSnapshotWrite, DRAFT_PREVIEW_CHARS, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, @@ -89,8 +91,10 @@ interface SaveDraftInput { attachmentIds: string[]; /** File originals this revision binds (#3153). Absent binds none. */ fileIds?: string[]; - /** Set, clear (null) or keep (absent) the outgoing snapshot (#3153). */ + /** The single-slot write (#3153): create or dispatch its snapshot, or remove the one `outgoing` shows (null). */ outgoing?: DraftOutgoing | null; + /** The whole outgoing snapshot list (#3588). Absent keeps it. Not combined with `outgoing`. */ + snapshots?: DraftSnapshotWrite[]; } interface ReserveAttachmentInput { @@ -197,7 +201,7 @@ interface DraftRow { text: string; attachment_ids: string; file_ids: string; - outgoing_json: string | null; + outgoing_snapshots: string; updated_at: number; deleted_at: number | null; } @@ -286,8 +290,9 @@ export function createDraftStore( const maxFileBytes = limits.maxDraftFileBytes ?? ATTACHMENT_MAX_FILE_BYTES; const maxFilesBytes = limits.maxDraftFilesBytes ?? ATTACHMENT_MAX_TOTAL_BYTES; + const maxSnapshots = limits.maxOutgoingSnapshots ?? SESSION_DRAFT_LIMITS.maxOutgoingSnapshots ?? 10; const selectDraft = db.prepare( - "SELECT draft_id, session_id, revision, text, attachment_ids, file_ids, outgoing_json, updated_at, deleted_at FROM session_drafts WHERE draft_id = ?" + "SELECT draft_id, session_id, revision, text, attachment_ids, file_ids, outgoing_snapshots, updated_at, deleted_at FROM session_drafts WHERE draft_id = ?" ); const selectAttachments = db.prepare( "SELECT attachment_id, mime, name, bytes, size_bytes, attached FROM session_draft_attachments WHERE draft_id = ?" @@ -317,8 +322,94 @@ export function createDraftStore( return JSON.parse(row.file_ids) as string[]; } - function outgoingOf(row: DraftRow): DraftOutgoing | null { - return row.outgoing_json ? JSON.parse(row.outgoing_json) as DraftOutgoing : null; + function snapshotsOf(row: DraftRow): DraftSnapshot[] { + return JSON.parse(row.outgoing_snapshots) as DraftSnapshot[]; + } + + /** The single-slot view: the newest snapshot still held or unconfirmed. */ + function legacyOutgoing(snapshots: readonly DraftSnapshot[]): DraftSnapshot | null { + for (let i = snapshots.length - 1; i >= 0; i--) if (snapshots[i]!.state !== "returned") return snapshots[i]!; + return null; + } + + /** Every file a draft's snapshots own, once each. */ + function snapshotFiles(snapshots: readonly DraftSnapshotWrite[]): string[] { + return [...new Set(snapshots.flatMap((s) => s.fileIds))]; + } + + /** + * Live snapshots of the chat a draft belongs to, outside that draft: every + * other live draft bound to the same session, whichever tab or device saved + * it. A draft with no session yet is a chat of its own. + */ + function otherChatSnapshots(draftId: string, sessionId: string | null): number { + if (sessionId === null) return 0; + const row = db.query( + "SELECT COALESCE(SUM(json_array_length(outgoing_snapshots)), 0) AS n FROM session_drafts WHERE session_id = ? AND draft_id != ? AND deleted_at IS NULL" + ).get(sessionId, draftId) as { n: number }; + return row.n; + } + + function outgoingInvalid(message: string): DraftError { + return invalid(message); + } + + /** + * The list a save leaves, from the stored list and what the request names. + * Edits happen in place and never need a free slot; `created` lists the new + * snapshots, which the caller counts against the chat's capacity. + */ + function nextSnapshots(stored: readonly DraftSnapshot[], input: SaveDraftInput, at: number): { list: DraftSnapshot[]; created: DraftSnapshot[] } { + if (input.snapshots !== undefined && input.outgoing !== undefined) throw outgoingInvalid("Send either outgoing or snapshots, not both."); + if (input.snapshots === undefined && input.outgoing === undefined) return { list: [...stored], created: [] }; + const byId = new Map(stored.map((s) => [s.snapshotId, s])); + if (input.outgoing === null) { + // The single-slot clear removes the snapshot that slot shows, as #3153 did. + const shown = legacyOutgoing(stored); + return { list: stored.filter((s) => s !== shown), created: [] }; + } + const writes: DraftSnapshotWrite[] = input.outgoing !== undefined + ? (() => { + // The single-slot write addresses the snapshot of its request. + const o = input.outgoing; + const existing = stored.find((s) => s.requestId === o.requestId); + const write = { snapshotId: existing?.snapshotId ?? o.requestId, requestId: o.requestId, text: o.text, fileIds: o.fileIds, state: o.state }; + return existing ? stored.map((s) => (s === existing ? write : s)) : [...stored, write]; + })() + : input.snapshots!; + const seen = new Set(); + const requests = new Set(); + const list: DraftSnapshot[] = []; + const created: DraftSnapshot[] = []; + for (const write of writes) { + if (seen.has(write.snapshotId)) throw outgoingInvalid("A snapshot is listed twice."); + if (requests.has(write.requestId)) throw outgoingInvalid("Two snapshots name the same requestId."); + seen.add(write.snapshotId); requests.add(write.requestId); + const prior = byId.get(write.snapshotId); + if (!prior) { + if (write.state === "returned") throw outgoingInvalid("A new snapshot is held or dispatched."); + if (stored.some((s) => s.requestId === write.requestId)) throw outgoingInvalid("Another snapshot already sends this requestId."); + const snapshot = { ...write, fileIds: [...write.fileIds], createdAt: at }; + list.push(snapshot); created.push(snapshot); + continue; + } + // Nothing of a snapshot changes but its state, and a held one's files. + if (write.requestId !== prior.requestId || write.text !== prior.text) throw outgoingInvalid("A snapshot's text and requestId do not change."); + const sameFiles = write.fileIds.length === prior.fileIds.length && write.fileIds.every((id, i) => id === prior.fileIds[i]); + if (!sameFiles && prior.state !== "held") throw outgoingInvalid("Only a held snapshot's files change."); + const allowed = write.state === prior.state + || (prior.state === "held" && (write.state === "returned" || write.state === "dispatched")) + || (prior.state === "dispatched" && write.state === "returned"); + if (!allowed) throw outgoingInvalid(`A ${prior.state} snapshot cannot become ${write.state}.`); + list.push({ ...prior, fileIds: [...write.fileIds], state: write.state }); + } + // Leaving a snapshot out deletes it, which only a returned one may be. + for (const prior of stored) { + if (!seen.has(prior.snapshotId) && prior.state !== "returned") { + throw outgoingInvalid(`A ${prior.state} snapshot is not deleted; return it first.`); + } + } + return { list, created }; } function toDraft(row: DraftRow): Draft { @@ -326,12 +417,17 @@ export function createDraftStore( (selectAttachments.all(row.draft_id) as AttachmentRow[]).map((a) => [a.attachment_id, a]) ); const fileIds = fileIdsOf(row); - const outgoing = outgoingOf(row); + const snapshots = snapshotsOf(row); + const shown = legacyOutgoing(snapshots); + const outgoing: DraftOutgoing | null = shown + ? { requestId: shown.requestId, text: shown.text, fileIds: shown.fileIds, state: shown.state as DraftOutgoing["state"] } + : null; const files = readAttachments(db, fileIds); return { // Only files the revision still binds and that exist: a saved claim is never invented. ...(fileIds.length ? { files: fileIds.flatMap((id) => { const f = files.get(id); return f && f.state === "stored" ? [toAttachmentFile(f)] : []; }) } : {}), ...(outgoing ? { outgoing } : {}), + ...(snapshots.length ? { snapshots } : {}), draftId: row.draft_id, sessionId: row.session_id, revision: row.revision, @@ -443,7 +539,7 @@ export function createDraftStore( // acceptance keeps protecting what was sent. setRefs(db, "draft", row.draft_id, [], at); setRefs(db, "outgoing", row.draft_id, [], at); - db.prepare("UPDATE session_drafts SET file_ids = '[]', outgoing_json = NULL WHERE draft_id = ?").run(row.draft_id); + db.prepare("UPDATE session_drafts SET file_ids = '[]', outgoing_snapshots = '[]' WHERE draft_id = ?").run(row.draft_id); } return { @@ -454,7 +550,7 @@ export function createDraftStore( return db.transaction(() => { authorize(principalId); const rows = db.query( - `SELECT draft_id, session_id, revision, text, attachment_ids, file_ids, outgoing_json, updated_at, deleted_at FROM session_drafts + `SELECT draft_id, session_id, revision, text, attachment_ids, file_ids, outgoing_snapshots, updated_at, deleted_at FROM session_drafts WHERE deleted_at IS NULL AND (session_id IS NULL OR session_id NOT IN (SELECT id FROM chat_retired_identities WHERE kind = 'session')) ORDER BY updated_at DESC, draft_id ASC LIMIT ?` ).all(limits.maxDrafts) as DraftRow[]; @@ -490,9 +586,11 @@ export function createDraftStore( const fileIds = input.fileIds ?? []; // Older requests keep their exact fingerprint; file fields join it only when sent. const fingerprint = sha256("save", String(input.ifMatch), JSON.stringify( - input.fileIds === undefined && input.outgoing === undefined + input.fileIds === undefined && input.outgoing === undefined && input.snapshots === undefined ? [input.sessionId, input.text, input.attachmentIds] - : [input.sessionId, input.text, input.attachmentIds, fileIds, input.outgoing ?? null, input.outgoing === undefined])); + : input.snapshots === undefined + ? [input.sessionId, input.text, input.attachmentIds, fileIds, input.outgoing ?? null, input.outgoing === undefined] + : [input.sessionId, input.text, input.attachmentIds, fileIds, "snapshots", input.snapshots])); const replay = receipt(draftId, "save", input.idempotencyKey, fingerprint); if (replay !== undefined) return replay as DraftSaveResponse; @@ -503,8 +601,8 @@ export function createDraftStore( // Binding is its own proven operation; a save cannot move a draft. if (row && input.sessionId !== row.session_id) throw conflict(row); - const outgoing = input.outgoing === undefined ? (row ? outgoingOf(row) : null) : input.outgoing; - if (input.text.length === 0 && input.attachmentIds.length === 0 && fileIds.length === 0 && !outgoing) { + const { list: snapshots, created } = nextSnapshots(row ? snapshotsOf(row) : [], input, at); + if (input.text.length === 0 && input.attachmentIds.length === 0 && fileIds.length === 0 && snapshots.length === 0) { throw invalid("An empty draft is deleted, not saved."); } const textBytes = utf8Bytes(input.text); @@ -532,11 +630,25 @@ export function createDraftStore( } // File originals have their own envelope; the old draft ceiling bounds only text and inline images. checkFiles(draftId, fileIds, input.attachmentIds.length, imageBytes); - if (outgoing && input.outgoing !== undefined) { - if (utf8Bytes(outgoing.text) > limits.maxTextBytes) { + // Each snapshot is its own message: new ones, and a held one whose files changed, meet its envelope. + const priorSnapshots = new Map((row ? snapshotsOf(row) : []).map((s) => [s.snapshotId, s])); + for (const snapshot of snapshots) { + const prior = priorSnapshots.get(snapshot.snapshotId); + if (prior && prior.fileIds.join() === snapshot.fileIds.join()) continue; + if (!prior && utf8Bytes(snapshot.text) > limits.maxTextBytes) { throw new DraftError(413, { error: "DRAFT_TOO_LARGE", message: "Draft text is too large.", limit: limits.maxTextBytes, bound: "text" }); } - checkFiles(draftId, outgoing.fileIds, 0, 0); + checkFiles(draftId, snapshot.fileIds, 0, 0); + } + // The save that creates a snapshot is its reservation: it counts every + // live snapshot of the chat, across drafts, tabs and devices, inside + // this immediate transaction. Edits in place are never refused here. + if (created.length > 0 && otherChatSnapshots(draftId, input.sessionId) + snapshots.length > maxSnapshots) { + throw new DraftError(409, { + error: "DRAFT_OUTGOING_FULL", + message: `${maxSnapshots} messages in this chat are waiting or need recovery. Nothing was sent.`, + limit: maxSnapshots, + }); } if (!row) { const live = (db.query("SELECT COUNT(*) AS n FROM session_drafts WHERE deleted_at IS NULL").get() as { n: number }).n; @@ -555,7 +667,7 @@ export function createDraftStore( // Files are charged to the draft sub-limit once, by whichever live // draft or snapshot references them; only newly bound ones grow it. const growth = textBytes - previousTextBytes - droppedBytes - + newlyReferencedBytes([...fileIds, ...(outgoing?.fileIds ?? [])], draftId); + + newlyReferencedBytes([...fileIds, ...snapshotFiles(snapshots)], draftId); if (growth > 0 && totalBytes() + growth > limits.maxTotalBytes) { throw new DraftError(507, { error: "DRAFT_CAPACITY", message: "This host's draft storage is full.", limit: limits.maxTotalBytes, bound: "total" }); } @@ -564,19 +676,21 @@ export function createDraftStore( const ids = JSON.stringify(input.attachmentIds); if (row) { db.prepare( - "UPDATE session_drafts SET revision = ?, text = ?, attachment_ids = ?, file_ids = ?, outgoing_json = ?, size_bytes = ?, updated_at = ?, updated_by = ? WHERE draft_id = ?" - ).run(revision, input.text, ids, JSON.stringify(fileIds), outgoing ? JSON.stringify(outgoing) : null, textBytes + imageBytes, at, principalId, draftId); + "UPDATE session_drafts SET revision = ?, text = ?, attachment_ids = ?, file_ids = ?, outgoing_snapshots = ?, size_bytes = ?, updated_at = ?, updated_by = ? WHERE draft_id = ?" + ).run(revision, input.text, ids, JSON.stringify(fileIds), JSON.stringify(snapshots), textBytes + imageBytes, at, principalId, draftId); } else { db.prepare( - `INSERT INTO session_drafts (draft_id, session_id, revision, text, attachment_ids, file_ids, outgoing_json, size_bytes, created_at, created_by, updated_at, updated_by) + `INSERT INTO session_drafts (draft_id, session_id, revision, text, attachment_ids, file_ids, outgoing_snapshots, size_bytes, created_at, created_by, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` - ).run(draftId, input.sessionId, revision, input.text, ids, JSON.stringify(fileIds), outgoing ? JSON.stringify(outgoing) : null, textBytes + imageBytes, at, principalId, at, principalId); + ).run(draftId, input.sessionId, revision, input.text, ids, JSON.stringify(fileIds), JSON.stringify(snapshots), textBytes + imageBytes, at, principalId, at, principalId); } - // Exactly this revision's bindings; the outgoing snapshot owns its own. - // Insert before removal so a file moving between them never looks unreferenced. - for (const id of outgoing?.fileIds ?? []) addRef(db, id, "outgoing", draftId, at); + // Exactly this revision's bindings; the snapshots own theirs together. + // Insert before removal so a file moving between them never looks + // unreferenced. A deleted snapshot's files start their seven-day clock. + const owned = snapshotFiles(snapshots); + for (const id of owned) addRef(db, id, "outgoing", draftId, at); setRefs(db, "draft", draftId, fileIds, at); - setRefs(db, "outgoing", draftId, outgoing?.fileIds ?? [], at); + setRefs(db, "outgoing", draftId, owned, at); // An image the previous revision listed and this one dropped is gone; // an upload no revision has listed yet waits for its own save. for (const attachment of stored.values()) { @@ -650,6 +764,15 @@ export function createDraftStore( throw deleted(row); } if (ifMatch !== row.revision) throw conflict(row); + // Deleting the draft deletes its returned snapshots; a held or + // unconfirmed one is never dropped this way. + if (snapshotsOf(row).some((s) => s.state !== "returned")) { + throw new DraftError(409, { + error: "DRAFT_OUTGOING_PENDING", + message: "A message of this draft is still waiting or unconfirmed. Cancel it or check it first.", + current: toDraft(row), + }); + } tombstone(row, "deleted", principalId, at); }).immediate(); }, @@ -692,11 +815,12 @@ export function createDraftStore( for (const [id, file] of readAttachments(db, [...new Set(input.fileIds ?? [])])) { if (file.draft_id === draftId && file.state === "stored") addRef(db, id, "message", input.sessionId, at); } + // Only the accepted request's snapshot is released; the others stay. const settled = readDraft(draftId); - const snapshot = settled ? outgoingOf(settled) : null; - if (settled && snapshot && input.requestId && snapshot.requestId === input.requestId) { - setRefs(db, "outgoing", draftId, [], at); - db.prepare("UPDATE session_drafts SET outgoing_json = NULL WHERE draft_id = ?").run(draftId); + const kept = settled && input.requestId ? snapshotsOf(settled).filter((s) => s.requestId !== input.requestId) : null; + if (settled && kept && kept.length !== snapshotsOf(settled).length) { + setRefs(db, "outgoing", draftId, snapshotFiles(kept), at); + db.prepare("UPDATE session_drafts SET outgoing_snapshots = ? WHERE draft_id = ?").run(JSON.stringify(kept), draftId); } if (!input.resumed && input.requestId) { db.prepare( @@ -721,6 +845,18 @@ export function createDraftStore( .run(input.sessionId,row.revision+1,at,input.principalId,draftId); return "kept"; } + const remaining = snapshotsOf(row); + if (remaining.length > 0) { + // The sent revision is consumed, but the chat's other snapshots are + // never evicted with it: the draft stays, at the next revision, with + // an empty composer and those snapshots. + setRefs(db, "draft", draftId, [], at); + db.prepare("DELETE FROM session_draft_attachments WHERE draft_id = ?").run(draftId); + db.prepare( + "UPDATE session_drafts SET revision = ?, text = '', attachment_ids = '[]', file_ids = '[]', size_bytes = 0, updated_at = ?, updated_by = ? WHERE draft_id = ?" + ).run(row.revision + 1, at, input.principalId, draftId); + return "consumed"; + } tombstone(row, "sent", input.principalId, at); return "consumed"; }).immediate(); diff --git a/packages/ui-server/src/routes/drafts.ts b/packages/ui-server/src/routes/drafts.ts index 3460134f8e..6704c2ead7 100644 --- a/packages/ui-server/src/routes/drafts.ts +++ b/packages/ui-server/src/routes/drafts.ts @@ -1,5 +1,5 @@ import { Hono, type Context } from "hono"; -import { ALLOWED_IMAGE_MEDIA_TYPES, MAX_IMAGE_BYTES, type DraftOutgoing } from "@schlessera/brain-ui-sdk/protocol"; +import { ALLOWED_IMAGE_MEDIA_TYPES, MAX_IMAGE_BYTES, SESSION_DRAFT_LIMITS, type DraftOutgoing, type DraftSnapshotWrite } from "@schlessera/brain-ui-sdk/protocol"; import type { AppEnv } from "../app-env.js"; import { DraftAuthError, DraftError, type DraftImageType, type AwaitableDraftStore } from "../drafts/store.js"; @@ -11,8 +11,13 @@ import { DraftAuthError, DraftError, type DraftImageType, type AwaitableDraftSto * nothing. Responses are never cached: they carry unsent private text. */ -/** A save body: 64 KiB of text even at JSON's six-byte escapes, plus ids. */ -const MAX_SAVE_BODY_BYTES = 512 * 1024; +/** Most outgoing snapshots one save lists (#3588). */ +const MAX_SNAPSHOTS = SESSION_DRAFT_LIMITS.maxOutgoingSnapshots ?? 10; +/** + * A save body: the composer's 64 KiB of text and each snapshot's, even at + * JSON's six-byte escapes, plus 64 KiB for ids (4,390,912 bytes). + */ +const MAX_SAVE_BODY_BYTES = (1 + MAX_SNAPSHOTS) * 6 * SESSION_DRAFT_LIMITS.maxTextBytes + 64 * 1024; const MAX_BIND_BODY_BYTES = 4 * 1024; const MAX_NAME_CHARS = 255; const MAX_REFERENCE_CHARS = 256; @@ -137,7 +142,7 @@ export function createDraftRoutes(store: AwaitableDraftStore): Hono { const ifMatch = ifMatchOf(c); const idempotencyKey = idempotencyKeyOf(c); const body = await readJson(c, MAX_SAVE_BODY_BYTES); - const { sessionId, text, attachmentIds, fileIds, outgoing } = body; + const { sessionId, text, attachmentIds, fileIds, outgoing, snapshots } = body; if (sessionId !== null) reference(sessionId, "sessionId"); if (typeof text !== "string") throw invalid("text must be a string."); if (!Array.isArray(attachmentIds) || attachmentIds.some((id) => typeof id !== "string" || !DRAFT_ID.test(id))) { @@ -153,6 +158,24 @@ export function createDraftRoutes(store: AwaitableDraftStore): Hono { if (o.state !== "held" && o.state !== "dispatched") throw invalid("outgoing.state must be held or dispatched."); snapshot = { requestId: reference(o.requestId, "outgoing.requestId"), text: o.text, fileIds: fileIdList(o.fileIds, "outgoing.fileIds"), state: o.state }; } + let list: DraftSnapshotWrite[] | undefined; + if (snapshots !== undefined) { + if (outgoing !== undefined) throw invalid("Send either outgoing or snapshots, not both."); + if (!Array.isArray(snapshots) || snapshots.length > MAX_SNAPSHOTS) throw invalid(`snapshots must be an array of at most ${MAX_SNAPSHOTS} snapshots.`); + list = snapshots.map((item, i) => { + if (!item || typeof item !== "object" || Array.isArray(item)) throw invalid(`snapshots[${i}] must be an object.`); + const o = item as Record; + if (typeof o.text !== "string") throw invalid(`snapshots[${i}].text must be a string.`); + if (o.state !== "held" && o.state !== "returned" && o.state !== "dispatched") throw invalid(`snapshots[${i}].state must be held, returned or dispatched.`); + return { + snapshotId: reference(o.snapshotId, `snapshots[${i}].snapshotId`), + requestId: reference(o.requestId, `snapshots[${i}].requestId`), + text: o.text, + fileIds: fileIdList(o.fileIds, `snapshots[${i}].fileIds`), + state: o.state, + }; + }); + } return c.json(await store.save(principalId, draftId, { ifMatch, idempotencyKey, sessionId: sessionId as string | null, @@ -160,6 +183,7 @@ export function createDraftRoutes(store: AwaitableDraftStore): Hono { attachmentIds: attachmentIds as string[], ...(files !== undefined ? { fileIds: files } : {}), ...(snapshot !== undefined ? { outgoing: snapshot } : {}), + ...(list !== undefined ? { snapshots: list } : {}), })); })); diff --git a/packages/ui-server/tests/draft-snapshots.test.ts b/packages/ui-server/tests/draft-snapshots.test.ts new file mode 100644 index 0000000000..8e9ccc345e --- /dev/null +++ b/packages/ui-server/tests/draft-snapshots.test.ts @@ -0,0 +1,268 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { generateSignedCookie } from "hono/cookie"; +import type { Database } from "bun:sqlite"; +import type { Draft, DraftSnapshotWrite } from "@schlessera/brain-ui-sdk/protocol"; +import { draftSchema } from "@schlessera/brain-ui-sdk/schemas"; + +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { createDraftStore, DraftError, type DraftStore } from "../src/drafts/store"; +import { storeOriginal } from "./helpers/attachment-fixture"; +import { httpContractApp } from "./helpers/http-contract-app"; + +// The outgoing snapshot list of the #3155 G1 A ruling (#3588): up to ten +// snapshots per chat across its drafts, tabs and devices; only the save that +// creates one is refused when full, with 409 DRAFT_OUTGOING_FULL; every other +// transition edits a snapshot in place. Odysseus fixtures only. + +const SECRET = "draft-snapshots-fixture-secret-0123456789"; +const cleanups: Array<() => Promise | void> = []; +afterEach(async () => { for (const c of cleanups.splice(0).reverse()) await c(); }); + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "brain-snapshots-")); + cleanups.push(() => rmSync(dir, { recursive: true, force: true })); + let clock = 1_000_000; + const db = createUiDb(join(dir, "ui.db")); + cleanups.push(() => db.close()); + const store = createDraftStore(db, { now: () => clock }); + const owner = createPrincipal(db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 365 * 24 * 3600 }).id; + const revisions = new Map(); + let keys = 0; + /** Save one revision of `draftId`, If-Match its last revision. */ + const save = (draftId: string, body: { text?: string; fileIds?: string[]; snapshots?: DraftSnapshotWrite[]; sessionId?: string | null; outgoing?: unknown }, s: DraftStore = store) => { + clock += 1; + const { revision } = s.save(owner, draftId, { + ifMatch: revisions.get(draftId) ?? 0, idempotencyKey: `k-${++keys}`, + sessionId: body.sessionId === undefined ? "voyage-ithaca" : body.sessionId, + text: body.text ?? "", attachmentIds: [], + ...(body.fileIds ? { fileIds: body.fileIds } : {}), + ...(body.snapshots ? { snapshots: body.snapshots } : {}), + ...(body.outgoing !== undefined ? { outgoing: body.outgoing as never } : {}), + }); + revisions.set(draftId, revision); + return revision; + }; + const snapshot = (n: number, state: DraftSnapshotWrite["state"] = "held", fileIds: string[] = []): DraftSnapshotWrite => + ({ snapshotId: `snap-${n}`, requestId: `request-${n}`, text: `Message ${n} to Ithaca`, fileIds, state }); + const refuse = (fn: () => unknown): DraftError => { + try { fn(); } catch (error) { if (error instanceof DraftError) return error; throw error; } + throw new Error("expected a DraftError"); + }; + return { dir, db, store, owner, save, snapshot, refuse, revisions, tick: (ms: number) => { clock += ms; }, now: () => clock }; +} + +const messageRefs = (db: Database) => (db.query("SELECT COUNT(*) AS n FROM attachment_refs WHERE owner = 'message'").get() as { n: number }).n; + +test("ten snapshots fit one chat; the eleventh is refused before anything changes", () => { + const f = fixture(); + const list: DraftSnapshotWrite[] = []; + for (let n = 1; n <= 10; n++) { + list.push(f.snapshot(n, n % 2 ? "held" : "dispatched")); + f.save("draft-ithaca", { snapshots: [...list] }); + } + const before = f.store.get(f.owner, "draft-ithaca"); + expect(before.snapshots?.map((s) => s.snapshotId)).toEqual(list.map((s) => s.snapshotId)); + expect(draftSchema.safeParse(before).success).toBe(true); + + const error = f.refuse(() => f.save("draft-ithaca", { text: "Is the harbour open?", snapshots: [...list, f.snapshot(11)] })); + expect(error.status).toBe(409); + expect(error.body).toMatchObject({ error: "DRAFT_OUTGOING_FULL", limit: 10 }); + // Nothing was stored and nothing was sent: the revision, the list and the + // conversation are exactly as before. + expect(f.store.get(f.owner, "draft-ithaca")).toEqual(before); + expect(messageRefs(f.db)).toBe(0); +}); + +test("the count covers every draft of the chat, and only that chat", () => { + const f = fixture(); + // Six on the phone's draft, four on the laptop's draft of the same chat. + f.save("draft-phone", { snapshots: [1, 2, 3, 4, 5, 6].map((n) => f.snapshot(n)) }); + f.save("draft-laptop", { snapshots: [7, 8, 9, 10].map((n) => f.snapshot(n)) }); + const full = f.refuse(() => f.save("draft-laptop", { snapshots: [7, 8, 9, 10, 11].map((n) => f.snapshot(n)) })); + expect(full.body).toMatchObject({ error: "DRAFT_OUTGOING_FULL" }); + // Another chat, and a draft with no chat yet, have their own ten. + f.save("draft-troy", { sessionId: "voyage-troy", snapshots: [21].map((n) => f.snapshot(n)) }); + f.save("draft-new", { sessionId: null, snapshots: [31].map((n) => f.snapshot(n)) }); + // A deleted draft's snapshots are gone and free their slots. + f.save("draft-phone", { snapshots: [1, 2, 3, 4, 5, 6].map((n) => f.snapshot(n, "returned")) }); + f.store.remove(f.owner, "draft-phone", f.revisions.get("draft-phone")!); + f.save("draft-laptop", { snapshots: [7, 8, 9, 10, 11].map((n) => f.snapshot(n)) }); +}); + +test("Cancel, upload failure, dispatch and recovery edit in place at ten of ten", () => { + const f = fixture(); + const file = storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "crew-list.txt", "Eurylochus\n"); + const list = Array.from({ length: 10 }, (_, i) => f.snapshot(i + 1, i < 5 ? "held" : "dispatched")); + f.save("draft-ithaca", { snapshots: list }); + const created = f.store.get(f.owner, "draft-ithaca").snapshots!.map((s) => s.createdAt); + const step = (n: number, change: Partial) => { + list[n - 1] = { ...list[n - 1]!, ...change }; + f.save("draft-ithaca", { snapshots: [...list] }); + }; + step(1, { state: "returned" }); // Cancel + step(2, { state: "returned" }); // an upload failed + step(3, { fileIds: [file.fileId] }); // a held send's upload was admitted + step(3, { state: "dispatched" }); // dispatch + step(6, { state: "returned" }); // recovery read: not accepted + const after = f.store.get(f.owner, "draft-ithaca"); + expect(after.snapshots!.map((s) => s.state)).toEqual(["returned", "returned", "dispatched", "held", "held", "returned", "dispatched", "dispatched", "dispatched", "dispatched"]); + // In place: same ids, same order, same creation times. + expect(after.snapshots!.map((s) => s.createdAt)).toEqual(created); + expect(f.store.attachmentRef(file.fileId, "outgoing", "draft-ithaca")).toBe(true); +}); + +test("a snapshot is never overwritten, merged or evicted by a save", () => { + const f = fixture(); + f.save("draft-ithaca", { snapshots: [f.snapshot(1, "held"), f.snapshot(2, "dispatched")] }); + const invalid = (snapshots: DraftSnapshotWrite[]) => f.refuse(() => f.save("draft-ithaca", { snapshots })); + // Its text and request are fixed. + expect(invalid([{ ...f.snapshot(1), text: "Merged text" }, f.snapshot(2, "dispatched")]).body).toMatchObject({ error: "DRAFT_INVALID" }); + // A held or unconfirmed snapshot cannot be dropped, only returned first. + expect(invalid([f.snapshot(2, "dispatched")]).body).toMatchObject({ error: "DRAFT_INVALID" }); + expect(invalid([f.snapshot(1)]).body).toMatchObject({ error: "DRAFT_INVALID" }); + // A dispatched one never goes back to held, and a new one is never returned. + expect(invalid([f.snapshot(1), f.snapshot(2, "held")]).body).toMatchObject({ error: "DRAFT_INVALID" }); + expect(invalid([f.snapshot(1), f.snapshot(2, "dispatched"), f.snapshot(3, "returned")]).body).toMatchObject({ error: "DRAFT_INVALID" }); + // The single-slot field and the list are not combined. + expect(f.refuse(() => f.save("draft-ithaca", { snapshots: [f.snapshot(1), f.snapshot(2, "dispatched")], outgoing: null })).body).toMatchObject({ error: "DRAFT_INVALID" }); + // A draft delete never drops one that is still waiting. + const pending = f.refuse(() => f.store.remove(f.owner, "draft-ithaca", f.revisions.get("draft-ithaca")!)); + expect(pending.body).toMatchObject({ error: "DRAFT_OUTGOING_PENDING" }); + expect(f.store.get(f.owner, "draft-ithaca").snapshots).toHaveLength(2); +}); + +test("acceptance releases only the matching snapshot and moves its files to the message", () => { + const f = fixture(); + const fees = storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "harbour-fees.txt", "Two oxen\n"); + const crew = storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "crew-list.txt", "Eurylochus\n"); + f.save("draft-ithaca", { snapshots: [f.snapshot(1, "dispatched", [fees.fileId]), f.snapshot(2, "held", [crew.fileId])] }); + const revision = f.save("draft-ithaca", { snapshots: [f.snapshot(1, "dispatched", [fees.fileId]), f.snapshot(2, "returned", [crew.fileId])] }); + expect(f.store.accept({ draftRef: { draftId: "draft-ithaca", revision }, sessionId: "voyage-ithaca", resumed: true, requestId: "request-1", principalId: f.owner, fileIds: [fees.fileId] })).toBe("consumed"); + const after = f.store.get(f.owner, "draft-ithaca"); + // The sent revision is consumed, but the other snapshot is not evicted with it. + expect(after.revision).toBe(revision + 1); + expect(after.snapshots?.map((s) => s.snapshotId)).toEqual(["snap-2"]); + expect(f.store.attachmentRef(fees.fileId, "message", "voyage-ithaca")).toBe(true); + expect(f.store.attachmentRef(fees.fileId, "outgoing", "draft-ithaca")).toBe(false); + expect(f.store.attachmentRef(crew.fileId, "outgoing", "draft-ithaca")).toBe(true); + expect(f.store.attachmentRef(crew.fileId, "message", "voyage-ithaca")).toBe(false); + // With the last snapshot accepted, the draft is a tombstone as before. + f.revisions.set("draft-ithaca", after.revision); + f.save("draft-ithaca", { snapshots: [f.snapshot(2, "returned", [crew.fileId]), f.snapshot(3, "dispatched")] }); + f.save("draft-ithaca", { snapshots: [f.snapshot(3, "dispatched")] }); + expect(f.store.accept({ draftRef: { draftId: "draft-ithaca", revision: f.revisions.get("draft-ithaca")! }, sessionId: "voyage-ithaca", resumed: true, requestId: "request-3", principalId: f.owner })).toBe("consumed"); + expect(f.refuse(() => f.store.get(f.owner, "draft-ithaca")).body).toMatchObject({ error: "DRAFT_DELETED" }); +}); + +test("Delete of a returned snapshot starts its files' seven-day clock; Edit keeps them bound", () => { + const f = fixture(); + const chart = storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "star-chart.txt", "Pleiades\n"); + const log = storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "logbook.txt", "Day 3\n"); + f.save("draft-ithaca", { snapshots: [f.snapshot(1, "held", [chart.fileId]), f.snapshot(2, "held", [log.fileId])] }); + f.save("draft-ithaca", { snapshots: [f.snapshot(1, "returned", [chart.fileId]), f.snapshot(2, "returned", [log.fileId])] }); + // Edit: the snapshot moves into an empty composer revision, files and all. + f.save("draft-ithaca", { text: "Message 2 to Ithaca", fileIds: [log.fileId], snapshots: [f.snapshot(1, "returned", [chart.fileId])] }); + expect(f.store.attachmentRef(log.fileId, "draft", "draft-ithaca")).toBe(true); + expect(f.store.attachments([log.fileId]).get(log.fileId)?.unreferenced_since).toBeNull(); + // Delete…: the refs go and the clock starts; the file is not unlinked. + f.tick(5_000); + f.save("draft-ithaca", { text: "Message 2 to Ithaca", fileIds: [log.fileId], snapshots: [] }); + const row = f.store.attachments([chart.fileId]).get(chart.fileId)!; + expect(f.store.attachmentReferenced(chart.fileId)).toBe(false); + expect(row.unreferenced_since).toBe(f.now()); + expect(row.state).toBe("stored"); + expect(f.store.sweepMark()).toEqual([]); +}); + +test("an all-ready send records a dispatched snapshot, and the composer keeps its own envelope", () => { + const f = fixture(); + const files = Array.from({ length: 10 }, (_, i) => storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", `oar-${i}.txt`, `oar ${i}\n`)); + const ids = files.map((x) => x.fileId); + f.save("draft-ithaca", { text: "Ten oars", fileIds: ids }); + // Send: the same save empties the composer and records the dispatched send. + f.save("draft-ithaca", { text: "", fileIds: [], snapshots: [{ ...f.snapshot(1, "dispatched", ids), text: "Ten oars" }] }); + for (const id of ids) expect(f.store.attachmentRef(id, "outgoing", "draft-ithaca")).toBe(true); + // The newer composer revision can take a whole envelope of its own. + storeOriginal(f.dir, f.store, f.owner, "draft-ithaca", "sail.txt", "linen\n"); +}); + +test("the single-slot field keeps working beside the list", () => { + const f = fixture(); + f.save("draft-ithaca", { snapshots: [f.snapshot(1, "held")] }); + f.save("draft-ithaca", { snapshots: [f.snapshot(1, "returned")] }); + // The old write creates the snapshot of its request… + f.save("draft-ithaca", { outgoing: { requestId: "request-fees", text: "Fees?", fileIds: [], state: "held" } }); + let draft: Draft = f.store.get(f.owner, "draft-ithaca"); + expect(draft.outgoing).toEqual({ requestId: "request-fees", text: "Fees?", fileIds: [], state: "held" }); + expect(draft.snapshots?.map((s) => [s.snapshotId, s.state])).toEqual([["snap-1", "returned"], ["request-fees", "held"]]); + // …moves it to dispatched in place… + f.save("draft-ithaca", { outgoing: { requestId: "request-fees", text: "Fees?", fileIds: [], state: "dispatched" } }); + draft = f.store.get(f.owner, "draft-ithaca"); + expect(draft.outgoing?.state).toBe("dispatched"); + expect(draft.snapshots).toHaveLength(2); + // …and null removes the one it shows, leaving the rest. + f.save("draft-ithaca", { outgoing: null }); + draft = f.store.get(f.owner, "draft-ithaca"); + expect(draft).not.toHaveProperty("outgoing"); + expect(draft.snapshots?.map((s) => s.snapshotId)).toEqual(["snap-1"]); +}); + +test("a single-slot draft saved before the list migrates to its first snapshot", () => { + const dir = mkdtempSync(join(tmpdir(), "brain-snapshots-")); + cleanups.push(() => rmSync(dir, { recursive: true, force: true })); + const path = join(dir, "ui.db"); + let db = createUiDb(path); + const owner = createPrincipal(db, { authMethod: "password", label: "Odysseus phone", ttlSeconds: 3600 }).id; + createDraftStore(db).save(owner, "draft-ithaca", { ifMatch: 0, idempotencyKey: "k", sessionId: null, text: "And the crew?", attachmentIds: [] }); + // Put the row back the way migration 077 stored a slot, and re-run 079. + db.run("ALTER TABLE session_drafts ADD COLUMN outgoing_json TEXT"); + db.run("UPDATE session_drafts SET outgoing_snapshots = '[]', updated_at = 42, outgoing_json = ?", [JSON.stringify({ requestId: "request-fees", text: "Fees?", fileIds: [], state: "held" })]); + db.run("ALTER TABLE session_drafts DROP COLUMN outgoing_snapshots"); + db.run("DELETE FROM _migrations WHERE filename = '079_outgoing_snapshots.sql'"); + db.close(); + db = createUiDb(path); + cleanups.push(() => db.close()); + expect(createDraftStore(db).get(owner, "draft-ithaca").snapshots).toEqual([ + { snapshotId: "request-fees", requestId: "request-fees", text: "Fees?", fileIds: [], state: "held", createdAt: 42 }, + ]); +}); + +test("two devices at nine snapshots save at the same moment: exactly one is admitted", async () => { + const dir = mkdtempSync(join(tmpdir(), "brain-snapshots-")); + cleanups.push(() => rmSync(dir, { recursive: true, force: true })); + const t = await httpContractApp({ env: { + AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: "unused-fixture-hash", COOKIE_SECRET: SECRET, + BRAIN_UI_ALLOW_LOOPBACK_ORIGIN: "1", DB_PATH: join(dir, "ui.db"), + } }); + cleanups.push(() => t.close()); + const device = async (label: string) => { + const principal = createPrincipal(t.app.db, { authMethod: "password", label, ttlSeconds: 3600 }); + const cookie = (await generateSignedCookie("brain_ui_session", principal.id, SECRET)).split(";")[0]!; + return (draftId: string, ifMatch: number, key: string, snapshots: DraftSnapshotWrite[]) => t.fetch(`/api/drafts/${draftId}`, { + method: "PUT", + headers: { cookie, origin: "http://localhost", host: "localhost", "content-type": "application/json", "if-match": String(ifMatch), "idempotency-key": key }, + body: JSON.stringify({ sessionId: "voyage-ithaca", text: "", attachmentIds: [], snapshots }), + }); + }; + const snap = (n: number): DraftSnapshotWrite => ({ snapshotId: `snap-${n}`, requestId: `request-${n}`, text: `Message ${n}`, fileIds: [], state: "held" }); + const phone = await device("Odysseus phone"); + const laptop = await device("Penelope laptop"); + // Each device's draft of the chat holds part of the nine the chat keeps. + const phoneList = [1, 2, 3, 4, 5].map(snap); + const laptopList = [6, 7, 8, 9].map(snap); + expect((await phone("draft-phone", 0, "p1", phoneList)).status).toBe(200); + expect((await laptop("draft-laptop", 0, "l1", laptopList)).status).toBe(200); + const [a, b] = await Promise.all([ + phone("draft-phone", 1, "p2", [...phoneList, snap(10)]), + laptop("draft-laptop", 1, "l2", [...laptopList, snap(11)]), + ]); + expect([a.status, b.status].sort()).toEqual([200, 409]); + const refused = a.status === 409 ? a : b; + expect(await refused.json()).toMatchObject({ error: "DRAFT_OUTGOING_FULL", limit: 10 }); + const total = (t.app.db.query("SELECT SUM(json_array_length(outgoing_snapshots)) AS n FROM session_drafts WHERE session_id = 'voyage-ithaca'").get() as { n: number }).n; + expect(total).toBe(10); +}); From 1f5c6eb75c31f88c2808c62d890e11c75ce26184 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 08:58:07 +0100 Subject: [PATCH 2/3] CONTRACT: feat(ui-react): offer an unrestricted Files source with honest upload states and draft-bound originals (#3155) (#3590) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CONTRACT: feat(ui-react): offer an unrestricted Files source with honest upload states and draft-bound originals (#3155) On a host that advertises composerFiles, the composer offers Files with no allowlist (desktop: Files… and paste-or-drop; phones keep Photo library and Camera). Non-image files upload unfiltered to POST /api/drafts/:draftId/files under one idempotency key per item; chips follow design §8.4 and a lost answer is unknown, re-uploaded with the same key, never "not stored". Stored originals are draft content with their upload lineage, saved as fileIds, and Send holds until that binding is acknowledged, then sends attachmentRefs with the draftRef. Sent rows list originals without a read claim. ChatMessage.attachmentFiles is additive. Refs #3155 Co-Authored-By: Claude Opus 5.5 * wip: hosted fixes * docs(decisions): record how tracks follow the host's composerFiles capability --------- Co-authored-by: Claude Opus 5.5 --- .changeset/composer-generic-files.md | 12 + api-report/ui-react.txt | 1 + docs/decisions/chat-attachments.md | 52 ++- docs/integration-contract/package-api.md | 7 + .../src/components/chat/composer-view.tsx | 78 ++++- .../ui-react/src/components/chat/composer.tsx | 136 +++++++- .../src/components/chat/file-chip.tsx | 48 +++ .../src/components/chat/message-bubble.tsx | 3 +- .../src/hooks/websocket-handlers/chat.ts | 1 + packages/ui-react/src/lib/attachment-queue.ts | 270 +++++++++++++++ packages/ui-react/src/lib/auth-lock.ts | 2 + packages/ui-react/src/lib/draft-client.ts | 21 +- packages/ui-react/src/lib/draft-files.ts | 80 +++++ packages/ui-react/src/lib/local-work.ts | 20 +- packages/ui-react/src/lib/track-attachment.ts | 19 +- packages/ui-react/src/root.ts | 2 + .../src/stores/chat-slices/messages.ts | 3 +- .../src/stores/chat-slices/transcript.ts | 1 + packages/ui-react/src/stores/chat-state.ts | 6 +- packages/ui-react/src/stores/draft-state.ts | 90 +++-- .../ui-react/tests/attachment-queue.test.ts | 133 ++++++++ .../tests/auth-expiry-runtime.test.ts | 45 ++- .../tests/browser/composer-files.offline.tsx | 309 ++++++++++++++++++ .../connection-continuity-runtime.test.ts | 18 +- packages/ui-react/tests/draft-files.test.ts | 113 +++++++ .../tests/parallel-sessions-runtime.test.ts | 39 ++- scripts/source-browser-dispatch.ts | 4 +- 27 files changed, 1429 insertions(+), 84 deletions(-) create mode 100644 .changeset/composer-generic-files.md create mode 100644 packages/ui-react/src/components/chat/file-chip.tsx create mode 100644 packages/ui-react/src/lib/attachment-queue.ts create mode 100644 packages/ui-react/src/lib/draft-files.ts create mode 100644 packages/ui-react/tests/attachment-queue.test.ts create mode 100644 packages/ui-react/tests/browser/composer-files.offline.tsx create mode 100644 packages/ui-react/tests/draft-files.test.ts diff --git a/.changeset/composer-generic-files.md b/.changeset/composer-generic-files.md new file mode 100644 index 0000000000..09426d8e9a --- /dev/null +++ b/.changeset/composer-generic-files.md @@ -0,0 +1,12 @@ +--- +"@schlessera/brain-ui-react": minor +--- + +**Generic composer files (#3155, first slice).** When the host advertises `capabilities.composerFiles`, the composer offers an unrestricted **Files** source with no format allowlist. Desktop shows one Files… action and paste-or-drop guidance, without Photo library or Camera. Phones keep Photo library and Camera beside Files. Picked, pasted and dropped files that are not images upload unfiltered to `POST /api/drafts/:draftId/files`, and the host decides what each one is. Images keep their existing processing. + +- **Chips say what is known.** A chip shows waiting, uploading, waiting for connection, `checking upload…` (no answer yet), upload failed, or the host's refusal (too large, no space). A stored PDF or text file reads `not read yet`. A file without a reader reads `no reader here` and can still be sent. A rejected track reads `not a usable track`. +- **Lost answers.** A lost answer is uploaded again with the same idempotency key, once automatically on reconnect or with **Upload again**. It never stores a second copy and is never reported as not stored. +- **Saving and sending.** A stored original becomes part of the draft. It is saved as a `fileIds` binding and reads as saved only once the host acknowledges that revision. Send holds while uploads or that save are pending, then sends `attachmentRefs` with the acknowledged `draftRef`. +- **Sent messages.** A sent message lists its originals by name, kind and size, with no claim about which contents were read. +- **Older hosts.** A host without `composerFiles` keeps the previous menu and the tab-only track queue. +- **API.** `ChatMessage.attachmentFiles?` is additive. diff --git a/api-report/ui-react.txt b/api-report/ui-react.txt index 2e8565432d..386cf67c25 100644 --- a/api-report/ui-react.txt +++ b/api-report/ui-react.txt @@ -283,6 +283,7 @@ signatures (every public export and the types it is made of) askUserExchanges?: AskUserExchange[]; attachments?: MessageAttachment[]; files?: SharedFileMeta[]; + attachmentFiles?: AttachmentFile[]; attachmentCount?: number; blocks?: MessageBlock[]; journal?: TurnJournalSummary; diff --git a/docs/decisions/chat-attachments.md b/docs/decisions/chat-attachments.md index cb3f5dea5d..f5d4fcbf91 100644 --- a/docs/decisions/chat-attachments.md +++ b/docs/decisions/chat-attachments.md @@ -6,8 +6,9 @@ linked in each section below. The schemas, bounds and proof briefs; its six §13 recommendations were approved at review on 2026-11-02. Admission, storage, ownership and cleanup are built ([what #3153 built](#what-3153-built)), and so is reading contents -([what #3154 built](#what-3154-built)); the composer is open work in epic -#3150. +([what #3154 built](#what-3154-built)). The composer's first slice is built +([what #3155 built so far](#what-3155-built-so-far)); the rest is open work in +epic #3150. ## Sources and one pipeline @@ -245,7 +246,52 @@ The shared reader of the design's §7, with these concrete choices: parsing; then add an Odysseus fixture and its outcome tests. The composer's Files picker has no `accept` filter, so it does not change. -## Rejected alternatives +## What #3155 built so far + +The composer's Files source, its upload queue and the draft binding of +originals, on a host that advertises `composerFiles`: + +- **Menus as ruled.** Desktop shows Files… and paste-or-drop guidance, and no + 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 + 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. +- **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 + **Upload again**. A `503` waits and retries with that key. Only a received + `4xx` says *not stored*. `fetch` reports no upload progress, so the chip + says `uploading…` rather than invent a percentage. +- **Stored originals are draft content.** A stored original joins + `ComposerDraft.files`, together with the draft id it was uploaded to (its + lineage). It is saved as `fileIds`, and it reads as saved only when an + acknowledged revision lists it. A file carried to another draft id, by a + rotation or a kept copy, cannot be bound there. It shows *not attached*, + blocks Send and is never listed in that id's save. The device copy of a + draft (#1014) keeps the references, so a restore cannot unbind them. +- **Send waits for the binding.** Send holds while an upload or the save + that binds the originals is pending, and then sends `attachmentRefs` with + the acknowledged `draftRef`. A refused or failed upload, or a detached + file, blocks Send with a reason. Unread contents, and kinds with no + reader, never block it. The hold uses the composer's existing tab-local + hold. The durable held snapshot, recovery bubbles and queue-full notice of + design brief rev 5 wait for the snapshot list (#3588). +- **Tracks follow the host.** On a host with `composerFiles` a picked track + is a generic original: the host detects it, the draft binds it and a reload + restores it, so it is not a tab-only staged track and the #1150 leave guard + no longer applies once its binding is acknowledged. D52's tab-only path + remains for a host without `composerFiles`. The mounted-app suites that + 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*. + The rejected options were offered in the rulings above: diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 4999e996fe..e1bc86520c 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -517,6 +517,13 @@ root now exports the share pipeline (`shareMarkdown`, `renderBlockHtml`, website's demo uses exactly these, so it builds from the public entry instead of from ui-react's source tree. +**Additive: `ChatMessage.attachmentFiles` (#3155).** A user message in +ui-react's chat store may carry `attachmentFiles?: AttachmentFile[]`: the +composer originals it named in `chat_message.attachmentRefs`, from the +optimistic send or from `SessionHistoryMessage.attachmentFiles` on replay. It +lists the stored originals only. It says nothing about which of their contents +the agent read, and a reader must not infer a read state from it. + **Additive: `AppErrorBoundary` (#1377).** `@schlessera/brain-ui-react` exports `AppErrorBoundary` and `AppErrorBoundaryProps` (`children`, plus a `reload` hook for tests). A shell wraps its whole tree in it, providers included, so a diff --git a/packages/ui-react/src/components/chat/composer-view.tsx b/packages/ui-react/src/components/chat/composer-view.tsx index 9d2d68c822..cff8dad4c9 100644 --- a/packages/ui-react/src/components/chat/composer-view.tsx +++ b/packages/ui-react/src/components/chat/composer-view.tsx @@ -1,10 +1,13 @@ import { Overlay, Button, IconButton, Callout, Composer as KitComposer, ModelPicker, ListRow, type ComposerState, type ModelPickerProps } from "@schlessera/brain-ui-kit"; import { TrackChip } from "./track-chip.js"; +import { FileChip } from "./file-chip.js"; import type { PendingTrack } from "../../lib/track-uploads.js"; +import type { QueuedFile } from "../../lib/attachment-queue.js"; +import type { AttachmentFile } from "@schlessera/brain-ui-sdk/protocol"; import { X } from "lucide-react"; import { useId } from "react"; import { useMediaQuery } from "../../hooks/use-media-query.js"; -import type { ClipboardEvent, KeyboardEvent, ReactNode, RefObject } from "react"; +import type { ClipboardEvent, DragEvent, KeyboardEvent, ReactNode, RefObject } from "react"; import { isThinkingLevel, type ThinkingLevel } from "@schlessera/brain-ui-sdk/protocol"; /** @@ -80,6 +83,17 @@ export interface ComposerViewProps { tracks?: PendingTrack[]; onRemoveTrack?: (id: string) => void; onRetryTrack?: (id: string) => void; + /** + * The draft's composer files (#3155): uploads still queued, then the + * 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 }[] }; + onRemoveQueuedFile?: (id: string) => void; + onRetryQueuedFile?: (id: string) => void; + onRemoveStoredFile?: (fileId: string) => void; + /** Polite, once: a file's upload reached an end state (stored, failed, refused). */ + fileAnnouncement?: string; attachErrors: string[]; provider: ComposerProvider | null; chatProfile?: ModelPickerProps["chat"]; @@ -96,6 +110,13 @@ export interface ComposerViewProps { onPickLibrary: () => void; onPickCamera: () => void; onPickTracks?: () => void; + /** + * The unrestricted Files source (additive; #3155). Present when the host + * keeps composer originals: the menu then offers Files instead of Track + * files, desktop drops Photo library and Camera, and dropped files feed + * the same pipeline as pasted ones. `onPickTracks` stays supported. + */ + onPickFiles?: () => void; onPasteFiles: (files: File[]) => void; onRecall: () => void; onEscape: () => void; @@ -129,25 +150,58 @@ export function ComposerView(p: ComposerViewProps) { p.onPasteFiles(Array.from(files)); } + function onDrop(e: DragEvent) { + const files = e.dataTransfer?.files; + if (!p.onPickFiles || !files || files.length === 0) return; + e.preventDefault(); + p.onPasteFiles(Array.from(files)); + } + function onDragOver(e: DragEvent) { + if (p.onPickFiles && e.dataTransfer?.types.includes("Files")) e.preventDefault(); + } + + /** After Remove: the next chip, then the previous one, then Attach (§8.4). */ + function removeAndRefocus(index: number, remove: () => void) { + const frame = p.frameRef.current; + const hadFocus = !!frame?.querySelector("[data-file-chips]")?.contains(document.activeElement); + remove(); + if (!hadFocus) return; + setTimeout(() => { + const buttons = frame?.querySelectorAll('[data-file-chips] [data-file-chip] button[aria-label^="Remove "]'); + const target = buttons?.[index] ?? buttons?.[index - 1] ?? frame?.querySelector('[role="button"][aria-label^="Attach"]'); + target?.focus(); + }, 0); + } + const pointer = useMediaQuery("(min-width: 900px)"); + const files = p.onPickFiles ? p.files : undefined; + const fileCount = (files?.queued.length ?? 0) + (files?.stored.length ?? 0); // The trigger's name lists what its menu offers, in menu order (#3045): // live conversation is reached through the paperclip, so the paperclip says // so whenever the row is there. The kit paints the same string as the // pointer tooltip; a phone's sheet names the actions in its subtitle. - const attachLabel = p.onConversation ? "Attach — live conversation, photo, camera, files" : undefined; - const attachSubtitle = `${p.onConversation ? "Live conversation, photo" : "Photo"}, camera, ${p.onPickTracks ? "track files, " : ""}or paste.`; + // Desktop with composer files: one unrestricted Files action (desktop + // menu A, #3155); phones keep Photo library and Camera beside it. + const desktopFiles = pointer && !!p.onPickFiles; + const attachLabel = p.onConversation ? `Attach — live conversation, ${desktopFiles ? "files" : "photo, camera, files"}` : desktopFiles ? "Attach — files" : undefined; + const attachSubtitle = p.onPickFiles + ? `${p.onConversation ? "Live conversation, photo" : "Photo"}, camera, files or paste.` + : `${p.onConversation ? "Live conversation, photo" : "Photo"}, camera, ${p.onPickTracks ? "track files, " : ""}or paste.`; const attachMenu = (
{p.onConversation && } - - - {p.onPickTracks && } - + {!desktopFiles && } + {!desktopFiles && } + {p.onPickFiles + ? + : p.onPickTracks && } +
); return ( -
+
{p.dictation} {p.dictationNotice && (
{ @@ -188,6 +242,14 @@ export function ComposerView(p: ComposerViewProps) {
)} + {p.onPickFiles &&
{p.fileAnnouncement ?? ""}
} + {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))} />)} +
} + {!!p.tracks?.length &&
{p.tracks.map(track => p.onRemoveTrack?.(track.id)} onRetry={() => p.onRetryTrack?.(track.id)} />)}
} {p.palette} diff --git a/packages/ui-react/src/components/chat/composer.tsx b/packages/ui-react/src/components/chat/composer.tsx index e7f4fb463d..c35c31adb8 100644 --- a/packages/ui-react/src/components/chat/composer.tsx +++ b/packages/ui-react/src/components/chat/composer.tsx @@ -32,6 +32,9 @@ import { useChatCommands } from "./use-chat-commands.js"; 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 { queuedBlocking, queuedPending } from "../../lib/attachment-queue.js"; +import { bindableFiles, draftFiles as draftFilesOf, type DraftFile } from "../../stores/draft-state.js"; import { insertSuggestion } from "../../lib/answer-suggestions.js"; import { HANDOFF_ENTRY_LABEL, useHandoffEntry } from "../../hooks/use-handoff-entry.js"; import { DraftSaveLine } from "./draft-save-line.js"; @@ -72,6 +75,7 @@ type DraftEffort = { key: string | null; level?: ThinkingLevel; requested?: Thin type PendingSend = { requestId: string; key: string | null; effort: DraftEffort }; const NO_ATTACHMENTS: PendingAttachment[] = []; +const NO_FILES: DraftFile[] = []; /** * What the chat page may ask of the composer without reaching into its DOM: @@ -95,6 +99,10 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const draft = useRootStore("drafts", (s) => s.drafts[draftId]); const input = draft?.text ?? ""; const attachments = draft?.attachments ?? NO_ATTACHMENTS; + const draftFiles = draft?.files ?? NO_FILES; + // The draft's content is the revision the host acknowledged, file bindings included. + const draftClean = !!draft && draft.host !== null && draft.host.edit === draft.edit && draft.conflict === null; + const draftFailure = draft?.failure ?? null; /** Write the view's draft. A function reads the draft as it is now, not as rendered. */ const setInput = (value: string | ((current: string) => string)) => { const store = root.stores.drafts.getState(); @@ -165,6 +173,40 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void return () => { trackEntry.listeners.delete(updateTrackView); }; }, [trackEntry]); const tracks = trackUploads.files; + // Composer originals (#3155): offered only when the host keeps them. + const fileLimits = useRootStore("drafts", (s) => s.fileLimits); + const filesOn = fileLimits !== null; + const fileInputRef = useRef(null); + const [, updateFileView] = useReducer((n: number) => n + 1, 0); + const fileEntry = filesFor(root, trackKey(sessionId, trackOwner), sessionId); + const fileQueue = fileEntry.queue; + useEffect(() => { + fileEntry.listeners.add(updateFileView); + return () => { fileEntry.listeners.delete(updateFileView); }; + }, [fileEntry]); + const queuedFiles = fileQueue.files; + // Terminal transitions only, once each (§8.4): progress is never announced. + const [fileAnnouncement, setFileAnnouncement] = useState(""); + const lastFileStates = useRef(new Map()); + const lastStoredIds = useRef | null>(null); + useEffect(() => { + const before = lastFileStates.current; + for (const item of queuedFiles) { + if (before.get(item.id) === item.state) continue; + if (item.state === "failed" || item.state === "refused") setFileAnnouncement(`${item.name}: ${item.status ?? "upload failed"}.`); + } + lastFileStates.current = new Map(queuedFiles.map((item) => [item.id, item.state] as const)); + }, [queuedFiles]); + useEffect(() => { lastStoredIds.current = null; setFileAnnouncement(""); }, [draftId]); + useEffect(() => { + const ids = new Set(draftFiles.map((f) => f.file.fileId)); + // The first look at a draft (a switch, a restore) announces nothing. + const before = lastStoredIds.current; + lastStoredIds.current = ids; + if (!before) return; + const added = draftFiles.filter((f) => !before.has(f.file.fileId) && f.lineage === draftId); + if (added.length) setFileAnnouncement(`${added.map((f) => f.file.incomingName || f.file.name).join(", ")} uploaded.`); + }, [draftFiles, draftId]); // A send pressed while tracks upload is held for the draft it was pressed // in, by id: another draft opened meanwhile is never sent for it (#951). const [heldFor, setHeldFor] = useState(null); @@ -181,12 +223,16 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const handoffEntry = useHandoffEntry(sessionId, hasSettledTurn); const wsStatus = useConnectionStore((s) => s.wsStatus); useEffect(() => { - const changed = () => trackUploads.setOnline(wsStatus === "connected" && navigator.onLine !== false); + const changed = () => { + const online = wsStatus === "connected" && navigator.onLine !== false; + trackUploads.setOnline(online); + fileQueue.setOnline(online); + }; changed(); window.addEventListener("online", changed); window.addEventListener("offline", changed); return () => { window.removeEventListener("online", changed); window.removeEventListener("offline", changed); }; - }, [wsStatus, trackUploads]); + }, [wsStatus, trackUploads, fileQueue]); const profilesSupported = useConnectionStore(s => s.sessionProfiles); const profileEpoch = useConnectionStore(s => s.profileEpoch); const sessionProfile = useSessionProfile(sessionId, draftId, wsStatus === "connected", isStreaming, profilesSupported, profileEpoch); @@ -381,8 +427,17 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const owner = sessionId; const incoming = Array.from(files); const list = incoming.filter(file => file.type.startsWith("image/")); - const trackErrors = trackUploads.add(incoming.filter(file => !file.type.startsWith("image/")), attachmentsOf(target).length + list.length, - attachmentsOf(target).reduce((sum, image) => sum + image.bytes, 0)); + 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, + 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)); if (list.length === 0) { setAttachErrors(trackErrors); return; } const authEpoch = root.authLock.epoch(); @@ -410,10 +465,14 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void ...current, ...fresh, ]); - let combinedBytes = trackUploads.files.reduce((sum, track) => sum + (track.meta?.bytes ?? track.file.size), 0); + 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; const accepted = imageAccepted.filter((image, index) => { combinedBytes += image.bytes; - return index + trackUploads.files.length < SHARE_MAX_FILES && combinedBytes <= SHARE_MAX_TOTAL_BYTES; + return index + otherCount < maxFiles && combinedBytes <= SHARE_MAX_TOTAL_BYTES; }); // Revoke URLs of freshly-decoded images that didn't make the cut. for (const f of fresh) { @@ -445,7 +504,10 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void function handleSubmit() { const text = draftText(); const currentTracks = trackUploads.files; - const hasAttachments = attachments.length > 0 || currentTracks.length > 0; + const currentQueued = fileQueue.files; + const currentDraft = root.stores.drafts.getState().drafts[draftId]; + const currentFiles = currentDraft ? bindableFiles(currentDraft) : []; + const hasAttachments = attachments.length > 0 || currentTracks.length > 0 || currentQueued.length > 0 || draftFilesOf(currentDraft).length > 0; if ((!text && !hasAttachments) || wsStatus !== "connected" || waiting || sessionProfile.saving || sessionProfile.awaitingDraftFacts) return; if (restorationOf(root.stores.chat.getState())) return; @@ -455,6 +517,9 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void return; } if (currentTracks.some(trackPending)) { setHeldSend(true); return; } + const fileHold = composerFilesHold(); + if (fileHold.blocked) { setHeldSend(false); setEffortNotice(fileHold.blocked); return; } + if (fileHold.pending) { setHeldSend(true); return; } const readyFiles = currentTracks.filter(trackReady).map(track => track.meta!); // A send while a question is pending is the ANSWER to it, not a new @@ -506,7 +571,8 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void source, messageAttachments.length > 0 ? messageAttachments : undefined, requestId ? { requestId, thinkingLevel: selectedEffort } : undefined, - readyFiles.length ? readyFiles : undefined + readyFiles.length ? readyFiles : undefined, + currentFiles.length ? currentFiles.map((f) => f.file) : undefined ); } // A send while the session is already streaming is a follow-up — the server @@ -534,6 +600,9 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void ? undefined : selectedProviderId, ...(readyFiles.length ? { files: readyFiles.map(file => ({ kind: "file" as const, path: file.path })) } : {}), + // 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) : undefined, @@ -553,6 +622,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const draftRef = drafts.beginSend({ requestId, draftId, sessionId, text, attachments: [...attachments], ...(readyFiles.length ? { files: readyFiles } : {}), + ...(currentFiles.length ? { attachmentFiles: currentFiles } : {}), // Staged tracks stay in the field until the host accepts the message. ...(currentTracks.length ? { tracks: { key: trackKey(sessionId, trackOwner), ids: currentTracks.map((t) => t.id) } } : {}), message: snapshot, @@ -587,6 +657,26 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void setAttachErrors([]); } + /** + * Whether composer files let this draft send now (#3155). Required uploads + * and the save that binds their originals hold it; a file the host refused, + * a failed upload or one carried from another draft id blocks it until + * retried or removed. Unread PDF or text contents never hold it. + */ + function composerFilesHold(): { blocked?: string; pending?: boolean } { + const d = root.stores.drafts.getState().drafts[draftIdRef.current]; + const queued = fileQueue.files; + if (queued.some(queuedBlocking)) return { blocked: "Your draft is kept. Retry or remove the file that wasn't stored before sending." }; + if (d && draftFilesOf(d).some((f) => f.lineage !== d.draftId)) return { blocked: "Your draft is kept. Remove the files marked not attached, or choose them again, before sending." }; + if (queued.some(queuedPending)) return { pending: true }; + if (!d || draftFilesOf(d).length === 0) return {}; + if (d.failure && d.failure.kind !== "unsaved") return { blocked: "Your draft is kept. Its files couldn't be saved with it; remove one and try again." }; + 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 }; + return {}; + } + const submitHeldDraft = useRef(handleSubmit); useEffect(() => { submitHeldDraft.current = handleSubmit; }); @@ -594,15 +684,26 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void // once, only after every remaining file has a validated ready result. useEffect(() => { if (!heldSend) return; + const fileHold = composerFilesHold(); if (tracks.some(track => track.state === "failed")) { setHeldSend(false); setEffortNotice("Your draft is kept. Retry or remove the failed track before sending."); - } else if (!tracks.some(trackPending) && wsStatus === "connected") { + } else if (fileHold.blocked) { + setHeldSend(false); + setEffortNotice(fileHold.blocked); + } else if (!tracks.some(trackPending) && !fileHold.pending && wsStatus === "connected") { setHeldSend(false); submitHeldDraft.current(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [heldSend, tracks, wsStatus]); + }, [heldSend, tracks, queuedFiles, draftClean, draftFailure, draftFiles, wsStatus]); + + /** 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"}`; + return "sends when the draft with its files is saved"; + } function stopDictation() { // Read synchronously: another stop may arrive before React paints the @@ -701,7 +802,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void } const hasDraft = Boolean( - input.trim() || reviewText.trim() || attachments.length > 0 || tracks.length > 0 + input.trim() || reviewText.trim() || attachments.length > 0 || tracks.length > 0 || queuedFiles.length > 0 || draftFiles.length > 0 ); // A send while a session is running is a follow-up (not blocked by streaming). const canSend = hasDraft && wsStatus === "connected" && !waiting && restorePhase === null && !sessionProfile.saving && !sessionProfile.awaitingDraftFacts; @@ -769,6 +870,8 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void + {/* Files: no accept filter. The host decides what each file is (#3155). */} + {filesOn && } { setAttachMenuOpen(false); root.connection.conversation.enter(); } : undefined} @@ -811,7 +914,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void : "Connecting..." : root.config.composerPlaceholder } - hint={localPhase === "recording" ? "Recording on this device" : heldSend ? `sends when ${tracks.filter(trackPending).length} file${tracks.filter(trackPending).length === 1 ? " finishes" : "s finish"}` : voiceMode === "dictate" ? "Dictating… · stop to review your words" : localSaveFailed ? LOCAL_SAVE_FAILED : followUpHint ? `${followUpHint} · ${finePointer ? "esc or " : ""}the stop button ends the run` : undefined} + hint={localPhase === "recording" ? "Recording on this device" : heldSend ? heldHint() : voiceMode === "dictate" ? "Dictating… · stop to review your words" : localSaveFailed ? LOCAL_SAVE_FAILED : followUpHint ? `${followUpHint} · ${finePointer ? "esc or " : ""}the stop button ends the run` : undefined} blockedWhy={ wsStatus === "connected" && sessionProfile.saving ? "saving this chat profile · your draft is kept" : wsStatus === "connected" && sessionProfile.awaitingDraftFacts ? "waiting for this chat profile · reopen the model picker to retry" @@ -833,6 +936,14 @@ 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} + onRemoveQueuedFile={(id) => fileQueue.remove(id)} + onRetryQueuedFile={(id) => fileQueue.retry(id)} + onRemoveStoredFile={(fileId) => { + const current = root.stores.drafts.getState().drafts[draftId]; + if (current) root.stores.drafts.getState().edit(draftId, sessionId, { files: draftFilesOf(current).filter((f) => f.file.fileId !== fileId) }); + }} + fileAnnouncement={fileAnnouncement} attachErrors={attachErrors} chatProfile={sessionProfile.chat} provider={ @@ -882,6 +993,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void libraryInputRef.current?.click(); }} onPickTracks={() => { setAttachMenuOpen(false); trackInputRef.current?.click(); }} + onPickFiles={filesOn ? () => { setAttachMenuOpen(false); fileInputRef.current?.click(); } : undefined} onPickCamera={() => { setAttachMenuOpen(false); cameraInputRef.current?.click(); diff --git a/packages/ui-react/src/components/chat/file-chip.tsx b/packages/ui-react/src/components/chat/file-chip.tsx new file mode 100644 index 0000000000..3bcae204fa --- /dev/null +++ b/packages/ui-react/src/components/chat/file-chip.tsx @@ -0,0 +1,48 @@ +import { Button, IconButton } from "@schlessera/brain-ui-kit"; +import { FileText, X } from "lucide-react"; +import type { AttachmentFile } from "@schlessera/brain-ui-sdk/protocol"; +import { fileKindLabel, queuedFileCopy, storedFileCopy, type QueuedFile } from "../../lib/attachment-queue.js"; +import { trackBytes } from "../../lib/track-uploads.js"; + +/** + * One composer file (#3155, design §8.4): a queued upload, or an original + * the host stored for this draft. Its accessible name is + * `{name}, {kind}, {size}, {state}`; the words `readable`, `processed`, + * `decoded` and `saved` never appear on a chip, because a stored file is + * neither read nor, until the draft's save is acknowledged, saved. + * + * Retry and Upload again are text buttons with `reach`, so a coarse + * pointer gets a 44px target without a 44px painted box; Remove is the + * kit's 44px icon control. + */ +export function FileChip(p: { + queued?: QueuedFile; + stored?: AttachmentFile; + /** A stored original this draft's id cannot bind (it came from another draft id). */ + detached?: boolean; + onRemove: () => void; + onRetry?: () => void; +}) { + const name = p.queued?.name ?? (p.stored ? p.stored.incomingName || p.stored.name : "") ?? "Unnamed file"; + 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!); + 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
+
+
+
; +} diff --git a/packages/ui-react/src/components/chat/message-bubble.tsx b/packages/ui-react/src/components/chat/message-bubble.tsx index aac5bcf279..f7c55330c8 100644 --- a/packages/ui-react/src/components/chat/message-bubble.tsx +++ b/packages/ui-react/src/components/chat/message-bubble.tsx @@ -1,7 +1,7 @@ import { ConversationTaskContext } from "../voice/conversation-outputs.js"; import type { TranscriptRange } from "../../lib/transcript-timeline.js"; import { AttachmentRow } from "@schlessera/brain-ui-kit"; -import { trackRowProps } from "../../lib/track-attachment.js"; +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"; @@ -146,6 +146,7 @@ export const MessageBubble = memo(function MessageBubble({ {!!message.files?.length &&
{message.files.map(file => )}
} + {!!message.attachmentFiles?.length &&
{message.attachmentFiles.map(file => )}
} {message.content && (
{linkifyPaths(message.content)} diff --git a/packages/ui-react/src/hooks/websocket-handlers/chat.ts b/packages/ui-react/src/hooks/websocket-handlers/chat.ts index 9e2388f669..1021c0ee5e 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/chat.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/chat.ts @@ -75,6 +75,7 @@ function convertHistoryMessage(msg: SessionHistoryMessage): ChatMessage { timestamp: Date.now(), ...(askUserExchanges ? { askUserExchanges } : {}), ...(msg.files?.length ? { files: msg.files } : {}), + ...(msg.attachmentFiles?.length ? { attachmentFiles: msg.attachmentFiles } : {}), ...(msg.attachmentCount ? { attachmentCount: msg.attachmentCount } : {}), ...(msg.blocks && msg.blocks.length > 0 ? { blocks: msg.blocks } : {}), // Absent means typed: an older host never sends it, and a newer one diff --git a/packages/ui-react/src/lib/attachment-queue.ts b/packages/ui-react/src/lib/attachment-queue.ts new file mode 100644 index 0000000000..067d265311 --- /dev/null +++ b/packages/ui-react/src/lib/attachment-queue.ts @@ -0,0 +1,270 @@ +import { ATTACHMENT_MAX_FILE_BYTES, ATTACHMENT_MAX_FILES, ATTACHMENT_MAX_TOTAL_BYTES, type AttachmentFile, type AttachmentLimits } from "@schlessera/brain-ui-sdk/protocol"; +import { attachmentFileSchema } from "@schlessera/brain-ui-sdk/schemas"; +import type { BrainUiRoot } from "../root.js"; +import { trackBytes, trackStatus } from "./track-uploads.js"; + +/** + * The composer's generic file queue (#3155, design §6.1 and §8.4). + * + * Every file a source hands over is uploaded, unfiltered, to the neutral + * `POST /api/drafts/:draftId/files` route. The host decides what it is from + * the stored bytes; nothing here routes by MIME type or extension. A file + * leaves this queue once the host has stored it: it then belongs to the + * draft (`ComposerDraft.files`), which saves its binding, and only an + * acknowledged save of that binding reads as saved. + * + * Each item keeps one `Idempotency-Key` for its whole life, so asking again + * after a lost answer returns the same `fileId` and never stores a second + * copy. A missing answer is never read as "nothing was stored": the item + * waits as `unknown` until it is uploaded again with the same key. + */ +type QueuedFileState = + /** Not started yet, or the host was busy and it waits its turn. */ + | "waiting" + | "uploading" + /** Offline: it starts, or asks again, when the connection is back. */ + | "paused" + /** Sent, and no answer came. The host may have stored it. */ + | "unknown" + /** The host answered, but not with a stored file. Asking again is safe. */ + | "failed" + /** The host refused it, so it is known not stored. */ + | "refused"; + +export interface QueuedFile { + id: string; + file: File; + /** The name shown, with control and format characters removed. */ + name: string; + /** The draft id it is uploaded to: the host's lineage for the original. */ + draftId: string; + /** Kept for every retry of this file. */ + idempotencyKey: string; + state: QueuedFileState; + /** Chip copy for a failed or refused file. */ + status?: string; + /** The longer explanation for the same state. */ + detail?: string; +} + +/** Pending items hold Send; failed and refused ones block it until removed or retried. */ +export const queuedPending = (item: QueuedFile) => item.state === "waiting" || item.state === "uploading" || item.state === "paused" || item.state === "unknown"; +export const queuedBlocking = (item: QueuedFile) => item.state === "failed" || item.state === "refused"; + +function fileDisplayName(name: string): string { + return Array.from(name.replace(/[\p{Cc}\p{Cf}]/gu, "")).slice(0, 100).join("") || "Unnamed file"; +} + +/** `X-File-Name`: percent-encoded UTF-8, at most 1,024 bytes encoded (§6.1). */ +export function fileNameHeader(name: string): string { + const chars = Array.from(name); + let encoded = encodeURIComponent(name); + while (encoded.length > 1024 && chars.length > 0) { chars.pop(); encoded = encodeURIComponent(chars.join("")); } + return encoded; +} + +const KIND_LABEL: Record = { pdf: "PDF", text: "Text", track: "Track", image: "Image", archive: "Archive", binary: "File" }; + +/** 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 } { + 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) { + return { status: `Track · ${size} · ${trackStatus({ id: "", file: new File([], ""), name: "", state: "ready", meta: file.track })}` }; + } + 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}` }; + 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." }; +} + +/** What a queued file's chip says, and why (design §8.4). */ +export function queuedFileCopy(item: QueuedFile): { status: string; detail?: string } { + switch (item.state) { + case "waiting": return { status: "waiting to upload" }; + // `fetch` reports no upload progress, so no percentage is invented. + case "uploading": return { status: "uploading…" }; + case "paused": return { status: "waiting for connection" }; + case "unknown": return { status: "checking upload…", detail: "The host didn't answer yet. Upload again sends the same file under the same key, so it can't store a second copy." }; + case "failed": return { status: item.status ?? "upload failed", detail: item.detail ?? "Retrying is safe: it won't store a second copy." }; + case "refused": return { status: item.status ?? "not stored", detail: item.detail }; + } +} + +/** A limit as the design states it: decimal megabytes for the round ones (25 MB, 50 MB). */ +const limitBytes = (n: number): string => (n >= 1_000_000 && n % 1_000_000 === 0 ? `${n / 1_000_000} MB` : trackBytes(n)); + +/** A refusal's copy: the host answered with a 4xx, so the file is known not stored. */ +function refusal(status: number, body: { bound?: string; limit?: number; error?: string }): { status: string; detail: string } | null { + if (status === 413) { + if (body.bound === "draftCount") return { status: "not stored · too many files", detail: `Up to ${body.limit ?? ATTACHMENT_MAX_FILES} files per message.` }; + if (body.bound === "draftFiles") return { status: "not stored · message too large", detail: `Files can be up to ${limitBytes(body.limit ?? ATTACHMENT_MAX_TOTAL_BYTES)} together.` }; + return { status: "too large", detail: `Files can be up to ${limitBytes(body.limit ?? ATTACHMENT_MAX_FILE_BYTES)} each.` }; + } + if (status === 507) return { status: "not stored · no space", detail: "This host's attachment space is full. Nothing was removed to make room." }; + if (status === 410) return { status: "not stored · draft gone", detail: "The draft it was for was deleted. Choose the file again to attach it." }; + if (status === 400) return { status: "not stored", detail: "The host refused this file. Empty files can't be attached." }; + return null; +} + +/** How long a busy host is given before the same upload is asked again. */ +const BUSY_RETRY_MS = 2_000; +/** Uploads one composer runs at once; the host admits three across all clients. */ +const PARALLEL = 2; + +interface AttachmentQueueOptions { + request: BrainUiRoot["request"]; + apiBase: string; + /** The host stored it: the draft takes it from here. The item has already left the queue. */ + stored: (item: QueuedFile, file: AttachmentFile) => void; + changed: () => void; + /** Resolve a draft id that was rotated since the file was picked. */ + resolveDraft?: (draftId: string) => string; +} + +export function createAttachmentQueue(options: AttachmentQueueOptions) { + const { request, apiBase } = options; + let items: QueuedFile[] = []; + let online = true; + let disposed = false; + const running = new Map(); + const busyTimers = new Map>(); + const notify = () => { if (!disposed) options.changed(); }; + const has = (id: string) => items.some((item) => item.id === id); + function update(id: string, patch: Partial) { + items = items.map((item) => (item.id === id ? { ...item, ...patch } : item)); + notify(); + } + + async function upload(item: QueuedFile, controller: AbortController) { + // A rotated draft's successor is where the binding goes; the host checks lineage. + const draftId = options.resolveDraft?.(item.draftId) ?? item.draftId; + update(item.id, { state: "uploading", draftId, status: undefined, detail: undefined }); + let answered = false; + try { + const response = await request(`${apiBase}/drafts/${encodeURIComponent(draftId)}/files`, { + method: "POST", + headers: { + "Idempotency-Key": item.idempotencyKey, + "Content-Type": item.file.type || "application/octet-stream", + "X-File-Name": fileNameHeader(item.file.name || item.name), + }, + body: item.file, + signal: controller.signal, + }); + answered = true; + if (controller.signal.aborted || !has(item.id)) return; + const body = await response.json().catch(() => undefined) as Record | undefined; + if (controller.signal.aborted || !has(item.id)) return; + if (response.status === 503) { + update(item.id, { state: "waiting" }); + busyTimers.set(item.id, setTimeout(() => { busyTimers.delete(item.id); pump(); }, BUSY_RETRY_MS)); + return; + } + if (!response.ok) { + const refused = refusal(response.status, (body ?? {}) as { bound?: string; limit?: number }); + if (refused) update(item.id, { state: "refused", ...refused }); + else update(item.id, { state: "failed", status: "upload failed" }); + return; + } + const parsed = attachmentFileSchema.safeParse(body); + // A 2xx this client cannot read is not a stored file it knows: asking + // again with the same key returns it, so it is a retryable failure. + if (!parsed.success) { update(item.id, { state: "failed", status: "upload failed" }); return; } + items = items.filter((other) => other.id !== item.id); + notify(); + options.stored(item, parsed.data as AttachmentFile); + } catch { + if (controller.signal.aborted || !has(item.id)) return; + // No answer at all: the host may have stored it. Never "not stored". + if (!answered) update(item.id, { state: online ? "unknown" : "paused" }); + else update(item.id, { state: "failed", status: "upload failed" }); + } finally { + running.delete(item.id); + pump(); + } + } + + function pump() { + if (!online || disposed) return; + for (const item of items) { + if (running.size >= PARALLEL) break; + if (item.state !== "waiting" || running.has(item.id) || busyTimers.has(item.id)) continue; + const controller = new AbortController(); + running.set(item.id, controller); + void upload(item, controller); + } + } + + return { + get files(): readonly QueuedFile[] { return items; }, + /** + * Queue files for the draft `draftId`. `existing` is what that draft + * already holds (images and stored originals); `limits` the host's + * envelope. Files over it are not queued, and come back as one notice. + */ + add(incoming: readonly File[], draftId: string, existing: { count: number; bytes: number }, limits: AttachmentLimits | null): string[] { + const maxFiles = limits?.maxFiles ?? ATTACHMENT_MAX_FILES; + const maxFileBytes = limits?.maxFileBytes ?? ATTACHMENT_MAX_FILE_BYTES; + const maxTotal = limits?.maxTotalBytes ?? ATTACHMENT_MAX_TOTAL_BYTES; + let count = existing.count + items.length; + let bytes = existing.bytes + items.reduce((sum, item) => sum + item.file.size, 0); + let overCount = 0; + let overBytes = 0; + const tooLarge: string[] = []; + for (const file of incoming) { + if (file.size > maxFileBytes) { tooLarge.push(fileDisplayName(file.name)); continue; } + if (count >= maxFiles) { overCount++; continue; } + if (bytes + file.size > maxTotal) { overBytes++; continue; } + items = [...items, { id: crypto.randomUUID(), file, name: fileDisplayName(file.name), draftId, idempotencyKey: crypto.randomUUID(), state: online ? "waiting" : "paused" }]; + count++; + bytes += file.size; + } + const notices: string[] = []; + if (tooLarge.length) notices.push(`${tooLarge.join(", ")}: too large. Files can be up to ${limitBytes(maxFileBytes)} each.`); + if (overCount) notices.push(`Up to ${maxFiles} files per message. ${overCount} ${overCount === 1 ? "wasn't" : "weren't"} added.`); + if (overBytes) notices.push(`Files can be up to ${limitBytes(maxTotal)} together. ${overBytes} ${overBytes === 1 ? "wasn't" : "weren't"} added.`); + notify(); pump(); + return notices; + }, + /** Remove from the composer only. Nothing is claimed about what the host keeps. */ + remove(id: string) { + running.get(id)?.abort(); + clearTimeout(busyTimers.get(id)); + busyTimers.delete(id); + items = items.filter((item) => item.id !== id); + notify(); pump(); + }, + /** Retry a failure, or Upload again after no answer: the same bytes under the same key. */ + retry(id: string) { + const item = items.find((other) => other.id === id); + if (!item || !(item.state === "failed" || item.state === "unknown")) return; + update(id, { state: online ? "waiting" : "paused", status: undefined, detail: undefined }); + pump(); + }, + setOnline(value: boolean) { + online = value; + if (!value) { + for (const controller of running.values()) controller.abort(); + // A request that got no answer a moment before the page saw the drop + // was the drop's (#1013): it waits with the others, and each reconnect + // uploads it again once, under its same key (rev 5 §1). + items = items.map((item) => (item.state === "waiting" || item.state === "uploading" || item.state === "unknown" ? { ...item, state: "paused" } : item)); + } else { + items = items.map((item) => (item.state === "paused" ? { ...item, state: "waiting" } : item)); + } + notify(); pump(); + }, + dispose() { + disposed = true; + for (const controller of running.values()) controller.abort(); + for (const timer of busyTimers.values()) clearTimeout(timer); + }, + }; +} + +export type AttachmentQueue = ReturnType; diff --git a/packages/ui-react/src/lib/auth-lock.ts b/packages/ui-react/src/lib/auth-lock.ts index 5ae8e5fd93..a304ceddc2 100644 --- a/packages/ui-react/src/lib/auth-lock.ts +++ b/packages/ui-react/src/lib/auth-lock.ts @@ -1,6 +1,7 @@ import { createStore, type StoreApi } from "zustand/vanilla"; import type { BrainUiServices } from "../root.js"; import { disposeTracks } from "./draft-tracks.js"; +import { disposeFiles } from "./draft-files.js"; import { registerUpdateHold } from "./update-holds.js"; /** The ordered warm-auth transition (#1018, #578 §1). No account content is kept here. */ @@ -26,6 +27,7 @@ export function createAuthLock(root: BrainUiServices, lifecycle: { drop(): void; root.stores.connection.getState().setVpnStatus("unauthorized"); root.stores.drafts.getState().release(); disposeTracks(root); + disposeFiles(root); root.stores.file.getState().reset(); root.stores.graph.getState().reset(); root.stores.graph.clearSceneCache(); diff --git a/packages/ui-react/src/lib/draft-client.ts b/packages/ui-react/src/lib/draft-client.ts index b6061b5164..975b94fd9e 100644 --- a/packages/ui-react/src/lib/draft-client.ts +++ b/packages/ui-react/src/lib/draft-client.ts @@ -1,7 +1,7 @@ -import type { ClientMessage, Draft, ServerMessage, SessionDraftLimits } from "@schlessera/brain-ui-sdk/protocol"; +import { COMPOSER_FILES_CAPABILITY, type ClientMessage, type Draft, type ServerMessage, type SessionDraftLimits } from "@schlessera/brain-ui-sdk/protocol"; import type { BrainUiServices } from "../root.js"; import { createDraftApi, type DraftApi, type DraftCallResult } from "./draft-api.js"; -import { hasContent, type ComposerDraft, type DraftSend } from "../stores/draft-state.js"; +import { bindableFiles, hasContent, type ComposerDraft, type DraftSend } from "../stores/draft-state.js"; import type { PendingAttachment } from "./image-attachments.js"; import { moveTracks, removeTracks, trackKey } from "./draft-tracks.js"; @@ -162,7 +162,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt // The lost save created revision 1. A later one is another device's // edit since: never deleted unseen, it is a conflict on the empty draft. if (read.ok && read.value.revision > 1) { - drafts.setState((s) => (s.drafts[d.draftId] ? { drafts: { ...s.drafts, [d.draftId]: { ...s.drafts[d.draftId]!, uncertain: false, host: { revision: read.value.revision, edit: -1, sessionId: read.value.sessionId, attachmentIds: read.value.attachments.map((a) => a.attachmentId), updatedAt: read.value.updatedAt } } } } : s)); + drafts.setState((s) => (s.drafts[d.draftId] ? { drafts: { ...s.drafts, [d.draftId]: { ...s.drafts[d.draftId]!, uncertain: false, host: { revision: read.value.revision, edit: -1, sessionId: read.value.sessionId, attachmentIds: read.value.attachments.map((a) => a.attachmentId), ...(read.value.files ? { fileIds: read.value.files.map((f) => f.fileId) } : {}), updatedAt: read.value.updatedAt } } } } : s)); drafts.getState().conflictWith(d.draftId, read.value, true); return; } @@ -199,11 +199,17 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt uploads.set(attachment, result.value.attachmentId); drafts.getState().uploaded(d.draftId, attachment, result.value.attachmentId); } + // Only originals minted for this id can be bound here (#3155); one + // carried from another id waits to be chosen again, and is not listed. + const fileIds = bindableFiles(d).map((f) => f.file.fileId); const body = { // A save never moves a draft: a bound one stays its host session's until a bind. sessionId: d.host ? d.host.sessionId : d.sessionId, text: d.text, attachmentIds: d.attachments.map((a) => uploads.get(a)!), + // Listed whenever this revision or the last one binds any, so removing + // the last original unbinds it; omitted for a host without them. + ...(fileIds.length > 0 || (d.host?.fileIds?.length ?? 0) > 0 ? { fileIds } : {}), }; const ifMatch = d.host?.revision ?? 0; const fingerprint = JSON.stringify([ifMatch, body]); @@ -218,7 +224,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt bumpHost(d.draftId); drafts.getState().saved(d.draftId, { revision: result.value.revision, edit: d.edit, sessionId: body.sessionId, - attachmentIds: body.attachmentIds, updatedAt: result.value.updatedAt, + attachmentIds: body.attachmentIds, ...(body.fileIds ? { fileIds: body.fileIds } : {}), updatedAt: result.value.updatedAt, }, uploads); return; } @@ -371,7 +377,8 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt c.addUserMessage(key, send.text, send.message.source, send.attachments.length ? send.attachments.map((a) => ({ previewUrl: a.previewUrl, mediaType: a.attachment.mediaType })) : undefined, { requestId: send.requestId, ...(send.message.thinkingLevel !== undefined ? { thinkingLevel: send.message.thinkingLevel } : {}) }, - send.files?.length ? send.files : undefined); + send.files?.length ? send.files : undefined, + send.attachmentFiles?.length ? send.attachmentFiles.map((f) => f.file) : undefined); if (!(buffer?.isStreaming ?? false)) c.startAssistantMessage(key, undefined, send.requestId); } @@ -427,7 +434,9 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt hello(msg: Extract): void { if (disposed) return; const supported = msg.capabilities?.sessionDrafts === true; - drafts.getState().setSupport(supported, supported ? (msg.sessionDraftLimits as SessionDraftLimits | undefined) : undefined); + // Composer originals need durable drafts to bind them (#3155, design §9). + const files = supported && msg.capabilities?.[COMPOSER_FILES_CAPABILITY] === true ? msg.attachmentLimits ?? null : null; + drafts.getState().setSupport(supported, supported ? (msg.sessionDraftLimits as SessionDraftLimits | undefined) : undefined, files); if (!supported) return; failures.clear(); // A new connection is new evidence: what was full may have room now. diff --git a/packages/ui-react/src/lib/draft-files.ts b/packages/ui-react/src/lib/draft-files.ts new file mode 100644 index 0000000000..55cba5be91 --- /dev/null +++ b/packages/ui-react/src/lib/draft-files.ts @@ -0,0 +1,80 @@ +import type { AttachmentFile } from "@schlessera/brain-ui-sdk/protocol"; +import type { BrainUiServices } from "../root.js"; +import { apiBaseFor } from "./backend.js"; +import { createAttachmentQueue, type AttachmentQueue } from "./attachment-queue.js"; + +/** + * One root's generic upload queues, per composer view (#3155). + * + * A queue holds only files the host has not stored yet. A stored original + * goes straight into its draft (`ComposerDraft.files`), whose saved + * revision then binds it on the host; that, not the upload, is what can + * read as saved. What is still in a queue lives in this page only, so a + * reload or closing the tab while any queue holds a file asks the browser + * to confirm, as staged tracks do (#1150). + * + * Keyed as `trackKey` keys tracks: a session's view by its session id, so + * its queue survives the draft id rotating under it; the new-chat view by + * its draft's first id. + */ +type Entry = { queue: AttachmentQueue; listeners: Set<() => void> }; +type Registry = { entries: Map; leaving: ((event: BeforeUnloadEvent) => void) | null }; + +const registries = new WeakMap(); + +function registry(root: BrainUiServices): Registry { + let reg = registries.get(root.stores); + if (!reg) { reg = { entries: new Map(), leaving: null }; registries.set(root.stores, reg); } + return reg; +} + +function guardLeaving(reg: Registry) { + if (typeof window === "undefined") return; + const queued = [...reg.entries.values()].some((entry) => entry.queue.files.length > 0); + if (queued && !reg.leaving) { + reg.leaving = (event) => { event.preventDefault(); event.returnValue = ""; }; + window.addEventListener("beforeunload", reg.leaving); + } else if (!queued && reg.leaving) { + window.removeEventListener("beforeunload", reg.leaving); + reg.leaving = null; + } +} + +/** The stored original joins its draft: the draft's next save binds it. */ +function storedInto(root: BrainUiServices, sessionId: string | null, draftId: string, file: AttachmentFile) { + const drafts = root.stores.drafts.getState(); + 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 }] }); +} + +export function filesFor(root: BrainUiServices, key: string, sessionId: string | null): Entry { + const reg = registry(root); + let entry = reg.entries.get(key); + if (!entry) { + const listeners = new Set<() => void>(); + const created: Entry = { + queue: createAttachmentQueue({ + request: root.request, + apiBase: apiBaseFor(root.config), + resolveDraft: (draftId) => root.stores.drafts.getState().resolveId(draftId), + stored: (item, file) => storedInto(root, sessionId, item.draftId, file), + changed: () => { for (const l of listeners) l(); guardLeaving(reg); }, + }), + listeners, + }; + entry = created; + reg.entries.set(key, entry); + } + return entry; +} + +/** The root is going: every upload is aborted, and none starts another. */ +export function disposeFiles(root: BrainUiServices): void { + const reg = registries.get(root.stores); + if (!reg) return; + for (const entry of reg.entries.values()) entry.queue.dispose(); + reg.entries.clear(); + guardLeaving(reg); +} diff --git a/packages/ui-react/src/lib/local-work.ts b/packages/ui-react/src/lib/local-work.ts index b66312c25b..c80c7941f6 100644 --- a/packages/ui-react/src/lib/local-work.ts +++ b/packages/ui-react/src/lib/local-work.ts @@ -1,8 +1,9 @@ import { followDraftTarget } from "./draft-target.js"; import { createStore, type StoreApi } from "zustand/vanilla"; -import type { SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; +import type { AttachmentFile, SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; +import { attachmentFileSchema } from "@schlessera/brain-ui-sdk/schemas"; import type { BrainStores } from "../stores/create-stores.js"; -import { hasContent, type ComposerDraft, type LocalDraft } from "../stores/draft-state.js"; +import { hasContent, type ComposerDraft, type DraftFile, type LocalDraft } from "../stores/draft-state.js"; import { mintDraftId } from "./drafts.js"; import type { PendingAttachment } from "./image-attachments.js"; import { PartitionRefusedError, accountPartition, type LocalPartitions, type PartitionHandle, type PartitionWrite } from "./local-partitions.js"; @@ -125,7 +126,8 @@ function serializedDraft(value: unknown): string | undefined { const { deviceRevision: _revision, ...content } = value as StoredDraft; return JSON.stringify(content); } -const sameContent = (a: StoredDraft, b: StoredDraft): boolean => a.sessionId === b.sessionId && a.text === b.text && JSON.stringify(a.attachments) === JSON.stringify(b.attachments); +const sameContent = (a: StoredDraft, b: StoredDraft): boolean => a.sessionId === b.sessionId && a.text === b.text && JSON.stringify(a.attachments) === JSON.stringify(b.attachments) + && JSON.stringify(a.files ?? []) === JSON.stringify(b.files ?? []); type StoredContext = WorkContext & { v: 1 }; const isStr = (v: unknown): v is string => typeof v === "string"; @@ -141,6 +143,13 @@ export function parseDraft(raw: unknown): LocalDraft | null { if (!a || !isStr(a.data) || !isStr(a.mediaType) || !a.mediaType.startsWith("image/") || !isNum(a.bytes) || !isStr(a.name)) return null; attachments.push({ attachment: { data: a.data, mediaType: a.mediaType as PendingAttachment["attachment"]["mediaType"] }, previewUrl: `data:${a.mediaType};base64,${a.data}`, bytes: a.bytes, name: a.name }); } + // Originals are host references (#3155). One that does not parse is + // dropped on its own; the host's copy of the draft still lists it. + const files: DraftFile[] = []; + for (const f of Array.isArray(r.files) ? r.files : []) { + const parsed = f && isStr(f.lineage) ? attachmentFileSchema.safeParse(f.file) : null; + if (parsed?.success) files.push({ file: parsed.data as AttachmentFile, lineage: f.lineage }); + } const h = r.host; const host = h && isNum(h.revision) && isStrOrNull(h.sessionId ?? null) && isNum(h.updatedAt) && typeof h.clean === "boolean" ? { revision: h.revision, sessionId: h.sessionId ?? null, updatedAt: h.updatedAt, clean: h.clean } : null; @@ -148,7 +157,7 @@ export function parseDraft(raw: unknown): LocalDraft | null { // A malformed bind is dropped on its own, never the whole draft. const b = r.bind; const bind = b && isStr(b.sessionId) && isStr(b.requestId) ? { sessionId: b.sessionId, requestId: b.requestId } : null; - return { draftId: r.draftId, sessionId: r.sessionId ?? null, text: r.text, attachments, editedAt: r.editedAt, host, deviceOnly: r.deviceOnly === true, ...(r.deviceConflict && isStr(r.deviceConflict.otherId) && isStrOrNull(r.deviceConflict.sessionId) ? { deviceConflict: r.deviceConflict } : {}), + return { draftId: r.draftId, sessionId: r.sessionId ?? null, text: r.text, attachments, ...(files.length ? { files } : {}), editedAt: r.editedAt, host, deviceOnly: r.deviceOnly === true, ...(r.deviceConflict && isStr(r.deviceConflict.otherId) && isStrOrNull(r.deviceConflict.sessionId) ? { deviceConflict: r.deviceConflict } : {}), ...(r.uncertain === true ? { uncertain: true } : {}), ...(bind ? { bind } : {}) }; } @@ -179,6 +188,7 @@ export function storeDraft(d: ComposerDraft): StoredDraft { sessionId: d.sessionId, text: d.text, attachments: d.attachments.map((a) => ({ data: a.attachment.data, mediaType: a.attachment.mediaType, bytes: a.bytes, name: a.name })), + ...(d.files?.length ? { files: d.files.map((f) => ({ file: f.file, lineage: f.lineage })) } : {}), editedAt: d.editedAt, deviceOnly: d.deviceOnly === true, ...(d.deviceConflict ? { deviceConflict: d.deviceConflict } : {}), @@ -723,7 +733,7 @@ export function createLocalWork(options: LocalWorkOptions): LocalWork { const current = state.drafts[targetId]; const before = current?.text ?? ""; const base: ComposerDraft = current ?? { - draftId: targetId, sessionId: owner, text: "", attachments: [], editedAt: Date.now(), edit: 0, host: null, + draftId: targetId, sessionId: owner, text: "", attachments: [], files: [], editedAt: Date.now(), edit: 0, host: null, uploads: new Map(), failure: null, savingSince: null, conflict: null, uncertain: false, bind: null, }; const draft: ComposerDraft = { ...base, text: before ? `${before}\n${text}` : text, edit: base.edit + 1, deviceOnly: true }; diff --git a/packages/ui-react/src/lib/track-attachment.ts b/packages/ui-react/src/lib/track-attachment.ts index 8bcf2a6383..1b0ad33307 100644 --- a/packages/ui-react/src/lib/track-attachment.ts +++ b/packages/ui-react/src/lib/track-attachment.ts @@ -1,6 +1,7 @@ import type { AttachmentRowProps } from "@schlessera/brain-ui-kit"; -import type { SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; +import type { AttachmentFile, SharedFileMeta } from "@schlessera/brain-ui-sdk/protocol"; import { trackBytes } from "./track-uploads.js"; +import { fileKindLabel } from "./attachment-queue.js"; /** Sent-file facts only; the existing composer keeps its own queue controls. */ export function trackRowProps(file: SharedFileMeta): AttachmentRowProps { @@ -18,3 +19,19 @@ export function trackRowProps(file: SharedFileMeta): AttachmentRowProps { } return { kind: "doc", label, meta, tone: "neutral", actionIcon: "" }; } + +/** + * 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". + */ +export function attachmentRowProps(file: AttachmentFile): AttachmentRowProps { + if (file.kind === "track" && file.track && !file.trackRejected) return trackRowProps({ ...file.track, incomingName: file.incomingName ?? file.track.incomingName }); + 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: "" }; +} diff --git a/packages/ui-react/src/root.ts b/packages/ui-react/src/root.ts index d08ea8312c..458f1b211a 100644 --- a/packages/ui-react/src/root.ts +++ b/packages/ui-react/src/root.ts @@ -8,6 +8,7 @@ import { createBrainStores, type BrainStores } from "./stores/create-stores.js"; import { createWebSocketClient, dropConnectionContext, restoreConnectionContext } from "./connection.js"; import { createIndexedDbAnswerStorage, createMemoryAnswerStorage, type AnswerStorage } from "./lib/answer-delivery/storage.js"; import { createBrowserTabCoordinator, type TabCoordinator } from "./lib/answer-delivery/tabs.js"; +import { disposeFiles } from "./lib/draft-files.js"; import { disposeTracks, tracksFor, subscribeAllTracks, trackKey, trackRefs, stagedTrackViews } from "./lib/draft-tracks.js"; import { registerBuiltInUpdateHolds } from "./lib/update-holds.js"; import type { LocalCaptureSink } from "./voice/local-capture.js"; @@ -301,6 +302,7 @@ export function createRoot( // Previews of images still in a draft or a held send: nothing else will release them. stores.drafts.getState().release(); disposeTracks(services); + disposeFiles(services); answerTabs?.dispose(); stores.activity.dispose(); stores.graph.dispose(); diff --git a/packages/ui-react/src/stores/chat-slices/messages.ts b/packages/ui-react/src/stores/chat-slices/messages.ts index 716ade0925..b7ccfe8c54 100644 --- a/packages/ui-react/src/stores/chat-slices/messages.ts +++ b/packages/ui-react/src/stores/chat-slices/messages.ts @@ -36,7 +36,7 @@ export function createMessagesSlice(ctx: ChatSliceContext): MessagesSliceSlice { // createIfMissing: a user-initiated send must never be dropped, even when // the active session's buffer hasn't been materialized yet (cold start // racing the history replay). - addUserMessage: (key, text, source, attachments, effort, files) => + addUserMessage: (key, text, source, attachments, effort, files, attachmentFiles) => mutateBuffer( key, (chat) => ({ @@ -53,6 +53,7 @@ export function createMessagesSlice(ctx: ChatSliceContext): MessagesSliceSlice { source: source ?? "typed", ...effort, ...(files?.length ? { files } : {}), + ...(attachmentFiles?.length ? { attachmentFiles } : {}), ...(attachments && attachments.length > 0 ? { attachments, attachmentCount: attachments.length } : {}), diff --git a/packages/ui-react/src/stores/chat-slices/transcript.ts b/packages/ui-react/src/stores/chat-slices/transcript.ts index e572040902..29c73c23f3 100644 --- a/packages/ui-react/src/stores/chat-slices/transcript.ts +++ b/packages/ui-react/src/stores/chat-slices/transcript.ts @@ -323,6 +323,7 @@ function mergeLive(old: ChatMessage, m: ChatMessage): ChatMessage { retryOfTurnId: m.failure ? m.retryOfTurnId : base.retryOfTurnId, failureLive: m.failure ? undefined : base.failureLive, files: m.files ?? base.files, + attachmentFiles: m.attachmentFiles ?? base.attachmentFiles, blocks: m.blocks ?? base.blocks, id: old.id, timestamp: old.timestamp, isStreaming: true, turnId: m.turnId, streamTurnId: old.turnId ?? old.streamTurnId, diff --git a/packages/ui-react/src/stores/chat-state.ts b/packages/ui-react/src/stores/chat-state.ts index 6efc975bed..30faaa76e4 100644 --- a/packages/ui-react/src/stores/chat-state.ts +++ b/packages/ui-react/src/stores/chat-state.ts @@ -3,6 +3,7 @@ import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts import { createStore } from "zustand/vanilla"; import type { SharedFileMeta, + AttachmentFile, LocalExchange, MessageBlock, MessageLink, @@ -67,6 +68,8 @@ export interface ChatMessage { */ attachments?: MessageAttachment[]; files?: SharedFileMeta[]; + /** Composer originals the message named (#3155). Stored is not read: no read state is implied. */ + attachmentFiles?: AttachmentFile[]; /** Attachment count for history-loaded messages without preview data. */ attachmentCount?: number; /** @@ -431,7 +434,8 @@ export interface ChatState { source?: MessageSource, attachments?: MessageAttachment[], effort?: { requestId: string; thinkingLevel?: ThinkingLevel }, - files?: SharedFileMeta[] + files?: SharedFileMeta[], + attachmentFiles?: AttachmentFile[] ) => void; startAssistantMessage: (key: ChatKey, turnId?: string, requestId?: string) => void; appendText: (key: ChatKey, text: string) => void; diff --git a/packages/ui-react/src/stores/draft-state.ts b/packages/ui-react/src/stores/draft-state.ts index 0607f6d3e9..34f08dc388 100644 --- a/packages/ui-react/src/stores/draft-state.ts +++ b/packages/ui-react/src/stores/draft-state.ts @@ -4,6 +4,8 @@ import { type ClientMessage, type Draft, type DraftRef, + type AttachmentFile, + type AttachmentLimits, type SessionDraftLimits, type SharedFileMeta, } from "@schlessera/brain-ui-sdk/protocol"; @@ -36,6 +38,23 @@ type DraftSaveFailure = /** 507: the host keeps `limit` drafts, or bytes, already. */ | { kind: "full"; limit: number; bound: string }; +/** + * A composer original the host stored for a draft (#3155). `lineage` is the + * draft id it was uploaded to: the host binds a file only to that draft, so + * one carried to another id (a rotation, a kept copy) cannot be saved or + * sent there, and reads as needing to be chosen again. + */ +export interface DraftFile { + file: AttachmentFile; + lineage: string; +} + +const NO_FILES: readonly DraftFile[] = []; +/** A draft's originals; none when it was built without the field. */ +export const draftFiles = (d: Pick | undefined): readonly DraftFile[] => d?.files ?? NO_FILES; +/** The originals of a draft its own id can bind. */ +export const bindableFiles = (d: Pick): DraftFile[] => draftFiles(d).filter((f) => f.lineage === d.draftId); + /** What the host acknowledged for a draft: its revision, and the local edit it holds. */ interface DraftHostCopy { revision: number; @@ -43,6 +62,8 @@ interface DraftHostCopy { edit: number; sessionId: string | null; attachmentIds: string[]; + /** The originals this revision binds (#3155); absent on a host without composer files. */ + fileIds?: string[]; /** The host's `updatedAt` for this revision. */ updatedAt: number; } @@ -52,6 +73,12 @@ export interface ComposerDraft { sessionId: string | null; text: string; attachments: PendingAttachment[]; + /** + * Stored composer originals, in display order (#3155). Saved only when + * `host.fileIds` lists them. Optional: a draft built by older code or a + * kept device record has none; read it through `draftFiles`. + */ + files?: DraftFile[]; /** Local clock of the last change: the Sessions row's age and the compare sheet's time. */ editedAt: number; /** A locally accepted transcript waits for a user edit/send before host sync. */ @@ -94,6 +121,8 @@ export interface DraftSend { attachments: PendingAttachment[]; /** Track files the message referenced, as the transcript draws them. */ files?: SharedFileMeta[]; + /** Composer originals the message named in `attachmentRefs` (#3155). */ + attachmentFiles?: DraftFile[]; /** The staged track entries it carried, removed only once the host accepts it. */ tracks?: { key: string; ids: string[] }; /** The saved revision the message names, when it was sent from one. */ @@ -121,6 +150,8 @@ export interface LocalDraft { sessionId: string | null; text: string; attachments: PendingAttachment[]; + /** Stored originals, by reference (#3155): the bytes stay on the host. */ + files?: DraftFile[]; editedAt: number; /** A locally accepted transcript waits for a user edit/send before host sync. */ deviceOnly?: boolean; @@ -141,6 +172,8 @@ export interface DraftStoreState { /** `server_hello.capabilities.sessionDrafts`; null until a hello. */ supported: boolean | null; limits: SessionDraftLimits; + /** `server_hello.attachmentLimits` when the host keeps composer originals (`composerFiles`); else null. */ + fileLimits: AttachmentLimits | null; /** Host drafts to delete at a revision: a rotated-away id, or the losing side of a choice. */ orphans: Array<{ draftId: string; revision: number }>; @@ -163,7 +196,7 @@ export interface DraftStoreState { /** The draft a view shows: its session's, or `fresh`. Pure; mints nothing into state. */ idFor(sessionId: string | null): string; /** Change a draft's content; a draft emptied with nothing on the host is forgotten. */ - edit(draftId: string, sessionId: string | null, patch: { text?: string; attachments?: PendingAttachment[]; deviceOnly?: boolean }): void; + edit(draftId: string, sessionId: string | null, patch: { text?: string; attachments?: PendingAttachment[]; files?: DraftFile[]; deviceOnly?: boolean }): void; /** These previews belong to a transcript message now: never revoked here. */ transfer(attachments: readonly PendingAttachment[]): void; /** New chat: the new-chat view gets a fresh identity; the old draft stays where it is. */ @@ -206,7 +239,7 @@ export interface DraftStoreState { openDeviceVersion(draftId: string, kept?: LocalDraft): void; // The draft client's reports. - setSupport(supported: boolean, limits?: SessionDraftLimits): void; + setSupport(supported: boolean, limits?: SessionDraftLimits, fileLimits?: AttachmentLimits | null): void; saving(draftId: string, since: number | null): void; saved(draftId: string, copy: DraftHostCopy, uploads: ReadonlyMap): void; saveFailed(draftId: string, failure: DraftSaveFailure, uncertain?: boolean): void; @@ -242,23 +275,23 @@ const SETTLED_SENDS_KEPT = 16; */ export function holdsUnsaved(state: Pick): boolean { for (const d of Object.values(state.drafts)) { - if ((d.text.length > 0 || d.attachments.length > 0) && !(d.host !== null && d.host.edit === d.edit)) return true; + if (hasContent(d) && !(d.host !== null && d.host.edit === d.edit)) return true; // Emptied, with the host still holding it: the delete has not landed. // Or a save is out: its answer is still owed. - if (d.conflict || d.savingSince !== null || d.uncertain || (d.host !== null && d.text.length === 0 && d.attachments.length === 0)) return true; + if (d.conflict || d.savingSince !== null || d.uncertain || (d.host !== null && !hasContent(d))) return true; } return Object.values(state.sends).some((s) => s.state === "pending" || s.state === "unconfirmed"); } -export const hasContent = (d: Pick | undefined): boolean => - Boolean(d && (d.text.length > 0 || d.attachments.length > 0)); +export const hasContent = (d: (Pick & { files?: readonly DraftFile[] }) | undefined): boolean => + Boolean(d && (d.text.length > 0 || d.attachments.length > 0 || (d.files?.length ?? 0) > 0)); /** The draft's content is the revision the host acknowledged. */ const isClean = (d: ComposerDraft): boolean => d.host !== null && d.host.edit === d.edit; function blank(draftId: string, sessionId: string | null, now: number): ComposerDraft { return { - draftId, sessionId, text: "", attachments: [], editedAt: now, edit: 0, host: null, + draftId, sessionId, text: "", attachments: [], files: [], editedAt: now, edit: 0, host: null, uploads: new Map(), failure: null, savingSince: null, conflict: null, uncertain: false, bind: null, }; } @@ -269,6 +302,7 @@ function fromHost(draft: Draft): ComposerDraft { ...blank(draft.draftId, draft.sessionId, draft.updatedAt), text: draft.text, attachments, + files: (draft.files ?? []).map((file) => ({ file, lineage: draft.draftId })), // The host stores these images for this id already. uploads: new Map(attachments.map((a, i) => [a, draft.attachments[i]!.attachmentId])), host: hostCopy(draft, 0), @@ -276,7 +310,7 @@ function fromHost(draft: Draft): ComposerDraft { } function hostCopy(draft: Draft, edit: number): DraftHostCopy { - return { revision: draft.revision, edit, sessionId: draft.sessionId, attachmentIds: draft.attachments.map((a) => a.attachmentId), updatedAt: draft.updatedAt }; + return { revision: draft.revision, edit, sessionId: draft.sessionId, attachmentIds: draft.attachments.map((a) => a.attachmentId), ...(draft.files ? { fileIds: draft.files.map((f) => f.fileId) } : {}), updatedAt: draft.updatedAt }; } export function createDraftStore(options: { now?: () => number; revoke?: (url: string) => void } = {}) { @@ -364,7 +398,8 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s /** The content under a new id (attachments upload again), the old id left to delete. */ function rotate(d: ComposerDraft, sessionId: string | null): string { - const next: ComposerDraft = { ...blank(mintDraftId(), sessionId, now()), text: d.text, attachments: d.attachments, editedAt: d.editedAt, edit: 1, deviceOnly: d.deviceOnly, deviceConflict: d.deviceConflict }; + // Originals keep their lineage: the new id cannot bind them, so they read as needing to be chosen again. + const next: ComposerDraft = { ...blank(mintDraftId(), sessionId, now()), text: d.text, attachments: d.attachments, files: d.files, editedAt: d.editedAt, edit: 1, deviceOnly: d.deviceOnly, deviceConflict: d.deviceConflict }; successors.set(d.draftId, next.draftId); origins.set(next.draftId, origins.get(d.draftId) ?? d.draftId); set((state) => { @@ -407,7 +442,9 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s // cannot break the composer's. const returned = owned ? send.attachments : send.attachments.map((a) => ({ ...a, previewUrl: `data:${a.attachment.mediaType};base64,${a.attachment.data}` })); const attachments = [...returned, ...d.attachments.filter((a) => !send.attachments.includes(a))]; - const back = { ...d, text, attachments, edit: d.edit + 1, editedAt: now() }; + const sentFiles = send.attachmentFiles ?? []; + const files = [...sentFiles, ...draftFiles(d).filter((f) => !sentFiles.some((s) => s.file.fileId === f.file.fileId))]; + const back = { ...d, text, attachments, files, edit: d.edit + 1, editedAt: now() }; // One change: the content is back in the draft in the same state that // settles the send, so nothing observing the store ever sees neither. set((s) => ({ drafts: { ...s.drafts, [back.draftId]: back }, sends: settleSend(s.sends) })); @@ -425,6 +462,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s sends: {}, supported: null, limits: { ...SESSION_DRAFT_LIMITS }, + fileLimits: null, orphans: [], idFor(sessionId) { @@ -466,9 +504,10 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s const current = get().drafts[draftId] ?? blank(draftId, sessionId, now()); const text = patch.text ?? current.text; const attachments = patch.attachments ?? current.attachments; - if (text === current.text && attachments === current.attachments) return; + const files = patch.files ?? current.files; + if (text === current.text && attachments === current.attachments && files === current.files) return; if (patch.attachments) release(current.attachments, attachments); - put({ ...current, text, attachments, edit: current.edit + 1, editedAt: now(), deviceOnly: patch.deviceOnly === true, failure: current.failure?.kind === "unsaved" ? current.failure : null }); + put({ ...current, text, attachments, files, edit: current.edit + 1, editedAt: now(), deviceOnly: patch.deviceOnly === true, failure: current.failure?.kind === "unsaved" ? current.failure : null }); settle(draftId); }, @@ -503,7 +542,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s if (state.drafts[k.draftId] || successors.has(k.draftId) || retired.has(k.draftId)) continue; // An emptied draft comes back only while its deletion is owed to the // host, or while a lost first save may have left a copy there (#1214). - if (k.text.length === 0 && k.attachments.length === 0 && !(k.host && !k.host.clean) && !k.deviceConflict && !(k.uncertain && !k.host)) continue; + if (!hasContent(k) && !(k.host && !k.host.clean) && !k.deviceConflict && !(k.uncertain && !k.host)) continue; // A session whose draft this page already holds keeps that one. if (k.sessionId !== null && Object.values(state.drafts).some((d) => d.sessionId === k.sessionId && (hasContent(d) || d.host))) continue; // An id handed to the session before this arrived goes to it, as in @@ -517,9 +556,11 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s ...blank(k.draftId, k.sessionId, k.editedAt), deviceOnly: k.deviceOnly === true, deviceConflict: k.deviceConflict, text: k.text, attachments: k.attachments, + files: k.files ?? [], edit, // Its images upload again before the next save: the ids they had are not kept. - host: k.host ? { revision: k.host.revision, edit: k.host.clean ? edit : edit - 1, sessionId: k.host.sessionId, attachmentIds: [], updatedAt: k.host.updatedAt } : null, + // Originals are references the host already holds, so a clean copy lists them. + host: k.host ? { revision: k.host.revision, edit: k.host.clean ? edit : edit - 1, sessionId: k.host.sessionId, attachmentIds: [], ...(k.files?.length ? { fileIds: k.files.map((f) => f.file.fileId) } : {}), updatedAt: k.host.updatedAt } : null, // The draft client's uncertain-save and bind paths pick these up again (#1214). uncertain: k.uncertain === true && k.host === null, bind: k.bind ?? null, @@ -560,7 +601,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s if (other && (!preserveOther || !drafts[other.draftId])) { const edit = 1; const { uncertain: _uncertain, bind: _bind, ...content } = other; - drafts[other.draftId] = { ...blank(other.draftId, other.sessionId, other.editedAt), ...content, edit, + drafts[other.draftId] = { ...blank(other.draftId, other.sessionId, other.editedAt), ...content, files: content.files ?? [], edit, host: other.host ? { ...other.host, edit: other.host.clean ? edit : -1, attachmentIds: [] } : null }; } return { drafts, fresh: s.fresh === sourceId || s.fresh === liveId ? branchId : s.fresh }; @@ -572,7 +613,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s const edit = 1; // Another tab's pending reconciliation stays that tab's to finish. const { uncertain: _uncertain, bind: _bind, ...content } = kept; - const d = { ...blank(kept.draftId, kept.sessionId, kept.editedAt), ...content, edit, deviceEpoch: (current?.deviceEpoch ?? 0) + 1, + const d = { ...blank(kept.draftId, kept.sessionId, kept.editedAt), ...content, files: content.files ?? [], edit, deviceEpoch: (current?.deviceEpoch ?? 0) + 1, host: kept.host ? { ...kept.host, edit: kept.host.clean ? edit : -1, attachmentIds: [] } : null }; set(s => ({ drafts: { ...s.drafts, [kept.draftId]: d } })); }, @@ -602,8 +643,10 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s set((s) => ({ sends: pruneSends({ ...s.sends, [input.requestId]: send }) })); if (d) { const remaining = d.attachments.filter((a) => !input.attachments.includes(a)); + const sentFiles = input.attachmentFiles ?? []; + const files = draftFiles(d).filter((f) => !sentFiles.some((s) => s.file.fileId === f.file.fileId)); const text = d.text === consumedText ? "" : d.text; - put({ ...d, text, attachments: remaining, edit: d.edit + 1, editedAt: now(), deviceOnly: false }); + put({ ...d, text, attachments: remaining, files, edit: d.edit + 1, editedAt: now(), deviceOnly: false }); } return draftRef; }, @@ -718,8 +761,8 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s set((s) => ({ sends: { ...s.sends, [requestId]: next } })); }, - setSupport(supported, limits) { - set({ supported, limits: limits ? { ...limits } : { ...SESSION_DRAFT_LIMITS } }); + setSupport(supported, limits, fileLimits = null) { + set({ supported, limits: limits ? { ...limits } : { ...SESSION_DRAFT_LIMITS }, fileLimits: supported && fileLimits ? { ...fileLimits } : null }); }, saving(draftId, since) { @@ -794,7 +837,7 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s if (d.host && isClean(d) && !held(draftId)) { // Deleted or sent on another device, with nothing new here. release(d.attachments, []); - if (d.deviceConflict) rotate({ ...d, text: "", attachments: [], host: null, uploads: new Map() }, d.sessionId); + if (d.deviceConflict) rotate({ ...d, text: "", attachments: [], files: [], host: null, uploads: new Map() }, d.sessionId); else drop(draftId); return; } @@ -832,8 +875,10 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s if (local.conflict?.sameId && local.conflict.other.revision >= draft.revision) return; // The host holds exactly what is here (a save whose answer was lost): // that is an acknowledgement, not another device's version. + const hostFiles = draft.files ?? []; if (local.text === draft.text && local.attachments.length === draft.attachments.length - && local.attachments.every((a, i) => a.attachment.data === draft.attachments[i]!.bytes)) { + && local.attachments.every((a, i) => a.attachment.data === draft.attachments[i]!.bytes) + && draftFiles(local).length === hostFiles.length && draftFiles(local).every((f, i) => f.lineage === draft.draftId && f.file.fileId === hostFiles[i]!.fileId)) { // Bound on another device meanwhile: it is that session's draft here too. put({ ...local, sessionId: local.sessionId ?? draft.sessionId, host: hostCopy(draft, local.edit), uploads: new Map(local.attachments.map((a, i) => [a, draft.attachments[i]!.attachmentId])), failure: null, uncertain: false }); return; @@ -872,7 +917,8 @@ export function createDraftStore(options: { now?: () => number; revoke?: (url: s } if (choice === "both") { // The other version becomes an unbound Draft entry of its own. - const copy: ComposerDraft = { ...blank(mintDraftId(), null, now()), text: other.text, attachments: other.attachments.map(attachmentFromDraft), editedAt: other.updatedAt, edit: 1 }; + // Its originals stay the other draft's lineage: the copy shows them as needing to be chosen again. + const copy: ComposerDraft = { ...blank(mintDraftId(), null, now()), text: other.text, attachments: other.attachments.map(attachmentFromDraft), files: (other.files ?? []).map((file) => ({ file, lineage: other.draftId })), editedAt: other.updatedAt, edit: 1 }; put(copy); if (!sameId) orphan(other.draftId, other.revision); } else if (!sameId) { diff --git a/packages/ui-react/tests/attachment-queue.test.ts b/packages/ui-react/tests/attachment-queue.test.ts new file mode 100644 index 0000000000..23a8105e9d --- /dev/null +++ b/packages/ui-react/tests/attachment-queue.test.ts @@ -0,0 +1,133 @@ +import { expect, test } from "bun:test"; +import type { AttachmentFile } from "@schlessera/brain-ui-sdk/protocol"; +import { createAttachmentQueue, fileNameHeader, queuedFileCopy, storedFileCopy, type QueuedFile } from "../src/lib/attachment-queue.js"; + +// The generic composer queue (#3155, design §6.1, §8.4) against a fixture +// transport. Odysseus fixtures only; no network. + +const DRAFT = "6f1c2a4e-1d3b-4f6a-9c2e-0a7d5b3e9f10"; +async function settle(predicate: () => boolean, ms = 100) { const end = Date.now() + ms; while (Date.now() <= end) { if (predicate()) return; await Bun.sleep(1); } throw Error("The queue did not settle."); } +const permit = () => new File(["%PDF-1.7\nIthaca harbour permit: mooring fee, water levy\n%%EOF\n"], "ithaca-permit.pdf", { type: "application/pdf" }); +function stored(fileId: string, over: Partial = {}): AttachmentFile { + return { fileId, name: "ithaca-permit.pdf", path: `.brain-ui/attachments/${fileId}/ithaca-permit.pdf`, mediaType: "application/pdf", bytes: 56, sha256: "a".repeat(64), kind: "pdf", reader: "pdf", ...over }; +} +const FILE_ID = "0b6d2f3e-8c4a-4e1b-9f7d-2a5c6e8b1d30"; + +function harness(answer: (call: number, init: RequestInit, url: string) => Promise | Response) { + const calls: { url: string; init: RequestInit }[] = []; + const done: { item: QueuedFile; file: AttachmentFile }[] = []; + const queue = createAttachmentQueue({ + request: async (url, init) => { calls.push({ url, init: init! }); return answer(calls.length, init!, url); }, + apiBase: "/api", + stored: (item, file) => done.push({ item, file }), + changed: () => {}, + }); + return { queue, calls, done }; +} + +test("a PDF goes to the neutral draft route unfiltered, as its own raw bytes, and leaves the queue once stored", async () => { + const h = harness(() => Response.json(stored(FILE_ID), { status: 201 })); + try { + const file = permit(); + expect(h.queue.add([file], DRAFT, { count: 0, bytes: 0 }, null)).toEqual([]); + await settle(() => h.done.length === 1); + expect(h.calls).toHaveLength(1); + expect(h.calls[0]!.url).toBe(`/api/drafts/${DRAFT}/files`); + const headers = new Headers(h.calls[0]!.init.headers); + expect(headers.get("idempotency-key")).toMatch(/^[0-9a-f-]{36}$/); + expect(headers.get("x-file-name")).toBe("ithaca-permit.pdf"); + expect(headers.get("content-type")).toBe("application/pdf"); + expect(h.calls[0]!.init.body, "the original File, not a multipart form").toBe(file); + expect(h.done[0]!.file.fileId).toBe(FILE_ID); + expect(h.done[0]!.item.draftId).toBe(DRAFT); + expect(h.queue.files).toEqual([]); + } finally { h.queue.dispose(); } +}); + +test("a lost answer is unknown, never 'not stored'; the drop's reconnect uploads it again once under the same key", async () => { + const h = harness((call) => { if (call === 1) throw new TypeError("Failed to fetch"); return Response.json(stored(FILE_ID), { status: 201 }); }); + try { + h.queue.add([permit()], DRAFT, { count: 0, bytes: 0 }, null); + await settle(() => h.queue.files[0]?.state === "unknown"); + const copy = queuedFileCopy(h.queue.files[0]!); + expect(copy.status).toBe("checking upload…"); + expect(`${copy.status} ${copy.detail}`).not.toMatch(/not stored|nothing was stored/i); + h.queue.setOnline(false); + expect(h.calls).toHaveLength(1); + expect(h.queue.files[0]!.state, "it waits for the connection, with the others").toBe("paused"); + h.queue.setOnline(true); + await settle(() => h.done.length === 1); + expect(h.calls).toHaveLength(2); + const key = (n: number) => new Headers(h.calls[n]!.init.headers).get("idempotency-key"); + expect(key(1), "the re-upload replays the same key").toBe(key(0)); + // Stored now: a later reconnect asks nothing more. + h.queue.setOnline(false); h.queue.setOnline(true); + expect(h.calls).toHaveLength(2); + } finally { h.queue.dispose(); } +}); + +test("while connected, a lost answer waits for Upload again, which replays the same key; a busy host is asked again with it too", async () => { + // No automatic loop while the page is online: only Upload again asks. + const h = harness((call) => { + if (call === 1) throw new TypeError("Failed to fetch"); + if (call === 2) return Response.json({ error: "busy" }, { status: 503 }); + return Response.json(stored(FILE_ID), { status: 201 }); + }); + try { + h.queue.add([permit()], DRAFT, { count: 0, bytes: 0 }, null); + await settle(() => h.queue.files[0]?.state === "unknown"); + await Bun.sleep(20); + expect(h.calls, "nothing asks again on its own while connected").toHaveLength(1); + h.queue.retry(h.queue.files[0]!.id); + await settle(() => h.calls.length === 2 && h.queue.files[0]?.state === "waiting"); + // The busy host is asked again after its pause, not at once. + expect(h.calls).toHaveLength(2); + await settle(() => h.done.length === 1, 4_000); + const keys = h.calls.map((c) => new Headers(c.init.headers).get("idempotency-key")); + expect(new Set(keys).size).toBe(1); + } finally { h.queue.dispose(); } +}, 10_000); + +test("host refusals are known not stored and say why; a 5xx is a retryable failure", async () => { + const answers = [ + Response.json({ error: "ATTACHMENT_TOO_LARGE", message: "", limit: 25_000_000, bound: "file" }, { status: 413 }), + Response.json({ error: "ATTACHMENT_CAPACITY", message: "", limit: 1, bound: "pool" }, { status: 507 }), + Response.json({ error: "INTERNAL_ERROR" }, { status: 500 }), + ]; + const h = harness((call) => answers[call - 1]!); + try { + h.queue.add([permit(), permit(), permit()], DRAFT, { count: 0, bytes: 0 }, null); + await settle(() => h.queue.files.every((f) => f.state === "refused" || f.state === "failed")); + const [large, full, broken] = h.queue.files.map((f) => ({ state: f.state, ...queuedFileCopy(f) })); + expect(large).toMatchObject({ state: "refused", status: "too large", detail: "Files can be up to 25 MB each." }); + expect(full).toMatchObject({ state: "refused", status: "not stored · no space", detail: "This host's attachment space is full. Nothing was removed to make room." }); + expect(broken).toMatchObject({ state: "failed", status: "upload failed", detail: "Retrying is safe: it won't store a second copy." }); + } finally { h.queue.dispose(); } +}); + +test("files over the per-message envelope are not queued and come back as one batch notice", () => { + const h = harness(() => new Promise(() => {})); + try { + const notices = h.queue.add([permit(), permit(), permit()], DRAFT, { count: 8, bytes: 0 }, { maxFiles: 10, maxFileBytes: 25_000_000, maxTotalBytes: 50_000_000, poolBytes: 1 }); + expect(h.queue.files).toHaveLength(2); + expect(notices).toEqual(["Up to 10 files per message. 1 wasn't added."]); + } finally { h.queue.dispose(); } +}); + +test("stored chips: unread PDF/text says not read yet, no reader says so, a rejected track says so; never readable/processed/decoded/saved", () => { + const copies = [ + storedFileCopy(stored(FILE_ID)), + storedFileCopy(stored(FILE_ID, { name: "crew-list.txt", kind: "text", reader: "text", mediaType: "text/plain", bytes: 1_843 })), + storedFileCopy(stored(FILE_ID, { name: "sirens.m4a", kind: "binary", reader: "none", mediaType: "audio/mp4", bytes: 3_250_000 })), + storedFileCopy(stored(FILE_ID, { name: "dock-walk.json", kind: "text", reader: "text", mediaType: "application/json", trackRejected: true })), + ]; + expect(copies.map((c) => c.status)).toEqual(["PDF · 56 B · not read yet", "Text · 1.8 KB · not read yet", "3.1 MB · no reader here", "Text · not a usable track"]); + for (const copy of copies) expect(`${copy.status} ${copy.detail ?? ""}`).not.toMatch(/\b(readable|processed|decoded|saved)\b/i); +}); + +test("the file-name hint is percent-encoded and bounded to 1,024 encoded bytes", () => { + expect(fileNameHeader("Ἰθάκη.pdf")).toBe(encodeURIComponent("Ἰθάκη.pdf")); + const long = fileNameHeader(`${"Ὀδυσσεύς".repeat(80)}.pdf`); + expect(long.length).toBeLessThanOrEqual(1024); + expect(() => decodeURIComponent(long)).not.toThrow(); +}); diff --git a/packages/ui-react/tests/auth-expiry-runtime.test.ts b/packages/ui-react/tests/auth-expiry-runtime.test.ts index f4eab5a0fe..fd3fcd6c6a 100644 --- a/packages/ui-react/tests/auth-expiry-runtime.test.ts +++ b/packages/ui-react/tests/auth-expiry-runtime.test.ts @@ -7,7 +7,7 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { resolve } from "node:path"; import { deflateSync } from "node:zlib"; -import { chromium, type Browser, type Page } from "playwright"; +import { chromium, type Browser, type BrowserContext, type BrowserContextOptions, type Page } from "playwright"; import { createRecordingObservability, createStaticBackendRegistry, resolveServerConfig } from "@schlessera/brain-ui-server"; import { createFixtureApp as createApp } from "../../ui-server/tests/helpers/native-app-fixture.js"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; @@ -265,6 +265,33 @@ const field = (page: Page) => page.locator("textarea[data-composer]"); }, outcome); } let cell = 0; +/** + * A context whose host hello lacks `capabilities.composerFiles` and + * `attachmentLimits`, as an older host's would (design §9). The client then + * keeps D52's tab-only staged tracks, whose work-context snapshot these + * cases prove; on a host with composer files a track is a draft-bound + * original the host restores (#3155). + */ +async function legacyHostContext(options: BrowserContextOptions): Promise { + const context = await browser!.newContext(options); + await context.routeWebSocket("ws://127.0.0.1:*/**", (socket) => { + const host = socket.connectToServer(); + host.onMessage((message) => { + if (typeof message === "string" && message.includes('"server_hello"')) { + const frame = JSON.parse(message) as Record & { type: string; capabilities?: Record }; + if (frame.type === "server_hello") { + const { attachmentLimits: _limits, ...rest } = frame; + const { composerFiles: _files, ...capabilities } = frame.capabilities ?? {}; + socket.send(JSON.stringify({ ...rest, capabilities })); + return; + } + } + socket.send(message); + }); + }); + return context; +} + async function boot(page: Page) { // The container has no external network; localhost is reachable. Explicit // browser emulation makes its online hint agree with that real host path. @@ -292,8 +319,8 @@ async function expire(page: Page, kind: "401" | "1008" | "revoke") { } for (const kind of ["401", "1008"] as const) describe.skipIf(!executablePath)(`warm auth expiry ${kind} (#1018)`, () => { - test("capture ends; snapshot commits before unmount; same account restores all context without navigation", async () => { - const context = await browser!.newContext({viewport:{width:900,height:700}}); + test("on a host without composer files: capture ends; snapshot commits before unmount; same account restores all context without navigation", async () => { + const context = await legacyHostContext({viewport:{width:900,height:700}}); const page = await context.newPage(); try { await boot(page); @@ -445,8 +472,8 @@ describe.skipIf(!executablePath)("auth boundary failures and revocation (#1018)" describe.skipIf(!executablePath)("auth producer and identity races (#1018)",()=>{ - test("uploaded references in every inactive staged view survive same-account restoration",async()=>{ - const context=await browser!.newContext({viewport:{width:900,height:700}}); const page=await context.newPage(); + test("on a host without composer files, uploaded references in every inactive staged view survive same-account restoration",async()=>{ + const context=await legacyHostContext({viewport:{width:900,height:700}}); const page=await context.newPage(); try { await boot(page); const inactive:Array<{id:string;refs:unknown[]}>=[]; @@ -470,8 +497,8 @@ describe.skipIf(!executablePath)("auth producer and identity races (#1018)",()=> } } finally {await context.close();} },120_000); - test("restored uploaded reference bytes still govern the mixed composer budget",async()=>{ - const context=await browser!.newContext({viewport:{width:900,height:700}}); const page=await context.newPage(); + test("on a host without composer files, restored uploaded reference bytes still govern the mixed composer budget",async()=>{ + const context=await legacyHostContext({viewport:{width:900,height:700}}); const page=await context.newPage(); try { await boot(page); await page.locator('input[type="file"][accept^=".gpx"]').setInputFiles(resolve(scratch!,"ithaca.gpx")); await until(page,"f.tracks().length === 1"); @@ -515,8 +542,8 @@ describe.skipIf(!executablePath)("auth producer and identity races (#1018)",()=> expect(await fixture(page,f=>f.images())).toEqual([]); } finally {await context.close();} },120_000); - test("track-only New chat restores the same unbound composer identity",async()=>{ - const context=await browser!.newContext({viewport:{width:900,height:700}}); const page=await context.newPage(); + test("on a host without composer files, track-only New chat restores the same unbound composer identity",async()=>{ + const context=await legacyHostContext({viewport:{width:900,height:700}}); const page=await context.newPage(); try { await boot(page); await page.getByRole("button",{name:"New chat",exact:true}).click(); await until(page,"f.activeSessionId() === null"); diff --git a/packages/ui-react/tests/browser/composer-files.offline.tsx b/packages/ui-react/tests/browser/composer-files.offline.tsx new file mode 100644 index 0000000000..40537ead00 --- /dev/null +++ b/packages/ui-react/tests/browser/composer-files.offline.tsx @@ -0,0 +1,309 @@ +/// +/** + * Generic composer files in Chromium (#3155, design §8): the Files source, + * the neutral upload route, the §8.4 chip states, the draft binding of + * stored originals and the send that names them. + * + * The real Composer and the real draft client run against a fixture host + * that keeps #3153's rules in memory: one original per upload, minted for + * one draft id (its lineage), the same `fileId` for a repeated + * `Idempotency-Key`, and a save that binds only stored originals of its own + * draft. Native File, DataTransfer, change and paste events throughout. No + * key, no network. The real host routes are proved by ui-server's + * attachment tests. + */ +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 type { AttachmentFile, ClientMessage, Draft } from "@schlessera/brain-ui-sdk/protocol"; +import { Composer } from "../../src/components/chat/composer.js"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; +import { trackView } from "../track-fixtures.js"; + +const SESSION = "odysseus-ithaca"; + +/** The host's socket, driven by the test: hello and history arrive as the real client reads them. */ +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)); } +} +type Upload = { draftId: string; key: string; name: string; bytes: Uint8Array }; + +/** #3153's composer-file and draft rules, kept in memory. */ +function fileHost() { + const files = new Map(); + const keys = new Map(); + const rows = new Map(); + const uploads: Upload[] = []; + const saves: { draftId: string; fileIds?: string[] }[] = []; + /** Paths requested, in order. */ + const calls: string[] = []; + /** The next upload's answer is lost after the host stored it. */ + let dropNext = false; + /** The next upload is refused for space. */ + let fullNext = false; + let seq = 0; + const json = (body: unknown, status = 200) => Response.json(body, { status }); + function detect(name: string, draftId: string, fileId: string, bytes: number): AttachmentFile & { draftId: string } { + const path = `.brain-ui/attachments/${fileId}/${name}`; + const base = { fileId, name, path, bytes, sha256: fileId.replace(/-/g, "").padEnd(64, "0"), draftId }; + if (name.endsWith(".pdf")) return { ...base, mediaType: "application/pdf", kind: "pdf", reader: "pdf" }; + if (name.endsWith(".txt")) return { ...base, mediaType: "text/plain", kind: "text", reader: "text" }; + if (name.endsWith(".geojson")) return { ...base, mediaType: "application/geo+json", kind: "track", reader: "track", track: { ...trackView().file, path } }; + return { ...base, mediaType: "application/octet-stream", kind: "binary", reader: "none" }; + } + async function request(url: string, init: RequestInit = {}): Promise { + const path = new URL(url, "http://fixture.invalid").pathname; + calls.push(`${init.method ?? "GET"} ${path}`); + const headers = new Headers(init.headers); + const upload = /\/drafts\/([^/]+)\/files$/.exec(path); + if (upload) { + const draftId = decodeURIComponent(upload[1]!); + const key = headers.get("idempotency-key")!; + const bytes = new Uint8Array(await new Response(init.body as BodyInit).arrayBuffer()); + const name = decodeURIComponent(headers.get("x-file-name") ?? "file"); + uploads.push({ draftId, key, name, bytes }); + if (fullNext) { fullNext = false; return json({ error: "ATTACHMENT_CAPACITY", message: "", limit: 1, bound: "pool" }, 507); } + let fileId = keys.get(`${draftId}:${key}`); + if (!fileId) { + fileId = `00000000-0000-4000-8000-${String(++seq).padStart(12, "0")}`; + keys.set(`${draftId}:${key}`, fileId); + files.set(fileId, detect(name, draftId, fileId, bytes.byteLength)); + } + if (dropNext) { dropNext = false; throw new TypeError("Failed to fetch"); } + const { draftId: _lineage, ...file } = files.get(fileId)!; + return json(file, 201); + } + const draft = /\/drafts(?:\/([^/]+))?$/.exec(path); + if (draft) { + const id = draft[1] && decodeURIComponent(draft[1]); + if (!id) return json({ drafts: [] }); + const row = rows.get(id); + if ((init.method ?? "GET") === "GET") return row ? json(row) : json({ error: "DRAFT_NOT_FOUND", message: "" }, 404); + if (init.method === "DELETE") { rows.delete(id); return new Response(null, { status: 204 }); } + const body = JSON.parse(String(init.body)) as { sessionId: string | null; text: string; attachmentIds: string[]; fileIds?: string[] }; + saves.push({ draftId: id, fileIds: body.fileIds }); + if ((row?.revision ?? 0) !== Number(headers.get("if-match"))) return json({ error: "DRAFT_CONFLICT", message: "", current: row }, 409); + for (const fileId of body.fileIds ?? []) { + if (files.get(fileId)?.draftId !== id) return json({ error: "ATTACHMENT_INVALID", message: "A file is not stored for this draft; upload it again." }, 400); + } + const revision = (row?.revision ?? 0) + 1; + rows.set(id, { draftId: id, sessionId: body.sessionId, revision, updatedAt: Date.now(), text: body.text, attachments: [], + files: (body.fileIds ?? []).map((f) => { const { draftId: _l, ...file } = files.get(f)!; return file; }) }); + return json({ revision, updatedAt: Date.now() }); + } + return json({ providers: [], backends: {} }); + } + return { request, uploads, saves, calls, files, drop: () => { dropNext = true; }, fill: () => { fullNext = true; } }; +} + +const scenes: { host: HTMLDivElement; renderer: Root; root: BrainUiRoot }[] = []; +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's Chromium has no network, so `navigator.onLine` is false + * there and the queue would rightly wait for a connection. The fixture host is + * reachable, so each scene says online, and the complete own-property state of + * `navigator.onLine` is restored afterwards. + */ +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)) { flushSync(() => s.renderer.unmount()); s.root.dispose(); s.host.remove(); } + vi.unstubAllGlobals(); + restoreOnline(); +}); +afterAll(async () => { styles.remove(); await page.viewport(viewport.width, viewport.height); }); + +async function mount(width = 1280, height = 800) { + await page.viewport(width, height); + emulateOnline(); + const files = fileHost(); + const root = createBrainUiRoot({ storage: null, request: files.request }); + const frames: ClientMessage[] = []; + 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 }, + attachmentLimits: { maxFiles: 10, maxFileBytes: 25_000_000, maxTotalBytes: 50_000_000, poolBytes: 1_073_741_824 } }); + 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); + scenes.push({ host, renderer, root }); + flushSync(() => renderer.render( { frames.push(msg); return true; }} />)); + await new Promise((resolve) => setTimeout(resolve, 0)); + const field = () => host.querySelector("textarea")!; + 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 send = () => host.querySelector('[data-composer] [aria-label="Send"]')!.click(); + 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 messages = () => frames.filter((f): f is Extract => f.type === "chat_message"); + return { root, host, files, frames, field, chips, chip, status, send, draft, saved, messages }; +} +type Scene = Awaited>; + +const permit = () => new File(["%PDF-1.7\nIthaca harbour permit: mooring fee 3 obols, water levy 1 obol\n%%EOF\n"], "ithaca-permit.pdf", { type: "application/pdf" }); +const sirens = () => new File([new Uint8Array([0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x4d, 0x34, 0x41, 0x20])], "sirens.m4a", { type: "audio/mp4" }); +const loop = () => new File([JSON.stringify({ type: "LineString", coordinates: [[20.7, 38.4], [20.71, 38.41]] })], "ithaca-loop.geojson", { type: "" }); + +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 })); + return input; +} + +test("desktop offers one unrestricted Files action and paste-or-drop guidance, never Photo library, Camera or Track files", async () => { + const s = await mount(1280); + s.host.querySelector('[data-composer] [role="button"][aria-label^="Attach"]')!.click(); + await expect.poll(() => s.host.querySelector('[role="menu"][aria-label="Attach"]')).not.toBeNull(); + const menu = s.host.querySelector('[role="menu"][aria-label="Attach"]')!.textContent!; + expect(menu).toContain("Files…"); + expect(menu).toContain("Images, PDFs, tracks, any file"); + expect(menu).toContain("Paste or drop"); + for (const absent of ["Photo library", "Camera", "Track files", "GPX, KML or GeoJSON"]) expect(menu).not.toContain(absent); + const input = s.host.querySelector("input[data-files-input]")!; + expect(input.hasAttribute("accept"), "Files has no format allowlist").toBe(false); + expect(input.multiple).toBe(true); +}); + +test("a phone keeps Photo library and Camera beside unrestricted Files", async () => { + const s = await mount(320, 640); + s.host.querySelector('[data-composer] [role="button"][aria-label^="Attach"]')!.click(); + await expect.poll(() => document.querySelector('[data-overlay-site="attach"]')?.textContent ?? "").toContain("Files"); + const sheet = document.querySelector('[data-overlay-site="attach"]')!.textContent!; + for (const row of ["Photo library", "Camera", "Files", "Images, PDFs, tracks, any file", "Paste"]) expect(sheet).toContain(row); + expect(sheet).not.toContain("Track files"); + expect(sheet).not.toContain("Paste or drop"); +}); + +test("PDF, unknown binary and track go to the neutral route as their own bytes, show honest chips, and send as references of the saved revision", async () => { + const s = await mount(); + await userEvent.fill(s.field(), "Which harbour fees does the permit list?"); + const picked = [permit(), sirens(), loop()]; + const input = pickFiles(s, picked); + await expect.poll(() => input.value, { message: "the picker resets for the same file again" }).toBe(""); + await expect.poll(() => s.files.uploads.length, { timeout: 5_000 }).toBe(3); + for (const file of picked) { + const up = s.files.uploads.find((u) => u.name === file.name)!; + expect([...up.bytes], `${file.name} arrives byte for byte`).toEqual([...new Uint8Array(await file.arrayBuffer())]); + expect(up.draftId).toBe(s.draft()?.draftId ?? s.root.stores.drafts.getState().idFor(SESSION)); + } + expect(s.files.calls.some((c) => c.endsWith("/track-upload")), "no file goes through the track-only route").toBe(false); + await expect.poll(() => s.status("ithaca-permit.pdf")).toMatch(/^PDF · \d+ B · not read yet$/); + expect(s.chip("ithaca-permit.pdf")!.textContent).toContain("Your agent opens it when it needs the contents."); + await expect.poll(() => s.status("sirens.m4a")).toBe("12 B · no reader here"); + await expect.poll(() => s.status("ithaca-loop.geojson")).toMatch(/^Track · \d+ B · /); + for (const c of s.chips()) expect(c.textContent ?? "").not.toMatch(/\b(readable|processed|decoded|saved)\b/i); + // Saved means the host acknowledged this revision with all three bindings. + await expect.poll(() => s.saved(), { timeout: 5_000 }).toBe(true); + const bound = s.files.saves.at(-1)!.fileIds!; + expect(bound).toHaveLength(3); + s.send(); + expect(s.messages()).toHaveLength(1); + const frame = s.messages()[0]!; + expect(frame.attachmentRefs, "every stored original, the unreadable one included").toEqual(bound.map((fileId) => ({ kind: "attachment", fileId }))); + expect(frame.draftRef).toEqual({ draftId: s.files.saves.at(-1)!.draftId, revision: 1 }); + expect(frame.files, "no track-only staged reference").toBeUndefined(); + await expect.poll(() => s.chips().length).toBe(0); +}); + +test("Send pressed while a file uploads holds once, then sends that file after the save binds it", async () => { + const s = await mount(); + await userEvent.fill(s.field(), "Read the crew list before we sail."); + pickFiles(s, [new File(["Eurylochus\nPolites\nElpenor\n"], "crew-list.txt", { type: "text/plain" })]); + s.send(); + expect(s.messages(), "not sent before its file is stored and saved").toHaveLength(0); + await expect.poll(() => s.host.textContent ?? "").toMatch(/sends when (1 file finishes|the draft with its files is saved)/); + await expect.poll(() => s.messages().length, { timeout: 5_000 }).toBe(1); + expect(s.messages()[0]!.attachmentRefs).toHaveLength(1); + // The host resolves references against the revision the message names: + // the hold waits for the save that binds the file, never sends ahead of it. + expect(s.files.saves.length, "a save bound the file before the send").toBeGreaterThan(0); + expect(s.messages()[0]!.draftRef, "sent from the acknowledged revision that binds it").toEqual({ draftId: s.files.saves.at(-1)!.draftId, revision: s.files.saves.length }); + expect(s.files.saves.at(-1)!.fileIds).toEqual(s.messages()[0]!.attachmentRefs!.map((r) => r.fileId)); + await new Promise((resolve) => setTimeout(resolve, 1_200)); + expect(s.messages(), "the hold sends once").toHaveLength(1); +}); + +test("a lost upload answer reads as unconfirmed, and reconnecting uploads it again once under the same key, storing one file", async () => { + const s = await mount(); + s.files.drop(); + pickFiles(s, [permit()]); + await expect.poll(() => s.status("ithaca-permit.pdf")).toBe("checking upload…"); + const again = s.chip("ithaca-permit.pdf")!.querySelector('[aria-label="Upload again ithaca-permit.pdf"]'); + expect(again, "the action is an upload, never 'Check'").not.toBeNull(); + expect(again!.classList.contains("bk-hit"), "44px reach on a coarse pointer without a painted box").toBe(true); + expect(s.chip("ithaca-permit.pdf")!.textContent).not.toMatch(/not stored|nothing was stored|\bCheck\b/); + s.root.stores.connection.setState({ wsStatus: "disconnected" }); + await new Promise((resolve) => setTimeout(resolve, 0)); + s.root.stores.connection.setState({ wsStatus: "connected" }); + await expect.poll(() => s.status("ithaca-permit.pdf"), { timeout: 5_000 }).toMatch(/not read yet$/); + expect(s.files.uploads).toHaveLength(2); + expect(s.files.uploads[1]!.key).toBe(s.files.uploads[0]!.key); + expect(s.files.files.size, "one stored original").toBe(1); +}); + +test("a refused file blocks Send with a reason until removed; Remove moves focus to the next chip, and the rest sends", async () => { + const s = await mount(); + await userEvent.fill(s.field(), "Permit and crew list"); + s.files.fill(); + pickFiles(s, [permit(), new File(["Eurylochus\n"], "crew-list.txt", { type: "text/plain" })]); + await expect.poll(() => s.status("ithaca-permit.pdf")).toBe("not stored · no space"); + expect(s.chip("ithaca-permit.pdf")!.textContent).toContain("This host's attachment space is full. Nothing was removed to make room."); + await expect.poll(() => s.status("crew-list.txt")).toMatch(/not read yet$/); + s.send(); + expect(s.messages()).toHaveLength(0); + await expect.poll(() => s.host.textContent ?? "").toContain("Retry or remove the file that wasn't stored before sending."); + const remove = s.chip("ithaca-permit.pdf")!.querySelector('[aria-label="Remove ithaca-permit.pdf"]')!; + remove.focus(); + remove.click(); + await expect.poll(() => document.activeElement?.getAttribute("aria-label")).toBe("Remove crew-list.txt"); + await expect.poll(() => s.saved(), { timeout: 5_000 }).toBe(true); + s.send(); + expect(s.messages()).toHaveLength(1); + expect(s.messages()[0]!.attachmentRefs).toHaveLength(1); +}); + +test("pasted and dropped files take the same route as picked ones", async () => { + const s = await mount(); + const pasted = new DataTransfer(); pasted.items.add(permit()); + s.field().dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: pasted })); + const dropped = new DataTransfer(); dropped.items.add(sirens()); + s.host.querySelector("[data-composer]")!.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: dropped })); + await expect.poll(() => s.files.uploads.map((u) => u.name).sort(), { timeout: 5_000 }).toEqual(["ithaca-permit.pdf", "sirens.m4a"]); + expect(s.files.calls.some((c) => c.endsWith("/track-upload"))).toBe(false); +}); diff --git a/packages/ui-react/tests/connection-continuity-runtime.test.ts b/packages/ui-react/tests/connection-continuity-runtime.test.ts index f34e1a2feb..d4bfe817e1 100644 --- a/packages/ui-react/tests/connection-continuity-runtime.test.ts +++ b/packages/ui-react/tests/connection-continuity-runtime.test.ts @@ -385,7 +385,7 @@ async function finishRender(page: Page) { await page.evaluate(async () => { await document.fonts.ready; const frame = () => new Promise(done => requestAnimationFrame(() => done())); - const geometry = () => [...document.querySelectorAll("textarea[data-composer], [data-reading-column], [data-pill], [data-track-chip]")].map(el => { + const geometry = () => [...document.querySelectorAll("textarea[data-composer], [data-reading-column], [data-pill], [data-file-chip]")].map(el => { const rect = el.getBoundingClientRect(); return [rect.x, rect.y, rect.width, rect.height, el.parentElement?.scrollTop]; }); @@ -448,7 +448,9 @@ async function prepareScene(context: BrowserContext, cell: Cell): Promise const net: Net = { held: [], holdTracks: true, uploads: 0, sent: [], holdQueues: false, queues: [], trace: [] }; // Keep the real browser offline apart from this one local host. await context.route("**/*", (route) => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); - await context.route("**/api/track-upload", (route) => { + // 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). + await context.route("**/api/drafts/*/files", (route) => { net.uploads++; if (net.holdTracks) net.held.push(route); else void route.continue(); @@ -530,8 +532,8 @@ async function prepareScene(context: BrowserContext, cell: Cell): Promise await composer(page).fill(draft); 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[type="file"][accept*=".gpx"]').setInputFiles({ name: TRACK_NAME, mimeType: "application/geo+json", buffer: TRACK }); - await page.waitForFunction(() => /uploading/.test(document.querySelector("[data-track-chip]")?.getAttribute("aria-label") ?? "")); + 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.locator('[data-draft-save="saved"]').waitFor(); await hostUntil((d) => d.some((x) => x.sessionId === A && x.attachmentCount === 1 && x.preview === draft)); @@ -645,7 +647,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-track-chip]")?.getAttribute("aria-label") ?? "", + track: document.querySelector("[data-file-chip]")?.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, @@ -661,7 +663,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-track-chip]")?.getAttribute("aria-label") ?? "")); + if (uploading.length) await s.page.waitForFunction(() => !/uploading/.test(document.querySelector("[data-file-chip]")?.getAttribute("aria-label") ?? "")); await probe(s.page, p => p.backoff.pause()); server!.stop(true); const beforeOffline = await connectivity(s.page); @@ -1148,8 +1150,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-track-chip]")?.getAttribute("aria-label") ?? "")); - else await page.waitForFunction(() => /uploading/.test(document.querySelector("[data-track-chip]")?.getAttribute("aria-label") ?? "")); + 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") ?? "")); expect(net.uploads, `cycle ${cycle}: the upload resumed after reconnect`).toBe(uploadsBefore + 1); const after = await measure(page); log.push({ cycle, phase: "after", ...after }); diff --git a/packages/ui-react/tests/draft-files.test.ts b/packages/ui-react/tests/draft-files.test.ts new file mode 100644 index 0000000000..8e9683b809 --- /dev/null +++ b/packages/ui-react/tests/draft-files.test.ts @@ -0,0 +1,113 @@ +import { afterEach, expect, test } from "bun:test"; +import type { AttachmentFile, Draft, DraftSaveRequest, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { createBrainUiRoot, type BrainUiRoot } from "../src/root.ts"; +import { createDraftClient } from "../src/lib/draft-client.ts"; +import type { DraftApi } from "../src/lib/draft-api.ts"; +import { parseDraft, storeDraft } from "../src/lib/local-work.ts"; +import { holdsUnsaved } from "../src/stores/draft-state.ts"; + +// Composer originals as draft content (#3155): a stored original is bound by +// the draft's save, reads as saved only once the host acknowledged a +// revision listing it, and goes with the send that names it. Odysseus +// fixtures, an in-memory host, no network. + +const roots: BrainUiRoot[] = []; +afterEach(() => { for (const r of roots.splice(0)) r.dispose(); }); +const SESSION = "odysseus-ithaca"; +function original(fileId: string, name = "ithaca-permit.pdf"): AttachmentFile { + return { fileId, name, path: `.brain-ui/attachments/${fileId}/${name}`, mediaType: "application/pdf", bytes: 2_400_000, sha256: "b".repeat(64), kind: "pdf", reader: "pdf" }; +} +const PERMIT = original("2c7e1a90-5d3f-4b8e-a1c6-9f0d2e4b7a31"); +const CREW = original("7a1f3c5e-2b4d-4e6f-8a0c-1d3e5f7a9b20", "crew-list.txt"); + +function scene() { + const saves: { draftId: string; body: DraftSaveRequest }[] = []; + let revision = 0; + let answer: "ok" | "silent" = "ok"; + const api: DraftApi = { + list: async () => ({ ok: true, value: { drafts: [] } }), + get: async () => ({ ok: false, status: 404, body: {} }), + save: async (draftId, _ifMatch, _key, body) => { + saves.push({ draftId, body }); + if (answer === "silent") return { ok: false, status: 0, body: {} }; + return { ok: true, value: { revision: ++revision, updatedAt: 1_000 + revision } }; + }, + upload: async () => ({ ok: true, value: { attachmentId: "att-1" } }), + remove: async () => ({ ok: true, value: null }), + bind: async () => ({ ok: true, value: { revision: ++revision } }), + }; + const ui = createBrainUiRoot({ storage: null, request: async () => Response.json({}) }); + roots.push(ui); + const client = createDraftClient(ui, { send: () => true, api }); + client.hello({ type: "server_hello", protocolRev: 5, capabilities: { sessionDrafts: true, chatRequestAck: true, composerFiles: true }, + attachmentLimits: { maxFiles: 10, maxFileBytes: 25_000_000, maxTotalBytes: 50_000_000, poolBytes: 1_073_741_824 } } as Extract); + const drafts = ui.stores.drafts; + const id = drafts.getState().idFor(SESSION); + return { ui, drafts, id, saves, silence: () => { answer = "silent"; } }; +} +const pause = () => Bun.sleep(900); + +test("a hello with composerFiles exposes the host's file limits; without it there are none", () => { + const s = scene(); + expect(s.drafts.getState().fileLimits).toEqual({ maxFiles: 10, maxFileBytes: 25_000_000, maxTotalBytes: 50_000_000, poolBytes: 1_073_741_824 }); + s.drafts.getState().setSupport(true, undefined, null); + expect(s.drafts.getState().fileLimits).toBeNull(); +}); + +test("a stored original is saved as a fileIds binding, and reads as saved only after the host acknowledges that revision", async () => { + const s = scene(); + s.drafts.getState().edit(s.id, SESSION, { text: "Which harbour fees does the permit list?", files: [{ file: PERMIT, lineage: s.id }] }); + expect(holdsUnsaved(s.drafts.getState()), "unacknowledged files are at risk").toBe(true); + await pause(); + expect(s.saves).toHaveLength(1); + expect(s.saves[0]!.body.fileIds).toEqual([PERMIT.fileId]); + const d = s.drafts.getState().drafts[s.id]!; + expect(d.host?.fileIds).toEqual([PERMIT.fileId]); + expect(d.host?.edit).toBe(d.edit); + expect(holdsUnsaved(s.drafts.getState())).toBe(false); +}); + +test("a save that gets no answer never acknowledges the binding", async () => { + const s = scene(); + s.silence(); + s.drafts.getState().edit(s.id, SESSION, { files: [{ file: PERMIT, lineage: s.id }] }); + await pause(); + const d = s.drafts.getState().drafts[s.id]!; + expect(s.saves[0]!.body.fileIds).toEqual([PERMIT.fileId]); + expect(d.host).toBeNull(); + expect(holdsUnsaved(s.drafts.getState())).toBe(true); +}); + +test("a file of another draft id is never listed; removing the last original unbinds it with an empty list", async () => { + const s = scene(); + s.drafts.getState().edit(s.id, SESSION, { text: "Crew list for Ithaca", files: [{ file: PERMIT, lineage: s.id }, { file: CREW, lineage: "a-rotated-away-draft" }] }); + await pause(); + expect(s.saves.at(-1)!.body.fileIds).toEqual([PERMIT.fileId]); + s.drafts.getState().edit(s.id, SESSION, { files: [] }); + await pause(); + expect(s.saves.at(-1)!.body.fileIds, "the host is told to drop the binding").toEqual([]); +}); + +test("a send takes exactly its originals out of the draft; the content comes back when the frame never left", async () => { + const s = scene(); + s.drafts.getState().edit(s.id, SESSION, { text: "Read the permit", files: [{ file: PERMIT, lineage: s.id }] }); + await pause(); + const store = s.drafts.getState(); + const message = { type: "chat_message" as const, text: "Read the permit", sessionId: SESSION, requestId: "req-permit", attachmentRefs: [{ kind: "attachment" as const, fileId: PERMIT.fileId }] }; + const ref = store.beginSend({ requestId: "req-permit", draftId: s.id, sessionId: SESSION, text: "Read the permit", attachments: [], attachmentFiles: [{ file: PERMIT, lineage: s.id }], message }, "Read the permit"); + expect(ref, "a clean revision is named").toEqual({ draftId: s.id, revision: 1 }); + expect(s.drafts.getState().drafts[s.id]!.files).toEqual([]); + s.drafts.getState().sendFailed("req-permit"); + expect(s.drafts.getState().drafts[s.id]!.files!.map((f) => f.file.fileId)).toEqual([PERMIT.fileId]); +}); + +test("a host draft restores its originals with this id's lineage, and a device copy keeps them", () => { + const s = scene(); + const hostDraft: Draft = { draftId: "4e2a6c8d-0f1b-4d3e-9a5c-7b9d1f3e5a70", sessionId: "odysseus-raft", revision: 3, updatedAt: 5_000, text: "Raft lashing plan", attachments: [], files: [PERMIT] }; + s.drafts.getState().restore(hostDraft); + const d = s.drafts.getState().drafts[hostDraft.draftId]!; + expect(d.files).toEqual([{ file: PERMIT, lineage: hostDraft.draftId }]); + expect(d.host?.fileIds).toEqual([PERMIT.fileId]); + const kept = parseDraft(JSON.parse(JSON.stringify(storeDraft(d)))); + expect(kept?.files).toEqual([{ file: PERMIT, lineage: hostDraft.draftId }]); +}); diff --git a/packages/ui-react/tests/parallel-sessions-runtime.test.ts b/packages/ui-react/tests/parallel-sessions-runtime.test.ts index 658130c8a5..3eeae005f5 100644 --- a/packages/ui-react/tests/parallel-sessions-runtime.test.ts +++ b/packages/ui-react/tests/parallel-sessions-runtime.test.ts @@ -371,9 +371,36 @@ type ApprovalInput = { type: string; target: string | null; at: number; node: nu type ApprovalFrame = { event: "framesent" | "framereceived"; socket: number; at: number; frame: ClientMessage | ServerMessage }; type ProfileRead = { path: string; status?: number; body?: string; failure?: string }; type Device = { profileReads: ProfileRead[]; context: BrowserContext; page: Page; dialogs: string[]; sockets: string[]; approvals: ApprovalFrame[] }; -async function device(run: Run, opts: { clock?: boolean; update?: boolean } = {}): Promise { +/** + * Without composer files: the real host's hello reaches the page without + * `capabilities.composerFiles` and `attachmentLimits`, as an older host's + * would (design §9, "new client, old host"). The client then keeps D52's + * tab-only staged-track path, which the cases that prove it (#1112, #1150) + * need; on a host with composer files a track is a draft-bound original + * instead (#3155). + */ +async function withoutComposerFiles(context: BrowserContext) { + await context.routeWebSocket(`${origin.replace("http", "ws")}/**`, (socket) => { + const host = socket.connectToServer(); + host.onMessage((message) => { + if (typeof message === "string" && message.includes('"server_hello"')) { + const frame = JSON.parse(message) as Record & { type: string; capabilities?: Record }; + if (frame.type === "server_hello") { + const { attachmentLimits: _limits, ...rest } = frame; + const { composerFiles: _files, ...capabilities } = frame.capabilities ?? {}; + socket.send(JSON.stringify({ ...rest, capabilities })); + return; + } + } + socket.send(message); + }); + }); +} + +async function device(run: Run, opts: { clock?: boolean; update?: boolean; legacyHost?: boolean } = {}): Promise { const context = await browser!.newContext(run.options); await context.route("**/*", (route) => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); + if (opts.legacyHost) await withoutComposerFiles(context); // The whole app applies the root's stored theme to the document, so the // run's theme is stored under the fixture root's prefix before it loads. await context.addInitScript((theme) => { @@ -1302,9 +1329,9 @@ describe.skipIf(!executablePath)("mounted parallel sessions", () => { } }, 240_000); - test(`${run.name}: a new chat holding only a staged track stays reachable through New chat and sends nothing; removing its track ends the entry (#1112)`, async () => { + test(`${run.name}: on a host without composer files, a new chat holding only a staged track stays reachable through New chat and sends nothing; removing its track ends the entry (#1112)`, async () => { const tag = `(${run.name})`; - const a = await device(run); + const a = await device(run, { legacyHost: true }); const plan = `Plan: Route to Pylos ${tag}`; const name = "ithaca-to-pylos-coastal-route-day-3.geojson"; const route = Buffer.from(JSON.stringify({ type: "FeatureCollection", features: [{ type: "Feature", properties: { name: "Ithaca to Pylos" }, geometry: { type: "LineString", coordinates: [[20.71, 38.37], [20.95, 38.1], [21.3, 37.6], [21.69, 37.03]] } }] })); @@ -1389,7 +1416,7 @@ const leaveRuns: Run[] = [ { name: "1280 desktop, light, fine pointer", theme: "light", options: { viewport: { width: 1280, height: 800 } } }, ]; -describe.skipIf(!executablePath)("a staged track guards the tab it lives in", () => { +describe.skipIf(!executablePath)("on a host without composer files, a staged track guards the tab it lives in", () => { const name = "ithaca-to-pylos-coastal-route-day-3.geojson"; const route = Buffer.from(JSON.stringify({ type: "FeatureCollection", features: [{ type: "Feature", properties: { name: "Ithaca to Pylos" }, geometry: { type: "LineString", coordinates: [[20.71, 38.37], [20.95, 38.1], [21.3, 37.6], [21.69, 37.03]] } }] })); const remove = (page: Page) => page.getByRole("button", { name: `Remove ${name}`, exact: true }); @@ -1444,7 +1471,7 @@ describe.skipIf(!executablePath)("a staged track guards the tab it lives in", () for (const run of leaveRuns) for (const ending of ["removed", "sent"] as const) { test(`${run.name}: a reload asks while A holds a staged track out of view, and not once it is ${ending}`, async () => { const tag = `(${run.name}, leave, ${ending})`; - const a = await device(run, { update: true }); + const a = await device(run, { update: true, legacyHost: true }); try { // Nothing staged: nothing asked. await press(run, composer(a.page)); @@ -1467,7 +1494,7 @@ describe.skipIf(!executablePath)("a staged track guards the tab it lives in", () test(`${run.name}: a waiting update holds while A holds a staged track, then reloads once without asking when it is ${ending}`, async () => { const tag = `(${run.name}, update, ${ending})`; - const a = await device(run, { update: true }); + const a = await device(run, { update: true, legacyHost: true }); try { const id = await stageInA(run, a, tag); const before = await loads(a.page); diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index 03f56a2860..b11ad461bb 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -14,6 +14,8 @@ const helperConsumers:Record={ "packages/ui-react/src/ws-client/inbound.ts":"b66c9fc53d5fdf3418f290331d2cdbf4d8a24d4f7767fbcf152a5ccd79041a8d", "packages/ui-react/src/hooks/use-websocket.ts":"6edd8b289fa4dcf7f0a512ce1275bd9e9c70661ce5630e22503b4b1d888cf557" }; +// Re-audited for #3155: chat.ts only gained `attachmentFiles` in its history +// message mapping; chatFrameHandlers and its dispatch are unchanged. const declarations=[ { "owner": "packages/ui-react/src/hooks/websocket-handlers/index.ts", @@ -24,7 +26,7 @@ const declarations=[ { "owner": "packages/ui-react/src/hooks/websocket-handlers/chat.ts", "name": "chatFrameHandlers", - "source": "5c314921924458ce67f6a815553740b3828b447a2b34031f222745fdfb3bd15c" + "source": "7293732dfe85e43815c013e86af467a6d57c33d0eb8232310938ed3a6d5e3048" }, { "owner": "packages/ui-react/src/hooks/websocket-handlers/activity.ts", From 76621b2f53262123adf29fd1fe7d51ad1229d2b7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 6 Nov 2026 14:47:28 +0100 Subject: [PATCH 3/3] CONTRACT: feat(ui-server): deliver recorded attachment reads to the browser (#3589) (#3652) * CONTRACT: feat(ui-server): deliver recorded attachment reads to the browser (#3589) The `attachment_reads` records #3154 keeps reach a client two ways, both behind the new `server_hello.capabilities.attachmentReads`: - `GET /api/sessions/:id/attachment-reads` returns a session's recorded reads ({ fileId, turnId, outcome, scope, at }, never text) of the originals its messages still name, under the history replay's authority. - A read recorded during a live turn reaches connections that declared the flag as one `attachment_read` frame, sent with sendToCapable, so it never joins a transcript, the dialogue or provider history. The SDK adds ATTACHMENT_READS_CAPABILITY, AttachmentReadEntry, SessionAttachmentReadsResponse, ServerAttachmentRead and their schemas; the React client's frame map accepts the frame without declaring the flag. Refs #3589 Co-Authored-By: Claude Opus 5.5 * test(ui-sdk): add the attachment_read frame to the server frame inventory (#3589) Co-Authored-By: Claude Opus 5.5 * chore(ui-react): re-audit the connection frame handler map for attachment_read (#3589) Co-Authored-By: Claude Opus 5.5 * CONTRACT: docs(http): classify GET /api/sessions/:id/attachment-reads in the HTTP inventory (#3589) The ready proof's http-inventory test found the new route missing from the classified specification. Add it as a supported (S) row, raise both declared-endpoint counts to 174, add its coverage-matrix row under the session-drafts checks (X) with the delivery test as its detailed check, and give it a mounted-handler check and an explicit shared lifetime (an unknown session's empty read, no write, record or backend). Refs #3589 Co-Authored-By: Claude Opus 5.5 * test(ui-server): give the attachment-read delivery test a wall-clock turn deadline (#3589) A loaded host slowed one PDF-reading turn past the 2 s iteration budget after the epic merge. Wait up to 20 s of wall clock instead. Move the coverage matrix's citations this PR's test edits shifted: the delivery test and checkHandler. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .changeset/attachment-reads-delivery.md | 6 + api-report/ui-sdk.txt | 119 ++++++++++++- docs/decisions/chat-attachments.md | 10 ++ docs/http-api-coverage.md | 4 +- docs/http-api.md | 32 +++- docs/integration-contract.md | 13 ++ docs/integration-contract/wire.md | 25 +++ .../hooks/websocket-handlers/connection.ts | 6 +- packages/ui-sdk/src/protocol.ts | 46 ++++- packages/ui-sdk/src/schemas.ts | 24 +++ packages/ui-sdk/tests/server-schemas.test.ts | 4 + packages/ui-server/src/app.ts | 3 + packages/ui-server/src/attachments/read.ts | 5 +- packages/ui-server/src/attachments/store.ts | 15 +- packages/ui-server/src/drafts/store.ts | 8 +- .../ui-server/src/routes/attachment-reads.ts | 31 ++++ .../src/ws/bridge-capabilities/attachments.ts | 21 ++- packages/ui-server/src/ws/connection.ts | 5 +- .../tests/attachment-reads-delivery.test.ts | 159 ++++++++++++++++++ .../tests/helpers/http-mount-lifetimes.ts | 1 + .../tests/http-supported-mounts.test.ts | 1 + scripts/source-browser-dispatch.ts | 4 +- 22 files changed, 526 insertions(+), 16 deletions(-) create mode 100644 .changeset/attachment-reads-delivery.md create mode 100644 packages/ui-server/src/routes/attachment-reads.ts create mode 100644 packages/ui-server/tests/attachment-reads-delivery.test.ts diff --git a/.changeset/attachment-reads-delivery.md b/.changeset/attachment-reads-delivery.md new file mode 100644 index 0000000000..9d4d4a2823 --- /dev/null +++ b/.changeset/attachment-reads-delivery.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": patch +--- +Deliver recorded attachment reads to the browser so sent files can show what the agent read (#3589). A host with composer files advertises `server_hello.capabilities.attachmentReads`, answers `GET /api/sessions/:id/attachment-reads` with the recorded `read_attachment` calls of the originals a session's messages name (`{ fileId, turnId, outcome, scope, at }`, never text), and sends one `attachment_read` frame per read recorded during a live turn to connections that declared the flag. Nothing of either reaches a provider. The SDK adds `ATTACHMENT_READS_CAPABILITY`, `AttachmentReadEntry`, `SessionAttachmentReadsResponse`, `ServerAttachmentRead` and their schemas; the React client accepts the new frame without declaring the flag. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index b0dfde713e..7aeb8df647 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -14,6 +14,7 @@ export "." (./src/index.ts) ATTACHMENT_MAX_FILE_BYTES ATTACHMENT_MAX_TOTAL_BYTES ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_READS_CAPABILITY ATTACHMENT_UNBOUND_TTL_MS type ActionDigestEntry type ActionDigestState @@ -79,6 +80,7 @@ export "." (./src/index.ts) type AttachmentFile type AttachmentKind type AttachmentLimits + type AttachmentReadEntry type AttachmentReader type BillingMode type BrainSearchResult @@ -330,6 +332,7 @@ export "." (./src/index.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerAttachmentRead type ServerChatRetired type ServerConversationClosed type ServerConversationEvent @@ -369,6 +372,7 @@ export "." (./src/index.ts) type ServerToolUseStart type ServerTurnJournal type ServerUsage + type SessionAttachmentReadsResponse type SessionDraftLimits type SessionHistoryMessage type SessionRecovery @@ -518,6 +522,7 @@ export "./client" (./src/client/index.ts) ATTACHMENT_MAX_FILE_BYTES ATTACHMENT_MAX_TOTAL_BYTES ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_READS_CAPABILITY ATTACHMENT_READ_MAX_CALL_BYTES ATTACHMENT_READ_MAX_PAGES ATTACHMENT_READ_MAX_TURN_BYTES @@ -603,6 +608,7 @@ export "./client" (./src/client/index.ts) type AttachmentFile type AttachmentKind type AttachmentLimits + type AttachmentReadEntry type AttachmentReadFailure type AttachmentReadOutcome type AttachmentReadResult @@ -969,6 +975,7 @@ export "./client" (./src/client/index.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerAttachmentRead type ServerChatRetired type ServerConversationClosed type ServerConversationEvent @@ -1009,6 +1016,7 @@ export "./client" (./src/client/index.ts) type ServerToolUseStart type ServerTurnJournal type ServerUsage + type SessionAttachmentReadsResponse type SessionDraftLimits type SessionHistoryMessage type SessionRecovery @@ -1430,6 +1438,7 @@ export "./protocol" (./src/protocol.ts) ATTACHMENT_MAX_FILE_BYTES ATTACHMENT_MAX_TOTAL_BYTES ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_READS_CAPABILITY ATTACHMENT_UNBOUND_TTL_MS type ActionDigestEntry type ActionDigestState @@ -1495,6 +1504,7 @@ export "./protocol" (./src/protocol.ts) type AttachmentFile type AttachmentKind type AttachmentLimits + type AttachmentReadEntry type AttachmentReader type BillingMode type BrainSearchResult @@ -1738,6 +1748,7 @@ export "./protocol" (./src/protocol.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerAttachmentRead type ServerChatRetired type ServerConversationClosed type ServerConversationEvent @@ -1777,6 +1788,7 @@ export "./protocol" (./src/protocol.ts) type ServerToolUseStart type ServerTurnJournal type ServerUsage + type SessionAttachmentReadsResponse type SessionDraftLimits type SessionHistoryMessage type SessionRecovery @@ -2021,6 +2033,7 @@ export "./schemas" (./src/schemas.ts) serverAskUserListRequestSchema serverAskUserRankRequestSchema serverAskUserRequestSchema + serverAttachmentReadSchema serverChatRetiredSchema serverConversationClosedSchema serverConversationEventSchema @@ -2056,6 +2069,7 @@ export "./schemas" (./src/schemas.ts) serverToolUseStartSchema serverTurnJournalSchema serverUsageSchema + sessionAttachmentReadsResponseSchema sessionDraftLimitsSchema sessionRecoverySchema sessionWorkerProfileSchema @@ -2104,6 +2118,7 @@ export "./server" (./src/server/index.ts) ATTACHMENT_MAX_FILE_BYTES ATTACHMENT_MAX_TOTAL_BYTES ATTACHMENT_POOL_DEFAULT_BYTES + ATTACHMENT_READS_CAPABILITY ATTACHMENT_READ_MAX_CALL_BYTES ATTACHMENT_READ_MAX_PAGES ATTACHMENT_READ_MAX_TURN_BYTES @@ -2192,6 +2207,7 @@ export "./server" (./src/server/index.ts) type AttachmentFile type AttachmentKind type AttachmentLimits + type AttachmentReadEntry type AttachmentReadFailure type AttachmentReadOutcome type AttachmentReadResult @@ -2633,6 +2649,7 @@ export "./server" (./src/server/index.ts) type ServerAskUserListRequest type ServerAskUserRankRequest type ServerAskUserRequest + type ServerAttachmentRead type ServerChatRetired type ServerConversationClosed type ServerConversationEvent @@ -2672,6 +2689,7 @@ export "./server" (./src/server/index.ts) type ServerToolUseStart type ServerTurnJournal type ServerUsage + type SessionAttachmentReadsResponse type SessionDraftLimits type SessionHistoryMessage type SessionHistoryRemovalOutcome @@ -3601,6 +3619,8 @@ signatures (every public export and the types it is made of) const ATTACHMENT_MAX_TOTAL_BYTES: 50000000; ATTACHMENT_POOL_DEFAULT_BYTES (packages/ui-sdk/src/protocol.ts) const ATTACHMENT_POOL_DEFAULT_BYTES: 1073741824; + ATTACHMENT_READS_CAPABILITY (packages/ui-sdk/src/protocol.ts) + const ATTACHMENT_READS_CAPABILITY: "attachmentReads"; ATTACHMENT_READ_MAX_CALL_BYTES (packages/ui-sdk/src/tool-contracts/attachment.ts) const ATTACHMENT_READ_MAX_CALL_BYTES: 65536; ATTACHMENT_READ_MAX_PAGES (packages/ui-sdk/src/tool-contracts/attachment.ts) @@ -4352,6 +4372,14 @@ signatures (every public export and the types it is made of) maxTotalBytes: number; poolBytes: number; } + AttachmentReadEntry (packages/ui-sdk/src/protocol.ts) + export interface AttachmentReadEntry { + fileId: string; + turnId: string; + outcome: Exclude; + scope: NonNullable | null; + at: number; + } AttachmentReadFailure (packages/ui-sdk/src/tool-contracts/attachment.ts) export type AttachmentReadFailure = "timeout" | "resource_limit" | "crash" | "error"; AttachmentReadOutcome (packages/ui-sdk/src/tool-contracts/attachment.ts) @@ -10799,6 +10827,12 @@ signatures (every public export and the types it is made of) requestId: string; questions: AskUserQuestion[]; } + ServerAttachmentRead (packages/ui-sdk/src/protocol.ts) + export interface ServerAttachmentRead { + type: "attachment_read"; + sessionId: string; + read: AttachmentReadEntry; + } ServerChatRetired (packages/ui-sdk/src/protocol.ts) export interface ServerChatRetired { type: "chat_retired"; @@ -10938,7 +10972,7 @@ signatures (every public export and the types it is made of) instruction?: string; } ServerMessage (packages/ui-sdk/src/protocol.ts) - export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired; + export type ServerMessage = ServerSafetyHistory | ServerSafetyUpdate | ServerSafetyUnavailable | ServerScopeDecisionReceipt | ServerHello | ServerRetryReceipt | ServerTextDelta | ServerThinkingDelta | ServerToolUseStart | ServerToolInputDelta | ServerToolUseComplete | ServerToolResult | ServerToolApprovalRequest | ServerResultMessage | ServerError | ServerStatus | ServerSessionInfo | ServerSessionHistory | ServerAskUserRequest | ServerAskUserListRequest | ServerAskUserRankRequest | ServerAskUserFormRequest | ServerAskAnswerReceipt | ServerPong | ServerLocationRequest | ServerMaskRequest | ServerActivitySnapshot | ServerActivityDelta | ServerMessageBlocks | ServerMessageLinks | ServerLocalExchangeResult | ServerHandoffDraft | ServerHandoffReceipt | InboxSnapshot | InboxDelta | ServerToolResolution | ServerSessionQueue | ServerDialogueHistory | ServerConversationOpened | ServerConversationClosed | ServerConversationEvent | ServerConversationWork | ServerConversationOutput | ServerConversationPermission | ServerTurnJournal | ServerUsage | ServerChatRetired | ServerAttachmentRead; ServerMessageBlocks (packages/ui-sdk/src/protocol.ts) export interface ServerMessageBlocks extends SessionScoped { type: "message_blocks"; @@ -11128,6 +11162,11 @@ signatures (every public export and the types it is made of) addEventListener(type: "install", listener: () => void): void; addEventListener(type: "activate", listener: (event: ExtendableEventLike) => void): void; } + SessionAttachmentReadsResponse (packages/ui-sdk/src/protocol.ts) + export interface SessionAttachmentReadsResponse { + sessionId: string; + reads: AttachmentReadEntry[]; + } SessionDraftLimits (packages/ui-sdk/src/protocol.ts) export interface SessionDraftLimits { maxTextBytes: number; @@ -18922,6 +18961,33 @@ signatures (every public export and the types it is made of) turnId: z.ZodOptional; type: z.ZodLiteral<"ask_user_request">; }, z.core.$loose>; + serverAttachmentReadSchema (packages/ui-sdk/src/schemas.ts) + const serverAttachmentReadSchema: z.ZodObject<{ + read: z.ZodObject<{ + at: z.ZodNumber; + fileId: z.ZodString; + outcome: z.ZodEnum<{ + changed: "changed"; + encrypted: "encrypted"; + failed: "failed"; + malformed: "malformed"; + no_text: "no_text"; + partial: "partial"; + read: "read"; + unavailable: "unavailable"; + }>; + scope: z.ZodNullable; + }, z.core.$loose>, z.ZodObject<{ + bytes: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>; + totalBytes: z.ZodNumber; + }, z.core.$loose>]>>; + turnId: z.ZodString; + }, z.core.$loose>; + sessionId: z.ZodString; + type: z.ZodLiteral<"attachment_read">; + }, z.core.$loose>; serverChatRetiredSchema (packages/ui-sdk/src/schemas.ts) const serverChatRetiredSchema: z.ZodObject<{ generation: z.ZodNumber; @@ -19985,6 +20051,31 @@ signatures (every public export and the types it is made of) historyOwnerIds: z.ZodArray; sessionId: z.ZodOptional; type: z.ZodLiteral<"chat_retired">; + }, z.core.$loose>, z.ZodObject<{ + read: z.ZodObject<{ + at: z.ZodNumber; + fileId: z.ZodString; + outcome: z.ZodEnum<{ + changed: "changed"; + encrypted: "encrypted"; + failed: "failed"; + malformed: "malformed"; + no_text: "no_text"; + partial: "partial"; + read: "read"; + unavailable: "unavailable"; + }>; + scope: z.ZodNullable; + }, z.core.$loose>, z.ZodObject<{ + bytes: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>; + totalBytes: z.ZodNumber; + }, z.core.$loose>]>>; + turnId: z.ZodString; + }, z.core.$loose>; + sessionId: z.ZodString; + type: z.ZodLiteral<"attachment_read">; }, z.core.$loose>, z.ZodObject<{ attachmentCount: z.ZodOptional; files: z.ZodOptional>>>; @@ -24746,6 +24837,32 @@ signatures (every public export and the types it is made of) }, z.core.$loose>>>; }, z.core.$loose>; }, z.core.$loose>; + sessionAttachmentReadsResponseSchema (packages/ui-sdk/src/schemas.ts) + const sessionAttachmentReadsResponseSchema: z.ZodObject<{ + reads: z.ZodArray; + scope: z.ZodNullable; + }, z.core.$loose>, z.ZodObject<{ + bytes: z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>; + totalBytes: z.ZodNumber; + }, z.core.$loose>]>>; + turnId: z.ZodString; + }, z.core.$loose>>; + sessionId: z.ZodString; + }, z.core.$loose>; sessionDraftLimitsSchema (packages/ui-sdk/src/schemas.ts) const sessionDraftLimitsSchema: z.ZodObject<{ maxDraftBytes: z.ZodNumber; diff --git a/docs/decisions/chat-attachments.md b/docs/decisions/chat-attachments.md index f5d4fcbf91..b040d3268b 100644 --- a/docs/decisions/chat-attachments.md +++ b/docs/decisions/chat-attachments.md @@ -237,6 +237,16 @@ The shared reader of the design's §7, with these concrete choices: provider. Session release and the sweep's forget remove a session's or a file's rows. There is no derived cache, so nothing new is charged to the pool. +- **Delivering reads (#3589).** The records reach the browser two ways. A + route, `GET /api/sessions/:id/attachment-reads`, returns a session's reads + when its view opens. A capability-gated `attachment_read` frame carries a + read recorded during a live turn. The frame is sent with `sendToCapable`, + which bypasses the dialogue recorder, so it never joins a transcript or a + replay. Both return only reads of files that a `message` reference of the + same session still names. They use the history replay's authorization, + which is a usable principal of this host's shared namespace; the route adds + no ownership rule that a replay does not have. A replay field was not used: + the native transcript, not the host, owns a replayed message. - **Adding a reader.** A reader is concrete code, not a registry: add a rule to `detectKind` (`packages/ui-server/src/attachments/detect.ts`) and a `reader` value to `AttachmentReader` and migration 077's check; route it in diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 059fb4d717..f801c7a126 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -7,7 +7,7 @@ fake backends and injected transports keep the checks keyless. Each ordinary row runs the named `mounted supported handler: METHOD PATH` test in [http-supported-mounts.test.ts](../packages/ui-server/tests/http-supported-mounts.test.ts) -(`checkHandler`, `packages/ui-server/tests/http-supported-mounts.test.ts:180-199`). +(`checkHandler`, `packages/ui-server/tests/http-supported-mounts.test.ts:181-200`). The explicit [lifetime audit](../packages/ui-server/tests/helpers/http-mount-lifetimes.ts) permits a bounded group of immutable readers to share startup, with a new owner per case. Principal enumeration, activity ownership, CLI dispatch, caches, @@ -125,6 +125,7 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/sessions/:sessionId/turns/:turnId/journal/:sequence/:side` | `mounted supported handler: GET /api/sessions/:sessionId/turns/:turnId/journal/:sequence/:side` | J | | `GET /api/journal/configuration-coverage` | `mounted supported handler: GET /api/journal/configuration-coverage` | J | | `GET /api/sessions/:id/safety` | `mounted supported handler: GET /api/sessions/:id/safety` | S | +| `GET /api/sessions/:id/attachment-reads` | `mounted supported handler: GET /api/sessions/:id/attachment-reads` | X | | `GET /api/sessions/:id/recovery` | `mounted supported handler: GET /api/sessions/:id/recovery` | S | | `POST /api/queue` | `mounted supported handler: POST /api/queue` | Q | | `GET /api/schedules` | `mounted supported handler: GET /api/schedules` | K | @@ -343,6 +344,7 @@ checks both nonempty priced and mixed-knownness fixtures - `an upload retried after its bytes were swept stores them again under a usable id` ([source](../packages/ui-server/tests/drafts-store.test.ts)), (`an upload retried after its bytes were swept stores them again under a usable id`, `packages/ui-server/tests/drafts-store.test.ts:87-95`) - `acceptance consumes only a matching, current, same-session revision` ([source](../packages/ui-server/tests/drafts-store.test.ts)), (`acceptance consumes only a matching, current, same-session revision`, `packages/ui-server/tests/drafts-store.test.ts:97-109`) - `a revoked sender's acceptance consumes nothing` ([source](../packages/ui-server/tests/drafts-store.test.ts)), (`a revoked sender's acceptance consumes nothing`, `packages/ui-server/tests/drafts-store.test.ts:111-117`) +- `a client viewing a session gets that session's recorded reads, live and on request, and nothing else` ([source](../packages/ui-server/tests/attachment-reads-delivery.test.ts)), (`a client viewing a session gets that session's recorded reads, live and on request, and nothing else`, `packages/ui-server/tests/attachment-reads-delivery.test.ts:86-159`) **J — Confirmed share intake.** diff --git a/docs/http-api.md b/docs/http-api.md index 819d021ad3..2c9ce0fd2c 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark and chat-deletion routes mounted by `createApp`: 173 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark and chat-deletion routes mounted by `createApp`: 174 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -157,6 +157,7 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/agent-policy` | I | Read shared admission policy and reported enforcing limits | Read-only Devices & agents facts; no editor or duplicate policy cache. | | GET | `/api/policy-proposals/:turnId/:requestId` | I | Read one principal-owned policy request receipt | Same-request reconciliation only; never writes or reactivates approval. | | GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Exact authenticated history owner; immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). | +| GET | `/api/sessions/:id/attachment-reads` | S | Read a session's recorded attachment reads, outcome and scope only | Sent-row read states (#3589, #3155); preserve the session and message-reference filters, no text and no provider path. | | GET | `/api/sessions/:id/recovery` | S | Read a session's latest accepted work and pending interactions | Trackers and independent session clients (#964, D52); preserve the revision ordering, Activity terminal proof, honest unknown and the no-execution boundary. | | POST | `/api/queue` | S | Queue authenticated CLI intake without filing content | CLI and independent intake clients; preserve explicit key, provenance and queue receipt. | | GET | `/api/schedules` | S | List stored scheduled tasks, cancelled ones included | CLI and independent schedule clients; preserve keys, receipts, operator approval and the no-execution boundary. | @@ -206,7 +207,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 173 declared endpoints are mounted regardless of backend, renderer or +All 174 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -1148,6 +1149,33 @@ preview. `404 ATTACHMENT_NOT_FOUND` for an unknown, unreferenced or missing file; `409 ATTACHMENT_CHANGED` when the bytes no longer match, with none of them served. The raw file route keeps its 10,485,760-byte cap. + + +### `GET /api/sessions/:id/attachment-reads` (additive, 0.45.0, #3589) + +Advertised by `server_hello.capabilities.attachmentReads`; absent on a host +without composer files, which a client reads as "show no read state". Behind +the same authentication guard as the other session routes, with the same +authority a history replay of the session has: a usable principal of this host, +whose namespace every authenticated principal shares. A revoked or expired one +gets the guard's `401 { error: "Authentication required", authRequired: true }` +and nothing about the session. + +`200` returns `SessionAttachmentReadsResponse` `{ sessionId, reads }`, with +`Cache-Control: no-store`. Each `AttachmentReadEntry` is `{ fileId, turnId, +outcome, scope, at }`: one recorded `read_attachment` call that reached an +original, oldest first. `outcome` is any outcome but `refused`, whose calls +reach no original and are not recorded. `scope` is the pages or byte range +the result covered, or `null` when nothing was read. Only reads recorded by +this session's turns, of originals a message of this session still names, are +returned. A session with none, or one the host does not know, answers an empty +list. A retired chat is `404 SESSION_NOT_FOUND`. Text is never kept or +returned, and nothing here reaches a provider. + +A read recorded during a live turn also reaches every connection that declared +`attachmentReads` in its `client_hello`, as one +[`attachment_read` frame](integration-contract/wire.md#attachment-reads-additive-0450-3589). + ### Lifetime An upload no save or message ever bound is removed an hour after upload. An diff --git a/docs/integration-contract.md b/docs/integration-contract.md index a3825ab39b..67b9c2ce0e 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -121,6 +121,19 @@ files answers `unavailable`. See and [the package component](integration-contract/package-api.md#reading-composer-attachments-additive-0450-3154). This ships in a minor. +## Attachment reads for sent rows (additive, 0.45.0, #3589) + +A host with composer files advertises `server_hello.capabilities.attachmentReads`. +`GET /api/sessions/:id/attachment-reads` returns the recorded `read_attachment` +calls of the originals a session's messages name, as `{ fileId, turnId, +outcome, scope, at }` and never their text, under the session's existing +authorization. A read recorded during a live turn reaches the connections that +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. + ## Reading a chat deletion's outcome (additive, #3455) `GET /api/chat-deletions/:operationId` ([HTTP](http-api.md#explicit-chat-deletion-additive-3230)) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index abbe7bd7ff..02c603e509 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -1973,6 +1973,31 @@ and `AttachmentErrorResponse` types, and `attachmentFileSchema` and `attachmentLimitsSchema`. The governance `taint` event's `source` gains `chat_attachment`: reading under `.brain-ui/attachments/` taints the session as reading a staged share does. + + +### Attachment reads (additive, 0.45.0, #3589) + +A host with composer files sends `server_hello.capabilities.attachmentReads: +true` (`ATTACHMENT_READS_CAPABILITY`). It then answers +[`GET /api/sessions/:id/attachment-reads`](../http-api.md#attachment-reads-additive-0450-3589) +and sends `attachment_read` frames to the connections that declared the same +flag in `client_hello`. A connection without the flag never receives one, and a +client on a host without the capability shows no read state for a sent file. + +- **`attachment_read`** `{ type: "attachment_read", sessionId, read: + AttachmentReadEntry }` follows each `read_attachment` call that reached an + original during a turn of `sessionId`, once the read is recorded. `read` is + `{ fileId, turnId, outcome, scope, at }`: outcome and scope only, never text. + A refused call sends nothing, and nothing is sent for a retired chat. +- **Not conversation content.** The frame is not part of the transcript, the + host dialogue or a history replay, and it never reaches a provider: the + provider-facing history is unchanged. + +The SDK publishes `ATTACHMENT_READS_CAPABILITY`, `AttachmentReadEntry`, +`SessionAttachmentReadsResponse` and `ServerAttachmentRead`, and the +`serverAttachmentReadSchema` and `sessionAttachmentReadsResponseSchema` +schemas; `serverMessageSchema` accepts the new frame. + ### Explicit chat deletion (additive, #3230) diff --git a/packages/ui-react/src/hooks/websocket-handlers/connection.ts b/packages/ui-react/src/hooks/websocket-handlers/connection.ts index c14eca9806..27a1b42e08 100644 --- a/packages/ui-react/src/hooks/websocket-handlers/connection.ts +++ b/packages/ui-react/src/hooks/websocket-handlers/connection.ts @@ -5,7 +5,8 @@ type ConnectionFrame = "safety_history" | "safety_update" | "safety_unavailable" | "dialogue_history" | "scope_decision_receipt" | "server_hello" | "location_request" | "error" | "inbox_snapshot" | "inbox_delta" | "tool_resolution" | "session_queue" | "conversation_opened" | "conversation_closed" - | "conversation_event" | "conversation_work" | "conversation_output" | "conversation_permission" | "chat_retired"; + | "conversation_event" | "conversation_work" | "conversation_output" | "conversation_permission" | "chat_retired" + | "attachment_read"; export const connectionFrameHandlers = { safety_history: () => {}, safety_update: () => {}, safety_unavailable: () => {}, @@ -48,6 +49,9 @@ 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. + attachment_read: () => {}, conversation_opened: () => {}, conversation_closed: () => {}, conversation_event: () => {}, diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 20783c5f5a..dbe6a3d8be 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -963,7 +963,8 @@ export type ServerMessage = | ServerConversationPermission | ServerTurnJournal | ServerUsage - | ServerChatRetired; + | ServerChatRetired + | ServerAttachmentRead; /** * First frame a server sends after a socket opens (rev 2, additive). Clients @@ -2748,6 +2749,49 @@ export interface AttachmentFile { track?: SharedFileMeta; } +/** + * `server_hello`/`client_hello` capability (additive, #3589): the host + * answers `GET /api/sessions/:id/attachment-reads` and sends + * `attachment_read` frames, only to connections that declared the flag. + * Without it a client shows no read state for a sent original. + */ +export const ATTACHMENT_READS_CAPABILITY = "attachmentReads"; + +/** + * One recorded `read_attachment` call of a session (#3589): what the agent + * read of one original, never the text. UI evidence only; it never reaches a + * provider. + */ +export interface AttachmentReadEntry { + fileId: string; + /** The turn whose agent made the call. */ + turnId: string; + /** `refused` calls reached no original and are not recorded. */ + outcome: Exclude; + /** The pages or byte range the result covered, or null when nothing was read. */ + scope: NonNullable | null; + /** Host milliseconds since epoch when it was recorded. */ + at: number; +} + +/** `GET /api/sessions/:id/attachment-reads` (additive, #3589). */ +export interface SessionAttachmentReadsResponse { + sessionId: string; + /** Reads of the originals this session's messages name, oldest first. */ + reads: AttachmentReadEntry[]; +} + +/** + * Server → Client (additive, #3589). A turn of `sessionId` just recorded one + * read. Sent only to connections that declared + * {@link ATTACHMENT_READS_CAPABILITY}; never part of a transcript. + */ +export interface ServerAttachmentRead { + type: "attachment_read"; + sessionId: string; + read: AttachmentReadEntry; +} + /** `server_hello.attachmentLimits`. */ export interface AttachmentLimits { maxFiles: number; diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index adf9fbe993..2c2889d167 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1989,6 +1989,29 @@ export const serverChatRetiredSchema = z.looseObject({ generation: z.number().int().min(1), }) satisfies z.ZodType; +const attachmentReadEntrySchema = z.looseObject({ + fileId: z.string().regex(/^[a-f0-9-]{36}$/), + turnId: id, + outcome: z.enum(["read", "partial", "no_text", "encrypted", "malformed", "failed", "unavailable", "changed"]), + scope: z.union([ + z.looseObject({ pages: z.tuple([z.number().int().positive(), z.number().int().positive()]), pageCount: z.number().int().nonnegative() }), + z.looseObject({ bytes: z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()]), totalBytes: z.number().int().nonnegative() }), + ]).nullable(), + at: z.number().int().nonnegative(), +}) satisfies z.ZodType; + +/** `GET /api/sessions/:id/attachment-reads` (#3589). */ +export const sessionAttachmentReadsResponseSchema = z.looseObject({ + sessionId: id, + reads: z.array(attachmentReadEntrySchema), +}) satisfies z.ZodType; + +export const serverAttachmentReadSchema = z.looseObject({ + type: z.literal("attachment_read"), + sessionId: id, + read: attachmentReadEntrySchema, +}) satisfies z.ZodType; + export const serverUsageSchema = z.looseObject({ type:z.literal("usage"),sessionId:id.optional(),turnId:id, usage:turnUsageSchema,observedAt:z.number().int().nonnegative(),budget:turnBudgetReceiptSchema.optional().catch(undefined), }) satisfies z.ZodType; @@ -2004,6 +2027,7 @@ export const serverMessageSchema = z.discriminatedUnion("type", [ serverTurnJournalSchema, serverUsageSchema, serverChatRetiredSchema, + serverAttachmentReadSchema, serverRetryReceiptSchema, serverHelloSchema, serverTextDeltaSchema, diff --git a/packages/ui-sdk/tests/server-schemas.test.ts b/packages/ui-sdk/tests/server-schemas.test.ts index 571c2946b2..6f8a7ca560 100644 --- a/packages/ui-sdk/tests/server-schemas.test.ts +++ b/packages/ui-sdk/tests/server-schemas.test.ts @@ -136,6 +136,10 @@ const SAMPLES: ServerMessage[] = [ { type: "handoff_receipt", handoffId: "h-ithaca-01", state: "created", sessionId: "s2" }, { type: "tool_resolution", toolUseId: "t1", outcome: "expired", sessionId: "s1", turnId: "turn-1", reason: "Turn timed out" }, { type: "chat_retired", sessionId: "s1", historyOwnerIds: ["ithaca"], generation: 2 }, + { type: "attachment_read", sessionId: "s1", read: { + fileId: "8e9a1c52-3f4b-4d6e-9a7b-1c2d3e4f5a6b", turnId: "turn-1", outcome: "partial", + scope: { pages: [1, 20], pageCount: 48 }, at: 1_783_814_400_000, + } }, { type: "safety_history", requestId: "history-ithaca", page: { version: 1, identity: safetyIdentity, snapshotId: "snapshot-ithaca", cursor: null, highWater: "0", projection: safetyProjection, records: [], nextCursor: null, snapshotComplete: true, detailPruned: false, diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index a4968df504..8b03cc28c8 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -62,6 +62,7 @@ import { createSessionRecoveryRoutes } from "./routes/session-recovery.js"; import { supportsSessionRecovery } from "./ws/recovery.js"; import { createDraftStore } from "./drafts/store.js"; import { createAttachmentRoutes } from "./attachments/routes.js"; +import { createAttachmentReadRoutes } from "./routes/attachment-reads.js"; import { ATTACHMENT_SWEEP_INTERVAL_MS, reconcileAttachments, sweepAttachments } from "./attachments/sweep.js"; import { ATTACHMENT_MAX_FILES, ATTACHMENT_MAX_FILE_BYTES, ATTACHMENT_MAX_TOTAL_BYTES } from "@schlessera/brain-ui-sdk/protocol"; import { createActivityRoutes } from "./routes/activity.js"; @@ -1167,6 +1168,8 @@ export async function createApp(options: CreateAppOptions = {}): Promise activity.runtime.snapshot().workerHost?.limits ?? null)); app.route("/api", createDraftRoutes(drafts)); app.route("/api", createAttachmentRoutes({ brainRoot: config.brainPath, store: drafts, instanceId: attachmentInstanceId })); + // Only where server_hello advertises attachmentReads (#3589). + if (host.attachmentLimits) app.route("/api", createAttachmentReadRoutes(host)); // Behind the guard by mount position, like /api/status: the activity // record leaks strictly more (session activity, errors, spend). app.route("/api", createActivityRoutes({ db, settingsWrites, store: activity.store, notifier: activity.notifier, actionNotices: activity.actionNotices })); diff --git a/packages/ui-server/src/attachments/read.ts b/packages/ui-server/src/attachments/read.ts index bbe29819bc..6a21b58eac 100644 --- a/packages/ui-server/src/attachments/read.ts +++ b/packages/ui-server/src/attachments/read.ts @@ -23,7 +23,7 @@ interface AttachmentReadBudget { used: number } export interface AttachmentReadContext { brainRoot: string; - store: Pick; + store: AttachmentReadStore; /** The calling turn's session; null before the backend reported one. */ sessionId: string | null | undefined; turnId: string; @@ -46,6 +46,9 @@ function refused(id: string, message: string, row?: AttachmentRow): AttachmentRe return { id, ...(row ? { name: row.stored_name, kind: row.kind } : {}), outcome: "refused", message }; } +/** The draft store calls a read makes. */ +export type AttachmentReadStore = Pick; + export function createAttachmentReader(extractor: Extractor) { async function read(ctx: AttachmentReadContext, input: ReadAttachmentInput): Promise { const id = input.id; diff --git a/packages/ui-server/src/attachments/store.ts b/packages/ui-server/src/attachments/store.ts index 42bf30e377..1332422730 100644 --- a/packages/ui-server/src/attachments/store.ts +++ b/packages/ui-server/src/attachments/store.ts @@ -221,14 +221,25 @@ export interface AttachmentReadRecord { scope: AttachmentReadResult["scope"] | null; } +/** The client-facing shape of one recorded read (#3589): no session, since the caller asked for one. */ +export function toAttachmentReadEntry(read: AttachmentReadRecord & { at: number }): import("@schlessera/brain-ui-sdk/protocol").AttachmentReadEntry { + return { fileId: read.fileId, turnId: read.turnId, outcome: read.outcome, scope: read.scope ?? null, at: read.at }; +} + export function insertAttachmentRead(db: Database, read: AttachmentReadRecord, at: number): void { db.prepare("INSERT INTO attachment_reads (file_id, session_id, turn_id, outcome, scope_json, created_at) VALUES (?, ?, ?, ?, ?, ?)") .run(read.fileId, read.sessionId, read.turnId, read.outcome, read.scope ? JSON.stringify(read.scope) : null, at); } -/** The recorded reads of one session's originals, oldest first. */ +/** + * The recorded reads of one session's originals, oldest first: only of files a + * `message` reference of that same session still names, so a read never shows + * on a chat that was not sent the file. + */ export function listAttachmentReads(db: Database, sessionId: string): Array { - const rows = db.query("SELECT file_id, session_id, turn_id, outcome, scope_json, created_at FROM attachment_reads WHERE session_id = ? ORDER BY rowid") + const rows = db.query(`SELECT a.file_id, a.session_id, a.turn_id, a.outcome, a.scope_json, a.created_at FROM attachment_reads a + WHERE a.session_id = ?1 AND EXISTS (SELECT 1 FROM attachment_refs r WHERE r.file_id = a.file_id AND r.owner = 'message' AND r.owner_id = ?1) + ORDER BY a.rowid`) .all(sessionId) as Array<{ file_id: string; session_id: string; turn_id: string; outcome: AttachmentReadRecord["outcome"]; scope_json: string | null; created_at: number }>; return rows.map((r) => { let scope: AttachmentReadRecord["scope"] = null; diff --git a/packages/ui-server/src/drafts/store.ts b/packages/ui-server/src/drafts/store.ts index 354c72b6fe..2f9026d8f6 100644 --- a/packages/ui-server/src/drafts/store.ts +++ b/packages/ui-server/src/drafts/store.ts @@ -179,8 +179,8 @@ export interface DraftStore { /** Remove a deleted chat's `message` references, starting their seven-day clocks, and its read records. */ releaseSession(sessionId: string): void; /** Record one `read_attachment` call (#3154): UI and internal data, never provider context. */ - recordAttachmentRead(read: import("../attachments/store.js").AttachmentReadRecord): void; - /** Read side: one session's recorded attachment reads, oldest first. */ + recordAttachmentRead(read: import("../attachments/store.js").AttachmentReadRecord): { at: number }; + /** Read side: one session's recorded reads of originals its messages name, oldest first. */ attachmentReads(sessionId: string): Array; /** Read side: recorded originals by id (any state). */ attachments(fileIds: readonly string[]): Map; @@ -975,7 +975,9 @@ export function createDraftStore( }, recordAttachmentRead(read) { - db.transaction(() => insertAttachmentRead(db, read, now())).immediate(); + const at = now(); + db.transaction(() => insertAttachmentRead(db, read, at)).immediate(); + return { at }; }, attachmentReads(sessionId) { diff --git a/packages/ui-server/src/routes/attachment-reads.ts b/packages/ui-server/src/routes/attachment-reads.ts new file mode 100644 index 0000000000..c72235cf6d --- /dev/null +++ b/packages/ui-server/src/routes/attachment-reads.ts @@ -0,0 +1,31 @@ +import { Hono } from "hono"; +import { SESSION_NOT_FOUND, type SessionAttachmentReadsResponse } from "@schlessera/brain-ui-sdk/protocol"; + +import type { AppEnv } from "../app-env.js"; +import type { WsHost } from "../ws/host.js"; +import { toAttachmentReadEntry } from "../attachments/store.js"; + +/** + * `GET /api/sessions/:id/attachment-reads` (#3589). Mounted behind the auth + * guard, and only where `server_hello` advertises `attachmentReads`. It + * returns the recorded reads of the originals this session's messages name, + * under the same authority a history replay of that session has: a usable + * principal of this host. Outcome and scope only, never text, and nothing of + * it is provider context. Responses are not cached. + */ +export function createAttachmentReadRoutes(host: WsHost): Hono { + return new Hono().get("/sessions/:id/attachment-reads", async (c) => { + c.header("Cache-Control", "no-store"); + const principal = c.get("principal"); + const unauthorized = () => c.json({ error: "Authentication required", authRequired: true }, 401); + if (!principal || !host.isPrincipalValid(principal) || !host.drafts) return unauthorized(); + const sessionId = c.req.param("id"); + // A retired chat has nothing left to show (#3230). + if (host.catalog.chatRetired?.({ sessionId })) return c.json({ error: SESSION_NOT_FOUND, message: "This host has no such session." }, 404); + // Writes commit off the event loop: read what was submitted before this request. + await host.drafts.settled?.(); + if (!host.isPrincipalValid(principal)) return unauthorized(); + const body: SessionAttachmentReadsResponse = { sessionId, reads: host.drafts.attachmentReads(sessionId).map(toAttachmentReadEntry) }; + return c.json(body); + }); +} diff --git a/packages/ui-server/src/ws/bridge-capabilities/attachments.ts b/packages/ui-server/src/ws/bridge-capabilities/attachments.ts index f13116e727..d7d843caf1 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/attachments.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/attachments.ts @@ -1,5 +1,7 @@ +import { ATTACHMENT_READS_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; import { createExtractor } from "../../attachments/extract.js"; -import { createAttachmentReader, type AttachmentReader } from "../../attachments/read.js"; +import { toAttachmentReadEntry } from "../../attachments/store.js"; +import { createAttachmentReader, type AttachmentReader, type AttachmentReadStore } from "../../attachments/read.js"; import type { BridgeContext, BridgeSlice } from "./context.js"; import type { TurnTranscript } from "./emission.js"; @@ -19,6 +21,21 @@ export function createAttachmentRead(ctx: Pick): Partial> { const { host, turn, turnId, signal, backendId } = ctx; if (!host.drafts || !host.brainPath || (backendId !== "claude" && backendId !== "pi")) return {}; - const store = host.drafts, brainRoot = host.brainPath, reader = attachmentReaderOf(host), budget = { used: 0 }; + const drafts = host.drafts, brainRoot = host.brainPath, reader = attachmentReaderOf(host), budget = { used: 0 }; + // A recorded read reaches the clients that declared they show it (#3589), + // as its own frame: never a transcript, dialogue or provider message. + const store: AttachmentReadStore = { + attachments: ids => drafts.attachments(ids), + attachmentRef: (id, owner, ownerId) => drafts.attachmentRef(id, owner, ownerId), + settled: async () => { await drafts.settled?.(); }, + async recordAttachmentRead(read) { + const recorded = await drafts.recordAttachmentRead(read); + if (!host.catalog.chatRetired?.({ sessionId: read.sessionId })) { + host.sendToCapable(ATTACHMENT_READS_CAPABILITY, { type: "attachment_read", sessionId: read.sessionId, + read: toAttachmentReadEntry({ ...read, at: recorded.at }) }); + } + return recorded; + }, + }; return { readAttachment: input => reader.read({ brainRoot, store, sessionId: transcript.collectedSessionId ?? turn.sessionId, turnId, signal, budget }, input) }; } diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index 32ad8a8c14..32c8c0f4b8 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -2,7 +2,7 @@ import { SAFETY_READ_CAPABILITIES } from "@schlessera/brain-ui-sdk/protocol"; import { createHash } from "node:crypto"; import { upgradeWebSocket, websocket } from "hono/bun"; import type { MiddlewareHandler } from "hono"; -import { ASK_RECEIPTS_CAPABILITY, CHAT_DELETION_CAPABILITY, COMPOSER_FILES_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV, SESSION_RECOVERY_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; +import { ASK_RECEIPTS_CAPABILITY, ATTACHMENT_READS_CAPABILITY, CHAT_DELETION_CAPABILITY, COMPOSER_FILES_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV, SESSION_RECOVERY_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; import { withTurnScope } from "./frames.js"; import { resendPendingInteractive } from "./resend.js"; @@ -117,6 +117,9 @@ export function createWsHandlers(host: WsHost, principal: Principal) { // POST /api/drafts/:draftId/files stores originals and // chat_message.attachmentRefs is accepted (#3153). ...(host.attachmentLimits ? { [COMPOSER_FILES_CAPABILITY]: true } : {}), + // GET /api/sessions/:id/attachment-reads answers, and `attachment_read` + // reaches connections that declare the flag (#3589). + ...(host.attachmentLimits ? { [ATTACHMENT_READS_CAPABILITY]: true } : {}), // GET /api/sessions/:id/recovery answers, and replays carry // host-proven turn ids (#964). ...(supportsSessionRecovery(host) ? { [SESSION_RECOVERY_CAPABILITY]: true } : {}), diff --git a/packages/ui-server/tests/attachment-reads-delivery.test.ts b/packages/ui-server/tests/attachment-reads-delivery.test.ts new file mode 100644 index 0000000000..d1339f7ce7 --- /dev/null +++ b/packages/ui-server/tests/attachment-reads-delivery.test.ts @@ -0,0 +1,159 @@ +import { afterEach, expect, test } from "bun:test"; +import { generateSignedCookie } from "hono/cookie"; +import type { AttachmentFile, ServerMessage, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import type { SessionAttachmentReadsResponse } from "@schlessera/brain-ui-sdk/protocol"; +// Namespace imports, so a host without the feature fails on an assertion, not at module load. +import * as protocol from "@schlessera/brain-ui-sdk/protocol"; +import * as schemas from "@schlessera/brain-ui-sdk/schemas"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { createPrincipal, revokePrincipal } from "../src/db/principals"; +import { makeFakeBackend } from "./helpers/fake-backend"; +import { httpContractApp } from "./helpers/http-contract-app"; +import { ithacaPermitPdf, PERMIT_FACT } from "./helpers/odysseus-pdf"; + +// Delivering recorded attachment reads to the browser (#3589): a client +// viewing a session gets the reads of the originals that session was sent, +// outcome and scope only, through `GET /api/sessions/:id/attachment-reads`; +// a read recorded during a live turn reaches declaring connections as one +// `attachment_read` frame. Nothing of it is provider context. + +const SECRET = "attachment-reads-fixture-secret-0123456789"; +/** The capability's wire name, spelled out: the contract is the string. */ +const ATTACHMENT_READS = "attachmentReads"; +const HeaderWebSocket = WebSocket as unknown as { new(url: string, options: { headers: Record }): WebSocket }; +const cleanups: Array<() => Promise | void> = []; +afterEach(async () => { for (const c of cleanups.splice(0).reverse()) await c(); }); + +async function harness() { + const starts: StartTurnRequest[] = []; + let sessions = 0; + let readAlso: string | undefined; + const backend = makeFakeBackend({ + id: "claude", + async getHistory() { return []; }, + async startTurn(req) { + starts.push(req); + const sessionId = req.sessionId ?? `voyage-${++sessions}`; + req.bridge.emit({ type: "session_info", sessionId, isNew: !req.sessionId }); + const ids = [...req.prompt.matchAll(/"id":"([a-f0-9-]{36})"/g)].map((m) => m[1]!); + for (const id of ids) await req.bridge.readAttachment!({ id, pages: "2" }); + // A read of another conversation's file is refused, and never recorded. + if (readAlso) await req.bridge.readAttachment!({ id: readAlso }); + req.bridge.emit({ type: "result", sessionId, durationMs: 1, numTurns: 1, isError: false }); + }, + }); + const t = await httpContractApp({ registry: createStaticBackendRegistry([backend]), + env: { AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: "unused-fixture-hash", COOKIE_SECRET: SECRET, BRAIN_UI_ALLOW_LOOPBACK_ORIGIN: "1" } }); + cleanups.push(() => t.close()); + const server = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: t.app.fetch, websocket: t.app.websocket }); + cleanups.push(() => { server.stop(true); }); + + const login = async (label: string) => { + const principal = createPrincipal(t.app.db, { authMethod: "password", label, ttlSeconds: 3600 }); + const cookie = (await generateSignedCookie("brain_ui_session", principal.id, SECRET)).split(";")[0]!; + const call = (path: string, init: RequestInit = {}) => { + const headers = new Headers(init.headers); + headers.set("cookie", cookie); headers.set("origin", "http://localhost"); headers.set("host", "localhost"); + return t.fetch(path, { ...init, headers }); + }; + /** A socket that declares `capabilities` in its client_hello. */ + const connect = async (capabilities: Record) => { + const frames: ServerMessage[] = []; + const ws = new HeaderWebSocket(`ws://127.0.0.1:${server.port}/ws`, { headers: { cookie, origin: `http://127.0.0.1:${server.port}` } }); + cleanups.push(() => ws.close()); + await new Promise((resolve) => ws.addEventListener("message", (event) => { + const frame = JSON.parse(String(event.data)) as ServerMessage; + frames.push(frame); + if (frame.type === "server_hello") resolve(); + })); + ws.send(JSON.stringify({ type: "client_hello", protocolRev: 5, capabilities })); + await Bun.sleep(20); + return { frames, send: (frame: object) => ws.send(JSON.stringify(frame)) }; + }; + return { principal, call, connect }; + }; + + // A wall-clock deadline, not an iteration count: a turn spawns the PDF + // extractor, which a loaded host can slow well past a couple of seconds. + const until = async (condition: () => boolean) => { + const deadline = Date.now() + 20_000; + while (!condition() && Date.now() < deadline) await Bun.sleep(10); + expect(condition()).toBe(true); + }; + return { t, starts, login, until, readAlso: (id: string | undefined) => { readAlso = id; } }; +} + +test("a client viewing a session gets that session's recorded reads, live and on request, and nothing else", async () => { + const h = await harness(); + const phone = await h.login("Odysseus phone"); + const viewer = await phone.connect({ [ATTACHMENT_READS]: true }); + const legacy = await phone.connect({}); + expect(viewer.frames.find((f) => f.type === "server_hello"), "READS_ADVERTISED").toMatchObject({ capabilities: { [ATTACHMENT_READS]: true } }); + expect((protocol as Record).ATTACHMENT_READS_CAPABILITY).toBe(ATTACHMENT_READS); + + const upload = async (draftId: string, name: string) => { + const res = await phone.call(`/api/drafts/${draftId}/files`, { method: "POST", headers: { "idempotency-key": `${draftId}-${name}`, "content-type": "application/octet-stream", "x-file-name": encodeURIComponent(name) }, body: ithacaPermitPdf() as BodyInit }); + expect(res.status).toBe(201); + return await res.json() as AttachmentFile; + }; + const send = async (draftId: string, file: AttachmentFile) => { + const saved = await phone.call(`/api/drafts/${draftId}`, { method: "PUT", headers: { "content-type": "application/json", "if-match": "0", "idempotency-key": `${draftId}-save` }, + body: JSON.stringify({ sessionId: null, attachmentIds: [], text: "What does the permit allow?", fileIds: [file.fileId] }) }); + expect(saved.status).toBe(200); + const results = viewer.frames.filter((f) => f.type === "result").length; + viewer.send({ type: "chat_message", text: "What does the permit allow?", requestId: `${draftId}-send`, draftId, + draftRef: { draftId, revision: 1 }, attachmentRefs: [{ kind: "attachment", fileId: file.fileId }] }); + await h.until(() => viewer.frames.filter((f) => f.type === "result" || f.type === "error").length > results); + const err = viewer.frames.findLast((f) => f.type === "error"); if (err) throw new Error(JSON.stringify(err)); + }; + + const troy = await upload("draft-troy", "troy-permit.pdf"); + await send("draft-troy", troy); + h.readAlso(troy.fileId); + const ithaca = await upload("draft-ithaca", "ithaca-permit.pdf"); + await send("draft-ithaca", ithaca); + + // Live: each recorded read reached the declaring connection as its own frame, without a reload. + const live = viewer.frames.filter((f) => f.type === "attachment_read"); + expect(live.map((f) => schemas.serverMessageSchema.safeParse(f).success)).toEqual([true, true]); + expect(live).toMatchObject([ + { sessionId: "voyage-1", read: { fileId: troy.fileId, outcome: "read", scope: { pages: [2, 2], pageCount: 3 } } }, + { sessionId: "voyage-2", read: { fileId: ithaca.fileId, outcome: "read", scope: { pages: [2, 2], pageCount: 3 } } }, + ]); + // A connection that did not declare the flag never gets one. + expect(legacy.frames.some((f) => f.type === "attachment_read")).toBe(false); + // No text, and nothing of the frame is in what the provider saw. + expect(JSON.stringify(live)).not.toContain(PERMIT_FACT); + for (const start of h.starts) expect(start.prompt).not.toContain("attachment_read"); + + // On request: the session's own reads, and not the other conversation's. + const reads = async (sessionId: string) => { + const res = await phone.call(`/api/sessions/${sessionId}/attachment-reads`); + expect(res.status).toBe(200); + expect(res.headers.get("cache-control")).toBe("no-store"); + const body = await res.json() as SessionAttachmentReadsResponse; + expect((schemas as unknown as Record).sessionAttachmentReadsResponseSchema!.safeParse(body).success).toBe(true); + return body; + }; + const voyage2 = await reads("voyage-2"); + expect(voyage2.sessionId).toBe("voyage-2"); + expect(voyage2.reads.map((r) => [r.fileId, r.outcome])).toEqual([[ithaca.fileId, "read"]]); + expect(JSON.stringify(voyage2)).not.toContain(PERMIT_FACT); + expect((await reads("voyage-1")).reads.map((r) => r.fileId)).toEqual([troy.fileId]); + expect((await reads("voyage-unknown")).reads).toEqual([]); + + // A read row naming a file this session was never sent is not shown on it. + h.t.app.db.prepare("INSERT INTO attachment_reads (file_id, session_id, turn_id, outcome, scope_json, created_at) VALUES (?, 'voyage-2', 'turn-stray', 'read', NULL, 1)").run(troy.fileId); + expect((await reads("voyage-2")).reads.map((r) => r.fileId), "READS_SESSION_BOUNDARY").toEqual([ithaca.fileId]); + // Nor does a read recorded for another session show on this one. + expect((await reads("voyage-1")).reads.map((r) => r.fileId), "READS_OTHER_SESSION").toEqual([troy.fileId]); + + // Another login's principal: a usable one has this host's shared view; a + // revoked one gets the auth envelope and nothing about the session. + const laptop = await h.login("Penelope laptop"); + expect((await laptop.call("/api/sessions/voyage-2/attachment-reads")).status).toBe(200); + revokePrincipal(h.t.app.db, laptop.principal.id, Date.now()); + const refused = await laptop.call("/api/sessions/voyage-2/attachment-reads"); + expect(refused.status).toBe(401); + expect(JSON.stringify(await refused.json())).not.toContain(ithaca.fileId); +}); diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index cfe6a190a0..7f9d5b606a 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -91,6 +91,7 @@ export const mountLifetimes: Record = { "GET /api/journal/configuration-coverage": { path: "/api/journal/configuration-coverage", status: 200, body: { state: "unknown" } }, // Imported history: the session exists, and the host proves nothing about it. "GET /api/sessions/:id/safety": {path:"/api/sessions/fixture-session/safety",status:404,body:{version:1,reason:"unavailable"},verify:async r=>{expect(r.headers.get("cache-control")).toBe("no-store");}}, + "GET /api/sessions/:id/attachment-reads": { path: "/api/sessions/fixture-session/attachment-reads", body: { sessionId: "fixture-session", reads: [] }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "GET /api/sessions/:id/recovery": { path: "/api/sessions/fixture-session/recovery", body: { sessionId: "fixture-session", revision: 0, latest: { requestId: null, turnId: null, state: "unknown", outcome: null }, pending: [] }, verify: async (r) => { expect(r.headers.get("cache-control")).toBe("no-store"); } }, "GET /api/push/public-key": { verify: async (r) => { const b = await r.json(); expect(b.publicKey.length).toBeGreaterThan(0); expect(Object.keys(b)).toEqual(["publicKey"]); } }, "GET /api/push/subscriptions": { body: { subscriptions: [] } }, diff --git a/scripts/source-browser-dispatch.ts b/scripts/source-browser-dispatch.ts index b11ad461bb..f76ca6bc9a 100644 --- a/scripts/source-browser-dispatch.ts +++ b/scripts/source-browser-dispatch.ts @@ -43,10 +43,12 @@ const declarations=[ "name": "providerFrameHandlers", "source": "0de9131781f27ba26a4469640e849170b9e063ed1d595a90361ac815128b617f" }, + // Re-audited for #3589: the added attachment_read handler is a no-op + // that reads no runtime input, like chat_retired. { "owner": "packages/ui-react/src/hooks/websocket-handlers/connection.ts", "name": "connectionFrameHandlers", - "source": "1274d2b9466c5d6e27de3bdaef3ab9287dc2dc76b98af2a2c79d699731b622b0" + "source": "847362ebc5510a0dbede9bbbe50cedfdf03346685efe2286238f6be445ece2fe" }, { "owner": "packages/ui-react/src/hooks/websocket-handlers/handoff.ts",