Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

Live call view: show each live line on its speaker's side (PR 1980)

Tim Gutberlet712e4894d31d
diff --git a/apps/web/src/call/Transcript.tsx b/apps/web/src/call/Transcript.tsx
index d5aba456..f6b7aaea 100644
--- a/apps/web/src/call/Transcript.tsx
+++ b/apps/web/src/call/Transcript.tsx
@@ -15,7 +15,7 @@ type Props = {
start: { time: string; label: string }
end: { time: string; label: string } | null
/** Lines still being spoken on a live call, after the written ones (the test call shows them). */
- pending?: readonly { id: string; speaker: 'caller' | 'agent'; text: string }[]
+ pending?: readonly { id: string; speaker: 'caller' | 'agent' | 'unknown'; text: string }[]
}
const toolIcons: Record<string, IconName> = { 'call.flagUrgent': 'spark', 'call.takeMessage': 'message' }
@@ -35,13 +35,22 @@ function CallEvent({ segment }: { segment: TranscriptSegment }) {
return <EventLine icon={icon} label={segment.tool_event?.label ?? segment.text} time={clock(segment.at_ms / 1000)} />
}
-type BubbleProps = { fromCaller: boolean; author: string | null; time: string | null; pending?: boolean; children: ReactNode }
+type BubbleProps = {
+ /** The caller's lines on the left, the assistant's on the right; a line whose speaker is not known yet in the middle. */
+ side: 'caller' | 'agent' | 'unknown'
+ author: string | null
+ time: string | null
+ pending?: boolean
+ children: ReactNode
+}
+
+const sideClass = { caller: 'k-msg-them', agent: 'k-msg-me', unknown: 'k-msg-unknown' } as const
-function Bubble({ fromCaller, author, time, pending, children }: BubbleProps) {
+function Bubble({ side, author, time, pending, children }: BubbleProps) {
const t = useT()
return (
- <div className={cx('k-msg', fromCaller ? 'k-msg-them' : 'k-msg-me', author && 'k-msg-tail', pending && 'k-msg-pending')}>
- <div className={cx('k-bubble', fromCaller ? 'k-tone-signal' : 'k-tone-neutral')}>
+ <div className={cx('k-msg', sideClass[side], author && 'k-msg-tail', pending && 'k-msg-pending')}>
+ <div className={cx('k-bubble', side === 'caller' ? 'k-tone-signal' : 'k-tone-neutral')}>
{author && <div className="k-msg-author">{author}</div>}
<span className="k-msg-text">{children}</span>
<span className="k-meta-space" aria-hidden="true" />
@@ -64,16 +73,17 @@ export function Transcript({ segments, callerName, assistantName, search, start,
const speakerChanged = previous !== s.speaker
previous = s.speaker
return (
- <Bubble key={s.id} fromCaller={s.speaker === 'caller'} author={speakerChanged ? names[s.speaker]! : null} time={clock(s.at_ms / 1000)}>
+ <Bubble key={s.id} side={s.speaker === 'caller' ? 'caller' : 'agent'} author={speakerChanged ? names[s.speaker]! : null} time={clock(s.at_ms / 1000)}>
{highlight(s.text, search)}
</Bubble>
)
})}
{pending.map(line => {
const speakerChanged = previous !== line.speaker
- previous = line.speaker
+ previous = line.speaker === 'unknown' ? null : line.speaker
+ const author = speakerChanged ? (names[line.speaker] ?? null) : null
return (
- <Bubble key={line.id} fromCaller={line.speaker === 'caller'} author={speakerChanged ? names[line.speaker]! : null} time={null} pending>
+ <Bubble key={line.id} side={line.speaker} author={author} time={null} pending>
{line.text}
</Bubble>
)
diff --git a/apps/web/src/call/liveSession.ts b/apps/web/src/call/liveSession.ts
index 809b55bd..8a3a2088 100644
--- a/apps/web/src/call/liveSession.ts
+++ b/apps/web/src/call/liveSession.ts
@@ -13,7 +13,7 @@ import { TimedOut, within } from '../settings/testCallModel.ts'
import { workspaceHeaders } from '../tabWorkspace.ts'
import { type LiveKit, loadFailed, loadLiveKit } from './livekit.ts'
import { microphoneAllowed } from './microphone.ts'
-import { transcribesOthers } from './useLiveLines.ts'
+import { streamSpeaker } from './useLiveLines.ts'
import { i18n } from '../i18n/index.tsx'
export type LivePhase = 'idle' | 'joining' | 'listening' | 'handingOff' | 'talking'
@@ -90,7 +90,7 @@ async function connect(join: LiveCallJoin, { Room, RoomEvent, Track }: LiveKit):
for (const element of track.detach()) element.remove()
})
next.registerTextStreamHandler(TRANSCRIPTION_TOPIC, (reader, from) =>
- streamSink?.(reader, transcribesOthers(reader, from, next) ? 'caller' : 'agent'),
+ streamSink?.(reader, streamSpeaker(reader, from, next)),
)
// The call ended (the room closed) or the connection is gone for good.
next.on(RoomEvent.Disconnected, () => {
diff --git a/apps/web/src/call/useLiveLines.ts b/apps/web/src/call/useLiveLines.ts
index eb3c003a..7d1e5d83 100644
--- a/apps/web/src/call/useLiveLines.ts
+++ b/apps/web/src/call/useLiveLines.ts
@@ -14,18 +14,15 @@ import {
pruneLines,
rowsOf,
SEGMENT_ATTRIBUTE,
+ speakerOf,
TRANSCRIPTION_TOPIC,
} from '../settings/liveTranscript.ts'
-/** Which of the room's transcription streams is the caller's speech (the rest is the assistant's). */
-export type CallerStream = (reader: TextStreamReader, from: { identity: string }, room: Room) => boolean
+/** Whose speech one of the room's transcription streams is. */
+export type StreamSpeaker = (reader: TextStreamReader, from: { identity: string }, room: Room) => LiveSpeaker
-/** The stream transcribes a track its sender does not publish: someone else's speech, the caller's. */
-export const transcribesOthers: CallerStream = (reader, from, room) => {
- const track = reader.info.attributes?.['lk.transcribed_track_id']
- const sender = room.remoteParticipants.get(from.identity)
- return !!track && !sender?.trackPublications.has(track)
-}
+/** Listening in to a call: see speakerOf. */
+export const streamSpeaker: StreamSpeaker = (reader, from, room) => speakerOf(reader.info.attributes, from, room)
export function useLiveLines(rows: TranscriptSegment[]) {
const [lines, setLines] = useState<LiveLines>([])
@@ -43,15 +40,22 @@ export function useLiveLines(rows: TranscriptSegment[]) {
return () => clearInterval(id)
}, [lines.length])
- /** Reads one stream into its line. The caller's line is replaced by each update, the assistant's grows. Stable across renders. */
+ /**
+ * Reads one stream into its line. The caller's line is replaced by each update, the assistant's grows; an unknown
+ * speaker's line shows what its latest stream said so far (right for both kinds). Stable across renders.
+ */
const read = useCallback(async (reader: TextStreamReader, speaker: LiveSpeaker) => {
const id = reader.info.attributes?.[SEGMENT_ATTRIBUTE] ?? reader.info.id
const final = reader.info.attributes?.[FINAL_ATTRIBUTE] === 'true'
- const mode = speaker === 'caller' ? 'replace' : 'append'
+ const mode = speaker === 'agent' ? 'append' : 'replace'
const rowsBefore = rowsOf(rowsRef.current, speaker)
+ let said = ''
try {
- for await (const text of reader)
+ for await (const chunk of reader) {
+ said += chunk
+ const text = speaker === 'unknown' ? said : chunk
setLines(current => applyChunk(current, { id, speaker, text, mode, final, now: Date.now(), rowsBefore }))
+ }
} catch {
// A stream cut off by the hang-up: what arrived stays until the row replaces it.
}
@@ -62,10 +66,10 @@ export function useLiveLines(rows: TranscriptSegment[]) {
return {
pending: useMemo(() => pendingLines(lines, rows, now), [lines, rows, now]),
read,
- /** Reads every transcription stream of the room; `isCaller` tells the caller's from the assistant's. */
- listen(room: Room, isCaller: CallerStream = transcribesOthers) {
+ /** Reads every transcription stream of the room; `speaker` tells whose speech each one is. */
+ listen(room: Room, speaker: StreamSpeaker = streamSpeaker) {
room.registerTextStreamHandler(TRANSCRIPTION_TOPIC, (reader, from) => {
- void read(reader, isCaller(reader, from, room) ? 'caller' : 'agent')
+ void read(reader, speaker(reader, from, room))
})
},
clear,
diff --git a/apps/web/src/settings/TestCall.tsx b/apps/web/src/settings/TestCall.tsx
index 8a9baa25..a8fdca2f 100644
--- a/apps/web/src/settings/TestCall.tsx
+++ b/apps/web/src/settings/TestCall.tsx
@@ -14,6 +14,7 @@ import './test-call-panel.css'
import { loadLiveKit, preloadNow } from '../call/livekit.ts'
import { microphoneAllowed } from '../call/microphone.ts'
import { useLiveLines } from '../call/useLiveLines.ts'
+import { TRACK_ATTRIBUTE } from './liveTranscript.ts'
import {
agentLeftText,
noJoinText,
@@ -179,11 +180,11 @@ export function useTestCall(canStart: boolean, assistant?: { id: string; name: s
})
// The browser is the caller here: its own speech is the stream about its own track.
live.listen(next, (reader, from, room) => {
- const track = reader.info.attributes?.['lk.transcribed_track_id']
- return (
+ const track = reader.info.attributes?.[TRACK_ATTRIBUTE]
+ const mine =
from.identity === room.localParticipant.identity ||
(!!track && room.localParticipant.trackPublications.has(track))
- )
+ return mine ? 'caller' : 'agent'
})
next.on(RoomEvent.Disconnected, () => {
watch.stop()
diff --git a/apps/web/src/settings/liveTranscript.test.ts b/apps/web/src/settings/liveTranscript.test.ts
index c38de919..bab6cee2 100644
--- a/apps/web/src/settings/liveTranscript.test.ts
+++ b/apps/web/src/settings/liveTranscript.test.ts
@@ -7,6 +7,8 @@ import {
type LiveLines,
pendingLines,
pruneLines,
+ rowsOf,
+ speakerOf,
} from './liveTranscript.ts'
const row = (speaker: TranscriptSegment['speaker'], text: string, n = 0) =>
@@ -22,7 +24,7 @@ const row = (speaker: TranscriptSegment['speaker'], text: string, n = 0) =>
const chunk = (
id: string,
- speaker: 'caller' | 'agent',
+ speaker: 'caller' | 'agent' | 'unknown',
text: string,
extra: Partial<Parameters<typeof applyChunk>[1]> = {},
) => ({
@@ -77,3 +79,47 @@ test('a finished line without a row is dropped after a while; one still spoken s
test('empty text is never shown', () => {
expect(pendingLines(applyChunk([], chunk('u1', 'caller', ' ')), [], 0)).toHaveLength(0)
})
+
+// A listened-to call: the agent (kind AGENT, its own microphone TR_agent) and the SIP caller (TR_caller).
+const room = (callerIdentity: string) => ({
+ remoteParticipants: new Map([
+ ['agent-1', { isAgent: true, trackPublications: new Map([['TR_agent', {}]]) }],
+ [callerIdentity, { isAgent: false, trackPublications: new Map([['TR_caller', {}]]) }],
+ ]),
+})
+const about = (track?: string, final = false) => ({
+ 'lk.transcription_final': String(final),
+ ...(track ? { 'lk.transcribed_track_id': track } : {}),
+})
+
+test("the caller's speech sent in the caller's name is the caller's, while it is recognised and once final", () => {
+ // Inbound (sip_+1503…) and outbound (outbound-callee) callers alike; with or without the track known yet.
+ for (const identity of ['sip_+15035550147', 'outbound-callee']) {
+ expect(speakerOf(about('TR_caller'), { identity }, room(identity))).toBe('caller')
+ expect(speakerOf(about('TR_caller', true), { identity }, room(identity))).toBe('caller')
+ expect(speakerOf(about(), { identity }, room(identity))).toBe('caller')
+ }
+})
+
+test("the assistant's own speech is the assistant's, with or without its track", () => {
+ const r = room('outbound-callee')
+ expect(speakerOf(about('TR_agent'), { identity: 'agent-1' }, r)).toBe('agent')
+ expect(speakerOf(about(), { identity: 'agent-1' }, r)).toBe('agent')
+})
+
+test("a stream the agent sends about the caller's track is the caller's", () => {
+ expect(speakerOf(about('TR_caller'), { identity: 'agent-1' }, room('outbound-callee'))).toBe('caller')
+})
+
+test('a sender not in the room is unknown, never guessed', () => {
+ expect(speakerOf(about('TR_caller'), { identity: 'someone' }, room('outbound-callee'))).toBe('unknown')
+})
+
+test("an unknown speaker's line counts and gives way to either side's row", () => {
+ const rows = [row('caller', 'Hi', 1), row('agent', 'Hello, Brightwater Plumbing', 2)]
+ expect(rowsOf(rows, 'unknown')).toBe(2)
+ const lines = applyChunk([], chunk('u', 'unknown', 'My boiler is leaking', { rowsBefore: 2 }))
+ expect(pendingLines(lines, rows, 1000).map(l => l.speaker)).toEqual(['unknown'])
+ const synced = [...rows, row('caller', 'My boiler is leaking.', 3)]
+ expect(pendingLines(lines, synced, 1000)).toEqual([])
+})
diff --git a/apps/web/src/settings/liveTranscript.ts b/apps/web/src/settings/liveTranscript.ts
index 17fd7a65..7a0050bc 100644
--- a/apps/web/src/settings/liveTranscript.ts
+++ b/apps/web/src/settings/liveTranscript.ts
@@ -8,11 +8,13 @@ import type { TranscriptSegment } from '@linedesk/db/types'
export const TRANSCRIPTION_TOPIC = 'lk.transcription'
export const FINAL_ATTRIBUTE = 'lk.transcription_final'
export const SEGMENT_ATTRIBUTE = 'lk.segment_id'
+export const TRACK_ATTRIBUTE = 'lk.transcribed_track_id'
/** How long a finished line waits for its transcript row before it is dropped anyway. */
export const FINAL_LINE_TTL_MS = 6000
-export type LiveSpeaker = 'caller' | 'agent'
+/** Who says a line; 'unknown' while a stream cannot be told apart (shown on neither side). */
+export type LiveSpeaker = 'caller' | 'agent' | 'unknown'
export type LiveLine = {
id: string
speaker: LiveSpeaker
@@ -28,7 +30,8 @@ export type Chunk = {
id: string
speaker: LiveSpeaker
text: string
- /** The caller's recognised speech replaces the line; the assistant's words add to it. */
+ /** The caller's recognised speech replaces the line; the assistant's words add to it (an unknown speaker's line
+ * is replaced by the stream's text so far). */
mode: 'replace' | 'append'
final: boolean
now: number
@@ -61,6 +64,10 @@ const words = (text: string) =>
.replace(/[^\p{L}\p{N}]+/gu, ' ')
.trim()
+/** The rows a line of this speaker can become: an unknown speaker's line may be either side's. */
+const rowsFor = (rows: readonly TranscriptSegment[], speaker: LiveSpeaker) =>
+ rows.filter(r => (speaker === 'unknown' ? r.speaker === 'caller' || r.speaker === 'agent' : r.speaker === speaker))
+
/** A row says the same as the line (an interrupted reply is spoken only in part, so either may be the start of the other). */
function sameTurn(row: TranscriptSegment, line: LiveLine): boolean {
const a = words(row.text)
@@ -75,15 +82,39 @@ function sameTurn(row: TranscriptSegment, line: LiveLine): boolean {
export function pendingLines(lines: LiveLines, rows: readonly TranscriptSegment[], now: number): LiveLines {
return lines.filter(line => {
if (!words(line.text)) return false
- const later = rows.filter(r => r.speaker === line.speaker).slice(line.rowsBefore)
+ const later = rowsFor(rows, line.speaker).slice(line.rowsBefore)
if (later.some(row => sameTurn(row, line))) return false
return line.finishedAt === null || now - line.finishedAt < FINAL_LINE_TTL_MS
})
}
/** The speaker's transcript rows so far, for a new line's rowsBefore. */
-export const rowsOf = (rows: readonly TranscriptSegment[], speaker: LiveSpeaker) =>
- rows.filter(r => r.speaker === speaker).length
+export const rowsOf = (rows: readonly TranscriptSegment[], speaker: LiveSpeaker) => rowsFor(rows, speaker).length
+
+/** The parts of a LiveKit transcription stream and room that tell whose speech a stream is. */
+export type StreamSender = { identity: string }
+type RoomParticipants = {
+ remoteParticipants: ReadonlyMap<string, { isAgent: boolean; trackPublications: ReadonlyMap<string, unknown> }>
+}
+
+/**
+ * Whose speech a transcription stream of a call is, for someone listening in. The voice agent sends the caller's
+ * speech in the caller's name (lk.transcribed_track_id: the caller's microphone) and its own in its own name; so a
+ * stream sent as anyone but the agent is the caller's (SIP callers on inbound and outbound calls alike), and one
+ * sent as the agent is the agent's, unless it is about a track the agent does not publish (older agents sent
+ * everything in their own name). A sender not (yet) in the room: unknown, never a guess.
+ */
+export function speakerOf(
+ attributes: Readonly<Record<string, string>> | undefined,
+ from: StreamSender,
+ room: RoomParticipants,
+): LiveSpeaker {
+ const sender = room.remoteParticipants.get(from.identity)
+ if (!sender) return 'unknown'
+ if (!sender.isAgent) return 'caller'
+ const track = attributes?.[TRACK_ATTRIBUTE]
+ return track && !sender.trackPublications.has(track) ? 'caller' : 'agent'
+}
/** Drops lines that will never be shown again, so the list stays short on a long call. */
export function pruneLines(lines: LiveLines, rows: readonly TranscriptSegment[], now: number): LiveLines {
diff --git a/apps/web/src/styles.css b/apps/web/src/styles.css
index c52aa760..4aa39a27 100644
--- a/apps/web/src/styles.css
+++ b/apps/web/src/styles.css
@@ -138,6 +138,9 @@ body { margin: 0; font-family: var(--font-sans); background: var(--bg); color: v
/* Message bubble */
.k-msg { display: flex; padding: 1px 0; }
.k-msg-me { justify-content: flex-end; }
+/* A live line whose speaker is not known yet: on neither side, muted. */
+.k-msg-unknown { justify-content: center; }
+.k-msg-unknown .k-bubble { color: var(--ink-muted); }
.k-msg-tail { margin-top: var(--space-2); }
.k-bubble { position: relative; box-sizing: border-box; max-width: min(72%, 520px); padding: 6px 10px 7px; border-radius: var(--radius-bubble); font-size: 14.5px; line-height: 20px; overflow-wrap: anywhere; }
.k-msg-them .k-bubble { background: var(--bubble-in); border: 1px solid var(--line); }