@arbidocs/react 0.4.166 → 0.4.168

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 (97) hide show
  1. package/dist/artifacts/index.cjs +15 -12
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.js +6 -3
  4. package/dist/artifacts/index.js.map +1 -1
  5. package/dist/calls/livekit/index.cjs +977 -0
  6. package/dist/calls/livekit/index.cjs.map +1 -0
  7. package/dist/calls/livekit/index.d.cts +280 -0
  8. package/dist/calls/livekit/index.d.ts +280 -0
  9. package/dist/calls/livekit/index.js +961 -0
  10. package/dist/calls/livekit/index.js.map +1 -0
  11. package/dist/{chunk-ON4PL6DQ.cjs → chunk-2M4B4FFA.cjs} +48 -4
  12. package/dist/chunk-2M4B4FFA.cjs.map +1 -0
  13. package/dist/chunk-3J7MEBOW.cjs +2551 -0
  14. package/dist/chunk-3J7MEBOW.cjs.map +1 -0
  15. package/dist/chunk-3NVSUYUV.js +528 -0
  16. package/dist/chunk-3NVSUYUV.js.map +1 -0
  17. package/dist/{chunk-QJHCVQ6C.js → chunk-3WIBD44F.js} +4734 -4673
  18. package/dist/chunk-3WIBD44F.js.map +1 -0
  19. package/dist/chunk-5B4PPJNW.cjs +1035 -0
  20. package/dist/chunk-5B4PPJNW.cjs.map +1 -0
  21. package/dist/chunk-5HDC43MF.js +145 -0
  22. package/dist/chunk-5HDC43MF.js.map +1 -0
  23. package/dist/{chunk-D66JCVBB.cjs → chunk-7NHOKV7N.cjs} +4093 -4040
  24. package/dist/chunk-7NHOKV7N.cjs.map +1 -0
  25. package/dist/chunk-APZZQZ6P.js +147 -0
  26. package/dist/chunk-APZZQZ6P.js.map +1 -0
  27. package/dist/{chunk-I5ZBQ63Y.js → chunk-DGMK3EUN.js} +188 -181
  28. package/dist/chunk-DGMK3EUN.js.map +1 -0
  29. package/dist/chunk-DPYBZDJB.js +18 -0
  30. package/dist/chunk-DPYBZDJB.js.map +1 -0
  31. package/dist/chunk-EEIYXVM4.cjs +181 -0
  32. package/dist/chunk-EEIYXVM4.cjs.map +1 -0
  33. package/dist/chunk-H3LMKO3T.js +2362 -0
  34. package/dist/chunk-H3LMKO3T.js.map +1 -0
  35. package/dist/{chunk-JSSKEXRR.js → chunk-KGCGA452.js} +2 -2
  36. package/dist/chunk-KGCGA452.js.map +1 -0
  37. package/dist/chunk-MJNZLWJD.js +986 -0
  38. package/dist/chunk-MJNZLWJD.js.map +1 -0
  39. package/dist/chunk-N73IMVFF.cjs +21 -0
  40. package/dist/chunk-N73IMVFF.cjs.map +1 -0
  41. package/dist/chunk-NVAIVJID.js +298 -0
  42. package/dist/chunk-NVAIVJID.js.map +1 -0
  43. package/dist/{chunk-GTJ667CP.cjs → chunk-QQ7SCJRY.cjs} +2 -2
  44. package/dist/chunk-QQ7SCJRY.cjs.map +1 -0
  45. package/dist/chunk-S4PCA3ES.cjs +572 -0
  46. package/dist/chunk-S4PCA3ES.cjs.map +1 -0
  47. package/dist/chunk-VAMPYLQ4.cjs +157 -0
  48. package/dist/chunk-VAMPYLQ4.cjs.map +1 -0
  49. package/dist/chunk-VLK52VXC.cjs +307 -0
  50. package/dist/chunk-VLK52VXC.cjs.map +1 -0
  51. package/dist/{chunk-SVHGCX25.js → chunk-YWYCEEBF.js} +43 -4
  52. package/dist/chunk-YWYCEEBF.js.map +1 -0
  53. package/dist/{chunk-EUC2BTNS.cjs → chunk-ZI2VJOID.cjs} +206 -199
  54. package/dist/chunk-ZI2VJOID.cjs.map +1 -0
  55. package/dist/document-tools/index.cjs +85 -109
  56. package/dist/document-tools/index.cjs.map +1 -1
  57. package/dist/document-tools/index.d.cts +19 -5
  58. package/dist/document-tools/index.d.ts +19 -5
  59. package/dist/document-tools/index.js +28 -70
  60. package/dist/document-tools/index.js.map +1 -1
  61. package/dist/index.cjs +12692 -9494
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/{index.d-DfCFKora.d.cts → index.d-Bvp6rKNo.d.cts} +139 -1
  64. package/dist/{index.d-DfCFKora.d.ts → index.d-Bvp6rKNo.d.ts} +139 -1
  65. package/dist/{index.d-DCjYj7YK.d.ts → index.d-Dx9sGkW2.d.cts} +20 -8
  66. package/dist/{index.d-DCjYj7YK.d.cts → index.d-Dx9sGkW2.d.ts} +20 -8
  67. package/dist/index.d.cts +5465 -2291
  68. package/dist/index.d.ts +5465 -2291
  69. package/dist/index.js +11047 -8858
  70. package/dist/index.js.map +1 -1
  71. package/dist/query-keys.d-Kw0JMoff.d.cts +308 -0
  72. package/dist/query-keys.d-Kw0JMoff.d.ts +308 -0
  73. package/dist/shell/index.cjs +78 -21
  74. package/dist/shell/index.d.cts +1 -1
  75. package/dist/shell/index.d.ts +1 -1
  76. package/dist/shell/index.js +6 -1
  77. package/dist/ui/index.cjs +200 -195
  78. package/dist/ui/index.d.cts +1 -1
  79. package/dist/ui/index.d.ts +1 -1
  80. package/dist/ui/index.js +4 -3
  81. package/dist/useAudioRecorder.d-CWFDsb_S.d.cts +778 -0
  82. package/dist/useAudioRecorder.d-CWFDsb_S.d.ts +778 -0
  83. package/dist/viewers/index.cjs +2 -2
  84. package/dist/viewers/index.js +1 -1
  85. package/package.json +13 -3
  86. package/dist/chunk-6MTKKT2O.cjs +0 -999
  87. package/dist/chunk-6MTKKT2O.cjs.map +0 -1
  88. package/dist/chunk-CEZCFQ47.js +0 -932
  89. package/dist/chunk-CEZCFQ47.js.map +0 -1
  90. package/dist/chunk-D66JCVBB.cjs.map +0 -1
  91. package/dist/chunk-EUC2BTNS.cjs.map +0 -1
  92. package/dist/chunk-GTJ667CP.cjs.map +0 -1
  93. package/dist/chunk-I5ZBQ63Y.js.map +0 -1
  94. package/dist/chunk-JSSKEXRR.js.map +0 -1
  95. package/dist/chunk-ON4PL6DQ.cjs.map +0 -1
  96. package/dist/chunk-QJHCVQ6C.js.map +0 -1
  97. package/dist/chunk-SVHGCX25.js.map +0 -1
@@ -1,44 +1,18 @@
1
1
  'use strict';
2
2
 
3
+ var chunkVAMPYLQ4_cjs = require('./chunk-VAMPYLQ4.cjs');
4
+ var chunkN73IMVFF_cjs = require('./chunk-N73IMVFF.cjs');
5
+ var chunkZWFMFOGP_cjs = require('./chunk-ZWFMFOGP.cjs');
3
6
  var chunkHUZB36QU_cjs = require('./chunk-HUZB36QU.cjs');
4
7
  var chunkHJDR5HEO_cjs = require('./chunk-HJDR5HEO.cjs');
5
8
  var chunkS6A6FSG7_cjs = require('./chunk-S6A6FSG7.cjs');
6
9
  var chunkRCKA7BEF_cjs = require('./chunk-RCKA7BEF.cjs');
7
- var react = require('react');
8
- var jsxRuntime = require('react/jsx-runtime');
9
10
  var vanilla = require('zustand/vanilla');
10
- var server = require('react-dom/server');
11
11
  var sonner = require('sonner');
12
- var zustand = require('zustand');
12
+ var jsxRuntime = require('react/jsx-runtime');
13
+ var react = require('react');
13
14
  var lucideReact = require('lucide-react');
14
15
 
15
- // src/host/merge.ts
16
- var MERGED = /* @__PURE__ */ new Set(["environment"]);
17
- var OWN_SESSION_SLOT = "__ownSession";
18
- function defined(record) {
19
- return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== void 0));
20
- }
21
- function mergeHostConfig(parent, config2) {
22
- const next = { ...parent };
23
- for (const [key, value] of Object.entries(defined(config2))) {
24
- if (key === "connection") continue;
25
- next[key] = MERGED.has(key) && value && typeof value === "object" ? { ...parent[key], ...defined(value) } : value;
26
- }
27
- return next;
28
- }
29
- function ArbiHost({
30
- config: config2,
31
- children
32
- }) {
33
- const parent = react.useContext(chunkRCKA7BEF_cjs.ArbiHostContext);
34
- const [ownSession] = react.useState(() => ({ current: null }));
35
- const value = react.useMemo(() => {
36
- const merged = mergeHostConfig(parent, config2);
37
- return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession };
38
- }, [parent, config2, ownSession]);
39
- const Connection = config2.connection?.Provider;
40
- return /* @__PURE__ */ jsxRuntime.jsx(chunkRCKA7BEF_cjs.ArbiHostContext.Provider, { value, children: Connection ? /* @__PURE__ */ jsxRuntime.jsx(Connection, { children }) : children });
41
- }
42
16
  var EMPTY = {
43
17
  query: "",
44
18
  results: [],
@@ -87,141 +61,24 @@ function persistSearchSession(key, storage = globalThis.localStorage, session =
87
61
  }
88
62
  });
89
63
  }
90
- var MAX_SESSION_NOTIFICATIONS = 5e3;
91
- var seq = 0;
92
- var uid = () => `n${Date.now().toString(36)}${(seq++).toString(36)}`;
93
- function capSession(items) {
94
- let session = 0;
95
- return items.filter((n) => n.source || ++session <= MAX_SESSION_NOTIFICATIONS);
96
- }
97
- var useNotify = zustand.create((set) => ({
98
- notifications: [],
99
- muted: false,
100
- setMuted: (muted) => set({ muted }),
101
- markRead: (id) => set((s) => ({
102
- notifications: s.notifications.map((n) => n.id === id ? { ...n, read: true } : n)
103
- })),
104
- markAllRead: () => set((s) => ({ notifications: s.notifications.map((n) => ({ ...n, read: true })) })),
105
- removeNotification: (id) => set((s) => ({ notifications: s.notifications.filter((n) => n.id !== id) })),
106
- removeNotifications: (ids) => {
107
- const drop = new Set(ids);
108
- set((s) => ({ notifications: s.notifications.filter((n) => !drop.has(n.id)) }));
109
- },
110
- clearNotifications: () => set({ notifications: [] }),
111
- seed: (items) => set({ notifications: items }),
112
- record: (note) => set((s) => ({ notifications: capSession([note, ...s.notifications]) })),
113
- syncSource: (source, items) => set((s) => ({
114
- notifications: [
115
- ...items.map((n) => ({ ...n, source })),
116
- ...s.notifications.filter((n) => n.source !== source)
117
- ].sort((a, b) => b.ts - a.ts)
118
- }))
119
- }));
120
- var config = {};
121
- function configureNotify(next) {
122
- config = { ...config, ...next };
123
- }
124
- function richMarkup(title) {
125
- try {
126
- return server.renderToStaticMarkup(title);
127
- } catch {
128
- return void 0;
64
+ var DEFAULT_TOAST_OPTIONS = {
65
+ classNames: {
66
+ toast: "group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg",
67
+ description: "group-[.toast]:text-muted-foreground",
68
+ actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
69
+ cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"
129
70
  }
130
- }
131
- var textOf = (html) => (html ?? "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
132
- function make(variant) {
133
- return (title, opts = {}) => {
134
- const { workspaceId } = opts;
135
- const ambient = opts.ambient ?? config.ambient ?? false;
136
- if (opts.toast !== false && !useNotify.getState().muted) {
137
- sonner.toast[variant](title, {
138
- description: opts.description,
139
- duration: opts.duration,
140
- action: opts.action,
141
- icon: opts.icon ?? (workspaceId ? config.workspaceIcon?.(workspaceId) : void 0),
142
- className: opts.className
143
- });
144
- }
145
- const id = uid();
146
- if (opts.record !== false) {
147
- const html = opts.html ?? (typeof title === "string" || title == null ? void 0 : richMarkup(title));
148
- useNotify.getState().record({
149
- id,
150
- // A rich toast still needs a READABLE title — "Passage copied: gamma-services p.1",
151
- // not "Notification" — so it comes from the rendered markup, tags stripped.
152
- title: opts.recordTitle ?? (typeof title === "string" ? title : textOf(html) || "Notification"),
153
- description: typeof opts.description === "string" ? opts.description : void 0,
154
- variant,
155
- ts: Date.now(),
156
- // Ambient activity is a log line, not a claim on attention: it never wears an unread dot.
157
- read: ambient,
158
- // Clicking the entry goes where the notification points: its action (when it has one),
159
- // an explicit link, or the workspace it happened in.
160
- href: opts.href ?? (workspaceId ? config.workspaceHref?.(workspaceId) : void 0),
161
- onSelect: opts.action?.onClick,
162
- actionLabel: opts.action ? String(opts.action.label) : void 0,
163
- workspaceId,
164
- html,
165
- ambient
166
- });
167
- }
168
- return id;
169
- };
170
- }
171
- var notify = {
172
- success: make("success"),
173
- error: make("error"),
174
- info: make("info"),
175
- warning: make("warning")
176
71
  };
177
- function seedNotifications(items) {
178
- useNotify.getState().seed(items);
179
- }
180
- function persistNotifyHistory(key, storage = globalThis.localStorage) {
181
- if (!storage) return () => {
182
- };
183
- try {
184
- const saved2 = JSON.parse(storage.getItem(key) ?? "null");
185
- if (saved2) {
186
- const known = new Set(useNotify.getState().notifications.map((n) => n.id));
187
- useNotify.setState((s) => ({
188
- muted: saved2.muted ?? s.muted,
189
- notifications: capSession(
190
- [
191
- ...s.notifications,
192
- ...(saved2.notifications ?? []).filter((n) => !n.source && !known.has(n.id))
193
- ].sort((a, b) => b.ts - a.ts)
194
- )
195
- }));
196
- }
197
- } catch {
198
- }
199
- let saved = [];
200
- let savedMuted;
201
- return useNotify.subscribe((s) => {
202
- const session = s.notifications.filter((n) => !n.source);
203
- if (s.muted === savedMuted && session.length === saved.length && session.every((n, i) => n === saved[i]))
204
- return;
205
- saved = session;
206
- savedMuted = s.muted;
207
- const notifications = session.map((n) => ({
208
- ...n,
209
- onSelect: void 0,
210
- actionLabel: void 0
211
- }));
212
- try {
213
- storage.setItem(key, JSON.stringify({ muted: s.muted, notifications }));
214
- } catch {
72
+ function Toaster({ toastOptions, ...props }) {
73
+ return /* @__PURE__ */ jsxRuntime.jsx(
74
+ sonner.Toaster,
75
+ {
76
+ className: "toaster group",
77
+ toastOptions: toastOptions ?? DEFAULT_TOAST_OPTIONS,
78
+ ...props
215
79
  }
216
- });
80
+ );
217
81
  }
218
- var selectUnread = (s) => s.notifications.filter((n) => !n.read && !n.ambient).length;
219
- var DEFAULT_NOTIFY_TONE = {
220
- success: "text-green-600",
221
- error: "text-destructive",
222
- warning: "text-amber-500",
223
- info: "text-blue-500"
224
- };
225
82
 
226
83
  // src/lib/format-relative-time.ts
227
84
  var FORMATTERS = /* @__PURE__ */ new Map();
@@ -278,13 +135,13 @@ function NotificationBell({
278
135
  align = "end"
279
136
  }) {
280
137
  const [open, setOpen] = react.useState(false);
281
- const notifications = useNotify((s) => s.notifications);
282
- const unread = useNotify(selectUnread);
283
- const markAllRead = useNotify((s) => s.markAllRead);
284
- const markRead = useNotify((s) => s.markRead);
285
- const muted = useNotify((s) => s.muted);
286
- const setMuted = useNotify((s) => s.setMuted);
287
- const tone = (v) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v];
138
+ const notifications = chunkVAMPYLQ4_cjs.useNotify((s) => s.notifications);
139
+ const unread = chunkVAMPYLQ4_cjs.useNotify(chunkVAMPYLQ4_cjs.selectUnread);
140
+ const markAllRead = chunkVAMPYLQ4_cjs.useNotify((s) => s.markAllRead);
141
+ const markRead = chunkVAMPYLQ4_cjs.useNotify((s) => s.markRead);
142
+ const muted = chunkVAMPYLQ4_cjs.useNotify((s) => s.muted);
143
+ const setMuted = chunkVAMPYLQ4_cjs.useNotify((s) => s.setMuted);
144
+ const tone = (v) => toneClassNames?.[v] ?? chunkVAMPYLQ4_cjs.DEFAULT_NOTIFY_TONE[v];
288
145
  const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT);
289
146
  return /* @__PURE__ */ jsxRuntime.jsxs(chunkHJDR5HEO_cjs.DropdownMenu, { open, onOpenChange: setOpen, children: [
290
147
  /* @__PURE__ */ jsxRuntime.jsx(chunkHJDR5HEO_cjs.DropdownMenuTrigger, { asChild: true, children: renderTrigger ? renderTrigger({
@@ -424,48 +281,198 @@ function NotificationBell({
424
281
  )
425
282
  ] });
426
283
  }
427
- var DEFAULT_TOAST_OPTIONS = {
428
- classNames: {
429
- toast: "group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg",
430
- description: "group-[.toast]:text-muted-foreground",
431
- actionButton: "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
432
- cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"
284
+ function ArbiHost({
285
+ config,
286
+ children
287
+ }) {
288
+ const parent = react.useContext(chunkRCKA7BEF_cjs.ArbiHostContext);
289
+ const [ownSession] = react.useState(() => ({ current: null }));
290
+ const value = react.useMemo(() => {
291
+ const merged = chunkN73IMVFF_cjs.mergeHostConfig(parent, config);
292
+ return merged[chunkN73IMVFF_cjs.OWN_SESSION_SLOT] ? merged : { ...merged, [chunkN73IMVFF_cjs.OWN_SESSION_SLOT]: ownSession };
293
+ }, [parent, config, ownSession]);
294
+ const Connection = config.connection?.Provider;
295
+ return /* @__PURE__ */ jsxRuntime.jsx(chunkRCKA7BEF_cjs.ArbiHostContext.Provider, { value, children: Connection ? /* @__PURE__ */ jsxRuntime.jsx(Connection, { children }) : children });
296
+ }
297
+
298
+ // src/chat/mentions.ts
299
+ var MAX_QUERY_LENGTH = 40;
300
+ function findMentionQuery(text, caret) {
301
+ const before = text.slice(0, caret);
302
+ const at = before.lastIndexOf("@");
303
+ if (at < 0) return null;
304
+ if (at > 0 && !/\s/.test(before[at - 1])) return null;
305
+ const query = before.slice(at + 1);
306
+ if (query.length > MAX_QUERY_LENGTH || query.includes("\n") || query.startsWith(" ")) return null;
307
+ return { start: at, query };
308
+ }
309
+ function filterMentionCandidates(candidates, query) {
310
+ const q = query.trim().toLowerCase();
311
+ if (!q) return candidates.slice();
312
+ const scored = [];
313
+ for (const c of candidates) {
314
+ const label = c.label.toLowerCase();
315
+ if (label.startsWith(q)) scored.push({ c, score: 0 });
316
+ else if (label.split(/\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 });
317
+ else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 });
433
318
  }
434
- };
435
- function Toaster({ toastOptions, ...props }) {
436
- return /* @__PURE__ */ jsxRuntime.jsx(
437
- sonner.Toaster,
438
- {
439
- className: "toaster group",
440
- toastOptions: toastOptions ?? DEFAULT_TOAST_OPTIONS,
441
- ...props
319
+ return scored.sort((a, b) => a.score - b.score).map((s) => s.c);
320
+ }
321
+ function insertMention(text, start, caret, label) {
322
+ const inserted = `@${label} `;
323
+ return {
324
+ text: text.slice(0, start) + inserted + text.slice(caret),
325
+ caret: start + inserted.length
326
+ };
327
+ }
328
+ function tokenRanges(text, label) {
329
+ const needle = `@${label}`;
330
+ const ranges = [];
331
+ let from = 0;
332
+ for (; ; ) {
333
+ const i = text.indexOf(needle, from);
334
+ if (i < 0) break;
335
+ const end = i + needle.length;
336
+ const startsToken = i === 0 || /\s|\(|\[/.test(text[i - 1]);
337
+ const endsToken = end === text.length || !/[\p{L}\p{N}_]/u.test(text[end]);
338
+ if (startsToken && endsToken) ranges.push([i, end]);
339
+ from = end;
340
+ }
341
+ return ranges;
342
+ }
343
+ function extractMentions(text, candidates) {
344
+ const taken = [];
345
+ const found = [];
346
+ const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length);
347
+ for (const c of byLength) {
348
+ if (!c.label) continue;
349
+ for (const [from, to] of tokenRanges(text, c.label)) {
350
+ if (taken.some(([a, b]) => from < b && to > a)) continue;
351
+ taken.push([from, to]);
352
+ if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from });
353
+ }
354
+ }
355
+ return found.sort((a, b) => a.at - b.at).map((f) => f.c);
356
+ }
357
+ function toMessageMentions(mentioned) {
358
+ return mentioned.map(
359
+ (c) => c.kind === "assistant" ? { type: "assistant" } : { type: "user", user_ext_id: c.id }
360
+ );
361
+ }
362
+ var MENTION_HREF_PREFIX = "#mention-";
363
+ function escapeLinkText(label) {
364
+ return label.replace(/[[\]\\]/g, (ch) => `\\${ch}`);
365
+ }
366
+ function linkMentions(content, mentions, assistantLabels = []) {
367
+ if (!mentions || mentions.length === 0 || !content) return content;
368
+ const targets = [];
369
+ for (const m of mentions) {
370
+ const id = m.type === "assistant" ? "assistant" : m.user_ext_id;
371
+ if (!id) continue;
372
+ const labels = m.type === "assistant" ? [m.label ?? "", ...assistantLabels] : [m.label ?? ""];
373
+ for (const label of labels) if (label) targets.push({ label, id });
374
+ }
375
+ targets.sort((a, b) => b.label.length - a.label.length);
376
+ const replacements = [];
377
+ for (const { label, id } of targets) {
378
+ for (const [from, to] of tokenRanges(content, label)) {
379
+ if (replacements.some((r) => from < r.to && to > r.from)) continue;
380
+ replacements.push({
381
+ from,
382
+ to,
383
+ text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`
384
+ });
442
385
  }
386
+ }
387
+ replacements.sort((a, b) => b.from - a.from);
388
+ let out = content;
389
+ for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to);
390
+ return out;
391
+ }
392
+ function mentionFromHref(href) {
393
+ if (!href?.startsWith(MENTION_HREF_PREFIX)) return null;
394
+ const id = href.slice(MENTION_HREF_PREFIX.length);
395
+ if (!id) return null;
396
+ return { kind: id === "assistant" ? "assistant" : "user", id };
397
+ }
398
+ function hasMessageBody(value, recipientLabel = "ARBI") {
399
+ const text = value.trim();
400
+ return !!text && text.toLowerCase() !== `@${recipientLabel}`.toLowerCase();
401
+ }
402
+ function savedDocumentIdFor(input) {
403
+ const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input;
404
+ if (!documentId || isDraft || isStreaming || isBlobArtifact) return null;
405
+ if (documentData?.wp_type !== "artifact" && !documentData?.file_name?.toLowerCase().endsWith(".docx"))
406
+ return null;
407
+ if (documentData.external_id !== documentId) return null;
408
+ return documentId;
409
+ }
410
+ var entries = [];
411
+ var listeners = /* @__PURE__ */ new Set();
412
+ function subscribe(listener) {
413
+ listeners.add(listener);
414
+ return () => listeners.delete(listener);
415
+ }
416
+ function emit() {
417
+ listeners.forEach((l) => l());
418
+ }
419
+ var top = () => entries[entries.length - 1];
420
+ function useRegisterOpenDocument(registration) {
421
+ const latest = react.useRef(registration);
422
+ react.useEffect(() => {
423
+ latest.current = registration;
424
+ });
425
+ const { documentId } = registration;
426
+ react.useEffect(() => {
427
+ if (!documentId) return;
428
+ const entry = { documentId, current: () => latest.current };
429
+ entries = [...entries, entry];
430
+ emit();
431
+ return () => {
432
+ entries = entries.filter((e) => e !== entry);
433
+ emit();
434
+ };
435
+ }, [documentId]);
436
+ }
437
+ function useOpenDocumentId() {
438
+ return react.useSyncExternalStore(
439
+ subscribe,
440
+ () => top()?.documentId ?? null,
441
+ () => null
443
442
  );
444
443
  }
444
+ function takeOpenDocumentForTurn(options) {
445
+ const entry = top();
446
+ if (!entry) return null;
447
+ const { shownId, showLive, workspaceId } = entry.current();
448
+ if (options?.workspaceId && workspaceId && options.workspaceId !== workspaceId) return null;
449
+ if (shownId && shownId !== entry.documentId && chunkZWFMFOGP_cjs.parseVersionRef(shownId).docId === entry.documentId)
450
+ showLive?.();
451
+ return entry.documentId;
452
+ }
445
453
 
446
- Object.defineProperty(exports, "toast", {
447
- enumerable: true,
448
- get: function () { return sonner.toast; }
449
- });
450
454
  exports.ArbiHost = ArbiHost;
451
- exports.DEFAULT_NOTIFY_TONE = DEFAULT_NOTIFY_TONE;
452
- exports.MAX_SESSION_NOTIFICATIONS = MAX_SESSION_NOTIFICATIONS;
455
+ exports.MENTION_HREF_PREFIX = MENTION_HREF_PREFIX;
453
456
  exports.NotificationBell = NotificationBell;
454
- exports.OWN_SESSION_SLOT = OWN_SESSION_SLOT;
455
457
  exports.Toaster = Toaster;
456
458
  exports.clearSearchSession = clearSearchSession;
457
- exports.configureNotify = configureNotify;
458
459
  exports.createSearchSession = createSearchSession;
460
+ exports.extractMentions = extractMentions;
461
+ exports.filterMentionCandidates = filterMentionCandidates;
462
+ exports.findMentionQuery = findMentionQuery;
459
463
  exports.formatRelativeTime = formatRelativeTime;
460
- exports.mergeHostConfig = mergeHostConfig;
461
- exports.notify = notify;
462
- exports.persistNotifyHistory = persistNotifyHistory;
464
+ exports.hasMessageBody = hasMessageBody;
465
+ exports.insertMention = insertMention;
466
+ exports.linkMentions = linkMentions;
467
+ exports.mentionFromHref = mentionFromHref;
463
468
  exports.persistSearchSession = persistSearchSession;
464
469
  exports.requestSearch = requestSearch;
465
- exports.seedNotifications = seedNotifications;
466
- exports.selectUnread = selectUnread;
470
+ exports.savedDocumentIdFor = savedDocumentIdFor;
467
471
  exports.sharedSearchSession = sharedSearchSession;
472
+ exports.takeOpenDocumentForTurn = takeOpenDocumentForTurn;
468
473
  exports.takePendingSearch = takePendingSearch;
469
- exports.useNotify = useNotify;
470
- //# sourceMappingURL=chunk-EUC2BTNS.cjs.map
471
- //# sourceMappingURL=chunk-EUC2BTNS.cjs.map
474
+ exports.toMessageMentions = toMessageMentions;
475
+ exports.useOpenDocumentId = useOpenDocumentId;
476
+ exports.useRegisterOpenDocument = useRegisterOpenDocument;
477
+ //# sourceMappingURL=chunk-ZI2VJOID.cjs.map
478
+ //# sourceMappingURL=chunk-ZI2VJOID.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/search/session.ts","../src/notifications/Toaster.tsx","../src/lib/format-relative-time.ts","../src/notifications/NotificationBell.tsx","../src/host/ArbiHost.tsx","../src/chat/mentions.ts","../src/chat/open-document.ts"],"names":["createStore","jsx","Sonner","CheckCircle2","XCircle","AlertTriangle","Info","useState","useNotify","selectUnread","DEFAULT_NOTIFY_TONE","jsxs","DropdownMenu","DropdownMenuTrigger","Bell","DropdownMenuContent","CheckCheck","cn","BellOff","DropdownMenuItem","X","ScrollArea","useContext","ArbiHostContext","useMemo","mergeHostConfig","OWN_SESSION_SLOT","useRef","useEffect","useSyncExternalStore","parseVersionRef"],"mappings":";;;;;;;;;;;;;;;AA8BA,IAAM,KAAA,GAAyD;AAAA,EAC7D,KAAA,EAAO,EAAA;AAAA,EACP,SAAS,EAAC;AAAA,EACV,QAAA,EAAU,KAAA;AAAA,EACV,MAAA,EAAQ,MAAA;AAAA,EACR,KAAA,EAAO,IAAA;AAAA,EACP,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,mBAAA,GAAqC;AACnD,EAAA,OAAOA,mBAAA,CAAgC,OAAO,EAAE,GAAG,OAAO,WAAA,EAAa,IAAA,EAAM,GAAA,EAAK,CAAA,EAAE,CAAE,CAAA;AACxF;AAGO,IAAM,sBAAqC,mBAAA;AAG3C,SAAS,kBAAA,CACd,WAAA,EACA,OAAA,GAAyB,mBAAA,EACnB;AACN,EAAA,OAAA,CAAQ,QAAA,CAAS,CAAC,CAAA,MAAO;AAAA,IACvB,GAAG,KAAA;AAAA,IACH,WAAA,EAAa,WAAA,KAAgB,MAAA,G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,MAAA,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAM,MAAM,KAAK,CAAA;AAC3C,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,UAAU,CAAC,CAAA;AACjB;AAGO,SAAS,iBAAA,GAAmC;AACjD,EAAA,OAAOC,0BAAA;AAAA,IACL,SAAA;AAAA,IACA,MAAM,GAAA,EAAI,EAAG,UAAA,IAAc,IAAA;AAAA,IAC3B,MAAM;AAAA,GACR;AACF;AAQO,SAAS,wBAAwB,OAAA,EAA0D;AAChG,EAAA,MAAM,QAAQ,GAAA,EAAI;AAClB,EAAA,IAAI,CAAC,OAAO,OAAO,IAAA;AACnB,EAAA,MAAM,EAAE,OAAA,EAAS,QAAA,EAAU,WAAA,EAAY,GAAI,MAAM,OAAA,EAAQ;AACzD,EAAA,IAAI,SAAS,WAAA,IAAe,WAAA,IAAe,OAAA,CAAQ,WAAA,KAAgB,aAAa,OAAO,IAAA;AACvF,EAAA,IACE,OAAA,IACA,YAAY,KAAA,CAAM,UAAA,IAClBC,kCAAgB,OAAO,CAAA,CAAE,UAAU,KAAA,CAAM,UAAA;AAEzC,IAAA,QAAA,IAAW;AACb,EAAA,OAAO,KAAA,CAAM,UAAA;AACf","file":"chunk-ZI2VJOID.cjs","sourcesContent":["/**\n * A search's state outside any component: the query last searched, its passages, and whether it\n * is running. A page that shows the shared session (`sharedSearchSession`) keeps its results when\n * it is left and opened again, another surface can hand it a query to run on arrival\n * ({@link requestSearch}), and {@link persistSearchSession} keeps the last query across reloads.\n */\nimport { createStore, type StoreApi } from 'zustand/vanilla'\nimport type { SearchChunk } from '@arbidocs/sdk/browser'\n\nexport type SearchStatus = 'idle' | 'running' | 'done' | 'error'\n\nexport interface SearchSessionState {\n /** The workspace the query and results belong to. */\n workspaceId: string | null\n /** The query last searched, or handed over to run. */\n query: string\n /** The last search's passages, best first. */\n results: SearchChunk[]\n /** A search has finished with results to show (cleared by {@link clearSearchSession}). */\n searched: boolean\n status: SearchStatus\n error: string | null\n /** A query handed over by {@link requestSearch}, run once by the page that shows the session. */\n pending: string | null\n /** Counts searches, so the reply to an older one never overwrites a newer one. */\n run: number\n}\n\nexport type SearchSession = StoreApi<SearchSessionState>\n\nconst EMPTY: Omit<SearchSessionState, 'workspaceId' | 'run'> = {\n query: '',\n results: [],\n searched: false,\n status: 'idle',\n error: null,\n pending: null,\n}\n\nexport function createSearchSession(): SearchSession {\n return createStore<SearchSessionState>(() => ({ ...EMPTY, workspaceId: null, run: 0 }))\n}\n\n/** The session a host's search page shows. */\nexport const sharedSearchSession: SearchSession = createSearchSession()\n\n/** Back to nothing searched (in `workspaceId` when given); a running search's reply is dropped. */\nexport function clearSearchSession(\n workspaceId?: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n session.setState((s) => ({\n ...EMPTY,\n workspaceId: workspaceId === undefined ? s.workspaceId : workspaceId,\n run: s.run + 1,\n }))\n}\n\n/**\n * Hand a query to the search page, which runs it when it shows the session (the user already\n * asked once; the page must not wait for a second Enter).\n */\nexport function requestSearch(\n query: string,\n workspaceId: string | null,\n session: SearchSession = sharedSearchSession\n): void {\n clearSearchSession(workspaceId, session)\n session.setState({ query, pending: query })\n}\n\n/** The handed-over query, once: the next call returns null. */\nexport function takePendingSearch(session: SearchSession = sharedSearchSession): string | null {\n const { pending } = session.getState()\n if (pending !== null) session.setState({ pending: null })\n return pending\n}\n\ninterface SavedSearch {\n query?: string\n workspaceId?: string | null\n}\n\n/**\n * Keep the last query (and its workspace) in `storage` under `key`, so the search box shows it\n * after a reload. Results are not kept. Returns the unsubscribe.\n */\nexport function persistSearchSession(\n key: string,\n storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = globalThis.localStorage,\n session: SearchSession = sharedSearchSession\n): () => void {\n if (!storage) return () => {}\n try {\n const saved = JSON.parse(storage.getItem(key) ?? 'null') as SavedSearch | null\n if (saved && typeof saved.query === 'string' && !session.getState().query)\n session.setState({ query: saved.query, workspaceId: saved.workspaceId ?? null })\n } catch {\n // Unreadable: start empty.\n }\n let last = ''\n return session.subscribe(({ query, workspaceId }) => {\n const next = JSON.stringify({ query, workspaceId })\n if (next === last) return\n last = next\n try {\n storage.setItem(key, next)\n } catch {\n // Storage full or blocked: the query is simply not kept.\n }\n })\n}\n","/**\n * Toaster — the one shared toast surface, built on sonner (the mature engine:\n * stacking, swipe-to-dismiss, a11y, timing). Mount once near the app root; any\n * code then calls `notify.*(...)` (or the re-exported `toast`) from anywhere.\n *\n * Firm-agnostic: every sonner `ToasterProps` passes through, so a consumer sets\n * its own `position` / `theme` / `toastOptions`. The defaults give a neutral\n * shadcn-token card that both apps can override.\n */\nimport { Toaster as Sonner, type ToasterProps } from 'sonner'\n\nexport type { ToasterProps }\n\nconst DEFAULT_TOAST_OPTIONS: ToasterProps['toastOptions'] = {\n classNames: {\n toast:\n 'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:rounded-lg',\n description: 'group-[.toast]:text-muted-foreground',\n actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',\n cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',\n },\n}\n\nexport function Toaster({ toastOptions, ...props }: ToasterProps) {\n return (\n <Sonner\n className=\"toaster group\"\n toastOptions={toastOptions ?? DEFAULT_TOAST_OPTIONS}\n {...props}\n />\n )\n}\n","/** Relative-time formatting shared by the notification bell, the DM kit and the app's thread lists\n * (no type imports, so the SDK-free `/shell` entry can use it). */\n\nconst FORMATTERS = new Map<Intl.RelativeTimeFormatStyle, Intl.RelativeTimeFormat>()\nconst DIVISIONS: Array<{ amount: number; unit: Intl.RelativeTimeFormatUnit }> = [\n { amount: 60, unit: 'seconds' },\n { amount: 60, unit: 'minutes' },\n { amount: 24, unit: 'hours' },\n { amount: 7, unit: 'days' },\n { amount: 4.34524, unit: 'weeks' },\n { amount: 12, unit: 'months' },\n { amount: Number.POSITIVE_INFINITY, unit: 'years' },\n]\n\nfunction formatter(style: Intl.RelativeTimeFormatStyle): Intl.RelativeTimeFormat {\n let f = FORMATTERS.get(style)\n if (!f) {\n f = new Intl.RelativeTimeFormat(undefined, { numeric: 'auto', style })\n FORMATTERS.set(style, f)\n }\n return f\n}\n\nexport interface FormatRelativeTimeOptions {\n /** The reference instant in epoch milliseconds (default: now). */\n now?: number\n /** `long` (default): \"2 hours ago\"; `short`: \"2 hr. ago\", for tight rows. */\n style?: Intl.RelativeTimeFormatStyle\n}\n\n/** Relative time of an ISO timestamp, past or future: \"2 hours ago\", \"in 3 days\", \"just now\".\n * Empty for an unparseable timestamp. */\nexport function formatRelativeTime(iso: string, options: FormatRelativeTimeOptions = {}): string {\n const then = Date.parse(iso)\n if (Number.isNaN(then)) return ''\n let duration = (then - (options.now ?? Date.now())) / 1000\n if (Math.abs(duration) < 45) return 'just now'\n for (const division of DIVISIONS) {\n if (Math.abs(duration) < division.amount) {\n return formatter(options.style ?? 'long').format(Math.round(duration), division.unit)\n }\n duration /= division.amount\n }\n return ''\n}\n","/**\n * NotificationBell — the topbar notification centre: a bell with an unread badge\n * that opens a dropdown of recorded entries (newest first) with an unread dot,\n * relative time and optional deep-link. \"Mark all read\" clears the badge. Backed\n * by the shared {@link useNotify} store (the same one the <Toaster/> renders).\n *\n * Firm-agnostic: navigation is a callback (`onNavigate`), styling tracks semantic\n * tokens, and per-variant glyph colours are overridable via `toneClassNames`.\n */\nimport { useState, type ReactElement } from 'react'\nimport {\n Bell,\n BellOff,\n CheckCheck,\n CheckCircle2,\n AlertTriangle,\n XCircle,\n Info,\n X,\n} from 'lucide-react'\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n} from '../ui/dropdown-menu'\nimport { ScrollArea } from '../ui/scroll-area'\nimport { cn } from '../lib/utils'\nimport { formatRelativeTime } from '../lib/format-relative-time'\nimport {\n useNotify,\n selectUnread,\n DEFAULT_NOTIFY_TONE,\n type NotifyVariant,\n type AppNotification,\n} from './notify-store'\n\nconst GLYPH: Record<NotifyVariant, typeof Info> = {\n success: CheckCircle2,\n error: XCircle,\n warning: AlertTriangle,\n info: Info,\n}\n\n/** Entries the panel lists, newest first. */\nconst BELL_LIMIT = 100\n\n/** What a custom bell trigger needs to render itself. */\nexport interface NotificationBellTriggerState {\n /** Unread count (0 when none). */\n unread: number\n /** Accessible name, including the count: \"Notifications, 2 unread\". */\n ariaLabel: string\n testId: string\n}\n\nexport interface NotificationBellProps {\n /**\n * Replaces the default icon button with the host's own trigger (for example a labelled sidebar\n * row). It must forward its ref and rest props: it is mounted as the dropdown trigger.\n */\n renderTrigger?: (state: NotificationBellTriggerState) => ReactElement\n /** Called with an entry's `href` when it's clicked (e.g. router navigate). */\n onNavigate?: (href: string) => void\n /** Open this entry in the host notification centre instead of following its link. */\n onSelectNotification?: (notification: AppNotification) => void\n /** Called after an entry is locally marked read — the hook for a backend\n * bridge to propagate read state upstream (filter by the ids it owns). */\n onMarkRead?: (id: string) => void\n /** Called after \"Mark all read\" — same upstream-propagation hook. */\n onMarkAllRead?: () => void\n /** Show the store's toast mute switch in the header — the bell is where notification\n * behaviour is controlled. */\n showMuteToggle?: boolean\n /** Override per-variant glyph colours (e.g. brand emerald for success). */\n toneClassNames?: Partial<Record<NotifyVariant, string>>\n emptyText?: string\n /** Footer link to the app's full notification surface. Omit to hide. */\n onViewAll?: () => void\n viewAllLabel?: string\n testId?: string\n /** Where the panel opens relative to the bell (a sidebar-footer bell opens upward). */\n side?: 'top' | 'right' | 'bottom' | 'left'\n align?: 'start' | 'center' | 'end'\n}\n\nexport function NotificationBell({\n renderTrigger,\n onNavigate,\n onSelectNotification,\n onMarkRead,\n onMarkAllRead,\n showMuteToggle = false,\n toneClassNames,\n emptyText = \"You're all caught up.\",\n onViewAll,\n viewAllLabel = 'View all',\n testId = 'notifications',\n side = 'bottom',\n align = 'end',\n}: NotificationBellProps) {\n const [open, setOpen] = useState(false)\n const notifications = useNotify((s) => s.notifications)\n const unread = useNotify(selectUnread)\n const markAllRead = useNotify((s) => s.markAllRead)\n const markRead = useNotify((s) => s.markRead)\n const muted = useNotify((s) => s.muted)\n const setMuted = useNotify((s) => s.setMuted)\n const tone = (v: NotifyVariant) => toneClassNames?.[v] ?? DEFAULT_NOTIFY_TONE[v]\n\n // Ambient entries (routine session activity — \"Opening workspace…\") are kept\n // for the log but never surfaced in the bell panel: they never badge and are\n // always filtered out here. The panel is the recent history; a host's\n // notification page (`onViewAll`) holds the rest.\n const visible = notifications.filter((n) => !n.ambient).slice(0, BELL_LIMIT)\n\n return (\n <DropdownMenu open={open} onOpenChange={setOpen}>\n <DropdownMenuTrigger asChild>\n {renderTrigger ? (\n renderTrigger({\n unread,\n ariaLabel: `Notifications${unread ? `, ${unread} unread` : ''}`,\n testId,\n })\n ) : (\n <button\n className=\"relative flex size-9 pointer-coarse:size-11 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n data-testid={testId}\n aria-label={`Notifications${unread ? `, ${unread} unread` : ''}`}\n title=\"Notifications\"\n >\n <Bell className=\"size-5\" />\n {unread > 0 && (\n <span\n className=\"absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-xs font-semibold leading-4 text-primary-foreground\"\n data-testid={`${testId}-badge`}\n >\n {unread > 9 ? '9+' : unread}\n </span>\n )}\n </button>\n )}\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align={align}\n side={side}\n sideOffset={8}\n collisionPadding={12}\n className=\"w-60 rounded-lg border-border/60 p-0 shadow-lg\"\n data-testid={`${testId}-panel`}\n data-topbar-popover=\"\"\n >\n <div className=\"flex items-center justify-between gap-3 border-b border-border px-3.5 py-2.5 pointer-coarse:py-0\">\n <p className=\"text-sm font-semibold text-foreground\">Notifications</p>\n <div className=\"flex items-center gap-3 pointer-coarse:gap-1\">\n {unread > 0 && (\n <button\n onClick={() => {\n markAllRead()\n onMarkAllRead?.()\n }}\n className=\"flex items-center gap-1 text-xs font-medium text-primary transition-colors hover:opacity-80 pointer-coarse:min-h-11 pointer-coarse:px-2\"\n data-testid={`${testId}-mark-all`}\n >\n <CheckCheck className=\"size-3.5\" /> Mark all read\n </button>\n )}\n {showMuteToggle && (\n <button\n onClick={() => setMuted(!muted)}\n aria-pressed={muted}\n title={muted ? 'Unmute notifications' : 'Mute notifications'}\n aria-label={muted ? 'Unmute notifications' : 'Mute notifications'}\n className={cn(\n 'flex size-6 items-center justify-center rounded-md transition-colors hover:bg-accent pointer-coarse:size-11',\n muted ? 'text-foreground' : 'text-muted-foreground hover:text-foreground'\n )}\n data-testid={`${testId}-mute`}\n >\n <BellOff className=\"size-3.5\" />\n </button>\n )}\n {/* Explicit close — the dropdown otherwise only dismisses via\n tap-outside/Escape, which isn't discoverable on touch and (at\n mobile width, see blocks.css) the panel covers most\n of the screen so there's nothing to tap outside of. Radix\n closes a DropdownMenu on any item select by default, so a\n plain item with no other effect doubles as a close button. */}\n <DropdownMenuItem\n className=\"flex size-6 items-center justify-center rounded-md p-0 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus:bg-accent pointer-coarse:size-11\"\n aria-label=\"Close notifications\"\n data-testid={`${testId}-close`}\n >\n <X className=\"size-3.5\" />\n </DropdownMenuItem>\n </div>\n </div>\n {muted && (\n <p\n className=\"border-b border-border/60 bg-amber-500/10 px-3.5 py-1.5 text-xs text-muted-foreground\"\n data-testid={`${testId}-muted-note`}\n >\n Toasts are muted — everything still lands here.\n </p>\n )}\n\n {visible.length === 0 ? (\n <div className=\"px-3.5 py-10 text-center text-sm text-muted-foreground\">{emptyText}</div>\n ) : (\n <ScrollArea className=\"max-h-[380px]\">\n <ul data-testid={`${testId}-list`}>\n {visible.map((n) => {\n const Glyph = GLYPH[n.variant]\n return (\n <li key={n.id}>\n <button\n onClick={() => {\n markRead(n.id)\n if (!n.read) onMarkRead?.(n.id)\n setOpen(false)\n if (onSelectNotification) {\n onSelectNotification(n)\n return\n }\n // The specific action wins over the generic deep link.\n if (n.onSelect) n.onSelect()\n else if (n.href) onNavigate?.(n.href)\n }}\n className={cn(\n 'flex w-full items-start gap-3 border-b border-border/60 px-3.5 py-3 text-left transition-colors hover:bg-accent',\n !n.read && 'bg-accent/40'\n )}\n data-testid={`${testId}-item`}\n data-notification-id={n.id}\n >\n <Glyph className={cn('mt-0.5 size-4 shrink-0', tone(n.variant))} />\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-sm font-medium leading-snug text-foreground\">\n {n.title}\n </p>\n {n.description && (\n <p className=\"mt-0.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground\">\n {n.description}\n </p>\n )}\n <p className=\"mt-1 text-xs text-muted-foreground/80\">\n {formatRelativeTime(new Date(n.ts).toISOString())}\n </p>\n </div>\n {!n.read && (\n <span className=\"mt-1.5 size-2 shrink-0 rounded-full bg-primary\" />\n )}\n </button>\n </li>\n )\n })}\n </ul>\n </ScrollArea>\n )}\n {onViewAll && (\n // A real menu item, not a bare button: selecting it must CLOSE the\n // dropdown on its way to the full surface.\n <DropdownMenuItem\n onClick={onViewAll}\n className=\"justify-center rounded-none border-t border-border px-3.5 py-2.5 text-xs font-medium text-primary focus:text-primary pointer-coarse:min-h-11\"\n data-testid={`${testId}-view-all`}\n >\n {viewAllLabel}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n","/**\n * `<ArbiHost config>`: the one place a host app hands its configuration to every hook and kit.\n *\n * <ArbiHost config={{ arbi, session, documents, calendar, mail, account, … }}>\n * <App />\n * </ArbiHost>\n *\n * Every field is optional and has a default (see `ArbiHostConfig`); a kit reads its domain from\n * the config (`useArbiHost().documents`, `useHost().billing` in blocks). A nested `<ArbiHost>`\n * overrides only the fields it gives and inherits the rest (`environment` field by field), for a\n * subtree that opens projects in its own tabs, say. There is no other host provider: a new domain\n * is a new optional field, never a new provider.\n *\n * SDK-free (this module, ./context and ./merge are all it reaches), so a marketing site that only sets the\n * blocks environment does not bundle the SDK.\n */\n\nimport { useContext, useMemo, useState, type ComponentType, type ReactNode } from 'react'\nimport { ArbiHostContext } from './context'\nimport { mergeHostConfig, OWN_SESSION_SLOT } from './merge'\n\n/** A sign-in layer mounted inside the host (`defaultHost` in `@arbidocs/blocks/connect`). */\nexport interface ArbiHostConnection {\n Provider: ComponentType<{ children: ReactNode }>\n}\n\nexport interface ArbiHostProps<Config extends object> {\n config: Config\n children?: ReactNode\n}\n\n/**\n * Provide the host configuration. Typed by the package it is imported from: `@arbidocs/react`'s\n * takes the react domains, `@arbidocs/blocks`' the blocks domains as well.\n */\nexport function ArbiHost<Config extends object>({\n config,\n children,\n}: ArbiHostProps<Config>): React.ReactElement {\n const parent = useContext(ArbiHostContext)\n // A top-level host without a session store gets its own, made on first use (useArbiSessionStore).\n const [ownSession] = useState(() => ({ current: null as unknown }))\n const value = useMemo(() => {\n const merged = mergeHostConfig(parent, config)\n return merged[OWN_SESSION_SLOT] ? merged : { ...merged, [OWN_SESSION_SLOT]: ownSession }\n }, [parent, config, ownSession])\n const Connection = (config as { connection?: ArbiHostConnection }).connection?.Provider\n return (\n <ArbiHostContext.Provider value={value}>\n {Connection ? <Connection>{children}</Connection> : children}\n </ArbiHostContext.Provider>\n )\n}\n","/**\n * @mentions in chat text: pure helpers shared by the composer (autocomplete, extraction) and\n * the message renderer (chips). No React, no SDK.\n *\n * A mention lives in two places: the readable `@Label` text in the message content, and a\n * structured entry on the message (`{ type, user_ext_id, label }`) that the server reads to share\n * the conversation and notify. The composer only ever inserts `@<label>` for a known candidate,\n * so the structured list can be recovered from the text at send time ({@link extractMentions});\n * the renderer turns each stored mention back into a chip ({@link linkMentions}).\n */\n\n/** Who can be mentioned: a workspace member, or the assistant. */\nexport type MentionKind = 'user' | 'assistant'\n\n/** One entry of the mention autocomplete. */\nexport interface MentionCandidate {\n /** User external id (`usr-…`) for a person; any stable key (e.g. `assistant`) for the assistant. */\n id: string\n kind: MentionKind\n /** Inserted as `@<label>`. For people this must be the server's display name (given + family). */\n label: string\n /** Secondary line in the menu (email, role, …). */\n description?: string\n}\n\n/** The structured mention a message carries (the API's `MessageMention`). */\nexport interface MessageMentionRef {\n type: MentionKind\n user_ext_id?: string | null\n label?: string | null\n}\n\n/** Longest text after `@` that still counts as a query in progress. */\nconst MAX_QUERY_LENGTH = 40\n\n/**\n * The `@query` the caret is in, if any: the `@` must start the text or follow whitespace, and the\n * query may contain spaces (names do) but no newline. Returns the index of the `@` and the query.\n */\nexport function findMentionQuery(\n text: string,\n caret: number\n): { start: number; query: string } | null {\n const before = text.slice(0, caret)\n const at = before.lastIndexOf('@')\n if (at < 0) return null\n if (at > 0 && !/\\s/.test(before[at - 1])) return null\n const query = before.slice(at + 1)\n if (query.length > MAX_QUERY_LENGTH || query.includes('\\n') || query.startsWith(' ')) return null\n return { start: at, query }\n}\n\n/** Candidates matching a query: label prefix (or word-prefix) matches, prefix matches first. */\nexport function filterMentionCandidates(\n candidates: ReadonlyArray<MentionCandidate>,\n query: string\n): MentionCandidate[] {\n const q = query.trim().toLowerCase()\n if (!q) return candidates.slice()\n const scored: Array<{ c: MentionCandidate; score: number }> = []\n for (const c of candidates) {\n const label = c.label.toLowerCase()\n if (label.startsWith(q)) scored.push({ c, score: 0 })\n else if (label.split(/\\s+/).some((word) => word.startsWith(q))) scored.push({ c, score: 1 })\n else if (c.description?.toLowerCase().startsWith(q)) scored.push({ c, score: 2 })\n }\n return scored.sort((a, b) => a.score - b.score).map((s) => s.c)\n}\n\n/** Replace the `@query` at `start…caret` with `@<label> `; returns the new text and caret. */\nexport function insertMention(\n text: string,\n start: number,\n caret: number,\n label: string\n): { text: string; caret: number } {\n const inserted = `@${label} `\n return {\n text: text.slice(0, start) + inserted + text.slice(caret),\n caret: start + inserted.length,\n }\n}\n\n/** Every `[from, to)` range where `@<label>` occurs as a whole token. */\nfunction tokenRanges(text: string, label: string): Array<[number, number]> {\n const needle = `@${label}`\n const ranges: Array<[number, number]> = []\n let from = 0\n for (;;) {\n const i = text.indexOf(needle, from)\n if (i < 0) break\n const end = i + needle.length\n const startsToken = i === 0 || /\\s|\\(|\\[/.test(text[i - 1])\n const endsToken = end === text.length || !/[\\p{L}\\p{N}_]/u.test(text[end])\n if (startsToken && endsToken) ranges.push([i, end])\n from = end\n }\n return ranges\n}\n\n/**\n * The candidates mentioned in `text`, in order of first appearance. Longer labels win overlaps,\n * so `@Bob Smith` is Bob Smith, not a separate `@Bob`.\n */\nexport function extractMentions(\n text: string,\n candidates: ReadonlyArray<MentionCandidate>\n): MentionCandidate[] {\n const taken: Array<[number, number]> = []\n const found: Array<{ c: MentionCandidate; at: number }> = []\n const byLength = [...candidates].sort((a, b) => b.label.length - a.label.length)\n for (const c of byLength) {\n if (!c.label) continue\n for (const [from, to] of tokenRanges(text, c.label)) {\n if (taken.some(([a, b]) => from < b && to > a)) continue\n taken.push([from, to])\n if (!found.some((f) => f.c.id === c.id)) found.push({ c, at: from })\n }\n }\n return found.sort((a, b) => a.at - b.at).map((f) => f.c)\n}\n\n/** The API payload for mentioned candidates. */\nexport function toMessageMentions(mentioned: ReadonlyArray<MentionCandidate>): MessageMentionRef[] {\n return mentioned.map((c) =>\n c.kind === 'assistant' ? { type: 'assistant' } : { type: 'user', user_ext_id: c.id }\n )\n}\n\n/** Fragment prefix of the links {@link linkMentions} writes. */\nexport const MENTION_HREF_PREFIX = '#mention-'\n\n/** Escape the characters that would end a markdown link text early. */\nfunction escapeLinkText(label: string): string {\n return label.replace(/[[\\]\\\\]/g, (ch) => `\\\\${ch}`)\n}\n\n/**\n * Turn each stored mention's `@<label>` in `content` into a markdown link\n * `[@<label>](#mention-<id>)`, so a markdown renderer can draw it as a chip (see\n * {@link mentionFromHref}). Text that no longer matches (a renamed user) stays plain text.\n * `assistantLabels` lists other names the assistant may have been mentioned by.\n */\nexport function linkMentions(\n content: string,\n mentions: ReadonlyArray<MessageMentionRef> | null | undefined,\n assistantLabels: ReadonlyArray<string> = []\n): string {\n if (!mentions || mentions.length === 0 || !content) return content\n const targets: Array<{ label: string; id: string }> = []\n for (const m of mentions) {\n const id = m.type === 'assistant' ? 'assistant' : m.user_ext_id\n if (!id) continue\n const labels = m.type === 'assistant' ? [m.label ?? '', ...assistantLabels] : [m.label ?? '']\n for (const label of labels) if (label) targets.push({ label, id })\n }\n targets.sort((a, b) => b.label.length - a.label.length)\n const replacements: Array<{ from: number; to: number; text: string }> = []\n for (const { label, id } of targets) {\n for (const [from, to] of tokenRanges(content, label)) {\n if (replacements.some((r) => from < r.to && to > r.from)) continue\n replacements.push({\n from,\n to,\n text: `[@${escapeLinkText(label)}](${MENTION_HREF_PREFIX}${id})`,\n })\n }\n }\n replacements.sort((a, b) => b.from - a.from)\n let out = content\n for (const r of replacements) out = out.slice(0, r.from) + r.text + out.slice(r.to)\n return out\n}\n\n/** The mention a `#mention-…` href points at, or null for any other href. */\nexport function mentionFromHref(\n href: string | null | undefined\n): { kind: MentionKind; id: string } | null {\n if (!href?.startsWith(MENTION_HREF_PREFIX)) return null\n const id = href.slice(MENTION_HREF_PREFIX.length)\n if (!id) return null\n return { kind: id === 'assistant' ? 'assistant' : 'user', id }\n}\n\n/** A recipient alone is not a message. */\nexport function hasMessageBody(value: string, recipientLabel = 'ARBI'): boolean {\n const text = value.trim()\n return !!text && text.toLowerCase() !== `@${recipientLabel}`.toLowerCase()\n}\n","import { useEffect, useRef, useSyncExternalStore } from 'react'\nimport { parseVersionRef } from '../artifacts/versions'\n\n/**\n * Drafting mode: the saved document open beside the chat is what a chat turn is about.\n *\n * A viewer registers the document it shows (`useRegisterOpenDocument`); every assistant turn names\n * it (`active_artifact_ext_id`, read with `takeOpenDocumentForTurn` as the question is sent), so the\n * server binds the live document to the turn: a Word document is read on demand and edited as\n * tracked changes in the open editor, and what the assistant saves becomes a child version of it.\n * The request carries a reference, never the content.\n *\n * The open document is always the subject, also while one of its earlier versions is on screen\n * read-only: a version still names its document. Sending a turn then returns the viewer to the live\n * document (`showLive`), where the assistant's edits appear as they are made. (Pinning a specific\n * version as a source is a separate feature: it does not go through here.)\n *\n * A module-level registry (not React context), like `useChatSurface`, so a viewer and a chat agree\n * wherever they sit in the tree; the most recently opened document wins and closing it hands back\n * to the one before. It is not the session state's viewing document (`useArbiSessionState`): it\n * holds what mounted viewers can draft in (saved documents only, with the callback that shows the\n * live one again), and a turn reads it outside React. A viewer on the session's viewing document\n * passes that as `shownId` (it may be a version reference, resolved here the same way as\n * `selectViewingDocumentId` does).\n */\n\n/** What a viewer knows about the document it shows. */\nexport interface SavedDocumentInput {\n /** The document (`doc-…`), never a version reference. */\n documentId: string | null | undefined\n /** An unsaved draft (client-minted id, no backend record). */\n isDraft: boolean\n /** Still streaming: nothing is persisted yet. */\n isStreaming: boolean\n /** An image, audio or video artifact: there is no text to draft in. */\n isBlobArtifact: boolean\n /** The loaded document record. */\n documentData:\n | { external_id?: string | null; wp_type?: string | null; file_name?: string | null }\n | null\n | undefined\n}\n\n/**\n * The saved, content-backed document a chat can draft in, or null. Only a saved artifact or Word\n * document counts: drafts, an artifact still streaming and blob artifacts do not.\n */\nexport function savedDocumentIdFor(input: SavedDocumentInput): string | null {\n const { documentId, isDraft, isStreaming, isBlobArtifact, documentData } = input\n if (!documentId || isDraft || isStreaming || isBlobArtifact) return null\n if (\n documentData?.wp_type !== 'artifact' &&\n !documentData?.file_name?.toLowerCase().endsWith('.docx')\n )\n return null\n // A stale record of the previously viewed document is not this one.\n if (documentData.external_id !== documentId) return null\n return documentId\n}\n\nexport interface OpenDocumentRegistration {\n /** The saved document the viewer shows (`doc-…`); null or empty registers nothing. */\n documentId: string | null | undefined\n /** What is on screen: the document itself, or one of its earlier versions (`doc-…@v2`). */\n shownId?: string | null\n /** Show the live document again. Called when a turn starts while an earlier version is shown. */\n showLive?: () => void\n /** The workspace the document belongs to; a chat in another workspace does not draft in it. */\n workspaceId?: string | null\n}\n\ninterface Entry {\n documentId: string\n current: () => OpenDocumentRegistration\n}\n\nlet entries: Entry[] = []\nconst listeners = new Set<() => void>()\n\nfunction subscribe(listener: () => void): () => void {\n listeners.add(listener)\n return () => listeners.delete(listener)\n}\n\nfunction emit() {\n listeners.forEach((l) => l())\n}\n\nconst top = (): Entry | undefined => entries[entries.length - 1]\n\n/**\n * Registers the document a viewer shows as the open document while the caller is mounted and\n * `documentId` is set. Pass `savedDocumentIdFor(...)`, or the id of a document known to be saved.\n */\nexport function useRegisterOpenDocument(registration: OpenDocumentRegistration): void {\n const latest = useRef(registration)\n useEffect(() => {\n latest.current = registration\n })\n const { documentId } = registration\n useEffect(() => {\n if (!documentId) return\n const entry: Entry = { documentId, current: () => latest.current }\n entries = [...entries, entry]\n emit()\n return () => {\n entries = entries.filter((e) => e !== entry)\n emit()\n }\n }, [documentId])\n}\n\n/** The open document's id, or null. Re-renders when another document opens or it closes. */\nexport function useOpenDocumentId(): string | null {\n return useSyncExternalStore(\n subscribe,\n () => top()?.documentId ?? null,\n () => null\n )\n}\n\n/**\n * The document an assistant turn about to be sent drafts in, or null. Call it once per turn as the\n * question is sent: when an earlier version of the document is on screen, the viewer returns to the\n * live document, where the assistant's edits appear. With `workspaceId`, a document registered in\n * another workspace is not named (and its viewer is left alone).\n */\nexport function takeOpenDocumentForTurn(options?: { workspaceId?: string | null }): string | null {\n const entry = top()\n if (!entry) return null\n const { shownId, showLive, workspaceId } = entry.current()\n if (options?.workspaceId && workspaceId && options.workspaceId !== workspaceId) return null\n if (\n shownId &&\n shownId !== entry.documentId &&\n parseVersionRef(shownId).docId === entry.documentId\n )\n showLive?.()\n return entry.documentId\n}\n"]}