@aiquants/chat 0.2.0 → 0.4.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +234 -18
  3. package/dist/{ChatAnswerHtml-NBI6KBTM.js → ChatAnswerHtml-NAD7XPMQ.js} +1 -1
  4. package/dist/{chunk-NKHHXW42.js → chunk-44WLZMPZ.js} +1 -1
  5. package/dist/chunk-BTDHRYBO.js +1 -0
  6. package/dist/chunk-GSCTWGZT.js +1 -0
  7. package/dist/chunk-HC7HXC2K.js +1 -0
  8. package/dist/{chunk-PLNRET3Z.js → chunk-KNPMHSTQ.js} +1 -1
  9. package/dist/{chunk-7KWWXSGA.js → chunk-NWDLT2AZ.js} +1 -1
  10. package/dist/client.cjs +2 -2
  11. package/dist/client.d.cts +5 -5
  12. package/dist/client.d.ts +5 -5
  13. package/dist/client.js +1 -1
  14. package/dist/{httpTransport-BAaKwioS.d.ts → httpTransport-Cgj10OUn.d.ts} +1 -1
  15. package/dist/{httpTransport-D_JJABMq.d.cts → httpTransport-o7MkPUuY.d.cts} +1 -1
  16. package/dist/{index-iHWm67aF.d.cts → index-g-wjju1F.d.cts} +9518 -1785
  17. package/dist/{index-iHWm67aF.d.ts → index-g-wjju1F.d.ts} +9518 -1785
  18. package/dist/protocol.cjs +1 -1
  19. package/dist/protocol.d.cts +1 -1
  20. package/dist/protocol.d.ts +1 -1
  21. package/dist/protocol.js +1 -1
  22. package/dist/react.cjs +2 -2
  23. package/dist/react.d.cts +295 -56
  24. package/dist/react.d.ts +295 -56
  25. package/dist/react.js +2 -2
  26. package/dist/{runStream-7KHfaNOq.d.ts → runStream-Wn5F3RKe.d.ts} +1 -1
  27. package/dist/{runStream-CKisFztQ.d.cts → runStream-jp4rlkIw.d.cts} +1 -1
  28. package/dist/testing.cjs +6 -6
  29. package/dist/testing.d.cts +55 -4
  30. package/dist/testing.d.ts +55 -4
  31. package/dist/testing.js +6 -6
  32. package/dist/{transport-Clvkp7mW.d.ts → transport-CYd9hh42.d.cts} +23 -1
  33. package/dist/{transport-5ExGY_ti.d.cts → transport-DlhniH4C.d.ts} +23 -1
  34. package/package.json +7 -7
  35. package/dist/chunk-4NR4KSV6.js +0 -1
  36. package/dist/chunk-EEUIBWBF.js +0 -1
  37. package/dist/chunk-WGNEBS4H.js +0 -1
package/README.md CHANGED
@@ -22,8 +22,8 @@ Golden samples of an answer's end (`tests/fixtures/chat-answer-end-golden.json`,
22
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
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
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),
25
+ - For `@aiquants/chat/react`: `react` and `react-dom` >= 19 and `@aiquants/console-ui` ^0.11.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` ^15.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, and builds no parse result, whose `deck` 15.0.0 made required),
27
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
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
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`).
@@ -47,11 +47,11 @@ pnpm add react react-dom @aiquants/console-ui @aiquants/sse @aiquants/markdown @
47
47
 
48
48
  | Import path | Contents |
49
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`). |
50
+ | `@aiquants/chat/protocol` | The frozen source (`CHAT_PROTOCOL`, `CHAT_PROTOCOL_VERSION`), the leaves of the requests that carry a person's text (`CHAT_HUMAN_TEXT_LEAVES`), 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` with its bound `CHAT_SEARCH_TEXT_MAX_LENGTH`, `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`) the body that changes a person's settings (`chatUserSettingsUpdateSchema` with its type `ChatUserSettingsUpdate`), and the bodies and the answer of a switch of the chosen path (`chatActiveRootUpdateSchema`, `chatActiveChildUpdateSchema` and `chatActivePathSchema`, with their types `ChatActiveRootUpdate`, `ChatActiveChildUpdate` and `ChatActivePath`), the body that changes a conversation's row (`chatConversationUpdateSchema` with its type `ChatConversationUpdate` and the title's bound `CHAT_CONVERSATION_TITLE_MAX_LENGTH`), a conversation's tree and the hits of a search in it (`chatConversationTreeSchema` with `chatTreeNodeSchema` and the head's bound `CHAT_TREE_PREVIEW_MAX_LENGTH`, and `chatSearchHitsSchema` with `chatSearchHitSchema`, with their types `ChatConversationTree`, `ChatTreeNode`, `ChatSearchHits` and `ChatSearchHit`), the tenant's policy as a person reads it and the body of a consent (`chatPolicySchema` with `chatPolicyConsentSchemas`, `chatPolicyVersionSchema`, `chatPolicyTextsSchema` and the number's bound `CHAT_POLICY_VERSION_NO_MAX`, and `chatPolicyConsentRequestSchema`, with their types `ChatPolicy`, `ChatPolicyVersion`, `ChatPolicyTexts` and `ChatPolicyConsentRequest`), 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
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`). |
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`, its text `ChatMessageText` and its branch among its siblings `ChatMessageBranch`) 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`), the switch of a message's branch (its state `ChatBranchSwitchState`, a failed switch `ChatBranchSwitchProblem` and a switch's outcome `ChatBranchSwitchOutcome`) and what it answers (`ChatConversationWindow`). The sending, the edits, the regenerations and the stopping in that window, which hand the composer its phase, its failed send and whether an unfinished answer is on another branch, and the list the message sent and the edits and regenerations: `useChatSend` and the types of its options (`ChatSendOptions`), a message to send (`ChatSendMessage`), a send's outcome (`ChatSendOutcome`), a rewrite's kind (`ChatRewriteKind`), an edit's or a regeneration's outcome (`ChatRewriteOutcome`), a failed one (`ChatRewriteProblem`), their state (`ChatRewriteState`), why the window's path stops them (`ChatSendPathBlock`) 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 open conversation's heading band, `ChatConversationHeading` with its props (`ChatConversationHeadingProps`), its operations `useChatConversationActions` (with `ChatConversationActionsOptions`, `ChatConversationActions`, `ChatConversationAction`, `ChatConversationActionPhase`, `ChatConversationActionProblem` and `ChatConversationActionOutcome`), the row the band shows, `chatConversationShownRow`, and the announcement of a delete, `useChatConversationDeletedAnnouncer`. 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
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`). |
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`). The scenario's run streams a host hands its run streams in a server's place, so a screen draws a run's stream: `createChatScenarioRunStreams` with the types of its options (`ChatScenarioRunStreamsOptions`, with the timers `ChatScenarioTimers` and the heartbeat `ChatScenarioHeartbeat`), a step of a run's script (`ChatScenarioStreamStep`), an EventSource of it (`ChatScenarioEventSource`) and the streams (`ChatScenarioRunStreams`), and a step's longest wait (`CHAT_SCENARIO_STREAM_MAX_WAIT_MS`). |
55
55
 
56
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
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.
@@ -260,8 +260,8 @@ An answer message carries the run that writes it, with its finish reason only wh
260
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
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
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.
263
+ A query's `q` is a search text (`chatSearchTextSchema`): a text of the contract of at most `CHAT_SEARCH_TEXT_MAX_LENGTH` (400) UTF-16 code units without white space at either end, which `chatSearchText` makes of what a person typed (it never makes a text longer, so a screen bounds the typed text to the same length) (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, nor is one longer than `CHAT_SEARCH_TEXT_MAX_LENGTH`; the conversations' list answers both empty without a request, and its search box (`maxLength`) does not let a person type a longer text. The server refuses any other `q` instead of trimming it.
265
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
266
 
267
267
  ### Reading an endpoint's exchange
@@ -275,7 +275,7 @@ const { status, answer } = CHAT_EXCHANGES.startRun
275
275
  const accepted: ChatExchangeAnswer<"startRun"> = chatExchangeShapeSchemas[answer].parse(await response.json())
276
276
  ```
277
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.
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 (`deleteConversation`, `consentPolicy` and `deleteAttachment`), a 204 may still take a body (`consentPolicy`), only an upload takes a multipart body, and every answer is JSON.
279
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
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
281
 
@@ -306,7 +306,7 @@ Its type takes one endpoint and refuses a union of several, whose requests' fiel
306
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
307
  It answers one of four outcomes (`ChatExchangeOutcome<endpoint>`) and never throws for a failed sending or a broken answer:
308
308
 
309
- - `answered`: the answer at the endpoint's success status, as its shape reads it (`null` for `deleteAttachment`, which answers no body).
309
+ - `answered`: the answer at the endpoint's success status, as its shape reads it (`null` for an endpoint whose status is 204, `deleteConversation`, `consentPolicy` and `deleteAttachment`, which answer no body).
310
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
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
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).
@@ -486,6 +486,15 @@ const OpenConversation = ({ conversationUid, onReopen }: { readonly conversation
486
486
  onLoadOlder={conversation.loadOlder}
487
487
  olderReading={conversation.olderReading}
488
488
  olderFailure={conversation.olderFailure}
489
+ onSwitchBranch={conversation.switchBranch}
490
+ branchSwitch={conversation.branchSwitch}
491
+ onEditMessage={sending.edit}
492
+ onRegenerateMessage={sending.regenerate}
493
+ rewrite={sending.rewrite}
494
+ messageActionsDisplay={user.message_actions_display}
495
+ sendKey={user.send_key}
496
+ landing={landing}
497
+ messageHrefOf={(messageUid) => `${basePath}/${conversationUid}/${messageUid}`}
489
498
  labelledBy="talk-title"
490
499
  headingLevel={3}
491
500
  limits={limits}
@@ -493,6 +502,8 @@ const OpenConversation = ({ conversationUid, onReopen }: { readonly conversation
493
502
  />
494
503
  <ChatComposer
495
504
  phase={sending.phase}
505
+ runElsewhere={sending.runElsewhere}
506
+ pathBlock={sending.pathBlock}
496
507
  problem={sending.problem}
497
508
  onSend={(text) => void sending.send({ text, attachmentIds: uploadedIds }).then((outcome) => outcome === "accepted" && setDraft(""))}
498
509
  onStop={sending.stop}
@@ -522,12 +533,34 @@ It keeps its area (`data-testid` of the gate, with `data-aqchat-conversation-sta
522
533
  `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
534
 
524
535
  `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.
536
+ A page that draws the answers links the Markdown renderer's display stylesheets: `@aiquants/markdown/styles/katex.min.css`, `message.css`, `details.css` and `github-markdown.css`, in that cascade order.
537
+ The renderer draws every document inside `.markdown-body` (the GitHub display style, whose light and dark follow the `data-theme` of an ancestor), and a host's Tailwind entry carries only the renderer's components' own rules (`@aiquants/markdown/styles/markdown.css`), so without the display sheets the answers' headings, lists, tables and code blocks draw unstyled.
538
+ The chat's layout rule lets the conversation's surface show through each answer's document root (`[data-aqmd-document]`) and gives the root the surface's text colour, so the display style's own background and text colour never draw.
539
+
540
+ `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, from any element in an article but one that takes text, before a widget there (such as a message's toolbar, whose Home and End move inside it) reads them.
526
541
  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.
542
+ 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.
543
+ An element of a message's actions, the article's last part, comes up from below with the article's end when the rest of the row fits, and in the last row with the content's bottom inset too, so the list reaches its tail and a following list keeps following; an element in a message's text lands its ring's edge only, so a growing answer does not carry it away. jsdom has no `Element.prototype.scrollIntoView`, so a jsdom spec that moves such a focus into the list models it.
528
544
  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
545
  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
546
  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).
547
+ Every message ends its article with its actions: one toolbar named "Message actions" (one stop in the Tab order; the arrow keys, Home and End move inside it) that holds the branch switch while the message has two siblings or more (a user's message edited, an answer generated again) and the action of its role, "Edit" for a user's message and "Regenerate" for an answer.
548
+ The switch is the previous branch's button, its place among its siblings in the order they were made ("Branch 2 of 3") and the next branch's button, as one group the place names. A button at an end does not wrap around: it cannot be pressed and says why, once after the toolbar.
549
+ The role's action shows as `messageActionsDisplay` (the person's `message_actions_display`) says: always (`always`), while the article is pointed at or holds focus (`hover`), or always on a device with a coarse pointer and otherwise as `hover` (`auto`); hidden, it is only transparent, so it keeps its place, its focus and its name. The switch always shows.
550
+ Pressing a branch button calls `onSwitchBranch` (the window's `switchBranch`) with the message and the sibling; it answers the outcome and neither throws nor rejects, and one that does is dropped and reported through `reportError` as a `RangeError` holding the error as its cause. While the switch runs (`branchSwitch`, the window's), the pressed button is busy, and the other button, every other message's switch and every role's action cannot be pressed.
551
+ Why a button cannot be pressed for the whole list (a switch under way, an answer not written yet, from a send until its run ends, or another message being edited) is a note the list draws once after the scroll box, and every button it holds for names it (`unavailable.reasonId`), so no reason is drawn twice.
552
+ Pressing "Edit" opens the edit form in the message's article, in place of its body and its actions: its input holds the message's `sourceText` (the text before the marks of invisible characters, as the composer holds its own text) and takes focus with the caret at its end, and the list holds the text, so it stays while the virtual list unmounts the row.
553
+ One message is edited at a time: meanwhile the other messages' switches and actions cannot be pressed. The form sends as the composer does (its send key, where an input method's commit does not send, and a text longer than `CHAT_USER_MESSAGE_MAX_CHARS`, one with a broken character (a lone surrogate) or an empty one not sent, in the composer's words); "Cancel" and Escape close it and focus goes back to "Edit", but while the edit is sent "Cancel" cannot be pressed and says why, and Escape tells it (the edit goes on whatever the form does); the form closes when its message leaves the list.
554
+ "Send the edit" calls `onEditMessage` (the send hook's `edit`) with the text and no attachments, and "Regenerate" calls `onRegenerateMessage` (its `regenerate`); both answer their outcome once the window's read after an acceptance has settled, and neither throws nor rejects (one that does is dropped and reported as a switch's is). While one is sent, its button is busy.
555
+ An accepted edit or regeneration lands as a switch does: the commit that first brings its new sibling (`rewrite.accepted`) keeps the place, focus moves to the same button of the sibling's article (which cannot be pressed while its answer is written), and the branch it shows is announced.
556
+ When the read after the acceptance shows no sibling while the message stays (another window switched), an edit's form closes with focus back on "Edit" (also when the reader moved focus inside the form meanwhile), and a regeneration leaves focus where it is. One not sent leaves its form, its text and focus; a failed one is a paragraph in the form or under the actions, which the list tells once per occurrence, and a form opened again shows only an edit that failed after it opened.
557
+ The commit that first brings the sibling keeps the message the reader was looking at at the same height on the screen, as an earlier page does (a message the switch took away gives its place to the sibling, shown from its top; a list following the tail stays at the tail).
558
+ Once the switch lands and the sibling is in the list, focus moves to the same button of the sibling's article without the browser's scroll (to the article itself, which the list lands in view, while the virtual list has not drawn its button), and the root's announcer says "Showing branch 2 of 3." once.
559
+ Focus moves only while it is on the pressed button or has fallen to the body (the pressed row leaves with the switch): a focus the reader moved elsewhere meanwhile stays, and the branch is still announced.
560
+ When the landed path (the pressed message has left the list) does not hold the sibling, focus goes to the earlier-messages button with the branch announced, since the sibling is on an earlier page (the path below it is longer than a page); with no earlier page, it goes to the last article and nothing is announced.
561
+ A switch that was not made leaves focus on the pressed button. One that failed is a paragraph under the group, which the list tells once per occurrence, however often the virtual list remounts the row.
562
+ The actions keep the hooks `<article's testId>-actions-bar` (the toolbar), `-branch`, `-branch-previous`, `-branch-next`, `-branch-position`, `-branch-end-reason`, `-branch-problem`, `-edit` or `-regenerate` (the role's action, with `data-aqchat-message-action` and `data-aqchat-actions-display`) and `-regenerate-problem`, and the branch buttons carry their direction (`data-aqchat-branch-button`: `previous` or `next`).
563
+ The edit form keeps `<article's testId>-edit-form` (`data-aqchat-message-edit`) with `-label`, `-input`, `-reason`, `-send`, `-cancel`, `-cancel-reason`, `-send-key-hint` and `-problem`, and the list's note `<testId>-actions-note` with `-actions-note-switching`, `-actions-note-writing` and `-actions-note-editing`.
531
564
  The host gives the list its height, opens one list per conversation (the conversation's `key`), and loads `@aiquants/virtualscroll`'s styles once.
532
565
 
533
566
  `useChatConversation` reads the conversation's row (`getConversation`) and the latest page of its chosen path (`listMessages`) together, and is `open` once both answer.
@@ -550,10 +583,17 @@ While it reads, the notice is `awaiting-end` (when no other notice shows), and t
550
583
  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
584
  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
585
  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.
586
+ `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, and so does a call while a change of the path runs, since a go-to reads the earlier pages it needs); a page whose cursor a read again replaced meanwhile is dropped.
554
587
  `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
588
  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
589
  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.
590
+ `switchBranch(messageUid, siblingUid)` switches a message on the path to another of its siblings: a message with a parent sends its parent's `setActiveChild`, a message without one the conversation's `setActiveRoot`, and the path the switch answers (`active_path`) lands as one read, the row and the page together, as a read lands.
591
+ A switch takes the one place reads take: during a read it is sent once that read lands, which hands the place to the switch within its own completion (no read sent before it lands an older path after it, and no waiter of that read reads again before it), a read asked for during the switch runs once after it, and a switch that lands settles the reads asked for before it.
592
+ It answers `switched`, or `not-switched` without sending while the window is not open, while the message is no longer on the path, or while another switch runs; a sibling that is not another sibling of the message rejects its promise with a `RangeError`.
593
+ `branchSwitch` holds the switch under way (`switching`: the message and the sibling) and the last one that failed (`problem`: the message, `unreached`, `refused` with the refusal, or `incompatible`, numbered by its occurrence and cleared when the next switch starts). A switch that failed reads the conversation again.
594
+ A switch is not the conversation's activity, so the row read at focus reads the conversation again when it shows another chosen root (`active_root_message_uid`), and another window's switch of a child shows at the next read.
595
+ `runElsewhere` is true while the conversation's unfinished run writes an answer that is not on the window's path (another branch: a conversation has one unfinished run at most). While nothing on the path is followed and the window holds no view of that run (a subscription without a view closes in the same commit, as when a switch takes a streamed answer off the path), the state read follows that run, reading its end alone, without the `awaiting-end` notice, and reads the conversation once it ends.
596
+ A switch that brings the followed run's answer onto the path, or takes it off, starts the state read again: on the path with the notice and the reads of its segments and answer, off the path without them.
557
597
  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
598
  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
599
  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.
@@ -564,9 +604,17 @@ An accepted send (`accepted`) answers the message sent as `sentMessageUid` and h
564
604
  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
605
  `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
606
  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.
607
+ 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, an accepted send waits, or the conversation's unfinished run writes on another branch (`runElsewhere`, the window's, which the hook answers too: the server refuses a send meanwhile, and the stop goes to the row's run), and `ready` otherwise.
568
608
  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).
609
+ `edit(messageUid, message)` edits a user's message on the window's path (`startRun` of kind `edit`: a sibling of the message with its answer) and `regenerate(messageUid)` regenerates an answer on the path (kind `regenerate`: a sibling of the answer), with the conversation's model and reasoning level, only while the phase is `ready`, the window is open and switches no branch, and the message is on the path in the role its kind names; otherwise they answer `not-sent` without sending.
610
+ They share the send's ID rule, its phase (`sending`, then the accepted run's wait), the stop's target and the numbering of failures; the content an ID stands for also holds the count of the target's siblings the window lists, since a rewrite adds a sibling: once the window lists the sibling of a request that landed unseen (or one another window wrote), the same request is a new rewrite with a new ID, which the server would otherwise answer with the earlier acceptance.
611
+ An acceptance names the new user's message for an edit and none for a regeneration (the contract's `user_message_uid` is `null` for `regenerate` alone), else it breaks the contract.
612
+ An accepted one answers `{ kind: "accepted", siblingUid }` (the new user's message, or the new answer) once the window's read after the acceptance has settled, so the list lands it, and leaves `sentMessageUid`, which only a send sets.
613
+ `rewrite` holds the one being sent (`pending`, from the press until that read settles), the last accepted one with the sibling it wrote (`accepted`, until the next one starts), the last failed one (`problem`: the message, the kind, `unreached`, `refused` with the refusal, or `incompatible`, cleared when the next send, edit or regeneration starts), and why none can be sent now (`block`: `sending` while a request of the window is under way, `writing` while a run has not ended). A failed one has the window read again; the list keeps the edit's text.
614
+ An argument that is not a uid or a message to send rejects the promise with a `TypeError`, and an edit the contract refuses with a `RangeError`, before the phase moves.
615
+ 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.
616
+ 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 and no edit or regeneration being sent (whether a hidden request landed shows in the window's read again).
617
+ The hidden window answers its read after an acceptance as not landed, so an accepted run still waiting has the shown window read again and ends its wait when that read lands.
570
618
 
571
619
  ### Writing and sending
572
620
 
@@ -577,6 +625,8 @@ import { ChatComposer, ChatFrame, ChatMessageList, ChatTalkHeading, chatBrowserM
577
625
  const microphone = chatBrowserMicrophone(globalThis)
578
626
 
579
627
  // draft: the conversation's draft the host keeps; phase: "ready", "sending", "running" or "stopping" (useChatSend's phase);
628
+ // runElsewhere: whether the conversation's unfinished answer is on another branch (useChatSend's runElsewhere);
629
+ // pathBlock: why the window's path stops sends now, "branch" or "going" (useChatSend's pathBlock), or null;
580
630
  // notice: the open conversation's window's notice (above); problem: the failed send ({ cause, occurrence }) useChatSend answers, or null;
581
631
  // attachments: the message's attachments in their stages of upload (ChatComposerAttachment[]);
582
632
  // model: the chosen model's flags; limits: GET /settings' limits (the composer reads a message's length and the attachments' five);
@@ -593,6 +643,8 @@ const microphone = chatBrowserMicrophone(globalThis)
593
643
  value={draft}
594
644
  onValueChange={setDraft}
595
645
  phase={phase}
646
+ runElsewhere={runElsewhere}
647
+ pathBlock={pathBlock}
596
648
  onSend={(text) => send(text)}
597
649
  onStop={() => stop()}
598
650
  notice={notice}
@@ -611,6 +663,7 @@ const microphone = chatBrowserMicrophone(globalThis)
611
663
  limits={limits}
612
664
  sendKey={sendKey}
613
665
  contentBaseUrl="/bff"
666
+ inputRef={null}
614
667
  testId="composer"
615
668
  />
616
669
  </>
@@ -621,8 +674,10 @@ const microphone = chatBrowserMicrophone(globalThis)
621
674
  />
622
675
  ```
623
676
 
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.
677
+ 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),
678
+ the paragraph of an unfinished answer on another branch, the guide to the send key, the guide to what the chosen model takes, and the disclaimer.
625
679
  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.
680
+ The host is handed the text area by `inputRef` (a ref object, or `null` for a host that is not), to move focus into it, as after the open conversation is deleted.
626
681
  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
682
  `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
683
  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.
@@ -634,12 +689,14 @@ The composer reads the failed send and each attachment once where it checks them
634
689
  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
690
  Keep the file for another try after the upload; an attachment restored with a draft holds none.
636
691
  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.
692
+ `onSend` receives the text only while the phase is `ready` and nothing stops the send.
693
+ In order of precedence, a text longer than the limit of a message (`CHAT_USER_MESSAGE_MAX_CHARS`) stops it until it is shortened, a text holding a broken character (a lone surrogate, which the contract refuses in every text and a paste can carry) until it is deleted, no model chosen until one is, 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.
694
+ 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`, as it is for a broken character. The text's length goes first since an attachment's problem also shows on its row, while the length shows nowhere else.
639
695
  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
696
  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
697
  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
698
  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.
699
+ While an answer on another branch has not finished (`runElsewhere`) and the phase is `running` or `stopping`, the composer says so in a paragraph (`<testId>-run-elsewhere`) that describes the stop button and the input, announced once when it appears.
643
700
  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
701
  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
702
  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.
@@ -782,7 +839,7 @@ A save that does not land, is refused or whose answer cannot be read keeps the s
782
839
  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
840
  `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
841
 
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.
842
+ `ChatSettingsForm` shows the eight 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, how a message's actions show and the default model. Collapsing the actions' labels at a narrow width waits for icons the actions can show, and keeps its value.
786
843
  Each is a radio group, or a group of one checkbox for a flag, with the catalog's name and description.
787
844
  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
845
  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.
@@ -797,6 +854,57 @@ A sign-in that ended goes to the root's presenter of access failures instead (si
797
854
  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
855
  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
856
 
857
+ ### Asking for consent to the usage policy
858
+
859
+ ```tsx
860
+ import { ChatConsentConversation, ChatPolicyGate, useChatPolicy } from "@aiquants/chat/react"
861
+ import { useRef } from "react"
862
+
863
+ // inside the settings gate's children: the policy's read and consent, and the gate around the screen's main place
864
+ const ChatMain = ({ conversationUid, onChanged, onDeleted }: ChatMainProps) => {
865
+ // transport: createHttpChatTransport's answer; hostRefusalCodes: the host's numbers of its refusal roles
866
+ const policy = useChatPolicy({ transport, hostRefusalCodes })
867
+ // the screen's heading, which takes focus when the consent opens the main place
868
+ const headingRef = useRef<HTMLHeadingElement>(null)
869
+ // the open conversation's band of the operations that need no consent: stop and delete
870
+ const aside = conversationUid === null ? null : <ChatConsentConversation transport={policy.transport} hostRefusalCodes={hostRefusalCodes} conversationUid={conversationUid} onChanged={onChanged} onDeleted={onDeleted} headingLevel={2} testId="chat-consent-conversation" />
871
+ return (
872
+ <ChatPolicyGate policy={policy} focusAfterConsent={headingRef} aside={aside} headingLevel={2} testId="chat-policy">
873
+ {/* every other part takes policy.transport, so a refusal that asks for consent reads the policy again */}
874
+ {() => <ChatTalk transport={policy.transport} headingRef={headingRef} />}
875
+ </ChatPolicyGate>
876
+ )
877
+ }
878
+ ```
879
+
880
+ `useChatPolicy` reads the tenant's usage policy (`getPolicy`) when it mounts, and again when it is shown while it holds none.
881
+ It says whether the person consented to the current version by the state the server decided, never by comparing the numbers: `consented`, or `consent-needed` with the policy to show (`none`, or `earlier` with the version last consented to).
882
+ A tenant that has published no version is refused with `CHAT_POLICY_NOT_PUBLISHED` (40311), which the hook tells apart as `not-published` with a `retry` that reads again; its other refusals and failures are those of the settings' read.
883
+ `consent()` sends the number of the current version shown (`consentPolicy`), one at a time and only while consent is needed.
884
+ Once the server takes it the policy is read again, and until that read lands `consenting` stays true and the state stays the consent shown, so the consent screen and its pressed button stay.
885
+ A consent refused because a later version was published after the read (`CHAT_POLICY_CONSENT_REQUIRED`) reads the policy again and holds the problem `superseded`.
886
+ The other problems (`unreached`, `refused` and `incompatible`) are held with their occurrence, and a consent that lands or a read that finds the current version consented clears them.
887
+ Leaving, or a hide by `Activity`, stops a consent under way, and a screen shown again after such a hide reads the policy again, since whether the consent arrived is not known.
888
+ `transport` is the given transport wrapped: when an endpoint other than these two refuses with `CHAT_POLICY_CONSENT_REQUIRED` while the policy is read as consented (a version published while the screen is open), the policy is read again, and the outcome is returned unchanged.
889
+ Hand it to every other part of the screen.
890
+
891
+ `ChatPolicyGate` draws its children once the person consented to the current version.
892
+ Until then it draws, in the root's language, the policy's read as the settings gate does, or the paragraph of a tenant without a version with a button that reads again, or the consent screen.
893
+ The consent screen has a heading, which takes focus when the screen appears and when a later version is shown, the version's number and publication date, its note, a lead, and the text in the root's language in the paragraphs its blank lines part.
894
+ For a person who consented to an earlier version it shows the line-by-line difference from that version instead, each added and removed line marked in words for a screen reader and by a sign on screen, as `ins` and `del`.
895
+ Then come the button that consents to the version shown, busy while the consent runs, and the paragraph of a consent that did not land, told once.
896
+ What the host passes as `aside` is drawn before the consent screen and the paragraph of a tenant without a version.
897
+ Its heading stands at `headingLevel`, the difference is a list (`role="list"`, kept until either text changes), and the paragraph of a consent that did not land shows once the policy's read after it has landed.
898
+ Children once drawn stay mounted, hidden by React's `Activity`, while the person is asked again, so what they were writing waits for the consent.
899
+ Focus moves to the consent screen's heading when it appears or shows another version, and to the read's area when the children are hidden for another state, only when focus is free, in the hidden children or in the consent screen, never out of the list or the aside.
900
+ When the consent opens the children and its button leaves holding focus, focus moves to `focusAfterConsent`.
901
+
902
+ `ChatConsentConversation` is the open conversation's band while consent is needed, which the host passes as the gate's `aside`.
903
+ It reads the conversation's row on its own (`getConversation`) and has only the operations that need no consent, so that a person who does not consent can still stop an answer that keeps sending the conversation to its model and delete the conversation.
904
+ The stop (`cancelRun`) is sent again while the admission is busy, and the row is read again after it: a run that ended is told once, and one still running says it was asked to stop, with a button that reads the row again.
905
+ Delete (`deleteConversation`) asks in the open conversation's band's confirmation dialog; it cannot be pressed while an answer is being written, which its reason says, and a delete that lands calls `onChanged` and `onDeleted`, even when the band left before the answer, so the host never keeps a deleted conversation.
906
+ The band keys itself by the conversation, its title stands at `headingLevel`, and when it loses its row to a failed read its dialog closes and a focus it held moves to the failed read's paragraph.
907
+
800
908
  ### Listing the conversations
801
909
 
802
910
  ```tsx
@@ -840,6 +948,75 @@ A section with a next cursor reads up to it in one request (`until`) and lays th
840
948
  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
949
  The operations on a conversation belong to its heading.
842
950
 
951
+ ### Operating an open conversation from its heading band
952
+
953
+ ```tsx
954
+ import { ChatConversationHeading, ChatTalkHeading, useChatConversationActions, useChatConversationDeletedAnnouncer } from "@aiquants/chat/react"
955
+
956
+ const actions = useChatConversationActions({
957
+ transport,
958
+ window,
959
+ hostRefusalCodes,
960
+ onChanged: () => {
961
+ list.pinned.reload()
962
+ list.recent.reload()
963
+ },
964
+ onDeleted: (conversation) => {
965
+ deletedRef.current = conversation
966
+ navigate(basePath, { replace: true })
967
+ },
968
+ })
969
+ // Once the new conversation's composer has taken focus:
970
+ const announceDeleted = useChatConversationDeletedAnnouncer()
971
+ announceDeleted(deletedRef.current)
972
+
973
+ talkHeading={state.kind === "open" ? <ChatConversationHeading conversation={state.conversation} actions={actions} level={2} labelId="talk-title" testId="talk-heading" /> : <ChatTalkHeading conversation={null} level={2} labelId="talk-title" testId="talk-heading" />}
974
+ ```
975
+
976
+ `ChatConversationHeading` draws the open conversation's heading band in the talk bar: the title (`ChatTalkHeading`, keeping the title's test ID), the declared level (`confidentialityLevels`' name), a button that renames the conversation, the console's switch that pins it, and a button that deletes it.
977
+ `useChatConversationActions` runs the operations one at a time; while one runs, the band's other controls cannot be pressed and say why.
978
+ A rename and a pin send `updateConversation`, and the band is ready again as soon as it answers: the window reads the conversation again (the band never applies the answer's row to the window, so the window's row and path stay its own reads) and `onChanged` lets the host read its list again (both sections: a pin moves the row between them).
979
+ The row the change answered is the hook's `landed` until a read of the window that started after the answer lands, and the band shows its title and pin over the window's row (`chatConversationShownRow(row, landed)`), so neither flickers back while the window reads; the band does not wait for that read, because a read that is not reached keeps waiting for a later one (the window's notice offers to read again).
980
+ A delete of a conversation whose run is running stops that run first (`cancelRun`, sent again while the admission is busy) and waits until the window's row no longer holds a running run; a run that is queued or awaits an approval goes with the conversation. It then sends `deleteConversation` and calls `onChanged` and `onDeleted` with the row the band showed, and stays deleting until the host takes the band away, so a second press sends no second delete.
981
+ A failure (refused, not reached, a broken contract) is the band's problem, numbered by its occurrence, and has the window read again. A refusal because an answer started elsewhere is being written (`CHAT_RUN_ACTIVE`) stays deleting until that read lands and then offers to stop and delete, which stops the run the read found; closing the confirmation gives the wait up.
982
+ Each failure's paragraph and the paragraph saying the run is being stopped are told once when they appear, and a failure that happens again is told again (into the open dialog's region while a dialog is open).
983
+ The rename's dialog checks the title as the contract does once the reader tried (not empty, at most `CHAT_CONVERSATION_TITLE_MAX_LENGTH` units, at least one character that shows), marks the field invalid with the reason and tells the reason at each try; the field has no `maxLength`, and a refusal that names the title marks the field with the refusal's paragraph. A rename that lands closes the dialog and is told once through the root's announcer after it closed.
984
+ The delete's confirmation names the title, says a deleted conversation cannot be restored and, for a running run, that the answer being written is stopped first; while the run is being stopped it says so, and closing it gives the delete up.
985
+ After a delete the host moves to a new conversation and puts focus in its composer, then calls the function `useChatConversationDeletedAnnouncer` answers with the deleted row, which says once through the root's announcer that the conversation was deleted.
986
+ The band's hooks are named after the title's test ID: `<testId>-band` (`data-aqchat-conversation-heading`), `<testId>-level` (`data-aqchat-conversation-level`), `<testId>-rename`, `<testId>-pin`, `<testId>-delete`, `<testId>-problem`, `<testId>-rename-dialog` (`-rename-field`, `-rename-save`, `-rename-problem`) and `<testId>-delete-dialog` (`-delete-stopping`, `-delete-problem`, `-delete-stop`, `-delete-confirm`).
987
+
988
+ ### Going to a message and showing another branch
989
+
990
+ ```tsx
991
+ import { ChatShownBranchBand, type ChatMessageLanding } from "@aiquants/chat/react"
992
+
993
+ const [landing, setLanding] = useState<ChatMessageLanding | null>(null)
994
+ const occurrence = useRef(0)
995
+ // A permalink (`<base>/<conversation uid>/<message uid>`) opens at its message without moving focus:
996
+ useEffect(() => {
997
+ if (window.state.kind !== "open" || messageUid === null) {
998
+ return
999
+ }
1000
+ void window.goTo(messageUid, "link").then((outcome) => {
1001
+ if (outcome === "shown") {
1002
+ occurrence.current += 1
1003
+ setLanding({ messageUid, focus: false, marked: true, occurrence: occurrence.current })
1004
+ }
1005
+ })
1006
+ }, [window.state.kind, messageUid])
1007
+
1008
+ <ChatShownBranchBand window={window} focusAfterChange={composerInput} testId="shown-branch" />
1009
+ ```
1010
+
1011
+ The window shows the chosen path, or another branch without writing a choice (`path`; the contract's §9.3.2).
1012
+ `goTo(messageUid, via)` shows a message the window holds at once; for any other it reads the conversation's tree and shows the branch through the message (from it, the tree's chosen children to the end): the chosen path when the message is on it, read by `listMessages`, or the branch, read by the path read of its last message (`getMessagePath`).
1013
+ Its page replaces the window's messages and their cursor, and it reads earlier pages until the message comes and answers `shown`, `missing` (the tree does not hold the message) or `not-gone`; `via` says whether a link (`link`) or the screen (`screen`) asked.
1014
+ While the window shows another branch, its reads and earlier pages read that branch, a switch of a message's branch shows the sibling's branch without writing, and `useChatSend` sends no message, edit or regeneration (`pathBlock` and `rewrite.block` are `branch`); nor does it while the window goes to a message from the chosen path (`going`), since what it shows may change to another branch.
1015
+ The composer's `pathBlock` says why the send button cannot be pressed; the list's blocked edits and regenerations name a note, shown while a branch shows and hidden while going (a go-to is brief, and a note that came and went would make the list jump).
1016
+ `chooseBranch()` writes the branch's choices from the end's side, the root last, so the chosen path changes at once with the last write; `returnToChosen()` reads the chosen path. A failed change is the window's `pathChange.problem`, numbered by its occurrence and cleared when the next change starts (a switch included).
1017
+ `ChatShownBranchBand` draws, over the messages, that the branch shown is not the chosen one with "Choose this branch" and "Back to the chosen branch", and the paragraph of a failed change; after a choice or a return lands it moves a focus that was in the band (or fell with it) to `focusAfterChange`.
1018
+ The list lands at a message the host names (`landing`: once per occurrence, with focus or not, and marking the message a link opened as "Linked message"), and every message's actions copy its link (`messageHrefOf`, made absolute against `location.href`).
1019
+
843
1020
  ### Checking an attachment before its upload
844
1021
 
845
1022
  ```ts
@@ -960,6 +1137,45 @@ A request no step is left for took no step and is not among `requests()`; one wh
960
1137
  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
1138
  `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
1139
 
1140
+ ### Drawing a run's stream without a server
1141
+
1142
+ ```ts
1143
+ import { formatSseHeartbeatData, SSE_HEARTBEAT_EVENT, systemSseRuntime } from "@aiquants/sse"
1144
+ import { createChatScenarioRunStreams } from "@aiquants/chat/testing"
1145
+
1146
+ const scenario = createChatScenarioRunStreams({
1147
+ baseUrl: streams.baseUrl,
1148
+ cursorParam: streams.cursorParam,
1149
+ idBaseMs: 1763690000000,
1150
+ heartbeat: { event: SSE_HEARTBEAT_EVENT, data: formatSseHeartbeatData(1763690000000), everyMs: 15_000 },
1151
+ timers: systemSseRuntime,
1152
+ runs: {
1153
+ [runUid]: [
1154
+ { kind: "event", afterMs: 0, event: "run.started", data: started },
1155
+ { kind: "event", afterMs: 80, event: "step.started", data: { step: 1, kind: "llm" } },
1156
+ { kind: "event", afterMs: 80, event: "text.delta", data: { step: 1, text: "## Monthly stock" } },
1157
+ { kind: "gate", gate: "stop" },
1158
+ { kind: "event", afterMs: 80, event: "usage", data: { step: 1, ...estimatedUsage } },
1159
+ { kind: "event", afterMs: 80, event: "run.cancelled", data: { cancelled_by: "user", calls: [] } },
1160
+ ],
1161
+ },
1162
+ })
1163
+ const scenarioStreams = { ...streams, reopen: { ...streams.reopen, createEventSource: scenario.createEventSource } }
1164
+ // The host's reads show the run running until its stream has carried its end.
1165
+ const running = scenario.endOf(runUid) === null
1166
+ ```
1167
+
1168
+ `createChatScenarioRunStreams` makes the scenario's run streams (`ChatScenarioRunStreams`, frozen), whose `createEventSource` a host hands its run streams (`reopen.createEventSource`) in the server's place, so a screen draws a run's stream (an answer being written, stopped, failed or cut) through the package's own subscription.
1169
+ Each run's script is a list of steps played in order on the timers the host gives (`@aiquants/sse`'s runtimes fit: `systemSseRuntime` in a browser, a manual runtime in a test): an event of the contract after `afterMs`, the stream layer's `resync-required` (`kind: "resync"`), a dropped connection (`kind: "drop"`) the subscription reopens from its last ID, or a gate (`kind: "gate"`) the host opens later with `release(runUid, gate)` (a gate opened before the stream reaches it passes at once).
1170
+ The streams behave as the server's do: every event carries a stream ID of the Redis form `<idBaseMs>-<seq>` (`idBaseMs` is a positive safe integer, since Redis never issues `0-0`), rising by one per event of the script, while `resync-required` carries none.
1171
+ An open stream sends the host's heartbeat (`heartbeat`: the stream layer's frame, `@aiquants/sse`'s `SSE_HEARTBEAT_EVENT` and `formatSseHeartbeatData` for instance, and the server's interval `everyMs`) from its opening to its last event, so the subscription's stale watch never reopens a stream held open: a script that ends without a terminal event, or one waiting at a gate.
1172
+ Nothing follows a terminal event of the contract, `resync-required` included, not even the heartbeat.
1173
+ A subscription without a cursor starts at the first step, and a stream with a cursor (a reopen, or a first stream from a seed's mark) continues after the event the cursor names and repeats nothing; a drop or a `resync-required` a stream has passed does not happen again.
1174
+ Once a stream has carried a run's end (`run.completed`, `run.failed` or `run.cancelled`), `endOf(runUid)` answers it, and `null` before; the scenario records the end before the frame reaches the subscription, so the host's reads can show the run as the server's do: running until its stream carries its end, and ended in the reread the end makes the window do.
1175
+ The scenario checks the options and every step when it is made, an event by the contract's reader (`parseChatEvent`), and throws for anything it cannot play: the heartbeat's event must be a non-empty name that is not an event of the contract, and its interval an integer from 1 to `CHAT_SCENARIO_STREAM_MAX_WAIT_MS`.
1176
+ A stream the scripts do not plan, a cursor its script does not hold, a second stream of a run while one is open, the release of a gate no script has and the end asked of a run no script plans are breaches, which `breaches()` lists in the order they happened; such a stream fails at once, and such an end is `null`.
1177
+ The entry imports no `@aiquants/sse`: the host hands the timers and the heartbeat's frame and composes the streams.
1178
+
963
1179
  ## Development
964
1180
 
965
1181
  ```bash
@@ -1 +1 @@
1
- import{a as k,b as y}from"./chunk-EEUIBWBF.js";import"./chunk-PLNRET3Z.js";import"./chunk-4NR4KSV6.js";import{MarkdownRenderer as K}from"@aiquants/markdown";import{useEffect as G,useMemo as V}from"react";var _=/<h([1-6])(?=[\s/>])/giu,v=/<!--[\s\S]*?(?:-->|$)|<(script|style|xmp|iframe|noembed|noframes|noscript|template)(?=[\s/>])[^>]*>[\s\S]*?(?:<\/\1\s*>|$)|<plaintext(?=[\s/>])[\s\S]*$/giu,D=e=>{let n=null;for(let[,t]of e.replace(v,"").matchAll(_)){let o=Number(t);(n===null||o<n)&&(n=o)}return n},C=(e,n,t)=>t?e:e.slice(0,n.at(-1)??0),E=(e,n)=>{let t=D(n);return t===null?e:Math.max(1,e-(t-1))};import{useConsoleUi as S,VisuallyHidden as L}from"@aiquants/console-ui";import{useContext as P}from"react";import{Fragment as w,jsx as p,jsxs as c}from"react/jsx-runtime";var b="noopener noreferrer nofollow",R="https://first.invalid/",x="https://second.invalid/",I=new Set(["mailto:","tel:"]),F=/^fn:[1-9]\d*$/u,W=/^fnref([1-9]\d*)?:([1-9]\d*)$/u,U=String.fromCodePoint(8617,65038),A="aqchat-answer-footnote-words",$=(e,n,t,o)=>{let a=`#${o}`;if(!n.startsWith(a))return null;let i=n.slice(a.length);if(e==="doc-noteref")return F.test(i)?{role:e}:null;let s=e==="doc-backlink"&&t===U?W.exec(i):null;if(s===null)return null;let r=s[1],l=r===void 0?1:Number(r)+1;return Number.isSafeInteger(l)?{role:"doc-backlink",number:s[2],reference:l}:null},T=e=>{if(!(URL.canParse(e,R)&&URL.canParse(e,x)))return{kind:"text"};let n=new URL(e,R);return n.href!==new URL(e,x).href?{kind:"text"}:n.protocol==="https:"||n.protocol==="http:"?{kind:"web",host:n.host}:I.has(n.protocol)?{kind:"contact"}:{kind:"text"}},d=(e,n)=>{let t=e.trim();if(t==="")return null;let o=e.indexOf(t);return c(w,{children:[e.slice(0,o),p("span",{lang:n.locale,dir:n.direction,children:t}),e.slice(o+t.length)]})},N=({href:e,className:n,attributes:t,children:o})=>{let a=k(),{locale:i}=S(),s=P(y);if(s===null)throw new Error("ChatAnswerLink: render the answer inside a message's body");let r={locale:i,direction:a.direction},{id:l,title:m,lang:u,dir:g}=t;if(e.startsWith("#")){let f=$(t.role,e,o,s.idPrefix),O=M=>{M.preventDefault(),s.follow(e)};return p("a",{id:l,title:m,lang:u,dir:g,role:f?.role,className:n,href:e,onClick:O,children:f===null?o:f.role==="doc-noteref"?c(w,{children:[p(L,{testId:A,children:d(a.answer.footnote.reference,r)}),o]}):c(w,{children:[p("span",{"aria-hidden":"true",children:o}),p(L,{testId:A,children:d(a.answer.footnote.back(f.number,f.reference),r)})]})})}let h=T(e);return h.kind==="web"?c("a",{id:l,title:m,lang:u,dir:g,className:n,href:e,target:"_blank",rel:b,children:[o," ",d(a.answer.newTab(h.host),r)]}):h.kind==="contact"?c("a",{id:l,title:m,lang:u,dir:g,className:n,href:e,rel:b,children:[o," ",d(a.answer.destination(e),r)]}):c("span",{id:l,title:m,lang:u,dir:g,children:[o," ",d(a.answer.destination(e),r)]})},B=(e,n,t)=>n===void 0||n===""?d(e.name,t):c(w,{children:[d(e.before,t),n,d(e.after,t)]}),H=({src:e,alt:n,insideLink:t})=>{let o=k(),{locale:a}=S(),i={locale:a,direction:o.direction},s=B(o.answer.image,n,i),r=e===void 0?null:T(e);return r===null||r.kind!=="web"?p("span",{children:s}):t?c("span",{children:[s," ",d(o.answer.destination(r.host),i)]}):c("a",{href:e,target:"_blank",rel:b,children:[s," ",d(o.answer.newTab(r.host),i)]})};import{jsx as q}from"react/jsx-runtime";var re=({conversion:e,streaming:n,truncated:t,headingLevel:o,idPrefix:a,theme:i,drawing:s,maxDiagrams:r,onDrew:l})=>{G(()=>{l(e)},[e,l]);let{htmlContent:m,blockOffsets:u}=e,g=V(()=>E(o,C(m,u,!(n||t))),[o,m,u,n,t]);return q(K,{allowlist:"untrusted",imageComponent:H,linkComponent:N,idPrefix:a,htmlContent:m,blockOffsets:u,blockKeyEpoch:e.blockKeyEpoch,streaming:n,truncated:t,theme:i,topHeadingLevel:g,mermaidDrawing:s,maxMermaidDiagrams:r})};export{re as ChatAnswerHtml};
1
+ import{a as k,b as y}from"./chunk-BTDHRYBO.js";import"./chunk-KNPMHSTQ.js";import"./chunk-GSCTWGZT.js";import{MarkdownRenderer as K}from"@aiquants/markdown";import{useEffect as G,useMemo as V}from"react";var _=/<h([1-6])(?=[\s/>])/giu,v=/<!--[\s\S]*?(?:-->|$)|<(script|style|xmp|iframe|noembed|noframes|noscript|template)(?=[\s/>])[^>]*>[\s\S]*?(?:<\/\1\s*>|$)|<plaintext(?=[\s/>])[\s\S]*$/giu,D=e=>{let n=null;for(let[,t]of e.replace(v,"").matchAll(_)){let o=Number(t);(n===null||o<n)&&(n=o)}return n},C=(e,n,t)=>t?e:e.slice(0,n.at(-1)??0),E=(e,n)=>{let t=D(n);return t===null?e:Math.max(1,e-(t-1))};import{useConsoleUi as S,VisuallyHidden as L}from"@aiquants/console-ui";import{useContext as P}from"react";import{Fragment as w,jsx as p,jsxs as c}from"react/jsx-runtime";var b="noopener noreferrer nofollow",R="https://first.invalid/",x="https://second.invalid/",I=new Set(["mailto:","tel:"]),F=/^fn:[1-9]\d*$/u,W=/^fnref([1-9]\d*)?:([1-9]\d*)$/u,U=String.fromCodePoint(8617,65038),A="aqchat-answer-footnote-words",$=(e,n,t,o)=>{let a=`#${o}`;if(!n.startsWith(a))return null;let i=n.slice(a.length);if(e==="doc-noteref")return F.test(i)?{role:e}:null;let s=e==="doc-backlink"&&t===U?W.exec(i):null;if(s===null)return null;let r=s[1],l=r===void 0?1:Number(r)+1;return Number.isSafeInteger(l)?{role:"doc-backlink",number:s[2],reference:l}:null},T=e=>{if(!(URL.canParse(e,R)&&URL.canParse(e,x)))return{kind:"text"};let n=new URL(e,R);return n.href!==new URL(e,x).href?{kind:"text"}:n.protocol==="https:"||n.protocol==="http:"?{kind:"web",host:n.host}:I.has(n.protocol)?{kind:"contact"}:{kind:"text"}},d=(e,n)=>{let t=e.trim();if(t==="")return null;let o=e.indexOf(t);return c(w,{children:[e.slice(0,o),p("span",{lang:n.locale,dir:n.direction,children:t}),e.slice(o+t.length)]})},N=({href:e,className:n,attributes:t,children:o})=>{let a=k(),{locale:i}=S(),s=P(y);if(s===null)throw new Error("ChatAnswerLink: render the answer inside a message's body");let r={locale:i,direction:a.direction},{id:l,title:m,lang:u,dir:g}=t;if(e.startsWith("#")){let f=$(t.role,e,o,s.idPrefix),O=M=>{M.preventDefault(),s.follow(e)};return p("a",{id:l,title:m,lang:u,dir:g,role:f?.role,className:n,href:e,onClick:O,children:f===null?o:f.role==="doc-noteref"?c(w,{children:[p(L,{testId:A,children:d(a.answer.footnote.reference,r)}),o]}):c(w,{children:[p("span",{"aria-hidden":"true",children:o}),p(L,{testId:A,children:d(a.answer.footnote.back(f.number,f.reference),r)})]})})}let h=T(e);return h.kind==="web"?c("a",{id:l,title:m,lang:u,dir:g,className:n,href:e,target:"_blank",rel:b,children:[o," ",d(a.answer.newTab(h.host),r)]}):h.kind==="contact"?c("a",{id:l,title:m,lang:u,dir:g,className:n,href:e,rel:b,children:[o," ",d(a.answer.destination(e),r)]}):c("span",{id:l,title:m,lang:u,dir:g,children:[o," ",d(a.answer.destination(e),r)]})},B=(e,n,t)=>n===void 0||n===""?d(e.name,t):c(w,{children:[d(e.before,t),n,d(e.after,t)]}),H=({src:e,alt:n,insideLink:t})=>{let o=k(),{locale:a}=S(),i={locale:a,direction:o.direction},s=B(o.answer.image,n,i),r=e===void 0?null:T(e);return r===null||r.kind!=="web"?p("span",{children:s}):t?c("span",{children:[s," ",d(o.answer.destination(r.host),i)]}):c("a",{href:e,target:"_blank",rel:b,children:[s," ",d(o.answer.newTab(r.host),i)]})};import{jsx as q}from"react/jsx-runtime";var re=({conversion:e,streaming:n,truncated:t,headingLevel:o,idPrefix:a,theme:i,drawing:s,maxDiagrams:r,onDrew:l})=>{G(()=>{l(e)},[e,l]);let{htmlContent:m,blockOffsets:u}=e,g=V(()=>E(o,C(m,u,!(n||t))),[o,m,u,n,t]);return q(K,{allowlist:"untrusted",imageComponent:H,linkComponent:N,idPrefix:a,htmlContent:m,blockOffsets:u,blockKeyEpoch:e.blockKeyEpoch,streaming:n,truncated:t,theme:i,topHeadingLevel:g,mermaidDrawing:s,maxMermaidDiagrams:r})};export{re as ChatAnswerHtml};