@poolse/react 3.7.1 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use client';
2
- import { Poolse, toTombstone, markQuoteDeleted, safeUuid, mergeMessage, isCallLogMessage, applyThreadUpdate } from '@poolse/sdk';
3
- export { ApiError, AuthError, NetworkError, PoolseError, RateLimitedError, callLogDisplayFor, describeCallLog, formatCallDuration, formatCallLogPreview, isCallLogMessage, isMessageVisibleTo, isTombstone, mergeMessage, parseCallLog, parseCallLogBody, toTombstone } from '@poolse/sdk';
4
- import { createContext, useRef, useMemo, useEffect, useContext, useState, useCallback } from 'react';
2
+ import { Poolse, MessageQueuedError, toTombstone, markQuoteDeleted, safeUuid, mergeMessage, isCallLogMessage, applyLiveSegment, ApiError, applyThreadUpdate } from '@poolse/sdk';
3
+ export { ApiError, AuthError, MessageDiscardedError, MessageQueuedError, NetworkError, POOLSE_SERVICE_IDENTITY_PREFIX, Poolse, PoolseError, RateLimitedError, applyLiveSegment, callLogDisplayFor, captureErrorMessage, captureLabel, createIndexedDbStorage, describeCallLog, describeRecordingNotice, findInText, formatCallDuration, formatCallLogPreview, formatRecordingNoticePreview, groupTranscript, isCallLogMessage, isMessageVisibleTo, isServiceParticipant, isTombstone, memoryStorage, mergeMessage, parseCallLog, parseCallLogBody, parseRecordingNotice, parseRecordingNoticeBody, recordingNoticeDisplayFor, speakerName, toTombstone } from '@poolse/sdk';
4
+ import { createContext, useRef, useMemo, useEffect, useContext, useState, useCallback, useSyncExternalStore } from 'react';
5
5
  import { jsx } from 'react/jsx-runtime';
6
6
 
7
7
  // src/provider.tsx
@@ -10,6 +10,10 @@ import { jsx } from 'react/jsx-runtime';
10
10
  var ConversationsStore = class {
11
11
  constructor(chat) {
12
12
  this.chat = chat;
13
+ const cached = chat.cache.peekConversations();
14
+ if (cached && cached.length > 0) {
15
+ this.state = { ...this.state, conversations: cached, loading: false };
16
+ }
13
17
  }
14
18
  chat;
15
19
  state = {
@@ -28,6 +32,14 @@ var ConversationsStore = class {
28
32
  nextCursor = null;
29
33
  /** Whether rows beyond the first page are held. */
30
34
  pagedBeyondFirst = false;
35
+ destroyed = false;
36
+ hydrating = null;
37
+ /** Called by `chat.destroy()`. @internal */
38
+ destroy() {
39
+ this.destroyed = true;
40
+ this.deactivate();
41
+ this.listeners.clear();
42
+ }
31
43
  getSnapshot() {
32
44
  return this.state;
33
45
  }
@@ -77,6 +89,7 @@ var ConversationsStore = class {
77
89
  }
78
90
  /** Zero a conversation's unread and mention counts. */
79
91
  markRead(conversationId) {
92
+ this.chat.unread.apply(conversationId, 0, 0);
80
93
  this.setConversations(
81
94
  (prev) => patchRow(
82
95
  prev,
@@ -104,8 +117,11 @@ var ConversationsStore = class {
104
117
  this.setConversations((prev) => prepend(prev, conversation));
105
118
  }
106
119
  activate() {
107
- void this.load(!this.loaded).catch(() => {
120
+ if (this.destroyed) return;
121
+ const showing = this.state.conversations.length > 0;
122
+ void this.load(!this.loaded && !showing).catch(() => {
108
123
  });
124
+ if (!this.loaded && !showing) this.hydrate();
109
125
  let off = null;
110
126
  let boundId = null;
111
127
  const bind = (me) => {
@@ -122,6 +138,16 @@ var ConversationsStore = class {
122
138
  off?.();
123
139
  };
124
140
  }
141
+ // Show the stored list (a previous session's) while the first fetch
142
+ // is out — or instead of it, offline.
143
+ hydrate() {
144
+ this.hydrating ??= this.chat.cache.loadConversations().then((rows) => {
145
+ if (this.destroyed || this.loaded || !rows || rows.length === 0) return;
146
+ if (this.state.conversations.length > 0) return;
147
+ this.chat.timings._once("cachedConversations");
148
+ this.set({ ...this.state, conversations: rows, loading: false });
149
+ });
150
+ }
125
151
  deactivate() {
126
152
  this.unbind?.();
127
153
  this.unbind = null;
@@ -155,6 +181,7 @@ var ConversationsStore = class {
155
181
  if (this.inflight) return this.inflight;
156
182
  const run = this.chat.conversations.list().then(
157
183
  (list) => {
184
+ if (this.destroyed) return;
158
185
  this.loaded = true;
159
186
  let conversations = list.data;
160
187
  if (this.pagedBeyondFirst) {
@@ -175,6 +202,7 @@ var ConversationsStore = class {
175
202
  });
176
203
  },
177
204
  (err) => {
205
+ if (this.destroyed) return;
178
206
  this.set({
179
207
  ...this.state,
180
208
  loading: false,
@@ -192,6 +220,10 @@ var ConversationsStore = class {
192
220
  if (next !== this.state.conversations) this.set({ ...this.state, conversations: next });
193
221
  }
194
222
  set(state) {
223
+ if (state.conversations !== this.state.conversations) {
224
+ this.chat.unread.observe(state.conversations);
225
+ if (this.loaded) this.chat.cache.setConversations(state.conversations);
226
+ }
195
227
  this.state = state;
196
228
  for (const l of this.listeners) l();
197
229
  }
@@ -231,12 +263,27 @@ function mergeUpdated(prev, next, fromMe) {
231
263
  const rest = prev.slice(0, idx).concat(prev.slice(idx + 1));
232
264
  return [merged, ...rest];
233
265
  }
266
+ function conversationsStoreOf(chat) {
267
+ return chat.scoped("react:conversations", (c) => new ConversationsStore(c));
268
+ }
234
269
  var PoolseContext = createContext(null);
235
- function PoolseProvider({ config, trackActivity = true, children }) {
270
+ function PoolseProvider({
271
+ client,
272
+ config: configProp,
273
+ background,
274
+ trackActivity = true,
275
+ children
276
+ }) {
277
+ if (!client && !configProp) {
278
+ throw new Error("<PoolseProvider>: pass `client` or `config`.");
279
+ }
280
+ const config = configProp ?? { getToken: () => null };
236
281
  const configRef = useRef(config);
237
282
  configRef.current = config;
238
283
  const initialConnectionRef = useRef(null);
239
- const chat = useMemo(() => {
284
+ const externalRef = useRef(client !== void 0);
285
+ const ownChat = useMemo(() => {
286
+ if (externalRef.current) return null;
240
287
  const initial = configRef.current;
241
288
  initialConnectionRef.current = {
242
289
  apiUrl: initial.apiUrl,
@@ -264,6 +311,9 @@ function PoolseProvider({ config, trackActivity = true, children }) {
264
311
  ...initial.userResolver ? { userResolver: (id) => configRef.current.userResolver(id) } : {}
265
312
  });
266
313
  }, []);
314
+ const chat = client ?? ownChat;
315
+ if (!chat)
316
+ throw new Error("<PoolseProvider>: `client` was removed after mount; remount instead.");
267
317
  if (process.env.NODE_ENV !== "production") {
268
318
  useEffect(() => {
269
319
  const initial = initialConnectionRef.current;
@@ -276,17 +326,22 @@ function PoolseProvider({ config, trackActivity = true, children }) {
276
326
  }, [config.apiUrl, config.wsUrl, config.socketPath]);
277
327
  }
278
328
  useEffect(() => {
329
+ if (!ownChat) return;
279
330
  return () => {
280
- chat.destroy();
331
+ void ownChat.destroy();
281
332
  };
282
- }, [chat]);
333
+ }, [ownChat]);
334
+ useEffect(() => {
335
+ if (background === void 0) return;
336
+ chat.setBackground(background);
337
+ }, [chat, background]);
283
338
  const trackActivityRef = useRef(trackActivity);
284
339
  useEffect(() => {
285
340
  const opts = trackActivityRef.current;
286
341
  if (opts === false) return;
287
342
  return chat.presence.trackActivity(opts === true ? {} : opts);
288
343
  }, [chat]);
289
- const value = useMemo(() => ({ chat, conversations: new ConversationsStore(chat) }), [chat]);
344
+ const value = useMemo(() => ({ chat, conversations: conversationsStoreOf(chat) }), [chat]);
290
345
  return /* @__PURE__ */ jsx(PoolseContext.Provider, { value, children });
291
346
  }
292
347
  function usePoolse() {
@@ -295,6 +350,9 @@ function usePoolse() {
295
350
  function useConversationsStore() {
296
351
  return usePoolseContext("useConversations").conversations;
297
352
  }
353
+ function useOptionalPoolse() {
354
+ return useContext(PoolseContext)?.chat ?? null;
355
+ }
298
356
  function usePoolseContext(hook) {
299
357
  const value = useContext(PoolseContext);
300
358
  if (!value) {
@@ -335,42 +393,8 @@ function useMe() {
335
393
  }, [chat]);
336
394
  return state;
337
395
  }
338
- function useConversation(id) {
339
- const chat = usePoolse();
340
- const [conversation, setConversation] = useState(null);
341
- const [loading, setLoading] = useState(id !== null);
342
- const [error, setError] = useState(null);
343
- const fetcher = useCallback(
344
- async (signal) => {
345
- if (id === null) return;
346
- setLoading(true);
347
- setError(null);
348
- try {
349
- const conv = await chat.conversations.one(id).show(signal);
350
- setConversation(conv);
351
- } catch (err) {
352
- if (err?.name === "AbortError") return;
353
- setError(err instanceof Error ? err : new Error(String(err)));
354
- } finally {
355
- setLoading(false);
356
- }
357
- },
358
- [chat, id]
359
- );
360
- useEffect(() => {
361
- if (id === null) {
362
- setConversation(null);
363
- setLoading(false);
364
- setError(null);
365
- return;
366
- }
367
- const controller = new AbortController();
368
- void fetcher(controller.signal);
369
- return () => controller.abort();
370
- }, [fetcher, id]);
371
- const refetch = useCallback(() => fetcher(), [fetcher]);
372
- return { conversation, loading, error, refetch };
373
- }
396
+
397
+ // src/use-conversations.ts
374
398
  function useConversations() {
375
399
  const store = useConversationsStore();
376
400
  useMe();
@@ -415,6 +439,189 @@ function countsOf(conversations, key) {
415
439
  }
416
440
  return out;
417
441
  }
442
+
443
+ // src/use-unread.ts
444
+ function useUnreadTotals(client) {
445
+ const fromContext = useOptionalPoolse();
446
+ const chat = client ?? fromContext;
447
+ if (!chat) {
448
+ throw new Error("useUnreadTotals(): pass a client, or render inside a <PoolseProvider>.");
449
+ }
450
+ const subscribe = useCallback((fn) => chat.unread.subscribe(fn), [chat]);
451
+ const totals = useSyncExternalStore(subscribe, () => chat.unread.get());
452
+ const refresh = useCallback(() => chat.unread.refresh(), [chat]);
453
+ return useMemo(() => ({ ...totals, refresh }), [totals, refresh]);
454
+ }
455
+ function useUnreadQueue(opts = {}) {
456
+ const chat = usePoolse();
457
+ const { conversations, markConversationRead } = useConversations();
458
+ const { mentionsFirst = false, filter } = opts;
459
+ const [skipped, setSkipped] = useState(() => /* @__PURE__ */ new Set());
460
+ const [currentId, setCurrentId] = useState(null);
461
+ const queue = useMemo(
462
+ () => orderUnread(conversations, { mentionsFirst, ...filter ? { filter } : {} }),
463
+ [conversations, mentionsFirst, filter]
464
+ );
465
+ const offered = useMemo(() => queue.filter((c) => !skipped.has(c.id)), [queue, skipped]);
466
+ const pinned = currentId ? conversations.find((c) => c.id === currentId) ?? null : null;
467
+ const current = pinned ?? offered[0] ?? null;
468
+ useEffect(() => {
469
+ if (currentId && !pinned) setCurrentId(null);
470
+ }, [currentId, pinned]);
471
+ const markRead = useCallback(
472
+ async (conversationId) => {
473
+ markConversationRead(conversationId);
474
+ const page = await chat.conversations.one(conversationId).messages.list({ limit: 1 });
475
+ const latest = page.data[0];
476
+ if (latest) await chat.conversations.one(conversationId).messages.markRead(latest.id);
477
+ },
478
+ [chat, markConversationRead]
479
+ );
480
+ const after = (id) => offered.find((c) => c.id !== id) ?? null;
481
+ const next = () => {
482
+ if (current) void markRead(current.id).catch(() => {
483
+ });
484
+ const following = after(current?.id);
485
+ setCurrentId(following?.id ?? null);
486
+ return following;
487
+ };
488
+ const skip = () => {
489
+ const id = current?.id;
490
+ if (id) setSkipped((s) => new Set(s).add(id));
491
+ const following = after(id);
492
+ setCurrentId(following?.id ?? null);
493
+ return following;
494
+ };
495
+ const reset = useCallback(() => setSkipped(/* @__PURE__ */ new Set()), []);
496
+ return {
497
+ queue,
498
+ current,
499
+ remaining: offered.filter((c) => c.id !== current?.id).length,
500
+ next,
501
+ skip,
502
+ markRead,
503
+ reset
504
+ };
505
+ }
506
+ function orderUnread(conversations, opts = {}) {
507
+ const unread = conversations.filter(
508
+ (c) => (c.unread_count ?? 0) > 0 && (!opts.filter || opts.filter(c))
509
+ );
510
+ const at = (c) => c.last_message_at ? Date.parse(c.last_message_at) : 0;
511
+ return unread.sort((a, b) => {
512
+ if (opts.mentionsFirst) {
513
+ const ma = (a.mention_unread_count ?? 0) > 0 ? 1 : 0;
514
+ const mb = (b.mention_unread_count ?? 0) > 0 ? 1 : 0;
515
+ if (ma !== mb) return mb - ma;
516
+ }
517
+ return at(b) - at(a);
518
+ });
519
+ }
520
+ function useOutbox(opts = {}) {
521
+ const fromContext = useOptionalPoolse();
522
+ const chat = opts.client ?? fromContext;
523
+ if (!chat) throw new Error("useOutbox(): pass a client, or render inside a <PoolseProvider>.");
524
+ const subscribe = useCallback((fn) => chat.outbox.subscribe(fn), [chat]);
525
+ const all = useSyncExternalStore(subscribe, () => chat.outbox.entries());
526
+ const { conversationId } = opts;
527
+ const entries = useMemo(
528
+ () => conversationId ? all.filter((e) => e.conversationId === conversationId) : all,
529
+ [all, conversationId]
530
+ );
531
+ const retry = useCallback(
532
+ async (id) => {
533
+ try {
534
+ await chat.outbox.retry(id);
535
+ } catch (err) {
536
+ if (!(err instanceof MessageQueuedError)) throw err;
537
+ }
538
+ },
539
+ [chat]
540
+ );
541
+ const remove = useCallback((id) => chat.outbox.remove(id), [chat]);
542
+ const flush = useCallback(() => chat.outbox.flush(), [chat]);
543
+ return {
544
+ entries,
545
+ pending: entries.filter((e) => e.status !== "failed").length,
546
+ failed: entries.filter((e) => e.status === "failed").length,
547
+ retry,
548
+ remove,
549
+ flush
550
+ };
551
+ }
552
+ function useClientTimings(client) {
553
+ const fromContext = useOptionalPoolse();
554
+ const chat = client ?? fromContext;
555
+ if (!chat) {
556
+ throw new Error("useClientTimings(): pass a client, or render inside a <PoolseProvider>.");
557
+ }
558
+ const snapshot = useRef(null);
559
+ const subscribe = useCallback(
560
+ (fn) => chat.timings.on(() => {
561
+ snapshot.current = null;
562
+ fn();
563
+ }),
564
+ [chat]
565
+ );
566
+ const get = () => {
567
+ if (!snapshot.current || snapshot.current.chat !== chat) {
568
+ snapshot.current = { chat, value: chat.timings.get() };
569
+ }
570
+ return snapshot.current.value;
571
+ };
572
+ return useSyncExternalStore(subscribe, get);
573
+ }
574
+
575
+ // src/conversation-search.ts
576
+ function filterConversations(conversations, query, opts = {}) {
577
+ const needle = query.trim().toLowerCase();
578
+ if (!needle) return conversations.slice();
579
+ return conversations.filter((c) => {
580
+ const hay = [c.name ?? "", c.last_message_preview ?? ""];
581
+ for (const ext of c.member_external_ids ?? []) {
582
+ if (ext === opts.meExternalId) continue;
583
+ hay.push(ext);
584
+ if (opts.labelFor) hay.push(opts.labelFor(ext));
585
+ }
586
+ return hay.some((h) => h.toLowerCase().includes(needle));
587
+ });
588
+ }
589
+ function useConversation(id) {
590
+ const chat = usePoolse();
591
+ const [conversation, setConversation] = useState(null);
592
+ const [loading, setLoading] = useState(id !== null);
593
+ const [error, setError] = useState(null);
594
+ const fetcher = useCallback(
595
+ async (signal) => {
596
+ if (id === null) return;
597
+ setLoading(true);
598
+ setError(null);
599
+ try {
600
+ const conv = await chat.conversations.one(id).show(signal);
601
+ setConversation(conv);
602
+ } catch (err) {
603
+ if (err?.name === "AbortError") return;
604
+ setError(err instanceof Error ? err : new Error(String(err)));
605
+ } finally {
606
+ setLoading(false);
607
+ }
608
+ },
609
+ [chat, id]
610
+ );
611
+ useEffect(() => {
612
+ if (id === null) {
613
+ setConversation(null);
614
+ setLoading(false);
615
+ setError(null);
616
+ return;
617
+ }
618
+ const controller = new AbortController();
619
+ void fetcher(controller.signal);
620
+ return () => controller.abort();
621
+ }, [fetcher, id]);
622
+ const refetch = useCallback(() => fetcher(), [fetcher]);
623
+ return { conversation, loading, error, refetch };
624
+ }
418
625
  function useMembers(conversationId) {
419
626
  const chat = usePoolse();
420
627
  const [members, setMembers] = useState([]);
@@ -515,10 +722,14 @@ function useMessages(conversationId) {
515
722
  const chat = usePoolse();
516
723
  const conversationsStore = useConversationsStore();
517
724
  const { me } = useMe();
518
- const [messages, setMessages] = useState([]);
519
- const [loading, setLoading] = useState(true);
725
+ const [messages, setMessages] = useState(
726
+ () => initialRows(chat, conversationId) ?? []
727
+ );
728
+ const [loading, setLoading] = useState(() => !initialRows(chat, conversationId));
520
729
  const [error, setError] = useState(null);
521
730
  const [hasMore, setHasMore] = useState(true);
731
+ const [fromCache, setFromCache] = useState(() => !!chat.cache.peekMessages(conversationId));
732
+ const rowsForRef = useRef(null);
522
733
  const oldestSequenceRef = useRef(null);
523
734
  const messagesRef = useRef(messages);
524
735
  messagesRef.current = messages;
@@ -529,33 +740,77 @@ function useMessages(conversationId) {
529
740
  meIdRef.current = me?.id ?? null;
530
741
  const meExternalIdRef = useRef(me?.external_id ?? null);
531
742
  meExternalIdRef.current = me?.external_id ?? null;
743
+ useEffect(() => {
744
+ if (rowsForRef.current !== conversationId) return;
745
+ if (messages.some((m) => m.conversation_id !== conversationId)) return;
746
+ if (loading) return;
747
+ chat.cache.setMessages(conversationId, messages);
748
+ }, [chat, conversationId, messages, loading]);
532
749
  useEffect(() => {
533
750
  let cancelled = false;
534
- setLoading(true);
535
- setMessages([]);
751
+ let fresh = false;
752
+ const cached = chat.cache.peekMessages(conversationId);
753
+ rowsForRef.current = conversationId;
536
754
  setError(null);
537
755
  setHasMore(true);
538
- oldestSequenceRef.current = null;
756
+ if (cached) {
757
+ setMessages(withOutbox(cached, chat, conversationId));
758
+ setLoading(false);
759
+ setFromCache(true);
760
+ oldestSequenceRef.current = cached[0]?.sequence ?? null;
761
+ chat.timings._once("cachedMessages");
762
+ } else {
763
+ setLoading(true);
764
+ setMessages(withOutbox([], chat, conversationId));
765
+ setFromCache(false);
766
+ oldestSequenceRef.current = null;
767
+ void chat.cache.loadMessages(conversationId).then((stored) => {
768
+ if (cancelled || fresh || !stored || stored.length === 0) return;
769
+ setMessages(withOutbox(stored, chat, conversationId));
770
+ setLoading(false);
771
+ setError(null);
772
+ setFromCache(true);
773
+ oldestSequenceRef.current = stored[0]?.sequence ?? null;
774
+ chat.timings._once("cachedMessages");
775
+ });
776
+ }
539
777
  const handle = chat.conversations.one(conversationId).messages;
540
778
  handle.list({ limit: PAGE_SIZE }).then((page) => {
541
779
  if (cancelled) return;
780
+ fresh = true;
542
781
  const ordered = [...page.data].reverse();
543
- setMessages(ordered);
782
+ setMessages((prev) => keepLocal(ordered, prev));
544
783
  setHasMore(page.data.length === PAGE_SIZE);
545
784
  oldestSequenceRef.current = ordered[0]?.sequence ?? null;
546
785
  setLoading(false);
786
+ setFromCache(false);
547
787
  }).catch((err) => {
548
788
  if (cancelled) return;
789
+ if (chat.cache.peekMessages(conversationId)) {
790
+ setLoading(false);
791
+ return;
792
+ }
549
793
  setError(err instanceof Error ? err : new Error(String(err)));
550
794
  setLoading(false);
551
795
  });
552
796
  refetchRef.current = async () => {
553
797
  const page = await handle.list({ limit: PAGE_SIZE });
554
798
  const ordered = [...page.data].reverse();
555
- setMessages(ordered);
799
+ setMessages((prev) => keepLocal(ordered, prev));
556
800
  setHasMore(page.data.length === PAGE_SIZE);
557
801
  oldestSequenceRef.current = ordered[0]?.sequence ?? null;
802
+ setFromCache(false);
558
803
  };
804
+ const syncOutbox = () => {
805
+ if (cancelled) return;
806
+ const entries = chat.outbox.entries(conversationId);
807
+ setMessages((prev) => applyOutbox(prev, entries));
808
+ };
809
+ const offOutbox = chat.outbox.subscribe(syncOutbox);
810
+ const offSent = chat.outbox.onSent((entry, sent) => {
811
+ if (cancelled || entry.conversationId !== conversationId) return;
812
+ setMessages((prev) => upsertById(prev, sent));
813
+ });
559
814
  const conv = chat.realtime.conversation(conversationId);
560
815
  const offNew = conv.onMessage((msg) => {
561
816
  if (msg.thread_root_id) {
@@ -594,7 +849,10 @@ function useMessages(conversationId) {
594
849
  connectedBefore ||= wasConnected;
595
850
  if (!reconnected || cancelled) return;
596
851
  handle.list({ limit: PAGE_SIZE }).then((page) => {
597
- if (!cancelled) setMessages((prev) => mergeLatest(prev, page.data));
852
+ if (!cancelled) {
853
+ setMessages((prev) => mergeLatest(prev, page.data));
854
+ setFromCache(false);
855
+ }
598
856
  }).catch(() => {
599
857
  });
600
858
  });
@@ -605,6 +863,8 @@ function useMessages(conversationId) {
605
863
  offDeleted();
606
864
  offThread();
607
865
  offStatus();
866
+ offOutbox();
867
+ offSent();
608
868
  };
609
869
  }, [chat, conversationId]);
610
870
  const loadMore = useCallback(async () => {
@@ -686,6 +946,12 @@ function useMessages(conversationId) {
686
946
  inserted_at: (/* @__PURE__ */ new Date()).toISOString(),
687
947
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
688
948
  };
949
+ if (chat.outboxEnabled) {
950
+ setMessages((prev) => upsertById(prev, { ...tempMsg, local_status: "sending" }));
951
+ const sent = await chat.outbox.send(conversationId, { ...attrs, id }, tempMsg);
952
+ setMessages((prev) => upsertById(prev, sent));
953
+ return sent;
954
+ }
689
955
  setMessages((prev) => [...prev, tempMsg]);
690
956
  try {
691
957
  const sent = await chat.conversations.one(conversationId).messages.send({ ...attrs, id });
@@ -751,6 +1017,24 @@ function useMessages(conversationId) {
751
1017
  },
752
1018
  [chat, conversationId, conversationsStore]
753
1019
  );
1020
+ const retry = useCallback(
1021
+ async (messageId) => {
1022
+ try {
1023
+ await chat.outbox.retry(messageId);
1024
+ } catch (err) {
1025
+ if (err instanceof MessageQueuedError) return;
1026
+ throw err;
1027
+ }
1028
+ },
1029
+ [chat]
1030
+ );
1031
+ const discard = useCallback(
1032
+ (messageId) => {
1033
+ chat.outbox.remove(messageId);
1034
+ setMessages((prev) => prev.filter((m) => m.id !== messageId || !m.local_status));
1035
+ },
1036
+ [chat]
1037
+ );
754
1038
  const refetch = useCallback(async () => {
755
1039
  const fn = refetchRef.current;
756
1040
  if (!fn) return;
@@ -764,12 +1048,37 @@ function useMessages(conversationId) {
764
1048
  loadMore,
765
1049
  loadUntil,
766
1050
  send,
1051
+ retry,
1052
+ discard,
767
1053
  edit,
768
1054
  delete: deleteMessage,
769
1055
  markReadUpTo,
1056
+ fromCache,
770
1057
  refetch
771
1058
  };
772
1059
  }
1060
+ function initialRows(chat, conversationId) {
1061
+ const cached = chat.cache.peekMessages(conversationId);
1062
+ return cached ? withOutbox(cached, chat, conversationId) : null;
1063
+ }
1064
+ function withOutbox(rows, chat, conversationId) {
1065
+ return applyOutbox(rows, chat.outbox.entries(conversationId));
1066
+ }
1067
+ function applyOutbox(prev, entries) {
1068
+ const byId = new Map(entries.map((e) => [e.id, e]));
1069
+ let next = prev.filter((m) => !m.local_status || byId.has(m.id));
1070
+ for (const entry of entries) {
1071
+ const idx = next.findIndex((m) => m.id === entry.id);
1072
+ if (idx !== -1 && !next[idx].local_status) continue;
1073
+ if (idx !== -1 && next[idx] === entry.message) continue;
1074
+ next = upsertById(next, entry.message);
1075
+ }
1076
+ return next.length === prev.length && next.every((m, i) => m === prev[i]) ? prev : next;
1077
+ }
1078
+ function keepLocal(page, prev) {
1079
+ const local = prev.filter((m) => m.local_status && !page.some((p) => p.id === m.id));
1080
+ return local.length === 0 ? page : [...page, ...local];
1081
+ }
773
1082
  function patchById(prev, id, fn) {
774
1083
  const idx = prev.findIndex((m) => m.id === id);
775
1084
  if (idx === -1) return prev;
@@ -1458,6 +1767,7 @@ function useCallRoom(conversationId, opts) {
1458
1767
  const [activeDevices, setActiveDevices] = useState({});
1459
1768
  const [error, setError] = useState(null);
1460
1769
  const [sfuAvailable, setSfuAvailable] = useState(null);
1770
+ const [canPublish, setCanPublish] = useState(true);
1461
1771
  const optsRef = useRef(opts);
1462
1772
  optsRef.current = opts;
1463
1773
  const joined = useRef(false);
@@ -1469,7 +1779,8 @@ function useCallRoom(conversationId, opts) {
1469
1779
  ...optsRef.current.video !== void 0 ? { video: optsRef.current.video } : {},
1470
1780
  ...optsRef.current.muted !== void 0 ? { muted: optsRef.current.muted } : {},
1471
1781
  ...optsRef.current.facing !== void 0 ? { facing: optsRef.current.facing } : {},
1472
- ...optsRef.current.aloneGraceMs !== void 0 ? { aloneGraceMs: optsRef.current.aloneGraceMs } : {}
1782
+ ...optsRef.current.aloneGraceMs !== void 0 ? { aloneGraceMs: optsRef.current.aloneGraceMs } : {},
1783
+ ...optsRef.current.republishOnPermission !== void 0 ? { republishOnPermission: optsRef.current.republishOnPermission } : {}
1473
1784
  });
1474
1785
  }, [poolse, conversationId]);
1475
1786
  const refreshDevices = useCallback((target) => {
@@ -1494,6 +1805,7 @@ function useCallRoom(conversationId, opts) {
1494
1805
  setScreen(target.isScreenShareEnabled());
1495
1806
  setCanShare(target.canShareScreen());
1496
1807
  setFacing(target.getFacingMode());
1808
+ setCanPublish(target.canPublish());
1497
1809
  }, []);
1498
1810
  useEffect(() => {
1499
1811
  if (!room) {
@@ -1513,12 +1825,14 @@ function useCallRoom(conversationId, opts) {
1513
1825
  const offAlone = room.onAlone(() => setAlone(true));
1514
1826
  const offDevices = room.onDevices(() => refreshDevices(room));
1515
1827
  const offError = room.onError(setError);
1828
+ const offPublish = room.onPublishPermission(() => sync(room));
1516
1829
  return () => {
1517
1830
  offStatus();
1518
1831
  offRoster();
1519
1832
  offAlone();
1520
1833
  offDevices();
1521
1834
  offError();
1835
+ offPublish();
1522
1836
  held.current = null;
1523
1837
  if (joined.current) {
1524
1838
  joined.current = false;
@@ -1611,6 +1925,11 @@ function useCallRoom(conversationId, opts) {
1611
1925
  },
1612
1926
  [room]
1613
1927
  );
1928
+ const republish = useCallback(async () => {
1929
+ if (!room) return;
1930
+ await room.republish();
1931
+ sync(room);
1932
+ }, [room, sync]);
1614
1933
  return {
1615
1934
  status,
1616
1935
  participants,
@@ -1635,9 +1954,110 @@ function useCallRoom(conversationId, opts) {
1635
1954
  setMicrophoneEnabled,
1636
1955
  toggleMic,
1637
1956
  setScreenShareEnabled,
1638
- toggleScreenShare
1957
+ toggleScreenShare,
1958
+ canPublish,
1959
+ republish
1639
1960
  };
1640
1961
  }
1962
+ var IDLE_RECORDING = {
1963
+ available: true,
1964
+ active: false,
1965
+ id: null,
1966
+ mode: null,
1967
+ started_at: null,
1968
+ started_by_user_id: null,
1969
+ auto: false,
1970
+ consent_required: false,
1971
+ consent: { accepted: [], declined: [] }
1972
+ };
1973
+ var without = (list, id) => list.filter((x) => x !== id);
1974
+ function applyCaptureEvent(state, e) {
1975
+ const rec = state.recording ?? IDLE_RECORDING;
1976
+ switch (e.type) {
1977
+ case "recording:started": {
1978
+ const r = e.evt.recording;
1979
+ const starter = r.started_by_user_id;
1980
+ return {
1981
+ ...state,
1982
+ recording: {
1983
+ ...rec,
1984
+ active: true,
1985
+ id: r.id,
1986
+ mode: r.mode,
1987
+ started_at: r.started_at,
1988
+ started_by_user_id: starter,
1989
+ auto: r.auto,
1990
+ consent_required: e.evt.consent_required,
1991
+ // Starting is accepting.
1992
+ consent: starter ? {
1993
+ accepted: [...without(rec.consent.accepted, starter), starter],
1994
+ declined: without(rec.consent.declined, starter)
1995
+ } : rec.consent
1996
+ }
1997
+ };
1998
+ }
1999
+ case "recording:stopped":
2000
+ case "recording:ready":
2001
+ if (rec.id !== null && rec.id !== e.evt.recording.id) return state;
2002
+ return {
2003
+ ...state,
2004
+ recording: { ...rec, active: false, id: null, mode: null, consent_required: false }
2005
+ };
2006
+ case "recording:consent": {
2007
+ const { user_id: who, decision } = e.evt;
2008
+ const accepted = without(rec.consent.accepted, who);
2009
+ const declined = without(rec.consent.declined, who);
2010
+ (decision === "accepted" ? accepted : declined).push(who);
2011
+ return { ...state, recording: { ...rec, consent: { accepted, declined } } };
2012
+ }
2013
+ case "transcript:changed": {
2014
+ const t = e.evt.transcript;
2015
+ return {
2016
+ ...state,
2017
+ transcription: {
2018
+ available: state.transcription?.available ?? true,
2019
+ active: t.status === "live",
2020
+ id: t.id,
2021
+ status: t.status,
2022
+ language: t.language
2023
+ }
2024
+ };
2025
+ }
2026
+ }
2027
+ }
2028
+ function subscribeCapture(chat, conversationId, callId, fn) {
2029
+ const conv = chat.realtime.conversation(conversationId);
2030
+ const mine = (id) => callId === null || id === callId;
2031
+ const offs = [
2032
+ conv.onRecordingStarted((evt) => mine(evt.call_id) && fn({ type: "recording:started", evt })),
2033
+ conv.onRecordingStopped((evt) => mine(evt.call_id) && fn({ type: "recording:stopped", evt })),
2034
+ conv.onRecordingReady((evt) => mine(evt.call_id) && fn({ type: "recording:ready", evt })),
2035
+ conv.onRecordingConsent((evt) => mine(evt.call_id) && fn({ type: "recording:consent", evt })),
2036
+ conv.onTranscriptStarted((evt) => mine(evt.call_id) && fn({ type: "transcript:changed", evt })),
2037
+ conv.onTranscriptStopped((evt) => mine(evt.call_id) && fn({ type: "transcript:changed", evt })),
2038
+ conv.onTranscriptReady((evt) => mine(evt.call_id) && fn({ type: "transcript:changed", evt }))
2039
+ ];
2040
+ return () => offs.forEach((off) => off());
2041
+ }
2042
+ function useMeId(chat) {
2043
+ const [id, setId] = useState(() => chat.me.peek()?.id ?? null);
2044
+ useEffect(() => {
2045
+ setId(chat.me.peek()?.id ?? null);
2046
+ return chat.me.onChange((me) => setId(me.id));
2047
+ }, [chat]);
2048
+ return id;
2049
+ }
2050
+ function onReconnect(chat, fn) {
2051
+ let wasConnected = chat.realtime.getStatus() === "connected";
2052
+ let connectedBefore = wasConnected;
2053
+ return chat.realtime.onStatus((status) => {
2054
+ if (status === "connected" && !wasConnected && connectedBefore) fn();
2055
+ wasConnected = status === "connected";
2056
+ connectedBefore ||= wasConnected;
2057
+ });
2058
+ }
2059
+
2060
+ // src/use-live-call.ts
1641
2061
  function useLiveCall(conversationId) {
1642
2062
  const chat = usePoolse();
1643
2063
  const [call, setCall] = useState(null);
@@ -1670,6 +2090,21 @@ function useLiveCall(conversationId) {
1670
2090
  if (evt.call_id === callIdRef.current) setParticipantIds(evt.participants);
1671
2091
  else refresh();
1672
2092
  });
2093
+ const offCapture = subscribeCapture(chat, conversationId, null, (e) => {
2094
+ if (e.evt.call_id !== callIdRef.current) return;
2095
+ setCall((c) => {
2096
+ if (!c) return c;
2097
+ const next = applyCaptureEvent(
2098
+ { recording: c.recording ?? null, transcription: c.transcription ?? null },
2099
+ e
2100
+ );
2101
+ return {
2102
+ ...c,
2103
+ ...next.recording ? { recording: next.recording } : {},
2104
+ ...next.transcription ? { transcription: next.transcription } : {}
2105
+ };
2106
+ });
2107
+ });
1673
2108
  const offFinished = conv.onCallFinished((evt) => {
1674
2109
  if (evt.call_id !== callIdRef.current) return;
1675
2110
  seq.current++;
@@ -1686,6 +2121,7 @@ function useLiveCall(conversationId) {
1686
2121
  offStarted();
1687
2122
  offParticipants();
1688
2123
  offFinished();
2124
+ offCapture();
1689
2125
  offStatus();
1690
2126
  };
1691
2127
  }, [chat, conversationId, apply, refresh]);
@@ -1740,6 +2176,392 @@ function useRoom(conversationId, opts) {
1740
2176
  error: error ?? media.error
1741
2177
  };
1742
2178
  }
2179
+ function useRecording(callId, conversationId, initial) {
2180
+ const chat = usePoolse();
2181
+ const meId = useMeId(chat);
2182
+ const [state, setState] = useState(
2183
+ () => initial && initial.id === callId ? { recording: initial.recording ?? null, transcription: initial.transcription ?? null } : { recording: null, transcription: null }
2184
+ );
2185
+ const [notice, setNotice] = useState(null);
2186
+ const [lastRecording, setLastRecording] = useState(null);
2187
+ const [pending, setPending] = useState(false);
2188
+ const [error, setError] = useState(null);
2189
+ const [transcriptConsent, setTranscriptConsent] = useState(false);
2190
+ const seq = useRef(0);
2191
+ const hasInitial = useRef(!!initial && initial.id === callId);
2192
+ const refresh = useCallback(() => {
2193
+ if (!callId || !conversationId) return;
2194
+ const mine = ++seq.current;
2195
+ chat.liveCalls.get(conversationId).then((c) => {
2196
+ if (mine !== seq.current) return;
2197
+ if (c && c.id === callId)
2198
+ setState({ recording: c.recording ?? null, transcription: c.transcription ?? null });
2199
+ else
2200
+ setState((s) => ({
2201
+ recording: s.recording ? { ...s.recording, active: false } : null,
2202
+ transcription: s.transcription ? { ...s.transcription, active: false } : null
2203
+ }));
2204
+ }).catch(() => {
2205
+ });
2206
+ }, [chat, callId, conversationId]);
2207
+ useEffect(() => {
2208
+ if (!callId || !conversationId) {
2209
+ setState({ recording: null, transcription: null });
2210
+ return;
2211
+ }
2212
+ if (hasInitial.current) hasInitial.current = false;
2213
+ else refresh();
2214
+ const offCapture = subscribeCapture(chat, conversationId, callId, (e) => {
2215
+ seq.current++;
2216
+ setState((s) => applyCaptureEvent(s, e));
2217
+ if (e.type === "recording:started") {
2218
+ setNotice(e.evt.notice);
2219
+ setLastRecording(e.evt.recording);
2220
+ } else if (e.type === "recording:stopped" || e.type === "recording:ready") {
2221
+ setLastRecording(e.evt.recording);
2222
+ }
2223
+ });
2224
+ const conv = chat.realtime.conversation(conversationId);
2225
+ const offFinished = conv.onCallFinished((evt) => {
2226
+ if (evt.call_id !== callId) return;
2227
+ seq.current++;
2228
+ setState((s) => ({
2229
+ recording: s.recording ? { ...s.recording, active: false } : null,
2230
+ transcription: s.transcription ? { ...s.transcription, active: false } : null
2231
+ }));
2232
+ });
2233
+ const offStatus = onReconnect(chat, refresh);
2234
+ return () => {
2235
+ offCapture();
2236
+ offFinished();
2237
+ offStatus();
2238
+ };
2239
+ }, [chat, callId, conversationId, refresh]);
2240
+ const transcribing = !!state.transcription?.active;
2241
+ useEffect(() => {
2242
+ if (!conversationId || !transcribing) {
2243
+ setTranscriptConsent(false);
2244
+ return;
2245
+ }
2246
+ let cancelled = false;
2247
+ chat.calls.recording.settings(conversationId).then((s) => {
2248
+ if (!cancelled) setTranscriptConsent(s.effective.consent === "required");
2249
+ }).catch(() => {
2250
+ });
2251
+ return () => {
2252
+ cancelled = true;
2253
+ };
2254
+ }, [chat, conversationId, transcribing]);
2255
+ const run = useCallback(async (fn) => {
2256
+ setPending(true);
2257
+ setError(null);
2258
+ try {
2259
+ await fn();
2260
+ return true;
2261
+ } catch (err) {
2262
+ setError(err instanceof Error ? err : new Error(String(err)));
2263
+ return false;
2264
+ } finally {
2265
+ setPending(false);
2266
+ }
2267
+ }, []);
2268
+ const start = useCallback(
2269
+ (mode) => run(async () => {
2270
+ if (!callId) throw new Error("no call");
2271
+ const r = await chat.calls.recording.start(callId, mode ? { mode } : {});
2272
+ setLastRecording(r);
2273
+ }),
2274
+ [chat, callId, run]
2275
+ );
2276
+ const stop = useCallback(
2277
+ () => run(async () => {
2278
+ if (!callId) throw new Error("no call");
2279
+ const r = await chat.calls.recording.stop(callId);
2280
+ setLastRecording(r);
2281
+ }),
2282
+ [chat, callId, run]
2283
+ );
2284
+ const consent = useCallback(
2285
+ (decision) => run(async () => {
2286
+ if (!callId) throw new Error("no call");
2287
+ const res = await chat.calls.consent(callId, decision);
2288
+ setState(
2289
+ (s) => applyCaptureEvent(s, {
2290
+ type: "recording:consent",
2291
+ evt: { cv: 1, call_id: res.call_id, user_id: res.user_id, decision: res.decision }
2292
+ })
2293
+ );
2294
+ }),
2295
+ [chat, callId, run]
2296
+ );
2297
+ const rec = state.recording;
2298
+ const active = !!rec?.active;
2299
+ const capturing = active || transcribing;
2300
+ const consentRequired = active && !!rec?.consent_required || transcribing && transcriptConsent;
2301
+ const myConsent = meId && rec ? rec.consent.accepted.includes(meId) || active && rec.started_by_user_id === meId ? "accepted" : rec.consent.declined.includes(meId) ? "declined" : null : null;
2302
+ return {
2303
+ available: rec?.available ?? false,
2304
+ active,
2305
+ recording: rec,
2306
+ transcription: state.transcription,
2307
+ capturing,
2308
+ consentRequired,
2309
+ myConsent,
2310
+ needsConsent: capturing && consentRequired && myConsent !== "accepted",
2311
+ notice,
2312
+ lastRecording,
2313
+ pending,
2314
+ error,
2315
+ start,
2316
+ stop,
2317
+ consent,
2318
+ refresh
2319
+ };
2320
+ }
2321
+ function useLiveTranscript(callId, opts = {}) {
2322
+ const chat = usePoolse();
2323
+ const enabled = opts.enabled ?? true;
2324
+ const max = opts.maxSegments ?? 1e3;
2325
+ const [segments, setSegments] = useState([]);
2326
+ const [transcript, setTranscript] = useState(null);
2327
+ const [conversationId, setConversationId] = useState(null);
2328
+ const [joined, setJoined] = useState(false);
2329
+ const [error, setError] = useState(null);
2330
+ const [pending, setPending] = useState(false);
2331
+ useEffect(() => {
2332
+ setSegments([]);
2333
+ setTranscript(null);
2334
+ setJoined(false);
2335
+ setError(null);
2336
+ if (!callId || !enabled) return;
2337
+ let handle;
2338
+ try {
2339
+ handle = chat.realtime.transcript(callId);
2340
+ } catch (err) {
2341
+ setError(err instanceof Error ? err : new Error(String(err)));
2342
+ return;
2343
+ }
2344
+ const offJoined = handle.onJoined((reply) => {
2345
+ setJoined(true);
2346
+ setError(null);
2347
+ setConversationId(reply.conversation_id || null);
2348
+ setTranscript(reply.transcript);
2349
+ setSegments(reply.segments.slice(-max).map((s) => ({ ...s, final: true })));
2350
+ });
2351
+ const offSegment = handle.onSegment((evt) => {
2352
+ const { cv: _cv, call_id: _call, transcript_id: _t, ...seg } = evt;
2353
+ setSegments((list) => applyLiveSegment(list, seg, max));
2354
+ });
2355
+ const offError = handle.onError((reason) => {
2356
+ setJoined(false);
2357
+ setError(new Error(reason));
2358
+ });
2359
+ return () => {
2360
+ offJoined();
2361
+ offSegment();
2362
+ offError();
2363
+ handle.release();
2364
+ };
2365
+ }, [chat, callId, enabled, max]);
2366
+ useEffect(() => {
2367
+ if (!callId || !conversationId || !enabled) return;
2368
+ const conv = chat.realtime.conversation(conversationId);
2369
+ const apply = (evt) => {
2370
+ if (evt.call_id === callId) setTranscript(evt.transcript);
2371
+ };
2372
+ const offs = [
2373
+ conv.onTranscriptStarted(apply),
2374
+ conv.onTranscriptStopped(apply),
2375
+ conv.onTranscriptReady(apply),
2376
+ conv.onTranscriptSpeakers((evt) => {
2377
+ if (evt.call_id !== callId) return;
2378
+ const names = new Map(evt.speakers.map((s) => [s.key, s.name]));
2379
+ setSegments(
2380
+ (list) => list.map(
2381
+ (s) => names.has(s.speaker) ? { ...s, speaker_name: names.get(s.speaker) } : s
2382
+ )
2383
+ );
2384
+ })
2385
+ ];
2386
+ return () => offs.forEach((off) => off());
2387
+ }, [chat, callId, conversationId, enabled]);
2388
+ const run = useCallback(async (fn) => {
2389
+ setPending(true);
2390
+ setError(null);
2391
+ try {
2392
+ setTranscript(await fn());
2393
+ return true;
2394
+ } catch (err) {
2395
+ setError(err instanceof Error ? err : new Error(String(err)));
2396
+ return false;
2397
+ } finally {
2398
+ setPending(false);
2399
+ }
2400
+ }, []);
2401
+ const start = useCallback(
2402
+ () => callId ? run(() => chat.calls.transcription.start(callId)) : Promise.resolve(false),
2403
+ [chat, callId, run]
2404
+ );
2405
+ const stop = useCallback(
2406
+ () => callId ? run(() => chat.calls.transcription.stop(callId)) : Promise.resolve(false),
2407
+ [chat, callId, run]
2408
+ );
2409
+ const finals = useMemo(() => segments.filter((s) => s.final), [segments]);
2410
+ const interim = useMemo(() => segments.filter((s) => !s.final), [segments]);
2411
+ return {
2412
+ segments,
2413
+ finals,
2414
+ interim,
2415
+ transcript,
2416
+ live: transcript?.status === "live",
2417
+ joined,
2418
+ error,
2419
+ pending,
2420
+ start,
2421
+ stop
2422
+ };
2423
+ }
2424
+ function withSpeakers(t, speakers) {
2425
+ const names = new Map(speakers.map((s) => [s.key, s.name]));
2426
+ return {
2427
+ ...t,
2428
+ speakers,
2429
+ segments: t.segments.map(
2430
+ (s) => names.has(s.speaker) ? { ...s, speaker_name: names.get(s.speaker) ?? null } : s
2431
+ )
2432
+ };
2433
+ }
2434
+ function useTranscript(callId) {
2435
+ const chat = usePoolse();
2436
+ const [transcript, setTranscript] = useState(null);
2437
+ const [loading, setLoading] = useState(!!callId);
2438
+ const [missing, setMissing] = useState(false);
2439
+ const [error, setError] = useState(null);
2440
+ const seq = useRef(0);
2441
+ const refresh = useCallback(() => {
2442
+ if (!callId) return;
2443
+ const mine = ++seq.current;
2444
+ setLoading(true);
2445
+ chat.calls.transcript.get(callId).then((t) => {
2446
+ if (mine !== seq.current) return;
2447
+ setTranscript(t);
2448
+ setMissing(false);
2449
+ setError(null);
2450
+ }).catch((err) => {
2451
+ if (mine !== seq.current) return;
2452
+ if (err instanceof ApiError && err.status === 404) {
2453
+ setMissing(true);
2454
+ setTranscript(null);
2455
+ } else setError(err instanceof Error ? err : new Error(String(err)));
2456
+ }).finally(() => {
2457
+ if (mine === seq.current) setLoading(false);
2458
+ });
2459
+ }, [chat, callId]);
2460
+ useEffect(() => {
2461
+ setTranscript(null);
2462
+ setMissing(false);
2463
+ setError(null);
2464
+ setLoading(!!callId);
2465
+ refresh();
2466
+ }, [callId, refresh]);
2467
+ const conversationId = transcript?.conversation_id ?? null;
2468
+ useEffect(() => {
2469
+ if (!callId || !conversationId) return;
2470
+ const conv = chat.realtime.conversation(conversationId);
2471
+ const offSpeakers = conv.onTranscriptSpeakers((evt) => {
2472
+ if (evt.call_id !== callId) return;
2473
+ seq.current++;
2474
+ setTranscript((t) => t ? withSpeakers(t, evt.speakers) : t);
2475
+ });
2476
+ const offReady = conv.onTranscriptReady((evt) => {
2477
+ if (evt.call_id === callId) refresh();
2478
+ });
2479
+ const offStatus = onReconnect(chat, refresh);
2480
+ return () => {
2481
+ offSpeakers();
2482
+ offReady();
2483
+ offStatus();
2484
+ };
2485
+ }, [chat, callId, conversationId, refresh]);
2486
+ const renameSpeakers = useCallback(
2487
+ async (names) => {
2488
+ if (!callId) return;
2489
+ const t = await chat.calls.transcript.renameSpeakers(callId, names);
2490
+ seq.current++;
2491
+ setTranscript(t);
2492
+ },
2493
+ [chat, callId]
2494
+ );
2495
+ return { transcript, loading, missing, error, renameSpeakers, refresh };
2496
+ }
2497
+ function useCaptureList(conversationId, load, subscribe) {
2498
+ const chat = usePoolse();
2499
+ const [items, setItems] = useState([]);
2500
+ const [loading, setLoading] = useState(!!conversationId);
2501
+ const [error, setError] = useState(null);
2502
+ const seq = useRef(0);
2503
+ const loadRef = useRef(load);
2504
+ loadRef.current = load;
2505
+ const subscribeRef = useRef(subscribe);
2506
+ subscribeRef.current = subscribe;
2507
+ const refresh = useCallback(() => {
2508
+ if (!conversationId) return;
2509
+ const mine = ++seq.current;
2510
+ setLoading(true);
2511
+ loadRef.current(conversationId).then((list) => {
2512
+ if (mine !== seq.current) return;
2513
+ setItems(list);
2514
+ setError(null);
2515
+ }).catch((err) => {
2516
+ if (mine === seq.current) setError(err instanceof Error ? err : new Error(String(err)));
2517
+ }).finally(() => {
2518
+ if (mine === seq.current) setLoading(false);
2519
+ });
2520
+ }, [conversationId]);
2521
+ useEffect(() => {
2522
+ setItems([]);
2523
+ if (!conversationId) {
2524
+ setLoading(false);
2525
+ return;
2526
+ }
2527
+ refresh();
2528
+ const off = subscribeRef.current(conversationId, refresh);
2529
+ const offStatus = onReconnect(chat, refresh);
2530
+ return () => {
2531
+ off();
2532
+ offStatus();
2533
+ };
2534
+ }, [chat, conversationId, refresh]);
2535
+ return { items, loading, error, refresh };
2536
+ }
2537
+ function useTranscripts(conversationId, opts = {}) {
2538
+ const chat = usePoolse();
2539
+ return useCaptureList(
2540
+ conversationId,
2541
+ (id) => chat.calls.transcript.list(id, opts.limit !== void 0 ? { limit: opts.limit } : {}),
2542
+ (id, refresh) => {
2543
+ const conv = chat.realtime.conversation(id);
2544
+ const offs = [conv.onTranscriptStarted(refresh), conv.onTranscriptReady(refresh)];
2545
+ return () => offs.forEach((off) => off());
2546
+ }
2547
+ );
2548
+ }
2549
+ function useRecordings(conversationId, opts = {}) {
2550
+ const chat = usePoolse();
2551
+ return useCaptureList(
2552
+ conversationId,
2553
+ (id) => chat.calls.recording.list(id, opts.limit !== void 0 ? { limit: opts.limit } : {}),
2554
+ (id, refresh) => {
2555
+ const conv = chat.realtime.conversation(id);
2556
+ const offs = [
2557
+ conv.onRecordingStarted(refresh),
2558
+ conv.onRecordingStopped(refresh),
2559
+ conv.onRecordingReady(refresh)
2560
+ ];
2561
+ return () => offs.forEach((off) => off());
2562
+ }
2563
+ );
2564
+ }
1743
2565
  function useReadReceipts() {
1744
2566
  const chat = usePoolse();
1745
2567
  const { me } = useMe();
@@ -1769,6 +2591,6 @@ function canEditOwnMessage(args) {
1769
2591
  return Number.isFinite(sent) && (args.now ?? Date.now()) - sent < EDIT_WINDOW_MS;
1770
2592
  }
1771
2593
 
1772
- export { EDIT_WINDOW_MS, PoolseProvider, canEditOwnMessage, computeGroupPosition, formatDayLabel, receiptsOf, sameDay, sameGroup, useAppEvent, useAttachmentUpload, useAttachmentUrl, useCallRoom, useConversation, useConversationPresence, useConversations, useLiveCall, useMe, useMembers, useMessageStreams, useMessages, usePoolse, usePresence, usePresenceMany, useReactions, useReadReceipts, useRealtimeStatus, useRoom, useThread, useTyping, useUser, useUserPresence };
2594
+ export { EDIT_WINDOW_MS, PoolseProvider, applyCaptureEvent, canEditOwnMessage, computeGroupPosition, filterConversations, formatDayLabel, orderUnread, receiptsOf, sameDay, sameGroup, useAppEvent, useAttachmentUpload, useAttachmentUrl, useCallRoom, useClientTimings, useConversation, useConversationPresence, useConversations, useLiveCall, useLiveTranscript, useMe, useMembers, useMessageStreams, useMessages, useOutbox, usePoolse, usePresence, usePresenceMany, useReactions, useReadReceipts, useRealtimeStatus, useRecording, useRecordings, useRoom, useThread, useTranscript, useTranscripts, useTyping, useUnreadQueue, useUnreadTotals, useUser, useUserPresence };
1773
2595
  //# sourceMappingURL=index.js.map
1774
2596
  //# sourceMappingURL=index.js.map