dsh-folia 4.26.0-pre.43 → 4.26.0-pre.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -17685,36 +17685,7 @@ window.__ModuleLoader__.load({
17685
17685
  React.createElement("option", { value: "local" }, weT("本机 Wallpaper Engine({n})", { n: (sourceCounts && sourceCounts.local) || 0 })),
17686
17686
  React.createElement("option", { value: "site" }, weT("站点壁纸({n})", { n: (sourceCounts && sourceCounts.site) || 0 })),
17687
17687
  ),
17688
- React.createElement("span", { className: "we-picker__hint we-picker__label" }, weT("内容分级")),
17689
- React.createElement("select", {
17690
- className: "we-picker__playlist-select",
17691
- value: sel.contentRatingFilter,
17692
- onChange: onRatingFilterChange,
17693
- "aria-label": weT("内容分级"),
17694
- title: weT("对应 Wallpaper Engine 的内容分级(project.json contentrating)"),
17695
- },
17696
- React.createElement("option", { value: "all" }, weT("全部({n})", { n: basePlayable.length })),
17697
- React.createElement("option", { value: "everyone" }, weT("Everyone / G({n})", { n: ratingCounts.everyone })),
17698
- React.createElement("option", { value: "pg13" }, weT("PG13({n})", { n: ratingCounts.pg13 })),
17699
- React.createElement("option", { value: "mature" }, weT("Mature / R({n})", { n: ratingCounts.mature })),
17700
- React.createElement("option", { value: "unrated" }, weT("未分级({n})", { n: ratingCounts.unrated })),
17701
- ),
17702
- React.createElement("span", { className: "we-picker__hint we-picker__label" }, weT("类型")),
17703
- React.createElement("select", {
17704
- className: "we-picker__playlist-select",
17705
- value: sel.typeFilter,
17706
- onChange: onTypeFilterChange,
17707
- "aria-label": weT("类型"),
17708
- title: weT("按壁纸类型过滤(只筛列表与轮播候选,不打断正在应用的壁纸)"),
17709
- },
17710
- React.createElement("option", { value: "all" }, weT("全部({n})", { n: basePlayable.length })),
17711
- React.createElement("option", { value: "video" }, weT("视频({n})", { n: typeCounts.video || 0 })),
17712
- React.createElement("option", { value: "web" }, weT("网页({n})", { n: typeCounts.web || 0 })),
17713
- React.createElement("option", { value: "image" }, weT("图片({n})", { n: typeCounts.image || 0 })),
17714
- React.createElement("option", { value: "scene" }, weT("场景({n})", { n: typeCounts.scene || 0 })),
17715
- ),
17716
- renderTagSelect({ tagOptions, tagPicked, onTagFilterChange }),
17717
- );
17688
+ );
17718
17689
  }
17719
17690
 
17720
17691
  /**
@@ -20953,6 +20924,12 @@ window.__ModuleLoader__.load({
20953
20924
  const onText = typeof options.onText === 'function' ? options.onText : () => {};
20954
20925
  const onError = typeof options.onError === 'function' ? options.onError : () => {};
20955
20926
  const onState = typeof options.onState === 'function' ? options.onState : () => {};
20927
+ /**
20928
+ * barge-in(P1):**录音一开始**先停掉正在播的朗读。
20929
+ * 做成注入点而不是在这里直接引用 petSpeakStop:模块在构建期被内联进同一作用域,
20930
+ * 直接引用会把“朗读”与“录音”焊死;注入后判据也能用假函数断言调用顺序。
20931
+ */
20932
+ const onBeforeRecord = typeof options.onBeforeRecord === 'function' ? options.onBeforeRecord : () => {};
20956
20933
 
20957
20934
  let active = false;
20958
20935
 
@@ -20965,6 +20942,8 @@ window.__ModuleLoader__.load({
20965
20942
  async function start() {
20966
20943
  if (active) return true;
20967
20944
  active = true;
20945
+ // ⚠️ 顺序是判据:先打断朗读,再开麦(用户一说话就把桌宠的声音掐掉)
20946
+ try { onBeforeRecord(); } catch { /* 打断失败不能挡住录音 */ }
20968
20947
  onState({ state: 'listening' });
20969
20948
  let result;
20970
20949
  try {
@@ -21050,6 +21029,40 @@ window.__ModuleLoader__.load({
21050
21029
  let text = '';
21051
21030
  let visible = false;
21052
21031
  let fadeTimer = null;
21032
+ let stylesInjected = false;
21033
+
21034
+ /**
21035
+ * 三态与“说”的波形(P1):
21036
+ * listen / think / speak / idle —— 只改 `data-state`,由一小段**无颜色**的 CSS 表现:
21037
+ * · listen:正文前的实心点;think:省略号;speak:正文下一排四根跳动竖条。
21038
+ * 用伪元素而不是新增 DOM 子节点,是因为气泡正文一直用 `textContent` 整体写入
21039
+ * (设 textContent 会把子节点一起清掉);伪元素不会被它清掉,也不会引入第二种“文字容器”。
21040
+ */
21041
+ const WAVE_CSS = [
21042
+ '.we-pet-bubble[data-state="listen"]::before{content:"●";margin-right:4px;opacity:.55;}',
21043
+ '.we-pet-bubble[data-state="think"]::before{content:"…";margin-right:4px;opacity:.6;}',
21044
+ '.we-pet-bubble[data-state="speak"]::after{content:"";display:block;width:34px;height:10px;margin-top:6px;opacity:.85;',
21045
+ 'background:',
21046
+ 'linear-gradient(currentColor,currentColor) 0 100%/3px 45% no-repeat,',
21047
+ 'linear-gradient(currentColor,currentColor) 8px 100%/3px 90% no-repeat,',
21048
+ 'linear-gradient(currentColor,currentColor) 16px 100%/3px 60% no-repeat,',
21049
+ 'linear-gradient(currentColor,currentColor) 24px 100%/3px 100% no-repeat;',
21050
+ 'transform-origin:0 100%;animation:we-pet-bubble-wave .8s ease-in-out infinite alternate;}',
21051
+ '@keyframes we-pet-bubble-wave{from{transform:scaleY(.55);opacity:.55;}to{transform:scaleY(1);opacity:.95;}}',
21052
+ ].join('');
21053
+
21054
+ /** 只注入一次;没有 head 的环境(判据的极简 DOM)静默跳过。 */
21055
+ function ensureStyles() {
21056
+ if (stylesInjected) return;
21057
+ stylesInjected = true;
21058
+ try {
21059
+ if (!doc || !doc.head || typeof doc.createElement !== 'function') return;
21060
+ const style = doc.createElement('style');
21061
+ style.setAttribute('data-folia-pet-bubble', '1');
21062
+ style.textContent = WAVE_CSS;
21063
+ if (typeof doc.head.appendChild === 'function') doc.head.appendChild(style);
21064
+ } catch { /* 气泡是装饰层,样式失败不能影响显示 */ }
21065
+ }
21053
21066
 
21054
21067
  /** 锚点 → 气泡位置:水平居中于桌宠,垂直贴在头顶上方。 */
21055
21068
  function place() {
@@ -21144,9 +21157,10 @@ window.__ModuleLoader__.load({
21144
21157
  doHide();
21145
21158
  }
21146
21159
 
21147
- /** 状态:听 / 想 / 答(客户端据此换桌宠动作、给气泡配色)。 */
21160
+ /** 状态:听 / 想 / 说(客户端据此换桌宠动作、气泡配色与波形)。 */
21148
21161
  function setState(kind) {
21149
- if (!el) return;
21162
+ if (!ensure()) return;
21163
+ ensureStyles();
21150
21164
  el.dataset = el.dataset || {};
21151
21165
  el.dataset.state = String(kind || '');
21152
21166
  }
@@ -21172,14 +21186,323 @@ window.__ModuleLoader__.load({
21172
21186
  };
21173
21187
  }
21174
21188
 
21175
- // ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
21189
+ // ── 内联模块:src/pet-tts.js —— 桌宠朗读客户端:petTtsSplit 切句 / 排队播放 / 预取下一句 / stop 清队列 / 句字幕回调(构建期注入;勿手改本段)──
21176
21190
  /**
21177
- * pet-chat.js — 桌宠语音助手(v0.1 客户端)。
21191
+ * pet-tts.js(客户端)— 桌宠朗读:**按句合成 / 排队播放 / 字幕 / barge-in**。
21192
+ *
21193
+ * 为什么不把整段文字一次合成:
21194
+ * · 第一句能先出声(模型刚说完第一句就开始念,不等整段);
21195
+ * · 一句失败只影响一句,不会“整段静音”;
21196
+ * · stop 时清队列即可立刻闭嘴,不需要等一个长请求。
21178
21197
  *
21179
- * v0.1 范围(docs/PET-V01-ACCEPTANCE.md):**语音输入 + 头顶文字气泡 + 名字/记忆 + 主动搭话**,
21180
- * **不含任何朗读/TTS**(v0.2 再做)。所以这里没有 speechSynthesis、没有 /pet-chat/speak 调用。
21198
+ * 依赖全部注入(apiFetch / Audio / URL / 回调),所以 Node 里能用假播放器跑判据;
21199
+ * 浏览器侧由 `src/pet-chat.js` 用真实 `Audio` 与 `URL.createObjectURL` 构造。
21200
+ *
21201
+ * 与宿主的分工:
21202
+ * · 宿主负责“SAPI → Edge 系统音色 → 明确错误”的兜底链,返回 `audio/wav`;
21203
+ * · 客户端只负责切句、排队、播、停、把当前句交给气泡显示。
21204
+ */
21205
+
21206
+ /** 单句上限:超过就在标点/字数处切开(与宿主路由的 240 字上限配合)。 */
21207
+ const PET_TTS_MAX_SENTENCE = 48;
21208
+ /** 一次最多几句:再长也只念前 8 句(防止任务提醒念一整篇)。 */
21209
+ const PET_TTS_MAX_PIECES = 8;
21210
+ /** 与宿主 `TTS_MAX_CHARS` 对齐的总上限。 */
21211
+ const PET_TTS_MAX_CHARS = 240;
21212
+
21213
+ /**
21214
+ * 纯函数:把一段文字切成“适合一句一合成”的片段。
21215
+ * 优先在句末标点切;长句在逗号处或硬上限处切。
21216
+ */
21217
+ function petTtsSplit(text) {
21218
+ const raw = String(text == null ? '' : text).replace(/\s+/g, ' ').trim().slice(0, PET_TTS_MAX_CHARS);
21219
+ if (!raw) return [];
21220
+ const pieces = [];
21221
+ let buffer = '';
21222
+ const flush = () => {
21223
+ const piece = buffer.trim();
21224
+ buffer = '';
21225
+ if (piece) pieces.push(piece);
21226
+ };
21227
+ for (const ch of raw) {
21228
+ buffer += ch;
21229
+ const ends = /[。!?!?;;\n]/.test(ch);
21230
+ const commaCut = /[,,、]/.test(ch) && buffer.length >= PET_TTS_MAX_SENTENCE * 0.7;
21231
+ const hardCut = buffer.length >= PET_TTS_MAX_SENTENCE;
21232
+ if (ends || commaCut || hardCut) flush();
21233
+ if (pieces.length >= PET_TTS_MAX_PIECES) break;
21234
+ }
21235
+ flush();
21236
+ return pieces.slice(0, PET_TTS_MAX_PIECES);
21237
+ }
21238
+
21239
+ /**
21240
+ * 纯函数:流式场景下“已经说完的句子”与“还没说完的尾巴”。
21241
+ * SSE 每来一小段就调用一次,把完整句立刻入队(第一句更早出声)。
21242
+ */
21243
+ function petTtsSentences(text) {
21244
+ const raw = String(text == null ? '' : text);
21245
+ const sentences = [];
21246
+ let start = 0;
21247
+ for (let i = 0; i < raw.length; i += 1) {
21248
+ if (/[。!?!?;;\n]/.test(raw[i])) {
21249
+ const piece = raw.slice(start, i + 1).trim();
21250
+ if (piece) sentences.push(piece);
21251
+ start = i + 1;
21252
+ }
21253
+ }
21254
+ let rest = raw.slice(start);
21255
+ // 没有标点的长句也要在安全长度切开,避免一直等到整段结束
21256
+ if (rest.length >= PET_TTS_MAX_SENTENCE) {
21257
+ const cut = rest.lastIndexOf(',', PET_TTS_MAX_SENTENCE);
21258
+ const at = cut > 8 ? cut + 1 : PET_TTS_MAX_SENTENCE;
21259
+ sentences.push(rest.slice(0, at).trim());
21260
+ rest = rest.slice(at);
21261
+ }
21262
+ return { sentences, rest };
21263
+ }
21264
+
21265
+ /**
21266
+ * @param {{
21267
+ * apiFetch: Function,
21268
+ * apiPostJson?: Function,
21269
+ * Audio?: Function,
21270
+ * URL?: object,
21271
+ * getVoice?: () => {name?: string, muted?: boolean, rate?: number},
21272
+ * onSentence?: (text: string) => void,
21273
+ * onState?: (state: 'speak'|'idle') => void,
21274
+ * onError?: (error: {code: string, hint?: string, status?: number}) => void,
21275
+ * onIdle?: () => void,
21276
+ * log?: (line: string) => void,
21277
+ * }} deps
21278
+ */
21279
+ function petTtsCreate(deps) {
21280
+ const options = deps || {};
21281
+ const apiFetch = options.apiFetch;
21282
+ const apiPostJson = options.apiPostJson;
21283
+ const AudioCtor = typeof options.Audio === 'function' ? options.Audio : null;
21284
+ const UrlApi = options.URL || null;
21285
+ const getVoice = typeof options.getVoice === 'function' ? options.getVoice : () => ({});
21286
+ const onSentence = typeof options.onSentence === 'function' ? options.onSentence : () => {};
21287
+ const onState = typeof options.onState === 'function' ? options.onState : () => {};
21288
+ const onError = typeof options.onError === 'function' ? options.onError : () => {};
21289
+ const onIdle = typeof options.onIdle === 'function' ? options.onIdle : () => {};
21290
+ const log = typeof options.log === 'function' ? options.log : () => {};
21291
+
21292
+ let generation = 0;
21293
+ let queue = [];
21294
+ let busy = false;
21295
+ let playing = null;
21296
+ let prefetch = null;
21297
+ let disposed = false;
21298
+
21299
+ function revoke(url) {
21300
+ if (!url || !UrlApi || typeof UrlApi.revokeObjectURL !== 'function') return;
21301
+ try { UrlApi.revokeObjectURL(url); } catch { /* ignore */ }
21302
+ }
21303
+
21304
+ /** 取一句的 WAV:成功 `{url,size}`,失败 `{error}`,被 stop `{stopped:true}`。 */
21305
+ async function fetchSpeech(item, gen) {
21306
+ if (typeof apiFetch !== 'function') {
21307
+ return { error: { code: 'tts-unavailable', hint: '这个版本没有接朗读接口' } };
21308
+ }
21309
+ const query = '/pet-chat/tts?text=' + encodeURIComponent(item.text)
21310
+ + '&voice=' + encodeURIComponent(item.voice || '')
21311
+ + '&rate=' + encodeURIComponent(String(item.rate));
21312
+ let res;
21313
+ let blob;
21314
+ try {
21315
+ // parse:false:**二进制体**不能交给默认的 json() 解析(流会被吃掉);
21316
+ // 这里的 blob() 必须和它在同一个调用窗里(verify-api-client ①b 的判据)。
21317
+ res = await apiFetch(query, { parse: false, cache: 'no-store' });
21318
+ if (gen !== generation) return { stopped: true };
21319
+ if (!res || !res.ok || !res.response) {
21320
+ let hint = '';
21321
+ try {
21322
+ if (res && res.response && typeof res.response.json === 'function') {
21323
+ const doc = await res.response.json();
21324
+ hint = String((doc && doc.hint) || '');
21325
+ }
21326
+ } catch { /* 非 JSON 错误体 */ }
21327
+ return { error: { code: 'tts-failed', status: (res && res.status) || 0, hint: hint || '语音合成失败' } };
21328
+ }
21329
+ blob = await res.response.blob();
21330
+ } catch (error) {
21331
+ if (!res) return { error: { code: 'tts-network', hint: '连不上宿主,语音没出来' } };
21332
+ return { error: { code: 'tts-read-failed', hint: '读不到语音数据' } };
21333
+ }
21334
+ if (!blob || !blob.size) return { error: { code: 'tts-empty', hint: '没合成出声音' } };
21335
+ let url = '';
21336
+ if (UrlApi && typeof UrlApi.createObjectURL === 'function') {
21337
+ try { url = UrlApi.createObjectURL(blob); } catch { url = ''; }
21338
+ }
21339
+ if (!url) return { error: { code: 'tts-audio-unavailable', hint: '这个环境不能播放音频' } };
21340
+ return { url, size: blob.size };
21341
+ }
21342
+
21343
+ /** 播一句;stop 时由 `entry.finish` 立即结束 Promise。 */
21344
+ function playSpeech(item, prepared, gen) {
21345
+ return new Promise((resolve) => {
21346
+ let audio;
21347
+ try {
21348
+ audio = new AudioCtor(prepared.url);
21349
+ } catch (error) {
21350
+ resolve({ code: 'tts-audio', hint: '播放器创建失败' });
21351
+ return;
21352
+ }
21353
+ const entry = { audio, url: prepared.url, finish: null };
21354
+ let settled = false;
21355
+ const finish = (error) => {
21356
+ if (settled) return;
21357
+ settled = true;
21358
+ if (playing === entry) playing = null;
21359
+ revoke(prepared.url);
21360
+ resolve(error || null);
21361
+ };
21362
+ entry.finish = finish;
21363
+ playing = entry;
21364
+ onState('speak');
21365
+ onSentence(item.text);
21366
+ audio.onended = () => finish(null);
21367
+ audio.onerror = () => finish({ code: 'tts-play-failed', hint: '这条语音播放失败' });
21368
+ try {
21369
+ const ret = audio.play();
21370
+ if (ret && typeof ret.then === 'function') {
21371
+ ret.catch(() => finish({ code: 'tts-blocked', hint: '系统拦了自动播放,点一下桌宠再试' }));
21372
+ }
21373
+ } catch (error) {
21374
+ finish({ code: 'tts-blocked', hint: '系统拦了自动播放,点一下桌宠再试' });
21375
+ }
21376
+ if (gen !== generation) finish(null);
21377
+ });
21378
+ }
21379
+
21380
+ function startPrefetch(gen) {
21381
+ if (prefetch || !queue.length) return;
21382
+ const item = queue[0];
21383
+ if (item.gen !== gen) return;
21384
+ prefetch = { item, gen, promise: fetchSpeech(item, gen) };
21385
+ }
21386
+
21387
+ async function pump(gen) {
21388
+ if (busy || disposed) return;
21389
+ busy = true;
21390
+ try {
21391
+ while (queue.length) {
21392
+ const item = queue[0];
21393
+ // stop 之后的新一批有自己的 pump;旧 pump 不许动它
21394
+ if (item.gen !== gen) break;
21395
+ let prepared;
21396
+ if (prefetch && prefetch.item === item && prefetch.gen === gen) {
21397
+ prepared = await prefetch.promise;
21398
+ prefetch = null;
21399
+ } else {
21400
+ prepared = await fetchSpeech(item, gen);
21401
+ }
21402
+ if (item.gen !== generation) { queue.shift(); if (prepared && prepared.url) revoke(prepared.url); break; }
21403
+ if (!prepared || prepared.error) {
21404
+ queue.length = 0;
21405
+ onState('idle');
21406
+ onError((prepared && prepared.error) || { code: 'tts-failed', hint: '语音合成失败' });
21407
+ break;
21408
+ }
21409
+ queue.shift();
21410
+ startPrefetch(gen);
21411
+ const error = await playSpeech(item, prepared, gen);
21412
+ if (item.gen !== generation) break;
21413
+ if (error) {
21414
+ queue.length = 0;
21415
+ onState('idle');
21416
+ onError(error);
21417
+ break;
21418
+ }
21419
+ }
21420
+ } finally {
21421
+ busy = false;
21422
+ if (disposed) {
21423
+ // 已销毁:不再启动下一批,也不再回调界面
21424
+ } else if (queue.length && queue[0].gen === generation) {
21425
+ // stop 之后又来了新的一批:旧 pump 收尾时把接力棒交出去
21426
+ void pump(queue[0].gen);
21427
+ } else if (gen === generation && !queue.length && !playing) {
21428
+ onState('idle');
21429
+ onIdle();
21430
+ }
21431
+ }
21432
+ }
21433
+
21434
+ /** 停止:清队列 + 停当前音频 + 通知宿主作废在途合成(幂等)。 */
21435
+ function stop() {
21436
+ generation += 1;
21437
+ queue = [];
21438
+ prefetch = null;
21439
+ if (playing) {
21440
+ const entry = playing;
21441
+ playing = null;
21442
+ try { entry.audio.pause(); } catch { /* ignore */ }
21443
+ if (typeof entry.finish === 'function') entry.finish(null);
21444
+ revoke(entry.url);
21445
+ }
21446
+ onState('idle');
21447
+ if (typeof apiPostJson === 'function') {
21448
+ try {
21449
+ const ret = apiPostJson('/pet-chat/tts/stop', {});
21450
+ if (ret && typeof ret.catch === 'function') ret.catch(() => {});
21451
+ } catch { /* 停不下来也不能抛给界面 */ }
21452
+ }
21453
+ return true;
21454
+ }
21455
+
21456
+ /**
21457
+ * 说一段话(会按句切开排队)。
21458
+ * @returns {boolean} 是否入队(静音 / 空文本 / 环境不支持时 false)
21459
+ */
21460
+ function speak(text, speech) {
21461
+ if (disposed) return false;
21462
+ const cfg = getVoice() || {};
21463
+ if (cfg.muted === true) { onState('idle'); return false; }
21464
+ const pieces = petTtsSplit(text);
21465
+ if (!pieces.length) return false;
21466
+ if (!AudioCtor) {
21467
+ onError({ code: 'tts-no-audio', hint: '这个环境不能播放声音' });
21468
+ return false;
21469
+ }
21470
+ const speechOpts = speech || {};
21471
+ const voice = String(speechOpts.voice || cfg.name || '');
21472
+ const rawRate = speechOpts.rate !== undefined ? speechOpts.rate : cfg.rate;
21473
+ const rate = Number.isFinite(Number(rawRate)) ? Number(rawRate) : 0;
21474
+ const gen = generation;
21475
+ for (const piece of pieces) queue.push({ text: piece, voice, rate, gen });
21476
+ log('[pet-tts] queue ' + pieces.length + ' sentence(s) voice=' + (voice || '(auto)'));
21477
+ void pump(gen);
21478
+ return true;
21479
+ }
21480
+
21481
+ function isSpeaking() {
21482
+ return Boolean(playing) || queue.length > 0 || busy;
21483
+ }
21484
+
21485
+ function state() {
21486
+ return { busy, playing: Boolean(playing), queued: queue.length, generation };
21487
+ }
21488
+
21489
+ function dispose() {
21490
+ if (disposed) return;
21491
+ stop();
21492
+ disposed = true;
21493
+ }
21494
+
21495
+ return { speak, stop, isSpeaking, state, dispose };
21496
+ }
21497
+
21498
+ /* 供判据从产物/源码里取纯函数;浏览器侧由 pet-chat.js 构造实例。 */
21499
+
21500
+ // ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
21501
+ /**
21502
+ * pet-chat.js — 桌宠语音助手(P1:语音输入 + 朗读 + 头顶气泡 + 主动搭话)。
21181
21503
  *
21182
- * 交互:点桌宠 = 唤醒 → 气泡显示它的话(3 秒后淡出,点一下立刻收起)。
21504
+ * 交互:点桌宠 = 唤醒 → 录音(说完自动停)→ 转写 → SSE 回答 → 按句朗读
21505
+ * (气泡逐句字幕 + “说”态波形);说话/点击/打字都先打断当前朗读。
21183
21506
  * 没有聊天窗口:无输入框、无历史列表、无开关按钮。
21184
21507
  */
21185
21508
  const PET_CHAT_PRESET_LINES = {
@@ -21261,8 +21584,7 @@ window.__ModuleLoader__.load({
21261
21584
  * 然后轮询 /pet-chat/asr 把下载进度显示在气泡里。
21262
21585
  * 这样用户装完插件直接说话就行,不需要去 DSH 设置里找「语音输入」开关。
21263
21586
  */
21264
- async function ensureAsrReady() {
21265
- petBubble.setState('think');
21587
+ async function ensureAsrReady() { petBubble.setState('think');
21266
21588
  try {
21267
21589
  await apiPostJson('/pet-chat/asr', {}, { parse: 'always' });
21268
21590
  } catch { /* 触发失败也要继续轮询看状态 */ }
@@ -21294,14 +21616,72 @@ window.__ModuleLoader__.load({
21294
21616
  petBubble.hide(3000);
21295
21617
  }
21296
21618
 
21619
+ /**
21620
+ * 朗读配置(P1):`/pet-chat/state` 的 voice 字段。
21621
+ *
21622
+ * 懒加载:挂载时与每次唤醒时各刷一次(设置面板改完立刻生效,不用重启)。
21623
+ * 读不到就保持“不静音”,宁可多念一句,也不要让用户以为朗读坏了。
21624
+ */
21625
+ let petChatVoice = { name: '', muted: false, rate: 0 };
21626
+ async function petChatRefreshVoice() {
21627
+ try {
21628
+ const resp = await apiJson('/pet-chat/state', { parse: 'always' });
21629
+ const doc = (resp && resp.data) || {};
21630
+ if (doc.voice && typeof doc.voice === 'object') {
21631
+ petChatVoice = {
21632
+ name: String(doc.voice.name || ''),
21633
+ muted: doc.voice.muted === true,
21634
+ rate: Number.isFinite(Number(doc.voice.rate)) ? Number(doc.voice.rate) : 0,
21635
+ };
21636
+ }
21637
+ } catch { /* 读不到就用默认(不静音) */ }
21638
+ return petChatVoice;
21639
+ }
21640
+
21641
+ /**
21642
+ * 朗读实例(P1):宿主负责合成兜底,这里负责切句、排队、播、停、字幕同步。
21643
+ * 回调全部接到气泡:说 → `speak` 态 + 当前句;停/念完 → `idle` + 3 秒后淡出。
21644
+ */
21645
+ const petTts = petTtsCreate({
21646
+ // ⚠️ 包一层再传:`api-client.js` 的内联位置在 `pet-chat.js` **之后**,
21647
+ // 直接 `apiFetch` / `apiPostJson` 会在模块求值期触发 TDZ
21648
+ // (真机/冒烟统一症状:Cannot access 'apiPostJson' before initialization)。
21649
+ apiFetch: (path, opts) => apiFetch(path, opts),
21650
+ apiPostJson: (path, payload, opts) => apiPostJson(path, payload, opts),
21651
+ Audio: typeof Audio === 'function' ? Audio : null,
21652
+ URL: typeof URL === 'function' ? URL : null,
21653
+ getVoice: () => petChatVoice,
21654
+ onSentence: (text) => {
21655
+ petBubble.setState('speak');
21656
+ petBubble.show(text);
21657
+ },
21658
+ onState: (kind) => { petBubble.setState(kind); },
21659
+ onIdle: () => { petBubble.hide(3000); },
21660
+ onError: (error) => {
21661
+ // 失败只进气泡提示行(不弹窗);不静默 —— 用户至少知道为什么没声音
21662
+ const hint = (error && error.hint) || '语音没出来';
21663
+ petBubble.setState('idle');
21664
+ petBubble.show(hint);
21665
+ petBubble.hide(4000);
21666
+ },
21667
+ });
21668
+
21669
+ /** 对外/对内的“说一句”:按句入队,返回是否真的入队。 */
21670
+ function petSpeak(text, speech) { return petTts.speak(text, speech); }
21671
+ /** 立刻停:清队列 + 停当前音频 + 通知宿主作废在途合成(barge-in 用)。 */
21672
+ function petSpeakStop() { return petTts.stop(); }
21673
+
21297
21674
  /** 语音输入(v0.1):前端不碰麦克风 —— 宿主用 ffmpeg 录,这里只发请求、收文本。 */
21298
21675
  const petVoiceIn = petVoiceInputCreate({
21676
+ // barge-in:**一开录就先停朗读**(判据 verify-voice-tts 断言这个顺序)
21677
+ onBeforeRecord: () => { petSpeakStop(); },
21299
21678
  postRecord: async () => {
21300
21679
  const res = await apiPostJson('/pet-chat/record', { language: 'zh' }, { parse: 'always' });
21301
21680
  return (res && res.data) || {};
21302
21681
  },
21303
21682
  postChat: async (text, onState) => {
21304
- petBubble.setState('answer');
21683
+ // “想”态:模型还在回,先不给“说”的波形
21684
+ petBubble.setState('think');
21305
21685
  // ⚠️ apiFetch 的返回值里**已经带上了原始 Response**(字段 `response`)。
21306
21686
  // 上一版误写成 `res.body.getReader()`:res 是 { ok, status, data, response },
21307
21687
  // res.body 恒为 undefined ⇒ 抛 TypeError ⇒ 读流代码一行都跑不到
@@ -21334,6 +21714,18 @@ window.__ModuleLoader__.load({
21334
21714
  let rawReply = '';
21335
21715
  let replyStarted = false;
21336
21716
  let replyDone = false;
21717
+ /**
21718
+ * 朗读的流式切句(P1):
21719
+ * SSE 每来一小段就交给 `petTtsSentences`;**句末标点一到就入队**,
21720
+ * 不等 done —— 这是“录音停止后尽快开始播报”的关键(合成与模型生成重叠)。
21721
+ */
21722
+ let speakBuffer = '';
21723
+ let queuedSpeech = 0;
21724
+ const enqueueSpeech = (piece) => {
21725
+ const line = String(piece || '').trim();
21726
+ if (!line) return;
21727
+ if (petSpeak(line)) queuedSpeech += 1;
21728
+ };
21337
21729
  const reader = stream.body.getReader();
21338
21730
  const decoder = new TextDecoder();
21339
21731
  let buffer = '';
@@ -21348,7 +21740,7 @@ window.__ModuleLoader__.load({
21348
21740
  buffer = buffer.slice(cut + 2);
21349
21741
  const line = frame.split('\n').find((item) => item.startsWith('data:'));
21350
21742
  if (!line) continue;
21351
- let payload = null;
21743
+ let payload;
21352
21744
  try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
21353
21745
  // 防兜底:模型偶尔仍会输出 {"reply":"…","emotion":"…"} 信封,
21354
21746
  // 这里只把 reply 的正文喂给气泡(不显示大括号/字段名/emotion)。
@@ -21367,13 +21759,25 @@ window.__ModuleLoader__.load({
21367
21759
  if (piece && !replyDone) {
21368
21760
  const cut = piece.indexOf('","emotion"');
21369
21761
  if (cut >= 0) { piece = piece.slice(0, cut); replyDone = true; }
21370
- if (piece) petBubble.append(piece);
21762
+ if (piece) {
21763
+ // 朗读没开始时先照旧把文字逐字填进气泡;一开始播,气泡字幕就交给
21764
+ // petTts 的 onSentence(逐句显示),避免两路同时写同一个气泡。
21765
+ if (queuedSpeech === 0) petBubble.append(piece);
21766
+ speakBuffer += piece;
21767
+ const split = petTtsSentences(speakBuffer);
21768
+ for (const sentence of split.sentences) enqueueSpeech(sentence);
21769
+ speakBuffer = split.rest;
21770
+ }
21371
21771
  }
21372
21772
  }
21373
21773
  }
21374
21774
  }
21775
+ // 最后一段没有句末标点也要念(比如“我也在”)
21776
+ enqueueSpeech(speakBuffer);
21375
21777
  if (typeof onState === 'function') onState({ state: 'idle' });
21376
- petBubble.hide(3000);
21778
+ // 没有任何一句进入朗读(静音 / 合成不可用)⇒ 沿用旧行为:整段文字 3 秒后淡出。
21779
+ // 有朗读时由 petTts 的 onIdle 在念完后淡出(按句字幕不会被提前清掉)。
21780
+ if (!queuedSpeech) petBubble.hide(3000);
21377
21781
  },
21378
21782
  // P4:用户自己的话**不进**气泡(那是回声);只显示 assistant 的 SSE delta
21379
21783
  onText: () => {},
@@ -21422,6 +21826,8 @@ window.__ModuleLoader__.load({
21422
21826
  const text = String(input.value || '').trim();
21423
21827
  if (!text) return;
21424
21828
  box.remove();
21829
+ // 新的一轮 = 先掐掉上一轮还在念的(与录音入口同一条 barge-in 纪律)
21830
+ petSpeakStop();
21425
21831
  // 打字说的文本**不上气泡**(P4 同理:气泡只显示助手的回答)。
21426
21832
  // 这里只把状态切成"思考中",等 SSE 的 delta 逐字填进来。
21427
21833
  petBubble.setState('think');
@@ -21436,18 +21842,22 @@ window.__ModuleLoader__.load({
21436
21842
  input.focus();
21437
21843
  }
21438
21844
 
21439
- /** 说一句:气泡显示 + 3 秒后淡出。
21440
- * v0.1 不朗读 —— 这里刻意不做音频(验收⑦:lib/ 里不允许出现 speechSynthesis)。
21845
+ /**
21846
+ * 说一句:气泡显示 + 朗读(P1)。
21847
+ * 静音/合成不可用时退回“只显示 3 秒”,不抛错、不弹窗。
21441
21848
  */
21442
21849
  function petChatSay(text) {
21443
21850
  const line = String(text || '').trim();
21444
21851
  if (!line) return;
21445
21852
  petBubble.show(line);
21446
- petBubble.hide(3000);
21853
+ if (!petSpeak(line)) petBubble.hide(3000);
21447
21854
  }
21448
21855
 
21449
- /** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音);否则唤醒并开始听。 */
21856
+ /** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音与朗读);否则唤醒并开始听。 */
21450
21857
  function petChatWake() {
21858
+ // **任何一次唤醒都是 barge-in**:先把正在念的停掉,再决定是收起还是开麦。
21859
+ petSpeakStop();
21860
+ void petChatRefreshVoice();
21451
21861
  if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
21452
21862
  petBubble.setState('listen');
21453
21863
  // 先看语音模型是否就绪;没就绪就**立刻**开始下载并在气泡里显示进度,
@@ -21465,9 +21875,36 @@ window.__ModuleLoader__.load({
21465
21875
  });
21466
21876
  }
21467
21877
 
21878
+ /**
21879
+ * 工作联动反向通道(P1):宿主 `/pet-chat/speak` → SSE `/pet-chat/events` → 这里念。
21880
+ * 待办/提醒/其它插件可以直接 `POST /folia/pet-chat/speak`,也可以在同一渲染进程里
21881
+ * `window.__dshFoliaPet.speak(text)` / 派发 `we-pet-speak` 事件。
21882
+ * EventSource 自带重连;这里不弹任何提示。
21883
+ */
21884
+ let petChatEventSource = null;
21885
+ function petChatEventsStart() {
21886
+ if (petChatEventSource || typeof EventSource !== 'function') return;
21887
+ try {
21888
+ const source = new EventSource(apiUrl('/pet-chat/events'));
21889
+ source.onmessage = (event) => {
21890
+ let doc;
21891
+ try { doc = JSON.parse((event && event.data) || ''); } catch { doc = null; }
21892
+ if (!doc || doc.type !== 'speak' || !doc.text) return;
21893
+ petSpeak(String(doc.text), { voice: doc.voice, rate: doc.rate });
21894
+ };
21895
+ source.onerror = () => { /* EventSource 自动重连;失败不打扰用户 */ };
21896
+ petChatEventSource = source;
21897
+ } catch { /* 老环境没有 EventSource:仍在渲染进程内的调用走 window.__dshFoliaPet */ }
21898
+ }
21899
+ function petChatEventsStop() {
21900
+ if (!petChatEventSource) return;
21901
+ try { petChatEventSource.close(); } catch { /* ignore */ }
21902
+ petChatEventSource = null;
21903
+ }
21904
+
21468
21905
  /**
21469
21906
  * 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点桌宠 / 快捷键。
21470
- * 返回 cleanup —— 卸载时摘监听、销毁气泡。
21907
+ * 返回 cleanup —— 卸载时摘监听、断开反向通道、销毁气泡。
21471
21908
  */
21472
21909
  function mountPetChat() {
21473
21910
  if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return () => {};
@@ -21485,13 +21922,37 @@ window.__ModuleLoader__.load({
21485
21922
  // 打字入口只从**右键菜单「对话」**进:pet-layer 的菜单项派发 `we-pet-talk`。
21486
21923
  // 不再劫持 contextmenu —— 那会让右键弹不出桌宠原生菜单(试演动作/缩放…)。
21487
21924
  const onTalkEvent = () => { petChatOpenTyping(); };
21925
+
21926
+ /** 工作联动:同一渲染进程里的待办/提醒可以直接派发这个事件。 */
21927
+ const onSpeakEvent = (event) => {
21928
+ const detail = (event && event.detail) || {};
21929
+ const text = detail && detail.text;
21930
+ if (text) petSpeak(String(text), { voice: detail.voice, rate: detail.rate });
21931
+ };
21932
+
21488
21933
  window.addEventListener('we-pet-talk', onTalkEvent);
21934
+ window.addEventListener('we-pet-speak', onSpeakEvent);
21489
21935
  document.addEventListener('click', onDocumentClick, true);
21490
21936
  document.addEventListener('keydown', onKeyDown, true);
21937
+ void petChatRefreshVoice();
21938
+ petChatEventsStart();
21939
+ // 对外通道:`speak(text)` 供待办/提醒直接调用(不打开任何窗口)
21940
+ try {
21941
+ window.__dshFoliaPet = {
21942
+ speak: (text, speech) => petSpeak(text, speech || {}),
21943
+ stop: () => petSpeakStop(),
21944
+ chat: (text) => petVoiceIn.postChat(String(text || '')),
21945
+ isSpeaking: () => petTts.isSpeaking(),
21946
+ };
21947
+ } catch { /* 被别的插件占用就只保留事件通道 */ }
21491
21948
  return () => {
21492
21949
  window.removeEventListener('we-pet-talk', onTalkEvent);
21950
+ window.removeEventListener('we-pet-speak', onSpeakEvent);
21493
21951
  document.removeEventListener('click', onDocumentClick, true);
21494
21952
  document.removeEventListener('keydown', onKeyDown, true);
21953
+ petChatEventsStop();
21954
+ petSpeakStop();
21955
+ try { if (window.__dshFoliaPet) delete window.__dshFoliaPet; } catch { /* ignore */ }
21495
21956
  petBubble.dispose();
21496
21957
  };
21497
21958
  }
@@ -39920,8 +40381,9 @@ window.__ModuleLoader__.load({
39920
40381
  wallpapers: list,
39921
40382
  hiddenIds: selection.hiddenIds,
39922
40383
  search: sel.search,
39923
- ratingFilter: sel.contentRatingFilter,
39924
- typeFilter: sel.typeFilter,
40384
+ // 分级/类型下拉已移除 ⇒ 列表恒按 all 计算(旧持久化值不许在后台偷偷过滤)
40385
+ ratingFilter: "all",
40386
+ typeFilter: "all",
39925
40387
  sourceFilter: sel.sourceFilter,
39926
40388
  cacheFilter: readPickerCacheFilter(),
39927
40389
  subtagFilter: readPickerSubtagFilter(),