@istarry/spoon-companion 0.0.0-stage → 0.6.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.
package/lib/client.js ADDED
@@ -0,0 +1,1592 @@
1
+ window.__ModuleLoader__.load({ id: "@istarry/spoon-companion", factory: (require) => {
2
+ var module = { exports: {} }; var exports = module.exports;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/client/index.ts
22
+ var index_exports = {};
23
+ __export(index_exports, {
24
+ apply: () => apply2,
25
+ inject: () => inject
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/client/cleanup.js
30
+ var MARKER = "<!--more-->";
31
+ var TRIGGER_TEXTS = /* @__PURE__ */ new Set([
32
+ "\u6536\u5230\u6267\u884C\u8BF7\u6C42",
33
+ "\u7EE7\u7EED\u6267\u884C\u76EE\u6807",
34
+ "\u6536\u5230\u4EFB\u52A1\u6D88\u606F",
35
+ "\u6536\u5230\u56E2\u961F\u6D88\u606F",
36
+ "\u5B50\u4EFB\u52A1\u72B6\u6001\u66F4\u65B0",
37
+ "\u6536\u5230 GitHub \u4E8B\u4EF6",
38
+ "\u6536\u5230\u5916\u90E8\u4E8B\u4EF6",
39
+ "\u81EA\u52A8\u5316\u4EFB\u52A1",
40
+ "\u540E\u53F0\u4EFB\u52A1\u72B6\u6001\u66F4\u65B0"
41
+ ]);
42
+ function stripMarkers(root) {
43
+ let walker;
44
+ try {
45
+ walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
46
+ } catch {
47
+ return;
48
+ }
49
+ const hits = [];
50
+ let node = walker.nextNode();
51
+ while (node) {
52
+ const v = node.nodeValue;
53
+ if (typeof v === "string" && v.indexOf(MARKER) !== -1) hits.push(node);
54
+ node = walker.nextNode();
55
+ }
56
+ for (const n of hits) {
57
+ const cleaned = n.nodeValue.split(MARKER).join("").replace(/\n{3,}/g, "\n\n").replace(/^[\s\u00a0]+|[\s\u00a0]+$/g, "");
58
+ if (cleaned !== n.nodeValue) n.nodeValue = cleaned;
59
+ }
60
+ }
61
+ function hideTriggers(root) {
62
+ let candidates;
63
+ try {
64
+ candidates = root.querySelectorAll("span,div,p,a");
65
+ } catch {
66
+ return;
67
+ }
68
+ for (const el of candidates) {
69
+ if (el.children.length > 0) continue;
70
+ const text = (el.textContent || "").trim();
71
+ if (!TRIGGER_TEXTS.has(text)) continue;
72
+ let p = el;
73
+ for (let depth = 0; depth < 6 && p.parentElement; depth++) {
74
+ p = p.parentElement;
75
+ let bg = "";
76
+ try {
77
+ bg = getComputedStyle(p).backgroundColor;
78
+ } catch {
79
+ break;
80
+ }
81
+ if (bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent") {
82
+ p.setAttribute("data-spoon-cleanup-hidden", "1");
83
+ p.style.setProperty("display", "none", "important");
84
+ break;
85
+ }
86
+ }
87
+ }
88
+ }
89
+ function sweep() {
90
+ const body = document.body;
91
+ if (!body) return;
92
+ try {
93
+ stripMarkers(body);
94
+ } catch {
95
+ }
96
+ try {
97
+ hideTriggers(body);
98
+ } catch {
99
+ }
100
+ }
101
+ function applyCleanup(ctx) {
102
+ let timer = 0;
103
+ let observer;
104
+ const schedule = () => {
105
+ if (timer) return;
106
+ timer = window.setTimeout(() => {
107
+ timer = 0;
108
+ sweep();
109
+ }, 160);
110
+ };
111
+ try {
112
+ observer = new MutationObserver(schedule);
113
+ observer.observe(document.body, { childList: true, subtree: true, characterData: true });
114
+ } catch {
115
+ observer = void 0;
116
+ }
117
+ schedule();
118
+ window.setTimeout(sweep, 600);
119
+ try {
120
+ ctx?.effect?.(() => () => {
121
+ if (timer) window.clearTimeout(timer);
122
+ try {
123
+ observer?.disconnect();
124
+ } catch {
125
+ }
126
+ });
127
+ } catch {
128
+ }
129
+ }
130
+
131
+ // src/client/voice/ui.tsx
132
+ var import_react = require("react");
133
+
134
+ // src/client/voice/api.ts
135
+ var PREFIX = "/api/companion-voice";
136
+ var DEDUPE_MS = 1500;
137
+ var lastStartKey = "";
138
+ var lastStartAt = 0;
139
+ function shouldDrop(key) {
140
+ const now = Date.now();
141
+ if (key === lastStartKey && now - lastStartAt < DEDUPE_MS) return true;
142
+ lastStartKey = key;
143
+ lastStartAt = now;
144
+ return false;
145
+ }
146
+ async function jsonFetch(path, init = {}) {
147
+ const res = await fetch(path, {
148
+ ...init,
149
+ headers: { "Content-Type": "application/json", ...init.headers ?? {} }
150
+ });
151
+ const text = await res.text();
152
+ try {
153
+ return JSON.parse(text);
154
+ } catch {
155
+ throw new Error(`companion-voice \u8FD4\u56DE\u4E86\u975E JSON\uFF08HTTP ${res.status}\uFF09`);
156
+ }
157
+ }
158
+ var api = {
159
+ state: () => jsonFetch(`${PREFIX}/state`),
160
+ config: (patch) => jsonFetch(`${PREFIX}/config`, { method: "POST", body: JSON.stringify(patch) }),
161
+ speak: (text) => jsonFetch(`${PREFIX}/speak`, { method: "POST", body: JSON.stringify({ text }) }),
162
+ clearCache: () => jsonFetch(`${PREFIX}/cache/clear`, { method: "POST", body: "{}" }),
163
+ /** 上传克隆样本(原始二进制)。 */
164
+ uploadSample: async (file) => {
165
+ const res = await fetch(`${PREFIX}/sample`, {
166
+ method: "POST",
167
+ headers: { "Content-Type": file.type || "audio/wav" },
168
+ body: file
169
+ });
170
+ return await res.json();
171
+ },
172
+ /** 删除样本(同时关掉克隆)。 */
173
+ clearSample: () => jsonFetch(`${PREFIX}/sample/clear`, { method: "POST", body: "{}" })
174
+ };
175
+ var currentAudio;
176
+ var playback = { playing: false, messageId: "", label: "" };
177
+ var playbackListeners = /* @__PURE__ */ new Set();
178
+ function setPlayback(next) {
179
+ playback = { ...playback, ...next };
180
+ for (const fn of playbackListeners) fn();
181
+ }
182
+ function getPlayback() {
183
+ return playback;
184
+ }
185
+ function playAudio(url, meta) {
186
+ stopAudio();
187
+ const audio = new Audio(url);
188
+ currentAudio = audio;
189
+ setPlayback({
190
+ playing: true,
191
+ messageId: meta?.messageId ?? "",
192
+ label: (meta?.label ?? "").replace(/\s+/g, " ").slice(0, 40)
193
+ });
194
+ audio.addEventListener("ended", () => {
195
+ if (currentAudio !== audio) return;
196
+ currentAudio = void 0;
197
+ setPlayback({ playing: false, messageId: "", label: "" });
198
+ });
199
+ audio.addEventListener("error", () => {
200
+ if (currentAudio !== audio) return;
201
+ currentAudio = void 0;
202
+ setPlayback({ playing: false, messageId: "", label: "" });
203
+ });
204
+ void audio.play().catch(() => {
205
+ });
206
+ }
207
+ function stopAudio() {
208
+ const had = currentAudio !== void 0;
209
+ if (currentAudio) {
210
+ try {
211
+ currentAudio.pause();
212
+ currentAudio.currentTime = 0;
213
+ } catch {
214
+ }
215
+ currentAudio = void 0;
216
+ }
217
+ if (had || playback.playing) setPlayback({ playing: false, messageId: "", label: "" });
218
+ }
219
+ function isPlaying() {
220
+ return currentAudio !== void 0 && !currentAudio.paused;
221
+ }
222
+ var STREAM_SR = 24e3;
223
+ var stream;
224
+ function isStreaming() {
225
+ return stream !== void 0;
226
+ }
227
+ function stopStream() {
228
+ if (!stream) return;
229
+ const s = stream;
230
+ s.closed = true;
231
+ if (s.watchdog !== void 0) window.clearInterval(s.watchdog);
232
+ stream = void 0;
233
+ try {
234
+ s.abort.abort();
235
+ } catch {
236
+ }
237
+ for (const src of s.sources) {
238
+ try {
239
+ src.stop();
240
+ } catch {
241
+ }
242
+ }
243
+ s.sources.clear();
244
+ try {
245
+ void s.ctx.close();
246
+ } catch {
247
+ }
248
+ setPlayback({ playing: false, messageId: "", label: "" });
249
+ }
250
+ var speakQueue = [];
251
+ var queueRunning = false;
252
+ function waitPlaybackDone(timeoutMs = 18e4) {
253
+ return new Promise((resolve) => {
254
+ const deadline = Date.now() + timeoutMs;
255
+ const tick = () => {
256
+ if (!isStreaming() && !isPlaying()) {
257
+ resolve();
258
+ return;
259
+ }
260
+ if (Date.now() >= deadline) {
261
+ resolve();
262
+ return;
263
+ }
264
+ window.setTimeout(tick, 150);
265
+ };
266
+ tick();
267
+ });
268
+ }
269
+ function clearQueue() {
270
+ const pending = speakQueue.splice(0);
271
+ for (const item of pending) item.resolve();
272
+ }
273
+ async function drainQueue() {
274
+ if (queueRunning) return;
275
+ queueRunning = true;
276
+ try {
277
+ for (; ; ) {
278
+ const item = speakQueue.shift();
279
+ if (!item) break;
280
+ try {
281
+ await speakNow(item.text, item.meta, item.hooks);
282
+ await waitPlaybackDone();
283
+ item.resolve();
284
+ } catch (error) {
285
+ item.reject(error);
286
+ }
287
+ }
288
+ } finally {
289
+ queueRunning = false;
290
+ }
291
+ }
292
+ async function speakStream(text, meta, hooks = {}) {
293
+ if (meta.manual) {
294
+ clearQueue();
295
+ return speakNow(text, meta, hooks);
296
+ }
297
+ return new Promise((resolve, reject) => {
298
+ speakQueue.push({ text, meta, hooks, resolve, reject });
299
+ void drainQueue();
300
+ });
301
+ }
302
+ function stopAll(options) {
303
+ if (!options?.keepQueue) clearQueue();
304
+ stopStream();
305
+ stopAudio();
306
+ }
307
+ async function speakNow(text, meta, hooks = {}) {
308
+ if (!meta.manual && shouldDrop(`${meta.messageId}|${text}`)) {
309
+ hooks.onDone?.({ cached: false, skipped: true });
310
+ return;
311
+ }
312
+ if (meta.manual) {
313
+ lastStartKey = `${meta.messageId}|${text}`;
314
+ lastStartAt = Date.now();
315
+ }
316
+ stopAll({ keepQueue: true });
317
+ const ctx = new AudioContext({ sampleRate: STREAM_SR });
318
+ if (ctx.state === "suspended") {
319
+ try {
320
+ await ctx.resume();
321
+ } catch {
322
+ }
323
+ }
324
+ const abort = new AbortController();
325
+ const s = { ctx, nextTime: ctx.currentTime + 0.06, sources: /* @__PURE__ */ new Set(), abort, started: false, finished: false, closed: false, messageId: meta.messageId };
326
+ stream = s;
327
+ setPlayback({ playing: true, messageId: meta.messageId, label: meta.label.replace(/\s+/g, " ").slice(0, 40) });
328
+ let leadingSkipped = false;
329
+ const isSilent = (pcm) => {
330
+ let acc = 0;
331
+ let n = 0;
332
+ for (let i = 0; i < pcm.length; i += 32) {
333
+ acc += Math.abs(pcm[i]);
334
+ n++;
335
+ }
336
+ return n > 0 && acc / n < 40;
337
+ };
338
+ const finalize = () => {
339
+ if (stream !== s || s.closed) return;
340
+ if (!s.finished || s.sources.size > 0) return;
341
+ s.closed = true;
342
+ stream = void 0;
343
+ try {
344
+ void s.ctx.close();
345
+ } catch {
346
+ }
347
+ setPlayback({ playing: false, messageId: "", label: "" });
348
+ };
349
+ const watchdog = window.setInterval(() => {
350
+ if (s.closed) {
351
+ window.clearInterval(watchdog);
352
+ return;
353
+ }
354
+ if (!s.finished) return;
355
+ const remain = s.nextTime - s.ctx.currentTime;
356
+ if (remain <= 0.05 && s.sources.size === 0) {
357
+ window.clearInterval(watchdog);
358
+ finalize();
359
+ return;
360
+ }
361
+ if (remain < -3) {
362
+ window.clearInterval(watchdog);
363
+ for (const src of s.sources) {
364
+ try {
365
+ src.stop();
366
+ } catch {
367
+ }
368
+ }
369
+ s.sources.clear();
370
+ finalize();
371
+ }
372
+ }, 1e3);
373
+ s.watchdog = watchdog;
374
+ const enqueue = (pcm) => {
375
+ if (!stream || stream !== s) return;
376
+ if (pcm.length === 0) return;
377
+ if (!leadingSkipped) {
378
+ if (isSilent(pcm)) return;
379
+ leadingSkipped = true;
380
+ }
381
+ const buf = ctx.createBuffer(1, pcm.length, STREAM_SR);
382
+ const ch = buf.getChannelData(0);
383
+ for (let i = 0; i < pcm.length; i++) ch[i] = pcm[i] / 32768;
384
+ const src = ctx.createBufferSource();
385
+ src.buffer = buf;
386
+ src.connect(ctx.destination);
387
+ const at = Math.max(s.nextTime, ctx.currentTime + 0.02);
388
+ src.start(at);
389
+ s.nextTime = at + buf.duration;
390
+ s.sources.add(src);
391
+ src.onended = () => {
392
+ s.sources.delete(src);
393
+ finalize();
394
+ };
395
+ if (!s.started) {
396
+ s.started = true;
397
+ hooks.onStart?.();
398
+ }
399
+ };
400
+ try {
401
+ const res = await fetch(`${PREFIX}/speak-stream`, {
402
+ method: "POST",
403
+ headers: { "Content-Type": "application/json" },
404
+ body: JSON.stringify({ text }),
405
+ signal: abort.signal
406
+ });
407
+ if (!res.ok) {
408
+ const detail = await res.json().catch(() => ({}));
409
+ stream = void 0;
410
+ try {
411
+ void ctx.close();
412
+ } catch {
413
+ }
414
+ const r = await api.speak(text);
415
+ if (!r.ok || !r.url) throw new Error(r.error ?? detail.error ?? "\u5408\u6210\u5931\u8D25");
416
+ playAudio(r.url, meta);
417
+ hooks.onStart?.();
418
+ hooks.onDone?.({ cached: Boolean(r.cached), totalMs: r.ms });
419
+ return;
420
+ }
421
+ if (!res.body) throw new Error("\u6D41\u5F0F\u54CD\u5E94\u6CA1\u6709 body");
422
+ const reader = res.body.getReader();
423
+ const decoder = new TextDecoder();
424
+ let buffer = "";
425
+ for (; ; ) {
426
+ const { done, value } = await reader.read();
427
+ if (done) break;
428
+ buffer += decoder.decode(value, { stream: true });
429
+ let idx = buffer.indexOf("\n");
430
+ while (idx >= 0) {
431
+ const line = buffer.slice(0, idx).trim();
432
+ buffer = buffer.slice(idx + 1);
433
+ idx = buffer.indexOf("\n");
434
+ if (!line.startsWith("data:")) continue;
435
+ const payload = line.slice(5).trim();
436
+ if (!payload) continue;
437
+ let j;
438
+ try {
439
+ j = JSON.parse(payload);
440
+ } catch {
441
+ continue;
442
+ }
443
+ if (j.pcm) {
444
+ const raw = atob(j.pcm);
445
+ const bytes = new Uint8Array(raw.length);
446
+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
447
+ const view = new Int16Array(bytes.buffer, bytes.byteOffset, bytes.length >> 1);
448
+ enqueue(view);
449
+ } else if (j.ok === false && j.error) {
450
+ throw new Error(j.error);
451
+ } else if (j.cached === true && j.url) {
452
+ s.closed = true;
453
+ window.clearInterval(watchdog);
454
+ if (stream === s) {
455
+ stream = void 0;
456
+ try {
457
+ void ctx.close();
458
+ } catch {
459
+ }
460
+ }
461
+ playAudio(j.url, meta);
462
+ s.started = true;
463
+ hooks.onStart?.();
464
+ hooks.onDone?.({ cached: true });
465
+ } else if (j.firstMs !== void 0 || j.totalMs !== void 0) {
466
+ s.finished = true;
467
+ hooks.onDone?.({ cached: false, firstMs: j.firstMs, totalMs: j.totalMs });
468
+ finalize();
469
+ }
470
+ }
471
+ }
472
+ s.finished = true;
473
+ finalize();
474
+ } catch (e) {
475
+ const msg = e.message;
476
+ if (s.closed) return;
477
+ s.closed = true;
478
+ window.clearInterval(watchdog);
479
+ if (stream === s) {
480
+ stream = void 0;
481
+ try {
482
+ void ctx.close();
483
+ } catch {
484
+ }
485
+ setPlayback({ playing: false, messageId: "", label: "" });
486
+ }
487
+ if (/abort/i.test(msg)) return;
488
+ hooks.onError?.(msg);
489
+ }
490
+ }
491
+ var autoFlags = { enabled: false, autoPlay: false };
492
+ var autoListeners = /* @__PURE__ */ new Set();
493
+ function updateAutoFlags(enabled, autoPlay) {
494
+ if (autoFlags.enabled === enabled && autoFlags.autoPlay === autoPlay) return;
495
+ autoFlags = { enabled, autoPlay };
496
+ for (const fn of autoListeners) fn();
497
+ }
498
+ function shouldAutoPlay() {
499
+ return autoFlags.enabled && autoFlags.autoPlay;
500
+ }
501
+ function subscribeAutoFlags(fn) {
502
+ autoListeners.add(fn);
503
+ return () => {
504
+ autoListeners.delete(fn);
505
+ };
506
+ }
507
+ var autoPlayed = /* @__PURE__ */ new Set();
508
+ function hasAutoPlayed(id) {
509
+ return autoPlayed.has(id);
510
+ }
511
+ function markAutoPlayed(id) {
512
+ autoPlayed.add(id);
513
+ }
514
+
515
+ // src/client/voice/transcript.ts
516
+ function normalizeTime(raw) {
517
+ const t = Number(raw);
518
+ if (!Number.isFinite(t) || t <= 0) return 0;
519
+ return t > 1e12 ? t : t * 1e3;
520
+ }
521
+ function turnScalarId(turn) {
522
+ if (turn === void 0 || turn === null) return "";
523
+ if (typeof turn === "string" || typeof turn === "number") return String(turn);
524
+ if (typeof turn === "object") {
525
+ const o = turn;
526
+ for (const k of ["id", "turn", "index", "seq", "key"]) {
527
+ const v = o[k];
528
+ if (typeof v === "string" || typeof v === "number") return String(v);
529
+ }
530
+ const start = o.start;
531
+ if (start && (typeof start.seq === "string" || typeof start.seq === "number")) return String(start.seq);
532
+ const end = o.end;
533
+ if (end && (typeof end.seq === "string" || typeof end.seq === "number")) return String(end.seq);
534
+ }
535
+ return "";
536
+ }
537
+ function turnNodes(snapshot) {
538
+ const out = [];
539
+ for (const node of snapshot.legacy.nodes) {
540
+ if (node.kind !== "assistant") continue;
541
+ if (node.messageId === void 0) continue;
542
+ const parts = [];
543
+ for (const block of node.blocks) {
544
+ if (block.kind === "text") parts.push(block.text);
545
+ }
546
+ const turn = node.turn;
547
+ out.push({
548
+ messageId: String(node.messageId),
549
+ // 优先用 turn 的标量 id;抽不到就留空,稍后按「本轮首个 messageId」补齐
550
+ turnKey: turnScalarId(turn),
551
+ text: parts.join("\n").trim(),
552
+ time: normalizeTime(node.time)
553
+ });
554
+ }
555
+ let fallback = 0;
556
+ let prevEmpty = false;
557
+ for (const n of out) {
558
+ if (n.turnKey === "") {
559
+ if (!prevEmpty) fallback++;
560
+ n.turnKey = `grp:${fallback}`;
561
+ prevEmpty = true;
562
+ } else {
563
+ prevEmpty = false;
564
+ }
565
+ }
566
+ const firstOfGroup = /* @__PURE__ */ new Map();
567
+ for (const n of out) if (!firstOfGroup.has(n.turnKey)) firstOfGroup.set(n.turnKey, n.messageId);
568
+ for (const n of out) {
569
+ const first = firstOfGroup.get(n.turnKey);
570
+ if (first) n.turnKey = `turn@${first}`;
571
+ }
572
+ return out;
573
+ }
574
+ function streamingMessageId(snapshot) {
575
+ const partial = snapshot.legacy.partial;
576
+ if (!partial || partial.messageId === void 0) return "";
577
+ return String(partial.messageId);
578
+ }
579
+ function assistantInfoOf(snapshot, messageId) {
580
+ const nodes = turnNodes(snapshot);
581
+ const me = nodes.find((n) => n.messageId === String(messageId));
582
+ const empty = {
583
+ text: me?.text ?? "",
584
+ settled: false,
585
+ inLatestTurn: false,
586
+ isLastOfLatestTurn: false,
587
+ latestTurnText: "",
588
+ latestTurnKey: "",
589
+ streaming: false,
590
+ turnEndedAt: 0
591
+ };
592
+ if (!me) return empty;
593
+ const last = nodes[nodes.length - 1];
594
+ if (!last) return empty;
595
+ const latestKey = last.turnKey;
596
+ const inLatest = me.turnKey === latestKey;
597
+ const isLastOfLatest = last.messageId === String(messageId);
598
+ const merged = nodes.filter((n) => n.turnKey === latestKey).map((n) => n.text).filter((t) => t !== "").join("\n");
599
+ const turnEndedAt = last.time;
600
+ const streamingId = streamingMessageId(snapshot);
601
+ const streaming = streamingId === String(messageId);
602
+ return {
603
+ text: me.text,
604
+ // 在 finalized 列表里且不在流式中 = 这一轮已经说完
605
+ settled: !streaming,
606
+ inLatestTurn: inLatest,
607
+ isLastOfLatestTurn: isLastOfLatest,
608
+ latestTurnText: merged || me.text,
609
+ latestTurnKey: latestKey,
610
+ streaming,
611
+ turnEndedAt
612
+ };
613
+ }
614
+ function useAssistantInfo(useChat, messageId) {
615
+ return useChat((snapshot) => assistantInfoOf(snapshot, messageId));
616
+ }
617
+
618
+ // src/client/voice/ui.tsx
619
+ var import_jsx_runtime = require("react/jsx-runtime");
620
+ var CSS = `
621
+ .cv-btn{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;
622
+ padding:0;border:0;border-radius:6px;background:transparent;color:inherit;cursor:pointer;
623
+ opacity:.62;transition:opacity .15s ease,background .15s ease;flex:0 0 auto}
624
+ .cv-btn:hover:not(:disabled){opacity:1;background:rgba(128,128,128,.14)}
625
+ .cv-btn:disabled{opacity:.28;cursor:default}
626
+ .cv-btn--on{opacity:1;color:#4d6bfe}
627
+ .cv-spin{display:inline-block;width:13px;height:13px;border:2px solid currentColor;border-right-color:transparent;
628
+ border-radius:50%;animation:cv-spin .7s linear infinite}
629
+ @keyframes cv-spin{to{transform:rotate(360deg)}}
630
+ .cv-bars{display:inline-flex;align-items:flex-end;gap:2px;height:13px}
631
+ .cv-bars i{display:block;width:2.5px;border-radius:1px;background:currentColor;animation:cv-bar .9s ease-in-out infinite}
632
+ .cv-bars i:nth-child(1){height:5px;animation-delay:0s}
633
+ .cv-bars i:nth-child(2){height:12px;animation-delay:.15s}
634
+ .cv-bars i:nth-child(3){height:8px;animation-delay:.3s}
635
+ .cv-bars i:nth-child(4){height:13px;animation-delay:.45s}
636
+ @keyframes cv-bar{0%,100%{transform:scaleY(.35)}50%{transform:scaleY(1)}}
637
+
638
+ .cv-row{display:flex;align-items:center;gap:10px;width:100%;padding:2px 0}
639
+ .cv-row-main{flex:1 1 auto;min-width:0}
640
+ .cv-row-title{font-size:13px;line-height:20px}
641
+ .cv-row-desc{font-size:12px;line-height:18px;opacity:.62;margin-top:2px;
642
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
643
+ .cv-tag{flex:0 0 auto;font-size:11px;line-height:16px;padding:1px 7px;border-radius:999px;
644
+ border:1px solid currentColor;opacity:.7}
645
+ .cv-tag--ok{color:#2ea043;opacity:.9}
646
+ .cv-tag--err{color:#d1242f;opacity:.9}
647
+ .cv-panel{margin-top:8px;padding:12px;border-radius:10px;background:rgba(128,128,128,.08);
648
+ display:flex;flex-direction:column;gap:12px;font-size:12.5px;line-height:19px}
649
+ .cv-field{display:flex;flex-direction:column;gap:5px}
650
+ .cv-field label{opacity:.66;font-size:12px}
651
+ .cv-hint{font-size:11.5px;line-height:17px;opacity:.6}
652
+ .cv-input,.cv-textarea,.cv-select{width:100%;box-sizing:border-box;padding:6px 8px;border-radius:7px;
653
+ border:1px solid rgba(128,128,128,.34);background:rgba(255,255,255,.06);color:inherit;
654
+ font:inherit;font-size:12.5px;outline:none}
655
+ .cv-input:focus,.cv-textarea:focus,.cv-select:focus{border-color:#4d6bfe}
656
+ .cv-textarea{resize:vertical;min-height:52px;line-height:18px}
657
+ .cv-select{cursor:pointer}
658
+ .cv-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
659
+ .cv-primary{padding:5px 14px;border-radius:7px;border:0;background:#4d6bfe;color:#fff;
660
+ font:inherit;font-size:12.5px;cursor:pointer}
661
+ .cv-primary:disabled{opacity:.5;cursor:default}
662
+ .cv-ghost{padding:5px 12px;border-radius:7px;border:1px solid rgba(128,128,128,.4);
663
+ background:transparent;color:inherit;font:inherit;font-size:12.5px;cursor:pointer}
664
+ .cv-ghost:disabled{opacity:.5;cursor:default}
665
+ .cv-msg{font-size:12px;line-height:18px;opacity:.8;word-break:break-all}
666
+ .cv-msg--err{color:#d1242f;opacity:1}
667
+ .cv-msg--ok{color:#2ea043;opacity:1}
668
+ .cv-seg{display:inline-flex;border:1px solid rgba(128,128,128,.34);border-radius:8px;overflow:hidden}
669
+ .cv-seg button{padding:5px 16px;border:0;background:transparent;color:inherit;font:inherit;
670
+ font-size:12.5px;cursor:pointer;opacity:.72}
671
+ .cv-seg button+button{border-left:1px solid rgba(128,128,128,.34)}
672
+ .cv-seg button[data-on="1"]{background:#4d6bfe;color:#fff;opacity:1}
673
+ .cv-check{display:flex;align-items:center;gap:7px;cursor:pointer;user-select:none}
674
+ .cv-check input{width:14px;height:14px;cursor:pointer;accent-color:#4d6bfe}
675
+ .cv-file{display:none}
676
+
677
+ /* \u5168\u5C40\u542F\u7528\u5F00\u5173 */
678
+ .cv-switch{display:inline-flex;align-items:center;cursor:pointer;flex:0 0 auto}
679
+ .cv-switch input{position:absolute;opacity:0;width:0;height:0;pointer-events:none}
680
+ .cv-switch-track{position:relative;display:inline-block;width:34px;height:19px;border-radius:999px;
681
+ background:rgba(128,128,128,.4);transition:background .18s ease}
682
+ .cv-switch-thumb{position:absolute;top:2px;left:2px;width:15px;height:15px;border-radius:50%;
683
+ background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.28);transition:transform .18s ease}
684
+ .cv-switch input:checked+.cv-switch-track{background:#2ea043}
685
+ .cv-switch input:checked+.cv-switch-track .cv-switch-thumb{transform:translateX(15px)}
686
+ .cv-switch input:disabled+.cv-switch-track{opacity:.45;cursor:default}
687
+ .cv-switch:hover input:not(:disabled)+.cv-switch-track{filter:brightness(1.08)}
688
+ `;
689
+ function IconSpeaker() {
690
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
691
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M11 5 6 9H3v6h3l5 4V5z" }),
692
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M15.5 8.5a5 5 0 0 1 0 7" }),
693
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d: "M18.5 5.5a9 9 0 0 1 0 13" })
694
+ ] });
695
+ }
696
+ function PlayingBars() {
697
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "cv-bars", "aria-hidden": "true", children: [
698
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", {}),
699
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", {}),
700
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", {}),
701
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", {})
702
+ ] });
703
+ }
704
+ function SpeakerButton(props) {
705
+ const info = useAssistantInfo(props.useChat, String(props.messageId));
706
+ const [phase, setPhase] = (0, import_react.useState)("idle");
707
+ const [error, setError] = (0, import_react.useState)("");
708
+ const timer = (0, import_react.useRef)(void 0);
709
+ (0, import_react.useEffect)(() => () => {
710
+ window.clearInterval(timer.current);
711
+ }, []);
712
+ (0, import_react.useEffect)(() => () => {
713
+ if (getPlayback().messageId === String(props.messageId)) stopAll();
714
+ }, []);
715
+ const tick = (0, import_react.useCallback)(() => {
716
+ if (phase === "playing" && !isPlaying() && !isStreaming()) setPhase("idle");
717
+ }, [phase]);
718
+ (0, import_react.useEffect)(() => {
719
+ window.clearInterval(timer.current);
720
+ if (phase === "playing") timer.current = window.setInterval(tick, 350);
721
+ return () => window.clearInterval(timer.current);
722
+ }, [phase, tick]);
723
+ (0, import_react.useEffect)(() => {
724
+ if (phase !== "busy") return;
725
+ const t = window.setTimeout(() => {
726
+ if (!isStreaming() && !isPlaying()) {
727
+ setError("\u5408\u6210\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5");
728
+ setPhase("idle");
729
+ }
730
+ }, 9e4);
731
+ return () => window.clearTimeout(t);
732
+ }, [phase]);
733
+ const onClick = (0, import_react.useCallback)(async () => {
734
+ if (phase === "playing") {
735
+ stopAll();
736
+ setPhase("idle");
737
+ return;
738
+ }
739
+ if (phase === "busy") return;
740
+ const body = info.text.trim();
741
+ if (!body) return;
742
+ setError("");
743
+ setPhase("busy");
744
+ try {
745
+ let started = false;
746
+ await speakStream(
747
+ body,
748
+ { messageId: String(props.messageId), label: body, manual: true },
749
+ {
750
+ onStart: () => {
751
+ started = true;
752
+ setPhase("playing");
753
+ },
754
+ onDone: (r) => {
755
+ if (!started && !r?.cached) setPhase("idle");
756
+ },
757
+ onError: (m) => {
758
+ setError(m);
759
+ setPhase("idle");
760
+ }
761
+ }
762
+ );
763
+ if (!started && !isStreaming() && !isPlaying()) setPhase("idle");
764
+ } catch (e) {
765
+ setError(e.message);
766
+ setPhase("idle");
767
+ }
768
+ }, [phase, info.latestTurnText, info.text, props.messageId]);
769
+ const readable = info.text.trim();
770
+ const disabled = readable === "" || phase === "busy";
771
+ const title = error ? `\u6717\u8BFB\u5931\u8D25\uFF1A${error}` : readable === "" ? "\u8FD9\u6761\u56DE\u590D\u6CA1\u6709\u53EF\u6717\u8BFB\u7684\u6B63\u6587" : phase === "playing" ? "\u505C\u6B62\u64AD\u653E" : phase === "busy" ? "\u6B63\u5728\u5408\u6210\u2026" : "\u6717\u8BFB\u8FD9\u6761\u56DE\u590D";
772
+ const FRESH_MS = 12e4;
773
+ const autoRef = (0, import_react.useRef)(() => {
774
+ });
775
+ const tryAutoPlay = (0, import_react.useCallback)(() => {
776
+ const body = info.latestTurnText.trim();
777
+ const id = String(props.messageId);
778
+ if (!body) return;
779
+ if (!info.isLastOfLatestTurn) return;
780
+ if (!info.settled) return;
781
+ if (!shouldAutoPlay()) return;
782
+ if (hasAutoPlayed(info.latestTurnKey)) return;
783
+ if (info.turnEndedAt > 0 && Date.now() - info.turnEndedAt > FRESH_MS) return;
784
+ if (phase !== "idle") return;
785
+ markAutoPlayed(info.latestTurnKey);
786
+ setError("");
787
+ setPhase("busy");
788
+ let started = false;
789
+ void speakStream(
790
+ body,
791
+ { messageId: id, label: body },
792
+ {
793
+ onStart: () => {
794
+ started = true;
795
+ setPhase("playing");
796
+ },
797
+ onDone: (r) => {
798
+ if (!started && !r?.cached) setPhase("idle");
799
+ },
800
+ onError: (m) => {
801
+ setError(m);
802
+ setPhase("idle");
803
+ }
804
+ }
805
+ ).then(() => {
806
+ if (!started && !isStreaming() && !isPlaying()) setPhase("idle");
807
+ }).catch((e) => {
808
+ setError(e.message);
809
+ setPhase("idle");
810
+ });
811
+ }, [info.latestTurnText, info.isLastOfLatestTurn, info.settled, info.latestTurnKey, info.turnEndedAt, props.messageId, phase]);
812
+ autoRef.current = tryAutoPlay;
813
+ (0, import_react.useEffect)(
814
+ () => subscribeAutoFlags(() => {
815
+ if (shouldAutoPlay() && info.settled && info.latestTurnKey) {
816
+ markAutoPlayed(info.latestTurnKey);
817
+ }
818
+ }),
819
+ [info.latestTurnKey, info.settled]
820
+ );
821
+ (0, import_react.useEffect)(() => {
822
+ const t = window.setTimeout(() => autoRef.current(), 700);
823
+ return () => window.clearTimeout(t);
824
+ }, [info.latestTurnKey, info.settled, info.latestTurnText]);
825
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
826
+ "button",
827
+ {
828
+ type: "button",
829
+ className: `cv-btn${phase === "playing" ? " cv-btn--on" : ""}`,
830
+ onClick: () => void onClick(),
831
+ disabled,
832
+ title,
833
+ "aria-label": title,
834
+ children: phase === "busy" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cv-spin" }) : phase === "playing" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PlayingBars, {}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconSpeaker, {})
835
+ }
836
+ );
837
+ }
838
+ function SettingsRow() {
839
+ const [open, setOpen] = (0, import_react.useState)(false);
840
+ const [state, setState] = (0, import_react.useState)(void 0);
841
+ const [busy, setBusy] = (0, import_react.useState)("");
842
+ const [msg, setMsg] = (0, import_react.useState)("");
843
+ const [msgOk, setMsgOk] = (0, import_react.useState)(false);
844
+ const [dsKeyDraft, setDsKeyDraft] = (0, import_react.useState)("");
845
+ const [mimoKeyDraft, setMimoKeyDraft] = (0, import_react.useState)("");
846
+ const [styleDraft, setStyleDraft] = (0, import_react.useState)("");
847
+ const fileInput = (0, import_react.useRef)(null);
848
+ const refresh = (0, import_react.useCallback)(async () => {
849
+ try {
850
+ const s = await api.state();
851
+ setState(s);
852
+ updateAutoFlags(s.enabled, s.autoPlay);
853
+ setStyleDraft((prev) => prev === "" ? s.mimo.style : prev);
854
+ } catch (e) {
855
+ setMsg(`\u8BFB\u53D6\u72B6\u6001\u5931\u8D25\uFF1A${e.message}`);
856
+ setMsgOk(false);
857
+ }
858
+ }, []);
859
+ (0, import_react.useEffect)(() => {
860
+ void refresh();
861
+ const t = window.setInterval(() => {
862
+ void refresh();
863
+ }, open ? 2500 : 8e3);
864
+ return () => window.clearInterval(t);
865
+ }, [open, refresh]);
866
+ const run = (0, import_react.useCallback)(async (label, fn) => {
867
+ setBusy(label);
868
+ setMsg("");
869
+ try {
870
+ await fn();
871
+ } catch (e) {
872
+ setMsg(e.message);
873
+ setMsgOk(false);
874
+ } finally {
875
+ setBusy("");
876
+ }
877
+ }, []);
878
+ const patch = (0, import_react.useCallback)(
879
+ (body, okText) => run("patch", async () => {
880
+ const r = await api.config(body);
881
+ if (!r.ok) throw new Error(r.error ?? "\u4FDD\u5B58\u5931\u8D25");
882
+ await refresh();
883
+ if (okText) {
884
+ setMsg(`\u2713 ${okText}`);
885
+ setMsgOk(true);
886
+ }
887
+ }),
888
+ [run, refresh]
889
+ );
890
+ const engine = state?.engine ?? "deepseek";
891
+ const isMimo = engine === "mimo";
892
+ const enabled = state?.enabled ?? false;
893
+ const autoPlay = state?.autoPlay ?? false;
894
+ const cur = isMimo ? state?.mimo : state?.deepseek;
895
+ const hasKey = cur?.hasKey ?? false;
896
+ const onPickFile = (0, import_react.useCallback)(
897
+ (file) => {
898
+ if (!file) return;
899
+ void run("sample", async () => {
900
+ const r = await api.uploadSample(file);
901
+ if (!r.ok) throw new Error(r.error ?? "\u4E0A\u4F20\u5931\u8D25");
902
+ await refresh();
903
+ setMsg(`\u2713 \u6837\u672C\u5DF2\u4E0A\u4F20\uFF08${(file.size / 1024).toFixed(0)} KB\uFF09\uFF0C\u5DF2\u5207\u5230\u514B\u9686\u6A21\u5F0F`);
904
+ setMsgOk(true);
905
+ });
906
+ },
907
+ [run, refresh]
908
+ );
909
+ const engineName = isMimo ? "\u5C0F\u7C73 MiMo" : "DeepSeek";
910
+ const voiceName = isMimo ? state?.mimo.useClone ? "\u514B\u9686\u97F3\u8272" : state?.mimo.voices.find((v) => v.id === state?.mimo.voice)?.name ?? "\u2014" : state?.deepseek.voices.find((v) => v.id === state?.deepseek.voice)?.name ?? "\u2014";
911
+ const desc = !enabled ? "\u5DF2\u5173\u95ED" : hasKey ? `${engineName} \xB7 ${voiceName}${autoPlay ? " \xB7 \u81EA\u52A8\u64AD\u653E" : ""}` : `${engineName} \xB7 \u672A\u586B API Key`;
912
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [
913
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-row", children: [
914
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-row-main", children: [
915
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-row-title", children: "\u966A\u4F34\u8BED\u97F3" }),
916
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-row-desc", children: desc })
917
+ ] }),
918
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { className: "cv-switch", title: enabled ? "\u70B9\u51FB\u5173\u95ED\u966A\u4F34\u8BED\u97F3" : "\u70B9\u51FB\u542F\u7528\u966A\u4F34\u8BED\u97F3", children: [
919
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
920
+ "input",
921
+ {
922
+ type: "checkbox",
923
+ checked: enabled,
924
+ disabled: busy !== "",
925
+ onChange: (e) => void patch({ enabled: e.target.checked }, e.target.checked ? "\u5DF2\u542F\u7528" : "\u5DF2\u5173\u95ED")
926
+ }
927
+ ),
928
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cv-switch-track", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cv-switch-thumb" }) })
929
+ ] }),
930
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-ghost", onClick: () => setOpen((v) => !v), children: open ? "\u6536\u8D77" : "\u8BBE\u7F6E" })
931
+ ] }),
932
+ open && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-panel", children: [
933
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
934
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { className: "cv-check", style: { opacity: enabled ? 1 : 0.45 }, children: [
935
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
936
+ "input",
937
+ {
938
+ type: "checkbox",
939
+ checked: autoPlay,
940
+ disabled: busy !== "" || !enabled,
941
+ onChange: (e) => void patch({ autoPlay: e.target.checked }, e.target.checked ? "\u5DF2\u5F00\u542F\u81EA\u52A8\u64AD\u653E" : "\u5DF2\u5173\u95ED\u81EA\u52A8\u64AD\u653E")
942
+ }
943
+ ),
944
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "\u81EA\u52A8\u6717\u8BFB\u65B0\u56DE\u590D" })
945
+ ] }),
946
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-hint", children: enabled ? "\u5F00\u542F\u540E\uFF0C\u6BCF\u8F6E\u56DE\u590D\u7ED3\u675F\u65F6\u81EA\u52A8\u6717\u8BFB\uFF08\u624B\u52A8\u70B9\u5587\u53ED\u4E0D\u53D7\u5F71\u54CD\uFF09\u3002" : "\u9700\u8981\u5148\u542F\u7528\u966A\u4F34\u8BED\u97F3\uFF0C\u624D\u80FD\u5F00\u542F\u81EA\u52A8\u64AD\u653E\u3002" })
947
+ ] }),
948
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
949
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "\u8BED\u97F3\u5F15\u64CE" }),
950
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-seg", children: [
951
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", "data-on": engine === "deepseek" ? "1" : "0", onClick: () => void patch({ engine: "deepseek" }, "\u5DF2\u5207\u6362\u5230 DeepSeek"), disabled: busy !== "", children: "DeepSeek" }),
952
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", "data-on": engine === "mimo" ? "1" : "0", onClick: () => void patch({ engine: "mimo" }, "\u5DF2\u5207\u6362\u5230\u5C0F\u7C73 MiMo\uFF08\u9650\u65F6\u514D\u8D39\uFF09"), disabled: busy !== "", children: "\u5C0F\u7C73 MiMo" })
953
+ ] }),
954
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-hint", children: "\u5207\u6362\u7ACB\u5373\u751F\u6548\uFF0C\u4E0D\u7528\u4FDD\u5B58\u3002" })
955
+ ] }),
956
+ isMimo ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
957
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "\u5C0F\u7C73 API Key\uFF08api.xiaomimimo.com \u63A7\u5236\u53F0\u83B7\u53D6\uFF09" }),
958
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-actions", children: [
959
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
960
+ "input",
961
+ {
962
+ type: "password",
963
+ className: "cv-input",
964
+ style: { flex: "1 1 220px" },
965
+ value: mimoKeyDraft,
966
+ spellCheck: false,
967
+ autoComplete: "off",
968
+ onChange: (e) => setMimoKeyDraft(e.target.value),
969
+ onKeyDown: (e) => {
970
+ if (e.key === "Enter" && mimoKeyDraft.trim()) void patch({ mimoKey: mimoKeyDraft.trim() }, "API Key \u5DF2\u4FDD\u5B58").then(() => setMimoKeyDraft(""));
971
+ },
972
+ placeholder: state?.mimo.hasKey ? `\u5DF2\u4FDD\u5B58 \xB7 \u672B\u56DB\u4F4D ${state.mimo.keyTail}` : "\u586B MiMo API Key"
973
+ }
974
+ ),
975
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-primary", onClick: () => {
976
+ const k = mimoKeyDraft.trim();
977
+ if (k) void patch({ mimoKey: k }, "API Key \u5DF2\u4FDD\u5B58").then(() => setMimoKeyDraft(""));
978
+ }, disabled: busy !== "" || mimoKeyDraft.trim() === "", children: "\u4FDD\u5B58" })
979
+ ] })
980
+ ] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
981
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "DeepSeek API Key\uFF08platform.deepseek.com \u7533\u8BF7\uFF09" }),
982
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-actions", children: [
983
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
984
+ "input",
985
+ {
986
+ type: "password",
987
+ className: "cv-input",
988
+ style: { flex: "1 1 220px" },
989
+ value: dsKeyDraft,
990
+ spellCheck: false,
991
+ autoComplete: "off",
992
+ onChange: (e) => setDsKeyDraft(e.target.value),
993
+ onKeyDown: (e) => {
994
+ if (e.key === "Enter" && dsKeyDraft.trim()) void patch({ deepseekKey: dsKeyDraft.trim() }, "API Key \u5DF2\u4FDD\u5B58").then(() => setDsKeyDraft(""));
995
+ },
996
+ placeholder: state?.deepseek.hasKey ? `\u5DF2\u4FDD\u5B58 \xB7 \u672B\u56DB\u4F4D ${state.deepseek.keyTail}` : "sk-..."
997
+ }
998
+ ),
999
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-primary", onClick: () => {
1000
+ const k = dsKeyDraft.trim();
1001
+ if (k) void patch({ deepseekKey: k }, "API Key \u5DF2\u4FDD\u5B58").then(() => setDsKeyDraft(""));
1002
+ }, disabled: busy !== "" || dsKeyDraft.trim() === "", children: "\u4FDD\u5B58" })
1003
+ ] })
1004
+ ] }),
1005
+ isMimo && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1006
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
1007
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "\u98CE\u683C\u6307\u4EE4\uFF08\u4F1A\u4F5C\u4E3A user \u6D88\u606F\u4EA4\u7ED9\u6A21\u578B\uFF09" }),
1008
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1009
+ "textarea",
1010
+ {
1011
+ className: "cv-textarea",
1012
+ value: styleDraft,
1013
+ spellCheck: false,
1014
+ onChange: (e) => setStyleDraft(e.target.value),
1015
+ onBlur: () => {
1016
+ if (styleDraft !== (state?.mimo.style ?? "")) void patch({ mimoStyle: styleDraft }, "\u98CE\u683C\u5DF2\u4FDD\u5B58");
1017
+ },
1018
+ placeholder: state?.mimo.defaultStyle ?? "\u5C11\u5973\u97F3\uFF0C\u8BED\u6C14\u6E29\u67D4\uFF0C\u81EA\u7136\u8BED\u901F\uFF0C\u6C14\u58F0\u8F7B\u5FAE"
1019
+ }
1020
+ ),
1021
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-hint", children: "\u7559\u7A7A = \u4E0D\u53D1\u9001\u98CE\u683C\u6307\u4EE4\uFF0C\u4EA4\u7ED9\u670D\u52A1\u7AEF\u9ED8\u8BA4\u3002\u70B9\u300C\u6E05\u7A7A\u98CE\u683C\u300D\u53EF\u4E00\u952E\u6E05\u7A7A\u3002" }),
1022
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-hint", children: [
1023
+ "\u6B63\u6587\u91CC\u4E5F\u53EF\u4EE5\u63D2\u6807\u7B7E\uFF1A\u5F00\u5934\u5199 ",
1024
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "(\u6175\u61D2)" }),
1025
+ "\u3001\u53E5\u4E2D\u63D2 ",
1026
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "[\u53F9\u6C14]" }),
1027
+ "\u3001",
1028
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "[\u8F7B\u7B11]" }),
1029
+ "\u3001",
1030
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: "[\u8BED\u901F\u52A0\u5FEB]" }),
1031
+ " \u7B49\uFF0C\u6A21\u578B\u4F1A\u7167\u7740\u6F14\u3002"
1032
+ ] }),
1033
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-actions", children: [
1034
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-ghost", onClick: () => {
1035
+ setStyleDraft("");
1036
+ void patch({ mimoStyle: "" }, "\u5DF2\u6E05\u7A7A\u98CE\u683C\uFF08\u4E2D\u6027\u81EA\u7136\uFF09");
1037
+ }, disabled: busy !== "", children: "\u6E05\u7A7A\u98CE\u683C" }),
1038
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-ghost", onClick: () => {
1039
+ setStyleDraft(state?.mimo.defaultStyle ?? "");
1040
+ void patch({ mimoStyle: state?.mimo.defaultStyle ?? "" }, "\u5DF2\u6062\u590D\u9ED8\u8BA4\u98CE\u683C");
1041
+ }, disabled: busy !== "", children: "\u6062\u590D\u9ED8\u8BA4" })
1042
+ ] })
1043
+ ] }),
1044
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
1045
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { className: "cv-check", children: [
1046
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1047
+ "input",
1048
+ {
1049
+ type: "checkbox",
1050
+ checked: state?.mimo.useClone ?? false,
1051
+ onChange: (e) => void patch({ mimoUseClone: e.target.checked }, e.target.checked ? "\u5DF2\u5207\u5230\u514B\u9686\u97F3\u8272" : "\u5DF2\u5207\u56DE\u9884\u7F6E\u97F3\u8272"),
1052
+ disabled: busy !== "" || !(state?.mimo.hasSample ?? false)
1053
+ }
1054
+ ),
1055
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "\u4F7F\u7528\u514B\u9686\u97F3\u8272\uFF08\u57FA\u4E8E\u4E0A\u4F20\u7684\u97F3\u9891\u6837\u672C\uFF09" })
1056
+ ] }),
1057
+ !state?.mimo.hasSample ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-hint", children: "\u5148\u4E0A\u4F20\u4E00\u6BB5\u6E05\u6670\u4EBA\u58F0\uFF08wav / mp3\uFF0C\u22651 \u79D2\uFF09\u624D\u80FD\u5F00\u542F\u3002" }) : null
1058
+ ] }),
1059
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
1060
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "\u514B\u9686\u6837\u672C" }),
1061
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-actions", children: [
1062
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1063
+ "input",
1064
+ {
1065
+ ref: fileInput,
1066
+ type: "file",
1067
+ accept: "audio/wav,audio/mpeg,audio/mp3,.wav,.mp3",
1068
+ className: "cv-file",
1069
+ onChange: (e) => {
1070
+ onPickFile(e.target.files?.[0]);
1071
+ e.target.value = "";
1072
+ }
1073
+ }
1074
+ ),
1075
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-primary", onClick: () => fileInput.current?.click(), disabled: busy !== "", children: "\u9009\u62E9\u97F3\u9891\u6587\u4EF6" }),
1076
+ state?.mimo.hasSample ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1077
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cv-msg", children: state.mimo.sample }),
1078
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "cv-ghost", onClick: () => void run("sample", async () => {
1079
+ await api.clearSample();
1080
+ await refresh();
1081
+ setMsg("\u2713 \u6837\u672C\u5DF2\u5220\u9664\uFF0C\u5DF2\u5207\u56DE\u9884\u7F6E\u97F3\u8272");
1082
+ setMsgOk(true);
1083
+ }), disabled: busy !== "", children: "\u5220\u9664\u6837\u672C" })
1084
+ ] }) : null
1085
+ ] }),
1086
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-hint", children: "\u514B\u9686\u6A21\u5F0F\u4E0B\u6BCF\u6B21\u5408\u6210\u90FD\u4F1A\u628A\u6837\u672C\u4E00\u8D77\u53D1\u7ED9\u5C0F\u7C73\uFF0C\u6837\u672C\u4E0D\u4F1A\u4E0A\u4F20\u5230\u522B\u5904\u3002" })
1087
+ ] }),
1088
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
1089
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("label", { children: [
1090
+ "\u9884\u7F6E\u97F3\u8272",
1091
+ state?.mimo.useClone ? "\uFF08\u514B\u9686\u6A21\u5F0F\u4E0B\u4E0D\u751F\u6548\uFF09" : ""
1092
+ ] }),
1093
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1094
+ "select",
1095
+ {
1096
+ className: "cv-select",
1097
+ value: state?.mimo.voice ?? "\u51B0\u7CD6",
1098
+ onChange: (e) => void patch({ mimoVoice: e.target.value }, "\u97F3\u8272\u5DF2\u5207\u6362"),
1099
+ disabled: busy !== "" || (state?.mimo.useClone ?? false),
1100
+ children: (state?.mimo.voices ?? []).map((v) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { value: v.id, children: v.name }, v.id))
1101
+ }
1102
+ )
1103
+ ] })
1104
+ ] }),
1105
+ !isMimo && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
1106
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "\u97F3\u8272" }),
1107
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1108
+ "select",
1109
+ {
1110
+ className: "cv-select",
1111
+ value: state?.deepseek.voice ?? "stella",
1112
+ onChange: (e) => void patch({ deepseekVoice: e.target.value }, "\u97F3\u8272\u5DF2\u5207\u6362"),
1113
+ disabled: busy !== "",
1114
+ children: (state?.deepseek.voices ?? []).map((v) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("option", { value: v.id, children: v.name }, v.id))
1115
+ }
1116
+ )
1117
+ ] }),
1118
+ state?.lastError ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-msg cv-msg--err", children: [
1119
+ "\u4E0A\u6B21\u9519\u8BEF\uFF1A",
1120
+ state.lastError
1121
+ ] }) : null,
1122
+ msg ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `cv-msg${msgOk ? " cv-msg--ok" : " cv-msg--err"}`, children: msg }) : null,
1123
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-field", children: [
1124
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: "\u97F3\u9891\u7F13\u5B58" }),
1125
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "cv-actions", children: [
1126
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "cv-msg", children: state?.cache ? `${state.cache.count} \u4E2A\u6587\u4EF6 \xB7 ${(state.cache.bytes / 1048576).toFixed(1)} MB` : "\u2014" }),
1127
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1128
+ "button",
1129
+ {
1130
+ type: "button",
1131
+ className: "cv-ghost",
1132
+ disabled: busy !== "" || !(state?.cache?.count ?? 0),
1133
+ onClick: () => void run("cache", async () => {
1134
+ const r = await api.clearCache();
1135
+ await refresh();
1136
+ setMsg(`\u2713 \u5DF2\u6E05\u7A7A ${r.removed} \u4E2A\u6587\u4EF6\uFF0C\u91CA\u653E ${(r.freedBytes / 1048576).toFixed(1)} MB`);
1137
+ setMsgOk(true);
1138
+ }),
1139
+ children: "\u6E05\u7A7A\u7F13\u5B58"
1140
+ }
1141
+ )
1142
+ ] }),
1143
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "cv-hint", children: "\u540C\u4E00\u53E5\u8BDD\u518D\u6B21\u6717\u8BFB\u4F1A\u76F4\u63A5\u547D\u4E2D\u7F13\u5B58\uFF08\u96F6\u7B49\u5F85\u3001\u96F6\u8D39\u7528\uFF09\u3002\u8D85\u8FC7 200 MB \u6216 7 \u5929\u672A\u4F7F\u7528\u4F1A\u81EA\u52A8\u56DE\u6536\u3002" })
1144
+ ] })
1145
+ ] })
1146
+ ] });
1147
+ }
1148
+
1149
+ // src/client/voice/index.ts
1150
+ function apply(ctx) {
1151
+ ctx.effect(() => {
1152
+ const style = document.createElement("style");
1153
+ style.dataset.plugin = "companion-voice";
1154
+ style.textContent = CSS;
1155
+ document.head.appendChild(style);
1156
+ return () => {
1157
+ style.remove();
1158
+ };
1159
+ }, "companion-voice: styles");
1160
+ ctx.effect(() => {
1161
+ let alive = true;
1162
+ const sync = () => {
1163
+ void api.state().then((s) => {
1164
+ if (alive) updateAutoFlags(s.enabled, s.autoPlay);
1165
+ }).catch(() => {
1166
+ });
1167
+ };
1168
+ sync();
1169
+ const timer = window.setInterval(sync, 15e3);
1170
+ return () => {
1171
+ alive = false;
1172
+ window.clearInterval(timer);
1173
+ };
1174
+ }, "companion-voice: auto flags");
1175
+ ctx.slots.inject(
1176
+ "conversation.chat.assistant-actions",
1177
+ () => ctx.slots.register({ name: "conversation.chat.assistant-actions", id: "companion-voice-speak", order: 40 }, SpeakerButton)
1178
+ );
1179
+ ctx.slots.inject(
1180
+ "settings.general.item",
1181
+ () => ctx.slots.register({ name: "settings.general.item", id: "companion-voice-settings", order: 40 }, SettingsRow)
1182
+ );
1183
+ }
1184
+
1185
+ // src/client/mic.tsx
1186
+ var import_react2 = require("react");
1187
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1188
+ var FEED = "/api/spoon-companion/asr/feed";
1189
+ var CLOSE = "/api/spoon-companion/asr/close";
1190
+ var STATUS = "/api/spoon-companion/asr/status";
1191
+ var CALL = "/api/spoon-companion/call";
1192
+ var lastLoggedRef = null;
1193
+ var TAG = "[spoon-companion]";
1194
+ var TARGET_RATE = 16e3;
1195
+ var SILENCE_MS = 1800;
1196
+ var MAX_UTTERANCE_MS = 2e4;
1197
+ var VOICE_LEVEL = 8e-3;
1198
+ var MAX_QUEUE = 8;
1199
+ var BUFFER_SIZE = 8192;
1200
+ function toBase64(arr) {
1201
+ const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
1202
+ let binary = "";
1203
+ const CHUNK = 32768;
1204
+ for (let i = 0; i < bytes.length; i += CHUNK) {
1205
+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
1206
+ }
1207
+ return btoa(binary);
1208
+ }
1209
+ function rms(arr) {
1210
+ let sum = 0;
1211
+ let n = 0;
1212
+ for (let i = 0; i < arr.length; i += 4) {
1213
+ sum += arr[i] * arr[i];
1214
+ n++;
1215
+ }
1216
+ return Math.sqrt(sum / Math.max(1, n));
1217
+ }
1218
+ function findInput() {
1219
+ return document.querySelector(
1220
+ 'textarea:not([readonly]), [contenteditable="true"]'
1221
+ );
1222
+ }
1223
+ function fillInput(text) {
1224
+ const el = findInput();
1225
+ if (!el) {
1226
+ console.warn(`${TAG} \u627E\u4E0D\u5230\u8F93\u5165\u6846`);
1227
+ return;
1228
+ }
1229
+ if (el instanceof HTMLTextAreaElement) {
1230
+ const tracker = el._valueTracker;
1231
+ if (tracker) tracker.setValue("");
1232
+ const desc = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
1233
+ if (desc?.set) desc.set.call(el, text);
1234
+ else el.value = text;
1235
+ } else {
1236
+ el.textContent = text;
1237
+ el.focus();
1238
+ }
1239
+ el.dispatchEvent(new Event("input", { bubbles: true }));
1240
+ el.dispatchEvent(new Event("change", { bubbles: true }));
1241
+ }
1242
+ function submitInput() {
1243
+ const el = findInput();
1244
+ const btn = document.querySelector(
1245
+ 'button[aria-label*="\u53D1\u9001"], button[aria-label*="Send" i], button[title*="\u53D1\u9001"], button[type="submit"]'
1246
+ );
1247
+ if (btn && !btn.disabled) {
1248
+ btn.click();
1249
+ console.log(`${TAG} \u70B9\u4E86\u53D1\u9001\u6309\u94AE`);
1250
+ return;
1251
+ }
1252
+ if (!el) {
1253
+ console.warn(`${TAG} \u65E2\u6CA1\u6709\u53D1\u9001\u6309\u94AE\u4E5F\u6CA1\u6709\u8F93\u5165\u6846`);
1254
+ return;
1255
+ }
1256
+ el.focus();
1257
+ for (const type of ["keydown", "keyup"]) {
1258
+ el.dispatchEvent(
1259
+ new KeyboardEvent(type, { key: "Enter", code: "Enter", bubbles: true, cancelable: true })
1260
+ );
1261
+ }
1262
+ console.log(`${TAG} \u6CA1\u6709\u53D1\u9001\u6309\u94AE\uFF0C\u8BD5\u4E86\u56DE\u8F66`);
1263
+ }
1264
+ async function setCall(on) {
1265
+ try {
1266
+ const res = await fetch(CALL, {
1267
+ method: "POST",
1268
+ headers: { "Content-Type": "application/json" },
1269
+ body: JSON.stringify({ on })
1270
+ });
1271
+ const data = await res.json().catch(() => null);
1272
+ if (lastLoggedRef !== data?.on) {
1273
+ lastLoggedRef = data?.on === true;
1274
+ console.log(`${TAG} \u901A\u8BDD\u72B6\u6001 \u2192 ${data?.on ? "\u5F00" : "\u5173"}\uFF08HTTP ${res.status}\uFF09`);
1275
+ }
1276
+ } catch (error) {
1277
+ console.warn(`${TAG} \u901A\u8BDD\u72B6\u6001\u901A\u77E5\u5931\u8D25`, error);
1278
+ }
1279
+ }
1280
+ function sessionIdOf(props) {
1281
+ const anyProps = props;
1282
+ const direct = anyProps?.sessionId ?? anyProps?.session?.id ?? anyProps?.scope?.session?.id;
1283
+ return typeof direct === "string" ? direct : "";
1284
+ }
1285
+ function VoiceButton(props) {
1286
+ const [on, setOn] = (0, import_react2.useState)(false);
1287
+ const [busy, setBusy] = (0, import_react2.useState)(false);
1288
+ const [level, setLevel] = (0, import_react2.useState)(0);
1289
+ const sendRef = (0, import_react2.useRef)(props.send);
1290
+ sendRef.current = props.send;
1291
+ const propsRef = (0, import_react2.useRef)(props);
1292
+ propsRef.current = props;
1293
+ const ctxRef = (0, import_react2.useRef)(null);
1294
+ const streamRef = (0, import_react2.useRef)(null);
1295
+ const nodeRef = (0, import_react2.useRef)(null);
1296
+ const asrIdRef = (0, import_react2.useRef)("");
1297
+ const lastVoiceRef = (0, import_react2.useRef)(0);
1298
+ const startedRef = (0, import_react2.useRef)(0);
1299
+ const textRef = (0, import_react2.useRef)("");
1300
+ const nativeRateRef = (0, import_react2.useRef)(TARGET_RATE);
1301
+ const aliveRef = (0, import_react2.useRef)(true);
1302
+ const spokeRef = (0, import_react2.useRef)(false);
1303
+ const queueRef = (0, import_react2.useRef)([]);
1304
+ const pumpingRef = (0, import_react2.useRef)(false);
1305
+ const flushingRef = (0, import_react2.useRef)(false);
1306
+ const feedCountRef = (0, import_react2.useRef)(0);
1307
+ const hardStop = (0, import_react2.useCallback)(async (quiet = false) => {
1308
+ queueRef.current = [];
1309
+ try {
1310
+ nodeRef.current?.disconnect();
1311
+ } catch {
1312
+ }
1313
+ nodeRef.current = null;
1314
+ try {
1315
+ streamRef.current?.getTracks().forEach((t) => t.stop());
1316
+ } catch {
1317
+ }
1318
+ streamRef.current = null;
1319
+ try {
1320
+ await ctxRef.current?.close();
1321
+ } catch {
1322
+ }
1323
+ ctxRef.current = null;
1324
+ setOn(false);
1325
+ setLevel(0);
1326
+ if (!quiet) void setCall(false);
1327
+ }, []);
1328
+ (0, import_react2.useEffect)(() => {
1329
+ aliveRef.current = true;
1330
+ return () => {
1331
+ aliveRef.current = false;
1332
+ void hardStop(true);
1333
+ };
1334
+ }, []);
1335
+ (0, import_react2.useEffect)(() => {
1336
+ if (!on) return;
1337
+ void setCall(true);
1338
+ const timer = window.setInterval(() => {
1339
+ if (aliveRef.current) void setCall(true);
1340
+ }, 1500);
1341
+ return () => window.clearInterval(timer);
1342
+ }, [on]);
1343
+ const flush = (0, import_react2.useCallback)(async () => {
1344
+ if (flushingRef.current) return;
1345
+ flushingRef.current = true;
1346
+ const id = asrIdRef.current;
1347
+ asrIdRef.current = "";
1348
+ let final = textRef.current;
1349
+ if (id) {
1350
+ try {
1351
+ const res = await fetch(CLOSE, {
1352
+ method: "POST",
1353
+ headers: { "Content-Type": "application/json" },
1354
+ body: JSON.stringify({ streamId: id })
1355
+ });
1356
+ const data = await res.json();
1357
+ if (data?.text) final = data.text;
1358
+ } catch {
1359
+ }
1360
+ }
1361
+ textRef.current = "";
1362
+ spokeRef.current = false;
1363
+ queueRef.current = [];
1364
+ const trimmed = final.trim();
1365
+ if (trimmed) {
1366
+ console.log(`${TAG} \u8BC6\u522B\u5B8C\u6210\uFF1A\u300C${trimmed}\u300D`);
1367
+ const sid = sessionIdOf(propsRef.current);
1368
+ const sender = sendRef.current;
1369
+ const ok = sid && sender ? await sender(sid, trimmed) : false;
1370
+ if (ok) {
1371
+ console.log(`${TAG} \u5DF2\u901A\u8FC7 session.prompt \u9001\u51FA`);
1372
+ } else {
1373
+ console.warn(`${TAG} \u4F1A\u8BDD\u63A5\u53E3\u4E0D\u53EF\u7528\uFF08sid=${sid || "\u7A7A"}\uFF09\uFF0C\u9000\u56DE DOM`);
1374
+ fillInput(trimmed);
1375
+ window.setTimeout(() => submitInput(), 120);
1376
+ }
1377
+ lastVoiceRef.current = Date.now();
1378
+ startedRef.current = Date.now();
1379
+ spokeRef.current = false;
1380
+ flushingRef.current = false;
1381
+ return;
1382
+ }
1383
+ lastVoiceRef.current = Date.now();
1384
+ startedRef.current = Date.now();
1385
+ flushingRef.current = false;
1386
+ }, []);
1387
+ const pump = (0, import_react2.useCallback)(async () => {
1388
+ if (pumpingRef.current) return;
1389
+ pumpingRef.current = true;
1390
+ try {
1391
+ while (queueRef.current.length > 0 && aliveRef.current) {
1392
+ const pcm = queueRef.current.shift();
1393
+ if (!pcm) break;
1394
+ try {
1395
+ const res = await fetch(FEED, {
1396
+ method: "POST",
1397
+ headers: { "Content-Type": "application/json" },
1398
+ body: JSON.stringify({ pcm: toBase64(pcm), rate: nativeRateRef.current })
1399
+ });
1400
+ const data = await res.json();
1401
+ if (!aliveRef.current) return;
1402
+ if (typeof data?.level === "number") {
1403
+ setLevel(data.level > 0.01 ? Math.min(1, data.level * 12) : 0);
1404
+ feedCountRef.current++;
1405
+ if (feedCountRef.current % 6 === 0) {
1406
+ console.log(`${TAG} \u97F3\u91CF ${data.level.toFixed(5)}\uFF08\u4EBA\u58F0\u901A\u5E38 >0.02\uFF09`);
1407
+ }
1408
+ }
1409
+ if (data?.streamId) asrIdRef.current = data.streamId;
1410
+ if (data?.text) {
1411
+ textRef.current = data.text;
1412
+ fillInput(data.text);
1413
+ }
1414
+ const silentFor = Date.now() - lastVoiceRef.current;
1415
+ const tooLong = Date.now() - startedRef.current > MAX_UTTERANCE_MS;
1416
+ if (spokeRef.current && (silentFor > SILENCE_MS || tooLong)) {
1417
+ await flush();
1418
+ }
1419
+ } catch (error) {
1420
+ console.warn(`${TAG} \u9001\u97F3\u9891\u5931\u8D25`, error);
1421
+ }
1422
+ }
1423
+ } finally {
1424
+ pumpingRef.current = false;
1425
+ }
1426
+ }, [flush]);
1427
+ const start = (0, import_react2.useCallback)(async () => {
1428
+ setBusy(true);
1429
+ try {
1430
+ const st = await (await fetch(STATUS)).json();
1431
+ if (!st?.ready) {
1432
+ console.warn(`${TAG} \u6A21\u578B\u7F3A\u5931: ${st?.missing?.join(", ")}`);
1433
+ setBusy(false);
1434
+ return;
1435
+ }
1436
+ const media = await navigator.mediaDevices.getUserMedia({ audio: true });
1437
+ streamRef.current = media;
1438
+ const track = media.getAudioTracks()[0];
1439
+ console.log(`${TAG} \u9EA6\u514B\u98CE: ${track?.label ?? "\u672A\u77E5"}`);
1440
+ console.log(`${TAG} slot props: ${JSON.stringify(Object.keys(propsRef.current))}`);
1441
+ console.log(`${TAG} \u89E3\u6790\u51FA\u7684 sessionId: ${sessionIdOf(propsRef.current) || "(\u7A7A)"}`);
1442
+ const audioCtx = new AudioContext();
1443
+ ctxRef.current = audioCtx;
1444
+ if (audioCtx.state === "suspended") await audioCtx.resume();
1445
+ nativeRateRef.current = audioCtx.sampleRate;
1446
+ console.log(`${TAG} \u91C7\u6837\u7387 ${audioCtx.sampleRate}Hz`);
1447
+ const source = audioCtx.createMediaStreamSource(media);
1448
+ const node = audioCtx.createScriptProcessor(BUFFER_SIZE, 1, 1);
1449
+ nodeRef.current = node;
1450
+ const mute = audioCtx.createGain();
1451
+ mute.gain.value = 0;
1452
+ source.connect(node);
1453
+ node.connect(mute);
1454
+ mute.connect(audioCtx.destination);
1455
+ textRef.current = "";
1456
+ queueRef.current = [];
1457
+ spokeRef.current = false;
1458
+ feedCountRef.current = 0;
1459
+ lastVoiceRef.current = Date.now();
1460
+ startedRef.current = Date.now();
1461
+ node.onaudioprocess = (ev) => {
1462
+ if (!aliveRef.current) return;
1463
+ const pcm = new Float32Array(ev.inputBuffer.getChannelData(0));
1464
+ if (rms(pcm) > VOICE_LEVEL) {
1465
+ lastVoiceRef.current = Date.now();
1466
+ spokeRef.current = true;
1467
+ }
1468
+ if (queueRef.current.length >= MAX_QUEUE) queueRef.current.shift();
1469
+ queueRef.current.push(pcm);
1470
+ void pump();
1471
+ };
1472
+ setOn(true);
1473
+ setBusy(false);
1474
+ void setCall(true);
1475
+ console.log(`${TAG} \u5F00\u59CB\u542C\uFF08\u4E32\u884C\u63A8\u9001\uFF09`);
1476
+ } catch (error) {
1477
+ console.warn(`${TAG} \u5F00\u9EA6\u5931\u8D25`, error);
1478
+ setBusy(false);
1479
+ await hardStop();
1480
+ }
1481
+ }, [hardStop, pump]);
1482
+ const toggle = (0, import_react2.useCallback)(async () => {
1483
+ if (busy) return;
1484
+ if (on) {
1485
+ await flush();
1486
+ await hardStop();
1487
+ } else {
1488
+ await start();
1489
+ }
1490
+ }, [busy, on, flush, hardStop, start]);
1491
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1492
+ "button",
1493
+ {
1494
+ type: "button",
1495
+ onClick: () => void toggle(),
1496
+ disabled: busy,
1497
+ "aria-pressed": on,
1498
+ title: on ? level > 0 ? "\u6B63\u5728\u542C\u4F60\u8BF4\u8BDD" : "\u5DF2\u5F00\u9EA6\uFF0C\u7B49\u4E00\u4E0B\u58F0\u97F3" : "\u5F00\u59CB\u8BED\u97F3",
1499
+ "data-spoon-mic": on ? "on" : "off",
1500
+ className: `sp-mic${on ? " sp-mic--on" : ""}${busy ? " sp-mic--busy" : ""}${level > 0 ? " sp-mic--hearing" : ""}`,
1501
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: [
1502
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z" }),
1503
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M19 10v1a7 7 0 0 1-14 0v-1" }),
1504
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", y1: "18", x2: "12", y2: "22" })
1505
+ ] })
1506
+ }
1507
+ );
1508
+ }
1509
+ var MIC_CSS = `
1510
+ .sp-mic {
1511
+ display: inline-flex; align-items: center; justify-content: center;
1512
+ width: 30px; height: 30px; padding: 0;
1513
+ border: 1px solid transparent; border-radius: 8px;
1514
+ background: transparent; color: inherit; opacity: 0.55; cursor: pointer;
1515
+ pointer-events: auto; position: relative; z-index: 1;
1516
+ transition: opacity 120ms ease, color 120ms ease, background 120ms ease;
1517
+ }
1518
+ .sp-mic:hover:not(:disabled) { opacity: 1; background: rgba(127,127,127,.12); }
1519
+ .sp-mic:disabled { cursor: default; }
1520
+ .sp-mic--on {
1521
+ opacity: 1; color: #e0455a;
1522
+ background: rgba(224,69,90,.14);
1523
+ border-color: rgba(224,69,90,.35);
1524
+ animation: sp-mic-pulse 1.6s ease-in-out infinite;
1525
+ }
1526
+ .sp-mic--hearing {
1527
+ color: #16a34a;
1528
+ background: rgba(22,163,74,.16);
1529
+ border-color: rgba(22,163,74,.5);
1530
+ animation: sp-mic-hearing .9s ease-in-out infinite;
1531
+ }
1532
+ .sp-mic--busy { opacity: .4; }
1533
+ @keyframes sp-mic-pulse {
1534
+ 0%,100% { box-shadow: 0 0 0 0 rgba(224,69,90,.35); }
1535
+ 50% { box-shadow: 0 0 0 5px rgba(224,69,90,0); }
1536
+ }
1537
+ @keyframes sp-mic-hearing {
1538
+ 0%,100% { box-shadow: 0 0 0 0 rgba(22,163,74,.4); }
1539
+ 50% { box-shadow: 0 0 0 6px rgba(22,163,74,0); }
1540
+ }
1541
+ `;
1542
+
1543
+ // src/client/index.ts
1544
+ var inject = ["slots", "sessions"];
1545
+ function apply2(ctx) {
1546
+ try {
1547
+ applyCleanup(ctx);
1548
+ } catch {
1549
+ }
1550
+ const sessions = ctx.sessions;
1551
+ const send = async (sessionId, text) => {
1552
+ if (!sessionId) return false;
1553
+ try {
1554
+ const binding = sessions?.binding?.(sessionId);
1555
+ const session = binding?.session;
1556
+ if (typeof session?.prompt === "function") {
1557
+ await session.prompt([{ type: "text", text }], "steer");
1558
+ return true;
1559
+ }
1560
+ console.warn("[spoon-companion] \u4F1A\u8BDD\u5BF9\u8C61\u4E0A\u6CA1\u6709 prompt \u65B9\u6CD5");
1561
+ } catch (error) {
1562
+ console.warn("[spoon-companion] \u8C03 prompt \u5931\u8D25", error);
1563
+ }
1564
+ return false;
1565
+ };
1566
+ try {
1567
+ ctx.effect(() => {
1568
+ const style = document.createElement("style");
1569
+ style.dataset.plugin = "spoon-companion-mic";
1570
+ style.textContent = MIC_CSS;
1571
+ document.head.appendChild(style);
1572
+ return () => {
1573
+ style.remove();
1574
+ };
1575
+ }, "spoon-companion: mic styles");
1576
+ ctx.slots.inject(
1577
+ "conversation.input.right",
1578
+ () => ctx.slots.register(
1579
+ {
1580
+ name: "conversation.input.right",
1581
+ id: "spoon-companion-mic",
1582
+ order: 70
1583
+ },
1584
+ (props) => VoiceButton({ ...props, send })
1585
+ )
1586
+ );
1587
+ } catch {
1588
+ }
1589
+ apply(ctx);
1590
+ }
1591
+ return module.exports; } });
1592
+ //# sourceMappingURL=client.js.map