dsh-voice-mode 0.7.28 → 0.7.29

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.
package/lib/client.js CHANGED
@@ -496,6 +496,10 @@ function createAsrEngine(config, sessionId) {
496
496
  let partialInFlight = false;
497
497
  let resetGate = Promise.resolve();
498
498
  let segmentEpoch = 0;
499
+ let discardGen = 0;
500
+ let finalizeSeq = 0;
501
+ let nextEmitSeq = 1;
502
+ const pendingFinals = /* @__PURE__ */ new Map();
499
503
  let wakeSilenceMs = 0;
500
504
  let wakeConsumed = false;
501
505
  let forcePending = false;
@@ -510,6 +514,7 @@ function createAsrEngine(config, sessionId) {
510
514
  let preRollStartWall = 0;
511
515
  let preRollSeedWall = null;
512
516
  let wasPlaying = false;
517
+ let rawPlayingSinceWall = 0;
513
518
  let gateQueryScope = false;
514
519
  let partialFailStreak = 0;
515
520
  let detectFailStreak = 0;
@@ -539,6 +544,18 @@ function createAsrEngine(config, sessionId) {
539
544
  }
540
545
  }
541
546
  };
547
+ const flushOrderedFinals = () => {
548
+ while (pendingFinals.has(nextEmitSeq)) {
549
+ const item = pendingFinals.get(nextEmitSeq);
550
+ pendingFinals.delete(nextEmitSeq);
551
+ nextEmitSeq++;
552
+ if (item) emit(transcriptListeners, item.text, item.meta);
553
+ }
554
+ };
555
+ const settleFinal = (seq, item) => {
556
+ pendingFinals.set(seq, item);
557
+ flushOrderedFinals();
558
+ };
542
559
  const resetFailStreaks = () => {
543
560
  partialFailStreak = 0;
544
561
  detectFailStreak = 0;
@@ -607,6 +624,10 @@ function createAsrEngine(config, sessionId) {
607
624
  }, 5e3);
608
625
  });
609
626
  res = retry;
627
+ if (res.status === 202) {
628
+ if (epoch === segmentEpoch && active && state !== "wake") setState("loading-model");
629
+ return;
630
+ }
610
631
  }
611
632
  if (res.status === 403 && config.onSessionExpired) {
612
633
  const recovered = await config.onSessionExpired();
@@ -693,7 +714,10 @@ function createAsrEngine(config, sessionId) {
693
714
  if (!res.ok) return;
694
715
  const out = await res.json();
695
716
  if (epoch !== segmentEpoch || gen !== detectGeneration) return;
696
- if (out.isSpeech === true && preRollSeedWall === null) preRollSeedWall = reqBodyStartWall - 250;
717
+ const rawNow = config.isPlayingRaw ? config.isPlayingRaw() : config.isPlaying?.() ?? false;
718
+ if (out.isSpeech === true && preRollSeedWall === null && rawNow && reqBodyStartWall >= rawPlayingSinceWall) {
719
+ preRollSeedWall = reqBodyStartWall - 250;
720
+ }
697
721
  if (out.isSpeech !== void 0) deliverIsSpeech(out.isSpeech);
698
722
  detectFailStreak = 0;
699
723
  detectSent += samples.length;
@@ -741,6 +765,7 @@ function createAsrEngine(config, sessionId) {
741
765
  partialFailStreak = 0;
742
766
  detectFailStreak = 0;
743
767
  segmentEpoch++;
768
+ discardGen++;
744
769
  segment = [];
745
770
  segmentMs = 0;
746
771
  speechMs = 0;
@@ -766,6 +791,14 @@ function createAsrEngine(config, sessionId) {
766
791
  const recoverySegment = segment;
767
792
  const epochSnapshot = segmentEpoch;
768
793
  segmentEpoch++;
794
+ const discardSnapshot = discardGen;
795
+ const mySeq = ++finalizeSeq;
796
+ let settled = false;
797
+ const settle = (item) => {
798
+ if (settled) return;
799
+ settled = true;
800
+ settleFinal(mySeq, item);
801
+ };
769
802
  const meta = { force: forcePending };
770
803
  const consumedWake = wakeConsumed;
771
804
  wakeConsumed = false;
@@ -788,7 +821,10 @@ function createAsrEngine(config, sessionId) {
788
821
  const restoreState = () => setState(active ? speechActive || holdActive ? "speech" : wakeEnabled ? "wake" : "listening" : "idle");
789
822
  for (let attempt = 0; attempt < MAX_FINAL_ATTEMPTS; attempt++) {
790
823
  if (attempt > 0) {
791
- if (segmentEpoch !== epochSnapshot + 1) return;
824
+ if (discardGen !== discardSnapshot) {
825
+ settle(null);
826
+ return;
827
+ }
792
828
  await new Promise((r) => setTimeout(r, 500 * attempt));
793
829
  }
794
830
  const useFull = attempt > 0;
@@ -832,8 +868,16 @@ function createAsrEngine(config, sessionId) {
832
868
  continue;
833
869
  }
834
870
  if (res.status === 403 && config.onSessionExpired) {
835
- const recovered = await config.onSessionExpired();
836
- if (recovered && segmentEpoch === epochSnapshot + 1) {
871
+ let expireTimer = null;
872
+ const recovered = await Promise.race([
873
+ config.onSessionExpired(),
874
+ new Promise((resolve) => {
875
+ expireTimer = setTimeout(() => resolve(false), 5e3);
876
+ })
877
+ ]).finally(() => {
878
+ if (expireTimer) clearTimeout(expireTimer);
879
+ }).catch(() => false);
880
+ if (recovered && discardGen === discardSnapshot) {
837
881
  try {
838
882
  res = await fetch(asrUrl(true, 0, epochSnapshot), {
839
883
  signal: AbortSignal.timeout(25e3),
@@ -857,7 +901,10 @@ function createAsrEngine(config, sessionId) {
857
901
  if (attempt === MAX_FINAL_ATTEMPTS - 1) console.warn("[dsh-voice-mode] finalize response is not JSON (retries exhausted)");
858
902
  continue;
859
903
  }
860
- if (segmentEpoch !== epochSnapshot + 1) return;
904
+ if (discardGen !== discardSnapshot) {
905
+ settle(null);
906
+ return;
907
+ }
861
908
  resetFailStreaks();
862
909
  restoreState();
863
910
  const rawText = out.text ?? "";
@@ -866,17 +913,25 @@ function createAsrEngine(config, sessionId) {
866
913
  if ((wasSalvaged || wasYielded) && matchBackchannel(finalText)) {
867
914
  emit(noticeListeners, "backchannelDropped");
868
915
  if (active && wakeEnabled) setState("listening");
916
+ settle(null);
869
917
  return;
870
918
  }
871
- emit(transcriptListeners, finalText, meta);
872
- } else if (consumedWake && active && !speechActive && !holdActive) {
873
- setState("listening");
919
+ settle({ text: finalText, meta });
920
+ } else {
921
+ settle(null);
922
+ if (consumedWake && active && !speechActive && !holdActive) {
923
+ setState("listening");
924
+ }
874
925
  }
875
926
  return;
876
927
  }
877
928
  restoreState();
929
+ settle(null);
878
930
  emitError("recognitionFail");
879
- })();
931
+ })().catch((err) => {
932
+ console.warn(`[dsh-voice-mode] finalize unexpected error (seq=${mySeq}, settled as no-emit)`, err);
933
+ settle(null);
934
+ });
880
935
  };
881
936
  let latestResidualRms = 0;
882
937
  let echoFloorRms = 0;
@@ -915,6 +970,7 @@ function createAsrEngine(config, sessionId) {
915
970
  }
916
971
  }
917
972
  const playingNow = config.isPlaying?.() ?? false;
973
+ const rawNow = config.isPlayingRaw ? config.isPlayingRaw() : playingNow;
918
974
  const gateRatio = Math.pow(10, (config.echoGateDb ?? 6) / 20);
919
975
  const peakDecay = Math.pow(0.9, durationMs / 64);
920
976
  const floorAlpha = 1 - Math.pow(0.98, durationMs / 64);
@@ -947,7 +1003,7 @@ function createAsrEngine(config, sessionId) {
947
1003
  }
948
1004
  if (playingNow && !holdActive && config.mode !== "hold") {
949
1005
  detectChunks.push(data);
950
- if (salvageEnabled) {
1006
+ if (salvageEnabled && rawNow) {
951
1007
  if (preRoll.length === 0) preRollStartWall = Date.now();
952
1008
  preRoll.push(data);
953
1009
  preRollMs += durationMs;
@@ -959,14 +1015,13 @@ function createAsrEngine(config, sessionId) {
959
1015
  }
960
1016
  }
961
1017
  }
962
- if (playingNow && !wasPlaying) {
963
- wasPlaying = true;
1018
+ if (rawNow !== wasPlaying) {
1019
+ wasPlaying = rawNow;
1020
+ if (rawNow) rawPlayingSinceWall = Date.now() - durationMs;
964
1021
  preRollSeedWall = null;
965
1022
  preRoll = [];
966
1023
  preRollMs = 0;
967
1024
  preRollStartWall = 0;
968
- } else if (!playingNow && wasPlaying) {
969
- wasPlaying = false;
970
1025
  }
971
1026
  if (holdActive) {
972
1027
  if (!speechActive) {
@@ -1021,6 +1076,8 @@ function createAsrEngine(config, sessionId) {
1021
1076
  segment.push(data);
1022
1077
  if (segmentMs > MAX_SEGMENT_MS) finalizeSegment();
1023
1078
  }
1079
+ } else if (speechActive && config.isPlaying?.()) {
1080
+ finalizeSegment(true);
1024
1081
  } else if (speechActive) {
1025
1082
  if (utteranceEndAt === null) {
1026
1083
  utteranceEndAt = Date.now();
@@ -1034,6 +1091,7 @@ function createAsrEngine(config, sessionId) {
1034
1091
  finalizeSegment();
1035
1092
  } else {
1036
1093
  segmentEpoch++;
1094
+ discardGen++;
1037
1095
  segment = [];
1038
1096
  speechActive = false;
1039
1097
  salvagedSegment = false;
@@ -1074,6 +1132,7 @@ function createAsrEngine(config, sessionId) {
1074
1132
  } catch {
1075
1133
  }
1076
1134
  if (stream === myStream) stream = null;
1135
+ if (!myCtx) return;
1077
1136
  try {
1078
1137
  await myCtx.close();
1079
1138
  } catch {
@@ -1081,6 +1140,15 @@ function createAsrEngine(config, sessionId) {
1081
1140
  if (audioCtx === myCtx) audioCtx = null;
1082
1141
  };
1083
1142
  const startRecorder = async () => {
1143
+ const owned = {};
1144
+ try {
1145
+ await startRecorderInner(owned);
1146
+ } catch (error) {
1147
+ if (owned.stream) await abandonStart(owned.stream, owned.ctx ?? null);
1148
+ throw error;
1149
+ }
1150
+ };
1151
+ const startRecorderInner = async (owned) => {
1084
1152
  const mySeq = startSeq;
1085
1153
  const myStream = await navigator.mediaDevices.getUserMedia({
1086
1154
  audio: {
@@ -1094,6 +1162,7 @@ function createAsrEngine(config, sessionId) {
1094
1162
  autoGainControl: false
1095
1163
  }
1096
1164
  });
1165
+ owned.stream = myStream;
1097
1166
  if (stopRequested || mySeq !== startSeq) {
1098
1167
  myStream.getTracks().forEach((t3) => t3.stop());
1099
1168
  return;
@@ -1109,6 +1178,7 @@ function createAsrEngine(config, sessionId) {
1109
1178
  config.onAecState?.(aecOn);
1110
1179
  const AC = window.AudioContext ?? window.webkitAudioContext;
1111
1180
  const myCtx = new AC({ sampleRate: SAMPLE_RATE2 });
1181
+ owned.ctx = myCtx;
1112
1182
  audioCtx = myCtx;
1113
1183
  try {
1114
1184
  await audioCtx.resume?.();
@@ -1164,6 +1234,7 @@ function createAsrEngine(config, sessionId) {
1164
1234
  const myCtx = audioCtx;
1165
1235
  inFlush = true;
1166
1236
  segmentEpoch++;
1237
+ discardGen++;
1167
1238
  forcePending = false;
1168
1239
  holdActive = false;
1169
1240
  segment = [];
@@ -1243,6 +1314,7 @@ function createAsrEngine(config, sessionId) {
1243
1314
  startSeq++;
1244
1315
  const myStartSeq = startSeq;
1245
1316
  segmentEpoch++;
1317
+ discardGen++;
1246
1318
  partialFailStreak = 0;
1247
1319
  detectFailStreak = 0;
1248
1320
  lastPollAt = 0;
@@ -1292,6 +1364,7 @@ function createAsrEngine(config, sessionId) {
1292
1364
  if (!active || holdActive) return;
1293
1365
  holdActive = true;
1294
1366
  segmentEpoch++;
1367
+ discardGen++;
1295
1368
  wakeConsumed = false;
1296
1369
  salvagedSegment = false;
1297
1370
  yieldedSegment = false;
@@ -1312,6 +1385,7 @@ function createAsrEngine(config, sessionId) {
1312
1385
  },
1313
1386
  discardSegment() {
1314
1387
  segmentEpoch++;
1388
+ discardGen++;
1315
1389
  partialFailStreak = 0;
1316
1390
  detectFailStreak = 0;
1317
1391
  segment = [];
@@ -1369,7 +1443,9 @@ function createAsrEngine(config, sessionId) {
1369
1443
  holdActive = false;
1370
1444
  if (cancel) {
1371
1445
  segmentEpoch++;
1446
+ discardGen++;
1372
1447
  segment = [];
1448
+ uploadedSamples = 0;
1373
1449
  salvagedSegment = false;
1374
1450
  yieldedSegment = false;
1375
1451
  resetFailStreaks();
@@ -2453,6 +2529,16 @@ function createScopeBridge(raw) {
2453
2529
  }
2454
2530
  };
2455
2531
  }
2532
+ var RENEW_WHILE_HIDDEN = true;
2533
+ var IDLE_USER_ACTIVITY_CAP_MS = 2 * 60 * 60 * 1e3;
2534
+ function idleBusy(input) {
2535
+ if (input.hidden && !RENEW_WHILE_HIDDEN) return false;
2536
+ return input.playing || input.turn === "agent-speaking" || input.running;
2537
+ }
2538
+ function idleAction(input) {
2539
+ if (input.busy && input.sinceUserActivityMs <= IDLE_USER_ACTIVITY_CAP_MS) return "renew";
2540
+ return input.warn ? "warn" : "exit";
2541
+ }
2456
2542
 
2457
2543
  // src/runtime-boot.ts
2458
2544
  var runtimeBoot = null;
@@ -3749,7 +3835,8 @@ function VoiceSettingsCard({ scope, defaultOpen = false }) {
3749
3835
  var SETTINGS_URL = "/voice-mode/settings";
3750
3836
  var RETRY_BASE_MS = 500;
3751
3837
  var RETRY_MAX_MS = 1e4;
3752
- function createHttpScope(origin = location.origin, fetchImpl = fetch) {
3838
+ var REQUEST_TIMEOUT_MS = 8e3;
3839
+ function createHttpScope(origin = location.origin, fetchImpl = fetch, timeoutMs = REQUEST_TIMEOUT_MS) {
3753
3840
  let snap = { status: "loading", value: {} };
3754
3841
  const subs = /* @__PURE__ */ new Set();
3755
3842
  let inFlight = false;
@@ -3785,7 +3872,7 @@ function createHttpScope(origin = location.origin, fetchImpl = fetch) {
3785
3872
  clearRetry();
3786
3873
  const myGen = writeGen;
3787
3874
  try {
3788
- const res = await fetchImpl(origin + SETTINGS_URL);
3875
+ const res = await fetchImpl(origin + SETTINGS_URL, { signal: AbortSignal.timeout(timeoutMs) });
3789
3876
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
3790
3877
  const data = await res.json();
3791
3878
  retryDelay = 0;
@@ -3839,7 +3926,8 @@ function createHttpScope(origin = location.origin, fetchImpl = fetch) {
3839
3926
  const res = await fetchImpl(origin + SETTINGS_URL, {
3840
3927
  method: "POST",
3841
3928
  headers: { "content-type": "application/json" },
3842
- body: JSON.stringify({ [field]: value })
3929
+ body: JSON.stringify({ [field]: value }),
3930
+ signal: AbortSignal.timeout(timeoutMs)
3843
3931
  });
3844
3932
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
3845
3933
  const data = await res.json();
@@ -3896,7 +3984,7 @@ function telemetryDeltas(tel) {
3896
3984
  }
3897
3985
  return out;
3898
3986
  }
3899
- var BUILD_TAG = "dc828c8";
3987
+ var BUILD_TAG = "5c6d521";
3900
3988
  var TELEMETRY_FLAG = "dsh-voice-mode.telemetry";
3901
3989
  var telemetryEnabled = typeof localStorage !== "undefined" && localStorage.getItem(TELEMETRY_FLAG) === "1";
3902
3990
  console.log("[dsh-voice] build=" + BUILD_TAG);
@@ -3930,6 +4018,7 @@ var SAMPLE_RATE_16K = 16e3;
3930
4018
  var ECHO_DELAY_MS = 0;
3931
4019
  var AUTO_SEND_EXTRA_MS = 1200;
3932
4020
  var ECHO_TAIL_MS = 400;
4021
+ var TOGGLE_TIMEOUT_MS = 8e3;
3933
4022
  var HOLD_CLEAR_FRAMES = 2;
3934
4023
  var WAVE_BARS = 14;
3935
4024
  var BASE_PATH2 = "/voice-mode";
@@ -4134,6 +4223,8 @@ function createAudioEngine(setUi, onPlayed, onPlaybackRef, onAllPlayed) {
4134
4223
  const pending = [];
4135
4224
  const fallbackAudio = new Audio();
4136
4225
  let fallback = false;
4226
+ let decodeFailStreak = 0;
4227
+ let fallbackBusy = false;
4137
4228
  let ctx = null;
4138
4229
  let duckGain = null;
4139
4230
  let analyser = null;
@@ -4169,19 +4260,23 @@ function createAudioEngine(setUi, onPlayed, onPlaybackRef, onAllPlayed) {
4169
4260
  const playFallback = () => {
4170
4261
  const frame = pending.shift() ?? null;
4171
4262
  if (!frame) {
4263
+ fallbackBusy = false;
4172
4264
  setUi({ playing: false, playingCaption: null });
4173
4265
  return;
4174
4266
  }
4267
+ fallbackBusy = true;
4175
4268
  const url = URL.createObjectURL(new Blob([frame.audio], { type: frame.mime === "audio/wav" ? "audio/wav" : "audio/mpeg" }));
4176
4269
  fallbackAudio.src = url;
4177
- fallbackAudio.onended = () => {
4270
+ const next = () => {
4178
4271
  URL.revokeObjectURL(url);
4179
- playFallback();
4180
- };
4181
- fallbackAudio.onerror = () => {
4182
- URL.revokeObjectURL(url);
4183
- playFallback();
4272
+ fallbackBusy = false;
4273
+ if (!fallback && ctx) {
4274
+ if (pending.length > 0) drainPending();
4275
+ else setUi({ playing: false, playingCaption: null });
4276
+ } else playFallback();
4184
4277
  };
4278
+ fallbackAudio.onended = next;
4279
+ fallbackAudio.onerror = next;
4185
4280
  fallbackAudio.onplaying = () => {
4186
4281
  try {
4187
4282
  onPlayed?.();
@@ -4202,13 +4297,14 @@ function createAudioEngine(setUi, onPlayed, onPlaybackRef, onAllPlayed) {
4202
4297
  void fallbackAudio.play().catch(() => playFallback());
4203
4298
  };
4204
4299
  const drainPending = () => {
4205
- if (decoding || !ctx || !duckGain || pending.length === 0) return;
4300
+ if (decoding || fallbackBusy || !ctx || !duckGain || pending.length === 0) return;
4206
4301
  decoding = true;
4207
4302
  void (async () => {
4208
4303
  try {
4209
4304
  while (pending.length > 0) {
4210
4305
  const frame = pending[0];
4211
4306
  const buf = await ctx.decodeAudioData(frame.audio.buffer.slice(0));
4307
+ decodeFailStreak = 0;
4212
4308
  if (pending.length === 0 || pending[0] !== frame) return;
4213
4309
  pending.shift();
4214
4310
  const t0 = ctx.currentTime;
@@ -4252,7 +4348,7 @@ function createAudioEngine(setUi, onPlayed, onPlaybackRef, onAllPlayed) {
4252
4348
  }
4253
4349
  activeSrcs.clear();
4254
4350
  captionQueue.length = 0;
4255
- fallback = true;
4351
+ if (++decodeFailStreak >= 2) fallback = true;
4256
4352
  playFallback();
4257
4353
  } finally {
4258
4354
  decoding = false;
@@ -4272,6 +4368,7 @@ function createAudioEngine(setUi, onPlayed, onPlaybackRef, onAllPlayed) {
4272
4368
  },
4273
4369
  skip() {
4274
4370
  pending.length = 0;
4371
+ fallbackBusy = false;
4275
4372
  nextEndAt = 0;
4276
4373
  fallbackAudio.pause();
4277
4374
  fallbackAudio.onended = null;
@@ -4287,6 +4384,10 @@ function createAudioEngine(setUi, onPlayed, onPlaybackRef, onAllPlayed) {
4287
4384
  setUi({ playing: false, playingCaption: null });
4288
4385
  },
4289
4386
  warm,
4387
+ resetFallback() {
4388
+ fallback = false;
4389
+ decodeFailStreak = 0;
4390
+ },
4290
4391
  unduck() {
4291
4392
  if (!ctx || !duckGain) return;
4292
4393
  const now = ctx.currentTime;
@@ -4555,6 +4656,7 @@ function createVoiceBus(basePath = BASE_PATH2, ctx) {
4555
4656
  if (source) return;
4556
4657
  source = new EventSource(`${location.origin}${basePath}/stream?tabId=${encodeURIComponent(TAB_ID)}`);
4557
4658
  source.addEventListener("open", () => {
4659
+ engine.resetFallback();
4558
4660
  rejectSeqUpTo.clear();
4559
4661
  lastFinalSeq.clear();
4560
4662
  curSentenceId = null;
@@ -4872,11 +4974,14 @@ function createVoiceBus(basePath = BASE_PATH2, ctx) {
4872
4974
  return playingEndAt + ECHO_TAIL_MS + refDelaySamples / SAMPLE_RATE_16K * 1e3;
4873
4975
  },
4874
4976
  async enter(sessionId) {
4977
+ engine.resetFallback();
4875
4978
  try {
4876
4979
  const res = await fetch(`${location.origin}${basePath}/toggle`, {
4877
4980
  method: "POST",
4878
4981
  headers: { "content-type": "application/json" },
4879
- body: JSON.stringify({ sessionId, on: true, tabId: TAB_ID, lang: activeLocale() })
4982
+ body: JSON.stringify({ sessionId, on: true, tabId: TAB_ID, lang: activeLocale() }),
4983
+ signal: AbortSignal.timeout(TOGGLE_TIMEOUT_MS)
4984
+ // I-7:宿主无响应不再让按钮永久 pending
4880
4985
  });
4881
4986
  const out = await res.json();
4882
4987
  activeSessionId = out.active === sessionId ? sessionId : null;
@@ -4890,10 +4995,18 @@ function createVoiceBus(basePath = BASE_PATH2, ctx) {
4890
4995
  error: out.active === sessionId ? void 0 : t("enterFail")
4891
4996
  };
4892
4997
  } catch {
4998
+ void fetch(`${location.origin}${basePath}/toggle`, {
4999
+ method: "POST",
5000
+ headers: { "content-type": "application/json" },
5001
+ body: JSON.stringify({ sessionId, on: false, tabId: TAB_ID }),
5002
+ signal: AbortSignal.timeout(TOGGLE_TIMEOUT_MS)
5003
+ }).catch(() => {
5004
+ });
4893
5005
  return { ok: false, error: t("enterFail") };
4894
5006
  }
4895
5007
  },
4896
5008
  async exit(sessionId, keepAudio) {
5009
+ engine.resetFallback();
4897
5010
  resetTelemetry();
4898
5011
  ui.turn = "idle";
4899
5012
  if (!keepAudio) {
@@ -4903,7 +5016,9 @@ function createVoiceBus(basePath = BASE_PATH2, ctx) {
4903
5016
  const res = await fetch(`${location.origin}${basePath}/toggle`, {
4904
5017
  method: "POST",
4905
5018
  headers: { "content-type": "application/json" },
4906
- body: JSON.stringify({ sessionId, on: false, tabId: TAB_ID })
5019
+ body: JSON.stringify({ sessionId, on: false, tabId: TAB_ID }),
5020
+ signal: AbortSignal.timeout(TOGGLE_TIMEOUT_MS)
5021
+ // I-7
4907
5022
  });
4908
5023
  await res.json();
4909
5024
  activeSessionId = null;
@@ -5150,6 +5265,7 @@ function MicButton({
5150
5265
  const sidRef = (0, import_react3.useRef)(sessionId);
5151
5266
  const engineRef = (0, import_react3.useRef)(null);
5152
5267
  const micReadyRef = (0, import_react3.useRef)(false);
5268
+ const enterEpochRef = (0, import_react3.useRef)(0);
5153
5269
  const actionsRef = (0, import_react3.useRef)(inputActions);
5154
5270
  const submitTimerRef = (0, import_react3.useRef)(null);
5155
5271
  const autoSendTimerRef = (0, import_react3.useRef)(null);
@@ -5157,6 +5273,7 @@ function MicButton({
5157
5273
  const idleWarnTimerRef = (0, import_react3.useRef)(null);
5158
5274
  const idleWarnActiveRef = (0, import_react3.useRef)(false);
5159
5275
  const idleClearErrorRef = (0, import_react3.useRef)(null);
5276
+ const idleUserActivityAtRef = (0, import_react3.useRef)(Date.now());
5160
5277
  const runningRef = (0, import_react3.useRef)(false);
5161
5278
  const mountedRef = (0, import_react3.useRef)(true);
5162
5279
  const holdCtrlRef = (0, import_react3.useRef)(false);
@@ -5217,7 +5334,7 @@ function MicButton({
5217
5334
  };
5218
5335
  const fetchConfig = async () => {
5219
5336
  try {
5220
- const res = await fetch(`${location.origin}${BASE_PATH2}/config`);
5337
+ const res = await fetch(`${location.origin}${BASE_PATH2}/config`, { signal: AbortSignal.timeout(TOGGLE_TIMEOUT_MS) });
5221
5338
  if (!res.ok) return bootNow();
5222
5339
  const c = await res.json();
5223
5340
  const cur = bootNow();
@@ -5259,6 +5376,12 @@ function MicButton({
5259
5376
  return bootNow();
5260
5377
  }
5261
5378
  };
5379
+ const idleBusyNow = () => idleBusy({
5380
+ playing: bus.ui.playing,
5381
+ turn: bus.ui.turn,
5382
+ running: runningRef.current,
5383
+ hidden: document.hidden
5384
+ });
5262
5385
  const clearIdle = () => {
5263
5386
  if (idleTimerRef.current) {
5264
5387
  clearTimeout(idleTimerRef.current);
@@ -5277,12 +5400,22 @@ function MicButton({
5277
5400
  bus.setUi({ idleWarn: false });
5278
5401
  }
5279
5402
  };
5280
- const resetIdle = () => {
5403
+ const resetIdle = (userActivity = true) => {
5281
5404
  clearIdle();
5405
+ if (userActivity) idleUserActivityAtRef.current = Date.now();
5282
5406
  const idleMs = (bootNow().idleTimeoutMinutes > 0 ? bootNow().idleTimeoutMinutes : 10) * 60 * 1e3;
5283
5407
  if (idleMs > 3e4) {
5284
5408
  idleWarnTimerRef.current = setTimeout(() => {
5285
5409
  idleWarnTimerRef.current = null;
5410
+ const action = idleAction({
5411
+ busy: idleBusyNow(),
5412
+ warn: true,
5413
+ sinceUserActivityMs: Date.now() - idleUserActivityAtRef.current
5414
+ });
5415
+ if (action === "renew") {
5416
+ resetIdle(false);
5417
+ return;
5418
+ }
5286
5419
  idleWarnActiveRef.current = true;
5287
5420
  bus.setUi({ idleWarn: true });
5288
5421
  }, idleMs - 3e4);
@@ -5291,6 +5424,15 @@ function MicButton({
5291
5424
  idleTimerRef.current = null;
5292
5425
  const sid = sidRef.current;
5293
5426
  if (localRef.current === "on" && sid) {
5427
+ const action = idleAction({
5428
+ busy: idleBusyNow(),
5429
+ warn: false,
5430
+ sinceUserActivityMs: Date.now() - idleUserActivityAtRef.current
5431
+ });
5432
+ if (action === "renew") {
5433
+ resetIdle(false);
5434
+ return;
5435
+ }
5294
5436
  const quitMsg = t("idleTimeoutQuit");
5295
5437
  void exitModeRef.current("idle").then(() => {
5296
5438
  bus.setUi({ error: bus.ui.error ?? quitMsg });
@@ -5552,6 +5694,10 @@ function MicButton({
5552
5694
  const sid = sidRef.current;
5553
5695
  if (sid) await bus.exit(sid, reason === "typing");
5554
5696
  };
5697
+ const cancelPending = () => {
5698
+ enterEpochRef.current++;
5699
+ void exitModeRef.current("manual");
5700
+ };
5555
5701
  const enterMode = async () => {
5556
5702
  const sid = sidRef.current;
5557
5703
  if (!sid || localRef.current !== "off") return;
@@ -5559,10 +5705,11 @@ function MicButton({
5559
5705
  isSpeechFalseRun = 0;
5560
5706
  micReadyRef.current = false;
5561
5707
  setLocalMode("pending");
5708
+ const myEnter = ++enterEpochRef.current;
5562
5709
  try {
5563
5710
  const entered = await bus.enter(sid);
5564
- if (!mountedRef.current) {
5565
- if (entered.ok) void bus.exit(sid);
5711
+ if (!mountedRef.current || enterEpochRef.current !== myEnter) {
5712
+ if (entered.ok && localRef.current === "off") void bus.exit(sid);
5566
5713
  return;
5567
5714
  }
5568
5715
  if (!entered.ok) {
@@ -5575,6 +5722,10 @@ function MicButton({
5575
5722
  return;
5576
5723
  }
5577
5724
  const cfg = await fetchConfig();
5725
+ if (enterEpochRef.current !== myEnter) {
5726
+ if (localRef.current === "off") void bus.exit(sid);
5727
+ return;
5728
+ }
5578
5729
  const basePath = cfg.basePath;
5579
5730
  const silenceMs = cfg.silenceMs;
5580
5731
  const interruptLevel = cfg.interruptLevel;
@@ -5637,6 +5788,8 @@ function MicButton({
5637
5788
  echo: bus.echoForAsr(),
5638
5789
  // 回声尾音宽限:playing 或尾音窗口内均视为朗读中,防句播完瞬间的残响漏入 ASR。
5639
5790
  isPlaying: () => bus.ui.playing || Date.now() < bus.playingTailUntil(),
5791
+ // I-18:裸播放态(不含尾窗),预录环/抢救种子以它划句边界。
5792
+ isPlayingRaw: () => bus.ui.playing,
5640
5793
  // 打断根治阶段二:服务端 Silero VAD 帧级检测下行 → 驱动打断(替代 RMS 能量快
5641
5794
  // 路径)。连续 confirmFrames 次 true(墙钟节拍 100ms/拍,三档确认约 0.3/0.2/0.1s)
5642
5795
  // 判真实人声前沿;仅 AI 朗读中(bus.ui.playing)触发 hardBreak,
@@ -5862,10 +6015,10 @@ function MicButton({
5862
6015
  return;
5863
6016
  }
5864
6017
  await engine.start();
5865
- if (!mountedRef.current) {
5866
- engineRef.current = null;
6018
+ if (!mountedRef.current || enterEpochRef.current !== myEnter) {
6019
+ if (engineRef.current === engine) engineRef.current = null;
5867
6020
  await engine.stop();
5868
- void bus.exit(sid);
6021
+ if (!mountedRef.current || localRef.current === "off") void bus.exit(sid);
5869
6022
  return;
5870
6023
  }
5871
6024
  if (bus.activeSessionId !== sid) {
@@ -5892,6 +6045,8 @@ function MicButton({
5892
6045
  }
5893
6046
  }
5894
6047
  } catch (e) {
6048
+ if (enterEpochRef.current !== myEnter) return;
6049
+ engineRef.current = null;
5895
6050
  pendingHoldRef.current = false;
5896
6051
  pendingHoldReleaseRef.current = false;
5897
6052
  clearHoldExit();
@@ -5915,6 +6070,7 @@ function MicButton({
5915
6070
  if (!takeToggleSlot(toggleHistRef.current, Date.now())) return;
5916
6071
  if (localRef.current === "on") void exitModeRef.current("manual");
5917
6072
  else if (localRef.current === "off") void enterMode();
6073
+ else if (localRef.current === "pending") cancelPending();
5918
6074
  };
5919
6075
  const toggleRef = (0, import_react3.useRef)(toggle);
5920
6076
  toggleRef.current = toggle;
@@ -6374,6 +6530,8 @@ function MicButton({
6374
6530
  if (localRef.current === "on") {
6375
6531
  engineRef.current?.endHeld(true);
6376
6532
  void exitModeRef.current("manual");
6533
+ } else if (localRef.current === "pending") {
6534
+ cancelPending();
6377
6535
  } else {
6378
6536
  void enterMode();
6379
6537
  }
@@ -6615,8 +6773,6 @@ function VoiceStatusBar({ bus, sessionId }) {
6615
6773
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
6616
6774
  "div",
6617
6775
  {
6618
- role: "status",
6619
- "aria-live": "polite",
6620
6776
  style: {
6621
6777
  display: "flex",
6622
6778
  flexDirection: "column",
@@ -6635,6 +6791,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6635
6791
  botBars.some((v) => v > 0) && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6636
6792
  "span",
6637
6793
  {
6794
+ "aria-hidden": "true",
6638
6795
  title: t("botLevelsHint"),
6639
6796
  style: {
6640
6797
  display: "inline-flex",
@@ -6657,7 +6814,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6657
6814
  ))
6658
6815
  }
6659
6816
  ),
6660
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { display: "inline-flex", alignItems: "flex-end", gap: 2, height: 14, flexShrink: 0 }, children: bars.map((v, i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6817
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { "aria-hidden": "true", style: { display: "inline-flex", alignItems: "flex-end", gap: 2, height: 14, flexShrink: 0 }, children: bars.map((v, i) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6661
6818
  "span",
6662
6819
  {
6663
6820
  className: "dshvm-bar",
@@ -6669,7 +6826,32 @@ function VoiceStatusBar({ bus, sessionId }) {
6669
6826
  },
6670
6827
  i
6671
6828
  )) }),
6672
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flexGrow: 1 }, children: b.ui.error ? b.ui.error : b.ui.sseDown ? t("sseReconnect") : b.ui.notice ? b.ui.notice : b.ui.idleWarn ? t("idleWarn30s") : b.ui.state === "loading-model" || b.ui.model ? b.ui.model ? `${t("loadingModel")} ${b.ui.model.file} ${b.ui.model.percent}%` : stateText : b.ui.playing || b.ui.turn === "agent-speaking" ? stateText : b.ui.state === "wake" && b.ui.partial ? `${stateText} \xB7 ${b.ui.partial}` : b.ui.partial ? b.ui.partial : b.ui.ttsNotice ? b.ui.ttsNotice : stateText }),
6829
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6830
+ "span",
6831
+ {
6832
+ "data-dshvm": "status-text",
6833
+ role: "status",
6834
+ "aria-live": "polite",
6835
+ "aria-atomic": "true",
6836
+ style: {
6837
+ position: "absolute",
6838
+ width: 1,
6839
+ height: 1,
6840
+ overflow: "hidden",
6841
+ clip: "rect(0 0 0 0)",
6842
+ whiteSpace: "nowrap"
6843
+ },
6844
+ children: b.ui.error || (b.ui.sseDown ? t("sseReconnect") : "") || b.ui.notice || (b.ui.idleWarn ? t("idleWarn30s") : "") || (b.ui.state === "transcribing" ? t("recognizing") : stateText)
6845
+ }
6846
+ ),
6847
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6848
+ "span",
6849
+ {
6850
+ "aria-hidden": "true",
6851
+ style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flexGrow: 1 },
6852
+ children: b.ui.error ? b.ui.error : b.ui.sseDown ? t("sseReconnect") : b.ui.notice ? b.ui.notice : b.ui.idleWarn ? t("idleWarn30s") : b.ui.state === "loading-model" || b.ui.model ? b.ui.model ? `${t("loadingModel")} ${b.ui.model.file} ${b.ui.model.percent}%` : stateText : b.ui.playing || b.ui.turn === "agent-speaking" ? stateText : b.ui.state === "wake" && b.ui.partial ? `${stateText} \xB7 ${b.ui.partial}` : b.ui.partial ? b.ui.partial : b.ui.ttsNotice ? b.ui.ttsNotice : stateText
6853
+ }
6854
+ ),
6673
6855
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6674
6856
  "button",
6675
6857
  {
@@ -6693,6 +6875,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6693
6875
  b.ui.isSpeech === true && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6694
6876
  "span",
6695
6877
  {
6878
+ "aria-hidden": "true",
6696
6879
  title: t("vadDetected"),
6697
6880
  style: {
6698
6881
  flexShrink: 0,
@@ -6710,6 +6893,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6710
6893
  b.ui.ttsNotice && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6711
6894
  "span",
6712
6895
  {
6896
+ "aria-hidden": "true",
6713
6897
  title: b.ui.ttsNotice,
6714
6898
  style: {
6715
6899
  flexShrink: 0,
@@ -6731,6 +6915,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6731
6915
  elapsedSec > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
6732
6916
  "span",
6733
6917
  {
6918
+ "aria-hidden": "true",
6734
6919
  title: t("elapsedHint"),
6735
6920
  style: {
6736
6921
  flexShrink: 0,
@@ -6752,6 +6937,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6752
6937
  b.ui.aecOff === true && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6753
6938
  "span",
6754
6939
  {
6940
+ "aria-hidden": "true",
6755
6941
  title: b.ui.bargeInDetectFallback ? t("bargeInDetectFallback") : t("aecOffHint"),
6756
6942
  style: {
6757
6943
  flexShrink: 0,
@@ -6787,6 +6973,7 @@ function VoiceStatusBar({ bus, sessionId }) {
6787
6973
  telParts.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
6788
6974
  "div",
6789
6975
  {
6976
+ "aria-hidden": "true",
6790
6977
  style: {
6791
6978
  fontSize: 11,
6792
6979
  color: "#8b949e",