@memberjunction/ng-conversations 6.1.5 → 6.1.6

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 (26) hide show
  1. package/dist/lib/components/task/tasks-full-view.component.d.ts +6 -1
  2. package/dist/lib/components/task/tasks-full-view.component.d.ts.map +1 -1
  3. package/dist/lib/components/task/tasks-full-view.component.js +15 -6
  4. package/dist/lib/components/task/tasks-full-view.component.js.map +1 -1
  5. package/dist/lib/components/workspace/conversation-workspace.component.d.ts +11 -1
  6. package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
  7. package/dist/lib/components/workspace/conversation-workspace.component.js +21 -26
  8. package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
  9. package/dist/lib/services/conversation-agent.service.d.ts +14 -6
  10. package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
  11. package/dist/lib/services/conversation-agent.service.js +46 -17
  12. package/dist/lib/services/conversation-agent.service.js.map +1 -1
  13. package/dist/lib/services/conversation-tasks-filter.d.ts +15 -0
  14. package/dist/lib/services/conversation-tasks-filter.d.ts.map +1 -0
  15. package/dist/lib/services/conversation-tasks-filter.js +69 -0
  16. package/dist/lib/services/conversation-tasks-filter.js.map +1 -0
  17. package/dist/lib/services/realtime-audio-recorder.d.ts +21 -4
  18. package/dist/lib/services/realtime-audio-recorder.d.ts.map +1 -1
  19. package/dist/lib/services/realtime-audio-recorder.js +42 -8
  20. package/dist/lib/services/realtime-audio-recorder.js.map +1 -1
  21. package/dist/lib/services/realtime-session.service.js +3 -3
  22. package/dist/lib/services/realtime-session.service.js.map +1 -1
  23. package/dist/lib/services/search.service.d.ts.map +1 -1
  24. package/dist/lib/services/search.service.js +3 -16
  25. package/dist/lib/services/search.service.js.map +1 -1
  26. package/package.json +31 -31
@@ -2,9 +2,10 @@ import { encodePcm16Wav, PeakAccumulator } from './realtime-pcm-wav';
2
2
  /**
3
3
  * Browser-side audio recorder for a CLIENT-DIRECT realtime voice session.
4
4
  *
5
- * Mixes the user's microphone stream with the agent's remote-audio stream (when the driver
6
- * exposes one — `OpenAIRealtimeClient.GetRemoteMediaStream()`) into a single mono **WAV** (16-bit
7
- * PCM) blob via the Web Audio API. Rather than a `MediaRecorder` (which only emits webm/opus —
5
+ * Mixes the user's microphone stream with the agent's remote-audio stream (every driver exposes
6
+ * one via `GetRemoteMediaStream()`: WebRTC drivers publish their remote track, PCM drivers —
7
+ * Gemini, ElevenLabs, AssemblyAI, xAI, HuggingFace — publish their playout engine's output) into a
8
+ * single mono **WAV** (16-bit PCM) blob via the Web Audio API. Rather than a `MediaRecorder` (which only emits webm/opus —
8
9
  * header-less, no duration/cues, so HTTP-range seeking is unreliable), the mix is routed into an
9
10
  * {@link AudioWorkletNode} (preferred) or a {@link ScriptProcessorNode} (fallback) that captures
10
11
  * Float32 PCM frames. PCM is accumulated in memory and encoded as a seekable RIFF/WAVE file at
@@ -16,7 +17,10 @@ import { encodePcm16Wav, PeakAccumulator } from './realtime-pcm-wav';
16
17
  * - No `AudioContext` (server-side render / unsupported env) → the recorder disables itself
17
18
  * ({@link IsRecording} stays `false`, {@link Stop} resolves `null`); the voice call proceeds.
18
19
  * - No `AudioWorkletNode` AND no `ScriptProcessorNode` → disables itself rather than throwing.
19
- * - No remote stream (non-WebRTC drivers, or the track hasn't landed yet) → records mic only.
20
+ * - No remote stream yet (e.g. the WebRTC track hasn't landed) → records mic only until it does.
21
+ * - A remote stream that can't be connected (e.g. a browser that rejects cross-sample-rate
22
+ * `createMediaStreamSource` — the PCM playout context runs at 24 kHz, this one at the device
23
+ * rate) → warns and records mic only; the mic recording is never lost to the agent stream.
20
24
  * - Any construction/start error is logged and disables the recorder rather than throwing into
21
25
  * the session-start path.
22
26
  *
@@ -68,6 +72,12 @@ export class RealtimeAudioRecorder {
68
72
  startedAtMs = 0;
69
73
  /** Sample rate of the capturing {@link AudioContext}; 0 before {@link Start}. Needed to wrap shards. */
70
74
  sampleRate = 0;
75
+ /**
76
+ * Bumped by {@link cleanup}. The async setup snapshots it and, after each await, gives up if it moved:
77
+ * a {@link Stop} that lands mid-setup can only release what setup has already published, so setup
78
+ * must release the rest itself rather than build a live graph on a stopped recorder.
79
+ */
80
+ setupGeneration = 0;
71
81
  /** True while a recorder is actively capturing. */
72
82
  get IsRecording() {
73
83
  return this.recording;
@@ -132,8 +142,7 @@ export class RealtimeAudioRecorder {
132
142
  return;
133
143
  }
134
144
  if (this.audioContext && this.captureNode()) {
135
- this.connectStream(this.audioContext, stream);
136
- this.remoteAttached = true;
145
+ this.remoteAttached = this.connectRemoteStream(this.audioContext, stream);
137
146
  }
138
147
  else {
139
148
  // Audio-graph setup still in flight (awaiting resume / worklet load) — connect at setup.
@@ -195,6 +204,7 @@ export class RealtimeAudioRecorder {
195
204
  }
196
205
  /** Wires up the Web Audio mix graph + PCM capture node (worklet preferred) and starts capture. */
197
206
  async startMixedRecording(micStream, remoteStream) {
207
+ const generation = this.setupGeneration;
198
208
  const audioContext = new AudioContext();
199
209
  // CRITICAL: browsers create an AudioContext in the `suspended` state under the autoplay policy.
200
210
  // Without resuming it, the mix graph never processes audio and we capture only silence. Starting
@@ -202,6 +212,11 @@ export class RealtimeAudioRecorder {
202
212
  if (audioContext.state === 'suspended') {
203
213
  await audioContext.resume();
204
214
  }
215
+ if (generation !== this.setupGeneration) {
216
+ // Stopped while resuming: the context was never published, so cleanup() could not close it.
217
+ void audioContext.close().catch(() => { });
218
+ return;
219
+ }
205
220
  const destination = audioContext.createMediaStreamDestination();
206
221
  // Publish the context + sample rate BEFORE wiring the remote so a concurrent AttachRemoteStream()
207
222
  // (the agent track can land during the awaits above) sees a ready graph to connect to.
@@ -211,14 +226,32 @@ export class RealtimeAudioRecorder {
211
226
  // Build the PCM capture node: AudioWorklet preferred, ScriptProcessor fallback. Either way the
212
227
  // node both pulls audio from the mix AND drives the destination so the graph keeps processing.
213
228
  await this.createCaptureNode(audioContext, destination);
229
+ if (generation !== this.setupGeneration) {
230
+ return; // Stopped while the capture node loaded: cleanup() already closed the published context.
231
+ }
214
232
  this.connectStream(audioContext, micStream);
215
233
  // Connect the agent's stream if it was passed now, or if AttachRemoteStream() stashed one while
216
234
  // we were setting up. Either way, capture the agent voice — not just the mic.
217
235
  const remote = remoteStream ?? this.pendingRemoteStream;
218
236
  this.pendingRemoteStream = null;
219
237
  if (remote && remote.getAudioTracks().length > 0) {
220
- this.connectStream(audioContext, remote);
221
- this.remoteAttached = true;
238
+ this.remoteAttached = this.connectRemoteStream(audioContext, remote);
239
+ }
240
+ }
241
+ /**
242
+ * Connects the agent stream, degrading to mic-only on failure. Unlike the mic (whose failure
243
+ * rightly disables the recorder), the agent stream is best-effort: a browser may reject it
244
+ * (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.
245
+ * Returns whether it was connected, so the caller only marks it attached on success.
246
+ */
247
+ connectRemoteStream(audioContext, stream) {
248
+ try {
249
+ this.connectStream(audioContext, stream);
250
+ return true;
251
+ }
252
+ catch (error) {
253
+ console.warn('[RealtimeAudioRecorder] Could not mix the agent stream into the recording — continuing mic-only:', error);
254
+ return false;
222
255
  }
223
256
  }
224
257
  /**
@@ -345,6 +378,7 @@ export class RealtimeAudioRecorder {
345
378
  }
346
379
  /** Releases the audio graph + capture node and resets state. Idempotent. */
347
380
  cleanup() {
381
+ this.setupGeneration++;
348
382
  this.recording = false;
349
383
  this.pcmFrames = [];
350
384
  this.totalSamples = 0;
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-audio-recorder.js","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,OAAO,qBAAqB;IAC9B,2EAA2E;IACnE,MAAM,CAAU,WAAW,GAAG,WAAW,CAAC;IAClD,4EAA4E;IACpE,MAAM,CAAU,WAAW,GAAG,GAAG,CAAC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AC,CAAC;YACrE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC7B,CAAC;IACL,CAAC","sourcesContent":["import { encodePcm16Wav, PeakAccumulator } from './realtime-pcm-wav';\n\n/**\n * Browser-side audio recorder for a CLIENT-DIRECT realtime voice session.\n *\n * Mixes the user's microphone stream with the agent's remote-audio stream (when the driver\n * exposes one — `OpenAIRealtimeClient.GetRemoteMediaStream()`) into a single mono **WAV** (16-bit\n * PCM) blob via the Web Audio API. Rather than a `MediaRecorder` (which only emits webm/opus —\n * header-less, no duration/cues, so HTTP-range seeking is unreliable), the mix is routed into an\n * {@link AudioWorkletNode} (preferred) or a {@link ScriptProcessorNode} (fallback) that captures\n * Float32 PCM frames. PCM is accumulated in memory and encoded as a seekable RIFF/WAVE file at\n * {@link Stop}. WAV's header carries the exact duration and maps byte-offset → time linearly, so\n * range seeking is exact and waveform peaks are computed cheaply during capture. The tradeoff is\n * size (PCM WAV is larger than opus) — acceptable for these short session recordings.\n *\n * Robust + MVP by design — every step degrades gracefully:\n * - No `AudioContext` (server-side render / unsupported env) → the recorder disables itself\n * ({@link IsRecording} stays `false`, {@link Stop} resolves `null`); the voice call proceeds.\n * - No `AudioWorkletNode` AND no `ScriptProcessorNode` → disables itself rather than throwing.\n * - No remote stream (non-WebRTC drivers, or the track hasn't landed yet) → records mic only.\n * - Any construction/start error is logged and disables the recorder rather than throwing into\n * the session-start path.\n *\n * Not an Angular service: it owns transient per-session media plumbing the\n * {@link RealtimeSessionService} creates and discards per call, so a plain class is the right\n * shape (no DI, no singleton).\n */\nexport class RealtimeAudioRecorder {\n /** The container/codec we now produce — a seekable mono 16-bit PCM WAV. */\n private static readonly WavMimeType = 'audio/wav';\n /** Target waveform-peak resolution (buckets) across the whole recording. */\n private static readonly PeakBuckets = 600;\n /** PCM frame size for the ScriptProcessor fallback (worklet uses its native 128-frame quantum). */\n private static readonly ScriptProcessorBufferSize = 4096;\n /** Inline AudioWorklet processor: forwards each 128-frame mono input block to the main thread. */\n private static readonly WorkletProcessorSource = `\n class MJPcmCaptureProcessor extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0];\n if (input && input[0] && input[0].length > 0) {\n // Copy out of the reused worklet buffer before posting.\n this.port.postMessage(input[0].slice(0));\n }\n return true;\n }\n }\n registerProcessor('mj-pcm-capture', MJPcmCaptureProcessor);\n `;\n\n private audioContext: AudioContext | null = null;\n private destination: MediaStreamAudioDestinationNode | null = null;\n private workletNode: AudioWorkletNode | null = null;\n private scriptNode: ScriptProcessorNode | null = null;\n /** Captured mono Float32 PCM frames (in capture order); concatenated + encoded to WAV at Stop. */\n private pcmFrames: Float32Array[] = [];\n /** Total captured sample count across {@link pcmFrames} (kept in step to avoid re-summing). */\n private totalSamples = 0;\n /** Streaming waveform-peak accumulator — bounded regardless of recording length. */\n private peaks = new PeakAccumulator(RealtimeAudioRecorder.PeakBuckets);\n /** Final normalized peaks, snapshotted at {@link Stop} so {@link GetPeaks} survives cleanup. */\n private finalPeaks: number[] = [];\n private recording = false;\n\n /** True once the agent's remote stream has been wired into the mix (prevents double-attach). */\n private remoteAttached = false;\n /** A remote stream handed to AttachRemoteStream before the audio graph was ready; wired at setup. */\n private pendingRemoteStream: MediaStream | null = null;\n\n /** Sample index up to which crash-recovery shards have already been emitted (the segment cursor). */\n private flushedSampleCount = 0;\n\n /** Wall-clock ms at recording start; anchors {@link NowOffsetMs}. 0 before {@link Start}. */\n private startedAtMs = 0;\n\n /** Sample rate of the capturing {@link AudioContext}; 0 before {@link Start}. Needed to wrap shards. */\n private sampleRate = 0;\n\n /** True while a recorder is actively capturing. */\n public get IsRecording(): boolean {\n return this.recording;\n }\n\n /** Wall-clock ms when recording started (0 before {@link Start}). */\n public get StartedAtMs(): number {\n return this.startedAtMs;\n }\n\n /**\n * The container/codec the active recording uses. Always `'audio/wav'` once recording (empty\n * string before {@link Start} / when disabled) — the consolidated upload and the WAV-wrapped\n * crash-recovery shards are all 16-bit PCM WAV.\n */\n public get MimeType(): string {\n return this.recording ? RealtimeAudioRecorder.WavMimeType : '';\n }\n\n /**\n * The captured AudioContext sample rate (0 before {@link Start} / when disabled). Exposed so a\n * recovery path can WAV-wrap the raw-PCM shards with the correct rate.\n */\n public get SampleRate(): number {\n return this.sampleRate;\n }\n\n /**\n * Begins recording a mix of `micStream` and (when present) `remoteStream`. Best-effort:\n * a missing `AudioContext` / no worklet+scriptprocessor support / any setup failure disables\n * the recorder silently (logged) so the live call is never blocked.\n *\n * @param micStream The user's microphone capture stream (required).\n * @param remoteStream The agent's remote-audio stream, or `null` for mic-only capture.\n */\n public Start(micStream: MediaStream, remoteStream: MediaStream | null): void {\n if (this.recording) {\n return;\n }\n if (typeof AudioContext === 'undefined') {\n console.warn('[RealtimeAudioRecorder] AudioContext unavailable — recording disabled for this session.');\n return;\n }\n // Mark recording + stamp t0 SYNCHRONOUSLY so a caller that checks IsRecording immediately after\n // Start() (the session service does) sees `true`, even though the audio-graph setup\n // (AudioContext.resume + worklet module load) completes asynchronously below. Without this the\n // caller discards the recorder before it finishes starting and nothing is ever uploaded.\n this.startedAtMs = Date.now();\n this.finalPeaks = [];\n this.recording = true;\n // Fire-and-forget the async setup (it must `await audioContext.resume()` + worklet load); any\n // failure disables the recorder rather than throwing into the session-start path.\n void this.startMixedRecording(micStream, remoteStream).catch((error) => {\n console.warn('[RealtimeAudioRecorder] Failed to start recording — disabling for this session:', error);\n this.cleanup();\n });\n }\n\n /**\n * Wires the agent's remote-audio stream into the live mix once it arrives. The WebRTC\n * `ontrack` that delivers the agent voice usually lands AFTER recording has already begun\n * (mic-only), so the session attaches it here when it lands. Idempotent, and safe to call\n * before the audio graph finishes its async setup (the stream is connected once ready).\n */\n public AttachRemoteStream(stream: MediaStream): void {\n if (this.remoteAttached || stream.getAudioTracks().length === 0) {\n return;\n }\n if (this.audioContext && this.captureNode()) {\n this.connectStream(this.audioContext, stream);\n this.remoteAttached = true;\n } else {\n // Audio-graph setup still in flight (awaiting resume / worklet load) — connect at setup.\n this.pendingRemoteStream = stream;\n }\n }\n\n /**\n * Returns a Blob of the raw PCM captured since the last call (a window of header-less,\n * little-endian PCM16 bytes), advancing the segment cursor. `null` when nothing new. Used to\n * upload crash-recovery shards mid-call. NOTE: shards are header-less raw PCM (NOT individually\n * playable WAV) — recovery is concatenation in order, then WAV-wrapping with {@link SampleRate}.\n * The canonical consolidated file is still authored as a single WAV from full memory at {@link Stop}.\n */\n public SnapshotNewSegment(): Blob | null {\n if (!this.recording || this.flushedSampleCount >= this.totalSamples) {\n return null;\n }\n const fresh = this.collectSamples(this.flushedSampleCount, this.totalSamples);\n this.flushedSampleCount = this.totalSamples;\n if (fresh.length === 0) {\n return null;\n }\n const pcm16 = this.floatToPcm16Bytes(fresh);\n return new Blob([pcm16], { type: 'application/octet-stream' });\n }\n\n /** Ms elapsed since recording started (>= 0); 0 when not recording. */\n public NowOffsetMs(): number {\n if (this.startedAtMs === 0) {\n return 0;\n }\n return Math.max(0, Date.now() - this.startedAtMs);\n }\n\n /**\n * The downsampled waveform peaks (each 0..1, max-abs per bucket, ~{@link RealtimeAudioRecorder.PeakBuckets}\n * buckets across the whole recording). Computed incrementally during capture so it's cheap and\n * bounded regardless of length. Returns `[]` before any audio / for a silent recording. Safe to\n * call after {@link Stop} — the peaks are snapshotted there before {@link cleanup} clears state.\n */\n public GetPeaks(): number[] {\n return this.recording ? this.peaks.Normalize() : this.finalPeaks;\n }\n\n /**\n * Stops recording and resolves the captured audio as a single mono 16-bit PCM **WAV**\n * {@link Blob}, then releases the audio graph. Resolves `null` when nothing was recorded\n * (recorder disabled, or no samples captured). Safe to call when not recording.\n */\n public async Stop(): Promise<Blob | null> {\n if (!this.recording) {\n this.cleanup();\n return null;\n }\n // Detach the capture node so no further frames arrive while we assemble the file. Snapshot the\n // peaks BEFORE cleanup so GetPeaks() still returns them for the post-Stop upload.\n this.recording = false;\n this.finalPeaks = this.peaks.Normalize();\n const blob = this.encodeWavBlob();\n this.cleanup();\n return blob;\n }\n\n /** Wires up the Web Audio mix graph + PCM capture node (worklet preferred) and starts capture. */\n private async startMixedRecording(micStream: MediaStream, remoteStream: MediaStream | null): Promise<void> {\n const audioContext = new AudioContext();\n // CRITICAL: browsers create an AudioContext in the `suspended` state under the autoplay policy.\n // Without resuming it, the mix graph never processes audio and we capture only silence. Starting\n // a voice call is a user gesture, so resume() succeeds here.\n if (audioContext.state === 'suspended') {\n await audioContext.resume();\n }\n const destination = audioContext.createMediaStreamDestination();\n // Publish the context + sample rate BEFORE wiring the remote so a concurrent AttachRemoteStream()\n // (the agent track can land during the awaits above) sees a ready graph to connect to.\n this.audioContext = audioContext;\n this.destination = destination;\n this.sampleRate = audioContext.sampleRate;\n\n // Build the PCM capture node: AudioWorklet preferred, ScriptProcessor fallback. Either way the\n // node both pulls audio from the mix AND drives the destination so the graph keeps processing.\n await this.createCaptureNode(audioContext, destination);\n\n this.connectStream(audioContext, micStream);\n // Connect the agent's stream if it was passed now, or if AttachRemoteStream() stashed one while\n // we were setting up. Either way, capture the agent voice — not just the mic.\n const remote = remoteStream ?? this.pendingRemoteStream;\n this.pendingRemoteStream = null;\n if (remote && remote.getAudioTracks().length > 0) {\n this.connectStream(audioContext, remote);\n this.remoteAttached = true;\n }\n }\n\n /**\n * Creates the PCM capture node and inserts it into the graph: sources → captureNode → destination.\n * Prefers an {@link AudioWorkletNode} (off-main-thread, no deprecation); falls back to a\n * {@link ScriptProcessorNode} where worklets are unavailable. Throws when neither is supported\n * (caught by {@link Start}, which then disables the recorder).\n */\n private async createCaptureNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<void> {\n if (await this.tryCreateWorkletNode(audioContext, destination)) {\n return;\n }\n this.createScriptProcessorNode(audioContext, destination);\n }\n\n /** Attempts to build the AudioWorklet capture node; returns `false` (no throw) when unsupported. */\n private async tryCreateWorkletNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<boolean> {\n if (!audioContext.audioWorklet || typeof AudioWorkletNode === 'undefined' || typeof Blob === 'undefined') {\n return false;\n }\n try {\n const moduleUrl = URL.createObjectURL(\n new Blob([RealtimeAudioRecorder.WorkletProcessorSource], { type: 'application/javascript' }),\n );\n try {\n await audioContext.audioWorklet.addModule(moduleUrl);\n } finally {\n URL.revokeObjectURL(moduleUrl);\n }\n const node = new AudioWorkletNode(audioContext, 'mj-pcm-capture', { numberOfInputs: 1, numberOfOutputs: 1 });\n node.port.onmessage = (event: MessageEvent<Float32Array>) => this.captureFrame(event.data);\n node.connect(destination);\n this.workletNode = node;\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] AudioWorklet unavailable — falling back to ScriptProcessor:', error);\n return false;\n }\n }\n\n /** Builds the ScriptProcessor fallback capture node and inserts it into the graph. */\n private createScriptProcessorNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): void {\n if (typeof audioContext.createScriptProcessor !== 'function') {\n throw new Error('Neither AudioWorklet nor ScriptProcessor is supported');\n }\n const node = audioContext.createScriptProcessor(RealtimeAudioRecorder.ScriptProcessorBufferSize, 1, 1);\n node.onaudioprocess = (event: AudioProcessingEvent) => {\n // Copy out of the reused input buffer before retaining.\n this.captureFrame(event.inputBuffer.getChannelData(0).slice(0));\n };\n // ScriptProcessor only fires onaudioprocess while connected to the destination.\n node.connect(destination);\n this.scriptNode = node;\n }\n\n /** The active capture node (worklet or script processor), or `null` before setup. */\n private captureNode(): AudioNode | null {\n return this.workletNode ?? this.scriptNode;\n }\n\n /** Absorbs one captured PCM frame: accumulate samples + update the bounded peak array. */\n private captureFrame(frame: Float32Array): void {\n if (!this.recording || frame.length === 0) {\n return;\n }\n // Defensive copy — worklet/script buffers are reused by the engine.\n const copy = frame.slice(0);\n this.pcmFrames.push(copy);\n this.totalSamples += copy.length;\n this.peaks.Push(copy);\n }\n\n /** Routes one stream's audio tracks into the capture node (no-op when track-less / no node). */\n private connectStream(audioContext: AudioContext, stream: MediaStream): void {\n const node = this.captureNode();\n if (!node || stream.getAudioTracks().length === 0) {\n return;\n }\n const source = audioContext.createMediaStreamSource(stream);\n source.connect(node);\n }\n\n /** Concatenates a half-open sample range [from, to) across the captured frames into one Float32Array. */\n private collectSamples(from: number, to: number): Float32Array {\n const out = new Float32Array(Math.max(0, to - from));\n if (out.length === 0) {\n return out;\n }\n let cursor = 0; // absolute sample index at the start of the current frame\n let written = 0;\n for (const frame of this.pcmFrames) {\n const frameStart = cursor;\n const frameEnd = cursor + frame.length;\n cursor = frameEnd;\n if (frameEnd <= from) {\n continue; // entirely before the window\n }\n if (frameStart >= to) {\n break; // entirely after the window\n }\n const sliceStart = Math.max(0, from - frameStart);\n const sliceEnd = Math.min(frame.length, to - frameStart);\n for (let i = sliceStart; i < sliceEnd; i++) {\n out[written++] = frame[i];\n }\n }\n return written === out.length ? out : out.subarray(0, written);\n }\n\n /**\n * Converts a mono Float32 buffer to a little-endian PCM16 `ArrayBuffer` (for raw crash-recovery\n * shards). Returns the backing `ArrayBuffer` directly so it's a valid `BlobPart`.\n */\n private floatToPcm16Bytes(samples: Float32Array): ArrayBuffer {\n const buffer = new ArrayBuffer(samples.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < samples.length; i++) {\n const s = samples[i] < -1 ? -1 : samples[i] > 1 ? 1 : samples[i];\n view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n }\n return buffer;\n }\n\n /** Encodes all accumulated PCM into a single seekable WAV blob, or `null` when nothing captured. */\n private encodeWavBlob(): Blob | null {\n if (this.totalSamples === 0 || this.sampleRate === 0) {\n return null;\n }\n const all = this.collectSamples(0, this.totalSamples);\n const wav = encodePcm16Wav(all, this.sampleRate);\n return new Blob([wav], { type: RealtimeAudioRecorder.WavMimeType });\n }\n\n /** Releases the audio graph + capture node and resets state. Idempotent. */\n private cleanup(): void {\n this.recording = false;\n this.pcmFrames = [];\n this.totalSamples = 0;\n this.flushedSampleCount = 0;\n this.sampleRate = 0;\n this.peaks = new PeakAccumulator(RealtimeAudioRecorder.PeakBuckets);\n this.remoteAttached = false;\n this.pendingRemoteStream = null;\n if (this.workletNode) {\n this.workletNode.port.onmessage = null;\n try { this.workletNode.disconnect(); } catch { /* already disconnected */ }\n this.workletNode = null;\n }\n if (this.scriptNode) {\n this.scriptNode.onaudioprocess = null;\n try { this.scriptNode.disconnect(); } catch { /* already disconnected */ }\n this.scriptNode = null;\n }\n this.destination = null;\n if (this.audioContext) {\n void this.audioContext.close().catch(() => { /* already closed */ });\n this.audioContext = null;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"realtime-audio-recorder.js","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,OAAO,qBAAqB;IAC9B,2EAA2E;IACnE,MAAM,CAAU,WAAW,GAAG,WAAW,CAAC;IAClD,4EAA4E;IACpE,MAAM,CAAU,WAAW,GAAG,GAAG,CAAC;IAC1C,mGAAmG;IAC3F,MAAM,CAAU,yBAAyB,GAAG,IAAI,CAAC;IACzD,kGAAkG;IAC1F,MAAM,CAAU,sBAAsB,GAAG;;;;;;;;;;;;KAYhD,CAAC;IAEM,YAAY,GAAwB,IAAI,CAAC;IACzC,WAAW,GAA2C,IAAI,CAAC;IAC3D,WAAW,GAA4B,IAAI,CAAC;IAC5C,UAAU,GAA+B,IAAI,CAAC;IACtD,kGAAkG;IAC1F,SAAS,GAAmB,EAAE,CAAC;IACvC,+FAA+F;IACvF,YAAY,GAAG,CAAC,CAAC;IACzB,oFAAoF;IAC5E,KAAK,GAAG,IAAI,eAAe,CAAC,qBAAqB,CAAC,WAAW,CAAC,CAAC;IACvE,gGAAgG;IACxF,UAAU,GAAa,EAAE,CAAC;IAC1B,SAAS,GAAG,KAAK,CAAC;IAE1B,gGAAgG;IACxF,cAAc,GAAG,KAAK,CAAC;IAC/B,qGAAqG;IAC7F,mBAAmB,GAAuB,IAAI,C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YAAY,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAwB,CAAC,CAAC,CAAC;YACrE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC7B,CAAC;IACL,CAAC","sourcesContent":["import { encodePcm16Wav, PeakAccumulator } from './realtime-pcm-wav';\n\n/**\n * Browser-side audio recorder for a CLIENT-DIRECT realtime voice session.\n *\n * Mixes the user's microphone stream with the agent's remote-audio stream (every driver exposes\n * one via `GetRemoteMediaStream()`: WebRTC drivers publish their remote track, PCM drivers —\n * Gemini, ElevenLabs, AssemblyAI, xAI, HuggingFace — publish their playout engine's output) into a\n * single mono **WAV** (16-bit PCM) blob via the Web Audio API. Rather than a `MediaRecorder` (which only emits webm/opus —\n * header-less, no duration/cues, so HTTP-range seeking is unreliable), the mix is routed into an\n * {@link AudioWorkletNode} (preferred) or a {@link ScriptProcessorNode} (fallback) that captures\n * Float32 PCM frames. PCM is accumulated in memory and encoded as a seekable RIFF/WAVE file at\n * {@link Stop}. WAV's header carries the exact duration and maps byte-offset → time linearly, so\n * range seeking is exact and waveform peaks are computed cheaply during capture. The tradeoff is\n * size (PCM WAV is larger than opus) — acceptable for these short session recordings.\n *\n * Robust + MVP by design — every step degrades gracefully:\n * - No `AudioContext` (server-side render / unsupported env) → the recorder disables itself\n * ({@link IsRecording} stays `false`, {@link Stop} resolves `null`); the voice call proceeds.\n * - No `AudioWorkletNode` AND no `ScriptProcessorNode` → disables itself rather than throwing.\n * - No remote stream yet (e.g. the WebRTC track hasn't landed) → records mic only until it does.\n * - A remote stream that can't be connected (e.g. a browser that rejects cross-sample-rate\n * `createMediaStreamSource` — the PCM playout context runs at 24 kHz, this one at the device\n * rate) → warns and records mic only; the mic recording is never lost to the agent stream.\n * - Any construction/start error is logged and disables the recorder rather than throwing into\n * the session-start path.\n *\n * Not an Angular service: it owns transient per-session media plumbing the\n * {@link RealtimeSessionService} creates and discards per call, so a plain class is the right\n * shape (no DI, no singleton).\n */\nexport class RealtimeAudioRecorder {\n /** The container/codec we now produce — a seekable mono 16-bit PCM WAV. */\n private static readonly WavMimeType = 'audio/wav';\n /** Target waveform-peak resolution (buckets) across the whole recording. */\n private static readonly PeakBuckets = 600;\n /** PCM frame size for the ScriptProcessor fallback (worklet uses its native 128-frame quantum). */\n private static readonly ScriptProcessorBufferSize = 4096;\n /** Inline AudioWorklet processor: forwards each 128-frame mono input block to the main thread. */\n private static readonly WorkletProcessorSource = `\n class MJPcmCaptureProcessor extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0];\n if (input && input[0] && input[0].length > 0) {\n // Copy out of the reused worklet buffer before posting.\n this.port.postMessage(input[0].slice(0));\n }\n return true;\n }\n }\n registerProcessor('mj-pcm-capture', MJPcmCaptureProcessor);\n `;\n\n private audioContext: AudioContext | null = null;\n private destination: MediaStreamAudioDestinationNode | null = null;\n private workletNode: AudioWorkletNode | null = null;\n private scriptNode: ScriptProcessorNode | null = null;\n /** Captured mono Float32 PCM frames (in capture order); concatenated + encoded to WAV at Stop. */\n private pcmFrames: Float32Array[] = [];\n /** Total captured sample count across {@link pcmFrames} (kept in step to avoid re-summing). */\n private totalSamples = 0;\n /** Streaming waveform-peak accumulator — bounded regardless of recording length. */\n private peaks = new PeakAccumulator(RealtimeAudioRecorder.PeakBuckets);\n /** Final normalized peaks, snapshotted at {@link Stop} so {@link GetPeaks} survives cleanup. */\n private finalPeaks: number[] = [];\n private recording = false;\n\n /** True once the agent's remote stream has been wired into the mix (prevents double-attach). */\n private remoteAttached = false;\n /** A remote stream handed to AttachRemoteStream before the audio graph was ready; wired at setup. */\n private pendingRemoteStream: MediaStream | null = null;\n\n /** Sample index up to which crash-recovery shards have already been emitted (the segment cursor). */\n private flushedSampleCount = 0;\n\n /** Wall-clock ms at recording start; anchors {@link NowOffsetMs}. 0 before {@link Start}. */\n private startedAtMs = 0;\n\n /** Sample rate of the capturing {@link AudioContext}; 0 before {@link Start}. Needed to wrap shards. */\n private sampleRate = 0;\n\n /**\n * Bumped by {@link cleanup}. The async setup snapshots it and, after each await, gives up if it moved:\n * a {@link Stop} that lands mid-setup can only release what setup has already published, so setup\n * must release the rest itself rather than build a live graph on a stopped recorder.\n */\n private setupGeneration = 0;\n\n /** True while a recorder is actively capturing. */\n public get IsRecording(): boolean {\n return this.recording;\n }\n\n /** Wall-clock ms when recording started (0 before {@link Start}). */\n public get StartedAtMs(): number {\n return this.startedAtMs;\n }\n\n /**\n * The container/codec the active recording uses. Always `'audio/wav'` once recording (empty\n * string before {@link Start} / when disabled) — the consolidated upload and the WAV-wrapped\n * crash-recovery shards are all 16-bit PCM WAV.\n */\n public get MimeType(): string {\n return this.recording ? RealtimeAudioRecorder.WavMimeType : '';\n }\n\n /**\n * The captured AudioContext sample rate (0 before {@link Start} / when disabled). Exposed so a\n * recovery path can WAV-wrap the raw-PCM shards with the correct rate.\n */\n public get SampleRate(): number {\n return this.sampleRate;\n }\n\n /**\n * Begins recording a mix of `micStream` and (when present) `remoteStream`. Best-effort:\n * a missing `AudioContext` / no worklet+scriptprocessor support / any setup failure disables\n * the recorder silently (logged) so the live call is never blocked.\n *\n * @param micStream The user's microphone capture stream (required).\n * @param remoteStream The agent's remote-audio stream, or `null` for mic-only capture.\n */\n public Start(micStream: MediaStream, remoteStream: MediaStream | null): void {\n if (this.recording) {\n return;\n }\n if (typeof AudioContext === 'undefined') {\n console.warn('[RealtimeAudioRecorder] AudioContext unavailable — recording disabled for this session.');\n return;\n }\n // Mark recording + stamp t0 SYNCHRONOUSLY so a caller that checks IsRecording immediately after\n // Start() (the session service does) sees `true`, even though the audio-graph setup\n // (AudioContext.resume + worklet module load) completes asynchronously below. Without this the\n // caller discards the recorder before it finishes starting and nothing is ever uploaded.\n this.startedAtMs = Date.now();\n this.finalPeaks = [];\n this.recording = true;\n // Fire-and-forget the async setup (it must `await audioContext.resume()` + worklet load); any\n // failure disables the recorder rather than throwing into the session-start path.\n void this.startMixedRecording(micStream, remoteStream).catch((error) => {\n console.warn('[RealtimeAudioRecorder] Failed to start recording — disabling for this session:', error);\n this.cleanup();\n });\n }\n\n /**\n * Wires the agent's remote-audio stream into the live mix once it arrives. The WebRTC\n * `ontrack` that delivers the agent voice usually lands AFTER recording has already begun\n * (mic-only), so the session attaches it here when it lands. Idempotent, and safe to call\n * before the audio graph finishes its async setup (the stream is connected once ready).\n */\n public AttachRemoteStream(stream: MediaStream): void {\n if (this.remoteAttached || stream.getAudioTracks().length === 0) {\n return;\n }\n if (this.audioContext && this.captureNode()) {\n this.remoteAttached = this.connectRemoteStream(this.audioContext, stream);\n } else {\n // Audio-graph setup still in flight (awaiting resume / worklet load) — connect at setup.\n this.pendingRemoteStream = stream;\n }\n }\n\n /**\n * Returns a Blob of the raw PCM captured since the last call (a window of header-less,\n * little-endian PCM16 bytes), advancing the segment cursor. `null` when nothing new. Used to\n * upload crash-recovery shards mid-call. NOTE: shards are header-less raw PCM (NOT individually\n * playable WAV) — recovery is concatenation in order, then WAV-wrapping with {@link SampleRate}.\n * The canonical consolidated file is still authored as a single WAV from full memory at {@link Stop}.\n */\n public SnapshotNewSegment(): Blob | null {\n if (!this.recording || this.flushedSampleCount >= this.totalSamples) {\n return null;\n }\n const fresh = this.collectSamples(this.flushedSampleCount, this.totalSamples);\n this.flushedSampleCount = this.totalSamples;\n if (fresh.length === 0) {\n return null;\n }\n const pcm16 = this.floatToPcm16Bytes(fresh);\n return new Blob([pcm16], { type: 'application/octet-stream' });\n }\n\n /** Ms elapsed since recording started (>= 0); 0 when not recording. */\n public NowOffsetMs(): number {\n if (this.startedAtMs === 0) {\n return 0;\n }\n return Math.max(0, Date.now() - this.startedAtMs);\n }\n\n /**\n * The downsampled waveform peaks (each 0..1, max-abs per bucket, ~{@link RealtimeAudioRecorder.PeakBuckets}\n * buckets across the whole recording). Computed incrementally during capture so it's cheap and\n * bounded regardless of length. Returns `[]` before any audio / for a silent recording. Safe to\n * call after {@link Stop} — the peaks are snapshotted there before {@link cleanup} clears state.\n */\n public GetPeaks(): number[] {\n return this.recording ? this.peaks.Normalize() : this.finalPeaks;\n }\n\n /**\n * Stops recording and resolves the captured audio as a single mono 16-bit PCM **WAV**\n * {@link Blob}, then releases the audio graph. Resolves `null` when nothing was recorded\n * (recorder disabled, or no samples captured). Safe to call when not recording.\n */\n public async Stop(): Promise<Blob | null> {\n if (!this.recording) {\n this.cleanup();\n return null;\n }\n // Detach the capture node so no further frames arrive while we assemble the file. Snapshot the\n // peaks BEFORE cleanup so GetPeaks() still returns them for the post-Stop upload.\n this.recording = false;\n this.finalPeaks = this.peaks.Normalize();\n const blob = this.encodeWavBlob();\n this.cleanup();\n return blob;\n }\n\n /** Wires up the Web Audio mix graph + PCM capture node (worklet preferred) and starts capture. */\n private async startMixedRecording(micStream: MediaStream, remoteStream: MediaStream | null): Promise<void> {\n const generation = this.setupGeneration;\n const audioContext = new AudioContext();\n // CRITICAL: browsers create an AudioContext in the `suspended` state under the autoplay policy.\n // Without resuming it, the mix graph never processes audio and we capture only silence. Starting\n // a voice call is a user gesture, so resume() succeeds here.\n if (audioContext.state === 'suspended') {\n await audioContext.resume();\n }\n if (generation !== this.setupGeneration) {\n // Stopped while resuming: the context was never published, so cleanup() could not close it.\n void audioContext.close().catch(() => { /* already closed */ });\n return;\n }\n const destination = audioContext.createMediaStreamDestination();\n // Publish the context + sample rate BEFORE wiring the remote so a concurrent AttachRemoteStream()\n // (the agent track can land during the awaits above) sees a ready graph to connect to.\n this.audioContext = audioContext;\n this.destination = destination;\n this.sampleRate = audioContext.sampleRate;\n\n // Build the PCM capture node: AudioWorklet preferred, ScriptProcessor fallback. Either way the\n // node both pulls audio from the mix AND drives the destination so the graph keeps processing.\n await this.createCaptureNode(audioContext, destination);\n if (generation !== this.setupGeneration) {\n return; // Stopped while the capture node loaded: cleanup() already closed the published context.\n }\n\n this.connectStream(audioContext, micStream);\n // Connect the agent's stream if it was passed now, or if AttachRemoteStream() stashed one while\n // we were setting up. Either way, capture the agent voice — not just the mic.\n const remote = remoteStream ?? this.pendingRemoteStream;\n this.pendingRemoteStream = null;\n if (remote && remote.getAudioTracks().length > 0) {\n this.remoteAttached = this.connectRemoteStream(audioContext, remote);\n }\n }\n\n /**\n * Connects the agent stream, degrading to mic-only on failure. Unlike the mic (whose failure\n * rightly disables the recorder), the agent stream is best-effort: a browser may reject it\n * (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.\n * Returns whether it was connected, so the caller only marks it attached on success.\n */\n private connectRemoteStream(audioContext: AudioContext, stream: MediaStream): boolean {\n try {\n this.connectStream(audioContext, stream);\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] Could not mix the agent stream into the recording — continuing mic-only:', error);\n return false;\n }\n }\n\n /**\n * Creates the PCM capture node and inserts it into the graph: sources → captureNode → destination.\n * Prefers an {@link AudioWorkletNode} (off-main-thread, no deprecation); falls back to a\n * {@link ScriptProcessorNode} where worklets are unavailable. Throws when neither is supported\n * (caught by {@link Start}, which then disables the recorder).\n */\n private async createCaptureNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<void> {\n if (await this.tryCreateWorkletNode(audioContext, destination)) {\n return;\n }\n this.createScriptProcessorNode(audioContext, destination);\n }\n\n /** Attempts to build the AudioWorklet capture node; returns `false` (no throw) when unsupported. */\n private async tryCreateWorkletNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<boolean> {\n if (!audioContext.audioWorklet || typeof AudioWorkletNode === 'undefined' || typeof Blob === 'undefined') {\n return false;\n }\n try {\n const moduleUrl = URL.createObjectURL(\n new Blob([RealtimeAudioRecorder.WorkletProcessorSource], { type: 'application/javascript' }),\n );\n try {\n await audioContext.audioWorklet.addModule(moduleUrl);\n } finally {\n URL.revokeObjectURL(moduleUrl);\n }\n const node = new AudioWorkletNode(audioContext, 'mj-pcm-capture', { numberOfInputs: 1, numberOfOutputs: 1 });\n node.port.onmessage = (event: MessageEvent<Float32Array>) => this.captureFrame(event.data);\n node.connect(destination);\n this.workletNode = node;\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] AudioWorklet unavailable — falling back to ScriptProcessor:', error);\n return false;\n }\n }\n\n /** Builds the ScriptProcessor fallback capture node and inserts it into the graph. */\n private createScriptProcessorNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): void {\n if (typeof audioContext.createScriptProcessor !== 'function') {\n throw new Error('Neither AudioWorklet nor ScriptProcessor is supported');\n }\n const node = audioContext.createScriptProcessor(RealtimeAudioRecorder.ScriptProcessorBufferSize, 1, 1);\n node.onaudioprocess = (event: AudioProcessingEvent) => {\n // Copy out of the reused input buffer before retaining.\n this.captureFrame(event.inputBuffer.getChannelData(0).slice(0));\n };\n // ScriptProcessor only fires onaudioprocess while connected to the destination.\n node.connect(destination);\n this.scriptNode = node;\n }\n\n /** The active capture node (worklet or script processor), or `null` before setup. */\n private captureNode(): AudioNode | null {\n return this.workletNode ?? this.scriptNode;\n }\n\n /** Absorbs one captured PCM frame: accumulate samples + update the bounded peak array. */\n private captureFrame(frame: Float32Array): void {\n if (!this.recording || frame.length === 0) {\n return;\n }\n // Defensive copy — worklet/script buffers are reused by the engine.\n const copy = frame.slice(0);\n this.pcmFrames.push(copy);\n this.totalSamples += copy.length;\n this.peaks.Push(copy);\n }\n\n /** Routes one stream's audio tracks into the capture node (no-op when track-less / no node). */\n private connectStream(audioContext: AudioContext, stream: MediaStream): void {\n const node = this.captureNode();\n if (!node || stream.getAudioTracks().length === 0) {\n return;\n }\n const source = audioContext.createMediaStreamSource(stream);\n source.connect(node);\n }\n\n /** Concatenates a half-open sample range [from, to) across the captured frames into one Float32Array. */\n private collectSamples(from: number, to: number): Float32Array {\n const out = new Float32Array(Math.max(0, to - from));\n if (out.length === 0) {\n return out;\n }\n let cursor = 0; // absolute sample index at the start of the current frame\n let written = 0;\n for (const frame of this.pcmFrames) {\n const frameStart = cursor;\n const frameEnd = cursor + frame.length;\n cursor = frameEnd;\n if (frameEnd <= from) {\n continue; // entirely before the window\n }\n if (frameStart >= to) {\n break; // entirely after the window\n }\n const sliceStart = Math.max(0, from - frameStart);\n const sliceEnd = Math.min(frame.length, to - frameStart);\n for (let i = sliceStart; i < sliceEnd; i++) {\n out[written++] = frame[i];\n }\n }\n return written === out.length ? out : out.subarray(0, written);\n }\n\n /**\n * Converts a mono Float32 buffer to a little-endian PCM16 `ArrayBuffer` (for raw crash-recovery\n * shards). Returns the backing `ArrayBuffer` directly so it's a valid `BlobPart`.\n */\n private floatToPcm16Bytes(samples: Float32Array): ArrayBuffer {\n const buffer = new ArrayBuffer(samples.length * 2);\n const view = new DataView(buffer);\n for (let i = 0; i < samples.length; i++) {\n const s = samples[i] < -1 ? -1 : samples[i] > 1 ? 1 : samples[i];\n view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);\n }\n return buffer;\n }\n\n /** Encodes all accumulated PCM into a single seekable WAV blob, or `null` when nothing captured. */\n private encodeWavBlob(): Blob | null {\n if (this.totalSamples === 0 || this.sampleRate === 0) {\n return null;\n }\n const all = this.collectSamples(0, this.totalSamples);\n const wav = encodePcm16Wav(all, this.sampleRate);\n return new Blob([wav], { type: RealtimeAudioRecorder.WavMimeType });\n }\n\n /** Releases the audio graph + capture node and resets state. Idempotent. */\n private cleanup(): void {\n this.setupGeneration++;\n this.recording = false;\n this.pcmFrames = [];\n this.totalSamples = 0;\n this.flushedSampleCount = 0;\n this.sampleRate = 0;\n this.peaks = new PeakAccumulator(RealtimeAudioRecorder.PeakBuckets);\n this.remoteAttached = false;\n this.pendingRemoteStream = null;\n if (this.workletNode) {\n this.workletNode.port.onmessage = null;\n try { this.workletNode.disconnect(); } catch { /* already disconnected */ }\n this.workletNode = null;\n }\n if (this.scriptNode) {\n this.scriptNode.onaudioprocess = null;\n try { this.scriptNode.disconnect(); } catch { /* already disconnected */ }\n this.scriptNode = null;\n }\n this.destination = null;\n if (this.audioContext) {\n void this.audioContext.close().catch(() => { /* already closed */ });\n this.audioContext = null;\n }\n }\n}\n"]}
@@ -802,9 +802,9 @@ export class RealtimeSessionService {
802
802
  this.currentTurnStartMs = recorder.IsRecording ? 0 : null;
803
803
  this.turnAudioStartCaptured = false;
804
804
  if (this.recorder) {
805
- // The agent's WebRTC audio track usually lands AFTER Connect() resolves, so `remoteStream`
806
- // above is typically null and we'd capture mic-only. Attach the agent stream whenever it
807
- // arrives (fires immediately if already present) so the recording includes the agent voice.
805
+ // WebRTC drivers publish their track after Connect; PCM drivers publish their playout
806
+ // stream during Connect. The immediate callback may repeat the stream passed to Start;
807
+ // AttachRemoteStream is idempotent so the agent is mixed only once.
808
808
  client.OnRemoteMediaStream?.((stream) => this.recorder?.AttachRemoteStream(stream));
809
809
  this.startSegmentFlushing();
810
810
  }