@aiquants/chat 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,976 @@
1
- # Temporary Holding Version
1
+ # @aiquants/chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The chat of the AI Quants applications, starting with its wire contract: the closed set of stream events a run sends with the fields of each, which events begin and end a stream, the failure codes of a run with the closed fields of their detail, the business codes a JSON answer can carry with the closed fields of their detail and the chat's own rule tags of a refused request,
4
+ the body of a failed answer, the host refusal roles, the paths of the JSON, upload, content and stream endpoints with the queries they take, the resources the JSON endpoints answer with and the request that starts a run, the exchange of each endpoint the contract settles (its success's status and its bodies' shapes), the closed vocabularies, the keys of the screen's tunables, the characters of a text a reader cannot see,
5
+ and the attachments: their kinds with the model flag and the content types of each, their read text, their shapes as a resource and in a message, and the fields the chat's other resources take for them.
6
+ It subscribes to a run's stream through the host's run streams, tells a window what to show about the stream's connection, folds the stream into the view a window holds of the run, exchanges with the endpoints whose exchanges the contract settles (through the host's `fetch`),
7
+ lays out the chat's screen (the arithmetic with the container-query rules written from it, and the frame with its columns and drawers), writes and sends a message with its files and recordings (through the host's microphone), reads a refused JSON answer (by the chat's business codes, the numbers the host binds its refusal roles to, and the class of the answer's status),
8
+ gives the screen's rules for attachments by the chosen model's flags, names the diagrams a window saves, and declares the authorization resources the endpoints guard with.
9
+
10
+ The contract is data: one JSON source (`src/protocol/chatProtocol.json`) is read by this package and by the server's Python package (`aiquants-chat-core`), and the tests of each side hold its own types to the source in both directions.
11
+ Golden samples of stream frames (`tests/fixtures/chat-events-golden.json`, written by the writer in the Python package's tests) each state the answer both readers must give, and the tests of both sides give it: an accepted frame is written back byte for byte, a rewritten one (another spelling of the same value) is written in its canonical form, and a refused one is refused the way named.
12
+ Golden samples of attachments and of the JSON endpoints' resources (`tests/fixtures/chat-attachments-golden.json` and `tests/fixtures/chat-resources-golden.json`, written by the writers in the Python package's tests) each state whether both readers accept a JSON text of one shape, which an accepted text is then written back to byte for byte.
13
+ Golden samples of the characters a reader cannot see (`tests/fixtures/chat-invisible-golden.json`, written by the writer in the Python package's tests) each state the text a screen shows for a text, the number of its marks and whether the text shows anything, which both sides give.
14
+ Golden samples of file names (`tests/fixtures/export-file-names-golden.json`, written by hand) hold the title's rule this package and the Python package share, the names of a conversation's exports the server gives, and the names of the diagrams this package gives.
15
+ Golden samples of an answer's end (`tests/fixtures/chat-answer-end-golden.json`, written by hand) hold the kind of mark both sides give an ended answer, by its run's end and whether its text shows anything.
16
+
17
+ ## Prerequisites
18
+
19
+ - Node.js >= 18.0.0
20
+ - zod ^3.25.0 (a peer dependency of `./protocol`, `./client`, `./react` and `./testing`)
21
+ - For `@aiquants/chat/client`, whichever of its parts a host uses, and for `@aiquants/chat/react`, whose open conversation's window subscribes to its runs' streams: `@aiquants/sse` ^0.4.0, the first release with `assertValidReopeningOptions` (an optional peer dependency; `./client` and `./react` read it, its `./client` entry at run time and the types of its root and of its `./client` entry, and each entry reads it as it loads, so a host that uses only the transport needs it too)
22
+ - For the HTTP transport of `@aiquants/chat/client`: a runtime with the Fetch API (`fetch`, `Response`, `Headers`, `Blob`, `AbortSignal`, `ReadableStream`), the URL Standard's `URL` (which reads the bases) and `URLSearchParams`, `TextDecoder` and the Web Crypto's `crypto.getRandomValues`, as every browser, Node.js >= 20 and vitest's jsdom environment in its default pools have (Node.js 18 has no global `crypto` without a flag).
23
+ The transport reads `Response`, `Headers`, `ReadableStream`, `Blob` and `AbortSignal` through their prototypes, never through the value, and `createHttpChatTransport` refuses a runtime whose interface lacks a member it reads: an attribute must be an accessor of the interface's own prototype, as Web IDL defines it, and an operation a function the prototype reaches.
24
+ So it refuses happy-dom, which keeps those attributes on each object, and vitest's jsdom environment in a VM pool (`vmThreads`, `vmForks`), which has no `ReadableStream`.
25
+ - For `@aiquants/chat/react`: `react` and `react-dom` >= 19 and `@aiquants/console-ui` ^0.10.0 (optional peer dependencies that only `./react` reads; its components render inside console-ui's `ConsoleUiRoot`, which requires the host's presenter of access failures, an `AccessFailurePresenter` of `@aiquants/auth-core` >= 0.9.0, console-ui's own peer dependency), and a runtime with `Intl.Segmenter` and `TextEncoder`
26
+ - For `@aiquants/chat/react` too: `@aiquants/markdown` ^14.0.0, which the answers' rendering reads (the renderer's `truncated`, `mermaidDrawing` and `maxMermaidDiagrams` and the drawer's types, which 13.1.0 first had; this package reads none of the viewer that 14.0.0 split),
27
+ and `@aiquants/virtualscroll` ^3.26.0 (the first release with the list's measured heights, focused row retention, tail and end-visible states, unpinned landing and reduced motion), which the message list reads, and `@aiquants/input-method` ^0.1.2, whose `isInputMethodKey` keeps the send key off the Enter that commits an input method's composition (optional peer dependencies that only `./react` reads)
28
+ - For `@aiquants/chat/authz` only: `@aiquants/authz-core` ^0.6.2 (an optional peer dependency; the first release with `AuthzDefinition` and `collectAuthzDefinitions`: the entry reads nothing of it, and the host's registry call needs it)
29
+ - For `@aiquants/chat/testing`, in tests only: a runtime the HTTP transport takes, since every scenario drives it, with the URL Standard's `URL` and `URLSearchParams`, `TextEncoder` and `TextDecoder`, DOM's `AbortSignal.any`, and a `FileReader` where the global `Blob` has no `arrayBuffer` (jsdom 27's), as Node.js >= 24 and vitest's jsdom environment in its default pools have (the entry reads no peer dependency besides `zod`).
30
+ `createChatScenarioFetch` refuses, as the transport does, a runtime whose `Blob` or `AbortSignal` lacks a member the scenario reads through its prototype (`Blob`'s `size`, `type` and `slice`, `AbortSignal`'s `aborted`, `reason`, `addEventListener` and `removeEventListener`) or calls on the interface (`AbortSignal.any`).
31
+ On Node.js, whose `AbortSignal` keeps its state in properties of the signal, `AbortSignal.any` may refuse a signal that is frozen, sealed or made non-extensible where it would write into it, and it reads the `aborted` and `reason` members of a signal and of the signals it follows as ordinary members, where a browser reads their state, so it makes an aborted signal from one whose own or inherited `aborted` member reads true while it is not aborted: `fetch` records such an init's signal as a breach in either case.
32
+ A signal frozen after `fetch` cannot be aborted on Node, which writes an abort into the signal (its controller's `abort()` throws), and the scenario's looks at it may then throw the runtime's error; a signal whose members read otherwise than the runtime's readers only after `fetch`, or differently from one read to the next, is not supported.
33
+ The scenario relies on the abort order of Node.js 24, whose `AbortSignal` sets the aborted flags of a signal's dependents before it runs the signal's listeners, as the DOM does.
34
+ jsdom 27's `FileReader` finishes through `setImmediate`, which vitest's `vi.useFakeTimers()` fakes by default: a test with fake timers advances them while an upload is read, since every request after it waits its turn (`assertDone` names the requests still being read), or leaves `setImmediate` real.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pnpm add @aiquants/chat zod
40
+ # for the subscription of @aiquants/chat/client
41
+ pnpm add @aiquants/sse
42
+ # for the screen of @aiquants/chat/react
43
+ pnpm add react react-dom @aiquants/console-ui @aiquants/sse @aiquants/markdown @aiquants/virtualscroll @aiquants/input-method
44
+ ```
45
+
46
+ ## Entry Points
47
+
48
+ | Import path | Contents |
49
+ | --- | --- |
50
+ | `@aiquants/chat/protocol` | The frozen source (`CHAT_PROTOCOL`, `CHAT_PROTOCOL_VERSION`), the strict zod types of every event's fields (`chatEventSchemas`), of every failure code's detail (`chatFailureDetailSchemas`) and of every business code's detail (`chatBusinessDetailSchemas`, with a refused request's entries `chatRequestErrorSchema` and `chatRequestErrorsSchema`), the value types (`chatUidSchema`, `chatInstantSchema`, `chatCountSchema`, `chatStepSchema`, `chatTextSchema`, `chatTextOrEmptySchema`, `chatSearchTextSchema`, `chatSha256Schema`, `chatCursorSchema`, `chatRequestIdSchema`, `chatStreamIdSchema` with its type `ChatStreamId`, `chatCallOutcomeSchema`, `chatFailureCodeSchema`), the closed lists (`CHAT_VOCABULARIES`, `CHAT_FAILURE_CODES`, `CHAT_EVENT_REFUSALS`, `CHAT_HOST_REFUSAL_ROLES`, `CHAT_LIMIT_KEYS`, `CHAT_REQUEST_INVALID_TYPES`, `CHAT_START_EVENTS`, `CHAT_TERMINAL_EVENTS`), the types of Mermaid diagram the screen draws in an answer (`CHAT_DRAWABLE_DIAGRAMS` with its type `ChatDrawableDiagram`: a copy of `@aiquants/markdown`'s `MERMAID_DRAWABLE_TYPES`, which the server reads from the contract), the frame reader (`parseChatEvent`, `ChatEventRefusedError`, its nesting bound `CHAT_EVENT_DATA_MAX_DEPTH`, `isChatEventName`, `isTerminalChatEvent`, and the stream layer's reserved event `RESYNC_REQUIRED_EVENT`), the path helpers (`chatJsonEndpoint`, `chatUploadEndpoint`, `chatContentPath`, `chatStreamPath`) with the queries (`chatQuerySchemas`, `chatQueryString`), the attachments (`CHAT_ATTACHMENT_KINDS`, `CHAT_ATTACHMENT_KIND_FLAGS`, `CHAT_ATTACHMENT_ACCEPTED_TYPES`, `CHAT_ATTACHMENT_ORIGINS`, `CHAT_ATTACHMENT_STATES`, `CHAT_ATTACHMENT_FAILURE_TAGS`, `CHAT_ATTACHMENT_KIND_FAILURE_TAGS`, `CHAT_PDF_DELIVERIES`, the parts `chatAttachmentPageSchema`, `chatAttachmentSegmentSchema`, `chatAttachmentImageTextSchema` and `chatAttachmentPartSchemas`, the resource `chatAttachmentSchema` with its kinds' shapes `chatAttachmentKindSchemas`, a message's attachment `chatMessageAttachmentSchema` with `chatMessageAttachmentKindSchemas`, the lists `chatMessageAttachmentsSchema` and `chatAttachmentIdsSchema`, the fields other resources take `chatAttachmentFragments` with `checkChatModelAttachmentFlags`, the update's body `chatAttachmentUpdateSchema`, and the upload's body `chatAttachmentUploadSchema` in the order of its parts), the resources of the JSON endpoints (`chatConversationSchema` with `chatActiveRunSchema`, `chatConversationPageSchema`, `chatMessageSchema` with `chatMessageRoleSchemas`, `chatMessageRunSchema`, `chatMessageRunModelSchema` and `chatRunFailureSchema`, `chatMessagePageSchema`, `chatRunAcceptedSchema`, `chatRunSchema`, `chatSettingsSchema` with `chatUserSettingsSchema`, `chatConversationDefaultsSchema` and `chatLimitsSchema`, `chatModelListSchema` with `chatModelSchema`, `chatHiddenModelSchema` and `chatRecentFailuresSchema`), the request that starts a run (`chatRunRequestSchema` with `chatRunRequestKindSchemas`), the one that makes a conversation with its first message (`chatConversationRequestSchema` with its type `ChatConversationRequest`, and its answer `chatConversationAcceptedSchema`) and the body that changes a person's settings (`chatUserSettingsUpdateSchema` with its type `ChatUserSettingsUpdate`), the exchanges of the endpoints the contract settles (`CHAT_EXCHANGES` with the types `ChatExchangeEndpointName` and `ChatExchange`, the binding of their shapes to types `chatExchangeShapeSchemas` with `ChatExchangeShapeName`, and the types of an endpoint's body and answer `ChatExchangeBody` and `ChatExchangeAnswer`), the seed of a run's view (`chatRunSeedSchema` on the wire, `chatOpenStreamRunSeedSchema` for a run whose stream is open, `chatRunSeedStepSchema`, and the types `ChatRunSeed` and `ChatStepSeed`), the body of a failed answer (`chatErrorBodySchema`, `readChatBusinessError`, and the types `ChatErrorBody` and `ChatBusinessError`) and the marks of the characters a reader cannot see (`markChatInvisible` with its type `ChatMarkedText`, and `chatTextShows`) with the search text of a typed text (`chatSearchText`). |
51
+ | `@aiquants/chat/client` | The subscription to a run's stream: `openChatRunStream`, `assertValidChatRunStreams`, and the types of the host's run streams (`ChatRunStreams`, `ChatStreamReopen`), the options (`ChatRunStreamOptions`), the control (`ChatRunStreamHandle`), the status (`ChatRunStreamStatus`) and the cause of a break (`ChatStreamBreak`). The notice of the stream's connection: `nextChatStreamNotice`, `ChatStreamNotice` and the action of an unreachable stream's button (`ChatStreamNoticeAction`). The fold of a run's stream into a window's view: `seedChatRunView`, `reduceChatEvent`, the order of stream IDs (`compareChatStreamIds`), and the types of the view (`ChatRunView`, `ChatStepView` with `ChatStepKind`, `ChatStepRetry`, `ChatStepUsage` and `ChatStepFinish`, `ChatRunEnd`) and a stream item (`ChatStreamItem`); the seed and the stream ID are the contract's. The transport between the screen and the endpoints whose exchanges the contract settles: `createHttpChatTransport` with its options (`ChatHttpTransportOptions`), the host's sending (`ChatFetch`) and the host's stamp on a write (`ChatStampWrite`), and the types of a transport (`ChatTransport`, with the type of one endpoint `ChatSingleEndpoint`), a request (`ChatExchangeRequest`, with the parameters of an endpoint's path `ChatExchangeParams`), an outcome (`ChatExchangeOutcome`) and a breach of the contract (`ChatExchangeBreach`). |
52
+ | `@aiquants/chat/react` | The arithmetic of the screen and the rules written from it: `CHAT_LAYOUT`, `chatLayoutPlan`, `chatLayoutRule`, `chatFrameBlockSizePx`, and the types of a plan (`ChatLayoutPlan`, `ChatLayoutColumns`), a column (`ChatLayoutColumn`, `ChatPinnedSide`) and the rules (`ChatLayoutRule`). The screen's frame: `ChatFrame` and its props (`ChatFrameProps`). The talk's composer: `ChatComposer` and the types of its props (`ChatComposerProps`), its phase (`ChatComposerPhase`), a failed send (`ChatComposerProblem`), its attachments (`ChatComposerAttachments`) in their stages of upload (`ChatComposerAttachment`) with an endpoint's refusal (`ChatRefusal`), the saving of an attachment's alternative text (`ChatComposerSaveAltText`) with its outcome (`ChatComposerAltTextOutcome`), the model it can change back to (`ChatComposerRestore`), and the tunables it reads (`ChatComposerLimits`). The reading of a refused JSON answer: `chatRefusal` (one of the chat's business codes, a host refusal role by the host's numbers, or the class of the answer's status, with the body's request ID and code), `assertValidChatHostRefusalCodes`, and the types of a refusal (`ChatRefusal`), the class of a status (`ChatRefusalStatusClass`) and the host's numbers (`ChatHostRefusalCodes`). The microphone the composer records with: the port a host hands (`ChatMicrophone`, with a recording's request `ChatRecordingRequest`, its listener `ChatRecordingListener`, a started recording `ChatRecording`, the outcome of a start `ChatRecordingStart` and the microphone's problem `ChatMicrophoneProblem`) and the browser's (`chatBrowserMicrophone`, over a scope `ChatMicrophoneScope` such as `globalThis`, whose recorder `ChatMediaRecorderLike` records the stream `ChatMediaStreamLike` its devices open). The screen's rules for attachments by the chosen model's flags: `chatModelTakesKind`, `chatModelAttachmentKinds`, `chatFilePickerAccept`, `chatDeclaredAttachmentKind`, `precheckChatAttachment`, `chatAttachmentsRefusedByModel`, `chatAttachmentHasUnreadText`, and the types of a model's flags (`ChatModelAttachmentFlags`), the limits (`ChatAttachmentLimits`) and a refusal (`ChatAttachmentPrecheckRefusal`). The name of a diagram a window saves: `diagramFileName`, and the types of its context (`ChatDiagramFileContext`) and form (`ChatDiagramFormat`). The stream layer over the messages' answers: `ChatAnswerRendering` and the types of its props (`ChatAnswerRenderingProps`), the tunables it reads (`ChatAnswerRenderLimits`, with the conversions' `ChatConversionLimits`) and the host's factory of the browser converter (`ChatMarkdownConverterFactory`, which takes `ChatConverterTimeouts`). The message list: `ChatMessageList` and the types of its props (`ChatMessageListProps`), a message it lists (`ChatListMessage`, with its author `ChatMessageAuthor`, an answer's status `ChatAnswerStatus` and its text `ChatMessageText`) and the tunables it reads (`ChatMessageListLimits`). The window of one open conversation, which hands the list its messages and the composer its notice: `useChatConversation` and the types of its options (`ChatConversationOptions`, with its tunables `ChatConversationLimits`), its state (`ChatConversationState`) and what it answers (`ChatConversationWindow`). The sending and the stopping in that window, which hand the composer its phase and failed send and the list the message sent: `useChatSend` and the types of its options (`ChatSendOptions`), a message to send (`ChatSendMessage`), a send's outcome (`ChatSendOutcome`) and what it answers (`ChatSend`). The first send of a new conversation, which makes it: `useChatNewConversation` and the types of its options (`ChatNewConversationOptions`), a first message (`ChatNewConversationMessage`), a first send's outcome (`ChatNewConversationOutcome`) and what it answers (`ChatNewConversation`), with the announcement that it was made (`useChatConversationCreatedAnnouncer`). A new conversation's choice of its level, model and reasoning level: `useChatNewConversationChoice` and the types of its options (`ChatNewConversationChoiceOptions`), a row that can be chosen (`ChatChoosableModel`) and what it answers (`ChatNewConversationChoice`), and the groups that draw it, `ChatNewConversationChoices` and the type of its props (`ChatNewConversationChoicesProps`). The person's settings and their saving: `useChatSettings` and the types of its options (`ChatSettingsOptions`), its state (`ChatSettingsState`), a failed save (`ChatSettingsProblem`), a save's outcome (`ChatSettingsSaveOutcome`) and what it answers (`ChatSettingsAccess`). A list of models, a new conversation's or a conversation's: `useChatModels` and the types of its options (`ChatModelsOptions`), its query (`ChatModelsQuery`), its state (`ChatModelsState`) and what it answers (`ChatModels`). The form over both: `ChatSettingsForm` and the type of its props (`ChatSettingsFormProps`). The wait for the settings, which draws the screen's parts with the open settings: `ChatSettingsGate` and the type of its props (`ChatSettingsGateProps`). The talk's heading at the screen's heading origin, whose title's text carries the id the message list names: `ChatTalkHeading` and the type of its props (`ChatTalkHeadingProps`). The talk's flow, which scrolls what stands above the composer in place of a message list: `ChatTalkFlow` and the type of its props (`ChatTalkFlowProps`). The wait for the open conversation's window: `ChatConversationGate` and the type of its props (`ChatConversationGateProps`). The list of the person's conversations: `useChatConversationList` and the types of its options (`ChatConversationListOptions`, with its tunables `ChatConversationListLimits`), what it answers (`ChatConversationListState`) and a section of it (`ChatConversationSection`), and `ChatConversationList` with the types of its props (`ChatConversationListProps`) and the tunables it reads (`ChatConversationListViewLimits`). |
53
+ | `@aiquants/chat/authz` | `CHAT_RESOURCES`: the resources `chat`, `chat_admin` and `chat_audit`, in the shape a host's authorization registry collects, frozen with each definition. |
54
+ | `@aiquants/chat/testing` | The scenario a test runs the package's own transport over, answering in the server's place: `createChatScenarioFetch` with the types of the scenario (`ChatScenarioFetch`), its options (`ChatScenarioFetchOptions`, with the host's server's reading of a write's stamp `ChatUnstampWrite`), a step (`ChatScenarioStep`), a reply (`ChatScenarioReply`, with `ChatScenarioAnswer` and `ChatScenarioRefusedReply`), the request it read back (`ChatScenarioRequest`) and a held step's handle (`ChatScenarioHold`). The refused reply of a business code: `chatScenarioRefusal` and its fields (`ChatScenarioRefusalFields`). |
55
+
56
+ Every function and part of `./client`, `./react` and `./testing` refuses a value a host hands it where it is handed, before anything depends on it.
57
+ A refusal's message has one form, `<caller>: <field> must <rule>, got <what was given>`: a value of the wrong type is a `TypeError`, and a value of the right type outside its rule is a `RangeError`, as is any value outside a closed list of words, a tunable or a value of the contract, whatever its type.
58
+ The field is an argument's or a prop's path (`attachments.restore.modelName`), the rule is most often `be …` (`be null or …` for a field that also takes `null`), and what was given is the value, written as below, with the words that place it when the rule is about a part of the value (`got the key "x"`, `got "x" twice`) or words for a value of the right type whose shape breaks the rule (`got an empty array`).
59
+ Two refusals have another form. `@aiquants/sse`'s of the run streams' numbers and terminal events' names is a `RangeError`, since every value it sees has the right type, with sse's message after `<caller>: @aiquants/sse refuses the streams' reopening options:`.
60
+ The refusal of a string base of the contract's paths (a run stream's `baseUrl`, the composer's `contentBaseUrl`, the transport's and the scenario's `jsonBaseUrl` and `uploadBaseUrl`) names the caller, the field and the rule with no `got`, since a base may hold credentials (see [Subscribing to a run's stream](#subscribing-to-a-runs-stream) for both).
61
+ The value is written the same way in every refusal: a string quoted (`JSON.stringify`), a number, a boolean and `undefined` as they are, a bigint with its `n`, `null` as it is, and any other value by its type, running none of its code. A value of the contract is checked by its own schema: its refusal ends with the schema's first issue in parentheses and holds the schema's error as its cause, and an object or a function the schema accepted is not checked by it again.
62
+ A run's view and an item of its stream are checked the same way, by the package's schemas built from the contract's, and the views and the items the package makes are never parsed again.
63
+
64
+ ## Usage
65
+
66
+ ### Reading a stream frame
67
+
68
+ An event travels as one SSE frame: the frame's `event` is the event's name and its `data` is the compact JSON of the event's fields. `resync-required`, the stream layer's reserved event, carries an empty `data`.
69
+
70
+ ```ts
71
+ import { type ChatEvent, ChatEventRefusedError, isTerminalChatEvent, parseChatEvent } from "@aiquants/chat/protocol"
72
+
73
+ const readFrame = (frame: MessageEvent<string>, onEvent: (event: ChatEvent) => void, onEnd: () => void): void => {
74
+ try {
75
+ const event = parseChatEvent(frame.type, frame.data)
76
+ onEvent(event) // for "text.delta", event.data is { step, text }
77
+ if (isTerminalChatEvent(event.event)) {
78
+ onEnd()
79
+ }
80
+ } catch (error) {
81
+ if (error instanceof ChatEventRefusedError) {
82
+ // error.refusal is one of "unknown_event", "reserved_data", "too_deep", "not_json" and "shape";
83
+ // the message names fields and issue codes, never the data itself
84
+ }
85
+ throw error
86
+ }
87
+ }
88
+ ```
89
+
90
+ Every event's fields are a strict object: a missing field, an extra field, a value of another type and a value outside its closed vocabulary are all refused (`shape`).
91
+ Counts are integers from 0 up to `Number.MAX_SAFE_INTEGER`, a step is numbered from 1, a uid is an RFC 9562 version 7 UUID in lower case, an instant is UTC in ASCII digits with seven fractional ones (`yyyy-mm-ddThh:mi:ss.fffffffZ`) naming a real time from year 1 to 9999, and a text is not empty and holds no lone surrogate, which no UTF-8 stream carries.
92
+ `run.failed` takes the shape of its `error_code`: each failure code has its own closed `detail`.
93
+
94
+ A frame is refused in one of five ways, checked in the order of `CHAT_EVENT_REFUSALS`: a name the contract does not hold (`unknown_event`, an inherited property's name such as `toString` included), data on `resync-required` (`reserved_data`), data that opens more than `CHAT_EVENT_DATA_MAX_DEPTH` arrays and objects inside one another, the data's own object included (`too_deep`, counted outside strings before the data is parsed, so a text that is not JSON is counted too), data that is not JSON (`not_json`) and fields outside the event's shape (`shape`).
95
+ Every spelling JSON allows reads as the same value in both languages: a number is the nearest double and an integral one is an integer (`1.0`, `1E2` and `9.007199254740991e15` are steps, while a literal past a double's range is no number the shapes take), and a member given twice is read as its last value.
96
+
97
+ A stream begins with `run.started` (`CHAT_START_EVENTS`) and ends with `run.completed`, `run.failed`, `run.cancelled` or `resync-required` (`CHAT_TERMINAL_EVENTS`, `isTerminalChatEvent`).
98
+
99
+ ### Subscribing to a run's stream
100
+
101
+ `openChatRunStream` subscribes to one run's stream through the host's run streams (`ChatRunStreams`) on `@aiquants/sse`'s reopening EventSource: it reads every frame as an item of the contract with the frame's own ID, and ends on the contract's terminal events and on the host's own.
102
+ `assertValidChatRunStreams` refuses the host's run streams a subscription would refuse, with the same rules and messages as at open (naming itself as the caller), before anything depends on them; it opens, schedules and reports nothing. Every field of the streams is read once, the runtime's members and the terminal events (by index) included, and the subscription and `@aiquants/sse`'s check use only what was read (the runtime's functions read are called as its methods), so a change the host makes to the streams after the open changes nothing.
103
+ Every field's type is refused in the package's form, running none of the refused value's code; `@aiquants/sse`'s check of the reopening options then refuses the numbers outside their rules and the terminal events' names, and since every value it sees has the right type, its refusal is thrown as a `RangeError` that names the caller, gives sse's message after `@aiquants/sse refuses the streams' reopening options:` and holds sse's error as its cause.
104
+
105
+ ```ts
106
+ import { systemSseRuntime } from "@aiquants/sse"
107
+ import { createBrowserEventSource } from "@aiquants/sse/client"
108
+ import { assertValidChatRunStreams, type ChatRunStreams, type ChatRunView, type ChatStreamNotice, nextChatStreamNotice, openChatRunStream, reduceChatEvent, seedChatRunView } from "@aiquants/chat/client"
109
+ import type { ChatRunSeed } from "@aiquants/chat/protocol"
110
+
111
+ const streams: ChatRunStreams = {
112
+ baseUrl: "/bff",
113
+ cursorParam: "lastEventId",
114
+ terminalEvents: ["session-expired", "forbidden"],
115
+ reopen: {
116
+ withCredentials: true,
117
+ createEventSource: createBrowserEventSource,
118
+ runtime: systemSseRuntime,
119
+ backoff: { initialDelayMs: 1000, maxDelayMs: 30000, multiplier: 2 },
120
+ healthyOpenMs: 10000,
121
+ nativeRetryLimit: 1,
122
+ giveUpAfterFailures: 6,
123
+ staleAfterMs: 45000,
124
+ },
125
+ }
126
+ assertValidChatRunStreams(streams)
127
+
128
+ const watch = (runUid: string, seed: ChatRunSeed) => {
129
+ let view: ChatRunView = seedChatRunView(seed)
130
+ let notice: ChatStreamNotice | null = null
131
+ return openChatRunStream({
132
+ streams,
133
+ runUid,
134
+ initialLastEventId: view.mark,
135
+ onItem: (item) => {
136
+ view = reduceChatEvent(view, item)
137
+ },
138
+ onStatus: (status) => {
139
+ notice = nextChatStreamNotice(notice, status)
140
+ },
141
+ })
142
+ }
143
+ // The notice's button: `reconnectNow()` for "reconnect-now"; for "reread", read the conversation again and watch anew from its mark.
144
+ // When the window closes: `close()`.
145
+ ```
146
+
147
+ - The first open asks for `<baseUrl>/ai/chat/runs/<run_uid>/events`, with the mark as `?<cursorParam>=<mark>` when there is one, and each reopen carries the ID of the last item passed (the mark before any). A new EventSource cannot set `Last-Event-ID`, so the host's gateway reads `cursorParam` and passes it upstream as that header. A reopen asks for the path and parameter the subscription opened with, whatever the host changes later.
148
+ - `baseUrl` is empty (the origin's root), an absolute path of the page's origin or an absolute http(s) URL the URL parser (`URL`) reads, written as `http://` or `https://` and a non-empty authority without credentials (no `@` before the first `/`: the package never carries credentials in a URL, the host's `fetch` and the streams' `withCredentials` carry them, and `fetch` refuses a URL that holds them).
149
+ An absolute URL's path does not begin with `//`: what follows its origin is a path of that origin, as the target a write's stamp receives must be, and read as a reference a leading `//` names another host, as it does in a base of the page's origin.
150
+ It has no query, fragment, backslash, space or control character, no `.` or `..` between two slashes or after the last one, and does not end with `/`.
151
+ A `.` or `..` is refused whether written with dots or `%2e`: the URL parser resolves either, so the joined URL would not be the base as written, and a `..` takes the paths appended after it out of the base's path.
152
+ The rule checks the base's form, not whether a request can reach it: under a port the browser blocks or a host that does not resolve, every request fails (the stream cannot connect, and an exchange ends `unreached`).
153
+ Its refusal names the caller and the field, and never repeats a string base, which may hold credentials. The composer's content base (`contentBaseUrl`) and the transport's two bases follow the same rule.
154
+ - `reopen` holds every field of `@aiquants/sse`'s reopening options the host decides, each required and without a default. `giveUpAfterFailures` is a number, never `"never"`, so a stream that cannot connect ends as `exhausted`.
155
+ - Each item carries its frame's own ID. An EventSource shows a frame without an `id` the previous ID, and a new EventSource shows it an empty one; stream IDs never repeat, so a frame whose ID is missing, outside the stream ID's form or the same as the previous item's has no ID of its own. `resync-required` is passed without an ID.
156
+ - A frame without an event name, a frame the contract refuses, a frame without an ID of its own and a `run.started` of another contract version close the subscription and end it as `{ kind: "broken", cause }`, the cause (`ChatStreamBreak`) being `refused` with the reader's `ChatEventRefusedError`, `id` with the event's name, or `protocol` with the stream's version. The frame is not passed, and the `closed` of the closing is not reported.
157
+ - A contract's terminal event is passed as the last item, then its `terminated` is reported. A host's terminal event ends the subscription with its `terminated` and no item, its data unread.
158
+ - Every other status is reported as `@aiquants/sse` gives it (`connecting`, `open`, `retrying`, `waiting`, `exhausted`, `faulted`, `closed`), the first `connecting` before `openChatRunStream` returns. `reconnectNow()` reopens at once from `waiting` or `exhausted` with the failure count back to 0, and returns `false` from any other status; `close()` is idempotent and does nothing from a final status.
159
+ - `openChatRunStream` also refuses options that are not an object with a `TypeError`, a `runUid` the contract's schema refuses as a uid and an `initialLastEventId` that is neither `null` nor a stream ID with a `RangeError`, and an `onItem` or `onStatus` that is not a function with a `TypeError`. What the first `createEventSource` throws reaches the caller after the first `connecting`, with nothing left open.
160
+
161
+ ### Folding a run's stream
162
+
163
+ A window holds one view of a run: the mark (the ID of the last item it applied), the fields of `run.started`, each step's state in the order of the steps' numbers (its kind, text, reasoning summary, retries, usage and end), and the event that ended the view.
164
+ The view begins from the seed the read of the run's answer message gives (its run's `view`, read by `chatRunSeedSchema`), which is the view at the mark, and takes the stream's items one by one.
165
+ A view folds a stream, so it begins only from the seed of a run whose stream is open (`stream_open` on the message's run).
166
+
167
+ ```ts
168
+ import { type ChatRunView, type ChatStreamItem, reduceChatEvent, seedChatRunView } from "@aiquants/chat/client"
169
+ import type { ChatRunSeed } from "@aiquants/chat/protocol"
170
+
171
+ const start = (seed: ChatRunSeed): ChatRunView => seedChatRunView(seed)
172
+
173
+ const apply = (view: ChatRunView, item: ChatStreamItem): ChatRunView => reduceChatEvent(view, item)
174
+ ```
175
+
176
+ The subscription passes each item with its frame's own ID. A caller that reads frames itself passes the frame's own `id` field, not an `EventSource`'s `lastEventId`, which keeps the previous ID for a frame without one, so the reducer would discard the frame as already applied.
177
+
178
+ - A stream ID is a Redis stream entry's `<ms>-<seq>`: two unsigned 64-bit numbers in decimal without leading zeros. Two IDs are ordered as numbers, milliseconds first (`compareChatStreamIds`), since a text comparison puts `1-10` before `1-9`. A text is an ID only once the contract's `chatStreamIdSchema` has read it (a zod brand). `compareChatStreamIds` refuses an argument the contract's schema refuses as a stream ID with a `RangeError` naming it (`left` or `right`).
179
+ - `seedChatRunView` refuses with a `RangeError` a seed the contract's `chatOpenStreamRunSeedSchema` refuses: a seed with fields outside the contract, a seed whose steps are not in increasing order of their numbers, and a seed without a mark that holds a step's text or reasoning, which the stream read from its beginning would carry again. The schema names every break of these two rules, in the steps' order.
180
+ The seed on the wire (`chatRunSeedSchema`) is held to the order rule alone: a run whose stream is no longer open (its writer stopped it, or fenced it off) may write its answer without a mark, and the message's run holds its view to the mark rule only while `stream_open` is true.
181
+ - `reduceChatEvent` never changes the view in place. After the event that ended the view, and for an item at or below the mark, it returns the view itself. A view without a mark whose first item is not a start event (`CHAT_START_EVENTS`) ends with `resync-required`, as it cannot know it holds the stream's beginning.
182
+ - The events a takeover can write again are put by key, so a second copy changes nothing: `run.started` once, `step.started` creates a missing step and leaves one the view holds, `step.retry` once per retry's number, `usage` puts the step's absolute totals, and `step.finished` once. `step.reset` drops its step's whole state, so the step's next `step.started` and deltas apply from the beginning.
183
+ - An event naming a step the view lacks is not applied, and its ID still becomes the mark. `run.completed`, `run.failed`, `run.cancelled` and `resync-required` end the view with their fields (`end`); an item without an ID does not move the mark.
184
+ - `reduceChatEvent` checks the view, then the item, where they are handed, and refuses with a `RangeError` naming `view` or `item`, the contract's issue and the schema's error as its cause: a view with a field outside a view, steps that break the seed's two rules, a step's retries out of the increasing order of their numbers, or an end other than a contract's terminal event, and an item with a field outside an item, an event the contract does not hold, an ID outside a stream ID's form, or an event other than the stream layer's `resync-required` without an ID.
185
+ The views `seedChatRunView` and `reduceChatEvent` return and the items the subscription passes are never parsed again, so the check reads only a view or an item the host made, and that once; a view that grows over a long run is not read again at every item.
186
+ - The fold does not compare the contract's version: the subscription ends as `broken` on a `run.started` of another version, and a caller that reads frames itself compares `view.started.protocol` with `CHAT_PROTOCOL_VERSION` and stops reading on a different one.
187
+
188
+ ### Showing the stream's connection
189
+
190
+ `nextChatStreamNotice(previous, status)` decides the notice a window shows near its input from the previous notice and the subscription's status. The notice names what is shown; the window writes the words of its own catalog.
191
+
192
+ | Status | Notice |
193
+ | --- | --- |
194
+ | `open`, `closed`, `terminated` on a contract's terminal event | none (`null`) |
195
+ | `retrying` (the browser's own short reconnect) | the previous one, so the notice neither blinks nor is read out again |
196
+ | `connecting` without failures | `reconnecting` after `unreachable` (the button was pressed), otherwise the previous one |
197
+ | `connecting` after failures, `waiting` | `reconnecting` |
198
+ | `exhausted` | `unreachable` with `reconnect-now` (the subscription's `reconnectNow`) |
199
+ | `faulted`, `terminated` on a host's terminal event | `unreachable` with `reread` (read the conversation again; `reconnectNow` cannot revive them) |
200
+ | `broken` | `incompatible` (only reloading the page mends it) |
201
+
202
+ Every notice is one of four frozen values, so an unchanged notice is the very object returned before.
203
+ The window shows one more notice that no status gives: `awaiting-end`, while its state read waits for the end of a run whose stream cannot go on (below).
204
+ `nextChatStreamNotice` checks the previous notice, then the status, where they are handed: a previous notice that is neither `null` nor an object is a `TypeError`, and one whose kind is not one a status gives (`awaiting-end` included), or for `unreachable` whose action is not one of the notice's words, is a `RangeError`.
205
+ A status that is not an object is a `TypeError` and one whose kind the subscription does not have is a `RangeError`; of its fields, only those its kind reads are checked: a `terminated`'s `terminalEvent` must be a string (a `TypeError`), and a `connecting`'s `consecutiveFailures` an integer from 0 (a `TypeError` for a value that is not a number, a `RangeError` otherwise).
206
+
207
+ ### Filling a path
208
+
209
+ ```ts
210
+ import { chatContentPath, chatJsonEndpoint, chatStreamPath, chatUploadEndpoint } from "@aiquants/chat/protocol"
211
+
212
+ const { method, path } = chatJsonEndpoint("getConversation", { conversation_uid })
213
+ // method "GET", path "/ai/chat/conversations/<conversation_uid>"
214
+
215
+ const upload = chatUploadEndpoint("createAttachment")
216
+ // method "POST", path "/ai/chat/attachments" (a multipart body)
217
+
218
+ const preview = chatContentPath("getAttachmentPreview", { attachment_uid })
219
+ // "/ai/chat/attachments/<attachment_uid>/preview" (an image, not JSON)
220
+
221
+ const stream = chatStreamPath("runEvents", { run_uid })
222
+ // "/ai/chat/runs/<run_uid>/events"
223
+ ```
224
+
225
+ The endpoints are in four groups: JSON, an upload with a multipart body (`chatUploadEndpoint`), content a screen shows or saves as it is (`chatContentPath`, always `GET`) and the stream. Each value fills one path segment and is encoded with `encodeURIComponent`. A parameter the path names without a value, an empty value and a value the path does not name are refused with a `RangeError`. The paths are relative to the host's mount point of the chat's API.
226
+
227
+ ### Reading an attachment
228
+
229
+ ```ts
230
+ import { CHAT_ATTACHMENT_KIND_FLAGS, chatAttachmentFragments, chatAttachmentSchema, chatUidSchema, checkChatModelAttachmentFlags } from "@aiquants/chat/protocol"
231
+ import { z } from "zod"
232
+
233
+ const attachment = chatAttachmentSchema.parse(await response.json())
234
+ // attachment.kind is "image", "document" (a PDF) or "audio", with the kind's own fields
235
+
236
+ const modelSchema = z.object({ model_uid: chatUidSchema, ...chatAttachmentFragments.model }).strict().superRefine(checkChatModelAttachmentFlags)
237
+ const takesPdf = modelSchema.parse(model)[CHAT_ATTACHMENT_KIND_FLAGS.document]
238
+ ```
239
+
240
+ An attachment resource carries a failure tag exactly when it failed, one its kind fails with (`CHAT_ATTACHMENT_KIND_FAILURE_TAGS`: an image fails for no reading), and only a ready one holds read text (`parts`): the text read in an image, the pages of a PDF from its text layer or by OCR, or the segments of an audio's transcription, each part in the order of its page or start. A message's attachment (`chatMessageAttachmentSchema`) is the summary of a ready attachment bound to the message, without its digest and read text.
241
+ An image whose text the OCR inside the deployment did not read is ready with `text_unread`, and a PDF names the pages it could not read (`unread_pages`): a run whose model is outside the deployment refuses either (the rule tag `attachment_unread_for_external_model`), and a model inside the deployment takes both. A message's attachment carries both marks too, so a screen tells which attachments of the context such a model refuses before a send.
242
+ A model's flag for each kind is the one switch of the kind for the model, and `checkChatModelAttachmentFlags` holds how the model takes a PDF (`pdf_delivery`) to its flag for PDFs. The fields of `chatAttachmentFragments` are joined into the full shapes of a message, of the request that creates one and of a model.
243
+
244
+ ### Reading a JSON answer
245
+
246
+ ```ts
247
+ import { chatJsonEndpoint, chatMessagePageSchema, chatQueryString } from "@aiquants/chat/protocol"
248
+
249
+ const { path } = chatJsonEndpoint("listMessages", { conversation_uid }) // method "GET"
250
+ const url = `${path}${chatQueryString("listMessages", { cursor })}`
251
+ // "/ai/chat/conversations/<conversation_uid>/messages", followed by "?cursor=<cursor>" when a cursor is given
252
+
253
+ const page = chatMessagePageSchema.parse(await response.json())
254
+ // page.items: the path of the chosen branch, the root's side first; page.next_cursor: the earlier page's cursor, or null
255
+ ```
256
+
257
+ Every resource is a strict object whose fields and presences are the source's `resources`: a conversation's row with its run that has not ended, a page of rows with the next page's cursor, a message of either role, the request that starts a run of each kind with the answer accepting it, the request that makes a conversation with its first message with the answer holding the conversation's row and its first run's acceptance, the read of a run, the settings with what a new conversation starts with and the screen's tunables, and the list of models.
258
+ Every conversation is made with its first message: the request that makes it holds a send's fields without its kind and parent, then the conversation's declared confidentiality level, never below the tenant's default, so a conversation's row always has its model, its reasoning level and its chosen root, and a send always names the answer it follows.
259
+ An answer message carries the run that writes it, with its finish reason only when it completed (its `run.completed`'s, the reason of the step that ended its answer), its failure only when it failed, who cancelled it only when it was cancelled, and its view at the mark, which `seedChatRunView` starts a window's view from.
260
+ The list of models holds every model once, a hidden row (its uid and `access_denied` only) first when the conversation names a model the person may not read, and each shown row with the reasoning level a choice of it starts at; its query names the conversation whose list it is or a new conversation's declared level, not both.
261
+ `chatQueryString` writes an endpoint's query in the source's order, leaving the absent fields out and writing a truth as `true` or `false`. The closed vocabularies the fields take are `CHAT_VOCABULARIES`, each in its order.
262
+ The conversations' list answers a page from its head, or past `cursor`. With `until` instead, a cursor the list answered, it answers every row from its head before that cursor, not cut by the page's size, and its `next_cursor` is `until` while a row follows (`null` when none does), so a window reading again the rows it shows keeps the cursor it holds for the next page. A query naming both `cursor` and `until` is refused.
263
+ A query's `q` is a search text (`chatSearchTextSchema`): a text of the contract without white space at either end, which `chatSearchText` makes of what a person typed (see [Showing the characters a reader cannot see](#showing-the-characters-a-reader-cannot-see)).
264
+ When nothing is left, a screen leaves `q` out of the conversations' list and does not search a conversation, whose `q` is required. An answer holding a lone surrogate, which only a typed text holding one gives, is no search text either. The server refuses any other `q` instead of trimming it.
265
+ An answer's or a request's JSON text naming a member of an object twice is outside the contract, as I-JSON (RFC 7493) has it: `JSON.parse` keeps the last value and drops the earlier ones unread, while the Python side's reader reads them too and refuses the text for one it cannot read (a lone surrogate's escape, nesting past its recursion limit).
266
+
267
+ ### Reading an endpoint's exchange
268
+
269
+ ```ts
270
+ import { CHAT_EXCHANGES, type ChatExchangeAnswer, chatExchangeShapeSchemas } from "@aiquants/chat/protocol"
271
+
272
+ const { status, answer } = CHAT_EXCHANGES.startRun
273
+ // status 202 and answer "run_accepted" (CHAT_EXCHANGES.startRun.body is "run_request")
274
+
275
+ const accepted: ChatExchangeAnswer<"startRun"> = chatExchangeShapeSchemas[answer].parse(await response.json())
276
+ ```
277
+
278
+ `CHAT_EXCHANGES` holds, for each JSON or upload endpoint the contract settles and in the paths' order, the HTTP status of its success and the shapes of its request's and its answer's bodies, `null` where it has none: an endpoint answers no body exactly when its status is 204 (`deleteAttachment`), only an upload takes a multipart body, and every answer is JSON.
279
+ `chatExchangeShapeSchemas` binds every shape the table names to its type, among them the upload's body as a screen hands it over (`chatAttachmentUploadSchema`, in the order of the body's parts: the model it is meant for, the file's name, the alternative text, left out when there is none, and last the file as a `Blob`, so that the server checks the model before it reads the file).
280
+ `ChatExchangeBody<endpoint>` and `ChatExchangeAnswer<endpoint>` are the types of a request's body as its caller gives it and of an answer's body as its shape reads it, `null` where there is none: a stream ID an answer holds is a `ChatStreamId`. The content and stream endpoints are not in the table, nor yet the JSON endpoints whose shapes are still to be settled.
281
+
282
+ ### Exchanging with an endpoint
283
+
284
+ ```ts
285
+ import { createHttpChatTransport } from "@aiquants/chat/client"
286
+ import { chatRefusal } from "@aiquants/chat/react"
287
+
288
+ // the host's relay of JSON calls, a base that takes multipart bodies, and the host's stamp on every write
289
+ // (a host whose server checks no reader passes `(target) => target`)
290
+ const transport = createHttpChatTransport({ jsonBaseUrl: "/gateway", uploadBaseUrl: "/upload", fetch, stampWrite })
291
+
292
+ const outcome = await transport.exchange("listConversations", { query: { pinned: true }, signal })
293
+ if (outcome.kind === "answered") {
294
+ // outcome.answer is the page as `conversation_page` reads it, frozen
295
+ } else if (outcome.kind === "refused") {
296
+ const refusal = chatRefusal(outcome.status, outcome.body, hostRefusalCodes)
297
+ }
298
+
299
+ const uploaded = await transport.exchange("createAttachment", { body: { model_uid: modelUid, file_name: file.name, file } })
300
+ ```
301
+
302
+ `createHttpChatTransport` makes the package's transport over HTTP (`ChatTransport`, a frozen value), which sends every exchange through the host's `fetch` (`ChatFetch`, called as a plain function, so the browser's `fetch` can be handed as it is; a host that changes how credentials go wraps it). Its options are read once, in the order `jsonBaseUrl`, `uploadBaseUrl`, `fetch`, `stampWrite`, and `fetch` and `stampWrite` must be functions: `stampWrite` has no default, so a host whose server checks no reader passes the identity.
303
+ Once they are checked, it refuses with a `TypeError` naming the member a runtime that lacks a member of the platform's interfaces the transport reads through their prototypes, so such a runtime fails when the transport is made rather than at an exchange (see [Prerequisites](#prerequisites)).
304
+ Its one operation, `exchange(endpoint, request)`, takes an endpoint of the exchanges' table (`CHAT_EXCHANGES`) with its request (`ChatExchangeRequest<endpoint>`: `params`, the parameters its path names, only and always for an endpoint whose path names one; `query`, only for an endpoint that takes one, which may be left out when every field may be; `body`, only and always for an endpoint that takes one; and `signal`).
305
+ Its type takes one endpoint and refuses a union of several, whose requests' fields would merge (every member's parameters, any member's body): it takes the endpoint as `ChatSingleEndpoint<Endpoint>` (the endpoint, or `never` for a union).
306
+ A function that holds an endpoint in a type parameter and hands it on declares it the same way and passes no type argument (`<E extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<E>, request: ChatExchangeRequest<E>) => transport.exchange(endpoint, request)`, with `ChatExchangeEndpointName` from `./protocol`).
307
+ It answers one of four outcomes (`ChatExchangeOutcome<endpoint>`) and never throws for a failed sending or a broken answer:
308
+
309
+ - `answered`: the answer at the endpoint's success status, as its shape reads it (`null` for `deleteAttachment`, which answers no body).
310
+ - `refused`: a status from 400 to 599 with the failed answer's body, which `chatRefusal` reads (see [Showing a refused answer](#showing-a-refused-answer)); one of the chat's business codes only at its own status, a host's code or another code at any of them.
311
+ - `unreached`: no answer was read, since the sending threw or rejected (its signal stopping it included) or the answer's body broke off.
312
+ - `incompatible`: an answer that breaks the contract, with its breach (`ChatExchangeBreach`: `status`, another status, a redirect among them, which a browser answers with status 0 and a runtime whose `fetch` hands the redirect back with its 3xx status; `content-type`, a body not declared `application/json`; `json`, a body that is not a JSON text in UTF-8; `shape`, a body its shape refuses, with the `ZodError`; `business-status`, a business code at another status).
313
+
314
+ After `unreached` and `incompatible`, whether the request took effect is known only once the screen reads the server again: the endpoint may have acted on a request whose answer never arrived, and a request sent again acts again unless the endpoint guards against it (a run's `client_request_id` does; an upload does not).
315
+
316
+ A request is checked before anything is sent and refused naming `ChatTransport.exchange`, its fields read once each and checked in the order `endpoint`, `request`, `params`, `query`, `body`, `signal`.
317
+ It refuses an endpoint outside the table, a request that is not an object, `params` that are not an object where the path names a parameter, a parameter missing or not a chat uid (only the parameters' own keys are read) or an own enumerable key the path does not name, and a field the endpoint does not have unless left out.
318
+ It refuses a query or a body its schema refuses, an upload's file that is not a `Blob` as the browser's `Blob` reads one, and a signal that is not an `AbortSignal` as the browser's reads one.
319
+ The query and the body are sent as their schemas read them and an upload's file as the copy the browser's readers of a `Blob` make of it, so no getter, `toJSON` or prototype of the caller's runs.
320
+ A JSON endpoint is sent to `jsonBaseUrl` and an upload to `uploadBaseUrl` (a host's relay of JSON calls may refuse a multipart body; both may be one base), with the path's method, `Accept: application/json`, and a JSON body with its `Content-Type` or an upload's multipart body, no redirect followed (`redirect: "manual"`), no HTTP cache (`cache: "no-store"`, so a conversation is never kept there) and the signal when there is one. It is sent once and never again.
321
+ The transport writes an upload's multipart body itself: one part a field in the order of the upload's fields (the alternative text left out when there is none, the file last), and every text byte for byte in UTF-8 (`FormData` would rewrite a lone line feed or carriage return as CRLF, which the same text sent as JSON keeps).
322
+ The file's part is named by `file_name` (a line feed, a carriage return and a quotation mark escaped as `%0A`, `%0D` and `%22`, as browsers write a file's name) and has the file's type (`application/octet-stream` for a file without one); the boundary is `aiquants-chat-` followed by 16 bytes from `crypto.getRandomValues` in hexadecimal, made for each sending and declared in the body's `Content-Type`.
323
+ The answer is read once by the browser's own readers of a `Response`, its `Headers` and its body's stream, never by values the answer or its stream gives itself, its body declared `application/json` by a `Content-Type` holding one value (the type in any case, with any parameters) and decoded as UTF-8 without replacing a broken sequence; a body the transport does not read is cancelled.
324
+ The `Content-Type` is split into values as Fetch splits a header, at each comma outside a quoted string, a quoted string running to its closing quotation mark or, left open, to the value's end.
325
+ So a header given more than once, which `Headers` joins with commas, declares no type, unless a quoted string one of its values leaves open runs across a joining comma.
326
+ Every outcome is frozen, a breach included; the answer and the failed answer's body are frozen down to every array and plain object inside and held as accepted by the shapes that read them, so `chatRefusal` does not parse them again.
327
+ Every write (a request of any method but `GET` and `HEAD`) goes through the host's `stampWrite` (`ChatStampWrite`) once, after its request is checked and before it is sent; a read never does.
328
+ It is called as a plain function with the write's target, its path and query after the base's origin, which begin with one `/` (`/upload/ai/chat/attachments` for the base `/upload`, and for `https://files.example.test/upload` too), and answers the target the write is sent to, which the transport puts after the base's origin as the base writes it.
329
+ So a host whose server checks who reads the screen a write comes from puts its stamp there, its name and form the host's own (the package knows neither); the answer must be a path of the same origin that begins with one `/`, one the URL parser resolves as a path of whatever origin it is joined to, so a `//host`, a `/\host` or a tab or line break between the slashes is refused.
330
+ An exchange rejects only when its caller or the host breaks the port: a refused request, a `stampWrite` that breaks its port, or a `fetch` that resolves to something other than a `Response` (an object that only inherits from its prototype included) or to one whose body was read, cancelled or is locked, as the browser's readers tell rather than the answer's own members (a `TypeError`).
331
+ A `stampWrite` that throws is refused with a `RangeError` whose cause is what it threw, one that answers a value that is not a string with a `TypeError`, and one that answers a string that is not such a path with a `RangeError` that does not repeat it (it carries the host's stamp), each before anything is sent.
332
+
333
+ ### Reading a failed answer
334
+
335
+ ```ts
336
+ import { chatErrorBodySchema, readChatBusinessError } from "@aiquants/chat/protocol"
337
+
338
+ const body = chatErrorBodySchema.parse(await response.json())
339
+ const error = readChatBusinessError(body)
340
+ if (error?.name === "CHAT_STATE_CONFLICT" && error.detail?.kind === "attachment") {
341
+ // error.detail.reason is "processing", "failed" or "already_bound"
342
+ }
343
+ ```
344
+
345
+ Every failed answer has the platform's body: the business code's number, the name the failure was raised as, the request's ID, the detail (a text for the operator, which may be empty, or the code's object) and the stage a failure is put on when the endpoint names one.
346
+ An object detail of any code is a JSON object every language reads alike: no lone surrogate in a name or a text, numbers within ±`Number.MAX_SAFE_INTEGER` (the bound of the contract's counts, within which every number is one value in every language, while past it another language may read exactly an integer's literal `JSON.parse` rounds), JSON values only, and at most `CHAT_EVENT_DATA_MAX_DEPTH` (8) arrays and objects open inside one another.
347
+ It may be made in another realm, as that realm's `JSON.parse` makes it, but it holds no array or object twice: a JSON reading makes a new one for each `[` and `{`, so only a value built in code shares one or holds one inside itself.
348
+ It is read once into a copy after the body's other fields (a body refused for another field is refused for it alone), never by zod, whose check of a value's type reads the value's `then` and `catch` and walks its prototypes, and without recursion at any depth, each array and object opened once and each member read once through its own property descriptor, so no getter runs, the memory held grows with the detail's members, bounded by nothing but memory, and the work with its members and the length of its names and texts:
349
+ a member `JSON.parse` never makes (an accessor, a hole, a member that is not enumerable or is named by a symbol, a member of an array that is not one of its items) is refused.
350
+ An object detail the walk refuses is one issue at the detail, holding the first problem's reason and none of the detail's names, which are data: zod's `format()` reads each name of an issue's path as a member of a plain object, so a name such as `__proto__` there would write onto objects every reader shares.
351
+ The detail of one of the chat's business codes holds the code's closed fields besides, read at the detail's place so that every issue of theirs, those inside a union's `unionErrors` included, sits under the body's detail, while another code's stays open.
352
+ The closed fields' issues are zod's own, as when zod reads the detail as a field: their paths name only the fields' own names and the indices of their arrays, while zod's words and its `unrecognized_keys` name what was read (a value received, an extra member's name).
353
+ zod words the issues it makes for a detail by its global error map (`z.setErrorMap`) or its default, never by a contextual one handed to the reading (`safeParse(value, { errorMap })`): the detail's readers read with a fresh `safeParse`, to which a transform cannot hand that map, and their issues are handed on with the words that reading gave them, which zod keeps (the package's own words, a closed field's refinement among them, stay under every map).
354
+ Every refused body is aborted, whether refused for another field or for its detail, so no refinement layered over the body, or over an object holding it, runs on it, and a union holding the body, when none of its options takes the value, answers one `invalid_union` with the body's issues inside its `unionErrors`, unless another option is refused without being aborted, whose issues it answers instead.
355
+ Every issue of a refused detail carries zod's `fatal: true`: a host that reads a body inside its own refinement and forwards the issues verbatim (`ctx.addIssue(issue)`) ends its own reading there, and forwards `{ ...issue, fatal: false }` to read on.
356
+ The body holds the detail's copy, made as `JSON.parse` makes values (plain arrays and objects, a member named `__proto__` included, sharing nothing with what was read, and writable even when what was read is frozen), with the same values in every language: its numbers are each language's spelling of their values and its members each language's order of an object's names (JavaScript puts the names that are array indices first, ascending), so a body written back in two languages may spell such a number otherwise and order such members otherwise.
357
+ `readChatBusinessError` reads the body as one of the chat's business codes by its number, an object detail by the code's closed fields and a text or absent detail as `null`, and returns `null` for a number that is not one of the chat's codes.
358
+ A body the types refuse is its writer's error: both languages refuse it whole, never keeping its `error_code` or reading the rest without its detail (a detail holding a number past ±`Number.MAX_SAFE_INTEGER` or a lone surrogate included), so a host treats it as an unreadable answer, by its HTTP status alone, and fills in no `error_code` or `request_id`.
359
+
360
+ ### Showing a refused answer
361
+
362
+ ```ts
363
+ import { chatErrorBodySchema } from "@aiquants/chat/protocol"
364
+ import { assertValidChatHostRefusalCodes, type ChatHostRefusalCodes, chatRefusal } from "@aiquants/chat/react"
365
+
366
+ // the numbers of the host's own business codes it binds the roles to
367
+ const hostRefusalCodes: ChatHostRefusalCodes = { chat_disabled: 40398, knowledge_body_hidden: 40397 }
368
+ assertValidChatHostRefusalCodes(hostRefusalCodes)
369
+
370
+ const refusal = chatRefusal(response.status, chatErrorBodySchema.parse(await response.json()), hostRefusalCodes)
371
+ // refusal.kind is "business", "host-role", "unauthenticated", "unavailable" or "not-accepted"
372
+ ```
373
+
374
+ `chatRefusal` reads a refused answer (a status from 400 to 599, with the platform's body) by the body's code: one of the chat's business codes (`business`, with the error `readChatBusinessError` reads; the answer must have the code's status, and another status is a `RangeError`), then a host refusal role by the numbers the host binds the roles to (`host-role`, at any status).
375
+ For a code it knows neither way, it reads the class of the answer's status: 401 is a sign-in that ended (`unauthenticated`), 408, 429 and every 5xx an answer the chat cannot give now (`unavailable`), and every other 4xx a request the chat did not accept (`not-accepted`).
376
+ A status that is not a number is a `TypeError`, and one that is not an integer from 400 to 599 a `RangeError`.
377
+ A refusal a relay in front of the host answers is read the same way, by its status, unless its code is the chat's or a role's.
378
+ Every refusal keeps the body's request ID and code (`requestId`, `errorCode`), which an inquiry about it names.
379
+ The composer's refused send, its attachments refused by their endpoint and the outcome of saving an alternative text carry such a refusal, and the screen says one paragraph for it: a business error's code and detail sentences, or the one sentence of a role or a class, each stating the fact alone.
380
+ A refusal names a field of the request's body, which the screen marks invalid (the send's `text`, an attachment's `alt_text`), only when it is a refused request (`REQUEST_INVALID`) one of whose errors ends at the field, with or without the platform's `body` before it.
381
+ `assertValidChatHostRefusalCodes` refuses the host's numbers with the errors `chatRefusal` refuses them with at every reading, before anything depends on them: the roles must be the object's own keys and its only ones, each with a positive safe integer, none the number of one of the contract's business codes (which are read before the roles), and no two alike.
382
+
383
+ ### Showing the characters a reader cannot see
384
+
385
+ ```ts
386
+ import { chatSearchText, chatTextShows, markChatInvisible } from "@aiquants/chat/protocol"
387
+
388
+ markChatInvisible("a\u200Bb", { complete: true }) // { text: "a⟦U+200B⟧b", marks: 1 }
389
+ markChatInvisible("👨\u200D👩", { complete: true }) // { text: "👨\u200D👩", marks: 0 }: a joiner between visible characters stays
390
+ markChatInvisible("👨\u200D", { complete: false }) // { text: "👨", marks: 0 }: the joiner waits for the next delta
391
+
392
+ chatTextShows(markChatInvisible("\u200B", { complete: true }).text) // true: the mark shows
393
+ chatTextShows(" \u3000") // false: white space alone shows nothing
394
+
395
+ chatSearchText("\u3000売上 \u200B ") // "売上 \u200B": the white space at both ends goes, and every other character stays
396
+ chatSearchText(" \t\u3000") // null: nothing is left, so there is no q to send
397
+ ```
398
+
399
+ The set is the contract's (`CHAT_PROTOCOL.invisible`): every Default_Ignorable_Code_Point, the controls other than TAB, LF and CR, the line and paragraph separators, the interlinear annotation characters and the noncharacters.
400
+ `markChatInvisible` replaces each of them with its mark, `⟦U+XXXX⟧` (the code point in upper-case hexadecimal digits, at least four), one mark for each character, so a reader sees where a character that hides or reorders text stands and which one it is.
401
+ It keeps three exceptions as they are: one variation selector right after a visible character (E1), one ZWNJ or ZWJ between two visible characters, the left one possibly such a kept selector (E2), and the RGI tag flags of England, Scotland and Wales, each whole (E3).
402
+ A visible character is one neither in the set nor white space (the contract's `white_space` list); a lone surrogate, which no text of the contract holds, counts as visible.
403
+ The tables are the source's, read and checked when the module loads, so no answer leans on the Unicode version of the engine that runs it, and the Python package answers alike from its twin of them.
404
+ A stream's text is marked whole again after each delta with `complete: false`, which holds back the end a later delta may still turn into an exception: a joiner right after a visible character or a kept selector, and the tags of a flag begun but not closed.
405
+ What it shows of a text is a prefix of what it shows of the text grown by later deltas, the complete text included, so the marked text only grows. The promise is for a text that ends on a whole code point, as every sum of the contract's deltas does, no text of the contract holding a lone surrogate. The time grows with the text's length.
406
+ `chatTextShows` tells whether a text holds a visible character. Asked of the text after the marks, whose marks show, it tells whether a screen that shows the marks shows anything; asked of the text before them, it takes a text of invisible characters alone for one that shows nothing.
407
+ `chatSearchText` makes the search text of a typed text, a query's `q`: it removes the white space at both ends, by the contract's `white_space` list, and answers `null` when nothing is left. Every other character stays, an invisible one too.
408
+ The list is not JavaScript's `trim()`, which removes U+FEFF and keeps U+0085, and the Python package's `search_text` answers alike from its twin of the list.
409
+ The window's composer shows every name and every read text after these marks (see [Writing and sending](#writing-and-sending)).
410
+
411
+ ### Laying out the screen
412
+
413
+ ```tsx
414
+ import { ChatFrame, chatFrameBlockSizePx, ChatTalkHeading } from "@aiquants/chat/react"
415
+ import { ConsoleUiRoot } from "@aiquants/console-ui"
416
+ import type { CSSProperties } from "react"
417
+
418
+ // visibleHeight (V): the visible height of the page's scroller; frameTop (y₀): the frame's top in the scroller's content.
419
+ // The host measures both, and measures them again when they change.
420
+ const frameHeight = { "--aqchat-frame-block-size": `${chatFrameBlockSizePx(visibleHeight, frameTop)}px` } as CSSProperties
421
+
422
+ // presentAccessFailure: the host's presenter of access failures (AccessFailurePresenter<ReactNode> of @aiquants/auth-core),
423
+ // which console-ui's root requires. Keep it one value, so a render does not replace the root's context.
424
+ <ConsoleUiRoot locale="ja" formatLocale="ja-JP" timeZone="Asia/Tokyo" accessFailure={presentAccessFailure} testId="console">
425
+ <div style={frameHeight}>
426
+ {/* the screen's heading origin is the level below the host's own heading: 2 under a page's h1; conversation: { title } or null for a new one */}
427
+ <ChatFrame conversations={<ConversationList />} process={<ProcessAndSources />} talkHeading={<ChatTalkHeading conversation={conversation} level={2} labelId="talk-title" testId="talk-heading" />} talk={<Talk />} pinnedSide="conversations" headingLevel={2} testId="chat" />
428
+ </div>
429
+ </ConsoleUiRoot>
430
+ ```
431
+
432
+ Every length of the screen is solved from console-ui's lattice, 44 px target and `body-lg` type role (`CHAT_LAYOUT`), and reaches CSS in rem, so the screen follows the reader's root font size. The container queries of `chatLayoutRule` decide the columns: at a 16 px root, the talk alone below 1140 px (its column never wider than 688 px, the width left going to the outer margins), the talk and the `pinnedSide` column below 1592 px, and all three from there.
433
+ The talk's bar and the composer stand on the talk's line, 640 px at most, and the messages line up with it once the gutter holds the list's scroll bar beside a focus ring (from 672 px). `chatLayoutPlan(width)` gives the same plan as values.
434
+ A message's body spaces its flow by the paragraph gap p (1.5 ℓ, and 1.5 ℓ_r for a body with readings; WCAG 1.4.8): each block of a drawn answer, down into its list items, quotations, description details, footnotes, alerts and the contents of its messages and details, and each paragraph of a text shown as it is, which its blank lines part, stands p after the block before it only, over the renderer's own margins.
435
+ A text that sits beside such a block in one of those holders (a tight list item's text before its code block) becomes a block of its own when the answer is converted, so it is spaced too. A list is never moved into such a block (the renderer's sheet numbers an ordered list that is a `div`'s child as a top-level one), so a tight item's nested list keeps following its text, and a text beside lists alone stays as it is. The items of a loose list (a list one of whose items holds a paragraph) stand p apart whatever block they start with; a tight list's items do not.
436
+ A drawn answer, its holders included, takes its body's type and line (ℓ_r with readings) over the renderer's own sheets, which set the line as a ratio of the type and write a message, a details and the footnotes smaller, so every line stays on the body's lattice; a text shown as it is is written in the body's type too.
437
+ The frame fills the height left below its top (`chatFrameBlockSizePx`: F_p = max(V − y₀, V / φ)), so the composer shows without scrolling, and keeps the talk readable at V / φ when little is left.
438
+ F_p is the frame's least height. The composer stays at the frame's bottom, and above it the message list's scroll box, or the talk's flow, scrolls inside, as a side column's body does; each of these scrolling regions keeps at least R = 2T (88 px at a 16 px root), room for a control with its whole focus ring. When even that cannot fit (the talk's bar, the notices and the composer at their content, with each region at R), as at 400 % text, the frame grows to its content and the page scrolls the rest, so no part of the frame spills over what follows it.
439
+ Put what stands above the composer in place of a message list, such as a new conversation's choices, in `ChatTalkFlow` (in the talk body, before the notice slot and the composer): it scrolls its content inside, with an inset of the focus ring's reach on every side, and lines it up with the composer. Give it content that holds a focusable element: the region takes no tab stop of its own, and WebKit makes no scroller focusable, so a flow with nothing to focus could not be scrolled by keyboard there.
440
+ A side column's body scrolls the host's content inside an inset of the focus ring's reach, so a control at its edge keeps its whole ring. A side column the width hides opens as a modal drawer from its toggle in the talk's bar. A side column's content is drawn only where it can be seen, in its column or in its open drawer, so moving between the two mounts it anew: keep state that has to survive a change of width in the host.
441
+ A width change never leaves focus on what it hides: focus moves from a hidden column to its drawer toggle, from a hidden toggle (the width showed its column) to the column's heading, and from an open drawer whose column the width shows to that heading, without scrolling.
442
+ A drag of files that no part of the frame took is refused anywhere in it, drawers included, so a file dropped beside the composer shows as refused and the browser does not open it in place of the page; the host guards the rest of its page.
443
+ The frame's headings stand at the screen's heading origin, the level below the host's own heading (`headingLevel`: 2 under a page's `h1`): the side columns' headings, and the talk's heading the host puts in the talk bar (`ChatTalkHeading` at the same `level`).
444
+ The talk's heading says the open conversation's title with the marks of the characters a reader cannot see, the catalog's name of an untitled conversation, or the catalog's new conversation while none is open.
445
+ The list's sections and the messages' headings stand one level below (`ChatConversationList`'s and `ChatMessageList`'s `headingLevel`). console-ui's `Heading` draws the levels 1 to 3, so the list's sections fit under an origin of 2 at most.
446
+ An answer's shallowest heading stands one level below its message's heading and the deeper ones a level per depth below it, so an answer that starts at `##` skips no level; each takes the look of the level it stands at (the renderer's sheets style the heading elements) and carries its depth in the answer as `data-aqmd-heading-depth`.
447
+ Only the headings the renderer draws count (none inside a comment, a `template` or an element whose content is written as it is, such as `style`), and while an answer streams or after it was cut only its settled blocks do: the block being written may hold a line the next piece turns into something else (a `#` alone, a paragraph's text with a `-` below it), so it moves no heading already drawn. The renderer takes an origin from 1, so an answer whose shallowest heading is deeper than that (`#####` under a message's heading at 3) draws it at its depth.
448
+ The components render inside console-ui's `ConsoleUiRoot`, whose `locale` (`ja` or `en`) picks the screen's words, and take no class names: the rules reach them through `data-aqchat-*` attributes.
449
+
450
+ ### Showing an open conversation
451
+
452
+ ```tsx
453
+ import { ChatAnswerRendering, ChatComposer, ChatConversationGate, ChatFrame, ChatMessageList, ChatTalkHeading, useChatConversation, useChatSend } from "@aiquants/chat/react"
454
+
455
+ // one window per open conversation: the host keys the component by the conversation's uid, and opens a new window
456
+ // (a new key) when the gate asks it to open the conversation again
457
+ // <OpenConversation key={`${conversationUid}:${opening}`} conversationUid={conversationUid} onReopen={() => setOpening((n) => n + 1)} />
458
+ const OpenConversation = ({ conversationUid, onReopen }: { readonly conversationUid: string; readonly onReopen: () => void }) => {
459
+ // transport: createHttpChatTransport's answer; streams: the host's run streams;
460
+ // hostRefusalCodes: the host's numbers of its refusal roles; settings: the open settings useChatSettings answers
461
+ // (state.settings, below), whose limits set the interval of the window's state read too
462
+ const { user_settings: user, limits } = settings
463
+ const conversation = useChatConversation({ transport, streams, conversationUid, hostRefusalCodes, limits })
464
+ const sending = useChatSend({ transport, window: conversation, hostRefusalCodes })
465
+ // converterFactory: createMarkdownConverter with the bundler's worker and WebAssembly URLs bound;
466
+ // mermaidDrawer: createMermaidDrawer's answer; pageTitle: a ref to the page's own heading
467
+ const { state } = conversation
468
+ // uploadedIds: the uids of the attachments uploaded for the message; setDraft: the host's draft of this conversation
469
+ return (
470
+ <ChatAnswerRendering converterFactory={converterFactory} mermaidDrawer={mermaidDrawer} limits={limits} theme={theme} streamDisplay={user.stream_display} reduceMotion={user.reduce_motion}>
471
+ <ChatFrame
472
+ conversations={<ConversationList />}
473
+ process={null}
474
+ talkHeading={state.kind === "open" ? <ChatTalkHeading conversation={state.conversation} level={2} labelId="talk-title" testId="talk-heading" /> : null}
475
+ talk={
476
+ <ChatConversationGate conversation={conversation} onReopen={onReopen} focusAfterOpen={pageTitle} testId="talk-gate">
477
+ {() => (
478
+ <>
479
+ <ChatMessageList
480
+ messages={conversation.messages}
481
+ notificationLevel={user.notification_level}
482
+ followScroll={user.follow_scroll}
483
+ reduceMotion={user.reduce_motion}
484
+ sentMessageUid={sending.sentMessageUid}
485
+ older={conversation.older}
486
+ onLoadOlder={conversation.loadOlder}
487
+ olderReading={conversation.olderReading}
488
+ olderFailure={conversation.olderFailure}
489
+ labelledBy="talk-title"
490
+ headingLevel={3}
491
+ limits={limits}
492
+ testId="messages"
493
+ />
494
+ <ChatComposer
495
+ phase={sending.phase}
496
+ problem={sending.problem}
497
+ onSend={(text) => void sending.send({ text, attachmentIds: uploadedIds }).then((outcome) => outcome === "accepted" && setDraft(""))}
498
+ onStop={sending.stop}
499
+ notice={conversation.notice}
500
+ onNoticeAction={conversation.onNoticeAction}
501
+ /* the composer's other props, below */
502
+ />
503
+ </>
504
+ )}
505
+ </ChatConversationGate>
506
+ }
507
+ pinnedSide="conversations"
508
+ headingLevel={2}
509
+ testId="chat"
510
+ />
511
+ </ChatAnswerRendering>
512
+ )
513
+ }
514
+ ```
515
+
516
+ `ChatConversationGate` waits for the window: the host draws the talk in the gate's children, which it calls with the open conversation.
517
+ Until then it says the window's read in the root's language: the read under way, or the refused or failed read (a refusal without a body says its class alone), announced once.
518
+ A failed read has a button that reads again (the window's `retry`) and stays busy on the same element while it reads; a refusal the chat cannot answer now has a button that opens the conversation again (`onReopen`: the window holds the read it was opened with for its whole life, so the host opens a new one under a new key), and the gate first hands the button's focus, which a pressed button always holds, to the element the host names (`focusAfterOpen`), since the gate leaves with the old window.
519
+ A sign-in that ended goes to the root's presenter of access failures instead (signing in again, then `onReopen`; keyed by the occurrence of the refusal, which the gate tells by the window's state being another object), and any other refusal says its paragraph alone.
520
+ When the read-again button leaves holding focus, focus moves to the read's area for a refusal, or to `focusAfterOpen` when the window opens.
521
+ It keeps its area (`data-testid` of the gate, with `data-aqchat-conversation-state`) while the window is not open, its paragraph as `<testId>-loading`, `<testId>-refused` or `<testId>-failed`, and its button as `<testId>-retry` or `<testId>-reopen`.
522
+ `ChatTalkHeading` writes the title's text in an element with the id the host gives (`labelId`), so the message list names its feed by the visible heading (`labelledBy`).
523
+
524
+ `ChatAnswerRendering` goes once on the chat screen, above the message list, and is handed the same factory and drawer on every render. It holds the one browser converter the factory makes (started once the tunables are read, stopped while they are `null`, released when the screen leaves), shows a stream by the user's `stream_display` (`smooth` as `immediate` while motion is reduced, by the setting or by the reader's system), and holds the diagrams' queue while an answer streams.
525
+ `ChatMessageList` lists the conversation's messages as its feed (`role="feed"`, named by the visible heading `labelledBy` names) in a virtual list, one article per message, and only the visible rows and `CHAT_RENDER_LIST_OVERSCAN_ROWS` around them are mounted. Page Down and Page Up move between the articles, and Control + End and Control + Home leave the feed.
526
+ The article of a message whose `contextCutBefore` is true opens, before its heading, with the line that the messages before it, except the conversation's first question, are not in the latest answer's context (plan §2.6.2; the fit cuts the first question last, and a value cannot tell whether it went too): inside the article, since a feed owns only articles, outside the article's name, which stays its heading, and as the article's description, so a reader moving by the feed's keys hears it.
527
+ An element in the list that takes a focus its ring shows (`:focus-visible`) is brought into the scroll box's view in the next frame, once the browser's own focus scroll has moved the virtual list's content box (which the virtual list puts back) and the page, and the scroll box is brought into the page's view (`scrollIntoView` with `block: "nearest"`); a pointer's focus stays where the reader sees it. jsdom has no `Element.prototype.scrollIntoView`, so a jsdom spec that moves such a focus into the list models it.
528
+ It opens at the tail. While `followScroll` is true it keeps the tail as long as the reader stays there; while it is false it follows neither a growing answer nor an added message. Either way it lands once on the message the reader sent (`sentMessageUid`), shows a button to the latest message while away from the end (in a row of its own below the scroll box, which gives the row its height, so the button covers no message), and announces an answer's start and end only, as the user's `notification_level` lets it (`all` both, `finish` the end, `none` neither).
529
+ While the window has an earlier page (`older`), the list shows a button that reads it (`onLoadOlder`, the window's `loadOlder`) before the scroll box, outside the feed, busy while the page is read (`olderReading`).
530
+ When the page comes or the button goes, the message the reader was looking at stays at the same height on the screen. The list announces once how many messages it added, or an earlier page it could not read (`olderFailure`), and a focus the button took away with it goes to the last message added (or the first message).
531
+ The host gives the list its height, opens one list per conversation (the conversation's `key`), and loads `@aiquants/virtualscroll`'s styles once.
532
+
533
+ `useChatConversation` reads the conversation's row (`getConversation`) and the latest page of its chosen path (`listMessages`) together, and is `open` once both answer.
534
+ For every answer on the path whose run the read shows active with its stream open (`stream_open`), the window holds a view, the later of the one it held and the read's seed: a view the run's own end closed stays even when an older read still shows the run active, one `resync-required` ended gives way to the seed, and of two running views the one with the later mark stays. An answer whose run the read shows ended holds no view and shows the read's text.
535
+ Neither does an answer whose run's stream is no longer open (`stream_open` false), even while the read shows the run active: the window drops a view it held of it (save a view the run's own end closed, which stays) and opens no subscription, since the stream's endpoint would answer only `resync-required`.
536
+ It shows the read's text, the answer so far, as a growing text while the read shows the run writing (`running`), and follows the run by its state read (below) until the run ends.
537
+ It subscribes, in the same commit, to the stream of every run whose view has not ended, from the view's mark (from the beginning when the view has none, and for a run the state read below follows), folds the stream into the view, and closes the subscription of a run it no longer holds a view of. The contract's terminal events end a subscription by their names, whatever terminal events the host's streams name meanwhile.
538
+ It lists the messages: an answer's text is the texts of its view's steps in their order, growing while the view has not ended, and any other message's is the read's. A text no stream can write any more (a view `resync-required` ended, or no view) grows while the read shows the run writing. Each message is listed against the one the window showed last, so a message whose read, view and line stay is the same object, and a text that does not continue the text shown (a `step.reset`, or a read that replaced what the stream wrote) is marked `replaced` however many items one render applied.
539
+ One message holds the line of the latest answer's context (`contextCutBefore`): the message the latest answer whose run has been taken cut its context before (`context_cut_before`).
540
+ A run still waiting in the queue for its first segment has not chosen its context, so the line stays at the answer before it until a read shows the run taken (one queued again for a later segment after an approval keeps the boundary its first send chose). The stream carries no boundary, so the read after a run's end moves the line to the answer just written.
541
+ There is no line when that answer cut nothing or when the window does not hold the message it names (an earlier page not read yet: every message the window holds is in the context).
542
+ The notice follows the subscription the window opened last and goes when the window lets go of it. Its `reconnect-now` reopens that subscription at once, and its `reread` reads the conversation again. A read again of an open window that does not land shows `unreachable` with `reread`, and one whose answer breaks the contract `incompatible`, over the stream's notice until a read lands.
543
+ The window reads again, one read at a time with the triggers during a read joined into one more after it, when a stream ends with `resync-required`, when a stream brings its run's own end (the row's active run and the path are older than the end, and only the answer's read carries the boundary of its context), when `reread` is pressed,
544
+ and when the window becomes visible or gains focus and the row it reads then shows activity it does not follow: a newer last activity, an active run it neither follows on a stream nor holds ended, or a subscription that stalled (a host's terminal event, reopening given up, or a failed open). With none of them it only takes the row.
545
+ One row read runs at a time (visibility and focus may come together), and a row read that a read again overtook is dropped.
546
+ The state read (plan §2.5.2) follows, until it ends, the first answer on the path whose run is active and whose stream is no longer open, or whose stream the window could not continue twice (a read again's subscription that also ended with `resync-required`). It reads the run whether or not the path still holds its answer (a branch switched meanwhile).
547
+ Every `limits.CHAT_RUN_POLL_INTERVAL_MS` it reads the run (`getRun`). When the run has ended, or waits for an approval in a segment the window does not show yet, it reads the run's answer message (`getMessage`) and puts it in place of the path's message (when the path still holds it), unless the two reads disagree (the run moved between them), which waits for the next read.
548
+ When the run writes a later segment than the window shows, it reads the conversation again once for that segment. When it puts the run's end in place, it stops and reads the conversation once more, since the row's active run and the path are older than the end.
549
+ While it reads, the notice is `awaiting-end` (when no other notice shows), and the window counts the run as followed, so a focus reads only the row. A refusal of either read ends the window as any refusal does, and a read that does not land waits for the next interval.
550
+ When a read again opens a subscription to that run, from the stream's start (a key the stream remade while an approval waited no longer holds the view's mark), the state read pauses and keeps its notice: the subscription's first item that continues the stream ends the state read in favour of the stream.
551
+ A subscription that instead ends with `resync-required` first, enters the reopening (`waiting`), stops (`exhausted`, `faulted`, a host's terminal event), or gives no item within the interval is closed, the window does not subscribe to that view again, and the state read goes on at once. It goes on likewise when a read drops the subscription's view (the run's stream no longer open, or the answer off the path), which closes the subscription.
552
+ A read again that lands lets go of the stalled subscriptions, and the window subscribes again from the views it reconciled; it keeps the earlier pages the window read when the page starts inside them and repeats none of them. A broken subscription stays until a read shows its run ended, since the same stream would break again. A read again that does not land leaves the window and its stalled subscriptions as they are, with the notice above.
553
+ `older` says whether a page comes before the messages, and `loadOlder` reads it and puts it before them (a second call while it reads does nothing); a page whose cursor a read again replaced meanwhile is dropped.
554
+ `olderReading` is true while that read runs, and `olderFailure` names an earlier page that could not be read (`unreached`, or `incompatible` for an answer outside the contract or a page repeating a message's uid), numbered by its occurrence and cleared when the next read of an earlier page starts; the earlier page can be read again, while a refusal still ends the window.
555
+ The list never reads an earlier page by itself: its button calls `loadOlder`, and the host hands it the window's `older`, `loadOlder`, `olderReading` and `olderFailure`.
556
+ A page that repeats a message's uid breaks the contract: a first read is `failed` with `incompatible`, a read again shows the notice above, and an earlier page is dropped.
557
+ A refusal of any read (the row, a page, an earlier page, or the row at focus), taken before the other read's failure, closes every subscription and ends the window as `refused`: its controls and focus read nothing more. A first read that does not land or breaks the contract is `failed`, with `retry`, which goes back to reading.
558
+ The window holds the one conversation it opened for its whole life, so that no row, message or stream of one conversation shows under another: a render with another `conversationUid` throws a `RangeError`, and the host opens another conversation in another window (its `key`). The transport, the streams and the refusal roles' numbers may change between renders, and later reads and subscriptions use the latest.
559
+ Leaving the window stops its reads and closes its subscriptions, and its controls do nothing after it left; a window React's `Activity` hides does the same and keeps its views, and when shown again it subscribes again from them and reads the conversation again.
560
+
561
+ `useChatSend` sends in the window it is handed, one per window: a message goes under the end of the window's path (the last answer) with the conversation's model and reasoning level (`startRun` of kind `send`), only while the phase is `ready`, the window is open and its path ends with an answer (a conversation's first message is written by the request that makes the conversation).
562
+ Its ID (`client_request_id`, a lowercase UUID v4) stays the same for the same content sent again after a send that did not land, was refused or broke the contract, so that the send again starts no second run, and is new for new content.
563
+ An accepted send (`accepted`) answers the message sent as `sentMessageUid` and has the window read the conversation again; its run counts as the running run (the phase `running`, the stop's target) until a window read that started after the acceptance lands or a stop's answer shows the run ended, and a later change of the path never brings that wait back. The host clears its draft.
564
+ A send that does not land, is refused, breaks the contract or is accepted without naming the user's message is `not-sent` with `problem` (the composer's failed send, numbered by its occurrence), cleared when the next send starts, and has the window read the conversation again (whether the send landed is unknown, or the window is old), while the host keeps the draft.
565
+ `stop` cancels the running run (`cancelRun`); a second stop of the same run while its stop is in flight does nothing, while another run's stop goes through.
566
+ A stop refused because the admission is busy (`CHAT_ADMISSION_BUSY`) is sent again at once until the run ends, since the server waits on the stop's lock before it answers so; an answered stop keeps the phase `stopping` until the window shows the run's answer ended (an answer that shows the run ended also ends an accepted send's wait, even while the window's reads fail), any other goes back to `running`, and the window reads again when the server answered about the run.
567
+ The phase is `sending` while a send is in flight, `stopping` while a stop holds, `running` while the path's last answer is being written or an accepted send waits, and `ready` otherwise.
568
+ A message the contract refuses when it is sent (a lone surrogate in its text, neither text nor attachments, an attachment uid that is not one) rejects the send's promise with a `RangeError` naming the caller, `message` and the contract's first issue, before the phase moves.
569
+ The window's `reread` reads the conversation again on the hook's behalf and answers a promise: `true` once a read that started after the call lands (failed reads in between keep it waiting for the next), `false` when the window is refused or leaves. Leaving stops the hook's requests, and a send or stop after that does nothing; a hook React's `Activity` hides stops them too and, shown again, keeps no `sending` or `stopping` phase (whether a hidden send landed shows in the window's read again).
570
+
571
+ ### Writing and sending
572
+
573
+ ```tsx
574
+ import { ChatComposer, ChatFrame, ChatMessageList, ChatTalkHeading, chatBrowserMicrophone } from "@aiquants/chat/react"
575
+
576
+ // once per page: it reads the browser only when the composer asks, after hydration
577
+ const microphone = chatBrowserMicrophone(globalThis)
578
+
579
+ // draft: the conversation's draft the host keeps; phase: "ready", "sending", "running" or "stopping" (useChatSend's phase);
580
+ // notice: the open conversation's window's notice (above); problem: the failed send ({ cause, occurrence }) useChatSend answers, or null;
581
+ // attachments: the message's attachments in their stages of upload (ChatComposerAttachment[]);
582
+ // model: the chosen model's flags; limits: GET /settings' limits (the composer reads a message's length and the attachments' five);
583
+ // sendKey: the user's setting send_key ("enter" or "ctrl_enter") as GET /settings answers it;
584
+ // conversation: the open conversation's window (useChatConversation, above), whose open state holds the conversation's row
585
+ <ChatFrame
586
+ conversations={<ConversationList />}
587
+ process={<ProcessAndSources />}
588
+ talkHeading={<ChatTalkHeading conversation={conversation.state.kind === "open" ? conversation.state.conversation : null} level={2} labelId="talk-title" testId="talk-heading" />}
589
+ talk={
590
+ <>
591
+ <ChatMessageList messages={conversation.messages} /* the list's other props, above */ />
592
+ <ChatComposer
593
+ value={draft}
594
+ onValueChange={setDraft}
595
+ phase={phase}
596
+ onSend={(text) => send(text)}
597
+ onStop={() => stop()}
598
+ notice={notice}
599
+ onNoticeAction={conversation.onNoticeAction} // the open conversation's window (above), with its notice
600
+ problem={problem}
601
+ attachments={{
602
+ items: attachments,
603
+ model,
604
+ onAdd: (files) => addFiles(files), // precheckChatAttachment, then the upload, for each file
605
+ onRemove: (key) => removeAttachment(key),
606
+ onRetry: (key) => uploadAgain(key),
607
+ onSaveAltText: (key, altText) => saveAltText(key, altText), // the endpoint's update, answering its outcome without rejecting
608
+ restore: previousModel === null ? null : { modelName: previousModel.name, onRestore: () => chooseModel(previousModel) },
609
+ microphone, // null to offer no recording
610
+ }}
611
+ limits={limits}
612
+ sendKey={sendKey}
613
+ contentBaseUrl="/bff"
614
+ testId="composer"
615
+ />
616
+ </>
617
+ }
618
+ pinnedSide="conversations"
619
+ headingLevel={2}
620
+ testId="chat"
621
+ />
622
+ ```
623
+
624
+ The composer is the talk body's last item: a form named by its visible label that holds, from the top and 4 px apart, the notice of the run's stream, the paragraph of a failed send, the list of the message's attachments, the recording row, the label line (the label and, while it cannot send or is sending, the reason, with the button that changes the model back while it cannot send), the input row (the input, the attach button, the record button and the send or stop button), the guide to the send key, the guide to what the chosen model takes, and the disclaimer.
625
+ A row that appears or goes above the input moves only the box's top edge, so the input stays where the reader's eye is.
626
+ The host holds the text (keep a draft per conversation), the phase, the notice, the failed send and the attachments, each under a key unique among them and in its stage of upload (`ChatComposerAttachment`): `uploading`, `unreached` (the request got no answer), `stopped` (with `precheckChatAttachment`'s rule tag), `refused` (with the endpoint's refusal, read with `chatRefusal`), `incompatible` (an answer that breaks the contract), `uploaded` (with the endpoint's attachment, read again while it is being read) or `expired` (with the attachment that expired).
627
+ `useChatComposerAttachments` holds the attachments for the host: `useChatComposerAttachments({ transport, modelUid, model, limits, hostRefusalCodes })` answers `items`, `onAdd`, `onRemove`, `onRetry` and `onSaveAltText` to hand the composer (with the host's `model`, `restore` and `microphone`), `readyIds` for the send's `attachmentIds`, and `clear` to call once a send is accepted.
628
+ While no model is chosen (a new conversation before its choice), the host hands `null` for both `modelUid` and `model` (one alone throws a `RangeError`): an added file is stopped without an upload, by the check of a model taking no kind (`attachment_unsupported_by_model`, after the limit of their count), and `onRetry` does nothing until a model is chosen, when it uploads for that model.
629
+ Each file added is checked before its upload (`precheckChatAttachment`, counting the attachments the screen did not stop) and, unless stopped, uploaded for `modelUid` (`createAttachment`): an answer makes it `uploaded`, a refusal `refused` (read with `chatRefusal`), no answer `unreached`, and an answer that breaks the contract `incompatible`; `onRetry` uploads an `unreached` or `refused` one again with its file.
630
+ An uploaded attachment still being read (`processing`) is read again (`getAttachment`) every `CHAT_ATTACHMENT_POLL_INTERVAL_MS` until it is ready or failed (a read that gets no answer or another refusal reads again after the interval; an unreadable answer makes it `incompatible`, and a 404 `expired`, each keeping the attachment read last), and one whose `expires_at` passes before the send is `expired`.
631
+ `onRemove` stops its upload or read and deletes an uploaded attachment (`deleteAttachment`, not awaited: an unbound attachment expires anyway); `onSaveAltText` updates the alternative text (`updateAttachment`), takes a key's answers in the order it asked, and answers `unreached` for a key that is not uploaded. Leaving stops every upload, read and timer.
632
+
633
+ The composer reads the failed send and each attachment once where it checks them and shows what it read, so a host's value that answers differently when read again changes nothing it shows; the endpoint's attachment of an `uploaded` or `expired` one, a value of the contract, is kept as handed, as the package treats every value of the contract as read-only.
634
+ An `incompatible` attachment holds the file alone when the upload's answer broke the contract, and the attachment last read when a reread's did; it is never tried again, since only reloading the page mends it.
635
+ Keep the file for another try after the upload; an attachment restored with a draft holds none.
636
+ The host also hands the tunables the composer reads (`limits`, `ChatComposerLimits`): `GET /settings` answers every one of them in its `limits`, and the composer has no default of its own. A value that is not a positive safe integer throws a `RangeError` naming its key and the value.
637
+ `onSend` receives the text only while the phase is `ready` and nothing stops the send. In order of precedence, a text longer than the limit of a message (`CHAT_USER_MESSAGE_MAX_CHARS`) stops it until it is shortened, an attachment that cannot be sent until it is removed, one of a kind the chosen model does not take until it is removed or the model changes back (`restore`), a recording under way until it ends, and one not ready yet until it is; otherwise only the lack of both text and attachments stops it.
638
+ The text's length is counted in UTF-16 code units, as the contract counts a text's length, so a character outside the basic plane counts two. The composer never cuts the text: a paste past the limit stays whole, the reason says by how many characters to shorten it, with the limit, and the input is marked invalid while the phase is `ready`. The text's length goes first since an attachment's problem also shows on its row, while the length shows nowhere else.
639
+ An empty text is one of length 0, a text of spaces is sent as written, and ready attachments alone send an empty text. While something stops the send, the send button stays focusable and the reason describes both the button and the input.
640
+ The send key (`sendKey`, the user's setting `send_key`, which the composer never defaults) sends from the input through the form's submit, so a press passes the send button's checks: `enter` sends on Enter without a modifier and breaks the line on Shift + Enter, and `ctrl_enter` sends on Control + Enter and on ⌘ + Enter and breaks the line on Enter.
641
+ Every other Enter with a modifier is left to the browser, and the Enter that commits an input method's composition never sends (`isComposing`, or the key code 229 Safari gives once the composition ended).
642
+ While the composer cannot send, the send key adds no line break, never stops a run, and at each press announces why: the label line's reason, or, while sending, running or stopping, the phase's reason, which the label line does not show. The automatic repeat of a held key counts as no press.
643
+ The guide below the input row names both the send and the line break in the setting's words and describes the input, and the on-screen keyboard labels its Enter key to match (`enterkeyhint`: `send` or `enter`).
644
+ While no model is chosen, the host hands `model: null`: the attach button, the picker, a paste or drop of files and the recording stay closed and the guide says that choosing a model opens them, no model refuses an attachment, no attachment offers another try (there is no model to upload for), and the send stops (after a text too long, before every other reason) with the reason to choose a model.
645
+ Files come from the attach button's picker (offering the types of the kinds the chosen model takes), a paste of files without text (a copy that holds text pastes as text) and a drop on the form, and `onAdd` receives them: the host checks each with `precheckChatAttachment` before its upload. While the model takes no kind or the message holds its limit of attachments, the attach button cannot be pressed, a drop is refused, and files that arrive anyway are not handed over: the guide is announced instead.
646
+ While the host hands a microphone that records one of the contract's audio types here and the chosen model takes audio, the record button sits between the attach and send buttons; it cannot be pressed while the message holds its limit of attachments (the guide is its reason) or a recording is under way (the recording row is). A page drawn on the server offers no recording, since the microphone is read only after hydration, so the hydration matches.
647
+ A press opens the microphone, and the recording row above the label line shows the opening, then `Recording 0:42 / 30:00` beside the stop button (focus moves to the stop button when it was on the record button), or the microphone's problem when it cannot be opened, which is announced too and stays until the next press or until the composer no longer offers recording.
648
+ A recording asks for 64 kbit/s or the rate at which the longest recording fills `CHAT_ATTACHMENT_AUDIO_MAX_BYTES`, whichever is less, in pieces of a second. It stops by itself, announcing the limit, as soon as two more pieces as long as its longest so far (a second at least) could pass `CHAT_ATTACHMENT_AUDIO_MAX_SECONDS`, or two more as large as its largest so far could pass `CHAT_ATTACHMENT_AUDIO_MAX_BYTES`.
649
+ While its pieces keep that pace, even where a browser hands them less often than asked, it ends within both limits and is not refused for its length or size after it was spoken; one that still passes them is refused like any other file.
650
+ While a recording is under way, it counts as one of the message's attachments and stops the send. Its end hands `onAdd` one file of its pieces in the asked type, named by its start in the root's time zone (`2026.11.12 chat-recording-143005.webm`), even when the model or the attachments changed meanwhile; a recording with no byte hands nothing. The composer leaving discards a recording and releases the microphone.
651
+ A host may hand its own `ChatMicrophone`: `canRecord(mediaType)`, and `record(request, listener)`, which never rejects and answers the recording (`stop`, `discard`, neither of which throws) or the microphone's problem (`denied`, `missing` or `unavailable`, which the composer words), and hands the pieces and the end from the call on (a stop may hand its last piece and its end before it returns), none with a refusal and none after the end or a discard.
652
+ Each piece is a `Blob` as the browser's `Blob` reads one, with the time since the start in ms, a finite number from 0 and not less than the previous piece's; the composer counts it by the bytes it holds, never by a size it answers itself.
653
+ The composer reads the answer once and takes the pieces and the end one at a time in the order they come: those that come before the answer once the answer is the recording, and those a stop hands before it returns after the call that asked for it.
654
+ A microphone that breaks this contract on a start (it throws, rejects, answers outside it, or answers a refusal after handing a piece or its end) shows as one that could not be started (`unavailable`). One that hands a piece or its end the contract has none for (after answering a refusal, after the end, or after a discard) breaks it too, and so does a piece that is not a `Blob` or comes with a time outside its rule: the composer discards the recording, which releases the microphone, and ends it with the pieces it holds before that piece.
655
+ A recording whose `stop` or `discard` throws breaks it as well. The pieces and the end a throwing stop handed before it threw are taken first and its breach after them, the operator's stop and the stop at a limit alike, so a piece outside the rule it handed is the breach named; a recording still open after them (its end never came) is then discarded and ends with the pieces it holds.
656
+ Since no caller waits on the recording, the composer reports its first breach, named, as an uncaught error of the page (`reportError`), and drops its later calls.
657
+ Each attachment's row holds a decorative 44 px slot, which the endpoint's preview of a ready image or PDF fills (read from `contentBaseUrl` joined to the contract's preview path), the name, a line of the kind, a PDF's pages or a recording's length and the size (console-ui's `formatByteSize`), and the condition's sentence. Its remove button, its try-again button while another try can pass, and its details button while it is uploaded and has not failed (the two never show together) name the attachment after their visible label (`Remove (chart.png)`) and are described by the sentence.
658
+ The details button opens a modal dialog, named by the attachment's name and described by its facts, after the form (so a drop on the dialog never reaches the form).
659
+ It holds the field of the attachment's alternative text, which starts from the endpoint's text and follows it until the operator changes the field, with the save button, and the text read from the attachment: an image's text, a PDF's pages under one heading each (noting the text read from the page image), or a recording's segments as an ordered list of clocks and text, with the notes of the reading above them.
660
+ Every name the composer shows (an attachment's on its row, in its buttons' names and as the dialog's name, and the model's on the button that changes it back) and the read text carry the marks of the characters a reader cannot see (`markChatInvisible` on the whole text: `chart⟦U+200B⟧.png`), and the read text's notes end with how many it holds (`This text holds 2 characters a reader cannot see, each shown as ⟦U+XXXX⟧, where XXXX is the character's code point.`). The input and the field of the alternative text keep what the operator writes as it is.
661
+ Each paragraph of the read text carries the language of its text (`lang`: Japanese for a text with a kana, English for one whose letters a reader sees are mostly Latin, else the screen's), decided on the text before the marks, so the marks' Latin letters never make a text English.
662
+ Focus starts on the dialog's close button, console-ui's default, and not in the alternative text's field: the dialog is also where the read text is read and the field is optional, so a touch screen's keyboard does not cover the read text each time the dialog opens.
663
+ The save hands `onSaveAltText` the key and the written text (`null` for an empty field, which clears it), and the button is busy until the host answers the outcome (`ChatComposerAltTextOutcome`): `saved` shows a note while the field holds the saved text, a refusal naming the field (`REQUEST_INVALID` with an error at `alt_text`) marks it invalid, and any other refusal, `unreached` and `incompatible` (an answer that breaks the contract) show a paragraph beside the button.
664
+ Each outcome is announced once, also after the dialog closed. The wait is held in state rather than in a transition, since React gathers every async transition into one.
665
+ The host never throws or rejects, and takes a key's answers in the order it asked, since a closed and reopened dialog may ask again before an earlier save answered. A save that breaks this contract (it throws, rejects, or answers outside the outcomes) shows as `incompatible`, and the composer reports the breach, named, as an uncaught error of the page (`reportError`), since no caller waits on the save. The answer is read once, its refusal with it, and the composer shows what it read.
666
+ The close button and Escape close the details, but for an Escape inside a field holding text, however often it is pressed, and the Escape that cancels an IME composition (in an empty field too). Closing returns focus to the details button, also when a press that moves no focus (WebKit's) opened them; when the attachment no longer offers details (removed, expired, failed, or with a reread's answer that breaks the contract), the dialog goes and focus moves as from that attachment's leaving button, and the dialog never opens again unasked.
667
+ While a run is active, the stop button takes the send button's place. The two are separate elements, so a press meant for one never lands on the other.
668
+ While the host sends (`sending`), every hand that makes the message stops, since the send's ID is made from what it sends and the host empties the draft and the attachments once the send is accepted: the input is read-only (keeping focus, selection and reading), the attach and record buttons and an attachment's try-again, details and remove buttons cannot be pressed, files that arrive (pasted, dropped or picked) are not handed over and the phase's reason is announced instead, and the label line shows that reason, which describes the input and the stopped buttons.
669
+ A send that did not land keeps what it sent, so sending it again sends the same message; while a run is active or stopping, the next draft can be written.
670
+ When a pressed button leaves holding focus (console-ui's buttons take focus when pressed in every browser, WebKit included), focus moves to the input from the send, stop and change-back buttons, to the attachment's remove button from its try-again or details button, from a removed attachment's button to the remove button of the attachment that followed it, or of the closest one before it when none followed, or to the input when none is left, and from the recording's stop button to the record button, or to the input when it is gone, each scrolled into view when it is not.
671
+ The input grows with its text from the 44 px target to the smaller of ten lines and F_p / φ² (the frame's least height that the host writes, so the frame's growth to its content never feeds back), then scrolls inside, and keeps at least m / φ² (248 px at a 16 px root) beside its buttons, which otherwise wrap to a line of their own.
672
+ The list of attachments grows to the larger of F_p / φ³ and R, then scrolls inside, so with the input at its tallest the two take at most F_p / φ while F_p / φ³ holds R; a short window (as at 400 % zoom, where F_p / φ³ is shorter than one attachment) keeps R, as the message list's scroll box, the talk's flow and a side column's body do.
673
+ A failed send (`problem`: its cause, `unreached`, `refused` with the refusal `chatRefusal` read, or `incompatible` for an answer that breaks the contract, and the number of its occurrence, a positive safe integer) shows the paragraph the composer writes in the root's language, which for an answer that breaks the contract says that whether the message was sent is not known and adds the stream's `Reload the page.`. It marks the input invalid when the refusal names the text, as a text past the limit does while the phase is `ready`.
674
+ Through the console root's announcer the composer announces, in this order within one React commit, a failed send once per occurrence (again for the same paragraph at a new occurrence, not again for a change of language), each attachment's sentence after its name (but the kind the model does not take), the kinds the chosen model refuses once per set, and that the attachments are ready when a wait for them ends; and a recording that stopped before a limit or because the microphone stopped, and a microphone that could not be opened, as they happen.
675
+
676
+ ### Starting a new conversation
677
+
678
+ ```tsx
679
+ import { useChatConversationCreatedAnnouncer, useChatNewConversation } from "@aiquants/chat/react"
680
+
681
+ // one per new conversation the screen shows; it makes the conversation with its first message
682
+ const first = useChatNewConversation({ transport, hostRefusalCodes })
683
+
684
+ // first.phase: "ready" or "sending" (a new conversation has no run to stop); first.problem: the failed send, as useChatSend answers it
685
+ const announceCreated = useChatConversationCreatedAnnouncer()
686
+ const outcome = await first.send({ text, attachmentIds, modelUid, reasoningLevel, declaredLevel })
687
+ if (outcome.kind === "accepted") {
688
+ // move focus to the page's title, announce the conversation made, clear the new conversation's draft,
689
+ // then open outcome.conversationUid in place of the new conversation (no history entry)
690
+ pageTitle.current?.focus()
691
+ announceCreated()
692
+ }
693
+ ```
694
+
695
+ `useChatNewConversation` sends a new conversation's first message with the model, reasoning level and declared level the person chose (`createConversation`), which makes the conversation and starts its first run in one write, and answers the conversation it made.
696
+ Its ID (`client_request_id`, a lowercase UUID v4) stays the same only for the same content sent again after a send that did not land, was refused or broke the contract; the content is the request's body without its ID (the text, the attachments in their order, the model, the reasoning level and the declared level), so a change in any of them takes a new ID, and the server's check of an ID against its content never refuses a send for reusing one.
697
+ After an accepted send, the next send takes a new ID.
698
+ `useChatConversationCreatedAnnouncer` answers the function that says, once each time it is called, that the conversation was made (the catalog's sentence in the root's language) through the console root's announcer; call it once per accepted first send, after focus has landed on the page's title, since the focus move reads the title and can cut off speech under way; the polite region then reads it after the title.
699
+ A send that does not land, is refused (by the contract's business code or by a host's role), or is answered outside the contract is `not-sent` with `problem`, numbered by its occurrence and cleared when the next send starts; the host keeps the draft, and sending the same content again finds the conversation if the first send had made it.
700
+ A second send while one is in flight, and a send after the hook left, do nothing and answer `not-sent`. Leaving, or React's `Activity` hiding the hook, stops a send in flight and takes no answer of it; shown again, the hook is `ready` with no failed send.
701
+ A first message the contract refuses (a lone surrogate in its text, neither text nor attachments, a model or attachment uid that is not one, a level outside the vocabulary) rejects the send's promise with a `RangeError` naming the caller, `message` and the contract's first issue, whatever the phase and before the phase moves; `useChatSend` refuses such a message the same way when it sends.
702
+
703
+ ### Choosing a new conversation's level, model and reasoning level
704
+
705
+ ```tsx
706
+ import { ChatNewConversationChoices, ChatTalkFlow, useChatNewConversationChoice } from "@aiquants/chat/react"
707
+
708
+ // defaults: GET /settings' conversation_defaults, taken when the hook mounts
709
+ const choice = useChatNewConversationChoice({ transport, hostRefusalCodes, defaults })
710
+ const modelUid = choice.model === null ? null : choice.model.model_uid
711
+ const attachments = useChatComposerAttachments({ transport, modelUid, model: choice.flags, limits, hostRefusalCodes })
712
+
713
+ // above the new conversation's composer, in the talk's flow that scrolls inside; the composer takes choice.flags as attachments.model
714
+ // (null stops the send until a model is chosen) and offers choice.previousModel as attachments.restore
715
+ <ChatTalkFlow testId="new-conversation-flow">
716
+ {/* phase: the first send's phase, as the composer gets it (first.phase) */}
717
+ <ChatNewConversationChoices choice={choice} phase={first.phase} testId="choices" />
718
+ </ChatTalkFlow>
719
+ ```
720
+
721
+ `useChatNewConversationChoice` holds the level, the model and the reasoning level a new conversation's first send starts it with.
722
+ The level starts at the default and offers the contract's levels from the default up (`declaredLevels`, in the contract's order), and the models are the new conversation's list of the chosen level (`useChatModels` with `{ declaredLevel }`), read again when the level changes.
723
+ The default model is chosen once, when the first list opens, and only while the list shows it as a row that can be chosen; no other model is ever chosen for the person.
724
+ While the list is not open (being read, refused or failed) no model counts as chosen, and a raised level whose list no longer shows the chosen model as one that can be chosen lets go of it rather than changing it for another (lowering the level again does not choose it back).
725
+ Choosing a model (`chooseModel`) starts its reasoning level at the model's default, and keeps the model chosen before as `previousModel` while the list shows it (a choice let go of takes the model before it along). A kept model whose row in a new list no longer has the chosen reasoning level restarts at the row's default.
726
+ A level outside `declaredLevels`, a model outside the open list's rows that can be chosen, and a reasoning level outside the chosen model's (or with none chosen) throw a `RangeError`.
727
+ `ChatNewConversationChoices` draws three radio groups in order: the level (the catalog's names), the model (the same parts and look as the settings form's default model, without the deployment's option: the rows that can be chosen, the list's read again, the sign-in again and the rows that cannot be chosen with their reasons) and the reasoning level (only while a model with more than one level is chosen).
728
+ The model group's description says that the list is being read, or why it could not be read, which is also announced once through the console root (a sign-in that ended is left to the root's presenter). When the pressed read again button leaves holding focus and the model group has no radio, focus moves to the level group's first radio.
729
+ It takes the first send's `phase` (`ready` or `sending`, the phase the host hands the composer); while the host sends, the three groups cannot be chosen again (focus and values kept, a choice changing nothing), and the phase's reason, drawn once after them, describes each. A `phase` outside the two throws a `RangeError`.
730
+
731
+ ### Showing and saving the settings
732
+
733
+ ```tsx
734
+ import { type ChatSettingsAccess, ChatSettingsForm, ChatSettingsGate, useChatModels, useChatSettings } from "@aiquants/chat/react"
735
+ import { ConsoleUiRoot } from "@aiquants/console-ui"
736
+ import { useRef } from "react"
737
+
738
+ const ChatScreen = () => {
739
+ // transport: createHttpChatTransport's answer; hostRefusalCodes: the host's numbers of its refusal roles
740
+ const settings = useChatSettings({ transport, hostRefusalCodes })
741
+ const user = settings.state.kind === "open" ? settings.state.settings.user_settings : null
742
+ // the page's heading, which takes focus when a read the gate's button started opens
743
+ const headingRef = useRef<HTMLHeadingElement>(null)
744
+ // reduced motion stops every motion of the screen: the root, the stream layer and the list take the same value
745
+ return (
746
+ <>
747
+ <h1 ref={headingRef} tabIndex={-1}>
748
+ Chat
749
+ </h1>
750
+ <ConsoleUiRoot locale={user === null ? hostLocale : user.language_code} reducedMotion={user !== null && user.reduce_motion} /* the root's other props */>
751
+ <ChatSettingsGate settings={settings} focusAfterOpen={headingRef} testId="chat-settings-gate">
752
+ {(open) => (
753
+ <>
754
+ {/* the screen's parts, which take their tunables from open.limits (the frame of "Laying out the screen") */}
755
+ <ChatScreenParts limits={open.limits} />
756
+ <SettingsPanel settings={settings} />
757
+ </>
758
+ )}
759
+ </ChatSettingsGate>
760
+ </ConsoleUiRoot>
761
+ </>
762
+ )
763
+ }
764
+
765
+ // where the host shows the settings: a page, a drawer or a dialog
766
+ const SettingsPanel = ({ settings }: { readonly settings: ChatSettingsAccess }) => {
767
+ const models = useChatModels({ transport, hostRefusalCodes, query: null })
768
+ return (
769
+ <section>
770
+ <h2 id="settings-heading">Chat settings</h2>
771
+ <ChatSettingsForm settings={settings} models={models} labelledBy="settings-heading" testId="chat-settings" />
772
+ </section>
773
+ )
774
+ }
775
+ ```
776
+
777
+ `useChatSettings` reads the person's settings (`getSettings`) when it mounts, and again when it is shown while it holds none (React's `Activity`); once open it reads no more, since only its saves change the settings.
778
+ A refused read carries `retry` when reading again can mend it (an answer the chat cannot give now, `unavailable`, after waiting; a sign-in that ended, `unauthenticated`, after signing in again) and `null` for a refusal a read again answers alike (a business error, a host role, a request not accepted); a failed read always carries it. `useChatModels`' states do the same.
779
+ `save` sends the settings that changed (`updateSettings`; the body `chatUserSettingsUpdateSchema` checks, naming at least one setting, and a body it refuses rejects the returned promise with a `RangeError` whatever the state) while the settings are open and no other save runs, and takes the answer's settings whole: the person's settings, what a new conversation starts with and the tunables.
780
+ A save that does not land, is refused or whose answer cannot be read keeps the settings and holds `problem`, numbered by its occurrence and cleared by the next save that lands. Leaving, or a hide by `Activity`, stops the read and the save; a save stopped so is `not-saved`.
781
+ `useChatModels` reads a list of models (`listModels`) under its `query`: `null` reads the list a new conversation of the tenant's default level may start with, which the default model is chosen from; `{ declaredLevel }` the list a new conversation of that level may start with; `{ conversationUid }` the list that conversation may run with, its own model always among the rows (hidden from a person who may not read it).
782
+ A change of the query (compared by its content) shows the reading from that render on, never the earlier query's list, stops the earlier query's read and reads again; a query naming neither or both, or one the contract refuses, throws as the other options do.
783
+ `reread` reads it again in any state, and does nothing while a read is under way or once the screen is hidden or gone.
784
+
785
+ `ChatSettingsForm` shows the seven settings the chat's screen follows today, in this order: the language, the send key, how answers appear, following answers, motion, the announcements of answers and the default model. The two settings of a message's actions wait for the message's actions, and keep their values.
786
+ Each is a radio group, or a group of one checkbox for a flag, with the catalog's name and description.
787
+ The form holds the changes until a save that lands settles them: its button saves the changed settings only, says that nothing changed when nothing did, and says the settings are saved once a save lands with no change made while it ran (such a change stays, to be saved next).
788
+ A failed save is shown after the button and told, with the setting a refusal names marked; a refusal of the default model reads the list of models again, and when the list then says the chosen model cannot be chosen, the form tells why, once for that refusal.
789
+ The default model is chosen from the organization's default and the models that can be the default: those that can be chosen now, and those in an upstream's state of the moment (the contract's `model_upstream_unavailable_reasons`: stopped, or paused by their breaker), whose option names their state (the server takes them, and refuses a send to them while the state lasts).
790
+ The others are listed with their reason, and a chosen model that cannot be the default, or is not in the list, is said in the group's description, of the person's default or of the model just chosen.
791
+ While the settings or the list are read, or their read failed or was refused, the form says so; after a failure or a refusal the chat cannot answer now a button reads again and stays busy while the read it started runs, and when it leaves holding focus, focus moves to the form, to the settings' area, or to the default model's group.
792
+ A sign-in that ended goes to the root's presenter of access failures (signing in again, then the read again; keyed by the occurrence, as console-ui's `FailureMessage` hands an access failure), which the form leaves the telling to.
793
+
794
+ `ChatSettingsGate` waits for the settings: the screen's parts take their tunables (`limits`) and the person's settings from the answer, so the host draws them in the gate's children, which it calls with the open settings.
795
+ Until then it says the read in the root's language, as the form does: the read under way, or the refused or failed read (a refusal without a body says its class alone), announced once, and after a failure or a refusal the chat cannot answer now a button that reads again and stays busy on the same element while it reads.
796
+ A sign-in that ended goes to the root's presenter of access failures instead (signing in again, then the read again; keyed by the occurrence, as console-ui's `FailureMessage` hands an access failure), and any other refusal says its paragraph alone.
797
+ When that button leaves holding focus, focus moves to the read's area for a refusal, or to the element the host names (`focusAfterOpen`, a heading of the screen it draws) when the settings open.
798
+ It keeps its area (`data-testid` of the gate, with `data-aqchat-settings-state`) while the settings are not open, its paragraph as `<testId>-reading`, `<testId>-refused` or `<testId>-failed`, and its button as `<testId>-retry`.
799
+
800
+ ### Listing the conversations
801
+
802
+ ```tsx
803
+ import { ChatConversationList, ChatFrame, useChatConversationList } from "@aiquants/chat/react"
804
+
805
+ // inside ConsoleUiRoot and above the frame: the frame mounts its columns' content anew when the list moves between its
806
+ // column and its drawer, so the list's state (the typed text, the search, the pages read) lives in the hook up here
807
+ const ChatScreen = ({ currentConversationUid }: { readonly currentConversationUid: string | null }) => {
808
+ // transport: createHttpChatTransport's answer; limits: GET /settings' limits; navigate: the host router's push
809
+ const list = useChatConversationList({ transport, limits })
810
+ return (
811
+ <ChatFrame
812
+ conversations={
813
+ <ChatConversationList
814
+ list={list}
815
+ currentConversationUid={currentConversationUid}
816
+ hrefOf={(conversationUid) => `/chat/${conversationUid}`}
817
+ onNavigate={(href) => navigate(href)}
818
+ onNewConversation={() => navigate("/chat")}
819
+ headingLevel={3}
820
+ limits={limits}
821
+ testId="conversations"
822
+ />
823
+ }
824
+ /* the frame's other props, with headingLevel={2}: the list's sections are one level below the columns' headings */
825
+ />
826
+ )
827
+ }
828
+ ```
829
+
830
+ `useChatConversationList` holds the search box's text and reads the two sections of the list, the pinned conversations and the recent ones (`listConversations` with `pinned` true and false), a page at a time through console-ui's `usePagedResource`.
831
+ `search` searches a typed text once typing pauses for `CHAT_TITLE_SEARCH_PAUSE_MS`, as the contract's `chatSearchText` makes it (a blank text reads every conversation; a text holding a lone surrogate, which no title holds, is answered empty without a request), and `type` sets the text without a search while an input method composes.
832
+ A new search drops the reads of the one before, and while its first pages are read each section keeps showing its rows as a refresh; a search whose pause ends while the list is hidden is read once it is shown. Once both sections hold a search's answers, the hook tells how many conversations it shows, once for that search.
833
+ A read that fails hands console-ui its status and a short reason in the screen's language (none for a 401 or a 403, which the root's presenter states), and a 403 on a later page reads the first page again, whose 403 withdraws the section.
834
+
835
+ `ChatConversationList` draws only: the new conversation's button, the "Search titles" input in a `search` element, and the two sections under their headings, the pinned one only while it holds rows.
836
+ A row is console-ui's `RowLink` to the conversation's address, marked current for the open conversation: its title (or "Untitled conversation"), the time of its last activity with its active run in words (answering, or awaiting approval), and the time it will be deleted when one is set.
837
+ Each section ends with a `LoadMore` of `CHAT_CONVERSATION_PAGE_SIZE` rows; a failed first page shows console-ui's `ResourceFailed` (one for both sections when both fail), and when a row or a failure's button leaves holding focus, focus moves to the section's first row, its heading, or the search input.
838
+ When the page is shown again or its window gains focus, the hook reads each section again, one read at a time (the wakes during a read join into one more after it) and in turn with the section's `loadMore` (a press during a read again loads once it settles, and a wake during a read of more reads once that settles).
839
+ A section with a next cursor reads up to it in one request (`until`) and lays the answer over its rows with console-ui's `updateList`, which keeps the pages read, the cursor, the rows' DOM and the focus on them; an answer cut at the tenant's limit of a re-read (its `next_cursor` neither the cursor nor `null`) is dropped, and the section reads again from its first page (`refresh`).
840
+ A section read to its end reads every page from its head, one row per conversation. A 401 or a 403 reads the first page again (which withdraws the section), any other failure keeps the rows until the next wake, and a new search, unmounting and hiding (`Activity`) stop the read.
841
+ The operations on a conversation belong to its heading.
842
+
843
+ ### Checking an attachment before its upload
844
+
845
+ ```ts
846
+ import { chatAttachmentsRefusedByModel, chatFilePickerAccept, precheckChatAttachment } from "@aiquants/chat/react"
847
+
848
+ const accept = chatFilePickerAccept(model) // "" while the model takes no attachment: close the picker
849
+ const refusal = precheckChatAttachment(file, model, limits, pending.length)
850
+ // null: upload it, and the endpoint decides. Otherwise the endpoint's own rule tag:
851
+ // "attachment_count_exceeded", "attachment_unsupported_by_model" or "attachment_too_large"
852
+ const blocking = chatAttachmentsRefusedByModel(pending, model) // stop the sending while this is not empty
853
+ ```
854
+
855
+ A model's flag for each kind (`supports_images`, `supports_pdf`, `supports_audio`) is the one switch of every layer: the file picker offers only the types of the kinds the chosen model takes, a file of a kind it does not take stops before its upload (`attachment_unsupported_by_model`), and a model that takes no kind closes the attach button, the paste and the drop.
856
+ `precheckChatAttachment` checks in the endpoint's order (the count of the message's attachments, the kind the file declares, its size against the kind's limit) and only helps to stop early: the endpoint judges the kind from the file's first bytes, so a file whose declared type is not one of the contract's goes to the endpoint, unless it is larger than every kind the model takes allows.
857
+ `chatAttachmentHasUnreadText(attachment)` tells an attachment with text the deployment could not read, which a model outside the deployment refuses.
858
+
859
+ ### Naming a saved diagram
860
+
861
+ ```ts
862
+ import { diagramFileName } from "@aiquants/chat/react"
863
+
864
+ const name = diagramFileName({
865
+ conversationUid,
866
+ messageUid,
867
+ index: 2,
868
+ accTitle: "在庫の流れ",
869
+ format: "svg",
870
+ savedAt: new Date(),
871
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
872
+ })
873
+ // for example "2026.11.03 [AI] chat-5e8a91c4-b27d4f06-diagram-2 在庫の流れ.svg"
874
+ ```
875
+
876
+ A name is `yyyy.mm.dd [AI] chat-<the last 8 characters of the conversation's uid>-<the last 8 characters of the message's uid>-diagram-<the diagram's number in its message>[ <accTitle>].svg` or `.png`. The date is the day of the save in the user's time zone, in years 1 to 9999 of the proleptic Gregorian calendar. A uid's last 8 characters are its random tail, since the first 8 of a version 7 uid are its time.
877
+ The title's rule is the one the server's names of a conversation's exports follow:
878
+
879
+ 1. Drop `/ \ : * ? " < > \|`, the control characters (general category Cc) and the bidirectional controls (Bidi_Control), which could make the extension look different.
880
+ 2. Turn each run of spaces (general categories Zs, Zl and Zp) into one space.
881
+ 3. Keep the first 64 grapheme clusters.
882
+ 4. While the whole name is over 255 bytes in UTF-8, drop the title's last grapheme cluster.
883
+
884
+ The title never starts or ends with a space: the spaces at its ends are dropped as characters, since a space after a prepended mark (such as U+0600) is one grapheme cluster with it. An empty title and a `null` one are left out.
885
+ A uid the contract's schema refuses (one that is not a lower-case RFC 9562 version 7 UUID), a number that is not an integer from 1 to 2^53 - 1, a title with a lone surrogate, an invalid date, a time zone the runtime does not know, a day outside years 1 to 9999 and a form other than `svg` and `png`, which only a caller that bypasses the types can pass, are refused with a `RangeError`; a context that is not an object, an instant that is not a `Date`, a time zone that is not a string, an index that is not a number and a title that is neither `null` nor a string with a `TypeError`.
886
+
887
+ ### Registering the authorization resources
888
+
889
+ ```ts
890
+ import { collectAuthzDefinitions } from "@aiquants/authz-core"
891
+ import * as chatAuthz from "@aiquants/chat/authz"
892
+
893
+ const { resources } = collectAuthzDefinitions({ "chat.authz.ts": chatAuthz })
894
+ ```
895
+
896
+ The resources carry their keys, names and descriptions; which roles hold which operations is the host's grant, not this package's.
897
+
898
+ ### Testing a screen against the endpoints
899
+
900
+ ```ts
901
+ import { createHttpChatTransport } from "@aiquants/chat/client"
902
+ import { chatScenarioRefusal, createChatScenarioFetch } from "@aiquants/chat/testing"
903
+
904
+ const bases = { jsonBaseUrl: "/gateway", uploadBaseUrl: "/upload" }
905
+ // the host's server's reading of the stamp the host's `stampWrite` puts on a write
906
+ // (a host that stamps no write passes `(target) => target` to both)
907
+ const scenario = createChatScenarioFetch({ ...bases, unstampWrite })
908
+ // the screen under test gets the package's own transport, which sends to the scenario in the server's place
909
+ const transport = createHttpChatTransport({ ...bases, fetch: scenario.fetch, stampWrite })
910
+
911
+ scenario.plan("getSettings", { kind: "answered", answer: settings })
912
+ scenario.plan("getRun", chatScenarioRefusal("NOT_FOUND", { error_msg: "no such run", request_id: requestId, detail: { resource: "run" } }))
913
+ scenario.plan("listModels", (request) => ({ kind: "answered", answer: modelsFor(request.query) }))
914
+ const started = scenario.hold("startRun")
915
+
916
+ // render the screen with the transport and act on it, then:
917
+ const request = await started.arrived // read back as the transport's check reads it
918
+ started.settle({ kind: "answered", answer: accepted })
919
+
920
+ scenario.assertDone() // at the end of every test
921
+ ```
922
+
923
+ `createChatScenarioFetch` makes a scenario (`ChatScenarioFetch`, frozen) whose `fetch` a test hands the package's own transport in the server's place, so every test runs the transport's writing of requests and reading of answers; there is no fake transport. Its two bases are the transport's, held to the same rule, `unstampWrite` must be a function (it has no default), and its options are read once, in the order `jsonBaseUrl`, `uploadBaseUrl`, `unstampWrite`.
924
+ Once they are checked, it refuses a runtime the scenario cannot read in, as the transport does (see [Prerequisites](#prerequisites)), and one with neither `Blob.prototype.arrayBuffer` nor a `FileReader`, by one of which it reads an upload's file.
925
+ It reads each request back into the contract's words (`ChatScenarioRequest`: the endpoint, its path's parameters, its query as its schema reads it, its body as its shape reads it with an upload's file as a `Blob` of its part's type, and its signal), reading only `method`, `headers`, `body` and `signal` of `init`, once each and in that order when `fetch` is called.
926
+ A write's target (the URL after the origin it is written with, when that is a path of the origin that begins with one `/`) is first handed once to `unstampWrite` (`ChatUnstampWrite`, the host's server's reading of the stamp `stampWrite` puts there), called as a plain function, and the target it answers is read in its place; a read never is, nor a write whose URL is no such path, which no base names.
927
+ A reading that throws (a write without the host's stamp, as a host that forgot it sends), or answers a value that is not a string or a string that is not a path of the same origin that begins with one `/`, makes the request a breach naming `unstampWrite`, with what it threw as the cause, so a test of a stamping host fails where a write goes out unstamped; a stamped write over a scenario whose reading is the identity breaks as a query its endpoint does not take.
928
+ The method and the path must name an endpoint of the exchanges' table under the base of its channel, the path's parameters and the query must be written as the contract's path functions and `chatQueryString` write them, the body must be the JSON text or the multipart body (RFC 7578, read byte for byte) the transport writes, with the file's name escaped as the transport escapes it, and the request must pass the transport's own check.
929
+
930
+ Each endpoint has a queue of steps, which its requests take in the order `fetch` is called: a reply, a function that takes the request and returns a reply, or a held step (`hold`), whose `arrived` resolves to the request and whose `settle` answers it.
931
+ `plan` takes one step or more (an array of them may be spread), and `plan` and `hold` take one endpoint as `exchange` does (`ChatSingleEndpoint<Endpoint>`), so a function that holds an endpoint in a type parameter and writes it the same way hands it on with no type argument.
932
+ A reply is `answered` (an answer the endpoint's shape takes), `refused` (a status from 400 to 599 and a failed answer's body; `chatScenarioRefusal` makes a business code's at the code's own status), `unreached` (which `fetch` rejects with a `TypeError`, as a network error) or `response` (a function making what `fetch` resolves to, for breaking the contract on purpose).
933
+ A `response` function that returns a thenable is adopted as the language adopts one (its `then` read once, only its first outcome counting, a thenable it fulfils with adopted a job later in turn) and awaited within the exchange, its outcome heard the moment the thenable reports it by calling a function the scenario handed its `then`:
934
+ the request has no outcome until then (a held step settled with it refuses a second `settle` meanwhile, as it does while the function runs), a rejection reported before the request is stopped is a breach, and an abort before the outcome is reported rejects with the signal's reason and drops what is reported later.
935
+ A promise of the language reports its outcome a job after it settles, and no script reads it sooner, so an abort the scenario hears in between comes first: a promise settled in the job that then aborts the request, or an async `response` function that throws after it queued the abort, leaves the request rejecting with the reason and no breach.
936
+ What a `response` function makes is handed over as it is, so an abort after `fetch` resolved does not reach its body as it would a browser's: a test that needs that path makes the body from a stream it errors itself.
937
+ A reply is checked once, when it is planned or settled or a function step returns it, so `answered` and `refused` give the transport the same outcome.
938
+ The signal is read by the browser's readers of an `AbortSignal`, never by its own members, and listened to as a browser's `fetch` listens to it, through the request's own signal: one that follows it, made by the runtime's `AbortSignal.any` as the `Request` constructor makes a request's, whose abort steps run once the init's signal has run its own listeners, whatever they do (DOM's "signal abort").
939
+ The scenario leaves no listener on the init's signal, so one of its listeners that stops the abort event's immediate propagation does not keep the scenario from hearing the abort.
940
+ It adds one and removes it at once before it makes the request's own signal, and the same to that signal, since Node's `AbortSignal.any` places a signal it makes among the dependents of its sources only once that signal gets its first `abort` listener, where the DOM places it when it is made: an init made that way therefore runs a listener it first gets after `fetch` before the scenario's abort steps, as in a browser, and all the runtime writes into the init's signal and the signals it follows for a request is written when `fetch` is called.
941
+ Any other signal Node's `AbortSignal.any` made before `fetch` from the init's signal or a signal it follows (one such an init was made from among them) keeps Node's place, so on Node a listener it first gets after `fetch` runs after those steps (a browser runs it before).
942
+ A runtime that refuses to place the init's signal or the request's own, or makes the request's own signal aborted from an init's signal that is not aborted (see [Prerequisites](#prerequisites)), makes the request a breach when `fetch` is called, recorded as a `TypeError` naming `init.signal` with the runtime's error, or one naming the aborted signal, as its cause, before anything else of the request is read or kept.
943
+ One already aborted when `fetch` is called rejects with its reason once the four fields of `init` are read, and nothing else of the request is read (the browser's `fetch` first checks the init as it makes its `Request`, so it rejects an init it cannot read with another error).
944
+ A request stopped before the scenario has read it, while it waits its turn or while it is read, rejects then with the reason and is read no further: it takes no step, is not recorded and is no breach, even if it could not be read.
945
+ A request stopped after it took its step (a held step's, or one that a step's function or a `response` function stops) rejects with the reason and stays recorded: a held step is stopped, so its `settle` throws, and what a function returns is not answered (a step's function's reply is not made into an answer, nor its `response` function called).
946
+ A signal counts as aborted from the moment it is, as no answer of a browser's `fetch` arrives before its abort steps reject the call (an answer arrives in a task): while the abort is being dispatched to the init's signal's listeners, the scenario neither reads nor answers the request, a `settle` called there throws as one after the abort does, the request rejecting with the reason then, and `assertDone` called there counts the request as stopped.
947
+ The scenario looks at the init's signal for that before and after reading a request, when its read throws, before answering it, in every breach, when a `response` function's thenable reports its outcome, at each look `settle` takes at its step and at the start of `assertDone`.
948
+ A request whose step is a reply or a function is answered in the jobs that follow the call, once it is read, where a browser's answer arrives in a later task, so an abort later in the task that called `fetch` finds the request answered once those jobs have run, and then reaches only an unread body (below).
949
+ An answer's body is errored by the abort steps alone, as a browser's is: a read of it begun there gets its bytes, and a cancel of it there succeeds.
950
+ One stopped after `fetch` resolved with a reply the scenario made with a body (`answered`, `refused`) errors that body with the reason until the body is read to its end or cancelled, as a browser's `fetch` does, so the transport reads `unreached`, and a read or a cancel after that rejects with the reason; once the body is read, or for a reply with no body, the abort changes nothing.
951
+ The scenario's listener on the request's own signal is removed once the request is answered or rejected, and the body's once the body is read, cancelled or errored.
952
+ The body is a byte stream, as a browser's is, that holds every byte from the start, as the body of an answer that has fully arrived does: a reader in `byob` mode reads it too, each read taking as many bytes as its view holds or as are left (a default read takes a piece), and the body closes when its last byte is read, which also ends a read still waiting for more (a `byob` read whose `min` passes the bytes left) with those left and the end, as the Streams Standard's close for other specifications does.
953
+ A `byob` read whose view's elements are larger than a byte (a `Uint16Array`) and that leaves part of one errors the body with a `TypeError`, as the Streams Standard does for every byte stream.
954
+ A copy `clone()` makes shares the body: an abort before either copy has read it to its end errors both, but once one copy has read it, the abort errors neither, where a browser's still errors the original's body while it is unread (WHATWG Fetch's "abort the fetch() call" errors the `Response`'s own body, which "clone a body" leaves to the original); the package's transport never clones an answer.
955
+
956
+ A request the scenario cannot read, one whose signal the runtime refuses to place or makes an aborted request signal from, a request no step is left for, a step's function that throws or returns a reply the check refuses, a `response` function that throws, returns a thenable that reports a rejection before the request is stopped (through a thenable it fulfils with too), or returns a value whose `then` throws when read, and a reply the runtime cannot make into a `Response` are breaches, recorded when they happen (a thenable's rejection the moment it reports it).
957
+ `fetch` rejects with the error (the transport reads `unreached`), or with the signal's reason where the function stopped the request itself first.
958
+ A request no step is left for took no step and is not among `requests()`; one whose step breaches stays there.
959
+ `assertDone` throws an `Error` naming, in this order, the number of requests still being read (with neither an outcome nor a held step, one awaiting a `response` function's thenable among them), every breach, the number of steps never taken of each endpoint and every held request neither answered nor stopped (one whose `response` function runs or whose thenable is awaited among them).
960
+ Since the transport reads a breach as `unreached`, a test calls `assertDone` at its end, once every request it made has an outcome or was stopped. A request still being read may yet become a breach, so `assertDone` does not pass while one is; once it passes, its verdict does not change afterwards, as no request made before can become a breach later.
961
+ `requests()` answers the requests that took a step, in that order. Requests are read one at a time in the order `fetch` is called, so a request called later never takes a step before an upload whose body is still being read; where the global `Blob` has no `arrayBuffer` (jsdom 27's), a body's bytes are read by a `FileReader`, which finishes through `setImmediate` (fake timers: see [Prerequisites](#prerequisites)).
962
+
963
+ ## Development
964
+
965
+ ```bash
966
+ pnpm --filter @aiquants/chat build
967
+ pnpm --filter @aiquants/chat typecheck
968
+ pnpm --filter @aiquants/chat test:coverage
969
+ ```
970
+
971
+ The tests hold the zod types to `chatProtocol.json` name for name, field for field and value for value, hold the tables of the characters a reader cannot see to the Unicode properties of the engine that runs them, give every golden sample the answer it states (and every prefix of a sample of those characters, as a stream's text grows, marks that only grow), fold streams whose every event is read from its frame by the contract's reader, and require 100 % coverage of statements, branches, functions and lines.
972
+ They run the package's own transport over the scenario of `./testing` at every endpoint of the exchanges' table.
973
+
974
+ ## License
975
+
976
+ MIT