@ciridae/voice-conversations-react 0.0.0-stage → 0.1.0-nightly.0.bootstrap

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +30 -2
  2. package/components/BrowserTalkButton.tsx +96 -0
  3. package/components/CallBanner.tsx +43 -0
  4. package/components/CallCaptions.tsx +38 -0
  5. package/components/CallEntry.tsx +89 -0
  6. package/components/CallTranscript.tsx +58 -0
  7. package/components/RecentCallEntries.tsx +211 -0
  8. package/components/describeBrowserTalkError.ts +39 -0
  9. package/components/formatCallClock.ts +9 -0
  10. package/components/useEndPresentCall.ts +45 -0
  11. package/components/voiceCall.css +225 -0
  12. package/dist/MalformedVoiceResponseError.d.ts +6 -0
  13. package/dist/MalformedVoiceResponseError.js +9 -0
  14. package/dist/NumberToCallQrCode.d.ts +12 -0
  15. package/dist/NumberToCallQrCode.js +29 -0
  16. package/dist/PhoneNumberDialog.d.ts +25 -0
  17. package/dist/PhoneNumberDialog.js +333 -0
  18. package/dist/PhoneNumbersAdminPanel.d.ts +11 -0
  19. package/dist/PhoneNumbersAdminPanel.js +85 -0
  20. package/dist/VoiceApiError.d.ts +18 -0
  21. package/dist/VoiceApiError.js +19 -0
  22. package/dist/VoiceRequestTimedOutError.d.ts +6 -0
  23. package/dist/VoiceRequestTimedOutError.js +9 -0
  24. package/dist/averageSpeechBinsIntoBands.d.ts +6 -0
  25. package/dist/averageSpeechBinsIntoBands.js +20 -0
  26. package/dist/browserApisForBrowserTalk.d.ts +17 -0
  27. package/dist/browserApisForBrowserTalk.js +42 -0
  28. package/dist/browserTalkError.d.ts +36 -0
  29. package/dist/browserTalkError.js +1 -0
  30. package/dist/chooseCallToShowCaptionsOf.d.ts +22 -0
  31. package/dist/chooseCallToShowCaptionsOf.js +26 -0
  32. package/dist/createBrowserTalk.d.ts +56 -0
  33. package/dist/createBrowserTalk.js +414 -0
  34. package/dist/createBrowserTalkErrorFollower.d.ts +17 -0
  35. package/dist/createBrowserTalkErrorFollower.js +76 -0
  36. package/dist/createCallPresenceWatcher.d.ts +25 -0
  37. package/dist/createCallPresenceWatcher.js +66 -0
  38. package/dist/createLiveCallCaptionsPoller.d.ts +24 -0
  39. package/dist/createLiveCallCaptionsPoller.js +58 -0
  40. package/dist/createVisibleTabPoller.d.ts +13 -0
  41. package/dist/createVisibleTabPoller.js +56 -0
  42. package/dist/deriveCallPresence.d.ts +23 -0
  43. package/dist/deriveCallPresence.js +58 -0
  44. package/dist/describePhoneNumberError.d.ts +7 -0
  45. package/dist/describePhoneNumberError.js +29 -0
  46. package/dist/entries/index.d.ts +26 -0
  47. package/dist/entries/index.js +22 -0
  48. package/dist/followBrowserTalkErrorAgainstPresence.d.ts +23 -0
  49. package/dist/followBrowserTalkErrorAgainstPresence.js +52 -0
  50. package/dist/formatPhoneNumberAsTyped.d.ts +31 -0
  51. package/dist/formatPhoneNumberAsTyped.js +85 -0
  52. package/dist/generated/index.d.ts +1 -0
  53. package/dist/generated/index.js +2 -0
  54. package/dist/generated/types.gen.d.ts +795 -0
  55. package/dist/generated/types.gen.js +2 -0
  56. package/dist/getBrowserTalkForThisTab.d.ts +3 -0
  57. package/dist/getBrowserTalkForThisTab.js +13 -0
  58. package/dist/getCallPresenceWatcherForThisTab.d.ts +3 -0
  59. package/dist/getCallPresenceWatcherForThisTab.js +9 -0
  60. package/dist/mapStartBrowserTalkFailureToBrowserTalkError.d.ts +7 -0
  61. package/dist/mapStartBrowserTalkFailureToBrowserTalkError.js +60 -0
  62. package/dist/parseVoiceApiResponses.d.ts +11 -0
  63. package/dist/parseVoiceApiResponses.js +344 -0
  64. package/dist/readCallSummaryUntilItHasDuration.d.ts +12 -0
  65. package/dist/readCallSummaryUntilItHasDuration.js +45 -0
  66. package/dist/readTheBrowsersTimeZone.d.ts +8 -0
  67. package/dist/readTheBrowsersTimeZone.js +17 -0
  68. package/dist/readTimestampMilliseconds.d.ts +8 -0
  69. package/dist/readTimestampMilliseconds.js +10 -0
  70. package/dist/requestEndOfCall.d.ts +7 -0
  71. package/dist/requestEndOfCall.js +11 -0
  72. package/dist/startBrowserTalkErrorFollowerForThisTab.d.ts +6 -0
  73. package/dist/startBrowserTalkErrorFollowerForThisTab.js +12 -0
  74. package/dist/useAdminPhoneNumbers.d.ts +47 -0
  75. package/dist/useAdminPhoneNumbers.js +76 -0
  76. package/dist/useBrowserTalk.d.ts +10 -0
  77. package/dist/useBrowserTalk.js +23 -0
  78. package/dist/useBrowserTalkErrorWhileItApplies.d.ts +10 -0
  79. package/dist/useBrowserTalkErrorWhileItApplies.js +13 -0
  80. package/dist/useCallPresence.d.ts +5 -0
  81. package/dist/useCallPresence.js +34 -0
  82. package/dist/useCallSummaries.d.ts +9 -0
  83. package/dist/useCallSummaries.js +22 -0
  84. package/dist/useCallSummary.d.ts +15 -0
  85. package/dist/useCallSummary.js +21 -0
  86. package/dist/useFinePointerWithHover.d.ts +10 -0
  87. package/dist/useFinePointerWithHover.js +19 -0
  88. package/dist/useLiveCallCaptions.d.ts +8 -0
  89. package/dist/useLiveCallCaptions.js +27 -0
  90. package/dist/useLiveCallCaptionsOfLatestCall.d.ts +13 -0
  91. package/dist/useLiveCallCaptionsOfLatestCall.js +23 -0
  92. package/dist/usePhoneNumber.d.ts +45 -0
  93. package/dist/usePhoneNumber.js +125 -0
  94. package/dist/voiceApiModels.d.ts +85 -0
  95. package/dist/voiceApiModels.js +1 -0
  96. package/dist/voiceConversationsApi.d.ts +44 -0
  97. package/dist/voiceConversationsApi.js +227 -0
  98. package/dist/voiceConversationsSettings.d.ts +20 -0
  99. package/dist/voiceConversationsSettings.js +26 -0
  100. package/package.json +41 -4
package/README.md CHANGED
@@ -1,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @ciridae/voice-conversations-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React hooks for Ciridae voice conversations: browser talks, call presence, live call captions, and a drop-in phone number dialog.
4
+
5
+ Install from npm:
6
+
7
+ ```bash
8
+ npm install @ciridae/voice-conversations-react
9
+ ```
10
+
11
+ Use the published package for new and updated consumers.
12
+
13
+ Until 0.1.0 is released, only nightly builds exist. Pin the one whose UTC timestamp matches the
14
+ app's `ciridae-voice-conversations` build (`0.1.0.dev<timestamp>` pairs with
15
+ `0.1.0-nightly.<timestamp>.g<commit>`):
16
+
17
+ ```bash
18
+ pnpm add --save-exact @ciridae/voice-conversations-react@nightly
19
+ ```
20
+
21
+ Configure the hooks once, then use them anywhere:
22
+
23
+ ```ts
24
+ import { configureVoiceConversations, useBrowserTalk } from "@ciridae/voice-conversations-react";
25
+
26
+ configureVoiceConversations({ routePrefix: "/api/voice-conversations" });
27
+ ```
28
+
29
+ The call bar and transcript examples in `components/` are source files to copy into your app
30
+ and restyle; they are not exported. The full guide is `packages/voice-conversations-react/README.md`
31
+ in the Ciridae monorepo.
@@ -0,0 +1,96 @@
1
+ import {
2
+ type BrowserTalkControls,
3
+ type BrowserTalkState,
4
+ useBrowserTalk,
5
+ } from "@ciridae/voice-conversations-react"
6
+
7
+ /**
8
+ * Talk to the agent from the browser, in the composer beside Send: one round button that starts
9
+ * a browser talk, calls off one still connecting, and ends one that is live. It turns solid (the kit's
10
+ * primary colour) with the hang-up icon the moment Talk is pressed and stays that way through
11
+ * connecting, talking and ending, so the member never sees an in-between look. The tab has one
12
+ * browser talk (`useBrowserTalk`), so it keeps going when the chat or the route changes.
13
+ */
14
+ export function BrowserTalkButton({
15
+ agentName,
16
+ className,
17
+ }: {
18
+ agentName: string
19
+ className?: string
20
+ }) {
21
+ const browserTalk = useBrowserTalk()
22
+ if (browserTalk.state.status === "idle")
23
+ return (
24
+ <button
25
+ type="button"
26
+ className={`voice-call voice-call-browser-talk-button ${className ?? ""}`}
27
+ aria-label={`Talk to ${agentName}`}
28
+ onClick={() => void browserTalk.start()}
29
+ >
30
+ <PhoneIcon handset="call" />
31
+ </button>
32
+ )
33
+ const press = describeActiveBrowserTalkPress(browserTalk.state.status, browserTalk, agentName)
34
+ return (
35
+ <button
36
+ type="button"
37
+ className={`voice-call voice-call-browser-talk-button ${className ?? ""}`}
38
+ data-variant="primary"
39
+ aria-label={press.label}
40
+ // aria-disabled, not disabled: the button keeps focus while the browser talk winds down.
41
+ aria-disabled={press.onPress === null ? "true" : undefined}
42
+ onClick={press.onPress ?? undefined}
43
+ >
44
+ <PhoneIcon handset="hang_up" />
45
+ </button>
46
+ )
47
+ }
48
+
49
+ interface ActiveBrowserTalkPress {
50
+ label: string
51
+ /** What pressing does; null while the browser talk is already ending. */
52
+ onPress: (() => void) | null
53
+ }
54
+
55
+ function describeActiveBrowserTalkPress(
56
+ status: Exclude<BrowserTalkState["status"], "idle">,
57
+ browserTalk: BrowserTalkControls,
58
+ agentName: string
59
+ ): ActiveBrowserTalkPress {
60
+ switch (status) {
61
+ case "requesting_microphone":
62
+ case "connecting":
63
+ return {
64
+ label: `Cancel the Talk to ${agentName}, still connecting`,
65
+ onPress: browserTalk.cancel,
66
+ }
67
+ case "live":
68
+ return { label: `End the Talk to ${agentName}`, onPress: () => void browserTalk.end() }
69
+ case "ending":
70
+ return { label: `Ending the Talk to ${agentName}`, onPress: null }
71
+ default:
72
+ return status satisfies never
73
+ }
74
+ }
75
+
76
+ /** A handset (Feather Icons' `phone`, MIT); turned on its side when it hangs up. */
77
+ function PhoneIcon({ handset }: { handset: "call" | "hang_up" }) {
78
+ return (
79
+ <svg
80
+ viewBox="0 0 24 24"
81
+ width="16"
82
+ height="16"
83
+ fill="none"
84
+ stroke="currentColor"
85
+ strokeWidth="2"
86
+ strokeLinecap="round"
87
+ strokeLinejoin="round"
88
+ aria-hidden="true"
89
+ >
90
+ <path
91
+ transform={handset === "hang_up" ? "rotate(135 12 12)" : undefined}
92
+ d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"
93
+ />
94
+ </svg>
95
+ )
96
+ }
@@ -0,0 +1,43 @@
1
+ import { useCallPresence } from "@ciridae/voice-conversations-react"
2
+ import { formatCallClock } from "./formatCallClock"
3
+ import { useEndPresentCall } from "./useEndPresentCall"
4
+
5
+ /**
6
+ * The strip just above the composer while the member is on a call: "● On a call · 2:41" (or
7
+ * "● Connecting…", then "● Talking · 0:42") and End call. End works from the first moment, so a
8
+ * browser talk still connecting can be called off. Nothing when no call is present. Draw it between the
9
+ * messages and the composer, never across the top of the chat.
10
+ */
11
+ export function CallBanner({ className }: { className?: string }) {
12
+ const presence = useCallPresence()
13
+ const { ending, endCall } = useEndPresentCall(presence)
14
+ if (presence.presence === "none") return null
15
+ const label =
16
+ presence.presence === "on_phone_call"
17
+ ? "On a call"
18
+ : presence.call?.status === "connecting"
19
+ ? "Connecting…"
20
+ : "Talking"
21
+ const clock =
22
+ presence.elapsedSeconds === null ? "" : ` · ${formatCallClock(presence.elapsedSeconds)}`
23
+ return (
24
+ <div className={`voice-call voice-call-banner ${className ?? ""}`}>
25
+ <span className="voice-call-status">
26
+ <span className="voice-call-dot" aria-hidden="true" />
27
+ {/* Only the state is a live region: the clock ticks every second, so it is read by navigation, not announced. */}
28
+ <span role="status">{ending ? "Ending…" : label}</span>
29
+ {!ending && <span>{clock}</span>}
30
+ </span>
31
+ <button
32
+ type="button"
33
+ className="voice-call-button"
34
+ data-variant="end"
35
+ data-size="small"
36
+ onClick={endCall}
37
+ disabled={ending}
38
+ >
39
+ {presence.presence === "browser_talk_in_this_tab" ? "End" : "End call"}
40
+ </button>
41
+ </div>
42
+ )
43
+ }
@@ -0,0 +1,38 @@
1
+ import { type CallId, useLiveCallCaptions } from "@ciridae/voice-conversations-react"
2
+
3
+ /**
4
+ * What the member ("You") and the voice said on `callId`, as captions: one speaker's words until
5
+ * the other speaks, the last one growing while the call lasts. Captions are the backend's; this
6
+ * renders them as they come and groups nothing itself. Never the agent's chat replies. Reads the
7
+ * captions while mounted, so mount it only when the transcript is shown. Shared by the inline call
8
+ * entry and the transcript page.
9
+ */
10
+ export function CallCaptions({ callId }: { callId: CallId }) {
11
+ const liveCaptions = useLiveCallCaptions(callId)
12
+ return (
13
+ <>
14
+ <div className="voice-call-turns">
15
+ {liveCaptions.captions.map((caption) => (
16
+ <div
17
+ key={caption.first_fragment_id}
18
+ className="voice-call-turn"
19
+ data-speaker={caption.speaker}
20
+ >
21
+ <span className="voice-call-turn-speaker">
22
+ {caption.speaker === "caller" ? "You" : "Voice"}
23
+ </span>
24
+ <p className="voice-call-turn-text">{caption.text}</p>
25
+ </div>
26
+ ))}
27
+ </div>
28
+ {liveCaptions.readError !== null ? (
29
+ <p className="voice-call-error">The transcript could not be loaded.</p>
30
+ ) : (
31
+ liveCaptions.callStatus === "ended" &&
32
+ liveCaptions.captions.length === 0 && (
33
+ <p className="voice-call-hint">No transcript for this call.</p>
34
+ )
35
+ )}
36
+ </>
37
+ )
38
+ }
@@ -0,0 +1,89 @@
1
+ import { Fragment, useId, useState } from "react"
2
+ import {
3
+ type CallId,
4
+ type CallSummaryState,
5
+ useCallSummaries,
6
+ } from "@ciridae/voice-conversations-react"
7
+ import { CallCaptions } from "./CallCaptions"
8
+ import { formatCallClock } from "./formatCallClock"
9
+
10
+ /**
11
+ * One call session in the chat: a compact "Call · 3:12" that opens in place to show what was said,
12
+ * and closes again. A session is one call, or calls that handed straight over to each other, such
13
+ * as a browser talk a phone call took over: pass their ids in order. The clock is their total, and the
14
+ * transcript shows each call's captions in order with a line where the next one took over. The
15
+ * transcript is read when first opened, never by navigating away. Draw it wherever the chat shows
16
+ * a call: beside the messages through `RecentCallEntries` today, or inside the call's own chat
17
+ * message once the chat carries one. Pass the same `callIds` array while the calls are the same.
18
+ */
19
+ export function CallEntry({
20
+ callIds,
21
+ className,
22
+ }: {
23
+ callIds: readonly CallId[]
24
+ className?: string
25
+ }) {
26
+ const summaries = useCallSummaries(callIds)
27
+ const [open, setOpen] = useState(false)
28
+ const transcriptId = useId()
29
+ const totalSeconds = sumDurations(summaries)
30
+ const duration = totalSeconds === null ? "" : ` · ${formatCallClock(totalSeconds)}`
31
+ return (
32
+ <div className={`voice-call voice-call-entry ${className ?? ""}`}>
33
+ <button
34
+ type="button"
35
+ className="voice-call-entry-toggle"
36
+ aria-expanded={open}
37
+ aria-controls={transcriptId}
38
+ onClick={() => {
39
+ setOpen((wasOpen) => !wasOpen)
40
+ }}
41
+ >
42
+ <span className="voice-call-entry-chevron" aria-hidden="true" />
43
+ {`Call${duration}`}
44
+ </button>
45
+ {/* Present while closed too, so `aria-controls` always names an element on the page. */}
46
+ <div
47
+ id={transcriptId}
48
+ className="voice-call-entry-transcript"
49
+ role="region"
50
+ aria-label={`Transcript of the call${duration}`}
51
+ hidden={!open}
52
+ >
53
+ {open &&
54
+ callIds.map((callId, index) => (
55
+ <Fragment key={callId}>
56
+ {index > 0 && (
57
+ <p className="voice-call-entry-handover">
58
+ {describeHandover(summaries[index] ?? null)}
59
+ </p>
60
+ )}
61
+ <CallCaptions callId={callId} />
62
+ </Fragment>
63
+ ))}
64
+ </div>
65
+ </div>
66
+ )
67
+ }
68
+
69
+ /** The session's total once every call's duration is known; null before then. */
70
+ function sumDurations(summaries: readonly CallSummaryState[]): number | null {
71
+ let total = 0
72
+ for (const { summary } of summaries) {
73
+ if (summary === null || summary.duration_seconds === null) return null
74
+ total += summary.duration_seconds
75
+ }
76
+ return summaries.length === 0 ? null : total
77
+ }
78
+
79
+ /** The line between two calls of one session, named for the call that took over. */
80
+ function describeHandover(nextCall: CallSummaryState | null): string {
81
+ switch (nextCall?.summary?.started_through) {
82
+ case "phone_call":
83
+ return "Phone call took over"
84
+ case "browser_talk":
85
+ return "Talk took over"
86
+ case undefined:
87
+ return "The call continued"
88
+ }
89
+ }
@@ -0,0 +1,58 @@
1
+ import {
2
+ type CallId,
3
+ type CallSummary,
4
+ readTimestampMilliseconds,
5
+ useCallSummary,
6
+ } from "@ciridae/voice-conversations-react"
7
+ import { CallCaptions } from "./CallCaptions"
8
+ import { formatCallClock } from "./formatCallClock"
9
+
10
+ /**
11
+ * One call's transcript as a page of its own: the call's summary, then what the member ("You") and
12
+ * the voice said. The chat shows a call inline with `CallEntry` instead; mount this only if the
13
+ * app also wants a page per call, for example `/calls/:callId`. Another member's call reads as not
14
+ * found.
15
+ */
16
+ export function CallTranscript({ callId, className }: { callId: CallId; className?: string }) {
17
+ const { summary, readError } = useCallSummary(callId)
18
+ if (readError !== null)
19
+ return <p className="voice-call voice-call-error">This call could not be loaded.</p>
20
+ return (
21
+ <section
22
+ className={`voice-call voice-call-transcript ${className ?? ""}`}
23
+ aria-label="Call transcript"
24
+ >
25
+ {summary !== null && (
26
+ <header className="voice-call-transcript-header">
27
+ <h2>{summary.started_through === "phone_call" ? "Phone call" : "Talk"}</h2>
28
+ <p className="voice-call-hint">{describeCallSummary(summary)}</p>
29
+ </header>
30
+ )}
31
+ <CallCaptions callId={callId} />
32
+ </section>
33
+ )
34
+ }
35
+
36
+ /** "Ada · …0100 · Nov 11, 2026, 3:02 PM · 3:12 · 3 questions, 2 unanswered". */
37
+ function describeCallSummary(summary: CallSummary): string {
38
+ const parts: string[] = []
39
+ if (summary.member_display_name !== null) parts.push(summary.member_display_name)
40
+ if (summary.caller_last_four_digits !== null) parts.push(`…${summary.caller_last_four_digits}`)
41
+ if (summary.started_at !== null)
42
+ parts.push(
43
+ new Date(readTimestampMilliseconds(summary.started_at)).toLocaleString(undefined, {
44
+ dateStyle: "medium",
45
+ timeStyle: "short",
46
+ })
47
+ )
48
+ if (summary.duration_seconds !== null) parts.push(formatCallClock(summary.duration_seconds))
49
+ if (summary.delegation_count > 0) {
50
+ const asked = `${summary.delegation_count} ${summary.delegation_count === 1 ? "question" : "questions"}`
51
+ parts.push(
52
+ summary.unanswered_delegation_count > 0
53
+ ? `${asked}, ${summary.unanswered_delegation_count} unanswered`
54
+ : asked
55
+ )
56
+ }
57
+ return parts.join(" · ")
58
+ }
@@ -0,0 +1,211 @@
1
+ import { useEffect, useRef, useSyncExternalStore } from "react"
2
+ import { type CallId, useCallPresence, useBrowserTalk } from "@ciridae/voice-conversations-react"
3
+ import { CallEntry } from "./CallEntry"
4
+
5
+ /** Older sessions drop off the tab's record once this many have ended in it. */
6
+ const MAXIMUM_ENDED_SESSIONS_KEPT = 10
7
+ /**
8
+ * How long a browser talk the server closed waits for the reason it closed before its session ends. The
9
+ * reason ("Your phone call took over") arrives a read after the close; until then the browser talk may be
10
+ * handing over to a phone call.
11
+ */
12
+ const WAIT_FOR_WHY_THE_SERVER_CLOSED_THE_BROWSER_TALK_MS = 3_000
13
+ /**
14
+ * How long a browser talk a phone call took over waits for presence to show that phone call. Presence reads
15
+ * at once after the takeover and every few seconds after, so a phone call that never shows in this
16
+ * long never will, and the browser talk's session ends on its own.
17
+ */
18
+ const WAIT_FOR_THE_PHONE_CALL_THAT_TOOK_OVER_MS = 15_000
19
+
20
+ /** One call, or calls the tab saw hand straight over to each other, oldest first. */
21
+ interface CallSession {
22
+ callIds: readonly CallId[]
23
+ /** The member signed in when the tab first saw the session. */
24
+ signedInUserId: string
25
+ }
26
+
27
+ interface CallSessionsSeenInThisTab {
28
+ /** The session going on now; its last call is present or handing over. */
29
+ openSession: CallSession | null
30
+ /** Sessions the tab saw end, oldest first. */
31
+ endedSessions: readonly CallSession[]
32
+ }
33
+
34
+ /** Kept for the tab, so leaving the chat and coming back keeps the entry. */
35
+ let callSessionsSeenInThisTab: CallSessionsSeenInThisTab = {
36
+ openSession: null,
37
+ endedSessions: [],
38
+ }
39
+ const listenersToCallSessions = new Set<() => void>()
40
+
41
+ /**
42
+ * A "Call · 3:12" entry (`CallEntry`) for the member's most recent call session that ended while
43
+ * it was shown in this tab, opening in place to its transcript. A session is a browser talk, a phone call,
44
+ * or a browser talk a phone call took over: calls the tab saw hand straight over to each other make one
45
+ * entry, with their total time, once the last of them ends. Only the newest session shows, so
46
+ * entries never pile up where space is short (above a composer); the tab still remembers its last
47
+ * few. Draw it at the end of the chat's messages, so a call reads as the latest thing in the chat
48
+ * and scrolls away with it, never pinned above. Nothing for a session before it ends.
49
+ * `signedInUserId` is the signed-in member's user id: a session stays with the member who was
50
+ * signed in when it started, so another member who signs in never sees it.
51
+ */
52
+ export function RecentCallEntries({
53
+ signedInUserId,
54
+ className,
55
+ }: {
56
+ signedInUserId: string
57
+ className?: string
58
+ }) {
59
+ const { call } = useCallPresence()
60
+ const { state: browserTalkState } = useBrowserTalk()
61
+ const { openSession, endedSessions } = useSyncExternalStore(
62
+ subscribeToCallSessions,
63
+ readCallSessions,
64
+ readCallSessions
65
+ )
66
+ const browserTalkStatusAtLastReading = useRef(browserTalkState.status)
67
+ const presentCallAtLastReading = useRef<CallId | "no_call" | "not_seen_live">("no_call")
68
+ // A call counts once the tab has seen it live. One not yet seen live (a browser talk this tab is starting,
69
+ // which overlays whatever call is present, a phone call still ringing, or a ringing call ended
70
+ // from the app, which the server reads as "ending" before it ever connected) changes nothing:
71
+ // called off, it leaves no entry, and pressing Talk during a phone call never ends the phone
72
+ // call's session. A live call joins the open session; the session ends when presence turns none
73
+ // and no handover is under way.
74
+ const lastCallOfOpenSession = openSession?.callIds[openSession.callIds.length - 1] ?? null
75
+ const presentCallReading =
76
+ call === null
77
+ ? "no_call"
78
+ : call.callId !== null &&
79
+ (call.status === "live" ||
80
+ (call.status === "ending" && lastCallOfOpenSession === call.callId))
81
+ ? call.callId
82
+ : "not_seen_live"
83
+ useEffect(() => {
84
+ const browserTalkStatusBefore = browserTalkStatusAtLastReading.current
85
+ browserTalkStatusAtLastReading.current = browserTalkState.status
86
+ const presentCallBefore = presentCallAtLastReading.current
87
+ presentCallAtLastReading.current = presentCallReading
88
+ let stopWaiting: () => void = () => undefined
89
+ // The member's phone call took the browser talk over: the session goes on with that call.
90
+ const phoneTookOver =
91
+ browserTalkState.status === "idle" && browserTalkState.error?.kind === "phone_took_over"
92
+ // The server closed a live browser talk the member did not end; why arrives a read later.
93
+ const serverClosedTheBrowserTalk =
94
+ browserTalkStatusBefore === "live" &&
95
+ browserTalkState.status === "idle" &&
96
+ browserTalkState.error === null
97
+ // Talk pressed with no call present starts a session of its own, never joins a waiting one.
98
+ const browserTalkStartedWithNoCall =
99
+ browserTalkStatusBefore === "idle" &&
100
+ browserTalkState.status !== "idle" &&
101
+ presentCallBefore === "no_call"
102
+ if (browserTalkStartedWithNoCall) endOpenSession()
103
+ else if (presentCallReading === "not_seen_live") {
104
+ // Nothing changes: the call is not live yet.
105
+ } else if (presentCallReading !== "no_call") recordLiveCall(presentCallReading, signedInUserId)
106
+ else if (phoneTookOver)
107
+ stopWaiting = endOpenSessionAfterVisibleWait(
108
+ WAIT_FOR_THE_PHONE_CALL_THAT_TOOK_OVER_MS,
109
+ "presence never showed the phone call that took the browser talk over"
110
+ )
111
+ else if (serverClosedTheBrowserTalk)
112
+ stopWaiting = endOpenSessionAfterVisibleWait(
113
+ WAIT_FOR_WHY_THE_SERVER_CLOSED_THE_BROWSER_TALK_MS,
114
+ "the server closed the browser talk and no phone call took it over"
115
+ )
116
+ else endOpenSession()
117
+ return stopWaiting
118
+ }, [presentCallReading, signedInUserId, browserTalkState])
119
+ const endedSessionsOfMember = endedSessions.filter(
120
+ (endedSession) => endedSession.signedInUserId === signedInUserId
121
+ )
122
+ const latestEndedSessionOfMember = endedSessionsOfMember[endedSessionsOfMember.length - 1]
123
+ if (latestEndedSessionOfMember === undefined) return null
124
+ return (
125
+ <div className={`voice-call voice-call-entries ${className ?? ""}`}>
126
+ {/* Keyed by the session's first call, so the next session's entry starts closed. */}
127
+ <CallEntry
128
+ key={latestEndedSessionOfMember.callIds[0]}
129
+ callIds={latestEndedSessionOfMember.callIds}
130
+ />
131
+ </div>
132
+ )
133
+ }
134
+
135
+ /**
136
+ * A live call: the open session's call, the next call of it, or the first of a new session. A call
137
+ * seen while another member is signed in never joins the previous member's session: that session
138
+ * ends and the call starts the new member's.
139
+ */
140
+ function recordLiveCall(liveCallId: CallId, signedInUserId: string): void {
141
+ const { openSession } = callSessionsSeenInThisTab
142
+ if (openSession?.callIds.includes(liveCallId) === true) return
143
+ if (openSession !== null && openSession.signedInUserId !== signedInUserId) endOpenSession()
144
+ const { openSession: sessionToJoin, endedSessions } = callSessionsSeenInThisTab
145
+ setCallSessions({
146
+ openSession:
147
+ sessionToJoin === null
148
+ ? { callIds: [liveCallId], signedInUserId }
149
+ : { ...sessionToJoin, callIds: [...sessionToJoin.callIds, liveCallId] },
150
+ endedSessions,
151
+ })
152
+ }
153
+
154
+ /**
155
+ * Ends the open session once `waitMs` has passed with the tab visible: presence does not poll while
156
+ * the tab is hidden (picking up a phone often hides it), so a wait that runs out then restarts once
157
+ * the tab shows again and presence reads at once. Logs a warning naming `why` when it ends a
158
+ * session. Returns a function that calls the wait off.
159
+ */
160
+ function endOpenSessionAfterVisibleWait(waitMs: number, why: string): () => void {
161
+ let waitTimer: ReturnType<typeof setTimeout> | undefined
162
+ function startWaiting(): void {
163
+ waitTimer = setTimeout(() => {
164
+ if (document.visibilityState === "hidden") {
165
+ document.addEventListener("visibilitychange", restartWhenVisible)
166
+ return
167
+ }
168
+ const { openSession } = callSessionsSeenInThisTab
169
+ if (openSession === null) return
170
+ console.warn(
171
+ `Ending call session ${openSession.callIds.join(", ")} after ${waitMs} ms: ${why}`
172
+ )
173
+ endOpenSession()
174
+ }, waitMs)
175
+ }
176
+ function restartWhenVisible(): void {
177
+ if (document.visibilityState === "hidden") return
178
+ document.removeEventListener("visibilitychange", restartWhenVisible)
179
+ startWaiting()
180
+ }
181
+ startWaiting()
182
+ return () => {
183
+ clearTimeout(waitTimer)
184
+ document.removeEventListener("visibilitychange", restartWhenVisible)
185
+ }
186
+ }
187
+
188
+ function endOpenSession(): void {
189
+ const { openSession, endedSessions } = callSessionsSeenInThisTab
190
+ if (openSession === null) return
191
+ setCallSessions({
192
+ openSession: null,
193
+ endedSessions: [...endedSessions, openSession].slice(-MAXIMUM_ENDED_SESSIONS_KEPT),
194
+ })
195
+ }
196
+
197
+ function setCallSessions(next: CallSessionsSeenInThisTab): void {
198
+ callSessionsSeenInThisTab = next
199
+ for (const listener of listenersToCallSessions) listener()
200
+ }
201
+
202
+ function subscribeToCallSessions(listener: () => void): () => void {
203
+ listenersToCallSessions.add(listener)
204
+ return () => {
205
+ listenersToCallSessions.delete(listener)
206
+ }
207
+ }
208
+
209
+ function readCallSessions(): CallSessionsSeenInThisTab {
210
+ return callSessionsSeenInThisTab
211
+ }
@@ -0,0 +1,39 @@
1
+ import type { BrowserTalkError } from "@ciridae/voice-conversations-react"
2
+
3
+ /** One sentence per cause, in the member's words. Says "chat", never "thread". */
4
+ export function describeBrowserTalkError(error: BrowserTalkError, agentName: string): string {
5
+ switch (error.kind) {
6
+ case "microphone_blocked":
7
+ return "Microphone blocked. Allow it in the browser's site settings."
8
+ case "no_microphone":
9
+ return "No microphone found."
10
+ case "microphone_unavailable":
11
+ return "Your microphone couldn't start. Close other apps using it and try again."
12
+ case "did_not_connect":
13
+ return "Couldn't connect. Check your network and try again."
14
+ case "connection_dropped":
15
+ return "Connection dropped."
16
+ case "on_a_phone_call":
17
+ return `You're on a phone call with ${agentName}. End it to talk here.`
18
+ case "already_on_a_browser_talk":
19
+ return `You're already talking with ${agentName} in another tab.`
20
+ case "not_a_current_member":
21
+ return `Only members of this project can talk to ${agentName}.`
22
+ case "voice_not_ready":
23
+ return "Voice is restarting. Try again in a moment."
24
+ case "voice_unavailable":
25
+ return "Voice isn't available right now. Try again in a moment."
26
+ case "phone_took_over":
27
+ return "Your phone call took over."
28
+ case "time_limit_reached":
29
+ return "Talks end after one hour. Start a new one to keep going."
30
+ case "stopped_by_content_filter":
31
+ return "The voice service stopped this Talk."
32
+ case "host_refused":
33
+ return error.status === 401
34
+ ? "You're signed out. Sign in again to talk."
35
+ : "You can't talk here with your current access."
36
+ case "provider_rejected":
37
+ return `The voice service refused to start the Talk (${error.status}).`
38
+ }
39
+ }
@@ -0,0 +1,9 @@
1
+ /** "0:42", "2:41", "1:02:05": the call clock the banners and transcript show. */
2
+ export function formatCallClock(totalSeconds: number): string {
3
+ const hours = Math.floor(totalSeconds / 3600)
4
+ const minutes = Math.floor((totalSeconds % 3600) / 60)
5
+ const seconds = String(totalSeconds % 60).padStart(2, "0")
6
+ return hours > 0
7
+ ? `${hours}:${String(minutes).padStart(2, "0")}:${seconds}`
8
+ : `${minutes}:${seconds}`
9
+ }
@@ -0,0 +1,45 @@
1
+ import { useState } from "react"
2
+ import {
3
+ type CallId,
4
+ type CallPresence,
5
+ requestEndOfCall,
6
+ useBrowserTalk,
7
+ } from "@ciridae/voice-conversations-react"
8
+
9
+ export interface EndPresentCall {
10
+ /** Whether End was pressed (or the call is already ending), so the button disables. */
11
+ ending: boolean
12
+ endCall: () => void
13
+ }
14
+
15
+ /**
16
+ * End for whatever call is present: this tab's browser talk ends through the browser talk session (which also
17
+ * releases the microphone); a phone call or another tab's browser talk through the End route. Shared by
18
+ * `CallBanner` and any other End button an app draws.
19
+ */
20
+ export function useEndPresentCall({ presence, call }: CallPresence): EndPresentCall {
21
+ const browserTalk = useBrowserTalk()
22
+ const [endRequestedForCallId, setEndRequestedForCallId] = useState<CallId | null>(null)
23
+ const ending =
24
+ browserTalk.state.status === "ending" ||
25
+ call?.status === "ending" ||
26
+ (endRequestedForCallId !== null && call?.callId === endRequestedForCallId)
27
+
28
+ function endCall(): void {
29
+ if (presence === "browser_talk_in_this_tab") {
30
+ if (browserTalk.state.status === "live") void browserTalk.end()
31
+ else browserTalk.cancel()
32
+ return
33
+ }
34
+ const callId = call?.callId
35
+ if (!callId) return
36
+ setEndRequestedForCallId(callId)
37
+ requestEndOfCall(callId).catch((failure: unknown) => {
38
+ console.warn(`Ending call_id=${callId} from the app failed`, failure)
39
+ // Only this call's request: End pressed since for another call stays pending.
40
+ setEndRequestedForCallId((requested) => (requested === callId ? null : requested))
41
+ })
42
+ }
43
+
44
+ return { ending, endCall }
45
+ }