@schlessera/brain-ui-react 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +70 -0
  3. package/dist/components/chat/ask-user-card.d.ts +12 -0
  4. package/dist/components/chat/ask-user-card.d.ts.map +1 -0
  5. package/dist/components/chat/ask-user-card.js +185 -0
  6. package/dist/components/chat/ask-user-card.js.map +1 -0
  7. package/dist/components/chat/brain-markdown.d.ts +35 -0
  8. package/dist/components/chat/brain-markdown.d.ts.map +1 -0
  9. package/dist/components/chat/brain-markdown.js +363 -0
  10. package/dist/components/chat/brain-markdown.js.map +1 -0
  11. package/dist/components/chat/chat-page.d.ts +2 -0
  12. package/dist/components/chat/chat-page.d.ts.map +1 -0
  13. package/dist/components/chat/chat-page.js +442 -0
  14. package/dist/components/chat/chat-page.js.map +1 -0
  15. package/dist/components/chat/command-palette.d.ts +5 -0
  16. package/dist/components/chat/command-palette.d.ts.map +1 -0
  17. package/dist/components/chat/command-palette.js +18 -0
  18. package/dist/components/chat/command-palette.js.map +1 -0
  19. package/dist/components/chat/markdown-content.d.ts +4 -0
  20. package/dist/components/chat/markdown-content.d.ts.map +1 -0
  21. package/dist/components/chat/markdown-content.js +6 -0
  22. package/dist/components/chat/markdown-content.js.map +1 -0
  23. package/dist/components/chat/message-bubble.d.ts +9 -0
  24. package/dist/components/chat/message-bubble.d.ts.map +1 -0
  25. package/dist/components/chat/message-bubble.js +129 -0
  26. package/dist/components/chat/message-bubble.js.map +1 -0
  27. package/dist/components/chat/message-share.d.ts +10 -0
  28. package/dist/components/chat/message-share.d.ts.map +1 -0
  29. package/dist/components/chat/message-share.js +65 -0
  30. package/dist/components/chat/message-share.js.map +1 -0
  31. package/dist/components/chat/renderers/claude-tools.d.ts +3 -0
  32. package/dist/components/chat/renderers/claude-tools.d.ts.map +1 -0
  33. package/dist/components/chat/renderers/claude-tools.js +38 -0
  34. package/dist/components/chat/renderers/claude-tools.js.map +1 -0
  35. package/dist/components/chat/renderers/generic.d.ts +9 -0
  36. package/dist/components/chat/renderers/generic.d.ts.map +1 -0
  37. package/dist/components/chat/renderers/generic.js +68 -0
  38. package/dist/components/chat/renderers/generic.js.map +1 -0
  39. package/dist/components/chat/renderers/index.d.ts +5 -0
  40. package/dist/components/chat/renderers/index.d.ts.map +1 -0
  41. package/dist/components/chat/renderers/index.js +17 -0
  42. package/dist/components/chat/renderers/index.js.map +1 -0
  43. package/dist/components/chat/risk-hints.d.ts +20 -0
  44. package/dist/components/chat/risk-hints.d.ts.map +1 -0
  45. package/dist/components/chat/risk-hints.js +81 -0
  46. package/dist/components/chat/risk-hints.js.map +1 -0
  47. package/dist/components/chat/session-drawer.d.ts +6 -0
  48. package/dist/components/chat/session-drawer.d.ts.map +1 -0
  49. package/dist/components/chat/session-drawer.js +96 -0
  50. package/dist/components/chat/session-drawer.js.map +1 -0
  51. package/dist/components/chat/share-block.d.ts +9 -0
  52. package/dist/components/chat/share-block.d.ts.map +1 -0
  53. package/dist/components/chat/share-block.js +70 -0
  54. package/dist/components/chat/share-block.js.map +1 -0
  55. package/dist/components/chat/tool-call-timeline.d.ts +8 -0
  56. package/dist/components/chat/tool-call-timeline.d.ts.map +1 -0
  57. package/dist/components/chat/tool-call-timeline.js +100 -0
  58. package/dist/components/chat/tool-call-timeline.js.map +1 -0
  59. package/dist/components/chat/tool-views.d.ts +116 -0
  60. package/dist/components/chat/tool-views.d.ts.map +1 -0
  61. package/dist/components/chat/tool-views.js +628 -0
  62. package/dist/components/chat/tool-views.js.map +1 -0
  63. package/dist/components/chat/welcome-state.d.ts +4 -0
  64. package/dist/components/chat/welcome-state.d.ts.map +1 -0
  65. package/dist/components/chat/welcome-state.js +10 -0
  66. package/dist/components/chat/welcome-state.js.map +1 -0
  67. package/dist/components/connectivity/connection-gate.d.ts +5 -0
  68. package/dist/components/connectivity/connection-gate.d.ts.map +1 -0
  69. package/dist/components/connectivity/connection-gate.js +42 -0
  70. package/dist/components/connectivity/connection-gate.js.map +1 -0
  71. package/dist/components/connectivity/login-screen.d.ts +9 -0
  72. package/dist/components/connectivity/login-screen.d.ts.map +1 -0
  73. package/dist/components/connectivity/login-screen.js +99 -0
  74. package/dist/components/connectivity/login-screen.js.map +1 -0
  75. package/dist/components/files/file-panel.d.ts +5 -0
  76. package/dist/components/files/file-panel.d.ts.map +1 -0
  77. package/dist/components/files/file-panel.js +46 -0
  78. package/dist/components/files/file-panel.js.map +1 -0
  79. package/dist/components/files/file-tree.d.ts +2 -0
  80. package/dist/components/files/file-tree.d.ts.map +1 -0
  81. package/dist/components/files/file-tree.js +63 -0
  82. package/dist/components/files/file-tree.js.map +1 -0
  83. package/dist/components/files/file-viewer-binary.d.ts +5 -0
  84. package/dist/components/files/file-viewer-binary.d.ts.map +1 -0
  85. package/dist/components/files/file-viewer-binary.js +20 -0
  86. package/dist/components/files/file-viewer-binary.js.map +1 -0
  87. package/dist/components/files/file-viewer-html.d.ts +4 -0
  88. package/dist/components/files/file-viewer-html.d.ts.map +1 -0
  89. package/dist/components/files/file-viewer-html.js +5 -0
  90. package/dist/components/files/file-viewer-html.js.map +1 -0
  91. package/dist/components/files/file-viewer-markdown.d.ts +4 -0
  92. package/dist/components/files/file-viewer-markdown.d.ts.map +1 -0
  93. package/dist/components/files/file-viewer-markdown.js +10 -0
  94. package/dist/components/files/file-viewer-markdown.js.map +1 -0
  95. package/dist/components/files/file-viewer-raw.d.ts +5 -0
  96. package/dist/components/files/file-viewer-raw.d.ts.map +1 -0
  97. package/dist/components/files/file-viewer-raw.js +15 -0
  98. package/dist/components/files/file-viewer-raw.js.map +1 -0
  99. package/dist/components/files/file-viewer.d.ts +2 -0
  100. package/dist/components/files/file-viewer.d.ts.map +1 -0
  101. package/dist/components/files/file-viewer.js +175 -0
  102. package/dist/components/files/file-viewer.js.map +1 -0
  103. package/dist/components/files/frontmatter-panel.d.ts +5 -0
  104. package/dist/components/files/frontmatter-panel.d.ts.map +1 -0
  105. package/dist/components/files/frontmatter-panel.js +12 -0
  106. package/dist/components/files/frontmatter-panel.js.map +1 -0
  107. package/dist/components/layout/app-shell.d.ts +5 -0
  108. package/dist/components/layout/app-shell.d.ts.map +1 -0
  109. package/dist/components/layout/app-shell.js +10 -0
  110. package/dist/components/layout/app-shell.js.map +1 -0
  111. package/dist/components/layout/mobile-tab-bar.d.ts +2 -0
  112. package/dist/components/layout/mobile-tab-bar.d.ts.map +1 -0
  113. package/dist/components/layout/mobile-tab-bar.js +16 -0
  114. package/dist/components/layout/mobile-tab-bar.js.map +1 -0
  115. package/dist/components/layout/side-rail.d.ts +2 -0
  116. package/dist/components/layout/side-rail.d.ts.map +1 -0
  117. package/dist/components/layout/side-rail.js +26 -0
  118. package/dist/components/layout/side-rail.js.map +1 -0
  119. package/dist/components/layout/slide-panel.d.ts +9 -0
  120. package/dist/components/layout/slide-panel.d.ts.map +1 -0
  121. package/dist/components/layout/slide-panel.js +18 -0
  122. package/dist/components/layout/slide-panel.js.map +1 -0
  123. package/dist/components/quick-actions/streaming-modal.d.ts +8 -0
  124. package/dist/components/quick-actions/streaming-modal.d.ts.map +1 -0
  125. package/dist/components/quick-actions/streaming-modal.js +92 -0
  126. package/dist/components/quick-actions/streaming-modal.js.map +1 -0
  127. package/dist/components/quick-actions/whatsup-modal.d.ts +5 -0
  128. package/dist/components/quick-actions/whatsup-modal.d.ts.map +1 -0
  129. package/dist/components/quick-actions/whatsup-modal.js +82 -0
  130. package/dist/components/quick-actions/whatsup-modal.js.map +1 -0
  131. package/dist/components/settings/passkey-panel.d.ts +10 -0
  132. package/dist/components/settings/passkey-panel.d.ts.map +1 -0
  133. package/dist/components/settings/passkey-panel.js +118 -0
  134. package/dist/components/settings/passkey-panel.js.map +1 -0
  135. package/dist/components/share/share-menu.d.ts +23 -0
  136. package/dist/components/share/share-menu.d.ts.map +1 -0
  137. package/dist/components/share/share-menu.js +58 -0
  138. package/dist/components/share/share-menu.js.map +1 -0
  139. package/dist/components/voice/dictation-sheet.d.ts +6 -0
  140. package/dist/components/voice/dictation-sheet.d.ts.map +1 -0
  141. package/dist/components/voice/dictation-sheet.js +91 -0
  142. package/dist/components/voice/dictation-sheet.js.map +1 -0
  143. package/dist/components/voice/mic-button.d.ts +6 -0
  144. package/dist/components/voice/mic-button.d.ts.map +1 -0
  145. package/dist/components/voice/mic-button.js +9 -0
  146. package/dist/components/voice/mic-button.js.map +1 -0
  147. package/dist/components/voice/review-card.d.ts +8 -0
  148. package/dist/components/voice/review-card.d.ts.map +1 -0
  149. package/dist/components/voice/review-card.js +8 -0
  150. package/dist/components/voice/review-card.js.map +1 -0
  151. package/dist/config.d.ts +19 -0
  152. package/dist/config.d.ts.map +1 -0
  153. package/dist/config.js +10 -0
  154. package/dist/config.js.map +1 -0
  155. package/dist/hooks/use-vpn-status.d.ts +2 -0
  156. package/dist/hooks/use-vpn-status.d.ts.map +1 -0
  157. package/dist/hooks/use-vpn-status.js +71 -0
  158. package/dist/hooks/use-vpn-status.js.map +1 -0
  159. package/dist/hooks/use-websocket.d.ts +8 -0
  160. package/dist/hooks/use-websocket.d.ts.map +1 -0
  161. package/dist/hooks/use-websocket.js +366 -0
  162. package/dist/hooks/use-websocket.js.map +1 -0
  163. package/dist/index.d.ts +25 -0
  164. package/dist/index.d.ts.map +1 -0
  165. package/dist/index.js +31 -0
  166. package/dist/index.js.map +1 -0
  167. package/dist/lib/api-client.d.ts +115 -0
  168. package/dist/lib/api-client.d.ts.map +1 -0
  169. package/dist/lib/api-client.js +70 -0
  170. package/dist/lib/api-client.js.map +1 -0
  171. package/dist/lib/backend.d.ts +7 -0
  172. package/dist/lib/backend.d.ts.map +1 -0
  173. package/dist/lib/backend.js +33 -0
  174. package/dist/lib/backend.js.map +1 -0
  175. package/dist/lib/frontmatter.d.ts +21 -0
  176. package/dist/lib/frontmatter.d.ts.map +1 -0
  177. package/dist/lib/frontmatter.js +88 -0
  178. package/dist/lib/frontmatter.js.map +1 -0
  179. package/dist/lib/image-attachments.d.ts +36 -0
  180. package/dist/lib/image-attachments.d.ts.map +1 -0
  181. package/dist/lib/image-attachments.js +175 -0
  182. package/dist/lib/image-attachments.js.map +1 -0
  183. package/dist/lib/passkeys.d.ts +18 -0
  184. package/dist/lib/passkeys.d.ts.map +1 -0
  185. package/dist/lib/passkeys.js +36 -0
  186. package/dist/lib/passkeys.js.map +1 -0
  187. package/dist/lib/share.d.ts +53 -0
  188. package/dist/lib/share.d.ts.map +1 -0
  189. package/dist/lib/share.js +144 -0
  190. package/dist/lib/share.js.map +1 -0
  191. package/dist/lib/strip-markdown.d.ts +10 -0
  192. package/dist/lib/strip-markdown.d.ts.map +1 -0
  193. package/dist/lib/strip-markdown.js +37 -0
  194. package/dist/lib/strip-markdown.js.map +1 -0
  195. package/dist/lib/tool-names.d.ts +17 -0
  196. package/dist/lib/tool-names.d.ts.map +1 -0
  197. package/dist/lib/tool-names.js +23 -0
  198. package/dist/lib/tool-names.js.map +1 -0
  199. package/dist/lib/utils.d.ts +3 -0
  200. package/dist/lib/utils.d.ts.map +1 -0
  201. package/dist/lib/utils.js +6 -0
  202. package/dist/lib/utils.js.map +1 -0
  203. package/dist/lib/ws-client.d.ts +26 -0
  204. package/dist/lib/ws-client.d.ts.map +1 -0
  205. package/dist/lib/ws-client.js +93 -0
  206. package/dist/lib/ws-client.js.map +1 -0
  207. package/dist/stores/chat-store.d.ts +131 -0
  208. package/dist/stores/chat-store.d.ts.map +1 -0
  209. package/dist/stores/chat-store.js +376 -0
  210. package/dist/stores/chat-store.js.map +1 -0
  211. package/dist/stores/connection-store.d.ts +11 -0
  212. package/dist/stores/connection-store.d.ts.map +1 -0
  213. package/dist/stores/connection-store.js +8 -0
  214. package/dist/stores/connection-store.js.map +1 -0
  215. package/dist/stores/file-store.d.ts +53 -0
  216. package/dist/stores/file-store.d.ts.map +1 -0
  217. package/dist/stores/file-store.js +284 -0
  218. package/dist/stores/file-store.js.map +1 -0
  219. package/dist/stores/provider-store.d.ts +24 -0
  220. package/dist/stores/provider-store.d.ts.map +1 -0
  221. package/dist/stores/provider-store.js +56 -0
  222. package/dist/stores/provider-store.js.map +1 -0
  223. package/dist/stores/ui-store.d.ts +21 -0
  224. package/dist/stores/ui-store.d.ts.map +1 -0
  225. package/dist/stores/ui-store.js +23 -0
  226. package/dist/stores/ui-store.js.map +1 -0
  227. package/dist/styles.css +2 -0
  228. package/dist/voice/asr-clients.d.ts +2 -0
  229. package/dist/voice/asr-clients.d.ts.map +1 -0
  230. package/dist/voice/asr-clients.js +33 -0
  231. package/dist/voice/asr-clients.js.map +1 -0
  232. package/dist/voice/asr-deepgram.d.ts +38 -0
  233. package/dist/voice/asr-deepgram.d.ts.map +1 -0
  234. package/dist/voice/asr-deepgram.js +307 -0
  235. package/dist/voice/asr-deepgram.js.map +1 -0
  236. package/dist/voice/asr-webspeech.d.ts +23 -0
  237. package/dist/voice/asr-webspeech.d.ts.map +1 -0
  238. package/dist/voice/asr-webspeech.js +93 -0
  239. package/dist/voice/asr-webspeech.js.map +1 -0
  240. package/dist/voice/use-dictation.d.ts +6 -0
  241. package/dist/voice/use-dictation.d.ts.map +1 -0
  242. package/dist/voice/use-dictation.js +174 -0
  243. package/dist/voice/use-dictation.js.map +1 -0
  244. package/dist/voice/voice-store.d.ts +26 -0
  245. package/dist/voice/voice-store.d.ts.map +1 -0
  246. package/dist/voice/voice-store.js +27 -0
  247. package/dist/voice/voice-store.js.map +1 -0
  248. package/package.json +71 -0
  249. package/src/components/chat/ask-user-card.tsx +451 -0
  250. package/src/components/chat/brain-markdown.tsx +547 -0
  251. package/src/components/chat/chat-page.tsx +820 -0
  252. package/src/components/chat/command-palette.tsx +68 -0
  253. package/src/components/chat/markdown-content.tsx +5 -0
  254. package/src/components/chat/message-bubble.tsx +362 -0
  255. package/src/components/chat/message-share.ts +78 -0
  256. package/src/components/chat/renderers/claude-tools.tsx +53 -0
  257. package/src/components/chat/renderers/generic.tsx +85 -0
  258. package/src/components/chat/renderers/index.ts +19 -0
  259. package/src/components/chat/risk-hints.ts +95 -0
  260. package/src/components/chat/session-drawer.tsx +213 -0
  261. package/src/components/chat/share-block.tsx +128 -0
  262. package/src/components/chat/tool-call-timeline.tsx +322 -0
  263. package/src/components/chat/tool-views.tsx +898 -0
  264. package/src/components/chat/welcome-state.tsx +105 -0
  265. package/src/components/connectivity/connection-gate.tsx +137 -0
  266. package/src/components/connectivity/login-screen.tsx +169 -0
  267. package/src/components/files/file-panel.tsx +116 -0
  268. package/src/components/files/file-tree.tsx +143 -0
  269. package/src/components/files/file-viewer-binary.tsx +63 -0
  270. package/src/components/files/file-viewer-html.tsx +10 -0
  271. package/src/components/files/file-viewer-markdown.tsx +14 -0
  272. package/src/components/files/file-viewer-raw.tsx +44 -0
  273. package/src/components/files/file-viewer.tsx +290 -0
  274. package/src/components/files/frontmatter-panel.tsx +78 -0
  275. package/src/components/layout/app-shell.tsx +25 -0
  276. package/src/components/layout/mobile-tab-bar.tsx +54 -0
  277. package/src/components/layout/side-rail.tsx +128 -0
  278. package/src/components/layout/slide-panel.tsx +64 -0
  279. package/src/components/quick-actions/streaming-modal.tsx +168 -0
  280. package/src/components/quick-actions/whatsup-modal.tsx +149 -0
  281. package/src/components/settings/passkey-panel.tsx +281 -0
  282. package/src/components/share/share-menu.tsx +121 -0
  283. package/src/components/voice/dictation-sheet.tsx +217 -0
  284. package/src/components/voice/mic-button.tsx +31 -0
  285. package/src/components/voice/review-card.tsx +66 -0
  286. package/src/config.ts +27 -0
  287. package/src/hooks/use-vpn-status.ts +75 -0
  288. package/src/hooks/use-websocket.ts +403 -0
  289. package/src/index.ts +46 -0
  290. package/src/lib/api-client.ts +173 -0
  291. package/src/lib/backend.ts +35 -0
  292. package/src/lib/frontmatter.ts +99 -0
  293. package/src/lib/image-attachments.ts +221 -0
  294. package/src/lib/passkeys.ts +50 -0
  295. package/src/lib/share.ts +167 -0
  296. package/src/lib/strip-markdown.ts +38 -0
  297. package/src/lib/tool-names.ts +27 -0
  298. package/src/lib/utils.ts +6 -0
  299. package/src/lib/ws-client.ts +109 -0
  300. package/src/stores/chat-store.ts +619 -0
  301. package/src/stores/connection-store.ts +23 -0
  302. package/src/stores/file-store.ts +344 -0
  303. package/src/stores/provider-store.ts +85 -0
  304. package/src/stores/ui-store.ts +48 -0
  305. package/src/styles.css +4 -0
  306. package/src/theme.css +425 -0
  307. package/src/voice/asr-clients.ts +45 -0
  308. package/src/voice/asr-deepgram.ts +325 -0
  309. package/src/voice/asr-webspeech.ts +135 -0
  310. package/src/voice/use-dictation.ts +187 -0
  311. package/src/voice/voice-store.ts +55 -0
@@ -0,0 +1,619 @@
1
+ import { create } from "zustand";
2
+ import type {
3
+ MessageSource,
4
+ MessagePart,
5
+ AskUserQuestion,
6
+ AskUserAnnotation,
7
+ } from "@schlessera/brain-ui-sdk/protocol";
8
+ import { useProviderStore } from "./provider-store.js";
9
+
10
+ export type { MessagePart };
11
+
12
+ export interface ChatMessage {
13
+ id: string;
14
+ role: "user" | "assistant";
15
+ content: string;
16
+ thinking?: string;
17
+ toolCalls: ToolCall[];
18
+ /**
19
+ * Chronological thinking/text/tool segments, in arrival order. `content`,
20
+ * `thinking` and `toolCalls` remain the aggregated views (used for sharing
21
+ * and tool state); `parts` drives rendering order.
22
+ */
23
+ parts: MessagePart[];
24
+ isStreaming: boolean;
25
+ timestamp: number;
26
+ source?: MessageSource;
27
+ /** AskUserQuestion exchanges raised during this assistant turn. */
28
+ askUserExchanges?: AskUserExchange[];
29
+ /**
30
+ * Image attachments on a user message. Live messages carry a local
31
+ * `previewUrl` (object URL, revoked on clear). History-loaded messages
32
+ * carry no data — only `attachmentCount` — since base64 is never replayed.
33
+ */
34
+ attachments?: MessageAttachment[];
35
+ /** Attachment count for history-loaded messages without preview data. */
36
+ attachmentCount?: number;
37
+ }
38
+
39
+ export interface MessageAttachment {
40
+ previewUrl: string;
41
+ mediaType: string;
42
+ }
43
+
44
+ export interface ToolCall {
45
+ id: string;
46
+ name: string;
47
+ input: Record<string, unknown>;
48
+ inputJson: string;
49
+ output?: string;
50
+ isError?: boolean;
51
+ status: "streaming" | "pending_approval" | "approved" | "denied" | "complete";
52
+ /**
53
+ * Execution timing for the duration badge. `startedAt` is (re)stamped when
54
+ * the input finishes streaming or an approval is granted — so approval
55
+ * wait time doesn't inflate the reported duration. `endedAt` is stamped by
56
+ * the tool result. History-loaded messages carry no timing.
57
+ */
58
+ startedAt?: number;
59
+ endedAt?: number;
60
+ }
61
+
62
+ export interface AskUserExchange {
63
+ requestId: string;
64
+ questions: AskUserQuestion[];
65
+ /** Filled in once the user submits. Keyed by question text. */
66
+ answers?: Record<string, string>;
67
+ annotations?: Record<string, AskUserAnnotation>;
68
+ cancelled?: boolean;
69
+ }
70
+
71
+ /**
72
+ * One session's live transcript state. Every session the user has viewed (or
73
+ * that bound from the draft) keeps its own buffer, so frames from a background
74
+ * session accumulate in THAT session's transcript instead of being discarded —
75
+ * the multi-session contract the old single-active-buffer store violated.
76
+ */
77
+ export interface SessionChat {
78
+ messages: ChatMessage[];
79
+ isStreaming: boolean;
80
+ /**
81
+ * The currently-pending ask-user exchange in this session (no answers yet).
82
+ * Mirrors the same exchange that lives on the streaming assistant message;
83
+ * held here for fast lookup by hooks/components.
84
+ */
85
+ askUser: AskUserExchange | null;
86
+ /** LRU stamp for buffer eviction. */
87
+ lastTouched: number;
88
+ }
89
+
90
+ /**
91
+ * Buffer key: a server sessionId, or null for the DRAFT buffer — the new
92
+ * conversation that has no server identity yet. `session_info` re-keys the
93
+ * draft onto its real sessionId via bindDraftSession().
94
+ */
95
+ export type ChatKey = string | null;
96
+
97
+ /** Retained transcript buffers beyond the active one (LRU-evicted). */
98
+ const MAX_BUFFERS = 8;
99
+
100
+ interface ChatState {
101
+ /** Per-session transcript buffers, keyed by server sessionId. */
102
+ buffers: Record<string, SessionChat>;
103
+ /** The unbound new-conversation buffer, if one is in progress. */
104
+ draft: SessionChat | null;
105
+ /** The session in view; null = the draft / new-chat view. */
106
+ activeSessionId: string | null;
107
+
108
+ /**
109
+ * Live run-state per session id, for the session-list badges. Maintained for
110
+ * every session frame regardless of whether a buffer exists. "idle" is the
111
+ * absence of a running/queued turn.
112
+ */
113
+ runStates: Record<string, "streaming" | "queued" | "idle">;
114
+
115
+ // Buffer mutations (key: sessionId, or null for the draft)
116
+ addUserMessage: (
117
+ key: ChatKey,
118
+ text: string,
119
+ source?: MessageSource,
120
+ attachments?: MessageAttachment[]
121
+ ) => void;
122
+ startAssistantMessage: (key: ChatKey) => void;
123
+ appendText: (key: ChatKey, text: string) => void;
124
+ appendThinking: (key: ChatKey, text: string) => void;
125
+ startToolCall: (key: ChatKey, toolUseId: string, toolName: string) => void;
126
+ appendToolInput: (key: ChatKey, partialJson: string) => void;
127
+ completeToolCall: (
128
+ key: ChatKey,
129
+ toolUseId: string,
130
+ toolName: string,
131
+ input: Record<string, unknown>
132
+ ) => void;
133
+ requestToolApproval: (
134
+ key: ChatKey,
135
+ toolUseId: string,
136
+ toolName: string,
137
+ input: Record<string, unknown>,
138
+ description?: string
139
+ ) => void;
140
+ resolveToolApproval: (key: ChatKey, toolUseId: string, approved: boolean) => void;
141
+ setToolResult: (key: ChatKey, toolUseId: string, output: string, isError: boolean) => void;
142
+ setAskUserRequest: (key: ChatKey, requestId: string, questions: AskUserQuestion[]) => void;
143
+ submitAskUserAnswers: (
144
+ key: ChatKey,
145
+ requestId: string,
146
+ answers: Record<string, string>,
147
+ annotations?: Record<string, AskUserAnnotation>
148
+ ) => void;
149
+ cancelAskUser: (key: ChatKey, requestId: string) => void;
150
+ clearAskUser: (key: ChatKey) => void;
151
+ finishAssistantMessage: (key: ChatKey) => void;
152
+ setStreaming: (key: ChatKey, streaming: boolean) => void;
153
+ /** Replace a session's transcript (first replayed history chunk). Creates the buffer. */
154
+ setMessages: (key: ChatKey, messages: ChatMessage[]) => void;
155
+ /** Concatenate a continuation chunk of replayed history. Creates the buffer. */
156
+ appendMessages: (key: ChatKey, messages: ChatMessage[]) => void;
157
+
158
+ // Session lifecycle
159
+ /**
160
+ * Adopt the draft buffer as `sessionId` (the server just named the session).
161
+ * If the draft view is active, the view follows. No-op draft = empty buffer.
162
+ */
163
+ bindDraftSession: (sessionId: string) => void;
164
+ /** Switch the view to a session (creating an empty buffer if none), or to the draft (null). */
165
+ setActiveSession: (sessionId: string | null) => void;
166
+ /** New chat: drop the draft, unbind the view, unpin the provider. */
167
+ clearMessages: () => void;
168
+ setRunState: (sessionId: string, state: "streaming" | "queued" | "idle") => void;
169
+ }
170
+
171
+ let messageCounter = 0;
172
+ function nextId() {
173
+ return `msg-${++messageCounter}-${Date.now()}`;
174
+ }
175
+
176
+ const SESSION_ID_KEY = "brain-sessionId";
177
+
178
+ /**
179
+ * Persist the active session id to localStorage when a DOM is present (the
180
+ * browser). A no-op in non-DOM environments (tests, SSR) so creating the store
181
+ * never throws on a missing `localStorage`.
182
+ */
183
+ function persistSessionId(id: string | null) {
184
+ if (typeof localStorage === "undefined") return;
185
+ if (id) localStorage.setItem(SESSION_ID_KEY, id);
186
+ else localStorage.removeItem(SESSION_ID_KEY);
187
+ }
188
+
189
+ function readPersistedSessionId(): string | null {
190
+ if (typeof localStorage === "undefined") return null;
191
+ return localStorage.getItem(SESSION_ID_KEY);
192
+ }
193
+
194
+ function emptyChat(): SessionChat {
195
+ return { messages: [], isStreaming: false, askUser: null, lastTouched: Date.now() };
196
+ }
197
+
198
+ /** Frozen empty buffer for selectors when nothing is in view. */
199
+ const EMPTY_CHAT: SessionChat = Object.freeze({
200
+ messages: Object.freeze([]) as unknown as ChatMessage[],
201
+ isStreaming: false,
202
+ askUser: null,
203
+ lastTouched: 0,
204
+ });
205
+
206
+ /** The buffer currently in view (draft when no session is bound). */
207
+ export function activeChat(state: ChatState): SessionChat {
208
+ if (state.activeSessionId) return state.buffers[state.activeSessionId] ?? EMPTY_CHAT;
209
+ return state.draft ?? EMPTY_CHAT;
210
+ }
211
+
212
+ /** True when ANY buffer is streaming (service-worker busy check, etc.). */
213
+ export function anyStreaming(state: ChatState): boolean {
214
+ if (state.draft?.isStreaming) return true;
215
+ return Object.values(state.buffers).some((b) => b.isStreaming);
216
+ }
217
+
218
+ /** Append text to the last part if it has the same kind, else start a new part. */
219
+ function appendPart(
220
+ parts: MessagePart[],
221
+ kind: "thinking" | "text",
222
+ text: string
223
+ ): MessagePart[] {
224
+ const last = parts[parts.length - 1];
225
+ if (last && last.kind === kind) {
226
+ return [...parts.slice(0, -1), { kind, text: last.text + text }];
227
+ }
228
+ return [...parts, { kind, text }];
229
+ }
230
+
231
+ /** Free object URLs held by live message previews before dropping them. */
232
+ function revokeAttachmentUrls(messages: ChatMessage[]) {
233
+ for (const m of messages) {
234
+ for (const a of m.attachments ?? []) {
235
+ if (a.previewUrl.startsWith("blob:")) URL.revokeObjectURL(a.previewUrl);
236
+ }
237
+ }
238
+ }
239
+
240
+ /** Evict least-recently-touched non-active buffers beyond MAX_BUFFERS. */
241
+ function evictStale(
242
+ buffers: Record<string, SessionChat>,
243
+ activeSessionId: string | null
244
+ ): Record<string, SessionChat> {
245
+ const ids = Object.keys(buffers);
246
+ if (ids.length <= MAX_BUFFERS) return buffers;
247
+ const evictable = ids
248
+ .filter((id) => id !== activeSessionId && !buffers[id].isStreaming)
249
+ .sort((a, b) => buffers[a].lastTouched - buffers[b].lastTouched);
250
+ const next = { ...buffers };
251
+ for (const id of evictable.slice(0, ids.length - MAX_BUFFERS)) {
252
+ revokeAttachmentUrls(next[id].messages);
253
+ delete next[id];
254
+ }
255
+ return next;
256
+ }
257
+
258
+ export const useChatStore = create<ChatState>((set, get) => {
259
+ /**
260
+ * Immutably update one buffer. Draft mutations (key null) create the draft
261
+ * on demand; session mutations require an existing buffer — a frame for an
262
+ * evicted/never-opened session must not materialize a partial transcript
263
+ * (the view heals via session_resume instead).
264
+ */
265
+ function mutateBuffer(
266
+ key: ChatKey,
267
+ fn: (chat: SessionChat) => Partial<SessionChat>,
268
+ createIfMissing = false
269
+ ): void {
270
+ set((state) => {
271
+ if (key === null) {
272
+ const draft = state.draft ?? emptyChat();
273
+ return { draft: { ...draft, ...fn(draft), lastTouched: Date.now() } };
274
+ }
275
+ const existing = state.buffers[key] ?? (createIfMissing ? emptyChat() : undefined);
276
+ if (!existing) return state;
277
+ return {
278
+ buffers: {
279
+ ...state.buffers,
280
+ [key]: { ...existing, ...fn(existing), lastTouched: Date.now() },
281
+ },
282
+ };
283
+ });
284
+ }
285
+
286
+ /** Update the last message of a buffer when it is an assistant message. */
287
+ function mutateLastAssistant(
288
+ key: ChatKey,
289
+ fn: (msg: ChatMessage) => ChatMessage,
290
+ extra?: (chat: SessionChat) => Partial<SessionChat>
291
+ ): void {
292
+ mutateBuffer(key, (chat) => {
293
+ const msgs = [...chat.messages];
294
+ const last = msgs[msgs.length - 1];
295
+ let out: Partial<SessionChat> = {};
296
+ if (last?.role === "assistant") {
297
+ msgs[msgs.length - 1] = fn(last);
298
+ out = { messages: msgs };
299
+ }
300
+ return extra ? { ...out, ...extra(chat) } : out;
301
+ });
302
+ }
303
+
304
+ return {
305
+ buffers: {},
306
+ draft: null,
307
+ // localStorage (not sessionStorage) so the active session id survives the
308
+ // PWA process being killed on mobile — that durability is what lets a cold
309
+ // relaunch re-request the full transcript instead of showing nothing.
310
+ activeSessionId: readPersistedSessionId(),
311
+ runStates: {},
312
+
313
+ // createIfMissing: a user-initiated send must never be dropped, even when
314
+ // the active session's buffer hasn't been materialized yet (cold start
315
+ // racing the history replay).
316
+ addUserMessage: (key, text, source, attachments) =>
317
+ mutateBuffer(
318
+ key,
319
+ (chat) => ({
320
+ messages: [
321
+ ...chat.messages,
322
+ {
323
+ id: nextId(),
324
+ role: "user",
325
+ content: text,
326
+ toolCalls: [],
327
+ parts: [],
328
+ isStreaming: false,
329
+ timestamp: Date.now(),
330
+ source: source ?? "typed",
331
+ ...(attachments && attachments.length > 0
332
+ ? { attachments, attachmentCount: attachments.length }
333
+ : {}),
334
+ },
335
+ ],
336
+ }),
337
+ true
338
+ ),
339
+
340
+ startAssistantMessage: (key) =>
341
+ mutateBuffer(key, (chat) => ({
342
+ messages: [
343
+ ...chat.messages,
344
+ {
345
+ id: nextId(),
346
+ role: "assistant",
347
+ content: "",
348
+ thinking: "",
349
+ toolCalls: [],
350
+ parts: [],
351
+ isStreaming: true,
352
+ timestamp: Date.now(),
353
+ },
354
+ ],
355
+ isStreaming: true,
356
+ })),
357
+
358
+ appendText: (key, text) =>
359
+ mutateLastAssistant(key, (last) => ({
360
+ ...last,
361
+ content: last.content + text,
362
+ parts: appendPart(last.parts, "text", text),
363
+ })),
364
+
365
+ appendThinking: (key, text) =>
366
+ mutateLastAssistant(key, (last) => ({
367
+ ...last,
368
+ thinking: (last.thinking || "") + text,
369
+ parts: appendPart(last.parts, "thinking", text),
370
+ })),
371
+
372
+ startToolCall: (key, toolUseId, toolName) =>
373
+ mutateLastAssistant(key, (last) => ({
374
+ ...last,
375
+ parts: [...last.parts, { kind: "tool", toolIndex: last.toolCalls.length }],
376
+ toolCalls: [
377
+ ...last.toolCalls,
378
+ {
379
+ id: toolUseId,
380
+ name: toolName,
381
+ input: {},
382
+ inputJson: "",
383
+ status: "streaming",
384
+ startedAt: Date.now(),
385
+ },
386
+ ],
387
+ })),
388
+
389
+ appendToolInput: (key, partialJson) =>
390
+ mutateLastAssistant(key, (last) => {
391
+ if (last.toolCalls.length === 0) return last;
392
+ const tools = [...last.toolCalls];
393
+ const lastTool = tools[tools.length - 1];
394
+ tools[tools.length - 1] = {
395
+ ...lastTool,
396
+ inputJson: lastTool.inputJson + partialJson,
397
+ };
398
+ return { ...last, toolCalls: tools };
399
+ }),
400
+
401
+ completeToolCall: (key, toolUseId, toolName, input) =>
402
+ mutateLastAssistant(key, (last) => ({
403
+ ...last,
404
+ toolCalls: last.toolCalls.map((t) =>
405
+ t.id === toolUseId || (t.name === toolName && t.status === "streaming")
406
+ ? {
407
+ ...t,
408
+ id: toolUseId,
409
+ input,
410
+ status: "complete" as const,
411
+ // Input finished streaming — execution starts about now
412
+ startedAt: Date.now(),
413
+ }
414
+ : t
415
+ ),
416
+ })),
417
+
418
+ requestToolApproval: (key, toolUseId, toolName, input, description) =>
419
+ mutateLastAssistant(key, (last) => {
420
+ // Check if tool call already exists (from streaming)
421
+ const existingIdx = last.toolCalls.findIndex(
422
+ (t) => t.id === toolUseId || (t.name === toolName && t.status === "streaming")
423
+ );
424
+ const tools = [...last.toolCalls];
425
+ const toolCall: ToolCall = {
426
+ id: toolUseId,
427
+ name: toolName,
428
+ input,
429
+ inputJson: JSON.stringify(input, null, 2),
430
+ status: "pending_approval",
431
+ };
432
+ let parts = last.parts;
433
+ if (existingIdx >= 0) {
434
+ tools[existingIdx] = toolCall;
435
+ } else {
436
+ // Approval request for a tool that never streamed a start event —
437
+ // give it a chronological slot too.
438
+ parts = [...parts, { kind: "tool", toolIndex: tools.length }];
439
+ tools.push(toolCall);
440
+ }
441
+ return { ...last, toolCalls: tools, parts };
442
+ }),
443
+
444
+ resolveToolApproval: (key, toolUseId, approved) =>
445
+ mutateLastAssistant(key, (last) => ({
446
+ ...last,
447
+ toolCalls: last.toolCalls.map((t) =>
448
+ t.id === toolUseId
449
+ ? {
450
+ ...t,
451
+ status: approved ? ("approved" as const) : ("denied" as const),
452
+ // Don't let approval wait time inflate the duration badge
453
+ ...(approved ? { startedAt: Date.now() } : {}),
454
+ }
455
+ : t
456
+ ),
457
+ })),
458
+
459
+ setToolResult: (key, toolUseId, output, isError) =>
460
+ mutateLastAssistant(key, (last) => ({
461
+ ...last,
462
+ toolCalls: last.toolCalls.map((t) =>
463
+ t.id === toolUseId
464
+ ? {
465
+ ...t,
466
+ output,
467
+ isError,
468
+ status: "complete" as const,
469
+ endedAt: Date.now(),
470
+ }
471
+ : t
472
+ ),
473
+ })),
474
+
475
+ setAskUserRequest: (key, requestId, questions) =>
476
+ mutateBuffer(key, (chat) => {
477
+ const exchange: AskUserExchange = { requestId, questions };
478
+ const msgs = [...chat.messages];
479
+ const lastIdx = msgs.length - 1;
480
+ const last = msgs[lastIdx];
481
+ if (last?.role === "assistant") {
482
+ msgs[lastIdx] = {
483
+ ...last,
484
+ askUserExchanges: [...(last.askUserExchanges ?? []), exchange],
485
+ };
486
+ }
487
+ return { messages: msgs, askUser: exchange };
488
+ }),
489
+
490
+ submitAskUserAnswers: (key, requestId, answers, annotations) =>
491
+ mutateBuffer(key, (chat) => {
492
+ const update = (e: AskUserExchange): AskUserExchange =>
493
+ e.requestId === requestId ? { ...e, answers, annotations } : e;
494
+ const msgs = chat.messages.map((m) =>
495
+ m.askUserExchanges?.some((e) => e.requestId === requestId)
496
+ ? { ...m, askUserExchanges: m.askUserExchanges.map(update) }
497
+ : m
498
+ );
499
+ const askUser =
500
+ chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser;
501
+ return { messages: msgs, askUser };
502
+ }),
503
+
504
+ cancelAskUser: (key, requestId) =>
505
+ mutateBuffer(key, (chat) => {
506
+ const update = (e: AskUserExchange): AskUserExchange =>
507
+ e.requestId === requestId ? { ...e, cancelled: true } : e;
508
+ const msgs = chat.messages.map((m) =>
509
+ m.askUserExchanges?.some((e) => e.requestId === requestId)
510
+ ? { ...m, askUserExchanges: m.askUserExchanges.map(update) }
511
+ : m
512
+ );
513
+ const askUser =
514
+ chat.askUser?.requestId === requestId ? update(chat.askUser) : chat.askUser;
515
+ return { messages: msgs, askUser };
516
+ }),
517
+
518
+ clearAskUser: (key) => mutateBuffer(key, () => ({ askUser: null })),
519
+
520
+ finishAssistantMessage: (key) =>
521
+ mutateLastAssistant(
522
+ key,
523
+ (last) => ({ ...last, isStreaming: false }),
524
+ () => ({ isStreaming: false })
525
+ ),
526
+
527
+ setStreaming: (key, streaming) => mutateBuffer(key, () => ({ isStreaming: streaming })),
528
+
529
+ setMessages: (key, messages) =>
530
+ set((state) => {
531
+ if (key === null) {
532
+ if (state.draft) revokeAttachmentUrls(state.draft.messages);
533
+ return {
534
+ draft: { ...emptyChat(), messages },
535
+ };
536
+ }
537
+ const existing = state.buffers[key];
538
+ if (existing) revokeAttachmentUrls(existing.messages);
539
+ const buffers = {
540
+ ...state.buffers,
541
+ [key]: { ...emptyChat(), messages },
542
+ };
543
+ return { buffers: evictStale(buffers, state.activeSessionId) };
544
+ }),
545
+
546
+ appendMessages: (key, messages) =>
547
+ set((state) => {
548
+ if (key === null) {
549
+ const draft = state.draft ?? emptyChat();
550
+ return { draft: { ...draft, messages: [...draft.messages, ...messages] } };
551
+ }
552
+ const existing = state.buffers[key] ?? emptyChat();
553
+ return {
554
+ buffers: {
555
+ ...state.buffers,
556
+ [key]: {
557
+ ...existing,
558
+ messages: [...existing.messages, ...messages],
559
+ lastTouched: Date.now(),
560
+ },
561
+ },
562
+ };
563
+ }),
564
+
565
+ bindDraftSession: (sessionId) =>
566
+ set((state) => {
567
+ const adopted = state.buffers[sessionId] ?? state.draft ?? emptyChat();
568
+ const buffers = evictStale(
569
+ { ...state.buffers, [sessionId]: { ...adopted, lastTouched: Date.now() } },
570
+ sessionId
571
+ );
572
+ const followView = state.activeSessionId === null;
573
+ if (followView) persistSessionId(sessionId);
574
+ return {
575
+ buffers,
576
+ draft: null,
577
+ ...(followView ? { activeSessionId: sessionId } : {}),
578
+ };
579
+ }),
580
+
581
+ setActiveSession: (sessionId) =>
582
+ set((state) => {
583
+ persistSessionId(sessionId);
584
+ if (sessionId === null) return { activeSessionId: null };
585
+ const existing = state.buffers[sessionId];
586
+ const buffers = existing
587
+ ? state.buffers
588
+ : evictStale({ ...state.buffers, [sessionId]: emptyChat() }, sessionId);
589
+ return { activeSessionId: sessionId, buffers };
590
+ }),
591
+
592
+ setRunState: (sessionId, runState) =>
593
+ set((state) => {
594
+ if (state.runStates[sessionId] === runState) return state;
595
+ const runStates = { ...state.runStates };
596
+ if (runState === "idle") delete runStates[sessionId];
597
+ else runStates[sessionId] = runState;
598
+ return { runStates };
599
+ }),
600
+
601
+ clearMessages: () => {
602
+ const state = get();
603
+ if (state.draft) revokeAttachmentUrls(state.draft.messages);
604
+ persistSessionId(null);
605
+ // Starting fresh: unpin the provider so the picker unlocks.
606
+ useProviderStore.getState().setPinned(null);
607
+ set({ draft: null, activeSessionId: null });
608
+ },
609
+ };
610
+ });
611
+
612
+ // Dev-only handle so browser automation / manual debugging can inject
613
+ // fixture messages without a live Claude session. The env read is defensive:
614
+ // outside a Vite build `import.meta.env` does not exist.
615
+ const devEnv = (import.meta as { env?: Record<string, unknown> }).env;
616
+ if (typeof window !== "undefined" && devEnv?.DEV) {
617
+ (window as unknown as { __chatStore?: typeof useChatStore }).__chatStore =
618
+ useChatStore;
619
+ }
@@ -0,0 +1,23 @@
1
+ import { create } from "zustand";
2
+
3
+ type WsStatus = "connecting" | "connected" | "disconnected";
4
+ type VpnStatus =
5
+ | "connected"
6
+ | "forbidden"
7
+ | "unauthorized"
8
+ | "unreachable"
9
+ | "checking";
10
+
11
+ interface ConnectionState {
12
+ wsStatus: WsStatus;
13
+ vpnStatus: VpnStatus;
14
+ setWsStatus: (status: WsStatus) => void;
15
+ setVpnStatus: (status: VpnStatus) => void;
16
+ }
17
+
18
+ export const useConnectionStore = create<ConnectionState>((set) => ({
19
+ wsStatus: "disconnected",
20
+ vpnStatus: "checking",
21
+ setWsStatus: (wsStatus) => set({ wsStatus }),
22
+ setVpnStatus: (vpnStatus) => set({ vpnStatus }),
23
+ }));