@jskit-ai/assistant-voice 0.2.9 → 0.2.11

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.
@@ -2,8 +2,15 @@ import { effectScope, shallowReactive, watch } from "vue";
2
2
  import { useVoiceConversation } from "./voiceConversation.js";
3
3
  import { useJskitText, voiceError, voiceErrorText } from "./i18n.js";
4
4
 
5
- /** One controller per application shell. Bindings retain their own conversation. */
6
- export function createVoiceConversationController({ connectSpeech, createSession = useVoiceConversation } = {}) {
5
+ /**
6
+ * One controller per application shell. Bindings retain their own conversation.
7
+ * @param {{
8
+ * connectSpeech: (binding: import("./types.js").VoiceConversationBinding) => string | Promise<string>,
9
+ * createSession?: typeof useVoiceConversation
10
+ * }} options
11
+ */
12
+ export function createVoiceConversationController({ connectSpeech, createSession = useVoiceConversation }) {
13
+ // readable-check: allow method-probe - input validation: an application supplies the speech connection
7
14
  if (typeof connectSpeech !== "function") throw new TypeError("Voice requires an application speech connection.");
8
15
  const { t } = useJskitText();
9
16
  const state = shallowReactive({ binding: null, session: null, visible: false, nextTarget: null, busy: false, error: "" });
@@ -14,6 +21,7 @@ export function createVoiceConversationController({ connectSpeech, createSession
14
21
 
15
22
  function serialize(operation) {
16
23
  const result = operations.then(operation);
24
+ // The queued caller receives the failure; the queue keeps only the order.
17
25
  operations = result.catch(() => {});
18
26
  return result;
19
27
  }
@@ -24,6 +32,7 @@ export function createVoiceConversationController({ connectSpeech, createSession
24
32
  if (session) await session.close();
25
33
  scope?.stop();
26
34
  scope = null;
35
+ // readable-check: allow optional-call - optional operation: a binding whose application keeps its conversation alive itself has no release(), and voice lets go of nothing
27
36
  await state.binding?.release?.();
28
37
  state.binding = null;
29
38
  state.session = null;
@@ -37,6 +46,7 @@ export function createVoiceConversationController({ connectSpeech, createSession
37
46
  if (disposed || requestRevision !== revision) return false;
38
47
  const nextScope = effectScope(true);
39
48
  try {
49
+ // readable-check: allow optional-call - optional operation: a binding whose application keeps its conversation alive itself has no retain(), and voice keeps nothing
40
50
  binding.retain?.();
41
51
  const session = nextScope.run(() => createSession(binding, { socketUrl }));
42
52
  scope = nextScope;
@@ -52,12 +62,18 @@ export function createVoiceConversationController({ connectSpeech, createSession
52
62
  return true;
53
63
  } catch (error) {
54
64
  nextScope.stop();
65
+ // readable-check: allow optional-call - optional operation: a binding whose application keeps its conversation alive itself has no release(), and voice lets go of nothing
55
66
  binding.release?.();
56
67
  throw error;
57
68
  }
58
69
  }
59
70
 
71
+ /**
72
+ * Shows voice for a conversation, starting its session unless unsent words still belong to another one.
73
+ * @param {{ conversation: import("./types.js").VoiceConversationBinding }} request
74
+ */
60
75
  function open({ conversation } = {}) {
76
+ // readable-check: allow method-probe - input validation: an application supplies the conversation binding
61
77
  if (!conversation?.id || !conversation.state || typeof conversation.submitText !== "function") {
62
78
  return Promise.reject(new TypeError("Voice requires a conversation identity, state and text submission."));
63
79
  }
@@ -116,11 +132,19 @@ export function createVoiceConversationController({ connectSpeech, createSession
116
132
  });
117
133
  }
118
134
 
135
+ function minimize() { state.visible = false; }
136
+ function reveal() { if (state.session) state.visible = true; }
137
+ function cancelSwitch() { state.nextTarget = null; }
138
+ async function dispose() { disposed = true; await end({ discard: true }); }
139
+
119
140
  return {
120
- state, open, switchTarget, end,
121
- minimize() { state.visible = false; },
122
- reveal() { if (state.session) state.visible = true; },
123
- cancelSwitch() { state.nextTarget = null; },
124
- async dispose() { disposed = true; await end({ discard: true }); }
141
+ state,
142
+ open,
143
+ switchTarget,
144
+ end,
145
+ minimize,
146
+ reveal,
147
+ cancelSwitch,
148
+ dispose
125
149
  };
126
150
  }
@@ -1,18 +1,20 @@
1
1
  import { computed, onScopeDispose, ref, watch } from "vue";
2
- import { createVoiceTurnId, useVoiceTransport } from "./voiceTransport.js";
3
- import { speechTextFromAssistant, takeStreamingSpeech, VOICE_MAX_SPEECH_TEXT_CHARACTERS } from "../shared/protocol.js";
4
- import { createConversationNarrationTracker } from "./conversationNarration.js";
5
- import { useJskitText, voiceErrorText, voiceSpeechWording } from "./i18n.js";
2
+ import { useVoiceTransport } from "./voiceTransport.js";
3
+ import { listenToDocument, listenToPage, pageVisible } from "./browser.js";
4
+ import { useJskitText, voiceErrorText } from "./i18n.js";
5
+ import { useVoiceReplies } from "./voiceReplies.js";
6
6
 
7
- /** Created inside the controller's effect scope, independent of a mounted screen. */
8
- export function useVoiceConversation(binding, { socketUrl, createTransport = useVoiceTransport } = {}) {
7
+ /**
8
+ * One voice session for a conversation binding: capture and turn-taking for what the person says, the replies the
9
+ * assistant speaks (voiceReplies.js), and the status the voice view shows. Created inside the controller's effect
10
+ * scope, independent of a mounted screen.
11
+ * @param {import("./types.js").VoiceConversationBinding} binding
12
+ * @param {{ socketUrl: string, createTransport?: typeof useVoiceTransport }} options
13
+ */
14
+ export function useVoiceConversation(binding, { socketUrl, createTransport = useVoiceTransport }) {
9
15
  const { serverMessage, t } = useJskitText();
10
16
  const targetLabel = computed(() => binding.label || t("jskit.assistant.voice.assistant"));
11
17
  const readAloud = ref(binding.defaults?.readAloud === true);
12
- const readAloudChangePending = computed(() => binding.readAloudChangePending === true);
13
- const soundPreparing = ref(false);
14
- let soundRevision = 0;
15
- const conversationId = binding.conversationId || binding.id;
16
18
  const error = ref("");
17
19
  const pendingTranscript = ref(null);
18
20
  const heldReview = ref(false);
@@ -35,7 +37,7 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
35
37
  speechEnabled: readAloud,
36
38
  interruptSpeechOnListen: false,
37
39
  autoReconnect: true,
38
- onPlayback: receivePlayback
40
+ onPlayback: (event) => replies.receivePlayback(event)
39
41
  });
40
42
  watch([() => binding.defaults?.voiceId, voice.availableVoices], ([voiceId, voices]) => {
41
43
  if (voiceId === undefined) return;
@@ -102,272 +104,31 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
102
104
  const voiceWords = computed(() => heldTranscript.value || binding.state.messages?.findLast(message => message.role === "user")?.text || "");
103
105
  const voiceAnswer = computed(() => binding.state.streamingReply?.text || binding.state.messages?.findLast(message => message.role === "assistant")?.text || "");
104
106
  let recording = null;
105
- let primed = false;
106
- let draining = false;
107
107
  let disposed = false;
108
- const seen = new Set();
109
- const speechQueue = [];
110
- const replies = new Map();
111
- let speechSuppressed = false;
112
- let requestedMessageId = "";
113
- let speechInvitation = "";
114
- let lastStreamingId = "";
115
- const narrationTracker = createConversationNarrationTracker();
116
- const narrationPageVisible = ref(globalThis.document?.visibilityState !== "hidden");
108
+ const narrationPageVisible = ref(pageVisible());
117
109
  const hiddenNarrationPage = computed(() => Boolean(binding.narration) && !narrationPageVisible.value);
118
- let narrationSettleTimer;
119
- let thinkingMurmurTimer;
120
- let narrationEpoch = 0;
121
-
122
- function clearNarrationTimers() {
123
- ++narrationEpoch;
124
- clearTimeout(narrationSettleTimer);
125
- clearTimeout(thinkingMurmurTimer);
126
- }
127
- function retireNarration(selected = () => true) {
128
- for (let index = speechQueue.length - 1; index >= 0; --index) {
129
- const reply = speechQueue[index];
130
- if (!reply.narrationKind || !selected(reply.narrationKind)) continue;
131
- cancelReply(reply, "narration-retired");
132
- speechQueue.splice(index, 1);
133
- if (reply.turnId && voice.activeSpeechTurnId.value === reply.turnId) voice.stopSpeaking("narration-retired");
134
- }
135
- }
136
- function narrationEnabled() {
137
- const narration = binding.narration;
138
- return Boolean(narration && narration.eligible && !narration.loading && readAloud.value
139
- && binding.state.available !== false && narrationPageVisible.value && !capturing.value
140
- && !starting.value && !speechSuppressed && !disposed);
141
- }
142
- function queueNarration(kind, text) {
143
- // Optional activity uses the original queue but never impersonates a canonical output.
144
- if (!narrationEnabled()) return;
145
- // Only filler yields to queued speech. Actual messages keep arrival order.
146
- if (kind === "murmur" && (speechQueue.length || speechActive.value)) return;
147
- speechQueue.push({ narrationKind: kind, raw: text, consumed: 0, final: true, started: false });
148
- void drainSpeech();
149
- }
150
- function observeNarration(settled = false, enabled = narrationEnabled()) {
151
- const narration = binding.narration;
152
- if (!narration) return;
153
- const entries = narrationTracker.observe(narration.turns, {
154
- includeFinals: false, settled, enabled,
155
- vocalizeThinking: narration.vocalizeThinking,
156
- vocalizeInterimTurns: narration.vocalizeInterimTurns
157
- });
158
- for (const entry of entries) queueNarration(entry.kind, entry.text);
159
- }
160
- function scheduleThinkingMurmur(epoch) {
161
- const narration = binding.narration;
162
- if (!narrationEnabled() || !narration.working || !narration.thinkingSounds) return;
163
- thinkingMurmurTimer = setTimeout(() => {
164
- if (epoch !== narrationEpoch || !narrationEnabled() || !binding.narration?.working || !binding.narration.thinkingSounds) return;
165
- if (!speechQueue.length && !draining && !speechActive.value && voice.state.value === "idle") {
166
- queueNarration("murmur", t("jskit.assistant.voice.narration.murmur"));
167
- }
168
- scheduleThinkingMurmur(epoch);
169
- }, 20_000);
170
- }
171
- function refreshNarration(settled = false) {
172
- clearNarrationTimers();
173
- observeNarration(settled);
174
- const narration = binding.narration;
175
- if (!narrationEnabled() || !narration.working) return;
176
- const epoch = narrationEpoch;
177
- if (narration.vocalizeThinking || narration.vocalizeInterimTurns) {
178
- narrationSettleTimer = setTimeout(() => {
179
- if (epoch === narrationEpoch && narrationEnabled()) observeNarration(true);
180
- }, 700);
181
- }
182
- scheduleThinkingMurmur(epoch);
183
- }
110
+ const replies = useVoiceReplies({
111
+ binding,
112
+ voice,
113
+ readAloud,
114
+ error,
115
+ starting,
116
+ capturing,
117
+ speechActive,
118
+ narrationPageVisible,
119
+ hiddenNarrationPage,
120
+ closed: () => disposed
121
+ });
184
122
 
185
- function observe(callback, value) {
186
- try {
187
- Promise.resolve(callback?.(value)).catch(() => {});
188
- } catch {
189
- // Observers cannot take ownership of scheduling or cleanup.
190
- }
191
- }
192
- function emitReply(reply, phase, reason) {
193
- if (reply.terminal || (phase === "started" && reply.audible)) return;
194
- if (phase === "started") reply.audible = true;
195
- else reply.terminal = true;
196
- if (reply.narrationKind) return;
197
- observe(binding.onPlayback, {
198
- conversationId, outputId: reply.outputId, phase, ...(reason ? { reason } : {})
199
- });
200
- }
201
- function receivePlayback(event) {
202
- const reply = [...replies.values()].find(reply => reply.turnId === event.turnId)
203
- || speechQueue.find(reply => reply.narrationKind && reply.turnId === event.turnId);
204
- if (!reply) return;
205
- if (event.phase === "completed") {
206
- reply.drained = true;
207
- if (reply.canonicalFinal || reply.narrationKind) emitReply(reply, "completed");
208
- } else emitReply(reply, event.phase, event.reason);
209
- }
210
- function cancelReply(reply, reason = "cancelled", phase = "interrupted") {
211
- reply.cancelled = true;
212
- emitReply(reply, phase, reason);
213
- }
214
- function stopSpeech() { cancelSpeech(); }
215
- function cancelSpeech(reason = "cancelled", phase = "interrupted") {
216
- clearNarrationTimers();
217
- retireNarration();
218
- for (const reply of replies.values()) {
219
- if (!reply.terminal) cancelReply(reply, reason, phase);
220
- }
221
- speechQueue.length = 0;
222
- speechSuppressed = true;
223
- speechInvitation = "";
224
- voice.stopSpeaking(reason);
225
- }
226
- function inviteSpeech(messageId) {
227
- // Only a new request from this page can lift silence. A delayed admission,
228
- // history refresh or retry of the same request is not a new invitation.
229
- if (!messageId || messageId === requestedMessageId || seen.has(messageId)) return;
230
- requestedMessageId = messageId;
231
- speechInvitation = messageId;
232
- }
233
- async function drainSpeech() {
234
- if (draining || disposed || !readAloud.value || speechSuppressed || soundPreparing.value || voice.playbackBlocked?.value) return;
235
- draining = true;
236
- const wording = voiceSpeechWording();
237
- try {
238
- while (speechQueue.length) {
239
- const reply = speechQueue[0];
240
- if (reply.cancelled) { speechQueue.shift(); continue; }
241
- if (reply.started && !speechActive.value) { speechQueue.shift(); continue; }
242
- if (speechActive.value && !reply.started) return;
243
- if (reply.started && !voice.canAppendSpeech.value) return;
244
- const previousSpeech = reply.narrationKind ? "" : speechTextFromAssistant(reply.raw.slice(0, reply.consumed), undefined, wording);
245
- const maximumCharacters = reply.narrationKind ? (reply.started ? 140 : 64) : Math.max(1, Math.min(
246
- reply.started ? 140 : 64,
247
- VOICE_MAX_SPEECH_TEXT_CHARACTERS - previousSpeech.length,
248
- VOICE_MAX_SPEECH_TEXT_CHARACTERS - reply.spokenCharacters
249
- ));
250
- const chunk = reply.speechCapped ? null : takeStreamingSpeech(reply.raw.slice(reply.consumed), reply.final, maximumCharacters, wording);
251
- if (!chunk) {
252
- if (reply.final && reply.started) voice.endSpeech();
253
- else if (reply.final) {
254
- cancelReply(reply, "no-audio");
255
- speechQueue.shift();
256
- continue;
257
- }
258
- return;
259
- }
260
- reply.consumed += chunk.consumed;
261
- let text = chunk.text;
262
- if (!reply.narrationKind) {
263
- // Keep offsets in raw Markdown. The original limit applies after its
264
- // cleanup, including whitespace between separately streamed phrases.
265
- const speech = speechTextFromAssistant(reply.raw.slice(0, reply.consumed), undefined, wording);
266
- const boundary = speech.startsWith(previousSpeech)
267
- ? speech.slice(previousSpeech.length).match(/^\s*/u)[0].length : 0;
268
- text = text.slice(0, Math.max(0, Math.min(
269
- VOICE_MAX_SPEECH_TEXT_CHARACTERS - previousSpeech.length - boundary,
270
- VOICE_MAX_SPEECH_TEXT_CHARACTERS - reply.spokenCharacters
271
- )));
272
- reply.spokenCharacters += text.length;
273
- reply.speechCapped = speech.length >= VOICE_MAX_SPEECH_TEXT_CHARACTERS
274
- || reply.spokenCharacters >= VOICE_MAX_SPEECH_TEXT_CHARACTERS;
275
- reply.final ||= reply.speechCapped;
276
- }
277
- if (!text) continue;
278
- if (!reply.started) {
279
- reply.started = true;
280
- reply.turnId = createVoiceTurnId("speak");
281
- const accepted = await voice.speak(text, reply.turnId, { stream: true });
282
- if (disposed) return;
283
- if (reply.cancelled) {
284
- if (reply.narrationKind) continue;
285
- return;
286
- }
287
- if (accepted === false) {
288
- cancelReply(reply, "no-audio");
289
- continue;
290
- }
291
- } else if (!voice.appendSpeech(text)) return;
292
- if (reply.speechCapped || (reply.final && reply.consumed >= reply.raw.length)) { voice.endSpeech(); return; }
293
- }
294
- } catch (cause) { error.value = voiceErrorText(cause); stopSpeech(); }
295
- finally { draining = false; }
296
- }
297
- function queueReply(message, final) {
298
- let reply = replies.get(message.id);
299
- if (!reply) {
300
- if (!primed || !readAloud.value || speechSuppressed || seen.has(message.id) || (!final && message.autonomous)) return;
301
- retireNarration(kind => kind === "murmur");
302
- reply = {
303
- id: message.id, outputId: message.outputId || message.id, streamId: message.streamId,
304
- raw: "", consumed: 0, spokenCharacters: 0, speechCapped: false,
305
- final: false, canonicalFinal: false, started: false
306
- };
307
- replies.set(message.id, reply);
308
- speechQueue.push(reply);
309
- }
310
- if (reply.cancelled) return;
311
- if (hiddenNarrationPage.value && !reply.canonicalFinal && (final || !reply.raw)) {
312
- // Consume hidden outputs without replay; a streaming answer cannot claim
313
- // completion when its first canonical final was not admitted for speech.
314
- cancelReply(reply, "page-hidden");
315
- if (reply.turnId && voice.activeSpeechTurnId.value === reply.turnId) voice.stopSpeaking("page-hidden");
316
- return;
317
- }
318
- if (final) retireNarration(kind => kind === "murmur");
319
- const text = String(message.text || "").slice(0, VOICE_MAX_SPEECH_TEXT_CHARACTERS * 2);
320
- const spokenPrefix = reply.raw.slice(0, reply.consumed);
321
- if (!text.startsWith(spokenPrefix) && !(final && text.trimEnd() === spokenPrefix.trimEnd())) {
322
- // A model revision cannot unsay words. Retire that projection; never splice
323
- // its old prefix onto a different answer or replay it as a second answer.
324
- cancelReply(reply);
325
- if (speechQueue[0] === reply) voice.stopSpeaking();
326
- return;
327
- }
328
- reply.consumed = Math.min(reply.consumed, text.length);
329
- reply.raw = text;
330
- reply.canonicalFinal ||= final;
331
- reply.final = final || reply.speechCapped || text.length >= VOICE_MAX_SPEECH_TEXT_CHARACTERS * 2;
332
- if (reply.canonicalFinal && reply.drained) emitReply(reply, "completed");
333
- }
334
- async function enableSound() {
335
- const revision = ++soundRevision;
336
- soundPreparing.value = true;
337
- try {
338
- await voice.preparePlayback();
339
- } catch {
340
- // Requested sound stays on; its recovery control remains available.
341
- } finally {
342
- if (revision === soundRevision && !disposed) {
343
- soundPreparing.value = false;
344
- void drainSpeech();
345
- }
346
- }
347
- }
348
- async function toggleReadAloud() {
349
- if (readAloudChangePending.value) return;
350
- error.value = "";
351
- readAloud.value = !readAloud.value;
352
- observe(binding.onReadAloudChange, readAloud.value);
353
- await applyReadAloud();
354
- }
355
- async function applyReadAloud() {
356
- if (!readAloud.value) {
357
- ++soundRevision;
358
- soundPreparing.value = false;
359
- cancelSpeech("muted");
360
- return;
361
- }
362
- speechSuppressed = false;
363
- speechInvitation = "";
364
- await enableSound();
365
- if (!disposed) refreshNarration();
123
+ /** The destination the application gives a new recording; a binding without captureContext gives none. */
124
+ function readCaptureContext() {
125
+ // readable-check: allow optional-call - optional operation: a binding may leave out captureContext, and its recordings then keep no destination
126
+ return binding.captureContext?.() || {};
366
127
  }
367
128
  watch(() => binding.defaults?.readAloud, (value) => {
368
129
  if (disposed || typeof value !== "boolean" || value === readAloud.value) return;
369
130
  readAloud.value = value;
370
- void applyReadAloud();
131
+ void replies.applyReadAloud();
371
132
  });
372
133
  async function deliverTranscript() {
373
134
  const pending = pendingTranscript.value;
@@ -375,7 +136,7 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
375
136
  sending.value = true;
376
137
  error.value = "";
377
138
  try {
378
- inviteSpeech(pending.messageId);
139
+ replies.inviteSpeech(pending.messageId);
379
140
  const receipt = await binding.submitText(pending.text, { messageId: pending.messageId, context: pending.focus });
380
141
  if (receipt === false || receipt?.ok === false) {
381
142
  throw new Error(serverMessage(receipt || {}, t("jskit.assistant.voice.errors.notAccepted")));
@@ -431,7 +192,7 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
431
192
  heldReview.value = reviewBeforeSend;
432
193
  holding.value = reviewBeforeSend;
433
194
  // Keep the starting target even if navigation changes during this utterance.
434
- const next = { focus: { ...(binding.captureContext?.() || {}) }, messageId: crypto.randomUUID(), started: false, reviewBeforeSend, continuous };
195
+ const next = { focus: { ...readCaptureContext() }, messageId: crypto.randomUUID(), started: false, reviewBeforeSend, continuous };
435
196
  recording = next;
436
197
  try {
437
198
  const started = await voice.startListening({ continuous });
@@ -548,7 +309,7 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
548
309
  const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(10000)]);
549
310
  try {
550
311
  // Unlock requested sound in the gesture without delaying microphone startup.
551
- if (readAloud.value) void enableSound();
312
+ if (readAloud.value) void replies.enableSound();
552
313
  signal.throwIfAborted();
553
314
  await voice.connect();
554
315
  signal.throwIfAborted();
@@ -568,10 +329,6 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
568
329
  if (startupAbort === controller) { startupAbort = null; starting.value = false; }
569
330
  }
570
331
  }
571
- function currentSpokenText() {
572
- const reply = speechQueue[0];
573
- return reply ? reply.raw.slice(0, reply.consumed).slice(-2000) : "";
574
- }
575
332
  function explicitSilence(text) {
576
333
  return /^(?:please )?(?:st[oa]p (?:talking|speaking)|be quiet|wait[, ]+let me (?:explain|finish)|let me finish)[.!]?$/iu.test(text.trim());
577
334
  }
@@ -581,13 +338,13 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
581
338
  const key = `${candidate.turnId}:${candidate.revision}`;
582
339
  if (decidedCandidate === key) return;
583
340
  decidedCandidate = key;
584
- const captured = { focus: { ...(recording?.focus || (binding.captureContext?.() || {})) }, messageId: recording?.messageId || crypto.randomUUID(), text: candidate.text,
341
+ const captured = { focus: { ...(recording?.focus || readCaptureContext()) }, messageId: recording?.messageId || crypto.randomUUID(), text: candidate.text,
585
342
  ...(recording?.reviewBeforeSend ? { reviewBeforeSend: true } : {}) };
586
343
  try {
587
344
  const text = candidate.text.trim();
588
- const spoken = currentSpokenText();
345
+ const spoken = replies.currentSpokenText();
589
346
  if (explicitSilence(text)) {
590
- if (!spoken.toLowerCase().includes(text.toLowerCase())) stopSpeech();
347
+ if (!spoken.toLowerCase().includes(text.toLowerCase())) replies.stopSpeech();
591
348
  voice.finishUtterance(candidate, { discard: true });
592
349
  return;
593
350
  }
@@ -627,17 +384,17 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
627
384
  // A discard can lose a race with resumed speech. Keep this utterance's
628
385
  // identity and destination until the daemon acknowledges the boundary.
629
386
  if (reset?.turnId !== voice.activeListenTurnId.value || !live.value || !recording) return;
630
- recording = { focus: { ...(binding.captureContext?.() || {}) }, messageId: crypto.randomUUID(), started: true, continuous: true,
387
+ recording = { focus: { ...readCaptureContext() }, messageId: crypto.randomUUID(), started: true, continuous: true,
631
388
  ...(recording.reviewBeforeSend ? { reviewBeforeSend: true } : {}),
632
389
  ...(recording.finishAfterPending ? { finishAfterPending: true } : {}) };
633
390
  });
634
391
  watch(voice.partialTranscript, (text, previous) => {
635
392
  clearTimeout(stopTimer);
636
393
  if (!live.value || microphoneMuted.value) return;
637
- if (text && !previous && recording) recording.focus = { ...(binding.captureContext?.() || {}) };
638
- if (!explicitSilence(text) || currentSpokenText().toLowerCase().includes(text.toLowerCase())) return;
394
+ if (text && !previous && recording) recording.focus = { ...readCaptureContext() };
395
+ if (!explicitSilence(text) || replies.currentSpokenText().toLowerCase().includes(text.toLowerCase())) return;
639
396
  stopTimer = setTimeout(() => {
640
- if (live.value && !microphoneMuted.value && voice.partialTranscript.value === text) stopSpeech();
397
+ if (live.value && !microphoneMuted.value && voice.partialTranscript.value === text) replies.stopSpeech();
641
398
  }, 120);
642
399
  });
643
400
  watch([pendingTranscript, sending, voice.utteranceReset, voice.utteranceStale], () => {
@@ -694,7 +451,7 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
694
451
  return;
695
452
  }
696
453
  if (live.value && !finished.reviewBeforeSend && explicitSilence(text)) {
697
- stopSpeech();
454
+ replies.stopSpeech();
698
455
  return;
699
456
  }
700
457
  pendingTranscript.value = { ...finished, text };
@@ -708,65 +465,13 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
708
465
  if (pendingTranscript.value && messages.some((message) => message.role === "user" && message.id === pendingTranscript.value.messageId && message.receipt !== false)) {
709
466
  dismissTranscript();
710
467
  }
711
- let invited = false;
712
- for (const message of messages) {
713
- // Unadmitted local records do not acknowledge a request or lift speech silence.
714
- if (message.role === "user" && message.receipt === false) continue;
715
- if (seen.has(message.id)) continue;
716
- if (message.role === "user" && message.id === speechInvitation) {
717
- speechSuppressed = false;
718
- speechInvitation = "";
719
- invited = true;
720
- }
721
- if (message.role === "assistant") queueReply(message, true);
722
- seen.add(message.id);
723
- }
724
- if (lastStreamingId && lastStreamingId !== reply?.id && !messages.some(message => message.id === lastStreamingId)) {
725
- const retired = replies.get(lastStreamingId);
726
- if (retired && !retired.canonicalFinal && !retired.cancelled) {
727
- cancelReply(retired);
728
- if (speechQueue[0] === retired) voice.finishCurrentPhrase();
729
- }
730
- }
731
- lastStreamingId = reply?.id || "";
732
- if (reply?.text) {
733
- queueReply(reply, reply.status === "completed");
734
- if (!readAloud.value || !primed || reply.autonomous || hiddenNarrationPage.value) seen.add(reply.id);
735
- }
736
- // Keep only the visible history plus active playback receipts in memory.
737
- const retained = new Set([...messages.map((message) => message.id), reply?.id, ...speechQueue.map((item) => item.id),
738
- ...[...replies.values()].filter(item => !item.terminal).map(item => item.id)]);
739
- for (const id of seen) if (!retained.has(id)) seen.delete(id);
740
- for (const id of replies.keys()) if (!retained.has(id)) replies.delete(id);
741
- primed = true;
742
- if (invited) refreshNarration();
743
- void drainSpeech();
468
+ replies.observeHistory(messages, reply);
744
469
  }, { immediate: true });
745
- watch(() => {
746
- const narration = binding.narration;
747
- return {
748
- id: binding.id, conversationId: binding.conversationId, narration,
749
- loading: narration?.loading, eligible: narration?.eligible, working: narration?.working,
750
- thinking: narration?.vocalizeThinking, interim: narration?.vocalizeInterimTurns,
751
- sounds: narration?.thinkingSounds, turns: narration?.turns, enabled: narrationEnabled()
752
- };
753
- }, (current, previous) => {
754
- clearNarrationTimers();
755
- if (!current.narration || current.loading || current.id !== previous?.id || current.conversationId !== previous?.conversationId) {
756
- narrationTracker.reset();
757
- retireNarration();
758
- if (!current.narration || current.loading) return;
759
- }
760
- if (!current.enabled) retireNarration();
761
- else retireNarration(kind => kind === "thinking" ? !current.thinking
762
- : kind === "commentary" ? !current.interim : !current.sounds || !current.working);
763
- // Retire disabled tails before enabling a flag; settings are not a request to replay history.
764
- if (previous && (current.enabled !== previous.enabled || current.thinking !== previous.thinking || current.interim !== previous.interim)) observeNarration(true, false);
765
- refreshNarration(!current.enabled);
766
- }, { immediate: true, deep: true });
767
- watch(voice.error, (message) => { if (message) cancelSpeech("playback-error", "failed"); });
470
+ watch(replies.narrationSettings, replies.applyNarrationSettings, { immediate: true, deep: true });
471
+ watch(voice.error, (message) => { if (message) replies.cancelSpeech("playback-error", "failed"); });
472
+ // readable-check: allow optional-call - optional operation: a binding may leave out onError, and its errors then show only in the voice view
768
473
  watch(() => error.value || voice.error.value, (message) => { if (message) binding.onError?.(message); });
769
- watch([voice.activeSpeechTurnId, voice.canAppendSpeech], () => { void drainSpeech(); });
474
+ watch([voice.activeSpeechTurnId, voice.canAppendSpeech], () => { void replies.drainSpeech(); });
770
475
  function currentTranscript() {
771
476
  const pending = pendingTranscript.value;
772
477
  const currentWords = recording && ["listening", "transcribing"].includes(voice.captureState.value)
@@ -827,13 +532,14 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
827
532
  }
828
533
  function publishTranscript() {
829
534
  const transcript = currentTranscript();
535
+ // readable-check: allow optional-call - optional operation: a binding may leave out onTranscript, or its getter may return none, and it is then not shown unsent words
830
536
  binding.onTranscript?.(transcript, { canTake: Boolean(transcript && canTakeTranscript(transcript.id)) });
831
537
  }
832
538
  watch([pendingTranscript, voice.captureState, voice.partialTranscript, voice.endpoint, sending, starting, takingTranscript], publishTranscript, { immediate: true });
539
+ // readable-check: allow optional-call - optional operation: a binding may leave out onVisual, and then draws no avatar of its own
833
540
  watch(avatarVisual, (visual) => binding.onVisual?.(visual), { immediate: true });
834
- const page = globalThis.window || globalThis;
835
541
  const updateNarrationVisibility = () => {
836
- narrationPageVisible.value = globalThis.document?.visibilityState !== "hidden";
542
+ narrationPageVisible.value = pageVisible();
837
543
  if (disposed || !hiddenNarrationPage.value || !(recording || starting.value || committing || capturing.value)) return;
838
544
  // This is the original document-hidden capture boundary, not avatar/body
839
545
  // visibility. Retire B before cancellation; A's delivery stays untouched.
@@ -846,17 +552,21 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
846
552
  void discardRecording();
847
553
  voice.stopSpeaking("page-hidden");
848
554
  };
849
- globalThis.document?.addEventListener?.("visibilitychange", updateNarrationVisibility);
555
+ const stopVisibilityListener = listenToDocument("visibilitychange", updateNarrationVisibility);
850
556
  const cancelStartup = () => { if (starting.value) void discardRecording(); else void cancelPushToTalk(); };
851
- page.addEventListener?.("pagehide", cancelStartup);
852
- page.addEventListener?.("blur", cancelPushToTalk);
557
+ const stopPageHideListener = listenToPage("pagehide", cancelStartup);
558
+ const stopBlurListener = listenToPage("blur", cancelPushToTalk);
853
559
  onScopeDispose(() => {
854
- globalThis.document?.removeEventListener?.("visibilitychange", updateNarrationVisibility);
855
- page.removeEventListener?.("pagehide", cancelStartup);
856
- page.removeEventListener?.("blur", cancelPushToTalk);
560
+ stopVisibilityListener();
561
+ stopPageHideListener();
562
+ stopBlurListener();
857
563
  startupAbort?.abort(); startupAbort = null;
858
- stopSpeech();
859
- binding.onTranscript?.(null); binding.onVisual?.(null); disposed = true; live.value = false; clearTimeout(stopTimer); recording = null; speechQueue.length = 0;
564
+ replies.stopSpeech();
565
+ // readable-check: allow optional-call - optional operation: a binding may leave out onTranscript, and is then not told the words are gone
566
+ binding.onTranscript?.(null);
567
+ // readable-check: allow optional-call - optional operation: a binding may leave out onVisual, and is then not told the avatar is gone
568
+ binding.onVisual?.(null);
569
+ disposed = true; live.value = false; clearTimeout(stopTimer); recording = null;
860
570
  });
861
571
 
862
572
  async function close() {
@@ -866,7 +576,7 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
866
576
  clearTimeout(stopTimer);
867
577
  recording = null;
868
578
  committing = null;
869
- stopSpeech();
579
+ replies.stopSpeech();
870
580
  await voice.close();
871
581
  }
872
582
  function editTranscript(text, messageId = pendingTranscript.value?.messageId) {
@@ -877,11 +587,12 @@ export function useVoiceConversation(binding, { socketUrl, createTransport = use
877
587
  (sending.value || Boolean(pendingTranscript.value) || capturing.value));
878
588
  const hasUnsentSpeech = computed(() => capturing.value || starting.value || sending.value || Boolean(pendingTranscript.value));
879
589
  return {
880
- targetLabel, voice, readAloud, readAloudChangePending, error, pendingTranscript, heldReview, holding, sending,
590
+ targetLabel, voice, readAloud, readAloudChangePending: replies.readAloudChangePending, error, pendingTranscript, heldReview, holding, sending,
881
591
  live, starting, callMode, changingCallMode, pushHolding, microphoneMuted, capturing,
882
592
  speechActive, callConnection, callStatus, callModeBusy,
883
593
  avatarVisual, callAudioLevel, status, heldTranscript, voiceWords, voiceAnswer,
884
- stopSpeech, inviteSpeech, toggleReadAloud, enableSound, soundPreparing, deliverTranscript, cancelRecording,
594
+ stopSpeech: replies.stopSpeech, inviteSpeech: replies.inviteSpeech, toggleReadAloud: replies.toggleReadAloud,
595
+ enableSound: replies.enableSound, soundPreparing: replies.soundPreparing, deliverTranscript, cancelRecording,
885
596
  discardRecording, dismissTranscript, talk, toggleMicrophoneMuted, changeCallMode,
886
597
  startPushToTalk, finishPushToTalk, cancelPushToTalk, toggleLive, toggleHandsFree, startHeldRecording,
887
598
  finishHeldRecording, discardHeldRecording, close, editTranscript, canTakeTranscript, beginTranscriptEdit, takeTranscript, hasUnsentSpeech, composerBlocked