@oxvo/ai-live-assist 7.4.50 → 7.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/cjs/AiLiveAssist.d.ts +76 -11
  2. package/cjs/AiLiveAssist.js +1771 -298
  3. package/cjs/client.d.ts +19 -0
  4. package/cjs/client.js +51 -0
  5. package/cjs/context.d.ts +23 -1
  6. package/cjs/context.js +713 -126
  7. package/cjs/control.d.ts +2 -0
  8. package/cjs/control.js +42 -3
  9. package/cjs/ctaOffer.d.ts +11 -0
  10. package/cjs/ctaOffer.js +185 -0
  11. package/cjs/dialogFocusScope.js +1 -1
  12. package/cjs/guideAdmission.d.ts +46 -0
  13. package/cjs/guideAdmission.js +397 -0
  14. package/cjs/guideHost.d.ts +47 -0
  15. package/cjs/guideHost.js +48 -0
  16. package/cjs/guideInstallation.d.ts +12 -0
  17. package/cjs/guideInstallation.js +60 -0
  18. package/cjs/guideInstaller.d.ts +4 -0
  19. package/cjs/guideInstaller.js +116 -0
  20. package/cjs/guideMount.d.ts +22 -0
  21. package/cjs/guideMount.js +84 -0
  22. package/cjs/guideRecording.d.ts +64 -0
  23. package/cjs/guideRecording.js +176 -0
  24. package/cjs/guideRecordingSession.d.ts +35 -0
  25. package/cjs/guideRecordingSession.js +167 -0
  26. package/cjs/guideSubjectStore.d.ts +32 -0
  27. package/cjs/guideSubjectStore.js +105 -0
  28. package/cjs/guideTypes.d.ts +117 -0
  29. package/cjs/guideTypes.js +15 -0
  30. package/cjs/index.d.ts +6 -0
  31. package/cjs/index.js +25 -11
  32. package/cjs/liveAudioProcessor.d.ts +92 -0
  33. package/cjs/liveAudioProcessor.js +269 -0
  34. package/cjs/liveAudioQueue.d.ts +40 -0
  35. package/cjs/liveAudioQueue.js +130 -0
  36. package/cjs/liveAudioWorklet.d.ts +1 -0
  37. package/cjs/liveAudioWorklet.js +63 -0
  38. package/cjs/liveBrowserDetector.d.ts +16 -0
  39. package/cjs/liveBrowserDetector.js +75 -0
  40. package/cjs/liveBrowserDetectorWorker.d.ts +1 -0
  41. package/cjs/liveBrowserDetectorWorker.js +72 -0
  42. package/cjs/liveControlChannel.d.ts +176 -0
  43. package/cjs/liveControlChannel.js +829 -0
  44. package/cjs/liveDuplexMedia.d.ts +204 -0
  45. package/cjs/liveDuplexMedia.js +740 -0
  46. package/cjs/liveGuideAdmission.d.ts +21 -0
  47. package/cjs/liveGuideAdmission.js +94 -0
  48. package/cjs/liveGuideWidget.d.ts +68 -0
  49. package/cjs/liveGuideWidget.js +451 -0
  50. package/cjs/liveSpeechAssets.d.ts +36 -0
  51. package/cjs/liveSpeechAssets.js +39 -0
  52. package/cjs/liveSpeechCaptureBridge.d.ts +32 -0
  53. package/cjs/liveSpeechCaptureBridge.js +140 -0
  54. package/cjs/liveSpeechDetector.d.ts +62 -0
  55. package/cjs/liveSpeechDetector.js +206 -0
  56. package/cjs/liveSpeechModel.d.ts +46 -0
  57. package/cjs/liveSpeechModel.js +105 -0
  58. package/cjs/liveSpeechResampler.d.ts +22 -0
  59. package/cjs/liveSpeechResampler.js +93 -0
  60. package/cjs/liveSpeechWorker.d.ts +56 -0
  61. package/cjs/liveSpeechWorker.js +143 -0
  62. package/cjs/locales/resources.js +568 -8
  63. package/cjs/media.d.ts +11 -0
  64. package/cjs/media.js +78 -9
  65. package/cjs/messages.js +22 -8
  66. package/cjs/pageAssistancePreference.d.ts +15 -3
  67. package/cjs/pageAssistancePreference.js +46 -7
  68. package/cjs/preview.d.ts +4 -1
  69. package/cjs/preview.js +42 -1
  70. package/cjs/recording.d.ts +12 -0
  71. package/cjs/recording.js +150 -0
  72. package/cjs/standalone.d.ts +6 -0
  73. package/cjs/standalone.js +12 -0
  74. package/cjs/types.d.ts +31 -5
  75. package/cjs/types.js +14 -0
  76. package/cjs/ui.d.ts +128 -4
  77. package/cjs/ui.js +1918 -276
  78. package/cjs/version.d.ts +1 -1
  79. package/cjs/version.js +1 -1
  80. package/cjs/voicePresenceUi.d.ts +52 -4
  81. package/cjs/voicePresenceUi.js +659 -57
  82. package/lib/AiLiveAssist.d.ts +76 -11
  83. package/lib/AiLiveAssist.js +1772 -299
  84. package/lib/client.d.ts +19 -0
  85. package/lib/client.js +51 -0
  86. package/lib/context.d.ts +23 -1
  87. package/lib/context.js +713 -126
  88. package/lib/control.d.ts +2 -0
  89. package/lib/control.js +42 -3
  90. package/lib/ctaOffer.d.ts +11 -0
  91. package/lib/ctaOffer.js +179 -0
  92. package/lib/dialogFocusScope.js +1 -1
  93. package/lib/guideAdmission.d.ts +46 -0
  94. package/lib/guideAdmission.js +392 -0
  95. package/lib/guideHost.d.ts +47 -0
  96. package/lib/guideHost.js +42 -0
  97. package/lib/guideInstallation.d.ts +12 -0
  98. package/lib/guideInstallation.js +56 -0
  99. package/lib/guideInstaller.d.ts +4 -0
  100. package/lib/guideInstaller.js +113 -0
  101. package/lib/guideMount.d.ts +22 -0
  102. package/lib/guideMount.js +77 -0
  103. package/lib/guideRecording.d.ts +64 -0
  104. package/lib/guideRecording.js +172 -0
  105. package/lib/guideRecordingSession.d.ts +35 -0
  106. package/lib/guideRecordingSession.js +163 -0
  107. package/lib/guideSubjectStore.d.ts +32 -0
  108. package/lib/guideSubjectStore.js +101 -0
  109. package/lib/guideTypes.d.ts +117 -0
  110. package/lib/guideTypes.js +11 -0
  111. package/lib/index.d.ts +6 -0
  112. package/lib/index.js +21 -10
  113. package/lib/liveAudioProcessor.d.ts +92 -0
  114. package/lib/liveAudioProcessor.js +265 -0
  115. package/lib/liveAudioQueue.d.ts +40 -0
  116. package/lib/liveAudioQueue.js +126 -0
  117. package/lib/liveAudioWorklet.d.ts +1 -0
  118. package/lib/liveAudioWorklet.js +61 -0
  119. package/lib/liveBrowserDetector.d.ts +16 -0
  120. package/lib/liveBrowserDetector.js +71 -0
  121. package/lib/liveBrowserDetectorWorker.d.ts +1 -0
  122. package/lib/liveBrowserDetectorWorker.js +70 -0
  123. package/lib/liveControlChannel.d.ts +176 -0
  124. package/lib/liveControlChannel.js +825 -0
  125. package/lib/liveDuplexMedia.d.ts +204 -0
  126. package/lib/liveDuplexMedia.js +736 -0
  127. package/lib/liveGuideAdmission.d.ts +21 -0
  128. package/lib/liveGuideAdmission.js +90 -0
  129. package/lib/liveGuideWidget.d.ts +68 -0
  130. package/lib/liveGuideWidget.js +447 -0
  131. package/lib/liveSpeechAssets.d.ts +36 -0
  132. package/lib/liveSpeechAssets.js +35 -0
  133. package/lib/liveSpeechCaptureBridge.d.ts +32 -0
  134. package/lib/liveSpeechCaptureBridge.js +136 -0
  135. package/lib/liveSpeechDetector.d.ts +62 -0
  136. package/lib/liveSpeechDetector.js +202 -0
  137. package/lib/liveSpeechModel.d.ts +46 -0
  138. package/lib/liveSpeechModel.js +101 -0
  139. package/lib/liveSpeechResampler.d.ts +22 -0
  140. package/lib/liveSpeechResampler.js +89 -0
  141. package/lib/liveSpeechWorker.d.ts +56 -0
  142. package/lib/liveSpeechWorker.js +137 -0
  143. package/lib/locales/resources.js +568 -8
  144. package/lib/media.d.ts +11 -0
  145. package/lib/media.js +77 -8
  146. package/lib/messages.js +22 -8
  147. package/lib/pageAssistancePreference.d.ts +15 -3
  148. package/lib/pageAssistancePreference.js +46 -7
  149. package/lib/preview.d.ts +4 -1
  150. package/lib/preview.js +42 -1
  151. package/lib/recording.d.ts +12 -0
  152. package/lib/recording.js +146 -0
  153. package/lib/standalone.d.ts +6 -0
  154. package/lib/standalone.js +6 -0
  155. package/lib/types.d.ts +31 -5
  156. package/lib/types.js +14 -0
  157. package/lib/ui.d.ts +128 -4
  158. package/lib/ui.js +1919 -277
  159. package/lib/version.d.ts +1 -1
  160. package/lib/version.js +1 -1
  161. package/lib/voicePresenceUi.d.ts +52 -4
  162. package/lib/voicePresenceUi.js +659 -57
  163. package/package.json +16 -1
@@ -1,5 +1,6 @@
1
1
  import { AudioWaveform, RefreshCw, ShieldCheck, UserRound, X, createElement as createLucideElement, } from "lucide";
2
2
  import { DialogFocusScope } from "./dialogFocusScope.js";
3
+ import { CtaOfferCard, CTA_OFFER_STYLES, parseCtaOffer } from "./ctaOffer.js";
3
4
  import { VoicePresenceStateMachine } from "./experienceState.js";
4
5
  import { resolveWidgetMessages, widgetLocaleAttributes, } from "./locales/index.js";
5
6
  import { LauncherPlacementController } from "./placement.js";
@@ -26,6 +27,18 @@ const confirmationPresentation = (value, fallbackTitle, fallbackApprove) => {
26
27
  const INTRO_WAKE_MS = 620;
27
28
  const MAX_LIVE_ANNOUNCEMENTS = 6;
28
29
  const MAX_VISIBLE_SUBTITLES = 3;
30
+ const REMOTE_AUDIO_EVIDENCE_SAMPLE_MS = 50;
31
+ const REMOTE_AUDIO_EVIDENCE_RECHECK_MS = 250;
32
+ const REMOTE_AUDIO_EVIDENCE_IDLE_RECHECK_MS = 1000;
33
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_WINDOW = 3;
34
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_HITS = 2;
35
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_RMS = 0.006;
36
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_PEAK = 0.025;
37
+ const REMOTE_AUDIO_EVIDENCE_SUSTAIN_RMS = 0.0025;
38
+ const REMOTE_AUDIO_EVIDENCE_SUSTAIN_PEAK = 0.012;
39
+ const REMOTE_AUDIO_EVIDENCE_RELEASE_MS = 650;
40
+ const REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS = 5000;
41
+ const REMOTE_AUDIO_EVIDENCE_EXPECTATION_MS = 15000;
29
42
  const styles = `
30
43
  :host {
31
44
  all: initial;
@@ -1033,6 +1046,8 @@ export class VoicePresenceView {
1033
1046
  constructor(config, overrides, callbacks, tabId, onFallback = () => undefined, visualTestMode = false, options = {}) {
1034
1047
  this.callbacks = callbacks;
1035
1048
  this.onFallback = onFallback;
1049
+ this.ctaCard = null;
1050
+ this.ctaSlot = null;
1036
1051
  this.captionTimers = new Map();
1037
1052
  this.captionResizeObserver = null;
1038
1053
  this.captionLayoutFrame = null;
@@ -1054,9 +1069,26 @@ export class VoicePresenceView {
1054
1069
  this.statusTimer = null;
1055
1070
  this.attributionTimer = null;
1056
1071
  this.audioContext = null;
1072
+ this.audioContextStateListener = null;
1057
1073
  this.playbackResumePending = false;
1058
- this.outputSource = null;
1074
+ this.outputSources = [];
1075
+ this.outputAnalysisStreams = [];
1076
+ this.outputAnalysedTracks = new Set();
1059
1077
  this.outputAnalyser = null;
1078
+ this.outputSilentSink = null;
1079
+ this.outputEvidenceFloatBuffer = null;
1080
+ this.outputEvidenceByteBuffer = null;
1081
+ this.outputEvidenceTimer = null;
1082
+ this.outputEvidenceGeneration = 0;
1083
+ this.outputEvidenceAttackWindow = 0;
1084
+ this.outputEvidenceQuietSince = null;
1085
+ this.outputEvidenceAudible = false;
1086
+ this.outputEvidenceCandidateUntil = 0;
1087
+ this.outputEvidenceLastRms = 0;
1088
+ this.playbackGeneration = 0;
1089
+ this.playbackStateBindings = [];
1090
+ this.boundRemoteAudioStreams = new WeakSet();
1091
+ this.boundRemoteAudioTracks = new WeakSet();
1060
1092
  this.inputSource = null;
1061
1093
  this.inputAnalyser = null;
1062
1094
  this.levelFrame = null;
@@ -1084,6 +1116,17 @@ export class VoicePresenceView {
1084
1116
  };
1085
1117
  this.onVisibilityChange = () => {
1086
1118
  this.syncMotionPolicy();
1119
+ if (document.hidden) {
1120
+ this.stopOutputEvidenceSampling();
1121
+ const wasAudible = this.outputEvidenceAudible;
1122
+ this.resetOutputEvidenceState();
1123
+ if (wasAudible) {
1124
+ this.emitPlaybackState("waiting");
1125
+ this.syncPresenceFromPlayback();
1126
+ }
1127
+ return;
1128
+ }
1129
+ this.resumeOutputAudioContext();
1087
1130
  };
1088
1131
  this.onReducedMotionChange = () => {
1089
1132
  this.syncMotionPolicy();
@@ -1107,7 +1150,7 @@ export class VoicePresenceView {
1107
1150
  this.host.dir = locale.dir;
1108
1151
  this.shadow = this.host.attachShadow({ mode: "closed" });
1109
1152
  const sheet = document.createElement("style");
1110
- sheet.textContent = styles;
1153
+ sheet.textContent = styles + CTA_OFFER_STYLES;
1111
1154
  this.shadow.append(sheet, this.build());
1112
1155
  document.documentElement.append(this.host);
1113
1156
  this.orb = this.require('[data-role="orb"]');
@@ -1258,7 +1301,34 @@ export class VoicePresenceView {
1258
1301
  return true;
1259
1302
  }
1260
1303
  setRemoteStream(stream) {
1304
+ if (this.destroyed)
1305
+ return;
1261
1306
  const previous = this.audio.srcObject;
1307
+ const streamChanged = previous !== stream;
1308
+ const analysisChanged = !this.outputAnalyserMatchesStream(stream);
1309
+ if (streamChanged) {
1310
+ this.playbackGeneration += 1;
1311
+ this.playbackResumePending = false;
1312
+ this.stopOutputEvidenceSampling();
1313
+ const wasAudible = this.outputEvidenceAudible;
1314
+ this.resetOutputEvidenceState();
1315
+ this.playbackState = "waiting";
1316
+ if (wasAudible)
1317
+ this.emitPlaybackState("waiting");
1318
+ this.syncPresenceFromPlayback();
1319
+ this.boundRemoteAudioTracks = new WeakSet();
1320
+ }
1321
+ else if (analysisChanged) {
1322
+ const wasAudible = this.outputEvidenceAudible;
1323
+ this.stopOutputEvidenceSampling();
1324
+ this.resetOutputEvidenceState();
1325
+ if (wasAudible)
1326
+ this.emitPlaybackState("waiting");
1327
+ this.syncPresenceFromPlayback();
1328
+ }
1329
+ this.audio.srcObject = stream;
1330
+ if (streamChanged)
1331
+ this.bindPlaybackState();
1262
1332
  if (previous &&
1263
1333
  typeof MediaStream !== "undefined" &&
1264
1334
  previous instanceof MediaStream &&
@@ -1266,11 +1336,20 @@ export class VoicePresenceView {
1266
1336
  for (const track of previous.getTracks())
1267
1337
  track.stop();
1268
1338
  }
1269
- this.audio.srcObject = stream;
1270
- this.connectOutputAnalyser(stream);
1339
+ if (streamChanged || analysisChanged)
1340
+ this.connectOutputAnalyser(stream);
1341
+ this.bindRemoteAudioTrackState(stream);
1342
+ this.resumeOutputAudioContext();
1343
+ this.startOutputEvidenceSampling();
1344
+ const generation = this.playbackGeneration;
1271
1345
  void this.audio.play().catch(() => {
1346
+ if (!this.playbackSourceIsCurrent(generation, stream))
1347
+ return;
1272
1348
  this.playbackState = "blocked";
1349
+ this.stopOutputEvidenceSampling();
1350
+ this.resetOutputEvidenceState();
1273
1351
  this.emitPlaybackState("blocked");
1352
+ this.syncPresenceFromPlayback();
1274
1353
  this.orb.setAttribute("aria-label", this.messages.audioPaused);
1275
1354
  this.showTransientStatus(this.messages.audioPaused, 6000);
1276
1355
  });
@@ -1295,6 +1374,7 @@ export class VoicePresenceView {
1295
1374
  this.safetyCard,
1296
1375
  this.recoveryCard,
1297
1376
  this.orb,
1377
+ ...(this.ctaSlot ? [this.ctaSlot] : []),
1298
1378
  ];
1299
1379
  return candidates
1300
1380
  .filter((element) => element.isConnected && !element.hidden)
@@ -1337,7 +1417,9 @@ export class VoicePresenceView {
1337
1417
  setAssistantState(state) {
1338
1418
  if (!this.active)
1339
1419
  return;
1420
+ const previous = this.serverPresenceState;
1340
1421
  this.serverPresenceState = state;
1422
+ this.updateOutputEvidenceExpectation(previous, state);
1341
1423
  if (state === "thinking" || state === "speaking") {
1342
1424
  this.resumeRemotePlayback();
1343
1425
  }
@@ -1345,17 +1427,20 @@ export class VoicePresenceView {
1345
1427
  this.syncLevelLoop();
1346
1428
  }
1347
1429
  applyPresenceState(state, sequence, sessionId, pageId, fencingToken) {
1348
- this.serverPresenceState = state;
1349
- if (state === "thinking" || state === "speaking") {
1350
- this.resumeRemotePlayback();
1351
- }
1352
- const next = this.effectivePresenceState();
1353
- this.stateMachine.transition(next, {
1430
+ const previous = this.serverPresenceState;
1431
+ const accepted = this.stateMachine.transition(this.effectivePresenceState(state), {
1354
1432
  sessionId,
1355
1433
  serverSequence: sequence,
1356
1434
  ...(pageId ? { pageId } : {}),
1357
1435
  fencingToken,
1358
1436
  });
1437
+ if (!accepted)
1438
+ return;
1439
+ this.serverPresenceState = state;
1440
+ this.updateOutputEvidenceExpectation(previous, state);
1441
+ if (state === "thinking" || state === "speaking") {
1442
+ this.resumeRemotePlayback();
1443
+ }
1359
1444
  if (state === "reconnecting")
1360
1445
  this.showTransientStatus(this.messages.reconnecting, 5000);
1361
1446
  else if (state !== "awaiting_confirmation")
@@ -1409,7 +1494,8 @@ export class VoicePresenceView {
1409
1494
  this.addCaption("assistant", welcomeMessage, true);
1410
1495
  }
1411
1496
  }
1412
- addCaption(role, text, final) {
1497
+ addCaption(role, text, final, _options = {}) {
1498
+ void _options;
1413
1499
  if (!this.voiceConfig.captions.enabled)
1414
1500
  return;
1415
1501
  if (!final) {
@@ -1716,13 +1802,27 @@ export class VoicePresenceView {
1716
1802
  }
1717
1803
  setPushActive(_value) {
1718
1804
  void _value;
1805
+ return true;
1806
+ }
1807
+ setPushPending(_value) {
1808
+ void _value;
1809
+ return false;
1719
1810
  }
1720
1811
  interruptPlayback() {
1812
+ this.playbackGeneration += 1;
1813
+ this.playbackResumePending = false;
1814
+ this.outputEvidenceCandidateUntil = 0;
1815
+ this.stopOutputEvidenceSampling();
1816
+ this.resetOutputEvidenceState();
1817
+ this.serverPresenceState = "ready";
1818
+ this.playbackState = "paused";
1819
+ this.bindPlaybackState();
1721
1820
  this.audio.pause();
1722
1821
  this.stopLevelLoop();
1723
1822
  this.host.style.setProperty("--voice-level", "0");
1724
1823
  if (this.active)
1725
1824
  this.stateMachine.transition("active.ready");
1825
+ this.emitPlaybackState("paused");
1726
1826
  }
1727
1827
  showError(message, retryable = false, sessionActive = this.active) {
1728
1828
  this.hidePageAssistanceRequest(false);
@@ -1732,6 +1832,7 @@ export class VoicePresenceView {
1732
1832
  this.hideSafetyCard();
1733
1833
  const safeMessage = message || this.messages.error;
1734
1834
  if (sessionActive && this.active) {
1835
+ this.interruptPlayback();
1735
1836
  this.stateMachine.transition(retryable ? "recoverable_error" : "terminal_error");
1736
1837
  this.hideStatus();
1737
1838
  this.renderRecoveryCard(safeMessage, retryable);
@@ -1795,6 +1896,7 @@ export class VoicePresenceView {
1795
1896
  this.placement.refresh();
1796
1897
  }
1797
1898
  showEnded(message) {
1899
+ this.clearCtaOffer();
1798
1900
  this.active = false;
1799
1901
  this.hidePageAssistanceRequest(false);
1800
1902
  this.currentConfirmation = null;
@@ -1812,6 +1914,7 @@ export class VoicePresenceView {
1812
1914
  if (message)
1813
1915
  this.showTransientStatus(message, 3000);
1814
1916
  this.stateMachine.transition("launcher");
1917
+ this.orb.hidden = false;
1815
1918
  this.showAttribution();
1816
1919
  this.placement.refresh();
1817
1920
  }
@@ -1915,6 +2018,7 @@ export class VoicePresenceView {
1915
2018
  return true;
1916
2019
  }
1917
2020
  destroy() {
2021
+ this.clearCtaOffer();
1918
2022
  if (this.destroyed)
1919
2023
  return;
1920
2024
  this.destroyed = true;
@@ -1943,6 +2047,23 @@ export class VoicePresenceView {
1943
2047
  this.stopAudio();
1944
2048
  this.host.remove();
1945
2049
  }
2050
+ showCtaOffer(value, options = {}) {
2051
+ const offer = parseCtaOffer(value);
2052
+ if (!offer || this.ctaCard?.offer.offerId === offer.offerId)
2053
+ return;
2054
+ this.clearCtaOffer();
2055
+ this.ctaSlot = document.createElement("div");
2056
+ this.ctaSlot.className = "cta-action-slot";
2057
+ this.ctaCard = new CtaOfferCard(offer, this.messages, (result) => this.callbacks.onCtaResult?.(result) ?? false, () => this.orb.focus({ preventScroll: true }), options.announce !== false);
2058
+ this.ctaSlot.append(this.ctaCard.element);
2059
+ this.require(".orb-wrap").append(this.ctaSlot);
2060
+ }
2061
+ clearCtaOffer() {
2062
+ this.ctaCard?.destroy();
2063
+ this.ctaCard = null;
2064
+ this.ctaSlot?.remove();
2065
+ this.ctaSlot = null;
2066
+ }
1946
2067
  build() {
1947
2068
  const fragment = document.createDocumentFragment();
1948
2069
  const presenceField = document.createElement("div");
@@ -2258,29 +2379,73 @@ export class VoicePresenceView {
2258
2379
  });
2259
2380
  }
2260
2381
  bindPlaybackState() {
2261
- this.audio.addEventListener("playing", () => {
2382
+ this.unbindPlaybackState();
2383
+ const generation = this.playbackGeneration;
2384
+ const stream = this.audio.srcObject;
2385
+ const current = () => this.playbackSourceIsCurrent(generation, stream);
2386
+ const bind = (type, handler) => {
2387
+ const listener = () => {
2388
+ if (!current())
2389
+ return;
2390
+ handler();
2391
+ };
2392
+ this.playbackStateBindings.push({ type, listener });
2393
+ this.audio.addEventListener(type, listener);
2394
+ };
2395
+ bind("playing", () => {
2262
2396
  this.playbackState = "playing";
2263
- if (this.active)
2264
- this.orb.setAttribute("aria-label", this.messages.end);
2265
- this.emitPlaybackState("playing");
2266
- this.syncPresenceFromPlayback();
2267
- });
2268
- this.audio.addEventListener("waiting", () => {
2269
- this.playbackState = "waiting";
2397
+ this.orb.setAttribute("aria-label", this.messages.end);
2398
+ // A successful media-element transition is the browser's fresh proof
2399
+ // that playback may proceed after a user gesture. Report readiness
2400
+ // without claiming audibility; measured audio evidence will promote the
2401
+ // state to `playing` only once samples prove that sound is present.
2270
2402
  this.emitPlaybackState("waiting");
2403
+ this.resumeOutputAudioContext();
2404
+ this.startOutputEvidenceSampling();
2271
2405
  this.syncPresenceFromPlayback();
2272
2406
  });
2273
- this.audio.addEventListener("pause", () => {
2274
- this.playbackState = "paused";
2275
- this.emitPlaybackState("paused");
2276
- this.syncPresenceFromPlayback();
2277
- });
2278
- this.audio.addEventListener("ended", () => {
2279
- this.playbackState = "ended";
2280
- this.emitPlaybackState("ended");
2407
+ bind("waiting", () => this.applyPlaybackInactiveState("waiting"));
2408
+ bind("pause", () => this.applyPlaybackInactiveState("paused"));
2409
+ bind("ended", () => this.applyPlaybackInactiveState("ended"));
2410
+ bind("volumechange", () => {
2411
+ if (this.remoteAudioTrackIsPlayable()) {
2412
+ this.resumeOutputAudioContext();
2413
+ this.startOutputEvidenceSampling();
2414
+ return;
2415
+ }
2416
+ const wasAudible = this.outputEvidenceAudible;
2417
+ this.stopOutputEvidenceSampling();
2418
+ this.resetOutputEvidenceState();
2419
+ if (wasAudible)
2420
+ this.emitPlaybackState("waiting");
2281
2421
  this.syncPresenceFromPlayback();
2282
2422
  });
2283
2423
  }
2424
+ unbindPlaybackState() {
2425
+ for (const binding of this.playbackStateBindings) {
2426
+ this.audio.removeEventListener(binding.type, binding.listener);
2427
+ }
2428
+ this.playbackStateBindings = [];
2429
+ }
2430
+ playbackSourceIsCurrent(generation, stream) {
2431
+ return Boolean(!this.destroyed &&
2432
+ this.active &&
2433
+ stream &&
2434
+ generation === this.playbackGeneration &&
2435
+ this.audio.srcObject === stream);
2436
+ }
2437
+ applyPlaybackInactiveState(state) {
2438
+ if (this.playbackState === state &&
2439
+ !this.outputEvidenceAudible &&
2440
+ this.outputEvidenceTimer === null) {
2441
+ return;
2442
+ }
2443
+ this.playbackState = state;
2444
+ this.stopOutputEvidenceSampling();
2445
+ this.resetOutputEvidenceState();
2446
+ this.emitPlaybackState(state);
2447
+ this.syncPresenceFromPlayback();
2448
+ }
2284
2449
  resumeRemotePlayback() {
2285
2450
  if (!this.active ||
2286
2451
  !this.audio.paused ||
@@ -2288,21 +2453,31 @@ export class VoicePresenceView {
2288
2453
  this.playbackResumePending) {
2289
2454
  return;
2290
2455
  }
2456
+ const stream = this.audio.srcObject;
2457
+ const generation = this.playbackGeneration;
2291
2458
  this.playbackResumePending = true;
2292
2459
  void this.audio
2293
2460
  .play()
2294
2461
  .catch(() => {
2462
+ if (!this.playbackSourceIsCurrent(generation, stream))
2463
+ return;
2295
2464
  this.playbackState = "blocked";
2465
+ this.stopOutputEvidenceSampling();
2466
+ this.resetOutputEvidenceState();
2296
2467
  this.emitPlaybackState("blocked");
2468
+ this.syncPresenceFromPlayback();
2297
2469
  this.orb.setAttribute("aria-label", this.messages.audioPaused);
2298
2470
  this.showTransientStatus(this.messages.audioPaused, 6000);
2299
2471
  })
2300
2472
  .finally(() => {
2301
- this.playbackResumePending = false;
2473
+ if (generation === this.playbackGeneration &&
2474
+ this.audio.srcObject === stream) {
2475
+ this.playbackResumePending = false;
2476
+ }
2302
2477
  });
2303
2478
  }
2304
- effectivePresenceState() {
2305
- const state = this.serverPresenceState;
2479
+ effectivePresenceState(proposedState = this.serverPresenceState) {
2480
+ const state = proposedState;
2306
2481
  if (state === "ending")
2307
2482
  return "ending";
2308
2483
  if (state === "acting" ||
@@ -2311,7 +2486,7 @@ export class VoicePresenceView {
2311
2486
  return `active.${state}`;
2312
2487
  }
2313
2488
  if (state === "speaking") {
2314
- if (this.playbackState === "playing") {
2489
+ if (this.playbackState === "playing" && this.remoteAudioIsAudible()) {
2315
2490
  return "active.speaking";
2316
2491
  }
2317
2492
  return this.playbackState === "paused" || this.playbackState === "ended"
@@ -2327,18 +2502,335 @@ export class VoicePresenceView {
2327
2502
  this.syncLevelLoop();
2328
2503
  }
2329
2504
  syncLevelLoop() {
2330
- if (this.stateMachine.state === "active.listening" ||
2331
- this.stateMachine.state === "active.speaking") {
2505
+ if (this.stateMachine.state === "active.listening") {
2332
2506
  this.startLevelLoop();
2507
+ return;
2333
2508
  }
2334
- else {
2335
- this.stopLevelLoop();
2509
+ this.stopLevelLoop();
2510
+ if (this.stateMachine.state === "active.speaking") {
2511
+ this.startOutputEvidenceSampling();
2512
+ this.syncOutputLevel(this.outputEvidenceLastRms);
2513
+ }
2514
+ }
2515
+ remoteAudioIsAudible() {
2516
+ return this.outputEvidenceAudible && this.remoteAudioTrackIsPlayable();
2517
+ }
2518
+ remoteAudioTrackIsPlayable() {
2519
+ const stream = this.audio.srcObject;
2520
+ const currentTracks = typeof stream?.getAudioTracks === "function"
2521
+ ? stream.getAudioTracks()
2522
+ : [];
2523
+ if (!stream || this.outputAnalysedTracks.size === 0) {
2524
+ return false;
2525
+ }
2526
+ return Boolean(!this.audio.paused &&
2527
+ !this.audio.muted &&
2528
+ this.audio.volume > 0 &&
2529
+ [...this.outputAnalysedTracks].some((track) => currentTracks.some((candidate) => candidate === track) &&
2530
+ track.readyState === "live" &&
2531
+ track.enabled !== false &&
2532
+ track.muted !== true));
2533
+ }
2534
+ bindRemoteAudioTrackState(stream) {
2535
+ if (typeof stream.getAudioTracks !== "function")
2536
+ return;
2537
+ if (!this.boundRemoteAudioStreams.has(stream) &&
2538
+ typeof stream.addEventListener === "function") {
2539
+ this.boundRemoteAudioStreams.add(stream);
2540
+ const refreshTrackSet = () => {
2541
+ if (this.destroyed || !this.active || this.audio.srcObject !== stream) {
2542
+ return;
2543
+ }
2544
+ const wasAudible = this.outputEvidenceAudible;
2545
+ this.stopOutputEvidenceSampling();
2546
+ this.resetOutputEvidenceState();
2547
+ this.connectOutputAnalyser(stream);
2548
+ this.bindRemoteAudioTrackState(stream);
2549
+ if (wasAudible)
2550
+ this.emitPlaybackState("waiting");
2551
+ this.syncPresenceFromPlayback();
2552
+ this.startOutputEvidenceSampling();
2553
+ };
2554
+ stream.addEventListener("addtrack", refreshTrackSet);
2555
+ stream.addEventListener("removetrack", refreshTrackSet);
2556
+ }
2557
+ const isCurrent = (track) => !this.destroyed &&
2558
+ this.active &&
2559
+ this.audio.srcObject === stream &&
2560
+ stream.getAudioTracks().some((candidate) => candidate === track);
2561
+ for (const track of stream.getAudioTracks()) {
2562
+ if (this.boundRemoteAudioTracks.has(track) ||
2563
+ typeof track.addEventListener !== "function") {
2564
+ continue;
2565
+ }
2566
+ this.boundRemoteAudioTracks.add(track);
2567
+ track.addEventListener("mute", () => {
2568
+ if (!isCurrent(track))
2569
+ return;
2570
+ this.stopOutputEvidenceSampling();
2571
+ this.resetOutputEvidenceState();
2572
+ this.emitPlaybackState("waiting");
2573
+ this.syncPresenceFromPlayback();
2574
+ });
2575
+ track.addEventListener("unmute", () => {
2576
+ if (!isCurrent(track) || this.playbackState !== "playing")
2577
+ return;
2578
+ this.resetOutputEvidenceAttack();
2579
+ this.resumeOutputAudioContext();
2580
+ this.startOutputEvidenceSampling();
2581
+ });
2582
+ track.addEventListener("ended", () => {
2583
+ if (!isCurrent(track))
2584
+ return;
2585
+ this.stopOutputEvidenceSampling();
2586
+ this.resetOutputEvidenceState();
2587
+ this.connectOutputAnalyser(stream);
2588
+ if (stream
2589
+ .getAudioTracks()
2590
+ .some((candidate) => candidate.readyState === "live")) {
2591
+ this.playbackState = "waiting";
2592
+ this.emitPlaybackState("waiting");
2593
+ this.startOutputEvidenceSampling();
2594
+ }
2595
+ else {
2596
+ this.playbackState = "ended";
2597
+ this.emitPlaybackState("ended");
2598
+ }
2599
+ this.syncPresenceFromPlayback();
2600
+ });
2601
+ }
2602
+ }
2603
+ updateOutputEvidenceExpectation(previous, next) {
2604
+ const now = this.outputEvidenceNow();
2605
+ if (next === "thinking" || next === "speaking") {
2606
+ this.outputEvidenceCandidateUntil = Math.max(this.outputEvidenceCandidateUntil, now + REMOTE_AUDIO_EVIDENCE_EXPECTATION_MS);
2607
+ this.startOutputEvidenceSampling();
2608
+ return;
2336
2609
  }
2610
+ if (next === "ready" &&
2611
+ (previous === "thinking" ||
2612
+ previous === "speaking" ||
2613
+ this.outputEvidenceAudible)) {
2614
+ this.outputEvidenceCandidateUntil =
2615
+ now + REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS;
2616
+ this.startOutputEvidenceSampling();
2617
+ return;
2618
+ }
2619
+ this.outputEvidenceCandidateUntil = 0;
2620
+ this.stopOutputEvidenceSampling();
2621
+ this.resetOutputEvidenceState();
2622
+ }
2623
+ outputEvidenceNow() {
2624
+ const value = globalThis.performance?.now?.();
2625
+ return typeof value === "number" && Number.isFinite(value)
2626
+ ? value
2627
+ : Date.now();
2628
+ }
2629
+ outputEvidenceCandidateIsCurrent(now) {
2630
+ if (!this.outputEvidenceVisualStateIsEligible())
2631
+ return false;
2632
+ return Boolean(this.outputEvidenceAudible ||
2633
+ this.serverPresenceState === "thinking" ||
2634
+ this.serverPresenceState === "speaking" ||
2635
+ (this.outputEvidenceCandidateUntil > 0 &&
2636
+ now < this.outputEvidenceCandidateUntil));
2637
+ }
2638
+ outputEvidenceVisualStateIsEligible() {
2639
+ return (this.stateMachine.state === "active.thinking" ||
2640
+ this.stateMachine.state === "active.speaking" ||
2641
+ this.stateMachine.state === "active.ready");
2642
+ }
2643
+ startOutputEvidenceSampling() {
2644
+ const now = this.outputEvidenceNow();
2645
+ if (this.outputEvidenceTimer !== null ||
2646
+ this.destroyed ||
2647
+ !this.active ||
2648
+ this.playbackState !== "playing" ||
2649
+ !this.outputAnalyser ||
2650
+ (!this.outputEvidenceFloatBuffer && !this.outputEvidenceByteBuffer) ||
2651
+ this.audioContext?.state !== "running" ||
2652
+ !this.outputEvidenceCandidateIsCurrent(now)) {
2653
+ return;
2654
+ }
2655
+ const generation = this.outputEvidenceGeneration;
2656
+ const inBurstWindow = this.outputEvidenceAudible ||
2657
+ (this.outputEvidenceCandidateUntil > 0 &&
2658
+ now < this.outputEvidenceCandidateUntil);
2659
+ const delay = inBurstWindow
2660
+ ? this.remoteAudioTrackIsPlayable()
2661
+ ? REMOTE_AUDIO_EVIDENCE_SAMPLE_MS
2662
+ : REMOTE_AUDIO_EVIDENCE_RECHECK_MS
2663
+ : REMOTE_AUDIO_EVIDENCE_IDLE_RECHECK_MS;
2664
+ this.outputEvidenceTimer = setTimeout(() => {
2665
+ this.outputEvidenceTimer = null;
2666
+ if (generation !== this.outputEvidenceGeneration)
2667
+ return;
2668
+ this.sampleOutputEvidence(generation);
2669
+ }, delay);
2670
+ }
2671
+ sampleOutputEvidence(generation) {
2672
+ if (generation !== this.outputEvidenceGeneration ||
2673
+ this.destroyed ||
2674
+ !this.active ||
2675
+ this.playbackState !== "playing") {
2676
+ return;
2677
+ }
2678
+ if (!this.remoteAudioTrackIsPlayable()) {
2679
+ const wasAudible = this.outputEvidenceAudible;
2680
+ this.stopOutputEvidenceSampling();
2681
+ this.resetOutputEvidenceState();
2682
+ if (wasAudible)
2683
+ this.emitPlaybackState("waiting");
2684
+ this.syncPresenceFromPlayback();
2685
+ this.startOutputEvidenceSampling();
2686
+ return;
2687
+ }
2688
+ const now = this.outputEvidenceNow();
2689
+ if (!this.outputEvidenceCandidateIsCurrent(now)) {
2690
+ this.stopOutputEvidenceSampling();
2691
+ this.resetOutputEvidenceState();
2692
+ return;
2693
+ }
2694
+ const sample = this.readOutputEvidence();
2695
+ if (!sample) {
2696
+ const wasAudible = this.outputEvidenceAudible;
2697
+ this.stopOutputEvidenceSampling();
2698
+ this.resetOutputEvidenceState();
2699
+ if (wasAudible) {
2700
+ this.emitPlaybackState("waiting");
2701
+ this.syncPresenceFromPlayback();
2702
+ }
2703
+ this.startOutputEvidenceSampling();
2704
+ return;
2705
+ }
2706
+ this.outputEvidenceLastRms = sample.rms;
2707
+ const attack = sample.rms >= REMOTE_AUDIO_EVIDENCE_ATTACK_RMS ||
2708
+ sample.peak >= REMOTE_AUDIO_EVIDENCE_ATTACK_PEAK;
2709
+ const sustain = sample.rms >= REMOTE_AUDIO_EVIDENCE_SUSTAIN_RMS ||
2710
+ sample.peak >= REMOTE_AUDIO_EVIDENCE_SUSTAIN_PEAK;
2711
+ if (!this.outputEvidenceAudible) {
2712
+ const mask = (1 << REMOTE_AUDIO_EVIDENCE_ATTACK_WINDOW) - 1;
2713
+ this.outputEvidenceAttackWindow =
2714
+ ((this.outputEvidenceAttackWindow << 1) | Number(attack)) & mask;
2715
+ let hits = 0;
2716
+ for (let candidates = this.outputEvidenceAttackWindow; candidates > 0; candidates >>= 1) {
2717
+ hits += candidates & 1;
2718
+ }
2719
+ if (hits >= REMOTE_AUDIO_EVIDENCE_ATTACK_HITS) {
2720
+ this.outputEvidenceAudible = true;
2721
+ this.outputEvidenceQuietSince = null;
2722
+ this.outputEvidenceAttackWindow = 0;
2723
+ this.outputEvidenceCandidateUntil = Math.max(this.outputEvidenceCandidateUntil, now + REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS);
2724
+ this.emitPlaybackState("playing");
2725
+ this.syncPresenceFromPlayback();
2726
+ }
2727
+ }
2728
+ else if (sustain) {
2729
+ this.outputEvidenceQuietSince = null;
2730
+ this.outputEvidenceCandidateUntil = Math.max(this.outputEvidenceCandidateUntil, now + REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS);
2731
+ }
2732
+ else if (this.outputEvidenceQuietSince === null) {
2733
+ this.outputEvidenceQuietSince = now;
2734
+ }
2735
+ else if (now - this.outputEvidenceQuietSince >=
2736
+ REMOTE_AUDIO_EVIDENCE_RELEASE_MS) {
2737
+ this.outputEvidenceAudible = false;
2738
+ this.resetOutputEvidenceAttack();
2739
+ this.emitPlaybackState("waiting");
2740
+ this.syncPresenceFromPlayback();
2741
+ }
2742
+ this.syncOutputLevel(sample.rms);
2743
+ this.startOutputEvidenceSampling();
2744
+ }
2745
+ readOutputEvidence() {
2746
+ const analyser = this.outputAnalyser;
2747
+ const context = this.audioContext;
2748
+ if (!analyser || !context || context.state !== "running")
2749
+ return null;
2750
+ let length = 0;
2751
+ let valueAt = null;
2752
+ let floatRead = false;
2753
+ if (this.outputEvidenceFloatBuffer &&
2754
+ typeof analyser.getFloatTimeDomainData === "function") {
2755
+ try {
2756
+ analyser.getFloatTimeDomainData(this.outputEvidenceFloatBuffer);
2757
+ length = this.outputEvidenceFloatBuffer.length;
2758
+ valueAt = (index) => this.outputEvidenceFloatBuffer?.[index] ?? 0;
2759
+ floatRead = true;
2760
+ }
2761
+ catch {
2762
+ floatRead = false;
2763
+ }
2764
+ }
2765
+ if (!floatRead) {
2766
+ if (!this.outputEvidenceByteBuffer)
2767
+ return null;
2768
+ try {
2769
+ analyser.getByteTimeDomainData(this.outputEvidenceByteBuffer);
2770
+ length = this.outputEvidenceByteBuffer.length;
2771
+ valueAt = (index) => ((this.outputEvidenceByteBuffer?.[index] ?? 128) - 128) / 128;
2772
+ }
2773
+ catch {
2774
+ return null;
2775
+ }
2776
+ }
2777
+ if (length === 0 || !valueAt)
2778
+ return null;
2779
+ let mean = 0;
2780
+ for (let index = 0; index < length; index += 1) {
2781
+ const value = valueAt(index);
2782
+ if (!Number.isFinite(value))
2783
+ return null;
2784
+ mean += value;
2785
+ }
2786
+ mean /= length;
2787
+ let sum = 0;
2788
+ let peak = 0;
2789
+ for (let index = 0; index < length; index += 1) {
2790
+ const centered = valueAt(index) - mean;
2791
+ if (!Number.isFinite(centered))
2792
+ return null;
2793
+ sum += centered * centered;
2794
+ peak = Math.max(peak, Math.abs(centered));
2795
+ }
2796
+ const volume = Math.min(1, Math.max(0, this.audio.volume));
2797
+ const rms = Math.sqrt(sum / length) * volume;
2798
+ peak *= volume;
2799
+ return Number.isFinite(rms) && Number.isFinite(peak) ? { rms, peak } : null;
2800
+ }
2801
+ stopOutputEvidenceSampling() {
2802
+ if (this.outputEvidenceTimer !== null) {
2803
+ clearTimeout(this.outputEvidenceTimer);
2804
+ this.outputEvidenceTimer = null;
2805
+ }
2806
+ this.outputEvidenceGeneration += 1;
2807
+ }
2808
+ resetOutputEvidenceAttack() {
2809
+ this.outputEvidenceAttackWindow = 0;
2810
+ this.outputEvidenceQuietSince = null;
2811
+ }
2812
+ resetOutputEvidenceState() {
2813
+ this.outputEvidenceAudible = false;
2814
+ this.outputEvidenceLastRms = 0;
2815
+ this.resetOutputEvidenceAttack();
2816
+ this.syncOutputLevel(0);
2817
+ }
2818
+ syncOutputLevel(rms) {
2819
+ if (!this.outputEvidenceAudible ||
2820
+ this.stateMachine.state !== "active.speaking" ||
2821
+ !this.motionEnabled() ||
2822
+ document.hidden) {
2823
+ if (this.stateMachine.state !== "active.listening") {
2824
+ this.host.style.setProperty("--voice-level", "0");
2825
+ }
2826
+ return;
2827
+ }
2828
+ this.host.style.setProperty("--voice-level", Math.min(1, Math.max(0, rms) * 5.5).toFixed(3));
2337
2829
  }
2338
2830
  emitPlaybackState(state) {
2339
2831
  this.callbacks.onPlaybackState({
2340
2832
  state,
2341
- audible: state === "playing" && !this.audio.muted && this.audio.volume > 0,
2833
+ audible: state === "playing" && this.remoteAudioIsAudible(),
2342
2834
  utteranceId: null,
2343
2835
  sampledAt: new Date().toISOString(),
2344
2836
  });
@@ -2550,7 +3042,7 @@ export class VoicePresenceView {
2550
3042
  close.setAttribute("aria-label", this.messages.close);
2551
3043
  close.append(icon(X, "close-symbol"));
2552
3044
  close.addEventListener("click", () => {
2553
- this.hideRecoveryCard();
3045
+ this.dismissRecoveryCard();
2554
3046
  });
2555
3047
  const heading = document.createElement("div");
2556
3048
  heading.className = "recovery-head";
@@ -2604,10 +3096,27 @@ export class VoicePresenceView {
2604
3096
  initialFocus: () => primary ?? close,
2605
3097
  fallbackFocus: () => (this.orb.hidden ? null : this.orb),
2606
3098
  onEscape: () => {
2607
- this.hideRecoveryCard();
3099
+ this.dismissRecoveryCard();
2608
3100
  },
2609
3101
  });
2610
3102
  }
3103
+ dismissRecoveryCard() {
3104
+ const restoreLauncher = !this.active &&
3105
+ !this.activeElsewhere &&
3106
+ (this.stateMachine.state === "unavailable" ||
3107
+ this.stateMachine.state === "recoverable_error" ||
3108
+ this.stateMachine.state === "terminal_error");
3109
+ this.hideRecoveryCard();
3110
+ if (!restoreLauncher)
3111
+ return;
3112
+ this.orb.disabled = false;
3113
+ this.orb.dataset.active = "false";
3114
+ this.orb.hidden = false;
3115
+ this.orb.setAttribute("aria-label", this.launcherLabel());
3116
+ this.stateMachine.reset();
3117
+ this.stateMachine.transition("launcher");
3118
+ this.placement.refresh();
3119
+ }
2611
3120
  hideRecoveryCard(restore = true) {
2612
3121
  this.recoveryCard.hidden = true;
2613
3122
  this.recoveryCard.replaceChildren();
@@ -2782,7 +3291,7 @@ export class VoicePresenceView {
2782
3291
  }
2783
3292
  ensureAudioContext() {
2784
3293
  if (this.audioContext) {
2785
- void this.audioContext.resume().catch(() => undefined);
3294
+ this.resumeOutputAudioContext();
2786
3295
  return;
2787
3296
  }
2788
3297
  const AudioContextConstructor = window.AudioContext ||
@@ -2794,32 +3303,121 @@ export class VoicePresenceView {
2794
3303
  this.audioContext = new AudioContextConstructor({
2795
3304
  latencyHint: "interactive",
2796
3305
  });
2797
- void this.audioContext.resume().catch(() => undefined);
3306
+ const context = this.audioContext;
3307
+ this.audioContextStateListener = () => {
3308
+ if (this.destroyed || this.audioContext !== context)
3309
+ return;
3310
+ if (context.state === "running") {
3311
+ this.startOutputEvidenceSampling();
3312
+ return;
3313
+ }
3314
+ const wasAudible = this.outputEvidenceAudible;
3315
+ this.stopOutputEvidenceSampling();
3316
+ this.resetOutputEvidenceState();
3317
+ if (wasAudible) {
3318
+ this.emitPlaybackState("waiting");
3319
+ this.syncPresenceFromPlayback();
3320
+ }
3321
+ };
3322
+ context.addEventListener?.("statechange", this.audioContextStateListener);
3323
+ this.resumeOutputAudioContext();
2798
3324
  }
2799
3325
  catch {
2800
3326
  this.audioContext = null;
3327
+ this.audioContextStateListener = null;
3328
+ }
3329
+ }
3330
+ resumeOutputAudioContext() {
3331
+ const context = this.audioContext;
3332
+ if (!context || context.state === "closed" || this.destroyed)
3333
+ return;
3334
+ if (context.state === "running") {
3335
+ this.startOutputEvidenceSampling();
3336
+ return;
2801
3337
  }
3338
+ const generation = this.playbackGeneration;
3339
+ const stream = this.audio.srcObject;
3340
+ void context
3341
+ .resume()
3342
+ .then(() => {
3343
+ if (this.audioContext === context &&
3344
+ (!stream || this.playbackSourceIsCurrent(generation, stream))) {
3345
+ this.startOutputEvidenceSampling();
3346
+ }
3347
+ })
3348
+ .catch(() => undefined);
2802
3349
  }
2803
3350
  connectOutputAnalyser(stream) {
2804
3351
  this.ensureAudioContext();
2805
3352
  const context = this.audioContext;
2806
3353
  if (!context)
2807
3354
  return;
3355
+ this.disconnectOutputAnalyser();
2808
3356
  try {
2809
- this.outputSource?.disconnect();
2810
- this.outputAnalyser?.disconnect();
2811
3357
  this.outputAnalyser = context.createAnalyser();
2812
- this.outputAnalyser.fftSize = 256;
3358
+ this.outputAnalyser.fftSize = 512;
2813
3359
  this.outputAnalyser.smoothingTimeConstant = 0.78;
2814
- this.levelBuffer = new Uint8Array(this.outputAnalyser.fftSize);
2815
- this.outputSource = context.createMediaStreamSource(stream);
2816
- this.outputSource.connect(this.outputAnalyser);
3360
+ this.outputSilentSink = context.createGain();
3361
+ this.outputSilentSink.gain.value = 0;
3362
+ this.outputAnalyser.connect(this.outputSilentSink);
3363
+ this.outputSilentSink.connect(context.destination);
3364
+ this.outputEvidenceFloatBuffer = new Float32Array(this.outputAnalyser.fftSize);
3365
+ this.outputEvidenceByteBuffer = new Uint8Array(this.outputAnalyser.fftSize);
3366
+ const tracks = typeof stream.getAudioTracks === "function"
3367
+ ? stream
3368
+ .getAudioTracks()
3369
+ .filter((track) => track.readyState === "live")
3370
+ : [];
3371
+ const contextWithTrackSource = context;
3372
+ for (const track of tracks) {
3373
+ let source;
3374
+ if (typeof contextWithTrackSource.createMediaStreamTrackSource ===
3375
+ "function") {
3376
+ source = contextWithTrackSource.createMediaStreamTrackSource(track);
3377
+ }
3378
+ else if (tracks.length === 1) {
3379
+ source = context.createMediaStreamSource(stream);
3380
+ }
3381
+ else if (typeof MediaStream === "function") {
3382
+ const isolatedStream = new MediaStream([track]);
3383
+ this.outputAnalysisStreams.push(isolatedStream);
3384
+ source = context.createMediaStreamSource(isolatedStream);
3385
+ }
3386
+ else {
3387
+ throw new Error("Multiple remote audio tracks cannot be analysed.");
3388
+ }
3389
+ source.connect(this.outputAnalyser);
3390
+ this.outputSources.push(source);
3391
+ this.outputAnalysedTracks.add(track);
3392
+ }
3393
+ if (this.outputSources.length === 0) {
3394
+ this.disconnectOutputAnalyser();
3395
+ }
2817
3396
  }
2818
3397
  catch {
2819
- this.outputSource = null;
2820
- this.outputAnalyser = null;
2821
- this.levelBuffer = null;
2822
- }
3398
+ this.disconnectOutputAnalyser();
3399
+ }
3400
+ }
3401
+ outputAnalyserMatchesStream(stream) {
3402
+ const liveTracks = typeof stream.getAudioTracks === "function"
3403
+ ? stream.getAudioTracks().filter((track) => track.readyState === "live")
3404
+ : [];
3405
+ return Boolean(this.outputAnalyser &&
3406
+ liveTracks.length === this.outputAnalysedTracks.size &&
3407
+ liveTracks.every((track) => this.outputAnalysedTracks.has(track)));
3408
+ }
3409
+ disconnectOutputAnalyser() {
3410
+ for (const source of this.outputSources)
3411
+ source.disconnect();
3412
+ this.outputSources = [];
3413
+ this.outputAnalysisStreams = [];
3414
+ this.outputAnalysedTracks.clear();
3415
+ this.outputAnalyser?.disconnect();
3416
+ this.outputAnalyser = null;
3417
+ this.outputSilentSink?.disconnect();
3418
+ this.outputSilentSink = null;
3419
+ this.outputEvidenceFloatBuffer = null;
3420
+ this.outputEvidenceByteBuffer = null;
2823
3421
  }
2824
3422
  startLevelLoop() {
2825
3423
  if (this.levelFrame !== null ||
@@ -2861,6 +3459,12 @@ export class VoicePresenceView {
2861
3459
  this.host.style.setProperty("--voice-level", "0");
2862
3460
  }
2863
3461
  stopAudio() {
3462
+ this.playbackGeneration += 1;
3463
+ this.playbackResumePending = false;
3464
+ this.unbindPlaybackState();
3465
+ this.outputEvidenceCandidateUntil = 0;
3466
+ this.stopOutputEvidenceSampling();
3467
+ this.resetOutputEvidenceState();
2864
3468
  this.stopLevelLoop();
2865
3469
  this.audio.pause();
2866
3470
  const remoteStream = this.audio.srcObject;
@@ -2871,15 +3475,16 @@ export class VoicePresenceView {
2871
3475
  for (const track of remoteStream.getTracks())
2872
3476
  track.stop();
2873
3477
  }
2874
- this.outputSource?.disconnect();
2875
- this.outputSource = null;
2876
- this.outputAnalyser?.disconnect();
2877
- this.outputAnalyser = null;
3478
+ this.disconnectOutputAnalyser();
2878
3479
  this.inputSource?.disconnect();
2879
3480
  this.inputSource = null;
2880
3481
  this.inputAnalyser?.disconnect();
2881
3482
  this.inputAnalyser = null;
2882
3483
  this.levelBuffer = null;
3484
+ if (this.audioContext && this.audioContextStateListener) {
3485
+ this.audioContext.removeEventListener?.("statechange", this.audioContextStateListener);
3486
+ }
3487
+ this.audioContextStateListener = null;
2883
3488
  if (this.audioContext)
2884
3489
  void this.audioContext.close().catch(() => undefined);
2885
3490
  this.audioContext = null;
@@ -2909,9 +3514,6 @@ export class VoicePresenceView {
2909
3514
  activeAnalyser() {
2910
3515
  if (this.stateMachine.state === "active.listening")
2911
3516
  return this.inputAnalyser;
2912
- if (this.stateMachine.state === "active.speaking" && !this.audio.paused) {
2913
- return this.outputAnalyser;
2914
- }
2915
3517
  return null;
2916
3518
  }
2917
3519
  legalLink(url, label) {