@poolse/react 3.9.0 → 3.10.1

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, 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';
2
+ import { Poolse, MessageQueuedError, toTombstone, markQuoteDeleted, safeUuid, mergeMessage, ApiError, isCallLogMessage, stageRoleOf, sortQuestions, agendaOverrunMs, CallReactions, ScreenAnnotations, CallQualityMonitor, meetingNameOf, openWhiteboard, applyLiveSegment, ASK_QUESTION_MAX, summaryFromWire, applyLocalVote, isPollClosed, toggleVote, clipFromWire, applyThreadUpdate } from '@poolse/sdk';
3
+ export { APPROVAL_REASON_MAX, ASK_QUESTION_MAX, ApiError, AuthError, BRIEF_RULE_MAX, BRIEF_TEXT_MAX, DEFAULT_DOC_LIMITS, DocChannel, DocPushError, ESCALATION_ANSWER_MAX, MessageDiscardedError, MessageQueuedError, NetworkError, PLAYBACK_RATES, POOLSE_SERVICE_IDENTITY_PREFIX, Poolse, PoolseError, RateLimitedError, activeSegmentIndex, agentFromWire, agentMetaOf, applyLiveSegment, approvalErrorMessage, approvalFromWire, approvalIdOf, approvalStatusLabel, callAgentModeLabel, callAgentOfParticipant, callAgentStateLabel, callAgentStateOf, callLogDisplayFor, captureErrorMessage, captureLabel, chapterIndexAt, chaptersOf, citationLabel, citationsOf, clipFromWire, clipOf, createIndexedDbStorage, describeCallLog, describeRecordingNotice, escalationErrorMessage, escalationStatusLabel, findInText, formatCallDuration, formatCallLogPreview, formatCallSummaryPreview, formatClock, formatDue, formatRecordingNoticePreview, formatTimeRange, groupTranscript, isCallLogMessage, isMessageVisibleTo, isServiceParticipant, isTombstone, meetingsErrorMessage, memoryStorage, mergeMessage, messageAgent, momentOf, parseCallLog, parseCallLogBody, parseCallSummary, parseRecordingNotice, parseRecordingNoticeBody, recordingNoticeDisplayFor, silencesFromSegments, silencesOf, skipSilenceTarget, speakerName, summaryFromWire, summaryStatusText, summaryStyleLabel, toTombstone, toolLabel, whisperErrorMessage, whisperHintKindLabel } from '@poolse/sdk';
4
+ import { createContext, useRef, useMemo, useEffect, useContext, useState, useCallback, useSyncExternalStore, createElement } from 'react';
5
5
  import { jsx } from 'react/jsx-runtime';
6
6
 
7
7
  // src/provider.tsx
@@ -629,6 +629,9 @@ function useMembers(conversationId) {
629
629
  const [error, setError] = useState(null);
630
630
  const membersRef = useRef([]);
631
631
  membersRef.current = members;
632
+ useEffect(() => {
633
+ chat.users.noteAgents(members);
634
+ }, [chat, members]);
632
635
  const pendingReadsRef = useRef([]);
633
636
  const hasFetchedRef = useRef(false);
634
637
  const applyRead = (list, evt) => list.map(
@@ -746,6 +749,9 @@ function useMessages(conversationId) {
746
749
  if (loading) return;
747
750
  chat.cache.setMessages(conversationId, messages);
748
751
  }, [chat, conversationId, messages, loading]);
752
+ useEffect(() => {
753
+ chat.users.noteAgents(messages);
754
+ }, [chat, messages]);
749
755
  useEffect(() => {
750
756
  let cancelled = false;
751
757
  let fresh = false;
@@ -1168,6 +1174,9 @@ var PAGE_SIZE2 = 500;
1168
1174
  function useThread(conversationId, rootMessageId) {
1169
1175
  const chat = usePoolse();
1170
1176
  const [replies, setReplies] = useState([]);
1177
+ useEffect(() => {
1178
+ chat.users.noteAgents(replies);
1179
+ }, [chat, replies]);
1171
1180
  const [loading, setLoading] = useState(true);
1172
1181
  const [error, setError] = useState(null);
1173
1182
  const [hasMore, setHasMore] = useState(true);
@@ -1675,15 +1684,17 @@ function useAttachmentUrl(attachmentId) {
1675
1684
  }, [chat, attachmentId]);
1676
1685
  return { url, loading, error };
1677
1686
  }
1678
- var EMPTY = { profile: null, loading: false };
1687
+ var EMPTY = { profile: null, loading: false, agent: null };
1679
1688
  function useUser(externalId) {
1680
1689
  const chat = usePoolse();
1681
1690
  const shownForRef = useRef(null);
1691
+ const agentRef = useRef(null);
1682
1692
  const [state, setState] = useState(() => {
1683
1693
  if (!externalId) return EMPTY;
1684
1694
  const cached = chat.users.peek(externalId);
1685
- if (cached === void 0) return { profile: null, loading: true };
1686
- return { profile: cached, loading: false };
1695
+ const agent = chat.users.agentOf(externalId);
1696
+ if (cached === void 0) return { profile: null, loading: true, agent };
1697
+ return { profile: cached, loading: false, agent };
1687
1698
  });
1688
1699
  useEffect(() => {
1689
1700
  if (!externalId) {
@@ -1692,13 +1703,15 @@ function useUser(externalId) {
1692
1703
  }
1693
1704
  const apply = () => {
1694
1705
  const cached = chat.users.peek(externalId);
1706
+ const agent = sameAgent(agentRef.current, chat.users.agentOf(externalId));
1707
+ agentRef.current = agent;
1695
1708
  if (cached === void 0) {
1696
1709
  const keep = shownForRef.current === externalId;
1697
- setState((prev) => ({ profile: keep ? prev.profile : null, loading: true }));
1710
+ setState((prev) => ({ profile: keep ? prev.profile : null, loading: true, agent }));
1698
1711
  void chat.users.get(externalId);
1699
1712
  } else {
1700
1713
  shownForRef.current = externalId;
1701
- setState({ profile: cached, loading: false });
1714
+ setState({ profile: cached, loading: false, agent });
1702
1715
  }
1703
1716
  };
1704
1717
  const off = chat.users.subscribe(externalId, apply);
@@ -1707,12 +1720,251 @@ function useUser(externalId) {
1707
1720
  }, [chat, externalId]);
1708
1721
  return state;
1709
1722
  }
1723
+ function sameAgent(prev, next) {
1724
+ if (prev && next && prev.id === next.id && prev.name === next.name && prev.kind === next.kind) {
1725
+ return prev;
1726
+ }
1727
+ return next;
1728
+ }
1729
+ function useAgent(externalId) {
1730
+ const chat = usePoolse();
1731
+ const [agent, setAgent] = useState(() => chat.users.agentOf(externalId));
1732
+ useEffect(() => {
1733
+ if (!externalId) {
1734
+ setAgent(null);
1735
+ return;
1736
+ }
1737
+ const read = () => setAgent((prev) => sameAgent(prev, chat.users.agentOf(externalId)));
1738
+ read();
1739
+ return chat.users.subscribe(externalId, read);
1740
+ }, [chat, externalId]);
1741
+ return agent;
1742
+ }
1710
1743
  function useAppEvent(handler) {
1711
1744
  const chat = usePoolse();
1712
1745
  const handlerRef = useRef(handler);
1713
1746
  handlerRef.current = handler;
1714
1747
  useEffect(() => chat.onAppEvent((evt) => handlerRef.current(evt)), [chat]);
1715
1748
  }
1749
+
1750
+ // src/composer-tools.ts
1751
+ var FORMAT_ACTIONS = [
1752
+ { kind: "bold", label: "Bold", glyph: "B", shortcut: "Mod+B" },
1753
+ { kind: "italic", label: "Italic", glyph: "I", shortcut: "Mod+I" },
1754
+ { kind: "strike", label: "Strikethrough", glyph: "S", shortcut: "Mod+Shift+X" },
1755
+ { kind: "code", label: "Code", glyph: "<>", shortcut: "Mod+E" },
1756
+ { kind: "link", label: "Link", glyph: "\u{1F517}", shortcut: "Mod+K" },
1757
+ { kind: "quote", label: "Quote", glyph: "\u275D" },
1758
+ { kind: "bulletList", label: "Bulleted list", glyph: "\u2022" },
1759
+ { kind: "numberedList", label: "Numbered list", glyph: "1." },
1760
+ { kind: "checklist", label: "Checklist", glyph: "\u2610" },
1761
+ { kind: "codeBlock", label: "Code block", glyph: "{}" },
1762
+ { kind: "table", label: "Table", glyph: "\u25A6" }
1763
+ ];
1764
+ var INLINE = {
1765
+ bold: "**",
1766
+ italic: "_",
1767
+ strike: "~~",
1768
+ code: "`"
1769
+ };
1770
+ var LINE_PREFIX = {
1771
+ quote: "> ",
1772
+ bulletList: "- ",
1773
+ checklist: "- [ ] "
1774
+ };
1775
+ function clampSelection(value, sel) {
1776
+ const start = Math.max(0, Math.min(sel.start, sel.end, value.length));
1777
+ const end = Math.max(start, Math.min(Math.max(sel.start, sel.end), value.length));
1778
+ return { start, end };
1779
+ }
1780
+ function applyFormat(value, selection, kind) {
1781
+ const { start, end } = clampSelection(value, selection);
1782
+ const selected = value.slice(start, end);
1783
+ const before = value.slice(0, start);
1784
+ const after = value.slice(end);
1785
+ const marker = INLINE[kind];
1786
+ if (marker) {
1787
+ const m = marker.length;
1788
+ if (before.endsWith(marker) && after.startsWith(marker)) {
1789
+ return {
1790
+ value: before.slice(0, -m) + selected + after.slice(m),
1791
+ selection: { start: start - m, end: end - m }
1792
+ };
1793
+ }
1794
+ if (selected.length > 2 * m && selected.startsWith(marker) && selected.endsWith(marker)) {
1795
+ const inner = selected.slice(m, -m);
1796
+ return { value: before + inner + after, selection: { start, end: start + inner.length } };
1797
+ }
1798
+ return {
1799
+ value: before + marker + selected + marker + after,
1800
+ selection: { start: start + m, end: end + m }
1801
+ };
1802
+ }
1803
+ if (kind === "link") {
1804
+ const text = selected || "text";
1805
+ const url = "https://";
1806
+ const next2 = `${before}[${text}](${url})${after}`;
1807
+ const urlStart = start + text.length + 3;
1808
+ return { value: next2, selection: { start: urlStart, end: urlStart + url.length } };
1809
+ }
1810
+ if (kind === "codeBlock") {
1811
+ const lead = before === "" || before.endsWith("\n") ? "" : "\n";
1812
+ const tail = after === "" || after.startsWith("\n") ? "" : "\n";
1813
+ const block2 = `${lead}\`\`\`
1814
+ ${selected}
1815
+ \`\`\`${tail}`;
1816
+ const innerStart = start + lead.length + 4;
1817
+ return {
1818
+ value: before + block2 + after,
1819
+ selection: { start: innerStart, end: innerStart + selected.length }
1820
+ };
1821
+ }
1822
+ if (kind === "table") {
1823
+ const lead = before === "" || before.endsWith("\n") ? "" : "\n";
1824
+ const header = selected.trim() || "Column";
1825
+ const table = `${lead}| ${header} | Column |
1826
+ | --- | --- |
1827
+ | | |
1828
+ `;
1829
+ const cell = start + table.length - 6;
1830
+ return { value: before + table + after, selection: { start: cell, end: cell } };
1831
+ }
1832
+ const lineStart = value.lastIndexOf("\n", start - 1) + 1;
1833
+ const nl = value.indexOf("\n", end);
1834
+ const lineEnd = nl === -1 ? value.length : nl;
1835
+ const lines = value.slice(lineStart, lineEnd).split("\n");
1836
+ const numbered = /^\d+\. /;
1837
+ const prefix = LINE_PREFIX[kind];
1838
+ const has = (line) => kind === "numberedList" ? numbered.test(line) : line.startsWith(prefix);
1839
+ const allHave = lines.every(has);
1840
+ const nextLines = lines.map((line, i) => {
1841
+ if (allHave)
1842
+ return kind === "numberedList" ? line.replace(numbered, "") : line.slice(prefix.length);
1843
+ const bare = line.replace(/^(\d+\. |- \[[ xX]\] |- |\* |> )/, "");
1844
+ return (kind === "numberedList" ? `${i + 1}. ` : prefix) + bare;
1845
+ });
1846
+ const block = nextLines.join("\n");
1847
+ const next = value.slice(0, lineStart) + block + value.slice(lineEnd);
1848
+ if (start === end) {
1849
+ const caret = lineStart + nextLines[0].length;
1850
+ return { value: next, selection: { start: caret, end: caret } };
1851
+ }
1852
+ return { value: next, selection: { start: lineStart, end: lineStart + block.length } };
1853
+ }
1854
+ function formatForShortcut(e) {
1855
+ if (!(e.metaKey || e.ctrlKey) || e.altKey) return null;
1856
+ const key = e.key.toLowerCase();
1857
+ if (e.shiftKey) return key === "x" ? "strike" : null;
1858
+ switch (key) {
1859
+ case "b":
1860
+ return "bold";
1861
+ case "i":
1862
+ return "italic";
1863
+ case "e":
1864
+ return "code";
1865
+ case "k":
1866
+ return "link";
1867
+ default:
1868
+ return null;
1869
+ }
1870
+ }
1871
+ function slashQuery(value, caret) {
1872
+ if (!value.startsWith("/")) return null;
1873
+ const head = value.slice(1, caret);
1874
+ if (caret < 1 || /\s/.test(head)) return null;
1875
+ const end = value.search(/\s/);
1876
+ if (end !== -1 && caret > end) return null;
1877
+ return { query: head.toLowerCase() };
1878
+ }
1879
+ function filterSlashCommands(commands, query, limit = 8) {
1880
+ const q = query.toLowerCase();
1881
+ const prefix = [];
1882
+ const contains = [];
1883
+ for (const c of commands) {
1884
+ const name = c.name.toLowerCase();
1885
+ if (name.startsWith(q)) prefix.push(c);
1886
+ else if (q && (name.includes(q) || c.description?.toLowerCase().includes(q))) contains.push(c);
1887
+ }
1888
+ prefix.sort((a, b) => a.name.localeCompare(b.name));
1889
+ return [...prefix, ...contains].slice(0, limit);
1890
+ }
1891
+ function applySlashCommand(value, name) {
1892
+ const end = value.search(/\s/);
1893
+ const rest = end === -1 ? "" : value.slice(end).replace(/^\s+/, "");
1894
+ const head = `/${name} `;
1895
+ return { value: head + rest, selection: { start: head.length, end: head.length } };
1896
+ }
1897
+ function slashCommandsFromWorkspace(commands) {
1898
+ return commands.map((c) => ({
1899
+ name: c.command,
1900
+ ...c.description ? { description: c.description } : {},
1901
+ ...c.usage ? { usage: c.usage } : {},
1902
+ ...c.app?.name ? { source: c.app.name } : {}
1903
+ }));
1904
+ }
1905
+ function parseSlashCommand(value) {
1906
+ const m = /^\/([a-z0-9_-]+)(?:\s+([\s\S]*))?$/i.exec(value.trim());
1907
+ if (!m) return null;
1908
+ return { name: m[1].toLowerCase(), args: (m[2] ?? "").trim() };
1909
+ }
1910
+ function rankMentionGroups(groups, query, limit = 8) {
1911
+ const q = query.toLowerCase();
1912
+ const scored = [];
1913
+ for (const g of groups) {
1914
+ const handle = g.handle.toLowerCase();
1915
+ const name = g.name.toLowerCase();
1916
+ const score = q === "" ? 1 : handle.startsWith(q) ? 3 : name.split(/\s+/).some((w) => w.startsWith(q)) ? 2 : handle.includes(q) || name.includes(q) ? 1 : 0;
1917
+ if (score > 0) scored.push({ g, score });
1918
+ }
1919
+ scored.sort((a, b) => b.score - a.score || a.g.handle.localeCompare(b.g.handle));
1920
+ return scored.slice(0, limit).map((s) => s.g);
1921
+ }
1922
+ function mentionGroupMeta(g) {
1923
+ if (g.description) return g.description;
1924
+ if (g.memberCount === void 0) return null;
1925
+ return `${g.memberCount} ${g.memberCount === 1 ? "person" : "people"}`;
1926
+ }
1927
+ var MESSAGE_PLAYBACK_RATES = [1, 1.5, 2];
1928
+ function nextPlaybackRate(rate) {
1929
+ const i = MESSAGE_PLAYBACK_RATES.indexOf(rate);
1930
+ return MESSAGE_PLAYBACK_RATES[(i + 1) % MESSAGE_PLAYBACK_RATES.length];
1931
+ }
1932
+ function playbackRateLabel(rate) {
1933
+ return `${rate}\xD7`;
1934
+ }
1935
+ function waveformBars(samples, bars) {
1936
+ if (bars <= 0) return [];
1937
+ if (samples.length === 0) return new Array(bars).fill(0.08);
1938
+ const out = [];
1939
+ for (let i = 0; i < bars; i++) {
1940
+ const from = Math.floor(i * samples.length / bars);
1941
+ const to = Math.max(from + 1, Math.floor((i + 1) * samples.length / bars));
1942
+ let peak = 0;
1943
+ for (let j = from; j < to && j < samples.length; j++) peak = Math.max(peak, samples[j]);
1944
+ out.push(Math.max(0.08, Math.min(1, peak)));
1945
+ }
1946
+ return out;
1947
+ }
1948
+ var WARN_CODES = /* @__PURE__ */ new Set(["dlp_warning"]);
1949
+ var BLOCK_CODES = /* @__PURE__ */ new Set(["dlp_blocked"]);
1950
+ function readDlpError(err) {
1951
+ if (!(err instanceof ApiError)) return null;
1952
+ const code = String(err.code);
1953
+ const action = WARN_CODES.has(code) ? "warn" : BLOCK_CODES.has(code) ? "block" : null;
1954
+ if (!action) return null;
1955
+ const details = err.details ?? {};
1956
+ const raw = Array.isArray(details.rules) ? details.rules : Array.isArray(details.matches) ? details.matches : [];
1957
+ const matches = [];
1958
+ for (const m of raw) {
1959
+ if (!m || typeof m !== "object") continue;
1960
+ const r = m;
1961
+ const rule = typeof r.name === "string" ? r.name : typeof r.rule === "string" ? r.rule : null;
1962
+ if (!rule) continue;
1963
+ matches.push({ rule, ...typeof r.excerpt === "string" ? { excerpt: r.excerpt } : {} });
1964
+ }
1965
+ const message = typeof details.message === "string" ? details.message : void 0;
1966
+ return { action, matches, ...message ? { message } : {} };
1967
+ }
1716
1968
  function computeGroupPosition(msg, prev, next, windowMs) {
1717
1969
  const continuesPrev = sameGroup(msg, prev, windowMs);
1718
1970
  const continuesNext = sameGroup(next, msg, windowMs);
@@ -1768,6 +2020,10 @@ function useCallRoom(conversationId, opts) {
1768
2020
  const [error, setError] = useState(null);
1769
2021
  const [sfuAvailable, setSfuAvailable] = useState(null);
1770
2022
  const [canPublish, setCanPublish] = useState(true);
2023
+ const [background, setBackgroundState] = useState({ type: "none" });
2024
+ const [noiseSuppression, setNoise] = useState(opts.noiseSuppression ?? true);
2025
+ const [reconnecting, setReconnecting] = useState(false);
2026
+ const [disconnectReason, setDisconnectReason] = useState(null);
1771
2027
  const optsRef = useRef(opts);
1772
2028
  optsRef.current = opts;
1773
2029
  const joined = useRef(false);
@@ -1780,7 +2036,9 @@ function useCallRoom(conversationId, opts) {
1780
2036
  ...optsRef.current.muted !== void 0 ? { muted: optsRef.current.muted } : {},
1781
2037
  ...optsRef.current.facing !== void 0 ? { facing: optsRef.current.facing } : {},
1782
2038
  ...optsRef.current.aloneGraceMs !== void 0 ? { aloneGraceMs: optsRef.current.aloneGraceMs } : {},
1783
- ...optsRef.current.republishOnPermission !== void 0 ? { republishOnPermission: optsRef.current.republishOnPermission } : {}
2039
+ ...optsRef.current.republishOnPermission !== void 0 ? { republishOnPermission: optsRef.current.republishOnPermission } : {},
2040
+ ...optsRef.current.trackProcessors ? { trackProcessors: optsRef.current.trackProcessors } : {},
2041
+ ...optsRef.current.noiseSuppression !== void 0 ? { noiseSuppression: optsRef.current.noiseSuppression } : {}
1784
2042
  });
1785
2043
  }, [poolse, conversationId]);
1786
2044
  const refreshDevices = useCallback((target) => {
@@ -1826,6 +2084,12 @@ function useCallRoom(conversationId, opts) {
1826
2084
  const offDevices = room.onDevices(() => refreshDevices(room));
1827
2085
  const offError = room.onError(setError);
1828
2086
  const offPublish = room.onPublishPermission(() => sync(room));
2087
+ setReconnecting(room.isReconnecting());
2088
+ setDisconnectReason(null);
2089
+ setBackgroundState(room.getBackground());
2090
+ setNoise(room.isNoiseSuppressionEnabled());
2091
+ const offReconnect = room.onReconnecting(setReconnecting);
2092
+ const offDisconnect = room.onDisconnected(setDisconnectReason);
1829
2093
  return () => {
1830
2094
  offStatus();
1831
2095
  offRoster();
@@ -1833,6 +2097,8 @@ function useCallRoom(conversationId, opts) {
1833
2097
  offDevices();
1834
2098
  offError();
1835
2099
  offPublish();
2100
+ offReconnect();
2101
+ offDisconnect();
1836
2102
  held.current = null;
1837
2103
  if (joined.current) {
1838
2104
  joined.current = false;
@@ -1930,7 +2196,30 @@ function useCallRoom(conversationId, opts) {
1930
2196
  await room.republish();
1931
2197
  sync(room);
1932
2198
  }, [room, sync]);
2199
+ const setBackground = useCallback(
2200
+ async (effect) => {
2201
+ if (!room) return false;
2202
+ setBackgroundState(effect);
2203
+ return room.setBackground(effect);
2204
+ },
2205
+ [room]
2206
+ );
2207
+ const setNoiseSuppression = useCallback(
2208
+ async (enabled) => {
2209
+ setNoise(enabled);
2210
+ await room?.setNoiseSuppression(enabled);
2211
+ },
2212
+ [room]
2213
+ );
1933
2214
  return {
2215
+ room,
2216
+ backgroundSupported: room?.backgroundSupported() ?? false,
2217
+ background,
2218
+ setBackground,
2219
+ noiseSuppression,
2220
+ setNoiseSuppression,
2221
+ reconnecting,
2222
+ disconnectReason,
1934
2223
  status,
1935
2224
  participants,
1936
2225
  cameraEnabled,
@@ -2176,138 +2465,707 @@ function useRoom(conversationId, opts) {
2176
2465
  error: error ?? media.error
2177
2466
  };
2178
2467
  }
2179
- function useRecording(callId, conversationId, initial) {
2468
+ var asError = (err) => err instanceof Error ? err : new Error(String(err));
2469
+ function onReconnect2(chat, fn) {
2470
+ let was = chat.realtime.getStatus() === "connected";
2471
+ let before = was;
2472
+ return chat.realtime.onStatus((status) => {
2473
+ if (status === "connected" && !was && before) fn();
2474
+ was = status === "connected";
2475
+ before ||= was;
2476
+ });
2477
+ }
2478
+ function useLiveValue(conversationId, callId, load, listen, subscribeOpts = {}) {
2180
2479
  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);
2480
+ const [value, setValue] = useState(null);
2188
2481
  const [error, setError] = useState(null);
2189
- const [transcriptConsent, setTranscriptConsent] = useState(false);
2482
+ const [pending, setPending] = useState(false);
2483
+ const loadRef = useRef(load);
2484
+ loadRef.current = load;
2485
+ const listenRef = useRef(listen);
2486
+ listenRef.current = listen;
2190
2487
  const seq = useRef(0);
2191
- const hasInitial = useRef(!!initial && initial.id === callId);
2488
+ const selfUserId = subscribeOpts.selfUserId ?? null;
2192
2489
  const refresh = useCallback(() => {
2193
- if (!callId || !conversationId) return;
2490
+ if (!callId) return;
2194
2491
  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(() => {
2492
+ loadRef.current(chat, callId).then((v) => {
2493
+ if (mine === seq.current) setValue(v);
2494
+ }).catch((err) => {
2495
+ if (mine === seq.current) setError(asError(err));
2205
2496
  });
2206
- }, [chat, callId, conversationId]);
2497
+ }, [chat, callId]);
2207
2498
  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);
2499
+ setValue(null);
2500
+ setError(null);
2501
+ if (!callId || !conversationId) return;
2502
+ refresh();
2503
+ const off = chat.live.subscribe(
2504
+ conversationId,
2505
+ callId,
2506
+ listenRef.current((fn) => {
2507
+ seq.current++;
2508
+ setValue((prev) => fn(prev));
2509
+ }),
2510
+ selfUserId ? { selfUserId } : {}
2511
+ );
2512
+ const offStatus = onReconnect2(chat, refresh);
2234
2513
  return () => {
2235
- offCapture();
2236
- offFinished();
2514
+ off();
2237
2515
  offStatus();
2238
2516
  };
2239
- }, [chat, callId, conversationId, refresh]);
2240
- const transcribing = !!state.transcription?.active;
2517
+ }, [chat, conversationId, callId, refresh, selfUserId]);
2518
+ const run = useCallback(
2519
+ async (fn, apply) => {
2520
+ setPending(true);
2521
+ setError(null);
2522
+ try {
2523
+ const r = await fn();
2524
+ if (apply) {
2525
+ seq.current++;
2526
+ apply(r);
2527
+ }
2528
+ return r;
2529
+ } catch (err) {
2530
+ setError(asError(err));
2531
+ return null;
2532
+ } finally {
2533
+ setPending(false);
2534
+ }
2535
+ },
2536
+ []
2537
+ );
2538
+ return { chat, value, setValue, error, pending, refresh, run };
2539
+ }
2540
+ function useStage(conversationId, callId, selfUserId) {
2541
+ const { chat, value, setValue, error, pending, run } = useLiveValue(
2542
+ conversationId,
2543
+ callId,
2544
+ (c, id) => c.live.stage.get(id),
2545
+ (set) => ({ onStage: (s) => set(() => s) }),
2546
+ { selfUserId: selfUserId ?? null }
2547
+ );
2548
+ const ok = (r) => r !== null;
2549
+ const raiseHand = useCallback(
2550
+ async () => callId ? ok(await run(() => chat.live.stage.raiseHand(callId), setValue)) : false,
2551
+ [chat, callId, run, setValue]
2552
+ );
2553
+ const lowerHand = useCallback(
2554
+ async (userId) => callId ? ok(await run(() => chat.live.stage.lowerHand(callId, userId), setValue)) : false,
2555
+ [chat, callId, run, setValue]
2556
+ );
2557
+ const setRole = useCallback(
2558
+ async (userId, role) => callId ? ok(await run(() => chat.live.stage.setRole(callId, userId, role), setValue)) : false,
2559
+ [chat, callId, run, setValue]
2560
+ );
2561
+ const setMode = useCallback(
2562
+ async (mode) => callId ? ok(await run(() => chat.live.stage.setMode(callId, mode), setValue)) : false,
2563
+ [chat, callId, run, setValue]
2564
+ );
2565
+ const roleOf = useCallback((userId) => stageRoleOf(value, userId), [value]);
2566
+ const myRole = value?.myRole ?? "speaker";
2567
+ return {
2568
+ stage: value,
2569
+ myRole,
2570
+ isModerator: myRole === "moderator",
2571
+ handRaised: !!selfUserId && !!value?.hands.some((h) => h.userId === selfUserId),
2572
+ roleOf,
2573
+ raiseHand,
2574
+ lowerHand,
2575
+ setRole,
2576
+ setMode,
2577
+ error,
2578
+ pending
2579
+ };
2580
+ }
2581
+ function useQuestions(conversationId, callId) {
2582
+ const mineVoted = useRef(/* @__PURE__ */ new Set());
2583
+ const merge = (list, q) => {
2584
+ if (q.votedByMe) mineVoted.current.add(q.id);
2585
+ const withMine = { ...q, votedByMe: q.votedByMe || mineVoted.current.has(q.id) };
2586
+ const i = list.findIndex((x) => x.id === q.id);
2587
+ if (i < 0) return [...list, withMine];
2588
+ const next = list.slice();
2589
+ next[i] = withMine;
2590
+ return next;
2591
+ };
2592
+ const { chat, value, setValue, error, pending, run } = useLiveValue(
2593
+ conversationId,
2594
+ callId,
2595
+ async (c, id) => {
2596
+ const list = await c.live.questions.list(id);
2597
+ list.forEach((q) => q.votedByMe && mineVoted.current.add(q.id));
2598
+ return list;
2599
+ },
2600
+ (set) => ({
2601
+ onQuestion: (q) => set((prev) => merge(prev ?? [], q)),
2602
+ onQuestionDeleted: (id) => set((prev) => (prev ?? []).filter((q) => q.id !== id))
2603
+ })
2604
+ );
2605
+ const apply = useCallback(
2606
+ (q) => setValue((prev) => merge(prev ?? [], q)),
2607
+ // merge only reads the ref.
2608
+ [setValue]
2609
+ );
2610
+ const ask = useCallback(
2611
+ async (text, opts) => {
2612
+ if (!callId || !text.trim()) return false;
2613
+ return await run(() => chat.live.questions.ask(callId, text, opts ?? {}), apply) !== null;
2614
+ },
2615
+ [chat, callId, run, apply]
2616
+ );
2617
+ const toggleVote2 = useCallback(
2618
+ async (questionId) => {
2619
+ const voted = mineVoted.current.has(questionId);
2620
+ if (voted) mineVoted.current.delete(questionId);
2621
+ else mineVoted.current.add(questionId);
2622
+ const r = await run(
2623
+ () => voted ? chat.live.questions.unvote(questionId) : chat.live.questions.vote(questionId),
2624
+ (q) => apply({ ...q, votedByMe: !voted })
2625
+ );
2626
+ if (r === null) {
2627
+ if (voted) mineVoted.current.add(questionId);
2628
+ else mineVoted.current.delete(questionId);
2629
+ }
2630
+ },
2631
+ [chat, run, apply]
2632
+ );
2633
+ const setStatus = useCallback(
2634
+ async (questionId, status) => {
2635
+ await run(() => chat.live.questions.setStatus(questionId, status), apply);
2636
+ },
2637
+ [chat, run, apply]
2638
+ );
2639
+ const questions = useMemo(() => sortQuestions(value ?? []), [value]);
2640
+ return {
2641
+ questions,
2642
+ openCount: questions.filter((q) => q.status === "open").length,
2643
+ ask,
2644
+ toggleVote: toggleVote2,
2645
+ setStatus,
2646
+ error,
2647
+ pending
2648
+ };
2649
+ }
2650
+ function useBreakouts(conversationId, callId, opts = {}) {
2651
+ const { chat, value, setValue, error, pending, run } = useLiveValue(
2652
+ conversationId,
2653
+ callId,
2654
+ (c, id) => c.live.breakouts.get(id),
2655
+ (set) => ({ onBreakouts: (b) => set(() => b.status === "closed" ? null : b) })
2656
+ );
2657
+ const session = value ?? null;
2658
+ const [now, setNow] = useState(() => Date.now());
2659
+ const deadline = session?.status === "closing" ? session.returnAt : session?.endsAt;
2241
2660
  useEffect(() => {
2242
- if (!conversationId || !transcribing) {
2243
- setTranscriptConsent(false);
2244
- return;
2661
+ if (!deadline) return;
2662
+ const t = setInterval(() => setNow(Date.now()), 1e3);
2663
+ return () => clearInterval(t);
2664
+ }, [deadline]);
2665
+ const at = deadline ? Date.parse(deadline) : NaN;
2666
+ const secondsLeft = Number.isFinite(at) ? Math.max(0, Math.ceil((at - now) / 1e3)) : null;
2667
+ const open = useCallback(
2668
+ async (plan) => callId ? await run(() => chat.live.breakouts.open(callId, plan), setValue) !== null : false,
2669
+ [chat, callId, run, setValue]
2670
+ );
2671
+ const close = useCallback(
2672
+ async (afterSeconds) => callId ? await run(() => chat.live.breakouts.close(callId, afterSeconds), setValue) !== null : false,
2673
+ [chat, callId, run, setValue]
2674
+ );
2675
+ const join = useCallback(
2676
+ (roomId) => run(() => chat.live.breakouts.join(roomId)),
2677
+ [chat, run]
2678
+ );
2679
+ const returnToMain = useCallback(
2680
+ () => callId ? run(() => chat.live.breakouts.returnToMain(callId)) : Promise.resolve(null),
2681
+ [chat, callId, run]
2682
+ );
2683
+ const optsRef = useRef(opts);
2684
+ optsRef.current = opts;
2685
+ const inRoom = useRef(null);
2686
+ const myRoomId = session?.status === "open" ? session.myRoomId : null;
2687
+ useEffect(() => {
2688
+ if (!optsRef.current.auto || !callId) return;
2689
+ if (myRoomId && inRoom.current !== myRoomId) {
2690
+ const room = session?.rooms.find((r) => r.id === myRoomId);
2691
+ inRoom.current = myRoomId;
2692
+ void chat.live.breakouts.join(myRoomId).then((s) => room && optsRef.current.onJoinRoom?.(s, room)).catch(() => {
2693
+ inRoom.current = null;
2694
+ });
2695
+ } else if (!session && inRoom.current) {
2696
+ inRoom.current = null;
2697
+ void chat.live.breakouts.returnToMain(callId).then((s) => optsRef.current.onReturn?.(s)).catch(() => {
2698
+ });
2245
2699
  }
2246
- let cancelled = false;
2247
- chat.calls.recording.settings(conversationId).then((s) => {
2248
- if (!cancelled) setTranscriptConsent(s.effective.consent === "required");
2249
- }).catch(() => {
2700
+ }, [chat, callId, myRoomId, session]);
2701
+ return {
2702
+ session,
2703
+ myRoom: session?.rooms.find((r) => r.id === session.myRoomId) ?? null,
2704
+ secondsLeft,
2705
+ open,
2706
+ close,
2707
+ join,
2708
+ returnToMain,
2709
+ error,
2710
+ pending
2711
+ };
2712
+ }
2713
+ function useLobby(conversationId, callId = null) {
2714
+ const chat = usePoolse();
2715
+ const [lobby, setLobby] = useState(null);
2716
+ const [error, setError] = useState(null);
2717
+ const [pending, setPending] = useState(false);
2718
+ const seq = useRef(0);
2719
+ const target = useMemo(
2720
+ () => conversationId ? { conversationId, callId } : null,
2721
+ [conversationId, callId]
2722
+ );
2723
+ const refresh = useCallback(() => {
2724
+ if (!target) return;
2725
+ const mine = ++seq.current;
2726
+ chat.live.lobby.get(target).then((l) => {
2727
+ if (mine === seq.current) setLobby(l);
2728
+ }).catch((err) => {
2729
+ if (mine === seq.current) setError(asError(err));
2730
+ });
2731
+ }, [chat, target]);
2732
+ useEffect(() => {
2733
+ setLobby(null);
2734
+ setError(null);
2735
+ if (!target) return;
2736
+ refresh();
2737
+ const off = chat.live.subscribe(target.conversationId, target.callId ?? "", {
2738
+ onLobby: (l) => {
2739
+ seq.current++;
2740
+ setLobby(l);
2741
+ }
2250
2742
  });
2743
+ const offStatus = onReconnect2(chat, refresh);
2251
2744
  return () => {
2252
- cancelled = true;
2745
+ off();
2746
+ offStatus();
2253
2747
  };
2254
- }, [chat, conversationId, transcribing]);
2255
- const run = useCallback(async (fn) => {
2748
+ }, [chat, target, refresh]);
2749
+ const act = useCallback(async (fn) => {
2256
2750
  setPending(true);
2257
2751
  setError(null);
2258
2752
  try {
2259
- await fn();
2753
+ const l = await fn();
2754
+ seq.current++;
2755
+ setLobby(l);
2260
2756
  return true;
2261
2757
  } catch (err) {
2262
- setError(err instanceof Error ? err : new Error(String(err)));
2758
+ setError(asError(err));
2263
2759
  return false;
2264
2760
  } finally {
2265
2761
  setPending(false);
2266
2762
  }
2267
2763
  }, []);
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]
2764
+ const admit = useCallback(
2765
+ (id) => target ? act(() => chat.live.lobby.admit(target, id)) : Promise.resolve(false),
2766
+ [chat, target, act]
2275
2767
  );
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]
2768
+ const deny = useCallback(
2769
+ (id) => target ? act(() => chat.live.lobby.deny(target, id)) : Promise.resolve(false),
2770
+ [chat, target, act]
2283
2771
  );
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
- })
2772
+ const admitAll = useCallback(
2773
+ () => target ? act(() => chat.live.lobby.admitAll(target)) : Promise.resolve(false),
2774
+ [chat, target, act]
2775
+ );
2776
+ return { lobby, waitingCount: lobby?.waiting.length ?? 0, admit, deny, admitAll, error, pending };
2777
+ }
2778
+ function useMoments(conversationId, callId) {
2779
+ const add = (list, m) => (list ?? []).some((x) => x.id === m.id) ? list ?? [] : [...list ?? [], m];
2780
+ const { chat, value, setValue, error, pending, run } = useLiveValue(
2781
+ conversationId,
2782
+ callId,
2783
+ (c, id) => c.live.moments.list(id),
2784
+ (set) => ({ onMoment: (m) => set((prev) => add(prev, m)) })
2785
+ );
2786
+ const [lastMarked, setLast] = useState(null);
2787
+ const mark = useCallback(
2788
+ async (note) => {
2789
+ if (!callId) return null;
2790
+ const m = await run(
2791
+ () => chat.live.moments.mark(callId, note ? { note } : {}),
2792
+ (r) => setValue((prev) => add(prev, r))
2293
2793
  );
2294
- }),
2295
- [chat, callId, run]
2794
+ if (m) setLast(m);
2795
+ return m;
2796
+ },
2797
+ [chat, callId, run, setValue]
2798
+ );
2799
+ return { moments: value ?? [], mark, lastMarked, error, pending };
2800
+ }
2801
+ function useAgenda(conversationId, callId) {
2802
+ const [overtime, setOvertime] = useState(null);
2803
+ const { chat, value, setValue, error, pending, run } = useLiveValue(
2804
+ conversationId,
2805
+ callId,
2806
+ (c, id) => c.live.agenda.get(id),
2807
+ (set) => ({
2808
+ onAgenda: (a) => set(() => a),
2809
+ onAgendaOvertime: (o) => setOvertime({ itemId: o.itemId, overByMs: o.overByMs })
2810
+ })
2811
+ );
2812
+ const agenda = value ?? null;
2813
+ const current = agenda?.items.find((i) => i.id === agenda.currentItemId) ?? null;
2814
+ const [now, setNow] = useState(() => Date.now());
2815
+ useEffect(() => {
2816
+ if (!current?.minutes || current.status !== "active") return;
2817
+ const t = setInterval(() => setNow(Date.now()), 5e3);
2818
+ return () => clearInterval(t);
2819
+ }, [current?.id, current?.minutes, current?.status]);
2820
+ useEffect(() => {
2821
+ setOvertime((o) => o && o.itemId !== current?.id ? null : o);
2822
+ }, [current?.id]);
2823
+ const act = useCallback(
2824
+ async (fn) => await run(fn, setValue) !== null,
2825
+ [run, setValue]
2296
2826
  );
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
2827
  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",
2828
+ agenda,
2829
+ current,
2830
+ overrunMs: current ? agendaOverrunMs(current, now) : 0,
2831
+ overtime,
2832
+ start: useCallback(
2833
+ (id) => callId ? act(() => chat.live.agenda.start(callId, id)) : Promise.resolve(false),
2834
+ [chat, callId, act]
2835
+ ),
2836
+ done: useCallback(
2837
+ (id) => callId ? act(() => chat.live.agenda.done(callId, id)) : Promise.resolve(false),
2838
+ [chat, callId, act]
2839
+ ),
2840
+ reopen: useCallback(
2841
+ (id) => callId ? act(() => chat.live.agenda.reopen(callId, id)) : Promise.resolve(false),
2842
+ [chat, callId, act]
2843
+ ),
2844
+ error,
2845
+ pending
2846
+ };
2847
+ }
2848
+ function useCallReactions(room, opts = {}) {
2849
+ const visibleMs = opts.visibleMs ?? 4e3;
2850
+ const max = opts.max ?? 30;
2851
+ const [reactions, setReactions] = useState([]);
2852
+ const ref = useRef(null);
2853
+ useEffect(() => {
2854
+ setReactions([]);
2855
+ if (!room) return;
2856
+ const r = new CallReactions(room);
2857
+ ref.current = r;
2858
+ const timers = /* @__PURE__ */ new Set();
2859
+ const off = r.subscribe((reaction) => {
2860
+ setReactions((list) => [...list, reaction].slice(-max));
2861
+ const t = setTimeout(() => {
2862
+ timers.delete(t);
2863
+ setReactions((list) => list.filter((x) => x.id !== reaction.id));
2864
+ }, visibleMs);
2865
+ timers.add(t);
2866
+ });
2867
+ return () => {
2868
+ off();
2869
+ timers.forEach(clearTimeout);
2870
+ r.destroy();
2871
+ ref.current = null;
2872
+ };
2873
+ }, [room, visibleMs, max]);
2874
+ const send = useCallback(
2875
+ (emoji) => ref.current?.send(emoji) ?? Promise.resolve(false),
2876
+ []
2877
+ );
2878
+ return { reactions, send };
2879
+ }
2880
+ function useScreenAnnotations(room, sharerUserId, opts = {}) {
2881
+ const [state, setState] = useState(null);
2882
+ const [annotations, setAnnotations] = useState(null);
2883
+ const fadeMs = opts.fadeMs;
2884
+ useEffect(() => {
2885
+ setState(null);
2886
+ setAnnotations(null);
2887
+ if (!room || !sharerUserId) return;
2888
+ const layer = new ScreenAnnotations(room, sharerUserId, fadeMs ? { fadeMs } : {});
2889
+ setAnnotations(layer);
2890
+ const off = layer.subscribe(setState);
2891
+ return () => {
2892
+ off();
2893
+ layer.destroy();
2894
+ };
2895
+ }, [room, sharerUserId, fadeMs]);
2896
+ return { state, annotations };
2897
+ }
2898
+ function useCallQuality(room, opts = {}) {
2899
+ const chat = usePoolse();
2900
+ const [report, setReport] = useState(null);
2901
+ const intervalMs = opts.intervalMs;
2902
+ const callId = opts.callId ?? null;
2903
+ useEffect(() => {
2904
+ setReport(null);
2905
+ if (!room) return;
2906
+ const monitor = new CallQualityMonitor(room, {
2907
+ ...intervalMs ? { intervalMs } : {},
2908
+ ...callId ? { report: (body) => chat.live.quality.report(callId, body) } : {}
2909
+ });
2910
+ const off = monitor.subscribe(setReport);
2911
+ return () => {
2912
+ off();
2913
+ monitor.stop();
2914
+ };
2915
+ }, [chat, room, intervalMs, callId]);
2916
+ return report;
2917
+ }
2918
+ function useCallMeeting(conversationId, callId) {
2919
+ const { value, refresh } = useLiveValue(
2920
+ conversationId,
2921
+ callId,
2922
+ (c, id) => c.live.meeting(id),
2923
+ (set) => ({
2924
+ onAttendees: (attendees2) => set((m) => m ? { ...m, attendees: attendees2 } : m),
2925
+ onQuality: (q) => set((m) => m ? { ...m, quality: { ...m.quality, [q.identity]: q } } : m),
2926
+ onCaptions: (c) => set((m) => m ? { ...m, captionsUserIds: c.userIds } : m),
2927
+ onBreakouts: (b) => set((m) => m ? { ...m, breakout: b.status === "closed" ? null : b } : m),
2928
+ onLobby: (l) => set((m) => m ? { ...m, lobbyWaiting: l.waiting.length } : m),
2929
+ onStage: (s) => set((m) => m ? { ...m, stage: s.mode === "stage", roles: s.roles, hands: s.hands } : m)
2930
+ })
2931
+ );
2932
+ const attendees = useMemo(() => value?.attendees ?? [], [value]);
2933
+ const nameOf = useCallback(
2934
+ (identity, nameFor) => {
2935
+ const a = attendees.find((x) => x.identity === identity);
2936
+ if (a) return a.name;
2937
+ return meetingNameOf(identity, nameFor?.(identity) ?? null);
2938
+ },
2939
+ [attendees]
2940
+ );
2941
+ return { meeting: value, attendees, quality: value?.quality ?? {}, nameOf, refresh };
2942
+ }
2943
+ function useCaptions(conversationId, callId, selfUserId) {
2944
+ const { chat, value, setValue, error, pending, run } = useLiveValue(
2945
+ conversationId,
2946
+ callId,
2947
+ async (c, id) => (await c.live.meeting(id)).captionsUserIds,
2948
+ (set) => ({ onCaptions: (cap) => set(() => cap.userIds) })
2949
+ );
2950
+ const userIds = useMemo(() => value ?? [], [value]);
2951
+ const on = !!selfUserId && userIds.includes(selfUserId);
2952
+ const setOn = useCallback(
2953
+ async (next) => {
2954
+ if (!callId) return false;
2955
+ const r = await run(
2956
+ () => chat.live.captions.set(callId, next),
2957
+ (cap) => setValue(() => cap.userIds)
2958
+ );
2959
+ return r !== null;
2960
+ },
2961
+ [chat, callId, run, setValue]
2962
+ );
2963
+ const toggle = useCallback(() => setOn(!on), [setOn, on]);
2964
+ return { on, userIds, setOn, toggle, error, pending };
2965
+ }
2966
+ function useWhiteboard(callId, Y, opts = {}) {
2967
+ const chat = usePoolse();
2968
+ const [items, setItems] = useState([]);
2969
+ const [board, setBoard] = useState(null);
2970
+ const [error, setError] = useState(null);
2971
+ const optsRef = useRef(opts);
2972
+ optsRef.current = opts;
2973
+ const selfUserId = opts.selfUserId ?? null;
2974
+ useEffect(() => {
2975
+ setItems([]);
2976
+ setBoard(null);
2977
+ setError(null);
2978
+ if (!callId || !Y) return;
2979
+ let cancelled = false;
2980
+ let open = null;
2981
+ let off = null;
2982
+ const access = () => optsRef.current.access?.(callId) ?? chat.live.whiteboard(callId);
2983
+ access().then((a) => {
2984
+ if (cancelled) return;
2985
+ open = openWhiteboard(chat, Y, a, { selfUserId, refreshAccess: access });
2986
+ off = open.model.subscribe(setItems);
2987
+ setBoard(open);
2988
+ }).catch((err) => {
2989
+ if (!cancelled) setError(asError(err));
2990
+ });
2991
+ return () => {
2992
+ cancelled = true;
2993
+ off?.();
2994
+ open?.close();
2995
+ };
2996
+ }, [chat, callId, Y, selfUserId]);
2997
+ return { items, model: board?.model ?? null, readOnly: board ? board.readOnly() : true, error };
2998
+ }
2999
+ function useRoomPresence() {
3000
+ const chat = usePoolse();
3001
+ const { me } = useMe();
3002
+ const meId = me?.id ?? null;
3003
+ const [rooms, setRooms] = useState([]);
3004
+ const [presence, setPresence] = useState({});
3005
+ const refresh = useCallback(() => {
3006
+ chat.live.rooms().then((list) => {
3007
+ setRooms(list);
3008
+ setPresence((p) => {
3009
+ const next = { ...p };
3010
+ for (const r of list) next[r.conversationId] = r.presence;
3011
+ return next;
3012
+ });
3013
+ }).catch(() => {
3014
+ });
3015
+ }, [chat]);
3016
+ useEffect(() => {
3017
+ if (!meId) return;
3018
+ refresh();
3019
+ const off = chat.live.subscribeUser(meId, {
3020
+ onRoomParticipants: (r) => {
3021
+ setPresence((p) => ({ ...p, [r.conversationId]: r }));
3022
+ setRooms(
3023
+ (list) => list.map(
3024
+ (room) => room.conversationId === r.conversationId ? { ...room, presence: r } : room
3025
+ )
3026
+ );
3027
+ }
3028
+ });
3029
+ const offStatus = onReconnect2(chat, refresh);
3030
+ return () => {
3031
+ off();
3032
+ offStatus();
3033
+ };
3034
+ }, [chat, meId, refresh]);
3035
+ return { rooms, presence, refresh };
3036
+ }
3037
+ function useRecording(callId, conversationId, initial) {
3038
+ const chat = usePoolse();
3039
+ const meId = useMeId(chat);
3040
+ const [state, setState] = useState(
3041
+ () => initial && initial.id === callId ? { recording: initial.recording ?? null, transcription: initial.transcription ?? null } : { recording: null, transcription: null }
3042
+ );
3043
+ const [notice, setNotice] = useState(null);
3044
+ const [lastRecording, setLastRecording] = useState(null);
3045
+ const [pending, setPending] = useState(false);
3046
+ const [error, setError] = useState(null);
3047
+ const [transcriptConsent, setTranscriptConsent] = useState(false);
3048
+ const seq = useRef(0);
3049
+ const hasInitial = useRef(!!initial && initial.id === callId);
3050
+ const refresh = useCallback(() => {
3051
+ if (!callId || !conversationId) return;
3052
+ const mine = ++seq.current;
3053
+ chat.liveCalls.get(conversationId).then((c) => {
3054
+ if (mine !== seq.current) return;
3055
+ if (c && c.id === callId)
3056
+ setState({ recording: c.recording ?? null, transcription: c.transcription ?? null });
3057
+ else
3058
+ setState((s) => ({
3059
+ recording: s.recording ? { ...s.recording, active: false } : null,
3060
+ transcription: s.transcription ? { ...s.transcription, active: false } : null
3061
+ }));
3062
+ }).catch(() => {
3063
+ });
3064
+ }, [chat, callId, conversationId]);
3065
+ useEffect(() => {
3066
+ if (!callId || !conversationId) {
3067
+ setState({ recording: null, transcription: null });
3068
+ return;
3069
+ }
3070
+ if (hasInitial.current) hasInitial.current = false;
3071
+ else refresh();
3072
+ const offCapture = subscribeCapture(chat, conversationId, callId, (e) => {
3073
+ seq.current++;
3074
+ setState((s) => applyCaptureEvent(s, e));
3075
+ if (e.type === "recording:started") {
3076
+ setNotice(e.evt.notice);
3077
+ setLastRecording(e.evt.recording);
3078
+ } else if (e.type === "recording:stopped" || e.type === "recording:ready") {
3079
+ setLastRecording(e.evt.recording);
3080
+ }
3081
+ });
3082
+ const conv = chat.realtime.conversation(conversationId);
3083
+ const offFinished = conv.onCallFinished((evt) => {
3084
+ if (evt.call_id !== callId) return;
3085
+ seq.current++;
3086
+ setState((s) => ({
3087
+ recording: s.recording ? { ...s.recording, active: false } : null,
3088
+ transcription: s.transcription ? { ...s.transcription, active: false } : null
3089
+ }));
3090
+ });
3091
+ const offStatus = onReconnect(chat, refresh);
3092
+ return () => {
3093
+ offCapture();
3094
+ offFinished();
3095
+ offStatus();
3096
+ };
3097
+ }, [chat, callId, conversationId, refresh]);
3098
+ const transcribing = !!state.transcription?.active;
3099
+ useEffect(() => {
3100
+ if (!conversationId || !transcribing) {
3101
+ setTranscriptConsent(false);
3102
+ return;
3103
+ }
3104
+ let cancelled = false;
3105
+ chat.calls.recording.settings(conversationId).then((s) => {
3106
+ if (!cancelled) setTranscriptConsent(s.effective.consent === "required");
3107
+ }).catch(() => {
3108
+ });
3109
+ return () => {
3110
+ cancelled = true;
3111
+ };
3112
+ }, [chat, conversationId, transcribing]);
3113
+ const run = useCallback(async (fn) => {
3114
+ setPending(true);
3115
+ setError(null);
3116
+ try {
3117
+ await fn();
3118
+ return true;
3119
+ } catch (err) {
3120
+ setError(err instanceof Error ? err : new Error(String(err)));
3121
+ return false;
3122
+ } finally {
3123
+ setPending(false);
3124
+ }
3125
+ }, []);
3126
+ const start = useCallback(
3127
+ (mode) => run(async () => {
3128
+ if (!callId) throw new Error("no call");
3129
+ const r = await chat.calls.recording.start(callId, mode ? { mode } : {});
3130
+ setLastRecording(r);
3131
+ }),
3132
+ [chat, callId, run]
3133
+ );
3134
+ const stop = useCallback(
3135
+ () => run(async () => {
3136
+ if (!callId) throw new Error("no call");
3137
+ const r = await chat.calls.recording.stop(callId);
3138
+ setLastRecording(r);
3139
+ }),
3140
+ [chat, callId, run]
3141
+ );
3142
+ const consent = useCallback(
3143
+ (decision) => run(async () => {
3144
+ if (!callId) throw new Error("no call");
3145
+ const res = await chat.calls.consent(callId, decision);
3146
+ setState(
3147
+ (s) => applyCaptureEvent(s, {
3148
+ type: "recording:consent",
3149
+ evt: { cv: 1, call_id: res.call_id, user_id: res.user_id, decision: res.decision }
3150
+ })
3151
+ );
3152
+ }),
3153
+ [chat, callId, run]
3154
+ );
3155
+ const rec = state.recording;
3156
+ const active = !!rec?.active;
3157
+ const capturing = active || transcribing;
3158
+ const consentRequired = active && !!rec?.consent_required || transcribing && transcriptConsent;
3159
+ 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;
3160
+ return {
3161
+ available: rec?.available ?? false,
3162
+ active,
3163
+ recording: rec,
3164
+ transcription: state.transcription,
3165
+ capturing,
3166
+ consentRequired,
3167
+ myConsent,
3168
+ needsConsent: capturing && consentRequired && myConsent !== "accepted",
2311
3169
  notice,
2312
3170
  lastRecording,
2313
3171
  pending,
@@ -2590,7 +3448,1094 @@ function canEditOwnMessage(args) {
2590
3448
  const sent = Date.parse(args.insertedAt);
2591
3449
  return Number.isFinite(sent) && (args.now ?? Date.now()) - sent < EDIT_WINDOW_MS;
2592
3450
  }
3451
+ function useApprovals(opts = {}) {
3452
+ const chat = usePoolse();
3453
+ const pollMs = opts.pollMs ?? 6e4;
3454
+ const [approvals, setApprovals] = useState(() => chat.approvals.pending());
3455
+ const [loading, setLoading] = useState(true);
3456
+ const [error, setError] = useState(null);
3457
+ const mounted = useRef(true);
3458
+ const refresh = useCallback(async () => {
3459
+ try {
3460
+ await chat.approvals.list();
3461
+ if (mounted.current) setError(null);
3462
+ } catch (err) {
3463
+ if (mounted.current) setError(err instanceof Error ? err : new Error(String(err)));
3464
+ } finally {
3465
+ if (mounted.current) setLoading(false);
3466
+ }
3467
+ }, [chat]);
3468
+ useEffect(() => {
3469
+ mounted.current = true;
3470
+ const off = chat.approvals.subscribe(() => setApprovals(chat.approvals.pending()));
3471
+ setApprovals(chat.approvals.pending());
3472
+ void refresh();
3473
+ void chat.agents.list().catch(() => void 0);
3474
+ const offStatus = onReconnect(chat, () => void refresh());
3475
+ const timer = pollMs > 0 ? setInterval(() => void refresh(), pollMs) : null;
3476
+ return () => {
3477
+ mounted.current = false;
3478
+ off();
3479
+ offStatus();
3480
+ if (timer) clearInterval(timer);
3481
+ };
3482
+ }, [chat, refresh, pollMs]);
3483
+ const approve = useCallback(
3484
+ (id, reason) => chat.approvals.approve(id, reason !== void 0 ? { reason } : {}),
3485
+ [chat]
3486
+ );
3487
+ const deny = useCallback(
3488
+ (id, reason) => chat.approvals.deny(id, reason !== void 0 ? { reason } : {}),
3489
+ [chat]
3490
+ );
3491
+ return { approvals, loading, error, refresh, approve, deny };
3492
+ }
3493
+ function useApproval(source) {
3494
+ const chat = usePoolse();
3495
+ const id = typeof source === "string" ? source : source?.id ?? null;
3496
+ const sourceRef = useRef(source);
3497
+ sourceRef.current = source;
3498
+ const read = () => id ? chat.approvals.peek(id) ?? (typeof sourceRef.current === "object" ? sourceRef.current : null) : null;
3499
+ const [approval, setApproval] = useState(read);
3500
+ const [loading, setLoading] = useState(() => !!id && !read());
3501
+ const [pending, setPending] = useState(null);
3502
+ const [error, setError] = useState(null);
3503
+ useEffect(() => {
3504
+ if (!id) {
3505
+ setApproval(null);
3506
+ setLoading(false);
3507
+ return;
3508
+ }
3509
+ const given = sourceRef.current;
3510
+ if (given && typeof given === "object") chat.approvals._apply(given);
3511
+ const update = () => setApproval(read());
3512
+ const off = chat.approvals.subscribe(update);
3513
+ update();
3514
+ let live = true;
3515
+ if (!chat.approvals.peek(id)) {
3516
+ setLoading(true);
3517
+ void chat.approvals.ensure(id).catch(() => null).finally(() => {
3518
+ if (live) {
3519
+ setLoading(false);
3520
+ update();
3521
+ }
3522
+ });
3523
+ }
3524
+ return () => {
3525
+ live = false;
3526
+ off();
3527
+ };
3528
+ }, [chat, id]);
3529
+ const decide = useCallback(
3530
+ async (action, reason) => {
3531
+ if (!id) return;
3532
+ setPending(action);
3533
+ setError(null);
3534
+ try {
3535
+ const opts = reason !== void 0 ? { reason } : {};
3536
+ await (action === "approve" ? chat.approvals.approve(id, opts) : chat.approvals.deny(id, opts));
3537
+ } catch (err) {
3538
+ setError(err instanceof Error ? err : new Error(String(err)));
3539
+ throw err;
3540
+ } finally {
3541
+ setPending(null);
3542
+ }
3543
+ },
3544
+ [chat, id]
3545
+ );
3546
+ return {
3547
+ approval,
3548
+ loading,
3549
+ pending,
3550
+ error,
3551
+ approve: (reason) => decide("approve", reason),
3552
+ deny: (reason) => decide("deny", reason)
3553
+ };
3554
+ }
3555
+ var asError2 = (err) => err instanceof Error ? err : new Error(String(err));
3556
+ function useCallAgents(conversationId, callId) {
3557
+ const chat = usePoolse();
3558
+ const [agents, setAgents] = useState([]);
3559
+ const [directory, setDirectory] = useState([]);
3560
+ const [loading, setLoading] = useState(!!callId);
3561
+ const [error, setError] = useState(null);
3562
+ const [pending, setPending] = useState(null);
3563
+ const [said, setSaid] = useState(null);
3564
+ const [nonce, setNonce] = useState(0);
3565
+ useEffect(() => {
3566
+ setSaid(null);
3567
+ if (!callId || !conversationId) {
3568
+ setAgents([]);
3569
+ setLoading(false);
3570
+ return;
3571
+ }
3572
+ const controller = new AbortController();
3573
+ const load = () => chat.callAgents.list(callId, controller.signal).then((list) => {
3574
+ if (controller.signal.aborted) return;
3575
+ setAgents(list);
3576
+ setError(null);
3577
+ }).catch((err) => {
3578
+ if (!controller.signal.aborted) setError(asError2(err));
3579
+ }).finally(() => {
3580
+ if (!controller.signal.aborted) setLoading(false);
3581
+ });
3582
+ setLoading(true);
3583
+ void load();
3584
+ const off = chat.callAgents.subscribe(conversationId, callId, {
3585
+ onAgents: setAgents,
3586
+ onSaid: setSaid
3587
+ });
3588
+ const offRe = onReconnect(chat, () => void load());
3589
+ return () => {
3590
+ controller.abort();
3591
+ off();
3592
+ offRe();
3593
+ };
3594
+ }, [chat, conversationId, callId, nonce]);
3595
+ useEffect(() => {
3596
+ let live = true;
3597
+ chat.agents.list().then((list) => live && setDirectory(list)).catch(() => void 0);
3598
+ return () => {
3599
+ live = false;
3600
+ };
3601
+ }, [chat]);
3602
+ const available = useMemo(() => {
3603
+ const inCall = new Set(agents.map((a) => a.agentId));
3604
+ return directory.filter(
3605
+ (a) => a.status === "active" && !a.stopped && a.voiceEnabled && !inCall.has(a.id)
3606
+ );
3607
+ }, [agents, directory]);
3608
+ const run = useCallback(async (agentId, fn) => {
3609
+ setPending(agentId);
3610
+ setError(null);
3611
+ try {
3612
+ await fn();
3613
+ } catch (err) {
3614
+ setError(asError2(err));
3615
+ throw err;
3616
+ } finally {
3617
+ setPending(null);
3618
+ }
3619
+ }, []);
3620
+ const upsert = (a) => setAgents((prev) => {
3621
+ const i = prev.findIndex((x) => x.agentId === a.agentId);
3622
+ return i < 0 ? [...prev, a] : prev.map((x, j) => j === i ? a : x);
3623
+ });
3624
+ const invite = useCallback(
3625
+ (agentId, mode = "notetaker") => run(agentId, async () => {
3626
+ if (callId) upsert(await chat.callAgents.invite(callId, agentId, mode));
3627
+ }),
3628
+ [chat, callId, run]
3629
+ );
3630
+ const setMode = useCallback(
3631
+ (agentId, mode) => run(agentId, async () => {
3632
+ if (callId) upsert(await chat.callAgents.setMode(callId, agentId, mode));
3633
+ }),
3634
+ [chat, callId, run]
3635
+ );
3636
+ const remove = useCallback(
3637
+ (agentId) => run(agentId, async () => {
3638
+ if (!callId) return;
3639
+ await chat.callAgents.remove(callId, agentId);
3640
+ setAgents((prev) => prev.filter((x) => x.agentId !== agentId));
3641
+ }),
3642
+ [chat, callId, run]
3643
+ );
3644
+ const agentFor = useCallback(
3645
+ (identity) => agents.find((a) => a.userId === identity) ?? null,
3646
+ [agents]
3647
+ );
3648
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
3649
+ return {
3650
+ agents,
3651
+ available,
3652
+ loading,
3653
+ error,
3654
+ pending,
3655
+ invite,
3656
+ setMode,
3657
+ remove,
3658
+ said,
3659
+ agentFor,
3660
+ refresh
3661
+ };
3662
+ }
3663
+ function useWhisper(callId) {
3664
+ const chat = usePoolse();
3665
+ const { me } = useMe();
3666
+ const userId = me?.id ?? null;
3667
+ const [whisper, setWhisper] = useState(null);
3668
+ const [hints, setHints] = useState([]);
3669
+ const [latest, setLatest] = useState(null);
3670
+ const [loading, setLoading] = useState(!!callId);
3671
+ const [pending, setPending] = useState(false);
3672
+ const [error, setError] = useState(null);
3673
+ const onRef = useRef(false);
3674
+ onRef.current = whisper?.on ?? false;
3675
+ const merge = useCallback((list) => {
3676
+ setHints((prev) => {
3677
+ const byId = new Map(prev.map((h) => [h.id, h]));
3678
+ for (const h of list) byId.set(h.id, h);
3679
+ return [...byId.values()].sort((a, b) => (a.at ?? "").localeCompare(b.at ?? ""));
3680
+ });
3681
+ }, []);
3682
+ useEffect(() => {
3683
+ setHints([]);
3684
+ setLatest(null);
3685
+ setWhisper(null);
3686
+ if (!callId) {
3687
+ setLoading(false);
3688
+ return;
3689
+ }
3690
+ const controller = new AbortController();
3691
+ const load = () => chat.callAgents.whisper.get(callId, controller.signal).then((res) => {
3692
+ if (controller.signal.aborted) return;
3693
+ setWhisper(res.whisper);
3694
+ merge(res.hints);
3695
+ setError(null);
3696
+ }).catch((err) => {
3697
+ if (!controller.signal.aborted) setError(asError2(err));
3698
+ }).finally(() => {
3699
+ if (!controller.signal.aborted) setLoading(false);
3700
+ });
3701
+ setLoading(true);
3702
+ void load();
3703
+ const off = userId ? chat.callAgents.whisper.subscribe(userId, callId, {
3704
+ onHint: (h) => {
3705
+ merge([h]);
3706
+ setLatest(h);
3707
+ },
3708
+ onChanged: setWhisper
3709
+ }) : () => void 0;
3710
+ const offRe = onReconnect(chat, () => void load());
3711
+ return () => {
3712
+ controller.abort();
3713
+ off();
3714
+ offRe();
3715
+ };
3716
+ }, [chat, callId, userId, merge]);
3717
+ const setOn = useCallback(
3718
+ async (next, opts = {}) => {
3719
+ if (!callId) return;
3720
+ setPending(true);
3721
+ setError(null);
3722
+ try {
3723
+ setWhisper(await chat.callAgents.whisper.set(callId, next, opts));
3724
+ } catch (err) {
3725
+ setError(asError2(err));
3726
+ throw err;
3727
+ } finally {
3728
+ setPending(false);
3729
+ }
3730
+ },
3731
+ [chat, callId]
3732
+ );
3733
+ const toggle = useCallback(() => setOn(!onRef.current), [setOn]);
3734
+ return {
3735
+ on: whisper?.on ?? false,
3736
+ whisper,
3737
+ agentName: whisper?.on ? whisper.agent?.name ?? null : null,
3738
+ hints,
3739
+ latest,
3740
+ loading,
3741
+ pending,
3742
+ error,
3743
+ setOn,
3744
+ toggle
3745
+ };
3746
+ }
3747
+ function useEscalations(opts = {}) {
3748
+ const chat = usePoolse();
3749
+ const pollMs = opts.pollMs ?? 3e4;
3750
+ const callId = opts.callId ?? null;
3751
+ const read = useCallback(
3752
+ () => ({
3753
+ pending: chat.escalations.pending().filter((e) => !callId || e.callId === callId),
3754
+ all: chat.escalations.all().filter((e) => !callId || e.callId === callId)
3755
+ }),
3756
+ [chat, callId]
3757
+ );
3758
+ const [state, setState] = useState(read);
3759
+ const [loading, setLoading] = useState(true);
3760
+ const [error, setError] = useState(null);
3761
+ const [pending, setPending] = useState(null);
3762
+ const mounted = useRef(true);
3763
+ const refresh = useCallback(async () => {
3764
+ try {
3765
+ await chat.escalations.list();
3766
+ if (mounted.current) setError(null);
3767
+ } catch (err) {
3768
+ if (mounted.current) setError(asError2(err));
3769
+ } finally {
3770
+ if (mounted.current) setLoading(false);
3771
+ }
3772
+ }, [chat]);
3773
+ useEffect(() => {
3774
+ mounted.current = true;
3775
+ const off = chat.escalations.subscribe(() => setState(read()));
3776
+ setState(read());
3777
+ void refresh();
3778
+ const offRe = onReconnect(chat, () => void refresh());
3779
+ const timer = pollMs > 0 ? setInterval(() => void refresh(), pollMs) : null;
3780
+ return () => {
3781
+ mounted.current = false;
3782
+ off();
3783
+ offRe();
3784
+ if (timer) clearInterval(timer);
3785
+ };
3786
+ }, [chat, read, refresh, pollMs]);
3787
+ const reply = useCallback(
3788
+ async (id, r) => {
3789
+ setPending(id);
3790
+ setError(null);
3791
+ try {
3792
+ return await chat.escalations.reply(id, r);
3793
+ } catch (err) {
3794
+ if (mounted.current) setError(asError2(err));
3795
+ throw err;
3796
+ } finally {
3797
+ if (mounted.current) setPending(null);
3798
+ }
3799
+ },
3800
+ [chat]
3801
+ );
3802
+ const [, setNames] = useState(0);
3803
+ useEffect(() => {
3804
+ let live = true;
3805
+ void chat.agents.list().then(() => live && setNames((n) => n + 1)).catch(() => void 0);
3806
+ return () => {
3807
+ live = false;
3808
+ };
3809
+ }, [chat]);
3810
+ const agentNameOf = useCallback(
3811
+ (e) => (e.agentId ? chat.agents.peek(e.agentId)?.name : null) ?? "Your agent",
3812
+ [chat]
3813
+ );
3814
+ return {
3815
+ escalations: state.pending,
3816
+ all: state.all,
3817
+ loading,
3818
+ error,
3819
+ pending,
3820
+ reply,
3821
+ agentNameOf,
3822
+ refresh
3823
+ };
3824
+ }
3825
+ function useAgentBrief(target) {
3826
+ const chat = usePoolse();
3827
+ const meetingId = target.scheduledMeetingId ?? null;
3828
+ const callId = target.callId ?? null;
3829
+ const [brief, setBrief] = useState(null);
3830
+ const [loading, setLoading] = useState(!!(meetingId || callId));
3831
+ const [saving, setSaving] = useState(false);
3832
+ const [error, setError] = useState(null);
3833
+ const [nonce, setNonce] = useState(0);
3834
+ useEffect(() => {
3835
+ setBrief(null);
3836
+ if (!meetingId && !callId) {
3837
+ setLoading(false);
3838
+ return;
3839
+ }
3840
+ const controller = new AbortController();
3841
+ setLoading(true);
3842
+ chat.callAgents.briefs.list({
3843
+ ...meetingId ? { scheduledMeetingId: meetingId } : {},
3844
+ ...callId ? { callId } : {},
3845
+ signal: controller.signal
3846
+ }).then((list) => {
3847
+ if (!controller.signal.aborted) setBrief(list[0] ?? null);
3848
+ }).catch((err) => {
3849
+ if (!controller.signal.aborted) setError(asError2(err));
3850
+ }).finally(() => {
3851
+ if (!controller.signal.aborted) setLoading(false);
3852
+ });
3853
+ return () => controller.abort();
3854
+ }, [chat, meetingId, callId, nonce]);
3855
+ const save = useCallback(
3856
+ async (input) => {
3857
+ setSaving(true);
3858
+ setError(null);
3859
+ try {
3860
+ const b = await chat.callAgents.briefs.create({
3861
+ ...input,
3862
+ ...meetingId ? { scheduledMeetingId: meetingId } : {},
3863
+ ...callId && !meetingId ? { callId } : {}
3864
+ });
3865
+ setBrief(b);
3866
+ return b;
3867
+ } catch (err) {
3868
+ setError(asError2(err));
3869
+ throw err;
3870
+ } finally {
3871
+ setSaving(false);
3872
+ }
3873
+ },
3874
+ [chat, meetingId, callId]
3875
+ );
3876
+ const remove = useCallback(async () => {
3877
+ if (!brief) return;
3878
+ setSaving(true);
3879
+ setError(null);
3880
+ try {
3881
+ await chat.callAgents.briefs.remove(brief.id);
3882
+ setBrief(null);
3883
+ } catch (err) {
3884
+ setError(asError2(err));
3885
+ throw err;
3886
+ } finally {
3887
+ setSaving(false);
3888
+ }
3889
+ }, [chat, brief]);
3890
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
3891
+ return { brief, loading, saving, error, save, remove, refresh };
3892
+ }
3893
+ function useLoaded(load, key) {
3894
+ const [items, setItems] = useState([]);
3895
+ const [loading, setLoading] = useState(true);
3896
+ const [error, setError] = useState(null);
3897
+ const [nonce, setNonce] = useState(0);
3898
+ const loadRef = useRef(load);
3899
+ loadRef.current = load;
3900
+ useEffect(() => {
3901
+ const controller = new AbortController();
3902
+ setLoading(true);
3903
+ loadRef.current(controller.signal).then((rows) => {
3904
+ if (controller.signal.aborted) return;
3905
+ setItems(rows);
3906
+ setError(null);
3907
+ }).catch((err) => {
3908
+ if (controller.signal.aborted || err?.name === "AbortError") return;
3909
+ setError(err instanceof Error ? err : new Error(String(err)));
3910
+ }).finally(() => {
3911
+ if (!controller.signal.aborted) setLoading(false);
3912
+ });
3913
+ return () => controller.abort();
3914
+ }, [key, nonce]);
3915
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
3916
+ return { items, setItems, loading, error, refresh };
3917
+ }
3918
+ function useAgents() {
3919
+ const chat = usePoolse();
3920
+ const { items, loading, error, refresh } = useLoaded((signal) => chat.agents.list(signal), "all");
3921
+ return { agents: items, loading, error, refresh };
3922
+ }
3923
+ function useConversationAgents(conversationId) {
3924
+ const chat = usePoolse();
3925
+ const { items, setItems, loading, error, refresh } = useLoaded(
3926
+ (signal) => conversationId ? chat.agents.inConversation(conversationId, signal) : Promise.resolve([]),
3927
+ conversationId ?? ""
3928
+ );
3929
+ const put = (scope) => setItems((list) => list.map((a) => a.id === scope.agentId ? { ...a, scope } : a));
3930
+ const setScope = useCallback(
3931
+ async (agentId, patch) => {
3932
+ if (!conversationId) throw new Error("no conversation");
3933
+ const scope = await chat.agents.setScope(conversationId, agentId, patch);
3934
+ put(scope);
3935
+ return scope;
3936
+ },
3937
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3938
+ [chat, conversationId]
3939
+ );
3940
+ const resetScope = useCallback(
3941
+ async (agentId) => {
3942
+ if (!conversationId) throw new Error("no conversation");
3943
+ const scope = await chat.agents.resetScope(conversationId, agentId);
3944
+ put(scope);
3945
+ return scope;
3946
+ },
3947
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3948
+ [chat, conversationId]
3949
+ );
3950
+ return { agents: items, loading, error, refresh, setScope, resetScope };
3951
+ }
3952
+ function useMemory(opts = {}) {
3953
+ const chat = usePoolse();
3954
+ const key = JSON.stringify([opts.conversationId, opts.kind, opts.q, opts.limit]);
3955
+ const { items, setItems, loading, error, refresh } = useLoaded(
3956
+ (signal) => chat.agents.memory({
3957
+ ...opts.conversationId ? { conversationId: opts.conversationId } : {},
3958
+ ...opts.kind ? { kind: opts.kind } : {},
3959
+ ...opts.q ? { q: opts.q } : {},
3960
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
3961
+ signal
3962
+ }),
3963
+ key
3964
+ );
3965
+ const add = useCallback(
3966
+ async (input) => {
3967
+ const fact = await chat.agents.addMemory(input);
3968
+ setItems((list) => [fact, ...list]);
3969
+ return fact;
3970
+ },
3971
+ [chat, setItems]
3972
+ );
3973
+ const update = useCallback(
3974
+ async (id, patch) => {
3975
+ const fact = await chat.agents.updateMemory(id, patch);
3976
+ setItems((list) => list.map((f) => f.id === id ? fact : f));
3977
+ return fact;
3978
+ },
3979
+ [chat, setItems]
3980
+ );
3981
+ const remove = useCallback(
3982
+ async (id) => {
3983
+ await chat.agents.deleteMemory(id);
3984
+ setItems((list) => list.filter((f) => f.id !== id));
3985
+ },
3986
+ [chat, setItems]
3987
+ );
3988
+ return { facts: items, loading, error, refresh, add, update, remove };
3989
+ }
3990
+ function useFollowups(opts = {}) {
3991
+ const chat = usePoolse();
3992
+ const { items, setItems, loading, error, refresh } = useLoaded(
3993
+ (signal) => chat.agents.followups({ ...opts.status ? { status: opts.status } : {}, signal }),
3994
+ opts.status ?? ""
3995
+ );
3996
+ const act = useCallback(
3997
+ async (id, action) => {
3998
+ const f = await (action === "done" ? chat.agents.followupDone(id) : chat.agents.followupCancel(id));
3999
+ setItems(
4000
+ (list) => opts.status && f.status !== opts.status ? list.filter((x) => x.id !== id) : list.map((x) => x.id === id ? f : x)
4001
+ );
4002
+ return f;
4003
+ },
4004
+ [chat, setItems, opts.status]
4005
+ );
4006
+ return {
4007
+ followups: items,
4008
+ loading,
4009
+ error,
4010
+ refresh,
4011
+ done: (id) => act(id, "done"),
4012
+ cancel: (id) => act(id, "cancel")
4013
+ };
4014
+ }
4015
+ function useAskMeetings(opts = {}) {
4016
+ const chat = usePoolse();
4017
+ const callId = opts.callId ?? null;
4018
+ const conversationId = opts.conversationId ?? null;
4019
+ const [answer, setAnswer] = useState(null);
4020
+ const [question, setQuestion] = useState(null);
4021
+ const [loading, setLoading] = useState(false);
4022
+ const [error, setError] = useState(null);
4023
+ const inflight = useRef(null);
4024
+ useEffect(() => () => inflight.current?.abort(), []);
4025
+ const reset = useCallback(() => {
4026
+ inflight.current?.abort();
4027
+ inflight.current = null;
4028
+ setAnswer(null);
4029
+ setQuestion(null);
4030
+ setLoading(false);
4031
+ setError(null);
4032
+ }, []);
4033
+ useEffect(() => reset, [callId, conversationId, reset]);
4034
+ const ask = useCallback(
4035
+ async (q) => {
4036
+ const text = q.trim().slice(0, ASK_QUESTION_MAX);
4037
+ if (!text) return null;
4038
+ inflight.current?.abort();
4039
+ const controller = new AbortController();
4040
+ inflight.current = controller;
4041
+ setQuestion(text);
4042
+ setLoading(true);
4043
+ setError(null);
4044
+ try {
4045
+ const res = await chat.meetings.ask({
4046
+ question: text,
4047
+ ...callId ? { callId } : {},
4048
+ ...conversationId ? { conversationId } : {},
4049
+ signal: controller.signal
4050
+ });
4051
+ if (inflight.current !== controller) return null;
4052
+ setAnswer(res);
4053
+ return res;
4054
+ } catch (err) {
4055
+ if (inflight.current !== controller) return null;
4056
+ if (err?.name === "AbortError") return null;
4057
+ setError(err instanceof Error ? err : new Error(String(err)));
4058
+ return null;
4059
+ } finally {
4060
+ if (inflight.current === controller) {
4061
+ inflight.current = null;
4062
+ setLoading(false);
4063
+ }
4064
+ }
4065
+ },
4066
+ [chat, callId, conversationId]
4067
+ );
4068
+ return { answer, question, loading, error, ask, reset };
4069
+ }
4070
+ function useRecordingUrl(recordingId) {
4071
+ const chat = usePoolse();
4072
+ const [url, setUrl] = useState(null);
4073
+ const [contentType, setContentType] = useState(null);
4074
+ const [loading, setLoading] = useState(!!recordingId);
4075
+ const [error, setError] = useState(null);
4076
+ const [nonce, setNonce] = useState(0);
4077
+ useEffect(() => {
4078
+ if (!recordingId) {
4079
+ setUrl(null);
4080
+ setLoading(false);
4081
+ setError(null);
4082
+ return;
4083
+ }
4084
+ const controller = new AbortController();
4085
+ setLoading(true);
4086
+ setError(null);
4087
+ chat.calls.recording.downloadUrl(recordingId, controller.signal).then((res) => {
4088
+ if (controller.signal.aborted) return;
4089
+ setUrl(res.url);
4090
+ setContentType(res.content_type);
4091
+ setLoading(false);
4092
+ }).catch((err) => {
4093
+ if (controller.signal.aborted) return;
4094
+ setError(err instanceof Error ? err : new Error(String(err)));
4095
+ setLoading(false);
4096
+ });
4097
+ return () => controller.abort();
4098
+ }, [chat, recordingId, nonce]);
4099
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
4100
+ return { url, contentType, loading, error, refresh };
4101
+ }
4102
+ function useCallSummary(callId, initial = null) {
4103
+ const chat = usePoolse();
4104
+ const [summary, setSummary] = useState(initial);
4105
+ const [loading, setLoading] = useState(false);
4106
+ const [missing, setMissing] = useState(false);
4107
+ const [error, setError] = useState(null);
4108
+ const seq = useRef(0);
4109
+ const conversationId = initial?.conversationId ?? summary?.conversationId ?? null;
4110
+ const refresh = useCallback(() => {
4111
+ if (!callId) return;
4112
+ const mine = ++seq.current;
4113
+ setLoading(true);
4114
+ chat.meetings.summary(callId).then((s) => {
4115
+ if (mine !== seq.current) return;
4116
+ setSummary(s);
4117
+ setMissing(false);
4118
+ setError(null);
4119
+ }).catch((err) => {
4120
+ if (mine !== seq.current) return;
4121
+ if (err instanceof ApiError && err.status === 404) setMissing(true);
4122
+ else setError(err instanceof Error ? err : new Error(String(err)));
4123
+ }).finally(() => {
4124
+ if (mine === seq.current) setLoading(false);
4125
+ });
4126
+ }, [chat, callId]);
4127
+ const needsFull = !initial || initial.shortened;
4128
+ useEffect(() => {
4129
+ if (needsFull) refresh();
4130
+ }, [refresh, needsFull]);
4131
+ useEffect(() => {
4132
+ if (!callId || !conversationId) return;
4133
+ return chat.realtime.conversation(conversationId).onSummaryReady((evt) => {
4134
+ if (evt.call_id !== callId) return;
4135
+ const s = summaryFromWire(evt.summary);
4136
+ if (s) {
4137
+ seq.current++;
4138
+ setSummary(s);
4139
+ }
4140
+ refresh();
4141
+ });
4142
+ }, [chat, callId, conversationId, refresh]);
4143
+ return { summary, loading, missing, error, refresh };
4144
+ }
4145
+ function useRecordingPlayback(recordingId) {
4146
+ const chat = usePoolse();
4147
+ const [playback, setPlayback] = useState(null);
4148
+ const [loading, setLoading] = useState(!!recordingId);
4149
+ const [error, setError] = useState(null);
4150
+ const [nonce, setNonce] = useState(0);
4151
+ useEffect(() => {
4152
+ if (!recordingId) {
4153
+ setPlayback(null);
4154
+ setLoading(false);
4155
+ return;
4156
+ }
4157
+ const controller = new AbortController();
4158
+ setLoading(true);
4159
+ chat.meetings.playback(recordingId, controller.signal).then((p) => {
4160
+ if (controller.signal.aborted) return;
4161
+ setPlayback(p);
4162
+ setError(null);
4163
+ }).catch((err) => {
4164
+ if (controller.signal.aborted) return;
4165
+ setError(err instanceof Error ? err : new Error(String(err)));
4166
+ }).finally(() => {
4167
+ if (!controller.signal.aborted) setLoading(false);
4168
+ });
4169
+ return () => controller.abort();
4170
+ }, [chat, recordingId, nonce]);
4171
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
4172
+ return { playback, loading, error, refresh };
4173
+ }
4174
+ function useClip(clipId, initial = null) {
4175
+ const chat = usePoolse();
4176
+ const [clip, setClip] = useState(initial);
4177
+ const [url, setUrl] = useState(null);
4178
+ const [loading, setLoading] = useState(!!clipId);
4179
+ const [error, setError] = useState(null);
4180
+ const [nonce, setNonce] = useState(0);
4181
+ useEffect(() => {
4182
+ if (!clipId) {
4183
+ setClip(null);
4184
+ setLoading(false);
4185
+ return;
4186
+ }
4187
+ const controller = new AbortController();
4188
+ setLoading(true);
4189
+ chat.meetings.clip(clipId, controller.signal).then(async (c) => {
4190
+ if (controller.signal.aborted) return;
4191
+ setClip(c);
4192
+ if (c.status === "ready") {
4193
+ const d = await chat.meetings.clipDownloadUrl(clipId, controller.signal);
4194
+ if (!controller.signal.aborted) setUrl(d.url);
4195
+ }
4196
+ setError(null);
4197
+ }).catch((err) => {
4198
+ if (controller.signal.aborted) return;
4199
+ setError(err instanceof Error ? err : new Error(String(err)));
4200
+ }).finally(() => {
4201
+ if (!controller.signal.aborted) setLoading(false);
4202
+ });
4203
+ return () => controller.abort();
4204
+ }, [chat, clipId, nonce]);
4205
+ const conversationId = clip?.conversationId ?? null;
4206
+ useEffect(() => {
4207
+ if (!clipId || !conversationId) return;
4208
+ const conv = chat.realtime.conversation(conversationId);
4209
+ const apply = (evt) => {
4210
+ const c = clipFromWire(evt.clip);
4211
+ if (!c || c.id !== clipId) return;
4212
+ setClip(c);
4213
+ if (c.status === "ready") setNonce((n) => n + 1);
4214
+ if (c.status === "deleted") setUrl(null);
4215
+ };
4216
+ const offs = [conv.onClipReady(apply), conv.onClipDeleted(apply)];
4217
+ return () => offs.forEach((off) => off());
4218
+ }, [chat, clipId, conversationId]);
4219
+ const refresh = useCallback(() => setNonce((n) => n + 1), []);
4220
+ return { clip, url, loading, error, refresh };
4221
+ }
4222
+ function usePoll(message) {
4223
+ const chat = usePoolse();
4224
+ const [poll, setPoll] = useState(message.poll ?? null);
4225
+ const [mine, setMine] = useState(message.my_option_ids ?? []);
4226
+ const [pending, setPending] = useState(false);
4227
+ const [error, setError] = useState(null);
4228
+ const mineRef = useRef(mine);
4229
+ mineRef.current = mine;
4230
+ const pollRef = useRef(poll);
4231
+ pollRef.current = poll;
4232
+ const pollKey = JSON.stringify(message.poll ?? null);
4233
+ const mineKey = JSON.stringify(message.my_option_ids ?? null);
4234
+ useEffect(() => {
4235
+ setPoll(JSON.parse(pollKey));
4236
+ }, [pollKey]);
4237
+ useEffect(() => {
4238
+ const m = JSON.parse(mineKey);
4239
+ if (m) setMine(m);
4240
+ }, [mineKey]);
4241
+ useEffect(() => {
4242
+ const conv = chat.realtime.conversation(message.conversation_id);
4243
+ return conv.onPollUpdated((evt) => {
4244
+ if (evt.message_id === message.id) setPoll(evt.poll);
4245
+ });
4246
+ }, [chat, message.id, message.conversation_id]);
4247
+ const write = useCallback(
4248
+ async (next) => {
4249
+ const before = mineRef.current;
4250
+ const p = pollRef.current;
4251
+ if (!p) return;
4252
+ const me = chat.me.peek()?.id;
4253
+ setMine(next);
4254
+ setPoll(applyLocalVote(p, before, next, me));
4255
+ setPending(true);
4256
+ setError(null);
4257
+ try {
4258
+ const res = await chat.messages.one(message.id).vote(next);
4259
+ setPoll(res.poll);
4260
+ setMine(res.my_option_ids);
4261
+ } catch (err) {
4262
+ setMine(before);
4263
+ setPoll(p);
4264
+ setError(err);
4265
+ } finally {
4266
+ setPending(false);
4267
+ }
4268
+ },
4269
+ [chat, message.id]
4270
+ );
4271
+ const closed = poll ? isPollClosed(poll) : true;
4272
+ return {
4273
+ poll,
4274
+ myOptionIds: mine,
4275
+ closed,
4276
+ pending,
4277
+ error,
4278
+ toggle: async (optionId) => {
4279
+ const p = pollRef.current;
4280
+ if (!p || isPollClosed(p)) return;
4281
+ await write(toggleVote(p, mineRef.current, optionId));
4282
+ },
4283
+ clear: () => write([]),
4284
+ close: async () => {
4285
+ setError(null);
4286
+ try {
4287
+ const res = await chat.messages.one(message.id).closePoll();
4288
+ setPoll(res.poll);
4289
+ } catch (err) {
4290
+ setError(err);
4291
+ }
4292
+ }
4293
+ };
4294
+ }
4295
+ function usePins(conversationId) {
4296
+ const chat = usePoolse();
4297
+ const [pins, setPins] = useState([]);
4298
+ const [loading, setLoading] = useState(true);
4299
+ const [error, setError] = useState(null);
4300
+ const refresh = useCallback(async () => {
4301
+ try {
4302
+ setPins(await chat.conversations.one(conversationId).messages.pins());
4303
+ setError(null);
4304
+ } catch (err) {
4305
+ setError(err);
4306
+ } finally {
4307
+ setLoading(false);
4308
+ }
4309
+ }, [chat, conversationId]);
4310
+ useEffect(() => {
4311
+ setLoading(true);
4312
+ void refresh();
4313
+ const conv = chat.realtime.conversation(conversationId);
4314
+ return conv.onPinChanged(() => void refresh());
4315
+ }, [chat, conversationId, refresh]);
4316
+ return {
4317
+ pins,
4318
+ loading,
4319
+ error,
4320
+ refresh,
4321
+ pin: async (id) => {
4322
+ await chat.messages.one(id).pin();
4323
+ await refresh();
4324
+ },
4325
+ unpin: async (id) => {
4326
+ setPins((p) => p.filter((m) => m.id !== id));
4327
+ await chat.messages.one(id).unpin();
4328
+ await refresh();
4329
+ }
4330
+ };
4331
+ }
4332
+ function useThreadFollow(rootId) {
4333
+ const chat = usePoolse();
4334
+ const [following, setState] = useState(null);
4335
+ const [error, setError] = useState(null);
4336
+ useEffect(() => {
4337
+ if (!rootId) return;
4338
+ let live = true;
4339
+ setState(null);
4340
+ chat.messages.one(rootId).followState().then((s) => live && setState(s.following)).catch((err) => live && setError(err));
4341
+ return () => {
4342
+ live = false;
4343
+ };
4344
+ }, [chat, rootId]);
4345
+ return {
4346
+ following,
4347
+ error,
4348
+ setFollowing: async (on) => {
4349
+ if (!rootId) return;
4350
+ const before = following;
4351
+ setState(on);
4352
+ try {
4353
+ setState((await chat.messages.one(rootId).setFollow(on)).following);
4354
+ } catch (err) {
4355
+ setState(before);
4356
+ setError(err);
4357
+ }
4358
+ }
4359
+ };
4360
+ }
4361
+ function useCatchUp(conversationId) {
4362
+ const chat = usePoolse();
4363
+ const [result, setResult] = useState(null);
4364
+ const [loading, setLoading] = useState(false);
4365
+ const [error, setError] = useState(null);
4366
+ return {
4367
+ result,
4368
+ loading,
4369
+ error,
4370
+ run: async (opts) => {
4371
+ setLoading(true);
4372
+ setError(null);
4373
+ try {
4374
+ const r = await chat.conversations.one(conversationId).messages.catchUp(opts);
4375
+ setResult(r);
4376
+ return r;
4377
+ } catch (err) {
4378
+ setError(err);
4379
+ return null;
4380
+ } finally {
4381
+ setLoading(false);
4382
+ }
4383
+ }
4384
+ };
4385
+ }
4386
+ function useTranslation(messageId, language) {
4387
+ const chat = usePoolse();
4388
+ const [translation, setTranslation] = useState(null);
4389
+ const [loading, setLoading] = useState(false);
4390
+ const [error, setError] = useState(null);
4391
+ useEffect(() => setTranslation(null), [messageId, language]);
4392
+ return {
4393
+ translation,
4394
+ loading,
4395
+ error,
4396
+ reset: () => setTranslation(null),
4397
+ translate: async () => {
4398
+ setLoading(true);
4399
+ setError(null);
4400
+ try {
4401
+ setTranslation(await chat.messages.one(messageId).translate(language));
4402
+ } catch (err) {
4403
+ setError(err);
4404
+ } finally {
4405
+ setLoading(false);
4406
+ }
4407
+ }
4408
+ };
4409
+ }
4410
+ function useScheduledMessages(conversationId) {
4411
+ const chat = usePoolse();
4412
+ const [scheduled, setScheduled] = useState([]);
4413
+ const [loading, setLoading] = useState(true);
4414
+ const [error, setError] = useState(null);
4415
+ const refresh = useCallback(async () => {
4416
+ try {
4417
+ setScheduled(
4418
+ await chat.scheduledMessages.list(
4419
+ conversationId ? { conversation_id: conversationId } : {}
4420
+ )
4421
+ );
4422
+ setError(null);
4423
+ } catch (err) {
4424
+ setError(err);
4425
+ } finally {
4426
+ setLoading(false);
4427
+ }
4428
+ }, [chat, conversationId]);
4429
+ useEffect(() => {
4430
+ void refresh();
4431
+ const me = chat.me.peek()?.id;
4432
+ if (!me) return;
4433
+ return chat.realtime.user(me).onScheduledMessage(() => void refresh());
4434
+ }, [chat, refresh]);
4435
+ return {
4436
+ scheduled,
4437
+ loading,
4438
+ error,
4439
+ refresh,
4440
+ schedule: async (cid, req) => {
4441
+ const s = await chat.conversations.one(cid).messages.schedule(req);
4442
+ await refresh();
4443
+ return s;
4444
+ },
4445
+ cancel: async (id) => {
4446
+ setScheduled((l) => l.filter((s) => s.id !== id));
4447
+ await chat.scheduledMessages.cancel(id);
4448
+ },
4449
+ sendNow: async (id) => {
4450
+ setScheduled((l) => l.filter((s) => s.id !== id));
4451
+ await chat.scheduledMessages.sendNow(id);
4452
+ },
4453
+ reschedule: async (id, sendAt) => {
4454
+ await chat.scheduledMessages.update(id, { send_at: sendAt });
4455
+ await refresh();
4456
+ }
4457
+ };
4458
+ }
4459
+ function useFiles(conversationId, kind) {
4460
+ const chat = usePoolse();
4461
+ const [files, setFiles] = useState([]);
4462
+ const [cursor, setCursor] = useState(null);
4463
+ const [hasMore, setHasMore] = useState(false);
4464
+ const [loading, setLoading] = useState(true);
4465
+ const [error, setError] = useState(null);
4466
+ const load = useCallback(
4467
+ async (before) => {
4468
+ setLoading(true);
4469
+ try {
4470
+ const page = await chat.conversations.one(conversationId).messages.files({ ...kind ? { kind } : {}, ...before ? { before } : {} });
4471
+ setFiles((f) => before ? [...f, ...page.data] : page.data);
4472
+ setCursor(page.next_cursor);
4473
+ setHasMore(page.next_cursor !== null);
4474
+ setError(null);
4475
+ } catch (err) {
4476
+ setError(err);
4477
+ } finally {
4478
+ setLoading(false);
4479
+ }
4480
+ },
4481
+ [chat, conversationId, kind]
4482
+ );
4483
+ useEffect(() => {
4484
+ void load(null);
4485
+ const conv = chat.realtime.conversation(conversationId);
4486
+ return conv.onAttachmentProcessed((evt) => {
4487
+ if (kind && evt.attachment.kind !== kind) return;
4488
+ setFiles((f) => {
4489
+ const group = evt.attachment.version_group_id;
4490
+ const rest = f.filter(
4491
+ (a) => a.id !== evt.attachment.id && (!group || a.version_group_id !== group)
4492
+ );
4493
+ return [evt.attachment, ...rest];
4494
+ });
4495
+ });
4496
+ }, [chat, conversationId, kind, load]);
4497
+ return {
4498
+ files,
4499
+ loading,
4500
+ error,
4501
+ hasMore,
4502
+ loadMore: async () => {
4503
+ if (cursor) await load(cursor);
4504
+ }
4505
+ };
4506
+ }
4507
+ var NAME = /^[a-z0-9_+-]{1,32}$/;
4508
+ function customEmojiToken(name) {
4509
+ return `:${name}:`;
4510
+ }
4511
+ function parseCustomEmojiToken(token) {
4512
+ const m = /^:([a-z0-9_+-]{1,32}):$/.exec(token);
4513
+ return m ? m[1] : null;
4514
+ }
4515
+ function findCustomEmoji(token, set) {
4516
+ const name = parseCustomEmojiToken(token);
4517
+ if (!name || !set) return null;
4518
+ return set.find((e) => e.name === name) ?? null;
4519
+ }
4520
+ function searchCustomEmoji(set, query) {
4521
+ const words = query.toLowerCase().replace(/:/g, " ").split(/\s+/).filter(Boolean);
4522
+ if (words.length === 0) return [...set];
4523
+ const hits = set.filter((e) => NAME.test(e.name) && words.every((w) => e.name.includes(w)));
4524
+ return hits.sort(
4525
+ (a, b) => Number(!a.name.startsWith(words[0])) - Number(!b.name.startsWith(words[0])) || a.name.localeCompare(b.name)
4526
+ );
4527
+ }
4528
+ var CustomEmojiContext = createContext([]);
4529
+ function CustomEmojiProvider({
4530
+ emoji,
4531
+ children
4532
+ }) {
4533
+ return createElement(CustomEmojiContext.Provider, { value: emoji }, children);
4534
+ }
4535
+ function useCustomEmoji() {
4536
+ return useContext(CustomEmojiContext);
4537
+ }
2593
4538
 
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 };
4539
+ export { CustomEmojiProvider, EDIT_WINDOW_MS, FORMAT_ACTIONS, MESSAGE_PLAYBACK_RATES, PoolseProvider, applyCaptureEvent, applyFormat, applySlashCommand, canEditOwnMessage, computeGroupPosition, customEmojiToken, filterConversations, filterSlashCommands, findCustomEmoji, formatDayLabel, formatForShortcut, mentionGroupMeta, nextPlaybackRate, orderUnread, parseCustomEmojiToken, parseSlashCommand, playbackRateLabel, rankMentionGroups, readDlpError, receiptsOf, sameDay, sameGroup, searchCustomEmoji, slashCommandsFromWorkspace, slashQuery, useAgenda, useAgent, useAgentBrief, useAgents, useAppEvent, useApproval, useApprovals, useAskMeetings, useAttachmentUpload, useAttachmentUrl, useBreakouts, useCallAgents, useCallMeeting, useCallQuality, useCallReactions, useCallRoom, useCallSummary, useCaptions, useCatchUp, useClientTimings, useClip, useConversation, useConversationAgents, useConversationPresence, useConversations, useCustomEmoji, useEscalations, useFiles, useFollowups, useLiveCall, useLiveTranscript, useLobby, useMe, useMembers, useMemory, useMessageStreams, useMessages, useMoments, useOptionalPoolse, useOutbox, usePins, usePoll, usePoolse, usePresence, usePresenceMany, useQuestions, useReactions, useReadReceipts, useRealtimeStatus, useRecording, useRecordingPlayback, useRecordingUrl, useRecordings, useRoom, useRoomPresence, useScheduledMessages, useScreenAnnotations, useStage, useThread, useThreadFollow, useTranscript, useTranscripts, useTranslation, useTyping, useUnreadQueue, useUnreadTotals, useUser, useUserPresence, useWhisper, useWhiteboard, waveformBars };
2595
4540
  //# sourceMappingURL=index.js.map
2596
4541
  //# sourceMappingURL=index.js.map