@aiquants/chat 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/README.md +218 -26
- package/dist/{ChatAnswerHtml-3K6G6UKC.js → ChatAnswerHtml-UNWOOMYK.js} +1 -1
- package/dist/{chunk-7CEL735H.js → chunk-44WLZMPZ.js} +1 -1
- package/dist/chunk-5MWD2PSY.js +1 -0
- package/dist/chunk-GSCTWGZT.js +1 -0
- package/dist/chunk-HC7HXC2K.js +1 -0
- package/dist/{chunk-PLNRET3Z.js → chunk-KNPMHSTQ.js} +1 -1
- package/dist/{chunk-7KWWXSGA.js → chunk-NWDLT2AZ.js} +1 -1
- package/dist/client.cjs +2 -2
- package/dist/client.d.cts +5 -5
- package/dist/client.d.ts +5 -5
- package/dist/client.js +1 -1
- package/dist/{httpTransport-BAaKwioS.d.ts → httpTransport-Cgj10OUn.d.ts} +1 -1
- package/dist/{httpTransport-D_JJABMq.d.cts → httpTransport-o7MkPUuY.d.cts} +1 -1
- package/dist/{index-iHWm67aF.d.cts → index-g-wjju1F.d.cts} +9518 -1785
- package/dist/{index-iHWm67aF.d.ts → index-g-wjju1F.d.ts} +9518 -1785
- package/dist/protocol.cjs +1 -1
- package/dist/protocol.d.cts +1 -1
- package/dist/protocol.d.ts +1 -1
- package/dist/protocol.js +1 -1
- package/dist/react.cjs +2 -2
- package/dist/react.d.cts +210 -24
- package/dist/react.d.ts +210 -24
- package/dist/react.js +2 -2
- package/dist/{runStream-DLhaMZSu.d.ts → runStream-Wn5F3RKe.d.ts} +3 -1
- package/dist/{runStream-Dd5YdJoh.d.cts → runStream-jp4rlkIw.d.cts} +3 -1
- package/dist/testing.cjs +6 -6
- package/dist/testing.d.cts +55 -4
- package/dist/testing.d.ts +55 -4
- package/dist/testing.js +6 -6
- package/dist/{transport-Clvkp7mW.d.ts → transport-CYd9hh42.d.cts} +23 -1
- package/dist/{transport-5ExGY_ti.d.cts → transport-DlhniH4C.d.ts} +23 -1
- package/package.json +5 -5
- package/dist/chunk-4NR4KSV6.js +0 -1
- package/dist/chunk-TQNSD6RJ.js +0 -1
- package/dist/chunk-WGNEBS4H.js +0 -1
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ 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.
|
|
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
26
|
- For `@aiquants/chat/react` too: `@aiquants/markdown` ^14.0.0, which the answers' rendering reads (the renderer's `truncated`, `mermaidDrawing` and `maxMermaidDiagrams` and the drawer's types, which 13.1.0 first had; this package reads none of the viewer that 14.0.0 split),
|
|
27
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)
|
|
@@ -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`)
|
|
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
|
|
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`) 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.
|
|
@@ -200,7 +200,8 @@ The subscription passes each item with its frame's own ID. A caller that reads f
|
|
|
200
200
|
| `broken` | `incompatible` (only reloading the page mends it) |
|
|
201
201
|
|
|
202
202
|
Every notice is one of four frozen values, so an unchanged notice is the very object returned before.
|
|
203
|
-
|
|
203
|
+
The window shows one more notice that no status gives: `awaiting-end`, while its state read waits for the end of a run whose stream cannot go on (below).
|
|
204
|
+
`nextChatStreamNotice` checks the previous notice, then the status, where they are handed: a previous notice that is neither `null` nor an object is a `TypeError`, and one whose kind is not one a status gives (`awaiting-end` included), or for `unreachable` whose action is not one of the notice's words, is a `RangeError`.
|
|
204
205
|
A status that is not an object is a `TypeError` and one whose kind the subscription does not have is a `RangeError`; of its fields, only those its kind reads are checked: a `terminated`'s `terminalEvent` must be a string (a `TypeError`), and a `connecting`'s `consecutiveFailures` an integer from 0 (a `TypeError` for a value that is not a number, a `RangeError` otherwise).
|
|
205
206
|
|
|
206
207
|
### Filling a path
|
|
@@ -259,8 +260,8 @@ An answer message carries the run that writes it, with its finish reason only wh
|
|
|
259
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.
|
|
260
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.
|
|
261
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.
|
|
262
|
-
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)).
|
|
263
|
-
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.
|
|
264
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).
|
|
265
266
|
|
|
266
267
|
### Reading an endpoint's exchange
|
|
@@ -274,7 +275,7 @@ const { status, answer } = CHAT_EXCHANGES.startRun
|
|
|
274
275
|
const accepted: ChatExchangeAnswer<"startRun"> = chatExchangeShapeSchemas[answer].parse(await response.json())
|
|
275
276
|
```
|
|
276
277
|
|
|
277
|
-
`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.
|
|
278
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).
|
|
279
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.
|
|
280
281
|
|
|
@@ -305,7 +306,7 @@ Its type takes one endpoint and refuses a union of several, whose requests' fiel
|
|
|
305
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`).
|
|
306
307
|
It answers one of four outcomes (`ChatExchangeOutcome<endpoint>`) and never throws for a failed sending or a broken answer:
|
|
307
308
|
|
|
308
|
-
- `answered`: the answer at the endpoint's success status, as its shape reads it (`null` for `deleteAttachment`, which
|
|
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).
|
|
309
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.
|
|
310
311
|
- `unreached`: no answer was read, since the sending threw or rejected (its signal stopping it included) or the answer's body broke off.
|
|
311
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).
|
|
@@ -456,12 +457,13 @@ import { ChatAnswerRendering, ChatComposer, ChatConversationGate, ChatFrame, Cha
|
|
|
456
457
|
// <OpenConversation key={`${conversationUid}:${opening}`} conversationUid={conversationUid} onReopen={() => setOpening((n) => n + 1)} />
|
|
457
458
|
const OpenConversation = ({ conversationUid, onReopen }: { readonly conversationUid: string; readonly onReopen: () => void }) => {
|
|
458
459
|
// transport: createHttpChatTransport's answer; streams: the host's run streams;
|
|
459
|
-
// hostRefusalCodes: the host's numbers of its refusal roles
|
|
460
|
-
|
|
461
|
-
const sending = useChatSend({ transport, window: conversation, hostRefusalCodes })
|
|
462
|
-
// settings: the open settings useChatSettings answers (state.settings, below); converterFactory: createMarkdownConverter with the bundler's worker and
|
|
463
|
-
// WebAssembly URLs bound; mermaidDrawer: createMermaidDrawer's answer; pageTitle: a ref to the page's own heading
|
|
460
|
+
// hostRefusalCodes: the host's numbers of its refusal roles; settings: the open settings useChatSettings answers
|
|
461
|
+
// (state.settings, below), whose limits set the interval of the window's state read too
|
|
464
462
|
const { user_settings: user, limits } = settings
|
|
463
|
+
const conversation = useChatConversation({ transport, streams, conversationUid, hostRefusalCodes, limits })
|
|
464
|
+
const sending = useChatSend({ transport, window: conversation, hostRefusalCodes })
|
|
465
|
+
// converterFactory: createMarkdownConverter with the bundler's worker and WebAssembly URLs bound;
|
|
466
|
+
// mermaidDrawer: createMermaidDrawer's answer; pageTitle: a ref to the page's own heading
|
|
465
467
|
const { state } = conversation
|
|
466
468
|
// uploadedIds: the uids of the attachments uploaded for the message; setDraft: the host's draft of this conversation
|
|
467
469
|
return (
|
|
@@ -484,6 +486,13 @@ const OpenConversation = ({ conversationUid, onReopen }: { readonly conversation
|
|
|
484
486
|
onLoadOlder={conversation.loadOlder}
|
|
485
487
|
olderReading={conversation.olderReading}
|
|
486
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}
|
|
487
496
|
labelledBy="talk-title"
|
|
488
497
|
headingLevel={3}
|
|
489
498
|
limits={limits}
|
|
@@ -491,6 +500,7 @@ const OpenConversation = ({ conversationUid, onReopen }: { readonly conversation
|
|
|
491
500
|
/>
|
|
492
501
|
<ChatComposer
|
|
493
502
|
phase={sending.phase}
|
|
503
|
+
runElsewhere={sending.runElsewhere}
|
|
494
504
|
problem={sending.problem}
|
|
495
505
|
onSend={(text) => void sending.send({ text, attachmentIds: uploadedIds }).then((outcome) => outcome === "accepted" && setDraft(""))}
|
|
496
506
|
onStop={sending.stop}
|
|
@@ -520,27 +530,67 @@ It keeps its area (`data-testid` of the gate, with `data-aqchat-conversation-sta
|
|
|
520
530
|
`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`).
|
|
521
531
|
|
|
522
532
|
`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.
|
|
523
|
-
|
|
524
|
-
|
|
533
|
+
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.
|
|
534
|
+
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.
|
|
535
|
+
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.
|
|
536
|
+
|
|
537
|
+
`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.
|
|
538
|
+
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.
|
|
539
|
+
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.
|
|
540
|
+
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.
|
|
525
541
|
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).
|
|
526
542
|
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`).
|
|
527
543
|
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).
|
|
544
|
+
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.
|
|
545
|
+
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.
|
|
546
|
+
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.
|
|
547
|
+
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.
|
|
548
|
+
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.
|
|
549
|
+
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.
|
|
550
|
+
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.
|
|
551
|
+
"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.
|
|
552
|
+
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.
|
|
553
|
+
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.
|
|
554
|
+
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).
|
|
555
|
+
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.
|
|
556
|
+
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.
|
|
557
|
+
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.
|
|
558
|
+
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.
|
|
559
|
+
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`).
|
|
560
|
+
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`.
|
|
528
561
|
The host gives the list its height, opens one list per conversation (the conversation's `key`), and loads `@aiquants/virtualscroll`'s styles once.
|
|
529
562
|
|
|
530
563
|
`useChatConversation` reads the conversation's row (`getConversation`) and the latest page of its chosen path (`listMessages`) together, and is `open` once both answer.
|
|
531
564
|
For every answer on the path whose run the read shows active with its stream open (`stream_open`), the window holds a view, the later of the one it held and the read's seed: a view the run's own end closed stays even when an older read still shows the run active, one `resync-required` ended gives way to the seed, and of two running views the one with the later mark stays. An answer whose run the read shows ended holds no view and shows the read's text.
|
|
532
565
|
Neither does an answer whose run's stream is no longer open (`stream_open` false), even while the read shows the run active: the window drops a view it held of it (save a view the run's own end closed, which stays) and opens no subscription, since the stream's endpoint would answer only `resync-required`.
|
|
533
|
-
It shows the read's text, the answer so far, as a growing text while the read shows the run writing (`running`), and
|
|
534
|
-
It subscribes, in the same commit, to the stream of every run whose view has not ended, from the view's mark (from the beginning when the view has none), folds the stream into the view, and closes the subscription of a run it no longer holds a view of. The contract's terminal events end a subscription by their names, whatever terminal events the host's streams name meanwhile.
|
|
535
|
-
It lists the messages: an answer's text is the texts of its view's steps in their order, growing while the view has not ended, and any other message's is the read's. Each message is listed against the one the window showed last, so a message whose read and
|
|
566
|
+
It shows the read's text, the answer so far, as a growing text while the read shows the run writing (`running`), and follows the run by its state read (below) until the run ends.
|
|
567
|
+
It subscribes, in the same commit, to the stream of every run whose view has not ended, from the view's mark (from the beginning when the view has none, and for a run the state read below follows), folds the stream into the view, and closes the subscription of a run it no longer holds a view of. The contract's terminal events end a subscription by their names, whatever terminal events the host's streams name meanwhile.
|
|
568
|
+
It lists the messages: an answer's text is the texts of its view's steps in their order, growing while the view has not ended, and any other message's is the read's. A text no stream can write any more (a view `resync-required` ended, or no view) grows while the read shows the run writing. Each message is listed against the one the window showed last, so a message whose read, view and line stay is the same object, and a text that does not continue the text shown (a `step.reset`, or a read that replaced what the stream wrote) is marked `replaced` however many items one render applied.
|
|
569
|
+
One message holds the line of the latest answer's context (`contextCutBefore`): the message the latest answer whose run has been taken cut its context before (`context_cut_before`).
|
|
570
|
+
A run still waiting in the queue for its first segment has not chosen its context, so the line stays at the answer before it until a read shows the run taken (one queued again for a later segment after an approval keeps the boundary its first send chose). The stream carries no boundary, so the read after a run's end moves the line to the answer just written.
|
|
571
|
+
There is no line when that answer cut nothing or when the window does not hold the message it names (an earlier page not read yet: every message the window holds is in the context).
|
|
536
572
|
The notice follows the subscription the window opened last and goes when the window lets go of it. Its `reconnect-now` reopens that subscription at once, and its `reread` reads the conversation again. A read again of an open window that does not land shows `unreachable` with `reread`, and one whose answer breaks the contract `incompatible`, over the stream's notice until a read lands.
|
|
537
|
-
The window reads again, one read at a time with the triggers during a read joined into one more after it, when a stream ends with `resync-required`, when
|
|
573
|
+
The window reads again, one read at a time with the triggers during a read joined into one more after it, when a stream ends with `resync-required`, when a stream brings its run's own end (the row's active run and the path are older than the end, and only the answer's read carries the boundary of its context), when `reread` is pressed,
|
|
574
|
+
and when the window becomes visible or gains focus and the row it reads then shows activity it does not follow: a newer last activity, an active run it neither follows on a stream nor holds ended, or a subscription that stalled (a host's terminal event, reopening given up, or a failed open). With none of them it only takes the row.
|
|
538
575
|
One row read runs at a time (visibility and focus may come together), and a row read that a read again overtook is dropped.
|
|
576
|
+
The state read (plan §2.5.2) follows, until it ends, the first answer on the path whose run is active and whose stream is no longer open, or whose stream the window could not continue twice (a read again's subscription that also ended with `resync-required`). It reads the run whether or not the path still holds its answer (a branch switched meanwhile).
|
|
577
|
+
Every `limits.CHAT_RUN_POLL_INTERVAL_MS` it reads the run (`getRun`). When the run has ended, or waits for an approval in a segment the window does not show yet, it reads the run's answer message (`getMessage`) and puts it in place of the path's message (when the path still holds it), unless the two reads disagree (the run moved between them), which waits for the next read.
|
|
578
|
+
When the run writes a later segment than the window shows, it reads the conversation again once for that segment. When it puts the run's end in place, it stops and reads the conversation once more, since the row's active run and the path are older than the end.
|
|
579
|
+
While it reads, the notice is `awaiting-end` (when no other notice shows), and the window counts the run as followed, so a focus reads only the row. A refusal of either read ends the window as any refusal does, and a read that does not land waits for the next interval.
|
|
580
|
+
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.
|
|
581
|
+
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.
|
|
539
582
|
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.
|
|
540
583
|
`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.
|
|
541
584
|
`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.
|
|
542
585
|
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`.
|
|
543
586
|
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.
|
|
587
|
+
`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.
|
|
588
|
+
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.
|
|
589
|
+
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`.
|
|
590
|
+
`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.
|
|
591
|
+
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.
|
|
592
|
+
`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.
|
|
593
|
+
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.
|
|
544
594
|
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.
|
|
545
595
|
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.
|
|
546
596
|
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.
|
|
@@ -551,9 +601,17 @@ An accepted send (`accepted`) answers the message sent as `sentMessageUid` and h
|
|
|
551
601
|
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.
|
|
552
602
|
`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.
|
|
553
603
|
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.
|
|
554
|
-
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
|
|
604
|
+
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.
|
|
555
605
|
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.
|
|
556
|
-
|
|
606
|
+
`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.
|
|
607
|
+
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.
|
|
608
|
+
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.
|
|
609
|
+
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.
|
|
610
|
+
`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.
|
|
611
|
+
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.
|
|
612
|
+
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.
|
|
613
|
+
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).
|
|
614
|
+
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.
|
|
557
615
|
|
|
558
616
|
### Writing and sending
|
|
559
617
|
|
|
@@ -564,6 +622,7 @@ import { ChatComposer, ChatFrame, ChatMessageList, ChatTalkHeading, chatBrowserM
|
|
|
564
622
|
const microphone = chatBrowserMicrophone(globalThis)
|
|
565
623
|
|
|
566
624
|
// draft: the conversation's draft the host keeps; phase: "ready", "sending", "running" or "stopping" (useChatSend's phase);
|
|
625
|
+
// runElsewhere: whether the conversation's unfinished answer is on another branch (useChatSend's runElsewhere);
|
|
567
626
|
// notice: the open conversation's window's notice (above); problem: the failed send ({ cause, occurrence }) useChatSend answers, or null;
|
|
568
627
|
// attachments: the message's attachments in their stages of upload (ChatComposerAttachment[]);
|
|
569
628
|
// model: the chosen model's flags; limits: GET /settings' limits (the composer reads a message's length and the attachments' five);
|
|
@@ -580,6 +639,7 @@ const microphone = chatBrowserMicrophone(globalThis)
|
|
|
580
639
|
value={draft}
|
|
581
640
|
onValueChange={setDraft}
|
|
582
641
|
phase={phase}
|
|
642
|
+
runElsewhere={runElsewhere}
|
|
583
643
|
onSend={(text) => send(text)}
|
|
584
644
|
onStop={() => stop()}
|
|
585
645
|
notice={notice}
|
|
@@ -598,6 +658,7 @@ const microphone = chatBrowserMicrophone(globalThis)
|
|
|
598
658
|
limits={limits}
|
|
599
659
|
sendKey={sendKey}
|
|
600
660
|
contentBaseUrl="/bff"
|
|
661
|
+
inputRef={null}
|
|
601
662
|
testId="composer"
|
|
602
663
|
/>
|
|
603
664
|
</>
|
|
@@ -608,8 +669,10 @@ const microphone = chatBrowserMicrophone(globalThis)
|
|
|
608
669
|
/>
|
|
609
670
|
```
|
|
610
671
|
|
|
611
|
-
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),
|
|
672
|
+
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),
|
|
673
|
+
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.
|
|
612
674
|
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.
|
|
675
|
+
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.
|
|
613
676
|
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).
|
|
614
677
|
`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.
|
|
615
678
|
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.
|
|
@@ -621,12 +684,14 @@ The composer reads the failed send and each attachment once where it checks them
|
|
|
621
684
|
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.
|
|
622
685
|
Keep the file for another try after the upload; an attachment restored with a draft holds none.
|
|
623
686
|
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.
|
|
624
|
-
`onSend` receives the text only while the phase is `ready` and nothing stops the send.
|
|
625
|
-
|
|
687
|
+
`onSend` receives the text only while the phase is `ready` and nothing stops the send.
|
|
688
|
+
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.
|
|
689
|
+
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.
|
|
626
690
|
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.
|
|
627
691
|
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.
|
|
628
692
|
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).
|
|
629
693
|
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.
|
|
694
|
+
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.
|
|
630
695
|
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`).
|
|
631
696
|
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.
|
|
632
697
|
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.
|
|
@@ -769,7 +834,7 @@ A save that does not land, is refused or whose answer cannot be read keeps the s
|
|
|
769
834
|
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.
|
|
770
835
|
`reread` reads it again in any state, and does nothing while a read is under way or once the screen is hidden or gone.
|
|
771
836
|
|
|
772
|
-
`ChatSettingsForm` shows the
|
|
837
|
+
`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.
|
|
773
838
|
Each is a radio group, or a group of one checkbox for a flag, with the catalog's name and description.
|
|
774
839
|
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).
|
|
775
840
|
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.
|
|
@@ -784,6 +849,57 @@ A sign-in that ended goes to the root's presenter of access failures instead (si
|
|
|
784
849
|
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.
|
|
785
850
|
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`.
|
|
786
851
|
|
|
852
|
+
### Asking for consent to the usage policy
|
|
853
|
+
|
|
854
|
+
```tsx
|
|
855
|
+
import { ChatConsentConversation, ChatPolicyGate, useChatPolicy } from "@aiquants/chat/react"
|
|
856
|
+
import { useRef } from "react"
|
|
857
|
+
|
|
858
|
+
// inside the settings gate's children: the policy's read and consent, and the gate around the screen's main place
|
|
859
|
+
const ChatMain = ({ conversationUid, onChanged, onDeleted }: ChatMainProps) => {
|
|
860
|
+
// transport: createHttpChatTransport's answer; hostRefusalCodes: the host's numbers of its refusal roles
|
|
861
|
+
const policy = useChatPolicy({ transport, hostRefusalCodes })
|
|
862
|
+
// the screen's heading, which takes focus when the consent opens the main place
|
|
863
|
+
const headingRef = useRef<HTMLHeadingElement>(null)
|
|
864
|
+
// the open conversation's band of the operations that need no consent: stop and delete
|
|
865
|
+
const aside = conversationUid === null ? null : <ChatConsentConversation transport={policy.transport} hostRefusalCodes={hostRefusalCodes} conversationUid={conversationUid} onChanged={onChanged} onDeleted={onDeleted} headingLevel={2} testId="chat-consent-conversation" />
|
|
866
|
+
return (
|
|
867
|
+
<ChatPolicyGate policy={policy} focusAfterConsent={headingRef} aside={aside} headingLevel={2} testId="chat-policy">
|
|
868
|
+
{/* every other part takes policy.transport, so a refusal that asks for consent reads the policy again */}
|
|
869
|
+
{() => <ChatTalk transport={policy.transport} headingRef={headingRef} />}
|
|
870
|
+
</ChatPolicyGate>
|
|
871
|
+
)
|
|
872
|
+
}
|
|
873
|
+
```
|
|
874
|
+
|
|
875
|
+
`useChatPolicy` reads the tenant's usage policy (`getPolicy`) when it mounts, and again when it is shown while it holds none.
|
|
876
|
+
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).
|
|
877
|
+
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.
|
|
878
|
+
`consent()` sends the number of the current version shown (`consentPolicy`), one at a time and only while consent is needed.
|
|
879
|
+
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.
|
|
880
|
+
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`.
|
|
881
|
+
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.
|
|
882
|
+
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.
|
|
883
|
+
`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.
|
|
884
|
+
Hand it to every other part of the screen.
|
|
885
|
+
|
|
886
|
+
`ChatPolicyGate` draws its children once the person consented to the current version.
|
|
887
|
+
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.
|
|
888
|
+
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.
|
|
889
|
+
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`.
|
|
890
|
+
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.
|
|
891
|
+
What the host passes as `aside` is drawn before the consent screen and the paragraph of a tenant without a version.
|
|
892
|
+
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.
|
|
893
|
+
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.
|
|
894
|
+
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.
|
|
895
|
+
When the consent opens the children and its button leaves holding focus, focus moves to `focusAfterConsent`.
|
|
896
|
+
|
|
897
|
+
`ChatConsentConversation` is the open conversation's band while consent is needed, which the host passes as the gate's `aside`.
|
|
898
|
+
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.
|
|
899
|
+
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.
|
|
900
|
+
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.
|
|
901
|
+
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.
|
|
902
|
+
|
|
787
903
|
### Listing the conversations
|
|
788
904
|
|
|
789
905
|
```tsx
|
|
@@ -827,6 +943,43 @@ A section with a next cursor reads up to it in one request (`until`) and lays th
|
|
|
827
943
|
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.
|
|
828
944
|
The operations on a conversation belong to its heading.
|
|
829
945
|
|
|
946
|
+
### Operating an open conversation from its heading band
|
|
947
|
+
|
|
948
|
+
```tsx
|
|
949
|
+
import { ChatConversationHeading, ChatTalkHeading, useChatConversationActions, useChatConversationDeletedAnnouncer } from "@aiquants/chat/react"
|
|
950
|
+
|
|
951
|
+
const actions = useChatConversationActions({
|
|
952
|
+
transport,
|
|
953
|
+
window,
|
|
954
|
+
hostRefusalCodes,
|
|
955
|
+
onChanged: () => {
|
|
956
|
+
list.pinned.reload()
|
|
957
|
+
list.recent.reload()
|
|
958
|
+
},
|
|
959
|
+
onDeleted: (conversation) => {
|
|
960
|
+
deletedRef.current = conversation
|
|
961
|
+
navigate(basePath, { replace: true })
|
|
962
|
+
},
|
|
963
|
+
})
|
|
964
|
+
// Once the new conversation's composer has taken focus:
|
|
965
|
+
const announceDeleted = useChatConversationDeletedAnnouncer()
|
|
966
|
+
announceDeleted(deletedRef.current)
|
|
967
|
+
|
|
968
|
+
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" />}
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
`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.
|
|
972
|
+
`useChatConversationActions` runs the operations one at a time; while one runs, the band's other controls cannot be pressed and say why.
|
|
973
|
+
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).
|
|
974
|
+
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).
|
|
975
|
+
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.
|
|
976
|
+
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.
|
|
977
|
+
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).
|
|
978
|
+
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.
|
|
979
|
+
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.
|
|
980
|
+
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.
|
|
981
|
+
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`).
|
|
982
|
+
|
|
830
983
|
### Checking an attachment before its upload
|
|
831
984
|
|
|
832
985
|
```ts
|
|
@@ -947,6 +1100,45 @@ A request no step is left for took no step and is not among `requests()`; one wh
|
|
|
947
1100
|
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.
|
|
948
1101
|
`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)).
|
|
949
1102
|
|
|
1103
|
+
### Drawing a run's stream without a server
|
|
1104
|
+
|
|
1105
|
+
```ts
|
|
1106
|
+
import { formatSseHeartbeatData, SSE_HEARTBEAT_EVENT, systemSseRuntime } from "@aiquants/sse"
|
|
1107
|
+
import { createChatScenarioRunStreams } from "@aiquants/chat/testing"
|
|
1108
|
+
|
|
1109
|
+
const scenario = createChatScenarioRunStreams({
|
|
1110
|
+
baseUrl: streams.baseUrl,
|
|
1111
|
+
cursorParam: streams.cursorParam,
|
|
1112
|
+
idBaseMs: 1763690000000,
|
|
1113
|
+
heartbeat: { event: SSE_HEARTBEAT_EVENT, data: formatSseHeartbeatData(1763690000000), everyMs: 15_000 },
|
|
1114
|
+
timers: systemSseRuntime,
|
|
1115
|
+
runs: {
|
|
1116
|
+
[runUid]: [
|
|
1117
|
+
{ kind: "event", afterMs: 0, event: "run.started", data: started },
|
|
1118
|
+
{ kind: "event", afterMs: 80, event: "step.started", data: { step: 1, kind: "llm" } },
|
|
1119
|
+
{ kind: "event", afterMs: 80, event: "text.delta", data: { step: 1, text: "## Monthly stock" } },
|
|
1120
|
+
{ kind: "gate", gate: "stop" },
|
|
1121
|
+
{ kind: "event", afterMs: 80, event: "usage", data: { step: 1, ...estimatedUsage } },
|
|
1122
|
+
{ kind: "event", afterMs: 80, event: "run.cancelled", data: { cancelled_by: "user", calls: [] } },
|
|
1123
|
+
],
|
|
1124
|
+
},
|
|
1125
|
+
})
|
|
1126
|
+
const scenarioStreams = { ...streams, reopen: { ...streams.reopen, createEventSource: scenario.createEventSource } }
|
|
1127
|
+
// The host's reads show the run running until its stream has carried its end.
|
|
1128
|
+
const running = scenario.endOf(runUid) === null
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
`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.
|
|
1132
|
+
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).
|
|
1133
|
+
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.
|
|
1134
|
+
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.
|
|
1135
|
+
Nothing follows a terminal event of the contract, `resync-required` included, not even the heartbeat.
|
|
1136
|
+
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.
|
|
1137
|
+
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.
|
|
1138
|
+
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`.
|
|
1139
|
+
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`.
|
|
1140
|
+
The entry imports no `@aiquants/sse`: the host hands the timers and the heartbeat's frame and composes the streams.
|
|
1141
|
+
|
|
950
1142
|
## Development
|
|
951
1143
|
|
|
952
1144
|
```bash
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as k,b as y}from"./chunk-
|
|
1
|
+
import{a as k,b as y}from"./chunk-5MWD2PSY.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};
|