@pyxis-llm/react 0.0.0-stage → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/dist/AgentProfileEditor.d.ts +48 -0
  2. package/dist/AgentProfileEditor.d.ts.map +1 -0
  3. package/dist/AgentProfileEditor.js +122 -0
  4. package/dist/AgentProfileList.d.ts +17 -0
  5. package/dist/AgentProfileList.d.ts.map +1 -0
  6. package/dist/AgentProfileList.js +46 -0
  7. package/dist/AskCardAnswerChip.d.ts +8 -0
  8. package/dist/AskCardAnswerChip.d.ts.map +1 -0
  9. package/dist/AskCardAnswerChip.js +21 -0
  10. package/dist/AskCardView.d.ts +85 -0
  11. package/dist/AskCardView.d.ts.map +1 -0
  12. package/dist/AskCardView.js +158 -0
  13. package/dist/CatalogColumnBrowser.d.ts +33 -0
  14. package/dist/CatalogColumnBrowser.d.ts.map +1 -0
  15. package/dist/CatalogColumnBrowser.js +219 -0
  16. package/dist/CatalogModelPicker.d.ts +68 -0
  17. package/dist/CatalogModelPicker.d.ts.map +1 -0
  18. package/dist/CatalogModelPicker.js +119 -0
  19. package/dist/CatalogModelPickerMenuContent.d.ts +17 -0
  20. package/dist/CatalogModelPickerMenuContent.d.ts.map +1 -0
  21. package/dist/CatalogModelPickerMenuContent.js +103 -0
  22. package/dist/CatalogPickerMenuItem.d.ts +17 -0
  23. package/dist/CatalogPickerMenuItem.d.ts.map +1 -0
  24. package/dist/CatalogPickerMenuItem.js +15 -0
  25. package/dist/CatalogTreePickerOptions.d.ts +52 -0
  26. package/dist/CatalogTreePickerOptions.d.ts.map +1 -0
  27. package/dist/CatalogTreePickerOptions.js +248 -0
  28. package/dist/ChatMessage.d.ts +172 -0
  29. package/dist/ChatMessage.d.ts.map +1 -0
  30. package/dist/ChatMessage.js +295 -0
  31. package/dist/ChatPanel.d.ts +252 -0
  32. package/dist/ChatPanel.d.ts.map +1 -0
  33. package/dist/ChatPanel.js +247 -0
  34. package/dist/ChatTranscriptFind.d.ts +19 -0
  35. package/dist/ChatTranscriptFind.d.ts.map +1 -0
  36. package/dist/ChatTranscriptFind.js +224 -0
  37. package/dist/ChatTranscriptFindBar.d.ts +15 -0
  38. package/dist/ChatTranscriptFindBar.d.ts.map +1 -0
  39. package/dist/ChatTranscriptFindBar.js +22 -0
  40. package/dist/Composer.d.ts +43 -0
  41. package/dist/Composer.d.ts.map +1 -0
  42. package/dist/Composer.js +45 -0
  43. package/dist/ComposerAttachments.d.ts +101 -0
  44. package/dist/ComposerAttachments.d.ts.map +1 -0
  45. package/dist/ComposerAttachments.js +126 -0
  46. package/dist/DisplayCards.d.ts +18 -0
  47. package/dist/DisplayCards.d.ts.map +1 -0
  48. package/dist/DisplayCards.js +72 -0
  49. package/dist/ErrorBoundary.d.ts +27 -0
  50. package/dist/ErrorBoundary.d.ts.map +1 -0
  51. package/dist/ErrorBoundary.js +107 -0
  52. package/dist/ImageDisplayCard.d.ts +6 -0
  53. package/dist/ImageDisplayCard.d.ts.map +1 -0
  54. package/dist/ImageDisplayCard.js +57 -0
  55. package/dist/MarkdownCodeComponents.d.ts +23 -0
  56. package/dist/MarkdownCodeComponents.d.ts.map +1 -0
  57. package/dist/MarkdownCodeComponents.js +256 -0
  58. package/dist/MermaidDiagram.d.ts +18 -0
  59. package/dist/MermaidDiagram.d.ts.map +1 -0
  60. package/dist/MermaidDiagram.js +66 -0
  61. package/dist/MessageContentWithPastes.d.ts +14 -0
  62. package/dist/MessageContentWithPastes.d.ts.map +1 -0
  63. package/dist/MessageContentWithPastes.js +44 -0
  64. package/dist/PastePill.d.ts +16 -0
  65. package/dist/PastePill.d.ts.map +1 -0
  66. package/dist/PastePill.js +43 -0
  67. package/dist/ProviderAuthTerminal.d.ts +12 -0
  68. package/dist/ProviderAuthTerminal.d.ts.map +1 -0
  69. package/dist/ProviderAuthTerminal.js +50 -0
  70. package/dist/ProviderConnectForm.d.ts +62 -0
  71. package/dist/ProviderConnectForm.d.ts.map +1 -0
  72. package/dist/ProviderConnectForm.js +206 -0
  73. package/dist/ProviderList.d.ts +18 -0
  74. package/dist/ProviderList.d.ts.map +1 -0
  75. package/dist/ProviderList.js +67 -0
  76. package/dist/QueueStrip.d.ts +17 -0
  77. package/dist/QueueStrip.d.ts.map +1 -0
  78. package/dist/QueueStrip.js +60 -0
  79. package/dist/SettingsScreen.d.ts +10 -0
  80. package/dist/SettingsScreen.d.ts.map +1 -0
  81. package/dist/SettingsScreen.js +26 -0
  82. package/dist/StreamingMarkdown.d.ts +47 -0
  83. package/dist/StreamingMarkdown.d.ts.map +1 -0
  84. package/dist/StreamingMarkdown.js +103 -0
  85. package/dist/TurnTimer.d.ts +72 -0
  86. package/dist/TurnTimer.d.ts.map +1 -0
  87. package/dist/TurnTimer.js +114 -0
  88. package/dist/VegaChart.d.ts +36 -0
  89. package/dist/VegaChart.d.ts.map +1 -0
  90. package/dist/VegaChart.js +180 -0
  91. package/dist/browser.d.ts +7 -0
  92. package/dist/browser.d.ts.map +1 -0
  93. package/dist/browser.js +18 -0
  94. package/dist/catalogColumnBrowserTree.d.ts +9 -0
  95. package/dist/catalogColumnBrowserTree.d.ts.map +1 -0
  96. package/dist/catalogColumnBrowserTree.js +48 -0
  97. package/dist/catalogPickerMenuStyles.d.ts +81 -0
  98. package/dist/catalogPickerMenuStyles.d.ts.map +1 -0
  99. package/dist/catalogPickerMenuStyles.js +130 -0
  100. package/dist/charts.d.ts +12 -0
  101. package/dist/charts.d.ts.map +1 -0
  102. package/dist/charts.js +45 -0
  103. package/dist/chatMessageScroll.d.ts +40 -0
  104. package/dist/chatMessageScroll.d.ts.map +1 -0
  105. package/dist/chatMessageScroll.js +62 -0
  106. package/dist/chatModelOptions.d.ts +28 -0
  107. package/dist/chatModelOptions.d.ts.map +1 -0
  108. package/dist/chatModelOptions.js +59 -0
  109. package/dist/chatTranscriptFindHighlights.d.ts +9 -0
  110. package/dist/chatTranscriptFindHighlights.d.ts.map +1 -0
  111. package/dist/chatTranscriptFindHighlights.js +88 -0
  112. package/dist/draftStore.d.ts +13 -0
  113. package/dist/draftStore.d.ts.map +1 -0
  114. package/dist/draftStore.js +38 -0
  115. package/dist/highlight.d.ts +4 -0
  116. package/dist/highlight.d.ts.map +1 -0
  117. package/dist/highlight.js +47 -0
  118. package/dist/index.d.ts +74 -0
  119. package/dist/index.d.ts.map +1 -0
  120. package/dist/index.js +48 -0
  121. package/dist/keyboardShortcuts.d.ts +5 -0
  122. package/dist/keyboardShortcuts.d.ts.map +1 -0
  123. package/dist/keyboardShortcuts.js +19 -0
  124. package/dist/markdownClipboard.d.ts +22 -0
  125. package/dist/markdownClipboard.d.ts.map +1 -0
  126. package/dist/markdownClipboard.js +98 -0
  127. package/dist/markdownPlugins.d.ts +31 -0
  128. package/dist/markdownPlugins.d.ts.map +1 -0
  129. package/dist/markdownPlugins.js +32 -0
  130. package/dist/mermaid.d.ts +17 -0
  131. package/dist/mermaid.d.ts.map +1 -0
  132. package/dist/mermaid.js +11 -0
  133. package/dist/mermaidRuntime.d.ts +21 -0
  134. package/dist/mermaidRuntime.d.ts.map +1 -0
  135. package/dist/mermaidRuntime.js +140 -0
  136. package/dist/modelCatalogHelpers.d.ts +14 -0
  137. package/dist/modelCatalogHelpers.d.ts.map +1 -0
  138. package/dist/modelCatalogHelpers.js +65 -0
  139. package/dist/modelCatalogSource.d.ts +22 -0
  140. package/dist/modelCatalogSource.d.ts.map +1 -0
  141. package/dist/modelCatalogSource.js +26 -0
  142. package/dist/modelCatalogTree.d.ts +24 -0
  143. package/dist/modelCatalogTree.d.ts.map +1 -0
  144. package/dist/modelCatalogTree.js +77 -0
  145. package/dist/node.d.ts +9 -0
  146. package/dist/node.d.ts.map +1 -0
  147. package/dist/node.js +13 -0
  148. package/dist/pasteFences.d.ts +20 -0
  149. package/dist/pasteFences.d.ts.map +1 -0
  150. package/dist/pasteFences.js +157 -0
  151. package/dist/pasteFormat.d.ts +5 -0
  152. package/dist/pasteFormat.d.ts.map +1 -0
  153. package/dist/pasteFormat.js +18 -0
  154. package/dist/plugins.d.ts +110 -0
  155. package/dist/plugins.d.ts.map +1 -0
  156. package/dist/plugins.js +98 -0
  157. package/dist/remarkAlerts.d.ts +12 -0
  158. package/dist/remarkAlerts.d.ts.map +1 -0
  159. package/dist/remarkAlerts.js +52 -0
  160. package/dist/sendMode.d.ts +69 -0
  161. package/dist/sendMode.d.ts.map +1 -0
  162. package/dist/sendMode.js +66 -0
  163. package/dist/useLlmdChatDriver.d.ts +367 -0
  164. package/dist/useLlmdChatDriver.d.ts.map +1 -0
  165. package/dist/useLlmdChatDriver.js +1739 -0
  166. package/dist/useLlmdModelCatalog.d.ts +23 -0
  167. package/dist/useLlmdModelCatalog.d.ts.map +1 -0
  168. package/dist/useLlmdModelCatalog.js +89 -0
  169. package/dist/useLlmdSessionModel.d.ts +34 -0
  170. package/dist/useLlmdSessionModel.d.ts.map +1 -0
  171. package/dist/useLlmdSessionModel.js +79 -0
  172. package/dist/useProviderAuthCommand.d.ts +26 -0
  173. package/dist/useProviderAuthCommand.d.ts.map +1 -0
  174. package/dist/useProviderAuthCommand.js +80 -0
  175. package/dist/vegaRuntime.d.ts +83 -0
  176. package/dist/vegaRuntime.d.ts.map +1 -0
  177. package/dist/vegaRuntime.js +314 -0
  178. package/dist/vendor/llmd-types/conversationEvents.d.ts +238 -0
  179. package/dist/vendor/llmd-types/conversationEvents.d.ts.map +1 -0
  180. package/dist/vendor/llmd-types/conversationEvents.js +98 -0
  181. package/dist/vendor/llmd-types/index.d.ts +4 -0
  182. package/dist/vendor/llmd-types/index.d.ts.map +1 -0
  183. package/dist/vendor/llmd-types/index.js +5 -0
  184. package/dist/vendor/llmd-types/messages.d.ts +67 -0
  185. package/dist/vendor/llmd-types/messages.d.ts.map +1 -0
  186. package/dist/vendor/llmd-types/messages.js +71 -0
  187. package/dist/vendor/llmd-types/sessionQueue.d.ts +54 -0
  188. package/dist/vendor/llmd-types/sessionQueue.d.ts.map +1 -0
  189. package/dist/vendor/llmd-types/sessionQueue.js +40 -0
  190. package/package.json +120 -4
  191. package/styles.css +389 -0
  192. package/README.md +0 -3
@@ -0,0 +1,1739 @@
1
+ /*
2
+ * Copyright 2026 John Ewart <john@johnewart.net>
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+ /**
6
+ * Drives a `ChatPanel` from any llmd client satisfying {@link ChatStreamCapableClient}
7
+ * — the reference implementation of the `messages`/`streaming`/`send`/`stop`
8
+ * contract `ChatPanel` expects. Transport-agnostic: it depends only on the
9
+ * message/event value types and the minimal `chatStreamEvents` shape, which
10
+ * `@pyxis-llm/client`'s `LlmdClient` satisfies on EITHER transport. This package's
11
+ * `./node` and `./browser` entry points both re-export this same hook under the
12
+ * name `useLlmdChatDriver`: it is the same hook over the same client type, and
13
+ * the transport is decided by which binding built the client.
14
+ *
15
+ * Usage (Node, native gRPC):
16
+ *
17
+ * import { createLlmdClient } from '@pyxis-llm/client/node';
18
+ * import { useLlmdChatDriver } from '@pyxis-llm/react/node';
19
+ * import { ChatPanel } from '@pyxis-llm/react';
20
+ *
21
+ * const client = useMemo(() => createLlmdClient({ address, tenantId, scopeId, sessionId }), [...]);
22
+ * const driver = useLlmdChatDriver(client);
23
+ * <ChatPanel messages={driver.messages} onSend={driver.send} streaming={driver.streaming}
24
+ * onStop={driver.stop} streamingMessageId={driver.streamingMessageId} />
25
+ *
26
+ * Usage (browser/fetch, grpc-web against llmd's token-guarded Connect listener):
27
+ *
28
+ * import { createLlmdWebClient } from '@pyxis-llm/client/web';
29
+ * import { useLlmdChatDriver } from '@pyxis-llm/react/browser';
30
+ * import { ChatPanel } from '@pyxis-llm/react';
31
+ *
32
+ * const client = useMemo(() => createLlmdWebClient({ baseUrl, tenantId, scopeId, sessionId, token }), [...]);
33
+ * const driver = useLlmdChatDriver(client);
34
+ * <ChatPanel messages={driver.messages} onSend={driver.send} streaming={driver.streaming}
35
+ * onStop={driver.stop} streamingMessageId={driver.streamingMessageId} />
36
+ *
37
+ * A host that can't import either client directly in the process rendering
38
+ * ChatPanel (typical Electron renderer with contextIsolation, a browser tab
39
+ * talking to a backend that itself proxies llmd) does not use this hook at
40
+ * all — it implements the same four-field shape itself, backed by
41
+ * IPC/WebSocket/REST to wherever a concrete client actually runs. `ChatPanel`
42
+ * never needs to know the difference.
43
+ *
44
+ * IMPORTANT — session history contract: llmd is the single source of truth
45
+ * for a persisted session's history. `ChatStream` ALWAYS prepends the
46
+ * session's persisted messages to whatever `messages` the client sends
47
+ * (`internal/server/server.go`'s `ChatStream`: `full := histMsgs ++
48
+ * incoming`) — every `ChatStream` call persists, unconditionally. So this
49
+ * driver sends ONLY the new user message each turn, never a client-side
50
+ * replay of prior turns; resending prior turns would double them up
51
+ * server-side (llmd has no dedup). This mirrors how a host app uses
52
+ * @pyxis-llm/client (see its `memoryChatHistoryStore`: "turn-scoped buffer,
53
+ * never pre-loaded with prior history... LLMD is the single source of
54
+ * truth"). `messages`/`setMessages`/`hydrate` below are purely about what
55
+ * THIS driver instance renders locally — never about what gets sent to
56
+ * llmd next turn.
57
+ *
58
+ * Turn lifetime: a turn runs on llmd independently of this client. Unmount,
59
+ * navigation or reload only DETACH — the model keeps going and the reply is
60
+ * persisted. On mount the driver asks llmd (`getSessionState`) whether a turn
61
+ * is still running; if so it shows a streaming bubble rebuilt live from the
62
+ * session-events subscription, and swaps in the persisted transcript once the
63
+ * turn commits. Only `stop()` / an interrupting `send()` end a turn, via
64
+ * `cancelTurn`.
65
+ *
66
+ * Mid-turn behavior:
67
+ * - `stop()` cancels the turn on llmd and detaches; the partial assistant bubble is
68
+ * finalized in place (whatever text streamed so far, plus
69
+ * `metadata.interrupted = true`) rather than left as a permanent empty
70
+ * placeholder or silently discarded.
71
+ * - `send()` while already streaming INTERRUPTS the current turn (same
72
+ * finalization as `stop()`) and immediately starts the new one — this is
73
+ * "type a correction and hit send" support, not a queue. A generation
74
+ * counter guards against the aborted turn's async cleanup clobbering the
75
+ * new turn's state once it (asynchronously) unwinds.
76
+ * - `<thinking>` deltas accumulate live into the streaming assistant
77
+ * message's `metadata.thinking` (not just after the turn completes),
78
+ * independent of the visible-text delta stream.
79
+ *
80
+ * Tool events (opt-in via `onToolEvent`):
81
+ * `ToolCallStreamStarted`/`ToolCallArgsDelta`/`ToolCallStreamFinished`/
82
+ * `ToolExecutionStarted`/`ToolExecutionFinished` are NOT accumulated into
83
+ * this driver's state or folded into `messages` — the intermediate
84
+ * tool-call turn still isn't persisted as its own message (see
85
+ * `toolInvocation.e2e.test.tsx`). Pass a third `onToolEvent` argument to
86
+ * receive them as they arrive; what to do with them (a "running
87
+ * tool-calls" list, a timeline, a toast) is entirely up to the host,
88
+ * since that rendering choice varies:
89
+ *
90
+ * const driver = useLlmdChatDriver(client, options, (ev) => {
91
+ * if (ev.type === ConversationEventType.ToolExecutionStarted) { ... }
92
+ * });
93
+ *
94
+ * Side-channel subscription (automatic when the client supports it):
95
+ * This channel carries EVERY frame of every turn on the session — text and
96
+ * thinking deltas, tool calls, turn started/finished/aborted, status, title,
97
+ * todos, queue — served from llmd's seq-ordered event log. It is what
98
+ * rebuilds a turn this driver rejoins after a reload. It is kept up for the
99
+ * component's lifetime and reconnects with backoff if it errors or is
100
+ * closed (e.g. by a proxy); `sessionEventsError` reports while it is down.
101
+ * `chatStreamEvents`' own stream only carries frames sourced from the
102
+ * specific turn it's driving. For CLI-backed providers (Claude Code,
103
+ * Cursor CLI), MCP-dispatched tool calls run in a separate request
104
+ * concurrent with that turn and never reach it (see
105
+ * internal/mcpserver/server.go's handleToolsCall /
106
+ * internal/serve/session_events_ws.go). If `client` also implements
107
+ * {@link SessionEventsSubscribableClient} (`LlmdClient` does on both
108
+ * transports — the SubscribeSessionEvents RPC on node, a WebSocket on web;
109
+ * see @pyxis-llm/client's web.ts for why that difference is deliberate), this hook
110
+ * opens that subscription itself, for the component's whole lifetime
111
+ * (not scoped to a single `send()` turn), and routes its events through
112
+ * the exact same handling as the primary stream: tool events to
113
+ * `onToolEvent`, session status/title/todos into this driver's own
114
+ * state. No extra wiring required — a host on `@pyxis-llm/client` gets live
115
+ * tool-execution visibility for CLI-backed sessions for free. A client that only implements
116
+ * {@link ChatStreamCapableClient} (e.g. a hand-rolled IPC/REST shim) just
117
+ * won't get this — `onToolEvent` still fires normally for whatever the
118
+ * primary stream itself carries.
119
+ */
120
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
121
+ import { ConversationEventType, UserMessage, } from './vendor/llmd-types/index.js';
122
+ import { createDraftStore } from './draftStore.js';
123
+ import { ASK_CARD_RESPONSE_KIND, buildAskCardResponseAttachment, decodeAskCard, encodeAskCardResponse, indexAskCardResponses, llmdMessageAttachmentFromRowContent, mergeLiveAttachments, } from '@pyxis-llm/core';
124
+ function supportsSessionEventsSubscription(client) {
125
+ return (typeof client === 'object' &&
126
+ client !== null &&
127
+ typeof client.subscribeSessionEvents === 'function');
128
+ }
129
+ function supportsTurnControl(client) {
130
+ return (typeof client === 'object' &&
131
+ client !== null &&
132
+ typeof client.cancelTurn === 'function');
133
+ }
134
+ function supportsSessionState(client) {
135
+ return (typeof client === 'object' &&
136
+ client !== null &&
137
+ typeof client.getSessionState === 'function');
138
+ }
139
+ function supportsSessionStatus(client) {
140
+ return (typeof client === 'object' &&
141
+ client !== null &&
142
+ typeof client.getSessionStatus === 'function');
143
+ }
144
+ function supportsSessionInfo(client) {
145
+ return (typeof client === 'object' &&
146
+ client !== null &&
147
+ typeof client.getSessionInfo === 'function');
148
+ }
149
+ function supportsSessionAttachments(client) {
150
+ return (typeof client === 'object' &&
151
+ client !== null &&
152
+ typeof client.getSessionAttachmentRows === 'function' &&
153
+ typeof client.upsertSessionAttachment === 'function');
154
+ }
155
+ function supportsAttachmentDelete(client) {
156
+ return (typeof client === 'object' &&
157
+ client !== null &&
158
+ typeof client.deleteSessionAttachment === 'function');
159
+ }
160
+ function supportsAnswerAskCard(client) {
161
+ return (typeof client === 'object' &&
162
+ client !== null &&
163
+ typeof client.answerAskCard === 'function');
164
+ }
165
+ function sessionIdentity(client) {
166
+ if (typeof client === 'object' &&
167
+ client !== null &&
168
+ typeof client.sessionKey === 'function') {
169
+ return client.sessionKey();
170
+ }
171
+ return client;
172
+ }
173
+ /** How often to re-check whether a rejoined turn has committed after its last frame. */
174
+ const REJOIN_SETTLE_POLL_MS = 300;
175
+ /** Give up waiting for a rejoined turn to commit after this many checks (~30s). */
176
+ const REJOIN_SETTLE_MAX_POLLS = 100;
177
+ /** While a rejoined turn is showing, check this often whether it has finished (safety net). */
178
+ const REJOIN_WATCH_MS = 3_000;
179
+ /** Session-events reconnect backoff: first retry delay, doubling up to the max. */
180
+ const SUBSCRIBE_RETRY_BASE_MS = 500;
181
+ const SUBSCRIBE_RETRY_MAX_MS = 10_000;
182
+ function supportsSessionQueue(client) {
183
+ return (typeof client === 'object' &&
184
+ client !== null &&
185
+ typeof client.enqueueMessage === 'function' &&
186
+ typeof client.saveDraft === 'function');
187
+ }
188
+ /** How long to wait after the last keystroke before persisting a draft. */
189
+ const DRAFT_SAVE_DEBOUNCE_MS = 400;
190
+ function pushSegmentDelta(segs, startNew, delta) {
191
+ const last = segs[segs.length - 1];
192
+ if (startNew || !last)
193
+ return [...segs, { text: delta }];
194
+ return [...segs.slice(0, -1), { ...last, text: last.text + delta }];
195
+ }
196
+ function noteSegmentTool(segs, id, name) {
197
+ const last = segs[segs.length - 1];
198
+ if (!last)
199
+ return segs;
200
+ return [...segs.slice(0, -1), { ...last, toolCalls: [...(last.toolCalls ?? []), { id, name }] }];
201
+ }
202
+ /**
203
+ * Merges each run of assistant/tool rows between other rows into one assistant
204
+ * message carrying `segments` (one per assistant text). Tool rows stay, ahead
205
+ * of the merged message. The merged row stands in for the dropped assistant
206
+ * rows (it keeps the last one's id); its content joins the segments with
207
+ * nothing between them, as the live path does. Runs with fewer than two text segments are unchanged.
208
+ */
209
+ function mergeSegmentedTurns(rows) {
210
+ const out = [];
211
+ let tools = [];
212
+ let assistants = [];
213
+ const flush = () => {
214
+ const segs = [];
215
+ for (const a of assistants) {
216
+ if (a.content.trim())
217
+ segs.push({ text: a.content, ...(a.toolCalls?.length ? { toolCalls: a.toolCalls } : {}) });
218
+ else if (a.toolCalls?.length && segs.length) {
219
+ const last = segs[segs.length - 1];
220
+ segs[segs.length - 1] = { ...last, toolCalls: [...(last.toolCalls ?? []), ...a.toolCalls] };
221
+ }
222
+ }
223
+ if (segs.length >= 2) {
224
+ const last = assistants[assistants.length - 1];
225
+ out.push(...tools, { ...last, content: segs.map((s) => s.text).join(''), segments: segs });
226
+ }
227
+ else {
228
+ // Not segmented: restore the original order.
229
+ out.push(...tools, ...assistants);
230
+ }
231
+ tools = [];
232
+ assistants = [];
233
+ };
234
+ for (const row of rows) {
235
+ if (row.role === 'assistant')
236
+ assistants.push(row);
237
+ else if (row.role === 'tool')
238
+ tools.push(row);
239
+ else {
240
+ flush();
241
+ out.push(row);
242
+ }
243
+ }
244
+ flush();
245
+ return out;
246
+ }
247
+ function supportsQueueDrain(client) {
248
+ const c = client;
249
+ return (typeof c === 'object' &&
250
+ c !== null &&
251
+ typeof c.claimNextQueuedMessage === 'function' &&
252
+ typeof c.heartbeatQueuedMessage === 'function' &&
253
+ typeof c.markQueuedMessageStarted === 'function' &&
254
+ typeof c.retireQueuedMessage === 'function' &&
255
+ typeof c.releaseQueuedMessage === 'function');
256
+ }
257
+ /** Client drainer heartbeat; well inside llmd's claim lease. */
258
+ const DRAIN_HEARTBEAT_MS = 5_000;
259
+ /** After an entry failed to start a turn, wait before claiming again (no hot loop). */
260
+ const DRAIN_RETRY_BACKOFF_MS = 3_000;
261
+ function randomId(prefix) {
262
+ return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
263
+ }
264
+ /**
265
+ * `finish_reason` values llmd stamps on an assistant turn that did NOT run to
266
+ * completion (a user abort, or a turn whose context died). Anything else — and
267
+ * the empty string — means the model finished on its own terms.
268
+ */
269
+ const CUT_SHORT_FINISH_REASONS = new Set(['cancelled', 'timed_out']);
270
+ function wasCutShort(m) {
271
+ if (m.role !== 'assistant')
272
+ return false;
273
+ // `finishReason` is declared on `AssistantMessage`, not on the base `Message`
274
+ // interface this function is handed (role-specific fields deliberately live on
275
+ // the concrete classes). Read it structurally rather than widening the shared
276
+ // message shape for one consumer.
277
+ const reason = m.finishReason;
278
+ return !!reason && CUT_SHORT_FINISH_REASONS.has(reason);
279
+ }
280
+ /**
281
+ * Adds one model call's usage (an AssistantTurnFinished event) to the running
282
+ * total for a live reply bubble. That bubble shows the text of every model call
283
+ * in the turn, so its numbers are their sum; a reloaded transcript has one
284
+ * bubble per call, each with its own numbers.
285
+ */
286
+ function addTurnUsage(total, ev) {
287
+ if (!ev.usage && ev.modelDurationMs === undefined)
288
+ return total;
289
+ const t = total ?? { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
290
+ const u = ev.usage ?? {};
291
+ const sum = (a, b) => a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);
292
+ const reasoningTokens = sum(t.reasoningTokens, u.reasoningTokens);
293
+ const modelDurationMs = sum(t.modelDurationMs, ev.modelDurationMs);
294
+ return {
295
+ inputTokens: t.inputTokens + (u.inputTokens ?? 0),
296
+ outputTokens: t.outputTokens + (u.outputTokens ?? 0),
297
+ cacheReadTokens: t.cacheReadTokens + (u.cacheReadTokens ?? 0),
298
+ cacheWriteTokens: t.cacheWriteTokens + (u.cacheWriteTokens ?? 0),
299
+ ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),
300
+ ...(modelDurationMs !== undefined ? { modelDurationMs } : {}),
301
+ };
302
+ }
303
+ function toChatMessageData(m) {
304
+ // A reply llmd recorded as cut short has to render as interrupted after a
305
+ // reload too, not as an answer the model completed. The live interrupt path
306
+ // sets `metadata.interrupted` itself, but a rehydrated transcript has only
307
+ // what was persisted, and `finish_reason` is the durable trace of it.
308
+ const metadata = wasCutShort(m) ? { ...(m.metadata ?? {}), interrupted: true } : m.metadata;
309
+ // Tool-call identity is kept (not rendered): it is how a card a tool
310
+ // produced (an image, a chart) finds its place right after that tool's
311
+ // result in a reloaded transcript. Read structurally: role-specific fields
312
+ // live on the concrete message classes, not the base Message.
313
+ const { toolCallId, toolCalls } = m;
314
+ return {
315
+ role: m.role,
316
+ content: m.content,
317
+ id: m.id,
318
+ metadata,
319
+ ...(m.role === 'tool' && toolCallId ? { toolCallId } : {}),
320
+ ...(m.role === 'assistant' && toolCalls?.length
321
+ ? { toolCalls: toolCalls.map((tc) => ({ id: tc.id, name: tc.name })) }
322
+ : {}),
323
+ };
324
+ }
325
+ /**
326
+ * Turns any {@link ChatStreamCapableClient} into the driver shape `ChatPanel`
327
+ * consumes. `client` may be `null`/`undefined` while a host is still setting
328
+ * up its connection — `send` is a no-op until it's provided.
329
+ */
330
+ export function useLlmdChatDriver(client, options, onToolEvent,
331
+ /**
332
+ * Fires once per user turn (llmd's UserTurnCommitted: one per message sent,
333
+ * covering every model round and tool call that answers it) — for every
334
+ * turn on the session: ones this driver sent, and ones started in another
335
+ * window or by the queue. This is THE signal for per-turn host UI: a host
336
+ * must clear what it accumulates from `onToolEvent` (its tool log) here.
337
+ * (`sessionStatus` needs nothing from the host: llmd clears it itself.)
338
+ *
339
+ * Not AssistantTurnStarted: llmd emits that once per model call, so an
340
+ * agent loop produces several per user turn.
341
+ */
342
+ onTurnStart, config) {
343
+ const [messages, setMessagesState] = useState([]);
344
+ const [streaming, setStreamingState] = useState(false);
345
+ const [turnTiming, setTurnTiming] = useState({});
346
+ // Every streaming change goes through here so turnTiming moves in the SAME
347
+ // render: a provisional local start when a turn begins (the turn's
348
+ // UserTurnCommitted replaces it with llmd's timestamp), the duration frozen
349
+ // when it ends. Updating timing in an effect instead left one render with
350
+ // `streaming` flipped but the previous turn's timing, which a host that
351
+ // memoizes on `streaming` then kept indefinitely.
352
+ const setStreaming = useCallback((next) => {
353
+ setStreamingState(next);
354
+ setTurnTiming((prev) => {
355
+ const live = prev.startedAt !== undefined && prev.durationMs === undefined;
356
+ if (next)
357
+ return live ? prev : { startedAt: Date.now() };
358
+ return live ? { ...prev, durationMs: Math.max(0, Date.now() - prev.startedAt) } : prev;
359
+ });
360
+ }, []);
361
+ // Adopt the turn timing llmd reports with the session status. This is what
362
+ // makes a session opened (or returned to, or reloaded) show its running
363
+ // turn's real start and how long its last turn took, rather than only what
364
+ // this driver happened to watch. Call AFTER any setStreaming for the same
365
+ // status, so a turn that ended is already closed off locally.
366
+ const adoptServerTurnTiming = useCallback((st) => {
367
+ if (st.turnInProgress) {
368
+ const at = st.turnStartedAtMs;
369
+ if (at === undefined)
370
+ return;
371
+ setTurnTiming((prev) => prev.durationMs === undefined && prev.startedAt === at
372
+ ? prev
373
+ : { ...(prev.durationMs === undefined ? prev : {}), startedAt: at });
374
+ return;
375
+ }
376
+ const last = st.lastTurn;
377
+ if (!last)
378
+ return;
379
+ setTurnTiming((prev) => {
380
+ // A turn this driver is running (or just started) is newer than any
381
+ // status that says nothing is running: keep it.
382
+ if (prev.startedAt !== undefined && prev.durationMs === undefined)
383
+ return prev;
384
+ const durationMs = Math.max(0, last.endedAtMs - last.startedAtMs);
385
+ if (prev.startedAt === last.startedAtMs && prev.durationMs === durationMs)
386
+ return prev;
387
+ return {
388
+ ...(prev.startedAt === last.startedAtMs && prev.userMessageId ? { userMessageId: prev.userMessageId } : {}),
389
+ startedAt: last.startedAtMs,
390
+ durationMs,
391
+ };
392
+ });
393
+ }, []);
394
+ const [streamingMessageId, setStreamingMessageId] = useState();
395
+ const [error, setError] = useState(null);
396
+ const [sessionStatus, setSessionStatus] = useState();
397
+ const [sessionTitle, setSessionTitle] = useState();
398
+ const [todos, setTodos] = useState([]);
399
+ // Attachments as last loaded from llmd, plus changes seen live since that
400
+ // load (null = deleted). Kept apart so a reload can replace the snapshot and
401
+ // drop the overlay without racing events: the load is read after the
402
+ // subscription cursor is chosen, so anything newer is replayed on top.
403
+ const [loadedAttachments, setLoadedAttachments] = useState(() => new Map());
404
+ const [liveAttachments, setLiveAttachments] = useState(() => new Map());
405
+ const [attachmentsError, setAttachmentsError] = useState();
406
+ const [queue, setQueue] = useState([]);
407
+ // The exported index includes ask-card answers that are still QUEUED
408
+ // (AnswerAskCard), not only persisted ones, so a card reads as answered while
409
+ // its answer waits (e.g. in a paused queue, or across a reload) — for hosts
410
+ // that pass only `attachmentIndex` to ChatPanel as well as those that also
411
+ // pass `askCardResponses`. Removing the queued entry un-answers the card, by
412
+ // design. A persisted row with the same id wins once the answer is sent.
413
+ const attachmentIndex = useMemo(() => {
414
+ const persisted = mergeLiveAttachments(loadedAttachments, liveAttachments);
415
+ let merged;
416
+ for (const q of queue) {
417
+ for (const a of q.attachments ?? []) {
418
+ if (a.kind !== ASK_CARD_RESPONSE_KIND || persisted.has(a.id))
419
+ continue;
420
+ merged ??= new Map(persisted);
421
+ merged.set(a.id, a);
422
+ }
423
+ }
424
+ return merged ?? persisted;
425
+ }, [loadedAttachments, liveAttachments, queue]);
426
+ const attachmentIndexRef = useRef(attachmentIndex);
427
+ attachmentIndexRef.current = attachmentIndex;
428
+ const askCardResponses = useMemo(() => indexAskCardResponses(attachmentIndex.values()), [attachmentIndex]);
429
+ const [sessionEventsError, setSessionEventsError] = useState();
430
+ // One store per driver instance; see DraftStore for why this is not state.
431
+ const [draftStore] = useState(createDraftStore);
432
+ const setDraftState = draftStore.set;
433
+ const [queuePaused, setQueuePausedState] = useState(false);
434
+ // Pending debounced draft save, so typing does not mean one RPC per keystroke.
435
+ const draftSaveTimer = useRef(null);
436
+ // The save the pending timer will run, so a session switch can flush it to the
437
+ // session the text was typed in rather than drop it (or send it to the new one).
438
+ const pendingDraftSave = useRef(null);
439
+ const abortRef = useRef(null);
440
+ // Bumped on every send() call; lets a superseded (interrupted) turn's
441
+ // async cleanup detect it's stale and avoid clobbering the new turn's
442
+ // streaming/error state. Message-array updates targeting a specific id
443
+ // are safe regardless (see the interrupt-finalization in the catch block
444
+ // below) since they can't collide with a different turn's message id.
445
+ const generationRef = useRef(0);
446
+ // Set while this driver is showing a turn it did NOT start — one still running
447
+ // server-side when the driver mounted (the user navigated away mid-reply and
448
+ // came back), or one that STARTED while we watch without this driver sending
449
+ // it (`observed`: llmd running a queued message, another window's send). Its
450
+ // reply is rebuilt from the session-events subscription.
451
+ //
452
+ // An observed turn may begin before this driver has finished unwinding its
453
+ // own previous turn (the server drainer claims the next queued message the
454
+ // moment a turn ends), so unlike a mount-time rejoin it is not gated on
455
+ // abortRef: everything after its UserTurnCommitted on the side channel
456
+ // belongs to it, because llmd serializes a session's turns.
457
+ //
458
+ // `awaitingCommit`: the subscription was (re)opened at this turn's start, so
459
+ // its replay begins with the turn's OWN UserTurnCommitted — which must be
460
+ // absorbed, not mistaken for a new turn.
461
+ const rejoinRef = useRef(null);
462
+ const segmentedRef = useRef(false);
463
+ segmentedRef.current = config?.segmentedTurns === true;
464
+ const historyToChat = useCallback((ms) => {
465
+ const rows = ms.map(toChatMessageData);
466
+ return segmentedRef.current ? mergeSegmentedTurns(rows) : rows;
467
+ }, []);
468
+ const rejoinPlaceholder = (r) => ({
469
+ role: 'assistant',
470
+ content: r.text,
471
+ id: r.assistantId,
472
+ ...(r.segments?.length ? { segments: r.segments } : {}),
473
+ metadata: { streamingPlaceholder: true, ...(r.thinking ? { thinking: r.thinking } : {}) },
474
+ });
475
+ const setMessages = useCallback((next) => {
476
+ setMessagesState(next);
477
+ }, []);
478
+ // This driver's own in-flight turn (started by send()), until llmd has
479
+ // persisted it. History does not contain the turn until it commits, so a
480
+ // hydrate that lands mid-turn must carry the local user message and the live
481
+ // bubble over rather than wiping them.
482
+ const ownTurnRef = useRef(null);
483
+ // Messages this driver sent with queueIfBusy and is still waiting on llmd's
484
+ // run-or-queue answer for. If llmd runs one, the session-events channel may
485
+ // deliver its UserTurnCommitted before our own stream does; this is how that
486
+ // is recognised as ours rather than shown a second time as an observed turn.
487
+ const pendingOwnIdsRef = useRef(new Set());
488
+ // Which channel owns each tool call's events. Two channels can carry the
489
+ // same call: send()'s own stream and the session-events side channel (which
490
+ // replays llmd's event log). Each call is owned by whichever delivers it
491
+ // FIRST, and only the owner forwards it to onToolEvent — so every event
492
+ // fires once, and a call's events never mix channels (args deltas have no
493
+ // unique key; interleaving two copies would garble the arguments).
494
+ // In practice: your own turn's in-band tools are owned by the primary stream
495
+ // (llmd sends each frame there before logging it), so they stay in order with
496
+ // the reply text; MCP-dispatched tools, rejoined turns and other windows'
497
+ // turns only exist on the side channel, which owns them.
498
+ const toolCallOwnerRef = useRef(new Map());
499
+ const claimToolCall = useCallback((ev, channel) => {
500
+ const id = 'toolCallId' in ev ? ev.toolCallId : 'id' in ev ? ev.id : '';
501
+ if (!id)
502
+ return channel === 'primary';
503
+ const owners = toolCallOwnerRef.current;
504
+ const owner = owners.get(id);
505
+ if (owner)
506
+ return owner === channel;
507
+ if (owners.size > 2_000)
508
+ owners.clear(); // bounded; ids are per call and never reused
509
+ owners.set(id, channel);
510
+ return true;
511
+ }, []);
512
+ // The single turn-start path, driven by UserTurnCommitted. Both channels
513
+ // deliver it for this driver's own turns, so it is deduped by user message
514
+ // id: each turn resets once.
515
+ const onTurnStartRef = useRef(onTurnStart);
516
+ onTurnStartRef.current = onTurnStart;
517
+ const lastTurnIdRef = useRef(undefined);
518
+ const beginTurn = useCallback((userMessageId, committedAtMs) => {
519
+ // Timing is recorded before the dedupe: a rejoin replays a turn this driver
520
+ // may already have begun, and its replayed commit carries the real start.
521
+ setTurnTiming((prev) => {
522
+ if (userMessageId && prev.userMessageId === userMessageId) {
523
+ return committedAtMs === undefined || prev.startedAt === committedAtMs
524
+ ? prev
525
+ : { ...prev, startedAt: committedAtMs };
526
+ }
527
+ return { userMessageId, startedAt: committedAtMs ?? Date.now() };
528
+ });
529
+ if (userMessageId && lastTurnIdRef.current === userMessageId)
530
+ return;
531
+ lastTurnIdRef.current = userMessageId;
532
+ onTurnStartRef.current?.(userMessageId);
533
+ }, []);
534
+ const hydrate = useCallback((seed) => {
535
+ // A host hydrates from history (typically on mount), and that can land
536
+ // while a turn is live — one this driver started, or one it rejoined. Neither
537
+ // is in history yet; keep both at the end instead of wiping them.
538
+ const base = historyToChat(seed);
539
+ setMessagesState((prev) => {
540
+ const tail = [];
541
+ const own = ownTurnRef.current;
542
+ if (own) {
543
+ // Between llmd persisting the turn and our stream delivering
544
+ // `complete`, history already holds it (user + assistant at the end):
545
+ // then history is authoritative and there is nothing to carry over.
546
+ // llmd persists the user message at turn START, and the reply at the
547
+ // end. So mid-turn, history already ends with our message (carry over
548
+ // only the live bubble); once committed it ends with message + reply
549
+ // (carry over nothing).
550
+ const n = base.length;
551
+ const last = base[n - 1];
552
+ const fullyPersisted = n >= 2 &&
553
+ last.role === 'assistant' &&
554
+ base[n - 2].role === 'user' &&
555
+ base[n - 2].content === own.user.content;
556
+ if (!fullyPersisted) {
557
+ const userPersisted = last?.role === 'user' && last.content === own.user.content;
558
+ const bubble = prev.find((m) => m.id === own.assistantId) ?? {
559
+ role: 'assistant',
560
+ content: '',
561
+ id: own.assistantId,
562
+ metadata: { streamingPlaceholder: true },
563
+ };
564
+ if (!userPersisted)
565
+ tail.push(own.user);
566
+ tail.push(bubble);
567
+ }
568
+ }
569
+ const r = rejoinRef.current;
570
+ if (r)
571
+ tail.push(rejoinPlaceholder(r));
572
+ return [...base, ...tail];
573
+ });
574
+ }, []);
575
+ // A new `client` is a different session (hosts build one client per session
576
+ // and may keep this hook mounted across a switch). Everything this driver holds
577
+ // is per-session, so it all starts over: the old session's transcript, title,
578
+ // status, todos, draft and queue must not show on the new one, and the old
579
+ // session's turn must stop writing into this state. Leaving is a DETACH, as on
580
+ // unmount — the old turn keeps running on llmd and is rejoined if the user
581
+ // comes back. A layout effect so the reset lands before paint and before any
582
+ // host effect hydrates the new session.
583
+ const sessionId = sessionIdentity(client);
584
+ // Session-scoped effects below key on `sessionId`, not `client`, and read the
585
+ // current client from here. A host that rebuilds an equivalent client object
586
+ // every render must not tear down and reopen the subscription (and re-fetch
587
+ // draft/queue, whose fresh state would re-render and loop) each time.
588
+ const clientRef = useRef(client);
589
+ clientRef.current = client;
590
+ const sessionIdRef = useRef(sessionId);
591
+ useLayoutEffect(() => {
592
+ if (sessionIdRef.current === sessionId)
593
+ return;
594
+ sessionIdRef.current = sessionId;
595
+ generationRef.current++;
596
+ abortRef.current?.abort();
597
+ abortRef.current = null;
598
+ ownTurnRef.current = null;
599
+ rejoinRef.current = null;
600
+ toolCallOwnerRef.current.clear();
601
+ lastTurnIdRef.current = undefined;
602
+ if (draftSaveTimer.current) {
603
+ clearTimeout(draftSaveTimer.current);
604
+ draftSaveTimer.current = null;
605
+ pendingDraftSave.current?.();
606
+ }
607
+ pendingDraftSave.current = null;
608
+ setMessagesState([]);
609
+ setStreaming(false);
610
+ setTurnTiming({});
611
+ setStreamingMessageId(undefined);
612
+ setError(null);
613
+ setSessionStatus(undefined);
614
+ setSessionTitle(undefined);
615
+ setTodos([]);
616
+ setLoadedAttachments(new Map());
617
+ setLiveAttachments(new Map());
618
+ setAttachmentsError(undefined);
619
+ setSessionEventsError(undefined);
620
+ setDraftState('');
621
+ setQueue([]);
622
+ setQueuePausedState(false);
623
+ }, [sessionId]);
624
+ // Unmount (navigation, closing the panel) DETACHES from a running turn; it
625
+ // never stops it. Abort this driver's own stream so a gone component stops
626
+ // consuming the turn and firing onToolEvent/setState, and bump the
627
+ // generation so any frame already in flight is dropped. llmd keeps the turn
628
+ // running and persists it; a remounted driver rejoins it from session state.
629
+ useEffect(() => () => {
630
+ generationRef.current++;
631
+ abortRef.current?.abort();
632
+ abortRef.current = null;
633
+ }, []);
634
+ /** Fire the explicit server-side Stop; never throws (a failed cancel is logged). */
635
+ const cancelServerTurn = useCallback(async () => {
636
+ if (!supportsTurnControl(client))
637
+ return;
638
+ try {
639
+ await client.cancelTurn();
640
+ }
641
+ catch (err) {
642
+ // eslint-disable-next-line no-console
643
+ console.error('useLlmdChatDriver: cancelTurn failed — the turn may keep running server-side', err);
644
+ }
645
+ }, [client]);
646
+ const stop = useCallback(() => {
647
+ // Order matters only loosely: the cancel is what stops the model; the abort
648
+ // just detaches this client's stream (which alone would NOT stop the turn).
649
+ void cancelServerTurn();
650
+ abortRef.current?.abort();
651
+ }, [cancelServerTurn]);
652
+ // --- draft + queue -------------------------------------------------------
653
+ /** Reads the queue back from llmd. Used on mount and after local edits. */
654
+ const refreshQueue = useCallback(async () => {
655
+ if (!supportsSessionQueue(client))
656
+ return;
657
+ try {
658
+ const snapshot = await client.listQueue();
659
+ setQueue(snapshot.queue);
660
+ setQueuePausedState(snapshot.paused);
661
+ }
662
+ catch (err) {
663
+ // Non-fatal: the queue is supplementary state, and a failure here must not
664
+ // take down the chat surface. It is logged rather than swallowed so a
665
+ // missing queue is diagnosable.
666
+ // eslint-disable-next-line no-console
667
+ console.error('useLlmdChatDriver: listQueue failed', err);
668
+ }
669
+ }, [client]);
670
+ const refreshQueueRef = useRef(refreshQueue);
671
+ refreshQueueRef.current = refreshQueue;
672
+ // Hydrate the persisted draft and queue once per session. The draft is only
673
+ // adopted while the composer is still untouched: a slow round trip must never
674
+ // overwrite something the user has started typing since mount.
675
+ useEffect(() => {
676
+ const client = clientRef.current;
677
+ const refreshQueue = refreshQueueRef.current;
678
+ if (!supportsSessionQueue(client))
679
+ return;
680
+ let cancelled = false;
681
+ void (async () => {
682
+ try {
683
+ const saved = await client.getDraft();
684
+ if (!cancelled && saved) {
685
+ setDraftState((current) => (current === '' ? saved : current));
686
+ }
687
+ }
688
+ catch (err) {
689
+ // eslint-disable-next-line no-console
690
+ console.error('useLlmdChatDriver: getDraft failed', err);
691
+ }
692
+ if (!cancelled)
693
+ await refreshQueue();
694
+ })();
695
+ return () => {
696
+ cancelled = true;
697
+ };
698
+ }, [sessionId]);
699
+ const setDraft = useCallback((text) => {
700
+ setDraftState(text);
701
+ if (!supportsSessionQueue(client))
702
+ return;
703
+ if (draftSaveTimer.current)
704
+ clearTimeout(draftSaveTimer.current);
705
+ const save = () => {
706
+ void client.saveDraft(text).catch((err) => {
707
+ // eslint-disable-next-line no-console
708
+ console.error('useLlmdChatDriver: saveDraft failed', err);
709
+ });
710
+ };
711
+ pendingDraftSave.current = save;
712
+ draftSaveTimer.current = setTimeout(() => {
713
+ draftSaveTimer.current = null;
714
+ pendingDraftSave.current = null;
715
+ save();
716
+ }, DRAFT_SAVE_DEBOUNCE_MS);
717
+ }, [client]);
718
+ /**
719
+ * Drops the draft, locally and on the server. Called when the text has become
720
+ * a real message (sent or queued): a draft that outlived its own send would
721
+ * reappear in the composer next to the message it turned into.
722
+ */
723
+ const discardDraft = useCallback(() => {
724
+ if (draftSaveTimer.current) {
725
+ clearTimeout(draftSaveTimer.current);
726
+ draftSaveTimer.current = null;
727
+ }
728
+ pendingDraftSave.current = null;
729
+ setDraftState('');
730
+ if (!supportsSessionQueue(client))
731
+ return;
732
+ void client.clearDraft().catch((err) => {
733
+ // eslint-disable-next-line no-console
734
+ console.error('useLlmdChatDriver: clearDraft failed', err);
735
+ });
736
+ }, [client]);
737
+ // On unmount (leaving the tab, closing the panel) FLUSH any in-flight debounce
738
+ // instead of dropping it: the last keystrokes before leaving are exactly the
739
+ // ones a remount must restore. The save is issued now, against the client it
740
+ // was typed for, and the timer is cleared so it never fires afterwards.
741
+ useEffect(() => () => {
742
+ if (draftSaveTimer.current) {
743
+ clearTimeout(draftSaveTimer.current);
744
+ draftSaveTimer.current = null;
745
+ pendingDraftSave.current?.();
746
+ }
747
+ pendingDraftSave.current = null;
748
+ }, []);
749
+ const enqueue = useCallback(async (text, attachments = []) => {
750
+ const trimmed = text.trim();
751
+ if ((!trimmed && attachments.length === 0) || !supportsSessionQueue(client))
752
+ return;
753
+ await client.enqueueMessage(trimmed, attachments);
754
+ discardDraft();
755
+ await refreshQueue();
756
+ }, [client, discardDraft, refreshQueue]);
757
+ const removeQueued = useCallback(async (entryId) => {
758
+ if (!supportsSessionQueue(client))
759
+ return;
760
+ await client.removeQueuedMessage(entryId);
761
+ await refreshQueue();
762
+ }, [client, refreshQueue]);
763
+ const reorderQueue = useCallback(async (entryIds) => {
764
+ if (!supportsSessionQueue(client))
765
+ return;
766
+ const next = await client.reorderQueue(entryIds);
767
+ setQueue(next);
768
+ }, [client]);
769
+ const setQueuePaused = useCallback(async (paused) => {
770
+ if (!supportsSessionQueue(client))
771
+ return;
772
+ // Optimistic: pausing is a deliberate act and the button should respond at
773
+ // once. The authoritative value arrives via the queue-changed event.
774
+ setQueuePausedState(paused);
775
+ try {
776
+ await client.setQueuePaused(paused);
777
+ }
778
+ catch (err) {
779
+ await refreshQueue();
780
+ throw err;
781
+ }
782
+ }, [client, refreshQueue]);
783
+ const interrupt = useCallback((text, attachments = [], hooks) => {
784
+ if (!client) {
785
+ hooks?.onDone?.();
786
+ return;
787
+ }
788
+ // Interrupting an in-flight turn: abort it now. Its own async
789
+ // cleanup (below) finalizes its assistant bubble once the abort
790
+ // propagates; we don't wait for that before starting the new turn.
791
+ // The abort only detaches our stream — the server-side Stop is the
792
+ // cancelTurn awaited at the top of the new turn below.
793
+ const interrupting = streaming;
794
+ if (streaming) {
795
+ abortRef.current?.abort();
796
+ }
797
+ // Interrupting a turn this driver rejoined (not one it started): finalize
798
+ // that bubble as interrupted; there is no local stream to unwind.
799
+ const rejoined = rejoinRef.current;
800
+ if (rejoined) {
801
+ rejoinRef.current = null;
802
+ setMessagesState((prev) => prev.map((m) => m.id === rejoined.assistantId
803
+ ? {
804
+ ...m,
805
+ content: rejoined.text,
806
+ metadata: { ...(rejoined.thinking ? { thinking: rejoined.thinking } : {}), interrupted: true },
807
+ }
808
+ : m));
809
+ }
810
+ // The text has become a real message, so it is no longer a draft. Done
811
+ // before the turn starts rather than after it finishes: the draft's job is
812
+ // to survive a crash, and a crash mid-turn should not restore text that was
813
+ // already sent.
814
+ discardDraft();
815
+ const generation = ++generationRef.current;
816
+ const userMessage = new UserMessage(text, hooks?.messageId ?? randomId('u'));
817
+ if (attachments.length > 0)
818
+ userMessage.attachments = attachments;
819
+ const assistantId = randomId('a');
820
+ const controller = new AbortController();
821
+ // Draw the turn: the user message, the live reply bubble, streaming on.
822
+ // Immediately for a plain send; for queueIfBusy only once llmd has said
823
+ // it is running this message now (its first frame that is not TurnQueued).
824
+ const deferred = hooks?.queueIfBusy === true;
825
+ let shown = false;
826
+ const showTurn = () => {
827
+ if (shown)
828
+ return;
829
+ shown = true;
830
+ if (attachments.length > 0) {
831
+ // llmd persists these anchored to this message and announces them to
832
+ // OTHER windows; this one shows them now (the echo, on reload, is the
833
+ // same rows).
834
+ setLiveAttachments((prev) => {
835
+ const next = new Map(prev);
836
+ for (const a of attachments) {
837
+ next.set(a.id, { ...a, anchorMessageId: userMessage.id });
838
+ }
839
+ return next;
840
+ });
841
+ }
842
+ setMessagesState((prev) => [...prev, toChatMessageData(userMessage)]);
843
+ ownTurnRef.current = { user: toChatMessageData(userMessage), assistantId };
844
+ setMessagesState((prev) => [
845
+ ...prev,
846
+ { role: 'assistant', content: '', id: assistantId, metadata: { streamingPlaceholder: true } },
847
+ ]);
848
+ setStreaming(true);
849
+ setStreamingMessageId(assistantId);
850
+ setError(null);
851
+ abortRef.current = controller;
852
+ };
853
+ if (deferred) {
854
+ pendingOwnIdsRef.current.add(userMessage.id);
855
+ }
856
+ else {
857
+ showTurn();
858
+ }
859
+ void (async () => {
860
+ let liveText = '';
861
+ let liveSegments = [];
862
+ let liveSegBreak = false;
863
+ const segmented = config?.segmentedTurns === true;
864
+ let liveThinking = '';
865
+ // Sum of this turn's model calls (see addTurnUsage), kept on the bubble.
866
+ let liveUsage;
867
+ let turnStartedReported = false;
868
+ // Stop the interrupted turn server-side BEFORE opening the new one. It
869
+ // must be awaited: llmd queues the new turn behind the running one, and
870
+ // a cancel that raced past it could land on the NEW turn instead.
871
+ if (interrupting) {
872
+ await cancelServerTurn();
873
+ }
874
+ try {
875
+ // Only the new message — llmd prepends persisted session history
876
+ // server-side (see module doc). Resending prior turns would
877
+ // double them up.
878
+ for await (const item of client.chatStreamEvents([userMessage], {
879
+ ...options,
880
+ ...(deferred ? { queueIfBusy: true } : {}),
881
+ signal: controller.signal,
882
+ })) {
883
+ if (generationRef.current !== generation)
884
+ return;
885
+ if (!shown) {
886
+ if (item.kind === 'event' && item.event.type === ConversationEventType.TurnQueued) {
887
+ // llmd queued it: no turn here. The queue snapshot also
888
+ // arrives over the session-events channel; read it now too so
889
+ // the entry shows without waiting on that.
890
+ void refreshQueueRef.current();
891
+ return;
892
+ }
893
+ showTurn();
894
+ }
895
+ if (item.kind === 'event' && item.event.type === ConversationEventType.AssistantTurnStarted) {
896
+ if (!turnStartedReported && item.event.turnId) {
897
+ turnStartedReported = true;
898
+ hooks?.onTurnStarted?.(item.event.turnId);
899
+ }
900
+ }
901
+ if (segmented &&
902
+ item.kind === 'event' &&
903
+ item.event.type === ConversationEventType.ToolExecutionStarted) {
904
+ const ev = item.event;
905
+ liveSegments = noteSegmentTool(liveSegments, ev.toolCallId, ev.name);
906
+ liveSegBreak = true;
907
+ }
908
+ if (item.kind === 'event' && item.event.type === ConversationEventType.AssistantTextDelta) {
909
+ liveText += item.event.delta;
910
+ const snapshot = liveText;
911
+ if (segmented) {
912
+ liveSegments = pushSegmentDelta(liveSegments, liveSegBreak, item.event.delta);
913
+ liveSegBreak = false;
914
+ }
915
+ const segSnapshot = liveSegments;
916
+ setMessagesState((prev) => prev.map((m) => m.id === assistantId
917
+ ? {
918
+ ...m,
919
+ content: snapshot,
920
+ ...(segmented ? { segments: segSnapshot } : {}),
921
+ metadata: {
922
+ ...(liveThinking ? { thinking: liveThinking } : {}),
923
+ ...(liveUsage ? { usage: liveUsage } : {}),
924
+ },
925
+ }
926
+ : m));
927
+ }
928
+ else if (item.kind === 'event' &&
929
+ item.event.type === ConversationEventType.AssistantThinkingDelta) {
930
+ liveThinking += item.event.delta;
931
+ const snapshot = liveThinking;
932
+ setMessagesState((prev) => prev.map((m) => m.id === assistantId ? { ...m, metadata: { ...m.metadata, thinking: snapshot } } : m));
933
+ }
934
+ else if (item.kind === 'event' && item.event.type === ConversationEventType.UserTurnCommitted) {
935
+ if (generationRef.current === generation)
936
+ beginTurn(item.event.userMessageId, item.event.committedAtMs);
937
+ }
938
+ else if (item.kind === 'event' && item.event.type === ConversationEventType.SessionStatus) {
939
+ if (generationRef.current === generation)
940
+ setSessionStatus(item.event.headline || undefined);
941
+ }
942
+ else if (item.kind === 'event' &&
943
+ item.event.type === ConversationEventType.SessionTitleChanged) {
944
+ if (generationRef.current === generation)
945
+ setSessionTitle(item.event.title);
946
+ }
947
+ else if (item.kind === 'event' && item.event.type === ConversationEventType.TodosUpdated) {
948
+ if (generationRef.current === generation)
949
+ setTodos(item.event.todos);
950
+ }
951
+ else if (item.kind === 'event' &&
952
+ (item.event.type === ConversationEventType.ToolCallStreamStarted ||
953
+ item.event.type === ConversationEventType.ToolCallArgsDelta ||
954
+ item.event.type === ConversationEventType.ToolCallStreamFinished ||
955
+ item.event.type === ConversationEventType.ToolExecutionStarted ||
956
+ item.event.type === ConversationEventType.ToolExecutionFinished)) {
957
+ // The side channel carries these same frames too; whichever
958
+ // channel saw this tool call first owns it (see claimToolCall).
959
+ if (generationRef.current === generation &&
960
+ claimToolCall(item.event, 'primary')) {
961
+ onToolEvent?.(item.event);
962
+ }
963
+ }
964
+ else if (item.kind === 'event' &&
965
+ item.event.type === ConversationEventType.AssistantTurnFinished) {
966
+ liveUsage = addTurnUsage(liveUsage, item.event);
967
+ const snapshot = liveUsage;
968
+ if (snapshot) {
969
+ setMessagesState((prev) => prev.map((m) => m.id === assistantId ? { ...m, metadata: { ...m.metadata, usage: snapshot } } : m));
970
+ }
971
+ }
972
+ else if (item.kind === 'complete') {
973
+ const finalUsage = liveUsage;
974
+ setMessagesState((prev) => prev.map((m) => {
975
+ if (m.id !== assistantId)
976
+ return m;
977
+ const done = toChatMessageData(item.message);
978
+ return {
979
+ ...done,
980
+ id: assistantId,
981
+ ...(segmented && liveSegments.length >= 2 ? { segments: liveSegments } : {}),
982
+ ...(finalUsage ? { metadata: { ...done.metadata, usage: finalUsage } } : {}),
983
+ };
984
+ }));
985
+ }
986
+ }
987
+ }
988
+ catch (err) {
989
+ const aborted = controller.signal.aborted;
990
+ if (generationRef.current === generation && !aborted) {
991
+ setError(err instanceof Error ? err : new Error(String(err)));
992
+ }
993
+ if (aborted) {
994
+ // Finalize THIS turn's bubble regardless of whether a newer
995
+ // turn has since started — leaving a permanently empty
996
+ // "streaming" placeholder after an interrupt/stop is a bug,
997
+ // not a feature.
998
+ setMessagesState((prev) => prev.map((m) => m.id === assistantId
999
+ ? {
1000
+ ...m,
1001
+ content: liveText,
1002
+ ...(segmented && liveSegments.length ? { segments: liveSegments } : {}),
1003
+ metadata: {
1004
+ ...(liveThinking ? { thinking: liveThinking } : {}),
1005
+ ...(liveUsage ? { usage: liveUsage } : {}),
1006
+ interrupted: true,
1007
+ },
1008
+ }
1009
+ : m));
1010
+ }
1011
+ }
1012
+ finally {
1013
+ pendingOwnIdsRef.current.delete(userMessage.id);
1014
+ // Only a turn this call actually drew is ended here. A queued send
1015
+ // drew nothing, and by now another turn (llmd draining the queue) may
1016
+ // be on screen; it is not ours to stop.
1017
+ //
1018
+ // That includes a turn this one drew: llmd starts the next queued
1019
+ // message the moment this turn ends, and the side channel can deliver
1020
+ // its UserTurnCommitted (observed turn: streaming on, new bubble)
1021
+ // BEFORE this stream finishes closing. An observed turn does not bump
1022
+ // the generation, so the generation check alone would switch
1023
+ // streaming off under it - the queued turn then ran with no live
1024
+ // state (no tool strip, "waiting") until the chat was reopened.
1025
+ const observedSince = rejoinRef.current?.observed === true;
1026
+ if (shown && generationRef.current === generation && !observedSince) {
1027
+ setStreaming(false);
1028
+ setStreamingMessageId(undefined);
1029
+ }
1030
+ if (abortRef.current === controller) {
1031
+ abortRef.current = null;
1032
+ }
1033
+ // The turn is over for this driver (completed, failed, or detached):
1034
+ // from here history, not local state, is the record of it.
1035
+ if (ownTurnRef.current?.assistantId === assistantId) {
1036
+ ownTurnRef.current = null;
1037
+ }
1038
+ hooks?.onDone?.();
1039
+ }
1040
+ })();
1041
+ }, [client, streaming, options, onToolEvent, discardDraft, cancelServerTurn, claimToolCall, beginTurn]);
1042
+ const send = useCallback((text, requested, attachments = []) => {
1043
+ if (!client)
1044
+ return;
1045
+ // No explicit behavior: plain-Enter semantics (see sendMode) — queue,
1046
+ // or send now while the queue is paused.
1047
+ const behavior = requested ?? (queuePaused ? 'interrupt' : 'queue');
1048
+ if (behavior === 'interrupt' || !supportsSessionQueue(client)) {
1049
+ interrupt(text, attachments);
1050
+ return;
1051
+ }
1052
+ if (!streaming) {
1053
+ // Nothing is streaming HERE, but that is not the same as llmd being
1054
+ // idle: a queued message may be between being claimed and starting,
1055
+ // another window may be running a turn, or the queue may be paused.
1056
+ // llmd decides, atomically, whether this runs now or waits its turn.
1057
+ interrupt(text, attachments, { queueIfBusy: true });
1058
+ return;
1059
+ }
1060
+ // A turn is visibly running (`streaming` covers rejoined and observed
1061
+ // turns too), so this certainly waits: queue it directly.
1062
+ enqueue(text, attachments).catch((err) => {
1063
+ const e = err instanceof Error ? err : new Error(String(err));
1064
+ // eslint-disable-next-line no-console
1065
+ console.error('useLlmdChatDriver: enqueue failed', e);
1066
+ setError(e);
1067
+ });
1068
+ }, [client, streaming, queuePaused, interrupt, enqueue]);
1069
+ const interruptWithQueued = useCallback(async (entryId) => {
1070
+ if (!supportsSessionQueue(client))
1071
+ return;
1072
+ const entry = queue.find((q) => q.id === entryId);
1073
+ if (!entry || entry.state === 'running')
1074
+ return;
1075
+ // Remove BEFORE sending: if the drainer picked it up in the meantime the
1076
+ // removal fails and we must not send a second copy.
1077
+ const removed = await client.removeQueuedMessage(entryId);
1078
+ await refreshQueue();
1079
+ if (!removed)
1080
+ return;
1081
+ interrupt(entry.content, entry.attachments ?? []);
1082
+ }, [client, queue, refreshQueue, interrupt]);
1083
+ // Client-side queue drainer (opt-in, `config.drainQueue`). One entry at a
1084
+ // time, only while nothing is running and the queue is not paused; the
1085
+ // claim makes it safe next to llmd's own drainer and other windows.
1086
+ const drainQueueEnabled = config?.drainQueue === true;
1087
+ const drainOwnerRef = useRef(randomId('react-drainer'));
1088
+ const drainingRef = useRef(false);
1089
+ const [drainTick, setDrainTick] = useState(0);
1090
+ useEffect(() => {
1091
+ if (!drainQueueEnabled || !client || !supportsQueueDrain(client))
1092
+ return;
1093
+ if (streaming || queuePaused || drainingRef.current)
1094
+ return;
1095
+ if (!queue.some((q) => q.state === 'pending'))
1096
+ return;
1097
+ drainingRef.current = true;
1098
+ const drainer = client;
1099
+ const owner = drainOwnerRef.current;
1100
+ const finish = (backoff) => {
1101
+ const done = () => {
1102
+ drainingRef.current = false;
1103
+ void refreshQueueRef.current();
1104
+ setDrainTick((n) => n + 1);
1105
+ };
1106
+ if (backoff)
1107
+ setTimeout(done, DRAIN_RETRY_BACKOFF_MS);
1108
+ else
1109
+ done();
1110
+ };
1111
+ void (async () => {
1112
+ let entry;
1113
+ try {
1114
+ entry = (await drainer.claimNextQueuedMessage(owner)).entry;
1115
+ }
1116
+ catch (err) {
1117
+ // eslint-disable-next-line no-console
1118
+ console.error('useLlmdChatDriver: queue claim failed', err);
1119
+ finish(true);
1120
+ return;
1121
+ }
1122
+ if (!entry) {
1123
+ finish(false);
1124
+ return;
1125
+ }
1126
+ const claimed = entry;
1127
+ let started = false;
1128
+ const hb = setInterval(() => {
1129
+ drainer.heartbeatQueuedMessage(claimed.id, owner).catch((err) => {
1130
+ // eslint-disable-next-line no-console
1131
+ console.warn('useLlmdChatDriver: queue heartbeat failed', err);
1132
+ });
1133
+ }, DRAIN_HEARTBEAT_MS);
1134
+ interrupt(claimed.content, claimed.attachments ?? [], {
1135
+ messageId: `queued_${claimed.id}`,
1136
+ onTurnStarted: (turnId) => {
1137
+ started = true;
1138
+ drainer.markQueuedMessageStarted(claimed.id, owner, turnId).catch((err) => {
1139
+ // eslint-disable-next-line no-console
1140
+ console.warn('useLlmdChatDriver: queue markStarted failed', err);
1141
+ });
1142
+ },
1143
+ onDone: () => {
1144
+ clearInterval(hb);
1145
+ // Delivered → retire (never re-send). Never reached the model →
1146
+ // hand it back at its position, and back off before retrying.
1147
+ const settle = started
1148
+ ? drainer.retireQueuedMessage(claimed.id, owner)
1149
+ : drainer.releaseQueuedMessage(claimed.id, owner);
1150
+ settle
1151
+ .catch((err) => {
1152
+ // eslint-disable-next-line no-console
1153
+ console.warn('useLlmdChatDriver: queue retire/release failed', err);
1154
+ })
1155
+ .finally(() => finish(!started));
1156
+ },
1157
+ });
1158
+ })();
1159
+ }, [drainQueueEnabled, client, streaming, queuePaused, queue, interrupt, drainTick]);
1160
+ // Latest onToolEvent in a ref so the subscription effect below doesn't
1161
+ // need to restart (tearing down and reopening the live connection) just
1162
+ // because the host passed a new closure identity this render.
1163
+ const onToolEventRef = useRef(onToolEvent);
1164
+ onToolEventRef.current = onToolEvent;
1165
+ // Automatic side-channel subscription — see this module's doc comment
1166
+ // ("Side-channel subscription"). Opened once per session, for the
1167
+ // component's whole lifetime, independent of any particular send() turn's
1168
+ // generation counter: this is session-scoped, not turn-scoped.
1169
+ useEffect(() => {
1170
+ const client = clientRef.current;
1171
+ if (!client)
1172
+ return;
1173
+ if (!supportsSessionEventsSubscription(client)) {
1174
+ // Silent no-op here reads identically to "everything's fine, nothing
1175
+ // to report" from the outside — which is exactly the debugging trap
1176
+ // this line exists to close. If you're staring at zero network
1177
+ // requests to /ws/session-events (or its gRPC equivalent) and no
1178
+ // console output at all, THIS is why: `client` doesn't have a
1179
+ // `subscribeSessionEvents` method as far as this hook can see, so it
1180
+ // never even tries. Common causes: an older @pyxis-llm/client(-web) build
1181
+ // (check its package.json version), or `client` being a wrapped/
1182
+ // spread/proxied object that dropped the method (it lives on the
1183
+ // class prototype, so `{ ...client }` silently loses it).
1184
+ // eslint-disable-next-line no-console
1185
+ console.debug('useLlmdChatDriver: client does not implement subscribeSessionEvents — skipping automatic ' +
1186
+ 'session-events side channel (no live tool-execution/session-status updates for CLI-backed ' +
1187
+ 'sessions). typeof client.subscribeSessionEvents ===', typeof client.subscribeSessionEvents, client);
1188
+ return;
1189
+ }
1190
+ const controller = new AbortController();
1191
+ setSessionEventsError(undefined);
1192
+ const updateRejoinBubble = () => {
1193
+ const r = rejoinRef.current;
1194
+ if (!r)
1195
+ return;
1196
+ setMessagesState((prev) => prev.map((m) => (m.id === r.assistantId ? rejoinPlaceholder(r) : m)));
1197
+ };
1198
+ /** Sleep that ends early when the effect is torn down. */
1199
+ const sleep = (ms) => new Promise((resolve) => {
1200
+ const t = setTimeout(resolve, ms);
1201
+ controller.signal.addEventListener('abort', () => {
1202
+ clearTimeout(t);
1203
+ resolve();
1204
+ }, { once: true });
1205
+ });
1206
+ /**
1207
+ * If llmd reports the rejoined turn as finished, swap its live bubble for the
1208
+ * persisted transcript. Returns true once there is nothing left to wait for.
1209
+ */
1210
+ // An observed turn is not displaced by our own (see rejoinRef); a mount-time
1211
+ // rejoin yields to a turn this driver is running.
1212
+ const rejoinActive = () => {
1213
+ const r = rejoinRef.current;
1214
+ return !!r && (r.observed || !abortRef.current);
1215
+ };
1216
+ const finishRejoinIfDone = async () => {
1217
+ if (!rejoinActive() || !supportsSessionState(client))
1218
+ return true;
1219
+ if (supportsSessionStatus(client)) {
1220
+ // Cheap check first: only pull the transcript once the turn is done.
1221
+ const status = await client.getSessionStatus();
1222
+ if (controller.signal.aborted || !rejoinRef.current)
1223
+ return true;
1224
+ if (status.turnInProgress)
1225
+ return false;
1226
+ }
1227
+ const st = await client.getSessionState();
1228
+ if (controller.signal.aborted || !rejoinRef.current)
1229
+ return true; // torn down or superseded
1230
+ if (st.turnInProgress)
1231
+ return false;
1232
+ rejoinRef.current = null;
1233
+ setMessagesState(historyToChat(st.messages));
1234
+ setStreaming(false);
1235
+ setStreamingMessageId(undefined);
1236
+ adoptServerTurnTiming(st);
1237
+ return true;
1238
+ };
1239
+ // The rejoined turn's last frame arrives just BEFORE llmd commits it to
1240
+ // history, so after a terminal frame re-read state (quickly) until the turn
1241
+ // is no longer in progress.
1242
+ let settling = false;
1243
+ const settleRejoin = async () => {
1244
+ if (settling)
1245
+ return;
1246
+ settling = true;
1247
+ try {
1248
+ for (let i = 0; i < REJOIN_SETTLE_MAX_POLLS && !controller.signal.aborted; i++) {
1249
+ if (await finishRejoinIfDone())
1250
+ return;
1251
+ await sleep(REJOIN_SETTLE_POLL_MS);
1252
+ }
1253
+ }
1254
+ catch (err) {
1255
+ // eslint-disable-next-line no-console
1256
+ console.error('useLlmdChatDriver: failed to settle rejoined turn', err);
1257
+ }
1258
+ finally {
1259
+ settling = false;
1260
+ }
1261
+ };
1262
+ // Safety net: a rejoined turn must end even if its terminal frame never
1263
+ // reaches us (connection dropped and the turn finished in the gap, a proxy
1264
+ // swallowing frames, …). Without this, the spinner's only exit is a frame
1265
+ // over the very channel that may be broken.
1266
+ const rejoinWatch = setInterval(() => {
1267
+ if (!rejoinActive() || settling)
1268
+ return;
1269
+ finishRejoinIfDone().catch((err) => {
1270
+ // eslint-disable-next-line no-console
1271
+ console.error('useLlmdChatDriver: rejoin watch failed to read session state', err);
1272
+ });
1273
+ }, REJOIN_WATCH_MS);
1274
+ // The subscription is kept up for the component's whole lifetime: when it
1275
+ // errors OR simply ends (server restart, a proxy dropping an idle socket),
1276
+ // it is re-established with backoff. Each (re)connect re-reads session state
1277
+ // to choose its cursor, so nothing a rejoined turn needs is skipped.
1278
+ // The idle-session transcript is loaded once per session (this effect is keyed
1279
+ // on it), on the first connect. Reconnects don't reload: the subscription
1280
+ // resumes from its cursor and llmd replays what was missed.
1281
+ let historyLoaded = false;
1282
+ void (async () => {
1283
+ let failures = 0;
1284
+ while (!controller.signal.aborted) {
1285
+ try {
1286
+ // Pick the subscription cursor from session state: rejoin a running
1287
+ // turn from where it started, otherwise receive only what is new.
1288
+ // Subscribing from 0 would replay the session's whole event history
1289
+ // and re-fire every old tool/abort event.
1290
+ let afterSeq;
1291
+ if (supportsSessionState(client)) {
1292
+ // Status first (no transcript); the full state is only needed when the
1293
+ // displayed transcript must be replaced: starting a rejoin, or a
1294
+ // rejoined turn having finished while we were disconnected.
1295
+ let st = supportsSessionStatus(client)
1296
+ ? await client.getSessionStatus()
1297
+ : await client.getSessionState();
1298
+ if (controller.signal.aborted)
1299
+ return;
1300
+ const needsTranscript = (st.turnInProgress && !abortRef.current && !rejoinRef.current) ||
1301
+ (!!rejoinRef.current && !st.turnInProgress);
1302
+ if (needsTranscript && !st.messages) {
1303
+ st = await client.getSessionState();
1304
+ if (controller.signal.aborted)
1305
+ return;
1306
+ }
1307
+ const messages = st.messages ?? [];
1308
+ const r = rejoinRef.current;
1309
+ if (st.turnInProgress && !abortRef.current) {
1310
+ afterSeq = st.turnStartSeq;
1311
+ if (r) {
1312
+ // Reconnecting mid-rejoin: the stream replays the turn from its
1313
+ // start, so rebuild the bubble from scratch rather than append.
1314
+ r.text = '';
1315
+ r.thinking = '';
1316
+ r.segments = undefined;
1317
+ r.segBreak = false;
1318
+ r.awaitingCommit = true;
1319
+ updateRejoinBubble();
1320
+ }
1321
+ else {
1322
+ const nr = { assistantId: randomId('a'), text: '', thinking: '', awaitingCommit: true };
1323
+ rejoinRef.current = nr;
1324
+ // The transcript to show is exactly what llmd has right now
1325
+ // (which, mid-turn, ends with the message the user sent — it is
1326
+ // persisted at turn start) plus the live reply. Seeding it here
1327
+ // makes a session load complete on its own; a host's own later
1328
+ // hydrate() carries the live bubble over.
1329
+ setMessagesState([...historyToChat(messages), rejoinPlaceholder(nr)]);
1330
+ setStreaming(true);
1331
+ setStreamingMessageId(nr.assistantId);
1332
+ }
1333
+ }
1334
+ else {
1335
+ afterSeq = st.eventsSeq;
1336
+ if (r && !st.turnInProgress) {
1337
+ // The rejoined turn finished while we were disconnected.
1338
+ rejoinRef.current = null;
1339
+ setMessagesState(historyToChat(messages));
1340
+ setStreaming(false);
1341
+ setStreamingMessageId(undefined);
1342
+ }
1343
+ else if (!historyLoaded) {
1344
+ // Opening an idle session: show its transcript. Without this a
1345
+ // session with history rendered empty unless the host remembered
1346
+ // to call hydrate() itself (the rejoin path above already seeded
1347
+ // a busy session on its own). hydrate() keeps a turn this driver
1348
+ // started meanwhile, so a slow load cannot wipe a fresh send.
1349
+ const transcript = st.messages ?? (await client.getSessionState()).messages;
1350
+ if (controller.signal.aborted)
1351
+ return;
1352
+ hydrate(transcript);
1353
+ }
1354
+ }
1355
+ historyLoaded = true;
1356
+ adoptServerTurnTiming(st);
1357
+ }
1358
+ // Seed title + todos from the session row. Read AFTER the cursor was
1359
+ // chosen: any change past it is replayed by the subscription below, so
1360
+ // the two always converge on the latest value.
1361
+ if (supportsSessionInfo(client)) {
1362
+ try {
1363
+ const info = await client.getSessionInfo();
1364
+ if (controller.signal.aborted)
1365
+ return;
1366
+ setSessionTitle(info.title || undefined);
1367
+ setSessionStatus(info.status || undefined);
1368
+ // Keep the old array when nothing changed: a host that rebuilds its
1369
+ // client every render re-runs this effect each time, and a fresh
1370
+ // (equal) array would re-render and restart it forever.
1371
+ setTodos((prev) => (JSON.stringify(prev) === JSON.stringify(info.todos) ? prev : info.todos));
1372
+ }
1373
+ catch (err) {
1374
+ // Non-fatal: live updates still arrive; only the initial snapshot is missing.
1375
+ // eslint-disable-next-line no-console
1376
+ console.error('useLlmdChatDriver: getSessionInfo failed; title/todos show once next updated', err);
1377
+ }
1378
+ }
1379
+ // Seed attachments the same way (after the cursor), replacing the live
1380
+ // overlay: everything it held is in this snapshot, and anything newer
1381
+ // than the cursor is replayed by the subscription below.
1382
+ if (supportsSessionAttachments(client)) {
1383
+ try {
1384
+ const rows = await client.getSessionAttachmentRows();
1385
+ if (controller.signal.aborted)
1386
+ return;
1387
+ const loaded = new Map();
1388
+ for (const row of rows) {
1389
+ const attachment = llmdMessageAttachmentFromRowContent(row.content);
1390
+ if (attachment) {
1391
+ loaded.set(attachment.id, attachment);
1392
+ }
1393
+ else {
1394
+ // eslint-disable-next-line no-console
1395
+ console.warn('useLlmdChatDriver: skipping undecodable attachment row', row);
1396
+ }
1397
+ }
1398
+ setLoadedAttachments(loaded);
1399
+ setLiveAttachments(new Map());
1400
+ setAttachmentsError(undefined);
1401
+ }
1402
+ catch (err) {
1403
+ // Non-fatal: live updates still arrive; only previously asked cards are missing.
1404
+ const e = err instanceof Error ? err : new Error(String(err));
1405
+ // eslint-disable-next-line no-console
1406
+ console.error('useLlmdChatDriver: loading session attachments failed', e);
1407
+ setAttachmentsError(e);
1408
+ }
1409
+ }
1410
+ for await (const event of client.subscribeSessionEvents({ afterSeq, signal: controller.signal })) {
1411
+ failures = 0;
1412
+ setSessionEventsError(undefined); // a message got through: connection is (still) good
1413
+ // Rebuild a rejoined turn's reply. Only while rejoined and with no
1414
+ // turn of our own running: our own turn's frames also flow through
1415
+ // this channel and are already rendered by send().
1416
+ const r = rejoinRef.current;
1417
+ if (r && rejoinActive()) {
1418
+ if (segmentedRef.current && event.type === ConversationEventType.ToolExecutionStarted) {
1419
+ const ev = event;
1420
+ r.segments = noteSegmentTool(r.segments ?? [], ev.toolCallId, ev.name);
1421
+ r.segBreak = true;
1422
+ }
1423
+ if (event.type === ConversationEventType.AssistantTextDelta) {
1424
+ r.text += event.delta;
1425
+ if (segmentedRef.current) {
1426
+ r.segments = pushSegmentDelta(r.segments ?? [], r.segBreak === true, event.delta);
1427
+ r.segBreak = false;
1428
+ }
1429
+ updateRejoinBubble();
1430
+ continue;
1431
+ }
1432
+ if (event.type === ConversationEventType.AssistantThinkingDelta) {
1433
+ r.thinking += event.delta;
1434
+ updateRejoinBubble();
1435
+ continue;
1436
+ }
1437
+ if (event.type === ConversationEventType.AssistantTurnFinished ||
1438
+ event.type === ConversationEventType.AssistantTurnFailed ||
1439
+ event.type === ConversationEventType.ConversationAborted) {
1440
+ void settleRejoin();
1441
+ }
1442
+ }
1443
+ if (event.type === ConversationEventType.UserTurnCommitted) {
1444
+ // A turn this driver did not send (llmd draining the queue, another
1445
+ // window): show it like one we just sent — the user message plus a
1446
+ // live reply bubble that the deltas above fill in. Our own turns
1447
+ // are recognised by the message id send() minted (llmd echoes it),
1448
+ // checked BEFORE beginTurn records it.
1449
+ const id = event.userMessageId;
1450
+ const own = !!id &&
1451
+ (ownTurnRef.current?.user.id === id ||
1452
+ lastTurnIdRef.current === id ||
1453
+ pendingOwnIdsRef.current.has(id));
1454
+ const cur = rejoinRef.current;
1455
+ if (cur?.awaitingCommit) {
1456
+ // Replay of the rejoined turn's own start (see rejoinRef).
1457
+ cur.awaitingCommit = false;
1458
+ }
1459
+ else if (!own) {
1460
+ const prevTurn = rejoinRef.current;
1461
+ const nr = { assistantId: randomId('a'), text: '', thinking: '', observed: true };
1462
+ rejoinRef.current = nr;
1463
+ const userMsg = {
1464
+ role: 'user',
1465
+ content: event.textPreview ?? '',
1466
+ id: id || randomId('u'),
1467
+ };
1468
+ setMessagesState((prev) => {
1469
+ // A previous observed/rejoined turn that ended without settling
1470
+ // yet (the next queued message started immediately): keep what
1471
+ // it streamed as a finished reply. Settle swaps in the persisted
1472
+ // transcript later.
1473
+ const base = prevTurn
1474
+ ? prev.map((m) => m.id === prevTurn.assistantId
1475
+ ? {
1476
+ ...m,
1477
+ content: prevTurn.text,
1478
+ metadata: prevTurn.thinking ? { thinking: prevTurn.thinking } : {},
1479
+ }
1480
+ : m)
1481
+ : prev;
1482
+ if (base.some((m) => m.id === userMsg.id))
1483
+ return [...base, rejoinPlaceholder(nr)];
1484
+ return [...base, userMsg, rejoinPlaceholder(nr)];
1485
+ });
1486
+ setStreaming(true);
1487
+ setStreamingMessageId(nr.assistantId);
1488
+ }
1489
+ beginTurn(id, event.committedAtMs);
1490
+ }
1491
+ else if (event.type === ConversationEventType.ToolCallStreamStarted ||
1492
+ event.type === ConversationEventType.ToolCallArgsDelta ||
1493
+ event.type === ConversationEventType.ToolCallStreamFinished ||
1494
+ event.type === ConversationEventType.ToolExecutionStarted ||
1495
+ event.type === ConversationEventType.ToolExecutionFinished) {
1496
+ if (claimToolCall(event, 'side')) {
1497
+ onToolEventRef.current?.(event);
1498
+ }
1499
+ }
1500
+ else if (event.type === ConversationEventType.SessionStatus) {
1501
+ // An empty headline is llmd clearing it (turn start/end).
1502
+ setSessionStatus(event.headline || undefined);
1503
+ }
1504
+ else if (event.type === ConversationEventType.SessionTitleChanged) {
1505
+ setSessionTitle(event.title);
1506
+ }
1507
+ else if (event.type === ConversationEventType.TodosUpdated) {
1508
+ setTodos(event.todos);
1509
+ }
1510
+ else if (event.type === ConversationEventType.QueueChanged) {
1511
+ // Whole-queue snapshot, so this converges even if an earlier event was
1512
+ // missed — and it is how edits made in another window (or a claim by a
1513
+ // background drainer) reach this one.
1514
+ setQueue(event.queue);
1515
+ setQueuePausedState(event.paused);
1516
+ }
1517
+ else if (event.type === ConversationEventType.AttachmentUpserted) {
1518
+ const att = event.attachment;
1519
+ const anchor = event.messageId;
1520
+ // The turn it was made in, until a reload brings the one llmd
1521
+ // recorded (which mergeLiveAttachments prefers): what places a card
1522
+ // whose tool call is not in the transcript (CLI tools over MCP).
1523
+ const turnNow = lastTurnIdRef.current;
1524
+ setLiveAttachments((prev) => {
1525
+ const next = new Map(prev);
1526
+ const turnMessageId = prev.get(att.id)?.turnMessageId ?? turnNow;
1527
+ // Keep the anchor: it is what ties an attachment to its message
1528
+ // (e.g. an ask-card answer to its "Answer to: …" bubble).
1529
+ next.set(att.id, {
1530
+ ...att,
1531
+ ...(anchor ? { anchorMessageId: anchor } : {}),
1532
+ ...(turnMessageId ? { turnMessageId } : {}),
1533
+ });
1534
+ return next;
1535
+ });
1536
+ }
1537
+ else if (event.type === ConversationEventType.AttachmentDeleted) {
1538
+ const id = event.attachmentId;
1539
+ setLiveAttachments((prev) => {
1540
+ const next = new Map(prev);
1541
+ next.set(id, null);
1542
+ return next;
1543
+ });
1544
+ }
1545
+ else if (event.type === ConversationEventType.ConversationAborted) {
1546
+ // A turn on this session was cut short. This matters for observers
1547
+ // that did not do the cancelling — a second window on the same
1548
+ // session — which have no aborted AbortController to learn from and
1549
+ // would otherwise show a turn as in-flight forever. llmd emits this
1550
+ // only after the salvaged partial is committed, so the transcript is
1551
+ // already consistent by the time we clear the in-flight state.
1552
+ //
1553
+ // Only act when THIS driver has no turn of its own running. The
1554
+ // window that interrupted also receives this event, and by then its
1555
+ // replacement turn is already streaming: clearing state here would
1556
+ // clobber the new turn and flag its live bubble as interrupted —
1557
+ // the same hazard send()'s generation counter guards against. That
1558
+ // window's own abort handling has already finalized the old turn.
1559
+ if (!abortRef.current && !rejoinRef.current) {
1560
+ setStreaming(false);
1561
+ setStreamingMessageId(undefined);
1562
+ setMessagesState((prev) => prev.map((m) => {
1563
+ const meta = m.metadata;
1564
+ if (!meta?.streamingPlaceholder)
1565
+ return m;
1566
+ const { streamingPlaceholder: _dropped, ...rest } = meta;
1567
+ return { ...m, metadata: { ...rest, interrupted: true } };
1568
+ }));
1569
+ }
1570
+ }
1571
+ }
1572
+ // The stream ended without an error. Nothing on our side ended it, so
1573
+ // the server or something in between (a dev-server proxy) closed it.
1574
+ // That is not "done": the session is still live, so reconnect.
1575
+ if (controller.signal.aborted)
1576
+ return;
1577
+ const closed = new Error('session-events stream was closed by the server or a proxy; reconnecting');
1578
+ // eslint-disable-next-line no-console
1579
+ console.warn('useLlmdChatDriver:', closed.message);
1580
+ setSessionEventsError(closed);
1581
+ }
1582
+ catch (err) {
1583
+ // A subscription error must never surface as this driver's own
1584
+ // `error` (that's reserved for the primary chatStreamEvents turn's
1585
+ // failures) — but it must NOT be silent either: while it is down,
1586
+ // rejoined turns and tool/status updates from other sources go dark.
1587
+ // Log AND expose via sessionEventsError (cleared by the next frame
1588
+ // that gets through), then retry.
1589
+ if (controller.signal.aborted)
1590
+ return;
1591
+ const e = err instanceof Error ? err : new Error(String(err));
1592
+ // eslint-disable-next-line no-console
1593
+ console.error('useLlmdChatDriver: session-events subscription failed; reconnecting', e);
1594
+ setSessionEventsError(e);
1595
+ }
1596
+ failures++;
1597
+ await sleep(Math.min(SUBSCRIBE_RETRY_MAX_MS, SUBSCRIBE_RETRY_BASE_MS * 2 ** Math.min(failures - 1, 6)));
1598
+ }
1599
+ })();
1600
+ return () => {
1601
+ clearInterval(rejoinWatch);
1602
+ controller.abort();
1603
+ };
1604
+ }, [sessionId, claimToolCall, beginTurn, adoptServerTurnTiming]);
1605
+ const submitAskCard = useCallback(async (response, options) => {
1606
+ const c = clientRef.current;
1607
+ const cardAttachment = attachmentIndexRef.current.get(response.cardId);
1608
+ const card = cardAttachment ? decodeAskCard(cardAttachment.payloadJson) : undefined;
1609
+ if (!card || !cardAttachment) {
1610
+ const e = new Error(`submitAskCard: no ask card ${JSON.stringify(response.cardId)} on this session`);
1611
+ // eslint-disable-next-line no-console
1612
+ console.error('useLlmdChatDriver:', e);
1613
+ setAttachmentsError(e);
1614
+ throw e;
1615
+ }
1616
+ if (supportsAnswerAskCard(c)) {
1617
+ // llmd queues the answer at the front of the session queue (resuming the
1618
+ // agent) or updates an earlier answer in place. The card flips to
1619
+ // answered from the queue entry (see askCardResponses), then from the
1620
+ // persisted attachment once its turn runs.
1621
+ try {
1622
+ await c.answerAskCard(card.id, encodeAskCardResponse(response), {
1623
+ continueWithTools: options?.continueWithTools === true,
1624
+ });
1625
+ setAttachmentsError(undefined);
1626
+ }
1627
+ catch (err) {
1628
+ const e = err instanceof Error ? err : new Error(String(err));
1629
+ // eslint-disable-next-line no-console
1630
+ console.error('useLlmdChatDriver: answering ask card failed', e);
1631
+ setAttachmentsError(e);
1632
+ throw e;
1633
+ }
1634
+ await refreshQueue();
1635
+ return;
1636
+ }
1637
+ if (!supportsSessionAttachments(c)) {
1638
+ const e = new Error('submitAskCard: this llmd client cannot write session attachments');
1639
+ // eslint-disable-next-line no-console
1640
+ console.error('useLlmdChatDriver:', e);
1641
+ setAttachmentsError(e);
1642
+ throw e;
1643
+ }
1644
+ const answer = buildAskCardResponseAttachment(card, response);
1645
+ const hadLive = liveAttachments.has(answer.id);
1646
+ const previous = liveAttachments.get(answer.id);
1647
+ // Optimistic: show the answer now. llmd's attachment_upserted echo later
1648
+ // overwrites this entry with the same value.
1649
+ setLiveAttachments((prev) => new Map(prev).set(answer.id, answer));
1650
+ try {
1651
+ await c.upsertSessionAttachment(cardAttachment.anchorMessageId || cardAttachment.afterToolCallId || card.id, answer);
1652
+ setAttachmentsError(undefined);
1653
+ }
1654
+ catch (err) {
1655
+ const e = err instanceof Error ? err : new Error(String(err));
1656
+ // eslint-disable-next-line no-console
1657
+ console.error('useLlmdChatDriver: saving ask-card answer failed; rolled back', e);
1658
+ setLiveAttachments((prev) => {
1659
+ const next = new Map(prev);
1660
+ if (hadLive)
1661
+ next.set(answer.id, previous ?? null);
1662
+ else
1663
+ next.delete(answer.id);
1664
+ return next;
1665
+ });
1666
+ setAttachmentsError(e);
1667
+ throw e;
1668
+ }
1669
+ }, [liveAttachments, refreshQueue]);
1670
+ const dismissAskCard = useCallback(async (cardId) => {
1671
+ const id = cardId.trim();
1672
+ const c = clientRef.current;
1673
+ if (!supportsAttachmentDelete(c)) {
1674
+ const e = new Error('dismissAskCard: this llmd client cannot delete session attachments');
1675
+ // eslint-disable-next-line no-console
1676
+ console.error('useLlmdChatDriver:', e);
1677
+ setAttachmentsError(e);
1678
+ throw e;
1679
+ }
1680
+ // Optimistic: hide it now. A `null` live entry removes it from
1681
+ // attachmentIndex (mergeLiveAttachments), which is what renders it.
1682
+ let hadLive = false;
1683
+ let previous;
1684
+ setLiveAttachments((prev) => {
1685
+ hadLive = prev.has(id);
1686
+ previous = prev.get(id);
1687
+ return new Map(prev).set(id, null);
1688
+ });
1689
+ try {
1690
+ await c.deleteSessionAttachment(id);
1691
+ setAttachmentsError(undefined);
1692
+ }
1693
+ catch (err) {
1694
+ const e = err instanceof Error ? err : new Error(String(err));
1695
+ // eslint-disable-next-line no-console
1696
+ console.error('useLlmdChatDriver: dismissing ask card failed; restored', e);
1697
+ setLiveAttachments((prev) => {
1698
+ const next = new Map(prev);
1699
+ if (hadLive)
1700
+ next.set(id, previous ?? null);
1701
+ else
1702
+ next.delete(id);
1703
+ return next;
1704
+ });
1705
+ setAttachmentsError(e);
1706
+ throw e;
1707
+ }
1708
+ }, []);
1709
+ return {
1710
+ attachmentIndex,
1711
+ askCardResponses,
1712
+ submitAskCard,
1713
+ dismissAskCard,
1714
+ attachmentsError,
1715
+ draft: draftStore,
1716
+ setDraft,
1717
+ queue,
1718
+ queuePaused,
1719
+ enqueue,
1720
+ removeQueued,
1721
+ reorderQueue,
1722
+ setQueuePaused,
1723
+ messages,
1724
+ streaming,
1725
+ turnTiming,
1726
+ streamingMessageId,
1727
+ send,
1728
+ interrupt,
1729
+ interruptWithQueued,
1730
+ stop,
1731
+ setMessages,
1732
+ hydrate,
1733
+ error,
1734
+ sessionStatus,
1735
+ sessionTitle,
1736
+ todos,
1737
+ sessionEventsError,
1738
+ };
1739
+ }