@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
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VoicePresenceView = void 0;
4
4
  const lucide_1 = require("lucide");
5
5
  const dialogFocusScope_js_1 = require("./dialogFocusScope.js");
6
+ const ctaOffer_js_1 = require("./ctaOffer.js");
6
7
  const experienceState_js_1 = require("./experienceState.js");
7
8
  const index_js_1 = require("./locales/index.js");
8
9
  const placement_js_1 = require("./placement.js");
@@ -29,6 +30,18 @@ const confirmationPresentation = (value, fallbackTitle, fallbackApprove) => {
29
30
  const INTRO_WAKE_MS = 620;
30
31
  const MAX_LIVE_ANNOUNCEMENTS = 6;
31
32
  const MAX_VISIBLE_SUBTITLES = 3;
33
+ const REMOTE_AUDIO_EVIDENCE_SAMPLE_MS = 50;
34
+ const REMOTE_AUDIO_EVIDENCE_RECHECK_MS = 250;
35
+ const REMOTE_AUDIO_EVIDENCE_IDLE_RECHECK_MS = 1000;
36
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_WINDOW = 3;
37
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_HITS = 2;
38
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_RMS = 0.006;
39
+ const REMOTE_AUDIO_EVIDENCE_ATTACK_PEAK = 0.025;
40
+ const REMOTE_AUDIO_EVIDENCE_SUSTAIN_RMS = 0.0025;
41
+ const REMOTE_AUDIO_EVIDENCE_SUSTAIN_PEAK = 0.012;
42
+ const REMOTE_AUDIO_EVIDENCE_RELEASE_MS = 650;
43
+ const REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS = 5000;
44
+ const REMOTE_AUDIO_EVIDENCE_EXPECTATION_MS = 15000;
32
45
  const styles = `
33
46
  :host {
34
47
  all: initial;
@@ -1036,6 +1049,8 @@ class VoicePresenceView {
1036
1049
  constructor(config, overrides, callbacks, tabId, onFallback = () => undefined, visualTestMode = false, options = {}) {
1037
1050
  this.callbacks = callbacks;
1038
1051
  this.onFallback = onFallback;
1052
+ this.ctaCard = null;
1053
+ this.ctaSlot = null;
1039
1054
  this.captionTimers = new Map();
1040
1055
  this.captionResizeObserver = null;
1041
1056
  this.captionLayoutFrame = null;
@@ -1057,9 +1072,26 @@ class VoicePresenceView {
1057
1072
  this.statusTimer = null;
1058
1073
  this.attributionTimer = null;
1059
1074
  this.audioContext = null;
1075
+ this.audioContextStateListener = null;
1060
1076
  this.playbackResumePending = false;
1061
- this.outputSource = null;
1077
+ this.outputSources = [];
1078
+ this.outputAnalysisStreams = [];
1079
+ this.outputAnalysedTracks = new Set();
1062
1080
  this.outputAnalyser = null;
1081
+ this.outputSilentSink = null;
1082
+ this.outputEvidenceFloatBuffer = null;
1083
+ this.outputEvidenceByteBuffer = null;
1084
+ this.outputEvidenceTimer = null;
1085
+ this.outputEvidenceGeneration = 0;
1086
+ this.outputEvidenceAttackWindow = 0;
1087
+ this.outputEvidenceQuietSince = null;
1088
+ this.outputEvidenceAudible = false;
1089
+ this.outputEvidenceCandidateUntil = 0;
1090
+ this.outputEvidenceLastRms = 0;
1091
+ this.playbackGeneration = 0;
1092
+ this.playbackStateBindings = [];
1093
+ this.boundRemoteAudioStreams = new WeakSet();
1094
+ this.boundRemoteAudioTracks = new WeakSet();
1063
1095
  this.inputSource = null;
1064
1096
  this.inputAnalyser = null;
1065
1097
  this.levelFrame = null;
@@ -1087,6 +1119,17 @@ class VoicePresenceView {
1087
1119
  };
1088
1120
  this.onVisibilityChange = () => {
1089
1121
  this.syncMotionPolicy();
1122
+ if (document.hidden) {
1123
+ this.stopOutputEvidenceSampling();
1124
+ const wasAudible = this.outputEvidenceAudible;
1125
+ this.resetOutputEvidenceState();
1126
+ if (wasAudible) {
1127
+ this.emitPlaybackState("waiting");
1128
+ this.syncPresenceFromPlayback();
1129
+ }
1130
+ return;
1131
+ }
1132
+ this.resumeOutputAudioContext();
1090
1133
  };
1091
1134
  this.onReducedMotionChange = () => {
1092
1135
  this.syncMotionPolicy();
@@ -1110,7 +1153,7 @@ class VoicePresenceView {
1110
1153
  this.host.dir = locale.dir;
1111
1154
  this.shadow = this.host.attachShadow({ mode: "closed" });
1112
1155
  const sheet = document.createElement("style");
1113
- sheet.textContent = styles;
1156
+ sheet.textContent = styles + ctaOffer_js_1.CTA_OFFER_STYLES;
1114
1157
  this.shadow.append(sheet, this.build());
1115
1158
  document.documentElement.append(this.host);
1116
1159
  this.orb = this.require('[data-role="orb"]');
@@ -1261,7 +1304,34 @@ class VoicePresenceView {
1261
1304
  return true;
1262
1305
  }
1263
1306
  setRemoteStream(stream) {
1307
+ if (this.destroyed)
1308
+ return;
1264
1309
  const previous = this.audio.srcObject;
1310
+ const streamChanged = previous !== stream;
1311
+ const analysisChanged = !this.outputAnalyserMatchesStream(stream);
1312
+ if (streamChanged) {
1313
+ this.playbackGeneration += 1;
1314
+ this.playbackResumePending = false;
1315
+ this.stopOutputEvidenceSampling();
1316
+ const wasAudible = this.outputEvidenceAudible;
1317
+ this.resetOutputEvidenceState();
1318
+ this.playbackState = "waiting";
1319
+ if (wasAudible)
1320
+ this.emitPlaybackState("waiting");
1321
+ this.syncPresenceFromPlayback();
1322
+ this.boundRemoteAudioTracks = new WeakSet();
1323
+ }
1324
+ else if (analysisChanged) {
1325
+ const wasAudible = this.outputEvidenceAudible;
1326
+ this.stopOutputEvidenceSampling();
1327
+ this.resetOutputEvidenceState();
1328
+ if (wasAudible)
1329
+ this.emitPlaybackState("waiting");
1330
+ this.syncPresenceFromPlayback();
1331
+ }
1332
+ this.audio.srcObject = stream;
1333
+ if (streamChanged)
1334
+ this.bindPlaybackState();
1265
1335
  if (previous &&
1266
1336
  typeof MediaStream !== "undefined" &&
1267
1337
  previous instanceof MediaStream &&
@@ -1269,11 +1339,20 @@ class VoicePresenceView {
1269
1339
  for (const track of previous.getTracks())
1270
1340
  track.stop();
1271
1341
  }
1272
- this.audio.srcObject = stream;
1273
- this.connectOutputAnalyser(stream);
1342
+ if (streamChanged || analysisChanged)
1343
+ this.connectOutputAnalyser(stream);
1344
+ this.bindRemoteAudioTrackState(stream);
1345
+ this.resumeOutputAudioContext();
1346
+ this.startOutputEvidenceSampling();
1347
+ const generation = this.playbackGeneration;
1274
1348
  void this.audio.play().catch(() => {
1349
+ if (!this.playbackSourceIsCurrent(generation, stream))
1350
+ return;
1275
1351
  this.playbackState = "blocked";
1352
+ this.stopOutputEvidenceSampling();
1353
+ this.resetOutputEvidenceState();
1276
1354
  this.emitPlaybackState("blocked");
1355
+ this.syncPresenceFromPlayback();
1277
1356
  this.orb.setAttribute("aria-label", this.messages.audioPaused);
1278
1357
  this.showTransientStatus(this.messages.audioPaused, 6000);
1279
1358
  });
@@ -1298,6 +1377,7 @@ class VoicePresenceView {
1298
1377
  this.safetyCard,
1299
1378
  this.recoveryCard,
1300
1379
  this.orb,
1380
+ ...(this.ctaSlot ? [this.ctaSlot] : []),
1301
1381
  ];
1302
1382
  return candidates
1303
1383
  .filter((element) => element.isConnected && !element.hidden)
@@ -1340,7 +1420,9 @@ class VoicePresenceView {
1340
1420
  setAssistantState(state) {
1341
1421
  if (!this.active)
1342
1422
  return;
1423
+ const previous = this.serverPresenceState;
1343
1424
  this.serverPresenceState = state;
1425
+ this.updateOutputEvidenceExpectation(previous, state);
1344
1426
  if (state === "thinking" || state === "speaking") {
1345
1427
  this.resumeRemotePlayback();
1346
1428
  }
@@ -1348,17 +1430,20 @@ class VoicePresenceView {
1348
1430
  this.syncLevelLoop();
1349
1431
  }
1350
1432
  applyPresenceState(state, sequence, sessionId, pageId, fencingToken) {
1351
- this.serverPresenceState = state;
1352
- if (state === "thinking" || state === "speaking") {
1353
- this.resumeRemotePlayback();
1354
- }
1355
- const next = this.effectivePresenceState();
1356
- this.stateMachine.transition(next, {
1433
+ const previous = this.serverPresenceState;
1434
+ const accepted = this.stateMachine.transition(this.effectivePresenceState(state), {
1357
1435
  sessionId,
1358
1436
  serverSequence: sequence,
1359
1437
  ...(pageId ? { pageId } : {}),
1360
1438
  fencingToken,
1361
1439
  });
1440
+ if (!accepted)
1441
+ return;
1442
+ this.serverPresenceState = state;
1443
+ this.updateOutputEvidenceExpectation(previous, state);
1444
+ if (state === "thinking" || state === "speaking") {
1445
+ this.resumeRemotePlayback();
1446
+ }
1362
1447
  if (state === "reconnecting")
1363
1448
  this.showTransientStatus(this.messages.reconnecting, 5000);
1364
1449
  else if (state !== "awaiting_confirmation")
@@ -1412,7 +1497,8 @@ class VoicePresenceView {
1412
1497
  this.addCaption("assistant", welcomeMessage, true);
1413
1498
  }
1414
1499
  }
1415
- addCaption(role, text, final) {
1500
+ addCaption(role, text, final, _options = {}) {
1501
+ void _options;
1416
1502
  if (!this.voiceConfig.captions.enabled)
1417
1503
  return;
1418
1504
  if (!final) {
@@ -1719,13 +1805,27 @@ class VoicePresenceView {
1719
1805
  }
1720
1806
  setPushActive(_value) {
1721
1807
  void _value;
1808
+ return true;
1809
+ }
1810
+ setPushPending(_value) {
1811
+ void _value;
1812
+ return false;
1722
1813
  }
1723
1814
  interruptPlayback() {
1815
+ this.playbackGeneration += 1;
1816
+ this.playbackResumePending = false;
1817
+ this.outputEvidenceCandidateUntil = 0;
1818
+ this.stopOutputEvidenceSampling();
1819
+ this.resetOutputEvidenceState();
1820
+ this.serverPresenceState = "ready";
1821
+ this.playbackState = "paused";
1822
+ this.bindPlaybackState();
1724
1823
  this.audio.pause();
1725
1824
  this.stopLevelLoop();
1726
1825
  this.host.style.setProperty("--voice-level", "0");
1727
1826
  if (this.active)
1728
1827
  this.stateMachine.transition("active.ready");
1828
+ this.emitPlaybackState("paused");
1729
1829
  }
1730
1830
  showError(message, retryable = false, sessionActive = this.active) {
1731
1831
  this.hidePageAssistanceRequest(false);
@@ -1735,6 +1835,7 @@ class VoicePresenceView {
1735
1835
  this.hideSafetyCard();
1736
1836
  const safeMessage = message || this.messages.error;
1737
1837
  if (sessionActive && this.active) {
1838
+ this.interruptPlayback();
1738
1839
  this.stateMachine.transition(retryable ? "recoverable_error" : "terminal_error");
1739
1840
  this.hideStatus();
1740
1841
  this.renderRecoveryCard(safeMessage, retryable);
@@ -1798,6 +1899,7 @@ class VoicePresenceView {
1798
1899
  this.placement.refresh();
1799
1900
  }
1800
1901
  showEnded(message) {
1902
+ this.clearCtaOffer();
1801
1903
  this.active = false;
1802
1904
  this.hidePageAssistanceRequest(false);
1803
1905
  this.currentConfirmation = null;
@@ -1815,6 +1917,7 @@ class VoicePresenceView {
1815
1917
  if (message)
1816
1918
  this.showTransientStatus(message, 3000);
1817
1919
  this.stateMachine.transition("launcher");
1920
+ this.orb.hidden = false;
1818
1921
  this.showAttribution();
1819
1922
  this.placement.refresh();
1820
1923
  }
@@ -1918,6 +2021,7 @@ class VoicePresenceView {
1918
2021
  return true;
1919
2022
  }
1920
2023
  destroy() {
2024
+ this.clearCtaOffer();
1921
2025
  if (this.destroyed)
1922
2026
  return;
1923
2027
  this.destroyed = true;
@@ -1946,6 +2050,23 @@ class VoicePresenceView {
1946
2050
  this.stopAudio();
1947
2051
  this.host.remove();
1948
2052
  }
2053
+ showCtaOffer(value, options = {}) {
2054
+ const offer = (0, ctaOffer_js_1.parseCtaOffer)(value);
2055
+ if (!offer || this.ctaCard?.offer.offerId === offer.offerId)
2056
+ return;
2057
+ this.clearCtaOffer();
2058
+ this.ctaSlot = document.createElement("div");
2059
+ this.ctaSlot.className = "cta-action-slot";
2060
+ this.ctaCard = new ctaOffer_js_1.CtaOfferCard(offer, this.messages, (result) => this.callbacks.onCtaResult?.(result) ?? false, () => this.orb.focus({ preventScroll: true }), options.announce !== false);
2061
+ this.ctaSlot.append(this.ctaCard.element);
2062
+ this.require(".orb-wrap").append(this.ctaSlot);
2063
+ }
2064
+ clearCtaOffer() {
2065
+ this.ctaCard?.destroy();
2066
+ this.ctaCard = null;
2067
+ this.ctaSlot?.remove();
2068
+ this.ctaSlot = null;
2069
+ }
1949
2070
  build() {
1950
2071
  const fragment = document.createDocumentFragment();
1951
2072
  const presenceField = document.createElement("div");
@@ -2261,29 +2382,73 @@ class VoicePresenceView {
2261
2382
  });
2262
2383
  }
2263
2384
  bindPlaybackState() {
2264
- this.audio.addEventListener("playing", () => {
2385
+ this.unbindPlaybackState();
2386
+ const generation = this.playbackGeneration;
2387
+ const stream = this.audio.srcObject;
2388
+ const current = () => this.playbackSourceIsCurrent(generation, stream);
2389
+ const bind = (type, handler) => {
2390
+ const listener = () => {
2391
+ if (!current())
2392
+ return;
2393
+ handler();
2394
+ };
2395
+ this.playbackStateBindings.push({ type, listener });
2396
+ this.audio.addEventListener(type, listener);
2397
+ };
2398
+ bind("playing", () => {
2265
2399
  this.playbackState = "playing";
2266
- if (this.active)
2267
- this.orb.setAttribute("aria-label", this.messages.end);
2268
- this.emitPlaybackState("playing");
2269
- this.syncPresenceFromPlayback();
2270
- });
2271
- this.audio.addEventListener("waiting", () => {
2272
- this.playbackState = "waiting";
2400
+ this.orb.setAttribute("aria-label", this.messages.end);
2401
+ // A successful media-element transition is the browser's fresh proof
2402
+ // that playback may proceed after a user gesture. Report readiness
2403
+ // without claiming audibility; measured audio evidence will promote the
2404
+ // state to `playing` only once samples prove that sound is present.
2273
2405
  this.emitPlaybackState("waiting");
2406
+ this.resumeOutputAudioContext();
2407
+ this.startOutputEvidenceSampling();
2274
2408
  this.syncPresenceFromPlayback();
2275
2409
  });
2276
- this.audio.addEventListener("pause", () => {
2277
- this.playbackState = "paused";
2278
- this.emitPlaybackState("paused");
2279
- this.syncPresenceFromPlayback();
2280
- });
2281
- this.audio.addEventListener("ended", () => {
2282
- this.playbackState = "ended";
2283
- this.emitPlaybackState("ended");
2410
+ bind("waiting", () => this.applyPlaybackInactiveState("waiting"));
2411
+ bind("pause", () => this.applyPlaybackInactiveState("paused"));
2412
+ bind("ended", () => this.applyPlaybackInactiveState("ended"));
2413
+ bind("volumechange", () => {
2414
+ if (this.remoteAudioTrackIsPlayable()) {
2415
+ this.resumeOutputAudioContext();
2416
+ this.startOutputEvidenceSampling();
2417
+ return;
2418
+ }
2419
+ const wasAudible = this.outputEvidenceAudible;
2420
+ this.stopOutputEvidenceSampling();
2421
+ this.resetOutputEvidenceState();
2422
+ if (wasAudible)
2423
+ this.emitPlaybackState("waiting");
2284
2424
  this.syncPresenceFromPlayback();
2285
2425
  });
2286
2426
  }
2427
+ unbindPlaybackState() {
2428
+ for (const binding of this.playbackStateBindings) {
2429
+ this.audio.removeEventListener(binding.type, binding.listener);
2430
+ }
2431
+ this.playbackStateBindings = [];
2432
+ }
2433
+ playbackSourceIsCurrent(generation, stream) {
2434
+ return Boolean(!this.destroyed &&
2435
+ this.active &&
2436
+ stream &&
2437
+ generation === this.playbackGeneration &&
2438
+ this.audio.srcObject === stream);
2439
+ }
2440
+ applyPlaybackInactiveState(state) {
2441
+ if (this.playbackState === state &&
2442
+ !this.outputEvidenceAudible &&
2443
+ this.outputEvidenceTimer === null) {
2444
+ return;
2445
+ }
2446
+ this.playbackState = state;
2447
+ this.stopOutputEvidenceSampling();
2448
+ this.resetOutputEvidenceState();
2449
+ this.emitPlaybackState(state);
2450
+ this.syncPresenceFromPlayback();
2451
+ }
2287
2452
  resumeRemotePlayback() {
2288
2453
  if (!this.active ||
2289
2454
  !this.audio.paused ||
@@ -2291,21 +2456,31 @@ class VoicePresenceView {
2291
2456
  this.playbackResumePending) {
2292
2457
  return;
2293
2458
  }
2459
+ const stream = this.audio.srcObject;
2460
+ const generation = this.playbackGeneration;
2294
2461
  this.playbackResumePending = true;
2295
2462
  void this.audio
2296
2463
  .play()
2297
2464
  .catch(() => {
2465
+ if (!this.playbackSourceIsCurrent(generation, stream))
2466
+ return;
2298
2467
  this.playbackState = "blocked";
2468
+ this.stopOutputEvidenceSampling();
2469
+ this.resetOutputEvidenceState();
2299
2470
  this.emitPlaybackState("blocked");
2471
+ this.syncPresenceFromPlayback();
2300
2472
  this.orb.setAttribute("aria-label", this.messages.audioPaused);
2301
2473
  this.showTransientStatus(this.messages.audioPaused, 6000);
2302
2474
  })
2303
2475
  .finally(() => {
2304
- this.playbackResumePending = false;
2476
+ if (generation === this.playbackGeneration &&
2477
+ this.audio.srcObject === stream) {
2478
+ this.playbackResumePending = false;
2479
+ }
2305
2480
  });
2306
2481
  }
2307
- effectivePresenceState() {
2308
- const state = this.serverPresenceState;
2482
+ effectivePresenceState(proposedState = this.serverPresenceState) {
2483
+ const state = proposedState;
2309
2484
  if (state === "ending")
2310
2485
  return "ending";
2311
2486
  if (state === "acting" ||
@@ -2314,7 +2489,7 @@ class VoicePresenceView {
2314
2489
  return `active.${state}`;
2315
2490
  }
2316
2491
  if (state === "speaking") {
2317
- if (this.playbackState === "playing") {
2492
+ if (this.playbackState === "playing" && this.remoteAudioIsAudible()) {
2318
2493
  return "active.speaking";
2319
2494
  }
2320
2495
  return this.playbackState === "paused" || this.playbackState === "ended"
@@ -2330,18 +2505,335 @@ class VoicePresenceView {
2330
2505
  this.syncLevelLoop();
2331
2506
  }
2332
2507
  syncLevelLoop() {
2333
- if (this.stateMachine.state === "active.listening" ||
2334
- this.stateMachine.state === "active.speaking") {
2508
+ if (this.stateMachine.state === "active.listening") {
2335
2509
  this.startLevelLoop();
2510
+ return;
2336
2511
  }
2337
- else {
2338
- this.stopLevelLoop();
2512
+ this.stopLevelLoop();
2513
+ if (this.stateMachine.state === "active.speaking") {
2514
+ this.startOutputEvidenceSampling();
2515
+ this.syncOutputLevel(this.outputEvidenceLastRms);
2516
+ }
2517
+ }
2518
+ remoteAudioIsAudible() {
2519
+ return this.outputEvidenceAudible && this.remoteAudioTrackIsPlayable();
2520
+ }
2521
+ remoteAudioTrackIsPlayable() {
2522
+ const stream = this.audio.srcObject;
2523
+ const currentTracks = typeof stream?.getAudioTracks === "function"
2524
+ ? stream.getAudioTracks()
2525
+ : [];
2526
+ if (!stream || this.outputAnalysedTracks.size === 0) {
2527
+ return false;
2528
+ }
2529
+ return Boolean(!this.audio.paused &&
2530
+ !this.audio.muted &&
2531
+ this.audio.volume > 0 &&
2532
+ [...this.outputAnalysedTracks].some((track) => currentTracks.some((candidate) => candidate === track) &&
2533
+ track.readyState === "live" &&
2534
+ track.enabled !== false &&
2535
+ track.muted !== true));
2536
+ }
2537
+ bindRemoteAudioTrackState(stream) {
2538
+ if (typeof stream.getAudioTracks !== "function")
2539
+ return;
2540
+ if (!this.boundRemoteAudioStreams.has(stream) &&
2541
+ typeof stream.addEventListener === "function") {
2542
+ this.boundRemoteAudioStreams.add(stream);
2543
+ const refreshTrackSet = () => {
2544
+ if (this.destroyed || !this.active || this.audio.srcObject !== stream) {
2545
+ return;
2546
+ }
2547
+ const wasAudible = this.outputEvidenceAudible;
2548
+ this.stopOutputEvidenceSampling();
2549
+ this.resetOutputEvidenceState();
2550
+ this.connectOutputAnalyser(stream);
2551
+ this.bindRemoteAudioTrackState(stream);
2552
+ if (wasAudible)
2553
+ this.emitPlaybackState("waiting");
2554
+ this.syncPresenceFromPlayback();
2555
+ this.startOutputEvidenceSampling();
2556
+ };
2557
+ stream.addEventListener("addtrack", refreshTrackSet);
2558
+ stream.addEventListener("removetrack", refreshTrackSet);
2559
+ }
2560
+ const isCurrent = (track) => !this.destroyed &&
2561
+ this.active &&
2562
+ this.audio.srcObject === stream &&
2563
+ stream.getAudioTracks().some((candidate) => candidate === track);
2564
+ for (const track of stream.getAudioTracks()) {
2565
+ if (this.boundRemoteAudioTracks.has(track) ||
2566
+ typeof track.addEventListener !== "function") {
2567
+ continue;
2568
+ }
2569
+ this.boundRemoteAudioTracks.add(track);
2570
+ track.addEventListener("mute", () => {
2571
+ if (!isCurrent(track))
2572
+ return;
2573
+ this.stopOutputEvidenceSampling();
2574
+ this.resetOutputEvidenceState();
2575
+ this.emitPlaybackState("waiting");
2576
+ this.syncPresenceFromPlayback();
2577
+ });
2578
+ track.addEventListener("unmute", () => {
2579
+ if (!isCurrent(track) || this.playbackState !== "playing")
2580
+ return;
2581
+ this.resetOutputEvidenceAttack();
2582
+ this.resumeOutputAudioContext();
2583
+ this.startOutputEvidenceSampling();
2584
+ });
2585
+ track.addEventListener("ended", () => {
2586
+ if (!isCurrent(track))
2587
+ return;
2588
+ this.stopOutputEvidenceSampling();
2589
+ this.resetOutputEvidenceState();
2590
+ this.connectOutputAnalyser(stream);
2591
+ if (stream
2592
+ .getAudioTracks()
2593
+ .some((candidate) => candidate.readyState === "live")) {
2594
+ this.playbackState = "waiting";
2595
+ this.emitPlaybackState("waiting");
2596
+ this.startOutputEvidenceSampling();
2597
+ }
2598
+ else {
2599
+ this.playbackState = "ended";
2600
+ this.emitPlaybackState("ended");
2601
+ }
2602
+ this.syncPresenceFromPlayback();
2603
+ });
2604
+ }
2605
+ }
2606
+ updateOutputEvidenceExpectation(previous, next) {
2607
+ const now = this.outputEvidenceNow();
2608
+ if (next === "thinking" || next === "speaking") {
2609
+ this.outputEvidenceCandidateUntil = Math.max(this.outputEvidenceCandidateUntil, now + REMOTE_AUDIO_EVIDENCE_EXPECTATION_MS);
2610
+ this.startOutputEvidenceSampling();
2611
+ return;
2339
2612
  }
2613
+ if (next === "ready" &&
2614
+ (previous === "thinking" ||
2615
+ previous === "speaking" ||
2616
+ this.outputEvidenceAudible)) {
2617
+ this.outputEvidenceCandidateUntil =
2618
+ now + REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS;
2619
+ this.startOutputEvidenceSampling();
2620
+ return;
2621
+ }
2622
+ this.outputEvidenceCandidateUntil = 0;
2623
+ this.stopOutputEvidenceSampling();
2624
+ this.resetOutputEvidenceState();
2625
+ }
2626
+ outputEvidenceNow() {
2627
+ const value = globalThis.performance?.now?.();
2628
+ return typeof value === "number" && Number.isFinite(value)
2629
+ ? value
2630
+ : Date.now();
2631
+ }
2632
+ outputEvidenceCandidateIsCurrent(now) {
2633
+ if (!this.outputEvidenceVisualStateIsEligible())
2634
+ return false;
2635
+ return Boolean(this.outputEvidenceAudible ||
2636
+ this.serverPresenceState === "thinking" ||
2637
+ this.serverPresenceState === "speaking" ||
2638
+ (this.outputEvidenceCandidateUntil > 0 &&
2639
+ now < this.outputEvidenceCandidateUntil));
2640
+ }
2641
+ outputEvidenceVisualStateIsEligible() {
2642
+ return (this.stateMachine.state === "active.thinking" ||
2643
+ this.stateMachine.state === "active.speaking" ||
2644
+ this.stateMachine.state === "active.ready");
2645
+ }
2646
+ startOutputEvidenceSampling() {
2647
+ const now = this.outputEvidenceNow();
2648
+ if (this.outputEvidenceTimer !== null ||
2649
+ this.destroyed ||
2650
+ !this.active ||
2651
+ this.playbackState !== "playing" ||
2652
+ !this.outputAnalyser ||
2653
+ (!this.outputEvidenceFloatBuffer && !this.outputEvidenceByteBuffer) ||
2654
+ this.audioContext?.state !== "running" ||
2655
+ !this.outputEvidenceCandidateIsCurrent(now)) {
2656
+ return;
2657
+ }
2658
+ const generation = this.outputEvidenceGeneration;
2659
+ const inBurstWindow = this.outputEvidenceAudible ||
2660
+ (this.outputEvidenceCandidateUntil > 0 &&
2661
+ now < this.outputEvidenceCandidateUntil);
2662
+ const delay = inBurstWindow
2663
+ ? this.remoteAudioTrackIsPlayable()
2664
+ ? REMOTE_AUDIO_EVIDENCE_SAMPLE_MS
2665
+ : REMOTE_AUDIO_EVIDENCE_RECHECK_MS
2666
+ : REMOTE_AUDIO_EVIDENCE_IDLE_RECHECK_MS;
2667
+ this.outputEvidenceTimer = setTimeout(() => {
2668
+ this.outputEvidenceTimer = null;
2669
+ if (generation !== this.outputEvidenceGeneration)
2670
+ return;
2671
+ this.sampleOutputEvidence(generation);
2672
+ }, delay);
2673
+ }
2674
+ sampleOutputEvidence(generation) {
2675
+ if (generation !== this.outputEvidenceGeneration ||
2676
+ this.destroyed ||
2677
+ !this.active ||
2678
+ this.playbackState !== "playing") {
2679
+ return;
2680
+ }
2681
+ if (!this.remoteAudioTrackIsPlayable()) {
2682
+ const wasAudible = this.outputEvidenceAudible;
2683
+ this.stopOutputEvidenceSampling();
2684
+ this.resetOutputEvidenceState();
2685
+ if (wasAudible)
2686
+ this.emitPlaybackState("waiting");
2687
+ this.syncPresenceFromPlayback();
2688
+ this.startOutputEvidenceSampling();
2689
+ return;
2690
+ }
2691
+ const now = this.outputEvidenceNow();
2692
+ if (!this.outputEvidenceCandidateIsCurrent(now)) {
2693
+ this.stopOutputEvidenceSampling();
2694
+ this.resetOutputEvidenceState();
2695
+ return;
2696
+ }
2697
+ const sample = this.readOutputEvidence();
2698
+ if (!sample) {
2699
+ const wasAudible = this.outputEvidenceAudible;
2700
+ this.stopOutputEvidenceSampling();
2701
+ this.resetOutputEvidenceState();
2702
+ if (wasAudible) {
2703
+ this.emitPlaybackState("waiting");
2704
+ this.syncPresenceFromPlayback();
2705
+ }
2706
+ this.startOutputEvidenceSampling();
2707
+ return;
2708
+ }
2709
+ this.outputEvidenceLastRms = sample.rms;
2710
+ const attack = sample.rms >= REMOTE_AUDIO_EVIDENCE_ATTACK_RMS ||
2711
+ sample.peak >= REMOTE_AUDIO_EVIDENCE_ATTACK_PEAK;
2712
+ const sustain = sample.rms >= REMOTE_AUDIO_EVIDENCE_SUSTAIN_RMS ||
2713
+ sample.peak >= REMOTE_AUDIO_EVIDENCE_SUSTAIN_PEAK;
2714
+ if (!this.outputEvidenceAudible) {
2715
+ const mask = (1 << REMOTE_AUDIO_EVIDENCE_ATTACK_WINDOW) - 1;
2716
+ this.outputEvidenceAttackWindow =
2717
+ ((this.outputEvidenceAttackWindow << 1) | Number(attack)) & mask;
2718
+ let hits = 0;
2719
+ for (let candidates = this.outputEvidenceAttackWindow; candidates > 0; candidates >>= 1) {
2720
+ hits += candidates & 1;
2721
+ }
2722
+ if (hits >= REMOTE_AUDIO_EVIDENCE_ATTACK_HITS) {
2723
+ this.outputEvidenceAudible = true;
2724
+ this.outputEvidenceQuietSince = null;
2725
+ this.outputEvidenceAttackWindow = 0;
2726
+ this.outputEvidenceCandidateUntil = Math.max(this.outputEvidenceCandidateUntil, now + REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS);
2727
+ this.emitPlaybackState("playing");
2728
+ this.syncPresenceFromPlayback();
2729
+ }
2730
+ }
2731
+ else if (sustain) {
2732
+ this.outputEvidenceQuietSince = null;
2733
+ this.outputEvidenceCandidateUntil = Math.max(this.outputEvidenceCandidateUntil, now + REMOTE_AUDIO_EVIDENCE_READY_TAIL_MS);
2734
+ }
2735
+ else if (this.outputEvidenceQuietSince === null) {
2736
+ this.outputEvidenceQuietSince = now;
2737
+ }
2738
+ else if (now - this.outputEvidenceQuietSince >=
2739
+ REMOTE_AUDIO_EVIDENCE_RELEASE_MS) {
2740
+ this.outputEvidenceAudible = false;
2741
+ this.resetOutputEvidenceAttack();
2742
+ this.emitPlaybackState("waiting");
2743
+ this.syncPresenceFromPlayback();
2744
+ }
2745
+ this.syncOutputLevel(sample.rms);
2746
+ this.startOutputEvidenceSampling();
2747
+ }
2748
+ readOutputEvidence() {
2749
+ const analyser = this.outputAnalyser;
2750
+ const context = this.audioContext;
2751
+ if (!analyser || !context || context.state !== "running")
2752
+ return null;
2753
+ let length = 0;
2754
+ let valueAt = null;
2755
+ let floatRead = false;
2756
+ if (this.outputEvidenceFloatBuffer &&
2757
+ typeof analyser.getFloatTimeDomainData === "function") {
2758
+ try {
2759
+ analyser.getFloatTimeDomainData(this.outputEvidenceFloatBuffer);
2760
+ length = this.outputEvidenceFloatBuffer.length;
2761
+ valueAt = (index) => this.outputEvidenceFloatBuffer?.[index] ?? 0;
2762
+ floatRead = true;
2763
+ }
2764
+ catch {
2765
+ floatRead = false;
2766
+ }
2767
+ }
2768
+ if (!floatRead) {
2769
+ if (!this.outputEvidenceByteBuffer)
2770
+ return null;
2771
+ try {
2772
+ analyser.getByteTimeDomainData(this.outputEvidenceByteBuffer);
2773
+ length = this.outputEvidenceByteBuffer.length;
2774
+ valueAt = (index) => ((this.outputEvidenceByteBuffer?.[index] ?? 128) - 128) / 128;
2775
+ }
2776
+ catch {
2777
+ return null;
2778
+ }
2779
+ }
2780
+ if (length === 0 || !valueAt)
2781
+ return null;
2782
+ let mean = 0;
2783
+ for (let index = 0; index < length; index += 1) {
2784
+ const value = valueAt(index);
2785
+ if (!Number.isFinite(value))
2786
+ return null;
2787
+ mean += value;
2788
+ }
2789
+ mean /= length;
2790
+ let sum = 0;
2791
+ let peak = 0;
2792
+ for (let index = 0; index < length; index += 1) {
2793
+ const centered = valueAt(index) - mean;
2794
+ if (!Number.isFinite(centered))
2795
+ return null;
2796
+ sum += centered * centered;
2797
+ peak = Math.max(peak, Math.abs(centered));
2798
+ }
2799
+ const volume = Math.min(1, Math.max(0, this.audio.volume));
2800
+ const rms = Math.sqrt(sum / length) * volume;
2801
+ peak *= volume;
2802
+ return Number.isFinite(rms) && Number.isFinite(peak) ? { rms, peak } : null;
2803
+ }
2804
+ stopOutputEvidenceSampling() {
2805
+ if (this.outputEvidenceTimer !== null) {
2806
+ clearTimeout(this.outputEvidenceTimer);
2807
+ this.outputEvidenceTimer = null;
2808
+ }
2809
+ this.outputEvidenceGeneration += 1;
2810
+ }
2811
+ resetOutputEvidenceAttack() {
2812
+ this.outputEvidenceAttackWindow = 0;
2813
+ this.outputEvidenceQuietSince = null;
2814
+ }
2815
+ resetOutputEvidenceState() {
2816
+ this.outputEvidenceAudible = false;
2817
+ this.outputEvidenceLastRms = 0;
2818
+ this.resetOutputEvidenceAttack();
2819
+ this.syncOutputLevel(0);
2820
+ }
2821
+ syncOutputLevel(rms) {
2822
+ if (!this.outputEvidenceAudible ||
2823
+ this.stateMachine.state !== "active.speaking" ||
2824
+ !this.motionEnabled() ||
2825
+ document.hidden) {
2826
+ if (this.stateMachine.state !== "active.listening") {
2827
+ this.host.style.setProperty("--voice-level", "0");
2828
+ }
2829
+ return;
2830
+ }
2831
+ this.host.style.setProperty("--voice-level", Math.min(1, Math.max(0, rms) * 5.5).toFixed(3));
2340
2832
  }
2341
2833
  emitPlaybackState(state) {
2342
2834
  this.callbacks.onPlaybackState({
2343
2835
  state,
2344
- audible: state === "playing" && !this.audio.muted && this.audio.volume > 0,
2836
+ audible: state === "playing" && this.remoteAudioIsAudible(),
2345
2837
  utteranceId: null,
2346
2838
  sampledAt: new Date().toISOString(),
2347
2839
  });
@@ -2553,7 +3045,7 @@ class VoicePresenceView {
2553
3045
  close.setAttribute("aria-label", this.messages.close);
2554
3046
  close.append(icon(lucide_1.X, "close-symbol"));
2555
3047
  close.addEventListener("click", () => {
2556
- this.hideRecoveryCard();
3048
+ this.dismissRecoveryCard();
2557
3049
  });
2558
3050
  const heading = document.createElement("div");
2559
3051
  heading.className = "recovery-head";
@@ -2607,10 +3099,27 @@ class VoicePresenceView {
2607
3099
  initialFocus: () => primary ?? close,
2608
3100
  fallbackFocus: () => (this.orb.hidden ? null : this.orb),
2609
3101
  onEscape: () => {
2610
- this.hideRecoveryCard();
3102
+ this.dismissRecoveryCard();
2611
3103
  },
2612
3104
  });
2613
3105
  }
3106
+ dismissRecoveryCard() {
3107
+ const restoreLauncher = !this.active &&
3108
+ !this.activeElsewhere &&
3109
+ (this.stateMachine.state === "unavailable" ||
3110
+ this.stateMachine.state === "recoverable_error" ||
3111
+ this.stateMachine.state === "terminal_error");
3112
+ this.hideRecoveryCard();
3113
+ if (!restoreLauncher)
3114
+ return;
3115
+ this.orb.disabled = false;
3116
+ this.orb.dataset.active = "false";
3117
+ this.orb.hidden = false;
3118
+ this.orb.setAttribute("aria-label", this.launcherLabel());
3119
+ this.stateMachine.reset();
3120
+ this.stateMachine.transition("launcher");
3121
+ this.placement.refresh();
3122
+ }
2614
3123
  hideRecoveryCard(restore = true) {
2615
3124
  this.recoveryCard.hidden = true;
2616
3125
  this.recoveryCard.replaceChildren();
@@ -2785,7 +3294,7 @@ class VoicePresenceView {
2785
3294
  }
2786
3295
  ensureAudioContext() {
2787
3296
  if (this.audioContext) {
2788
- void this.audioContext.resume().catch(() => undefined);
3297
+ this.resumeOutputAudioContext();
2789
3298
  return;
2790
3299
  }
2791
3300
  const AudioContextConstructor = window.AudioContext ||
@@ -2797,32 +3306,121 @@ class VoicePresenceView {
2797
3306
  this.audioContext = new AudioContextConstructor({
2798
3307
  latencyHint: "interactive",
2799
3308
  });
2800
- void this.audioContext.resume().catch(() => undefined);
3309
+ const context = this.audioContext;
3310
+ this.audioContextStateListener = () => {
3311
+ if (this.destroyed || this.audioContext !== context)
3312
+ return;
3313
+ if (context.state === "running") {
3314
+ this.startOutputEvidenceSampling();
3315
+ return;
3316
+ }
3317
+ const wasAudible = this.outputEvidenceAudible;
3318
+ this.stopOutputEvidenceSampling();
3319
+ this.resetOutputEvidenceState();
3320
+ if (wasAudible) {
3321
+ this.emitPlaybackState("waiting");
3322
+ this.syncPresenceFromPlayback();
3323
+ }
3324
+ };
3325
+ context.addEventListener?.("statechange", this.audioContextStateListener);
3326
+ this.resumeOutputAudioContext();
2801
3327
  }
2802
3328
  catch {
2803
3329
  this.audioContext = null;
3330
+ this.audioContextStateListener = null;
3331
+ }
3332
+ }
3333
+ resumeOutputAudioContext() {
3334
+ const context = this.audioContext;
3335
+ if (!context || context.state === "closed" || this.destroyed)
3336
+ return;
3337
+ if (context.state === "running") {
3338
+ this.startOutputEvidenceSampling();
3339
+ return;
2804
3340
  }
3341
+ const generation = this.playbackGeneration;
3342
+ const stream = this.audio.srcObject;
3343
+ void context
3344
+ .resume()
3345
+ .then(() => {
3346
+ if (this.audioContext === context &&
3347
+ (!stream || this.playbackSourceIsCurrent(generation, stream))) {
3348
+ this.startOutputEvidenceSampling();
3349
+ }
3350
+ })
3351
+ .catch(() => undefined);
2805
3352
  }
2806
3353
  connectOutputAnalyser(stream) {
2807
3354
  this.ensureAudioContext();
2808
3355
  const context = this.audioContext;
2809
3356
  if (!context)
2810
3357
  return;
3358
+ this.disconnectOutputAnalyser();
2811
3359
  try {
2812
- this.outputSource?.disconnect();
2813
- this.outputAnalyser?.disconnect();
2814
3360
  this.outputAnalyser = context.createAnalyser();
2815
- this.outputAnalyser.fftSize = 256;
3361
+ this.outputAnalyser.fftSize = 512;
2816
3362
  this.outputAnalyser.smoothingTimeConstant = 0.78;
2817
- this.levelBuffer = new Uint8Array(this.outputAnalyser.fftSize);
2818
- this.outputSource = context.createMediaStreamSource(stream);
2819
- this.outputSource.connect(this.outputAnalyser);
3363
+ this.outputSilentSink = context.createGain();
3364
+ this.outputSilentSink.gain.value = 0;
3365
+ this.outputAnalyser.connect(this.outputSilentSink);
3366
+ this.outputSilentSink.connect(context.destination);
3367
+ this.outputEvidenceFloatBuffer = new Float32Array(this.outputAnalyser.fftSize);
3368
+ this.outputEvidenceByteBuffer = new Uint8Array(this.outputAnalyser.fftSize);
3369
+ const tracks = typeof stream.getAudioTracks === "function"
3370
+ ? stream
3371
+ .getAudioTracks()
3372
+ .filter((track) => track.readyState === "live")
3373
+ : [];
3374
+ const contextWithTrackSource = context;
3375
+ for (const track of tracks) {
3376
+ let source;
3377
+ if (typeof contextWithTrackSource.createMediaStreamTrackSource ===
3378
+ "function") {
3379
+ source = contextWithTrackSource.createMediaStreamTrackSource(track);
3380
+ }
3381
+ else if (tracks.length === 1) {
3382
+ source = context.createMediaStreamSource(stream);
3383
+ }
3384
+ else if (typeof MediaStream === "function") {
3385
+ const isolatedStream = new MediaStream([track]);
3386
+ this.outputAnalysisStreams.push(isolatedStream);
3387
+ source = context.createMediaStreamSource(isolatedStream);
3388
+ }
3389
+ else {
3390
+ throw new Error("Multiple remote audio tracks cannot be analysed.");
3391
+ }
3392
+ source.connect(this.outputAnalyser);
3393
+ this.outputSources.push(source);
3394
+ this.outputAnalysedTracks.add(track);
3395
+ }
3396
+ if (this.outputSources.length === 0) {
3397
+ this.disconnectOutputAnalyser();
3398
+ }
2820
3399
  }
2821
3400
  catch {
2822
- this.outputSource = null;
2823
- this.outputAnalyser = null;
2824
- this.levelBuffer = null;
2825
- }
3401
+ this.disconnectOutputAnalyser();
3402
+ }
3403
+ }
3404
+ outputAnalyserMatchesStream(stream) {
3405
+ const liveTracks = typeof stream.getAudioTracks === "function"
3406
+ ? stream.getAudioTracks().filter((track) => track.readyState === "live")
3407
+ : [];
3408
+ return Boolean(this.outputAnalyser &&
3409
+ liveTracks.length === this.outputAnalysedTracks.size &&
3410
+ liveTracks.every((track) => this.outputAnalysedTracks.has(track)));
3411
+ }
3412
+ disconnectOutputAnalyser() {
3413
+ for (const source of this.outputSources)
3414
+ source.disconnect();
3415
+ this.outputSources = [];
3416
+ this.outputAnalysisStreams = [];
3417
+ this.outputAnalysedTracks.clear();
3418
+ this.outputAnalyser?.disconnect();
3419
+ this.outputAnalyser = null;
3420
+ this.outputSilentSink?.disconnect();
3421
+ this.outputSilentSink = null;
3422
+ this.outputEvidenceFloatBuffer = null;
3423
+ this.outputEvidenceByteBuffer = null;
2826
3424
  }
2827
3425
  startLevelLoop() {
2828
3426
  if (this.levelFrame !== null ||
@@ -2864,6 +3462,12 @@ class VoicePresenceView {
2864
3462
  this.host.style.setProperty("--voice-level", "0");
2865
3463
  }
2866
3464
  stopAudio() {
3465
+ this.playbackGeneration += 1;
3466
+ this.playbackResumePending = false;
3467
+ this.unbindPlaybackState();
3468
+ this.outputEvidenceCandidateUntil = 0;
3469
+ this.stopOutputEvidenceSampling();
3470
+ this.resetOutputEvidenceState();
2867
3471
  this.stopLevelLoop();
2868
3472
  this.audio.pause();
2869
3473
  const remoteStream = this.audio.srcObject;
@@ -2874,15 +3478,16 @@ class VoicePresenceView {
2874
3478
  for (const track of remoteStream.getTracks())
2875
3479
  track.stop();
2876
3480
  }
2877
- this.outputSource?.disconnect();
2878
- this.outputSource = null;
2879
- this.outputAnalyser?.disconnect();
2880
- this.outputAnalyser = null;
3481
+ this.disconnectOutputAnalyser();
2881
3482
  this.inputSource?.disconnect();
2882
3483
  this.inputSource = null;
2883
3484
  this.inputAnalyser?.disconnect();
2884
3485
  this.inputAnalyser = null;
2885
3486
  this.levelBuffer = null;
3487
+ if (this.audioContext && this.audioContextStateListener) {
3488
+ this.audioContext.removeEventListener?.("statechange", this.audioContextStateListener);
3489
+ }
3490
+ this.audioContextStateListener = null;
2886
3491
  if (this.audioContext)
2887
3492
  void this.audioContext.close().catch(() => undefined);
2888
3493
  this.audioContext = null;
@@ -2912,9 +3517,6 @@ class VoicePresenceView {
2912
3517
  activeAnalyser() {
2913
3518
  if (this.stateMachine.state === "active.listening")
2914
3519
  return this.inputAnalyser;
2915
- if (this.stateMachine.state === "active.speaking" && !this.audio.paused) {
2916
- return this.outputAnalyser;
2917
- }
2918
3520
  return null;
2919
3521
  }
2920
3522
  legalLink(url, label) {