dsh-folia 4.26.0-pre.62 → 4.26.0-pre.64

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
@@ -745,6 +745,22 @@ window.__ModuleLoader__.load({
745
745
  "在听": "Listening",
746
746
  "在想": "Thinking",
747
747
  "在说": "Speaking",
748
+ // pre.63:连续对话(右键菜单 + 设置页同一 voice.continuous)
749
+ "连续对话": "Continuous conversation",
750
+ "暂停听": "Pause listening",
751
+ "继续听": "Resume listening",
752
+ "连续对话中 · 右键可关闭": "Continuous conversation · right-click to turn off",
753
+ "⏸ 连续对话已暂停(点桌宠继续)": "⏸ Continuous conversation paused (click the pet to resume)",
754
+ "页面隐藏,连续对话已暂停": "Page hidden — continuous conversation paused",
755
+ "连续对话结束:已连续 {n} 轮": "Continuous conversation ended after {n} rounds",
756
+ "连续对话已停止:{e}": "Continuous conversation stopped: {e}",
757
+ "连续对话结束:连续 {n} 轮没听到": "Continuous conversation ended: no speech for {n} rounds",
758
+ "没听到,再说一次({n}/{m})": "Didn't hear that — try again ({n}/{m})",
759
+ // pre.64:大脑 v2(壁纸动作的客户端执行反馈)
760
+ "正在换壁纸…": "Switching wallpaper…",
761
+ "没找到叫「{name}」的壁纸": "No wallpaper named '{name}' was found",
762
+ "没有可用的壁纸": "No wallpapers available",
763
+ "壁纸切换没生效": "The wallpaper change did not take effect",
748
764
  "所选音色不可用,已用系统默认:{name}": "Selected voice is unavailable — using the system default: {name}",
749
765
  "所选音色不可用,已用系统默认音色": "Selected voice is unavailable — using the system default voice",
750
766
  // pre.54:本机音色来源 / 可下载目录骨架。
@@ -19407,6 +19423,25 @@ window.__ModuleLoader__.load({
19407
19423
  hasKey: false, maskedKey: '', lastError: '',
19408
19424
  });
19409
19425
  const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
19426
+ /** pre.63:把设置页的连续对话开关同步给右键菜单(同一 voice.continuous)。 */
19427
+ const publishContinuous = React.useCallback((enabled) => {
19428
+ try {
19429
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
19430
+ window.dispatchEvent(new CustomEvent('we-pet-continuous-state', { detail: { enabled: enabled === true } }));
19431
+ }
19432
+ } catch { /* 菜单同步是增强 */ }
19433
+ }, []);
19434
+ React.useEffect(() => {
19435
+ const onState = (event) => {
19436
+ const detail = (event && event.detail) || {};
19437
+ if (typeof detail.enabled === 'boolean') {
19438
+ setVoiceCfg((prev) => ({ ...prev, continuous: detail.enabled }));
19439
+ }
19440
+ };
19441
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return undefined;
19442
+ window.addEventListener('we-pet-continuous-state', onState);
19443
+ return () => window.removeEventListener('we-pet-continuous-state', onState);
19444
+ }, []);
19410
19445
 
19411
19446
  const load = React.useCallback(async () => {
19412
19447
  try {
@@ -19419,6 +19454,7 @@ window.__ModuleLoader__.load({
19419
19454
  voice.continuous = voice.continuous !== false;
19420
19455
  setDraft({ ...CHAT_DEFAULTS, ...doc, voice, apiKey: '' });
19421
19456
  setVoiceCfg({ sapiEnabled: voice.sapiEnabled, enabledEngine: voice.enabledEngine, continuous: voice.continuous });
19457
+ publishContinuous(voice.continuous !== false);
19422
19458
  setEnabledEngine(voice.enabledEngine);
19423
19459
  setCheckedEngine(voice.enabledEngine);
19424
19460
  setStatus(doc.hasApiKey
@@ -19426,7 +19462,7 @@ window.__ModuleLoader__.load({
19426
19462
  : { ok: null, text: weT('还没有填 API Key') });
19427
19463
  }
19428
19464
  } catch { /* 首次加载失败不打扰 */ }
19429
- }, []);
19465
+ }, [publishContinuous]);
19430
19466
 
19431
19467
  const loadVoices = React.useCallback(async () => {
19432
19468
  const resp = await apiJson('/pet-chat/tts/voices', { parse: 'always' }).catch(() => null);
@@ -19862,7 +19898,16 @@ window.__ModuleLoader__.load({
19862
19898
  },
19863
19899
  React.createElement('input', {
19864
19900
  type: 'checkbox', checked: continuousOn, disabled: busy,
19865
- onChange: (e) => setVoiceCfg((prev) => ({ ...prev, continuous: e.target.checked })),
19901
+ onChange: (e) => {
19902
+ const on = e.target.checked;
19903
+ setVoiceCfg((prev) => ({ ...prev, continuous: on }));
19904
+ publishContinuous(on);
19905
+ try {
19906
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
19907
+ window.dispatchEvent(new CustomEvent('we-pet-continuous', { detail: { action: 'set', enabled: on } }));
19908
+ }
19909
+ } catch { /* ignore */ }
19910
+ },
19866
19911
  }),
19867
19912
  weT('☑ 连续对话')));
19868
19913
  voicePage.push(React.createElement('div', {
@@ -20597,6 +20642,15 @@ window.__ModuleLoader__.load({
20597
20642
  let walkLeft = 0;
20598
20643
  /** 单击轮换到第几号轨道。 */
20599
20644
  let clickIdx = 0;
20645
+ /** pre.63:右键菜单的连续对话状态(由 pet-chat 通过事件同步)。 */
20646
+ let continuousEnabled = true;
20647
+ let continuousPaused = false;
20648
+ const onContinuousState = (event) => {
20649
+ const detail = (event && event.detail) || {};
20650
+ if (typeof detail.enabled === 'boolean') continuousEnabled = detail.enabled;
20651
+ if (typeof detail.paused === 'boolean') continuousPaused = detail.paused;
20652
+ if (menu) closeMenu();
20653
+ };
20600
20654
 
20601
20655
  let scaleCur = Number(scale) > 0 ? Number(scale) : 1;
20602
20656
  const cw = Math.max(1, Number(pet.cell && pet.cell.width) || 192);
@@ -20816,6 +20870,9 @@ window.__ModuleLoader__.load({
20816
20870
  * 菜单条目 = 9 条动作各一条(点一下立刻试演)+ 声音/大小/复位/隐藏。
20817
20871
  */
20818
20872
  let menu = null;
20873
+ if (typeof window !== "undefined" && window.addEventListener) {
20874
+ window.addEventListener("we-pet-continuous-state", onContinuousState);
20875
+ }
20819
20876
  function closeMenu() {
20820
20877
  if (menu && menu.parentNode) menu.parentNode.removeChild(menu);
20821
20878
  menu = null;
@@ -20858,6 +20915,33 @@ window.__ModuleLoader__.load({
20858
20915
  const hr = document.createElement("div");
20859
20916
  hr.style.cssText = "height:1px;margin:6px 0;background:rgba(255,255,255,0.14)";
20860
20917
  menu.appendChild(hr);
20918
+ // pre.63:连续对话(与设置页 voice.continuous 同一字段,由 pet-chat 同步状态/持久化)
20919
+ const sendContinuous = (action) => {
20920
+ try {
20921
+ window.dispatchEvent(new CustomEvent("we-pet-continuous", { detail: { action } }));
20922
+ } catch { /* 没装 pet-chat 时无副作用 */ }
20923
+ };
20924
+ menu.appendChild(buildMenuItem(
20925
+ (continuousEnabled ? "☑ " : "☐ ") + weT("连续对话"),
20926
+ () => {
20927
+ continuousEnabled = !continuousEnabled;
20928
+ sendContinuous("toggle");
20929
+ closeMenu();
20930
+ },
20931
+ ));
20932
+ if (continuousEnabled) {
20933
+ menu.appendChild(buildMenuItem(
20934
+ continuousPaused ? weT("继续听") : weT("暂停听"),
20935
+ () => {
20936
+ sendContinuous(continuousPaused ? "resume" : "pause");
20937
+ continuousPaused = !continuousPaused;
20938
+ closeMenu();
20939
+ },
20940
+ ));
20941
+ }
20942
+ const hr2 = document.createElement("div");
20943
+ hr2.style.cssText = "height:1px;margin:6px 0;background:rgba(255,255,255,0.14)";
20944
+ menu.appendChild(hr2);
20861
20945
  // 「对话」:打开桌宠对话的输入条(由 pet-chat 特性监听该事件;没装该特性时点了无副作用)
20862
20946
  menu.appendChild(buildMenuItem(weT("对话"), () => {
20863
20947
  try { window.dispatchEvent(new CustomEvent("we-pet-talk")); } catch { /* ignore */ }
@@ -20927,6 +21011,7 @@ window.__ModuleLoader__.load({
20927
21011
  if (typeof window !== "undefined") {
20928
21012
  window.removeEventListener("pointermove", onPointerMove);
20929
21013
  window.removeEventListener("pointerup", onPointerUp);
21014
+ window.removeEventListener("we-pet-continuous-state", onContinuousState);
20930
21015
  }
20931
21016
  }
20932
21017
 
@@ -22512,7 +22597,7 @@ window.__ModuleLoader__.load({
22512
22597
  return;
22513
22598
  }
22514
22599
  const labels = {
22515
- listen: '🎤 ' + (continuous ? tr('连续对话中·点桌宠暂停') : tr('在听')),
22600
+ listen: '🎤 ' + (continuous ? tr('连续对话中 · 右键可关闭') : tr('在听')),
22516
22601
  think: '💭 ' + tr('在想'),
22517
22602
  speak: '🔊 ' + tr('在说'),
22518
22603
  };
@@ -22534,11 +22619,11 @@ window.__ModuleLoader__.load({
22534
22619
 
22535
22620
  function isVisible() { return visible; }
22536
22621
 
22537
- /** 连续对话模式:把「在听」换成一语中的状态条,提醒用户点桌宠可暂停。 */
22622
+ /** 连续对话模式:把「在听」换成一语中的状态条,提醒右键可关闭。 */
22538
22623
  function setContinuous(active) {
22539
22624
  continuous = active === true;
22540
22625
  if (continuous && statusEl && statusEl.dataset && String(statusEl.dataset.state || '') === 'listen') {
22541
- statusEl.textContent = '🎤 ' + tr('连续对话中·点桌宠暂停');
22626
+ statusEl.textContent = '🎤 ' + tr('连续对话中 · 右键可关闭');
22542
22627
  }
22543
22628
  }
22544
22629
 
@@ -23074,6 +23159,7 @@ window.__ModuleLoader__.load({
23074
23159
  } catch { /* 读不到就用默认(不静音) */ }
23075
23160
  petChatContinuousEnabled = petChatVoice.continuous !== false;
23076
23161
  if (petChatContinuousEnabled === false) petChatContinuousStop('', true);
23162
+ petChatPublishContinuousState();
23077
23163
  return petChatVoice;
23078
23164
  }
23079
23165
 
@@ -23096,6 +23182,21 @@ window.__ModuleLoader__.load({
23096
23182
  }
23097
23183
  }
23098
23184
 
23185
+ /** pre.63:把连续对话状态推给右键菜单(pet-layer 监听)。 */
23186
+ function petChatPublishContinuousState() {
23187
+ try {
23188
+ if (typeof window === 'undefined' || typeof window.dispatchEvent !== 'function') return;
23189
+ window.dispatchEvent(new CustomEvent('we-pet-continuous-state', {
23190
+ detail: {
23191
+ enabled: petChatContinuousEnabled === true,
23192
+ active: petChatContinuousActive === true,
23193
+ paused: petChatContinuousPaused === true,
23194
+ rounds: petChatContinuousRounds,
23195
+ },
23196
+ }));
23197
+ } catch { /* 右键菜单是增强,事件失败不影响对话 */ }
23198
+ }
23199
+
23099
23200
  function petChatContinuousStart() {
23100
23201
  if (petChatContinuousEnabled !== true) return false;
23101
23202
  petChatContinuousClearTimer();
@@ -23103,6 +23204,7 @@ window.__ModuleLoader__.load({
23103
23204
  petChatContinuousPaused = false;
23104
23205
  if (petChatContinuousRounds === 0) petChatContinuousSilent = 0;
23105
23206
  petBubble.setContinuous(true);
23207
+ petChatPublishContinuousState();
23106
23208
  return true;
23107
23209
  }
23108
23210
 
@@ -23113,9 +23215,59 @@ window.__ModuleLoader__.load({
23113
23215
  petChatContinuousRounds = 0;
23114
23216
  petChatContinuousSilent = 0;
23115
23217
  petBubble.setContinuous(false);
23218
+ petChatPublishContinuousState();
23116
23219
  if (reason && silent !== true) petBubble.status('info', reason, { delay: 3500 });
23117
23220
  }
23118
23221
 
23222
+ /** 右键「暂停听」:立即停掉自动续听与当前录音,但保留 enabled 字段。 */
23223
+ function petChatContinuousPause(reason) {
23224
+ if (!petChatContinuousEnabled) return false;
23225
+ petChatVoiceAbort = true;
23226
+ try { petVoiceIn.stop(); } catch { /* ignore */ }
23227
+ petChatContinuousStop(reason || weT('⏸ 连续对话已暂停(点桌宠继续)'), false);
23228
+ return true;
23229
+ }
23230
+
23231
+ /** 右键「继续听」:恢复免点击循环,并立刻开下一轮(不用再点桌宠)。 */
23232
+ function petChatContinuousResume() {
23233
+ if (!petChatContinuousEnabled) return false;
23234
+ petChatVoiceAbort = false;
23235
+ petChatContinuousPaused = false;
23236
+ petChatContinuousStart();
23237
+ petChatContinuousArm(450);
23238
+ return true;
23239
+ }
23240
+
23241
+ /** 开关(菜单/设置页共用 voice.continuous):持久化 + 广播给菜单。 */
23242
+ function petChatSetContinuousEnabled(enabled) {
23243
+ const next = enabled === true;
23244
+ petChatContinuousEnabled = next;
23245
+ if (!next) {
23246
+ petChatVoiceAbort = true;
23247
+ try { petVoiceIn.stop(); } catch { /* ignore */ }
23248
+ petChatContinuousStop('', true);
23249
+ } else {
23250
+ petChatContinuousPaused = false;
23251
+ petChatVoiceAbort = false;
23252
+ petChatPublishContinuousState();
23253
+ }
23254
+ try {
23255
+ void apiPostJson('/pet-chat/voice/config', { continuous: next }, { parse: 'always' })
23256
+ .then(() => petChatRefreshVoice())
23257
+ .catch(() => { /* 设置页下次保存会再写 */ });
23258
+ } catch { /* ignore */ }
23259
+ return next;
23260
+ }
23261
+
23262
+ /** 右键菜单事件:toggle / pause / resume。 */
23263
+ function petChatOnContinuousCommand(event) {
23264
+ const action = String((event && event.detail && event.detail.action) || '');
23265
+ if (action === 'toggle') petChatSetContinuousEnabled(!petChatContinuousEnabled);
23266
+ else if (action === 'set') petChatSetContinuousEnabled(event.detail.enabled === true);
23267
+ else if (action === 'pause') petChatContinuousPause();
23268
+ else if (action === 'resume') petChatContinuousResume();
23269
+ }
23270
+
23119
23271
  /** 朗读结束或一次静默后,延迟 0.65s 自动开麦。 */
23120
23272
  function petChatContinuousArm(delayMs) {
23121
23273
  if (!petChatContinuousEnabled || !petChatContinuousActive || petChatContinuousPaused) return;
@@ -23150,6 +23302,253 @@ window.__ModuleLoader__.load({
23150
23302
  petChatContinuousArm(500);
23151
23303
  }
23152
23304
 
23305
+ /* ── v2 大脑(前端侧):情绪语速 / 环境快照 / 动作回执 / 主动触发 ─────────── */
23306
+
23307
+ /** 本轮回答的语速覆盖(宿主 meta 事件给 -1 = 夜间/疲惫 -10%)。 */
23308
+ let petChatSpeechRate = 0;
23309
+ /** 上一轮情绪(排障/测试可读;不参与 UI)。 */
23310
+ let petChatMood = 'neutral';
23311
+ /** 一轮对话进行中:主动搭话不得插嘴(模型在生成、气泡在更新)。 */
23312
+ let petChatTurnBusy = false;
23313
+ let petChatTurnBusyTimer = null;
23314
+ /** 壁纸变化观察:id / 变化时刻 / 标题。 */
23315
+ let petChatWallpaperId = '';
23316
+ let petChatWallpaperChangedAt = 0;
23317
+ let petChatWallpaperPendingTitle = '';
23318
+ let petChatWallpaperTimer = null;
23319
+ /** 连续工作:第一次用户消息 / 最近一条 / 今天是否已提醒。 */
23320
+ let petChatWorkStart = 0;
23321
+ let petChatWorkLastAt = 0;
23322
+ let petChatWorkNotifiedDay = '';
23323
+ let petChatWorkTimer = null;
23324
+ let petChatGreetingTimer = null;
23325
+
23326
+ function petChatDayKey(date) {
23327
+ const d = date instanceof Date ? date : new Date(date || Date.now());
23328
+ return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
23329
+ }
23330
+
23331
+ function petChatTurnBegin() {
23332
+ petChatTurnBusy = true;
23333
+ if (petChatTurnBusyTimer != null) clearTimeout(petChatTurnBusyTimer);
23334
+ // 兜底:任何异常路径都不该永久把主动搭话挡住
23335
+ petChatTurnBusyTimer = setTimeout(() => { petChatTurnBusy = false; petChatTurnBusyTimer = null; }, 30000);
23336
+ }
23337
+
23338
+ function petChatTurnEnd() {
23339
+ petChatTurnBusy = false;
23340
+ if (petChatTurnBusyTimer != null) { clearTimeout(petChatTurnBusyTimer); petChatTurnBusyTimer = null; }
23341
+ }
23342
+
23343
+ /** 现在能不能主动说一句:朗读中 / 录音中 / 一轮回答中 / 页面隐藏都不插嘴。 */
23344
+ function petChatProactiveAllowed() {
23345
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return false;
23346
+ if (petChatTurnBusy) return false;
23347
+ try { if (petTts.isSpeaking()) return false; } catch { /* 实例尚未就绪时按可说话处理 */ }
23348
+ try { if (petVoiceIn.isActive && petVoiceIn.isActive()) return false; } catch { /* ignore */ }
23349
+ return true;
23350
+ }
23351
+
23352
+ /** 宿主主动 tick:命中就念一句(事件触发 / 早晚问候共用)。 */
23353
+ async function petChatProactiveTick(event, extra) {
23354
+ if (!petChatProactiveAllowed()) return null;
23355
+ let speaking = false;
23356
+ let listening = false;
23357
+ try { speaking = petTts.isSpeaking(); } catch { speaking = false; }
23358
+ try { listening = Boolean(petVoiceIn.isActive && petVoiceIn.isActive()); } catch { listening = false; }
23359
+ try {
23360
+ const resp = await apiPostJson('/pet-chat/proactive/tick', {
23361
+ event,
23362
+ ...(extra || {}),
23363
+ speaking,
23364
+ listening,
23365
+ }, { parse: 'always' });
23366
+ const doc = (resp && resp.data) || {};
23367
+ if (!doc.ok || !doc.line) return null;
23368
+ petChatSay(String(doc.line));
23369
+ return String(doc.line);
23370
+ } catch {
23371
+ return null;
23372
+ }
23373
+ }
23374
+
23375
+ /** 当前壁纸(前端 selection 是唯一真源;拿不到就返回空)。 */
23376
+ function petChatCurrentWallpaper() {
23377
+ try {
23378
+ const id = String((typeof selection !== 'undefined' && selection && selection.id) || '');
23379
+ const list = (typeof selection !== 'undefined' && selection && selection.inventory
23380
+ && Array.isArray(selection.inventory.wallpapers)) ? selection.inventory.wallpapers : [];
23381
+ const hit = list.find((item) => item && String(item.id) === id) || null;
23382
+ return { id, title: String((hit && hit.title) || '') };
23383
+ } catch {
23384
+ return { id: '', title: '' };
23385
+ }
23386
+ }
23387
+
23388
+ /** 环境快照:壁纸名 + 正在播放(音量/桌宠由宿主读自己的配置)。 */
23389
+ async function petChatEnvSnapshot() {
23390
+ const wallpaper = petChatCurrentWallpaper();
23391
+ let playing = null;
23392
+ try {
23393
+ const resp = await Promise.race([
23394
+ apiJson('/now-playing', { parse: 'always' }),
23395
+ new Promise((resolve) => { setTimeout(() => resolve(null), 700); }),
23396
+ ]);
23397
+ const media = resp && resp.data && resp.data.media ? resp.data.media : null;
23398
+ if (media && media.title) playing = { title: media.title, artist: media.artist || '' };
23399
+ } catch { /* 没在播放 / 媒体桥没起:宿主环境行会写“无” */ }
23400
+ return { wallpaper, playing };
23401
+ }
23402
+
23403
+ function petChatLuminance(item) {
23404
+ const color = String((item && item.schemeColor) || '').replace('#', '');
23405
+ if (/^[0-9a-f]{6}$/i.test(color)) {
23406
+ const r = parseInt(color.slice(0, 2), 16);
23407
+ const g = parseInt(color.slice(2, 4), 16);
23408
+ const b = parseInt(color.slice(4, 6), 16);
23409
+ return r * 0.299 + g * 0.587 + b * 0.114;
23410
+ }
23411
+ return 999;
23412
+ }
23413
+
23414
+ function petChatIsDarkWallpaper(item) {
23415
+ return petChatLuminance(item) < 105 || /暗|黑|夜|深色|dark/i.test(String((item && item.title) || ''));
23416
+ }
23417
+
23418
+ /**
23419
+ * 客户端执行壁纸动作(宿主只发 action,不重写前端的 `applySelection`)。
23420
+ * 失败返回 `{ok:false,error}`,由宿主统一说人话 —— 这里只负责把真实结果回执回去。
23421
+ */
23422
+ async function petChatApplyAction(tool, args) {
23423
+ if (tool !== 'wallpaper_switch') return { ok: false, error: 'unsupported' };
23424
+ const input = args || {};
23425
+ let list;
23426
+ try {
23427
+ list = (selection.inventory && Array.isArray(selection.inventory.wallpapers))
23428
+ ? selection.inventory.wallpapers.slice() : [];
23429
+ } catch { list = []; }
23430
+ if (!list.length) {
23431
+ petBubble.status('error', weT('没有可用的壁纸'), { delay: 4000 });
23432
+ return { ok: false, error: 'no-wallpaper' };
23433
+ }
23434
+ const currentId = String((selection && selection.id) || '');
23435
+ const playable = list.filter((item) => item && item.playable !== false);
23436
+ const pool = playable.length ? playable : list;
23437
+ let target;
23438
+ const mode = String(input.mode || 'next');
23439
+ if (mode === 'byName') {
23440
+ const name = String(input.name || '').trim().toLowerCase();
23441
+ target = name
23442
+ ? list.find((item) => String((item && item.title) || '').toLowerCase().includes(name))
23443
+ : null;
23444
+ if (!target) {
23445
+ petBubble.status('error', weT('没找到叫「{name}」的壁纸', { name: String(input.name || '') }), { delay: 4000 });
23446
+ return { ok: false, error: 'no-match' };
23447
+ }
23448
+ } else if (mode === 'dark') {
23449
+ const dark = list.filter((item) => petChatIsDarkWallpaper(item));
23450
+ if (dark.length) target = dark[Math.floor(Math.random() * dark.length)];
23451
+ else {
23452
+ // 没有明确“暗色”的条目 ⇒ 选主题色最暗的那张,而不是随便挑一张亮图。
23453
+ const sorted = list.slice().sort((a, b) => petChatLuminance(a) - petChatLuminance(b));
23454
+ target = sorted[0] || null;
23455
+ }
23456
+ } else if (mode === 'random') {
23457
+ const source = pool.filter((item) => String(item.id) !== currentId);
23458
+ target = (source.length ? source : pool)[Math.floor(Math.random() * (source.length ? source.length : pool.length))];
23459
+ } else {
23460
+ const index = pool.findIndex((item) => String(item.id) === currentId);
23461
+ target = pool[(index >= 0 ? index + 1 : 0) % pool.length];
23462
+ }
23463
+ if (!target) return { ok: false, error: 'no-target' };
23464
+ petBubble.status('info', weT('正在换壁纸…'), { delay: 0 });
23465
+ try {
23466
+ applySelection(String(target.id), { fromManual: true });
23467
+ } catch {
23468
+ petBubble.hideStatus(0);
23469
+ return { ok: false, error: 'apply-failed' };
23470
+ }
23471
+ await new Promise((resolve) => { setTimeout(resolve, 700); });
23472
+ if (String((selection && selection.id) || '') !== String(target.id)) {
23473
+ petBubble.status('error', weT('壁纸切换没生效'), { delay: 4000 });
23474
+ return { ok: false, error: 'not-applied', targetId: String(target.id), title: String(target.title || '') };
23475
+ }
23476
+ petBubble.hideStatus(0);
23477
+ return { ok: true, targetId: String(target.id), title: String(target.title || '') };
23478
+ }
23479
+
23480
+ /** SSE action → 执行 → POST 回执。宿主据此**回读设置**再决定说不说成功。 */
23481
+ async function petChatHandleAction(payload) {
23482
+ const id = String((payload && payload.id) || '');
23483
+ if (!id) return;
23484
+ let result;
23485
+ try {
23486
+ result = await petChatApplyAction(String(payload.tool || ''), payload.args || {});
23487
+ } catch {
23488
+ result = { ok: false, error: 'action-failed' };
23489
+ }
23490
+ try {
23491
+ await apiPostJson('/pet-chat/tool-result', {
23492
+ id,
23493
+ ok: result.ok === true,
23494
+ targetId: result.targetId || '',
23495
+ title: result.title || '',
23496
+ error: result.error || '',
23497
+ }, { parse: 'always' });
23498
+ } catch { /* 回执失败由宿主超时判失败,不会谎报成功 */ }
23499
+ }
23500
+
23501
+ /** 每 4 秒看一次壁纸是否变化;变化满 30 秒且不忙时点评一句。 */
23502
+ function petChatWatchWallpaper() {
23503
+ if (typeof setInterval !== 'function') return null;
23504
+ const initial = petChatCurrentWallpaper();
23505
+ petChatWallpaperId = initial.id;
23506
+ return setInterval(() => {
23507
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
23508
+ const cur = petChatCurrentWallpaper();
23509
+ if (!petChatWallpaperId) { petChatWallpaperId = cur.id; return; }
23510
+ if (cur.id && cur.id !== petChatWallpaperId) {
23511
+ petChatWallpaperId = cur.id;
23512
+ petChatWallpaperChangedAt = Date.now();
23513
+ petChatWallpaperPendingTitle = cur.title;
23514
+ }
23515
+ if (!petChatWallpaperChangedAt) return;
23516
+ if (Date.now() - petChatWallpaperChangedAt < 30000) return;
23517
+ if (!petChatProactiveAllowed()) return; // 正在朗读/录音/回答:等下一拍,不插嘴
23518
+ const sinceMs = Date.now() - petChatWallpaperChangedAt;
23519
+ petChatWallpaperChangedAt = 0;
23520
+ void petChatProactiveTick('wallpaper', { wallpaperTitle: petChatWallpaperPendingTitle, sinceMs });
23521
+ }, 4000);
23522
+ }
23523
+
23524
+ /** 连续工作 ≥45 分钟(用户消息累计;10 分钟没消息视为中断)。 */
23525
+ function petChatWatchWork() {
23526
+ if (typeof setInterval !== 'function') return null;
23527
+ return setInterval(() => {
23528
+ if (!petChatWorkStart) return;
23529
+ const now = Date.now();
23530
+ if (now - petChatWorkLastAt > 10 * 60 * 1000) { petChatWorkStart = 0; return; }
23531
+ if (now - petChatWorkStart < 45 * 60 * 1000) return;
23532
+ const day = petChatDayKey(now);
23533
+ if (petChatWorkNotifiedDay === day) return;
23534
+ if (!petChatProactiveAllowed()) return;
23535
+ petChatWorkNotifiedDay = day;
23536
+ petChatWorkStart = 0;
23537
+ void petChatProactiveTick('work', { activeMinutes: 45 });
23538
+ }, 60000);
23539
+ }
23540
+
23541
+ /** 早晚问候:挂载后 3 秒试一次;宿主按 8–10 / 22 点后自行判定,每天只一次。 */
23542
+ function petChatMaybeGreet() {
23543
+ if (typeof setTimeout !== 'function') return null;
23544
+ return setTimeout(() => {
23545
+ if (!petChatProactiveAllowed()) return;
23546
+ void petChatProactiveTick('greeting', {});
23547
+ void petChatProactiveTick('night', {});
23548
+ }, 3500);
23549
+ }
23550
+
23551
+
23153
23552
  /**
23154
23553
  * 朗读实例(P1):宿主负责合成兜底,这里负责切句、排队、播、停、字幕同步。
23155
23554
  * 回调全部接到气泡:说 → `speak` 态 + 当前句;停/念完 → `idle` + 3 秒后淡出。
@@ -23218,11 +23617,19 @@ window.__ModuleLoader__.load({
23218
23617
  if (typeof onState === 'function') onState({ state: 'idle' });
23219
23618
  return;
23220
23619
  }
23620
+ petChatTurnBegin();
23621
+ petChatSpeechRate = 0;
23622
+ petChatMood = 'neutral';
23623
+ const workNow = Date.now();
23624
+ if (!petChatWorkStart || workNow - petChatWorkLastAt > 10 * 60 * 1000) petChatWorkStart = workNow;
23625
+ petChatWorkLastAt = workNow;
23221
23626
  petChatContinuousClearTimer();
23222
23627
  // “想”态:模型还在回,先不给“说”的波形
23223
23628
  petBubble.setState('think');
23224
23629
  // 新一轮回答从空气泡开始(否则会追加到上一轮回答的尾部)。
23225
23630
  petBubble.clear();
23631
+ // v2 环境感知:壁纸名 / 正在播放由前端补(宿主不认识 selection 与媒体桥实例)。
23632
+ const context = await petChatEnvSnapshot();
23226
23633
  // ⚠️ apiFetch 的返回值里**已经带上了原始 Response**(字段 `response`)。
23227
23634
  // 上一版误写成 `res.body.getReader()`:res 是 { ok, status, data, response },
23228
23635
  // res.body 恒为 undefined ⇒ 抛 TypeError ⇒ 读流代码一行都跑不到
@@ -23233,7 +23640,7 @@ window.__ModuleLoader__.load({
23233
23640
  res = await apiFetch('/pet-chat/chat', {
23234
23641
  method: 'POST',
23235
23642
  headers: { 'content-type': 'application/json' },
23236
- body: JSON.stringify({ text }),
23643
+ body: JSON.stringify({ text, context }),
23237
23644
  // ⚠️ 必须 parse:'none'。默认路径会 await response.json(),
23238
23645
  // 那会把 SSE 流**整个消费掉**(等到生成结束、再解析失败),
23239
23646
  // 之后 res.response.body 已 used ⇒ getReader() 抛错 ⇒ 气泡一个字都不出。
@@ -23242,12 +23649,14 @@ window.__ModuleLoader__.load({
23242
23649
  } catch {
23243
23650
  petBubble.status('error', '连不上宿主,稍后再试', { delay: 4000 });
23244
23651
  if (typeof onState === 'function') onState({ state: 'idle' });
23652
+ petChatTurnEnd();
23245
23653
  return;
23246
23654
  }
23247
23655
  const stream = res && res.response;
23248
23656
  if (!res || !res.ok || !stream || !stream.body) {
23249
23657
  petBubble.status('error', res && res.status === 401 ? '模型 Key 无效,去设置里换一把' : '这次没答上来,再试一次', { delay: 4000 });
23250
23658
  if (typeof onState === 'function') onState({ state: 'idle' });
23659
+ petChatTurnEnd();
23251
23660
  return;
23252
23661
  }
23253
23662
  let rawReply = '';
@@ -23263,7 +23672,8 @@ window.__ModuleLoader__.load({
23263
23672
  const enqueueSpeech = (piece) => {
23264
23673
  const line = String(piece || '').trim();
23265
23674
  if (!line) return;
23266
- if (petSpeak(line)) queuedSpeech += 1;
23675
+ // v2:本轮语速由宿主 meta 给(夜间/疲惫 -1 = -10%);队列里每句都带自己的 rate。
23676
+ if (petSpeak(line, { rate: petChatSpeechRate })) queuedSpeech += 1;
23267
23677
  };
23268
23678
  const reader = stream.body.getReader();
23269
23679
  const decoder = new TextDecoder();
@@ -23277,13 +23687,33 @@ window.__ModuleLoader__.load({
23277
23687
  if (cut < 0) break;
23278
23688
  const frame = buffer.slice(0, cut);
23279
23689
  buffer = buffer.slice(cut + 2);
23280
- const line = frame.split('\n').find((item) => item.startsWith('data:'));
23281
- if (!line) continue;
23690
+ let eventName = 'message';
23691
+ let dataLine = '';
23692
+ for (const row of frame.split('\n')) {
23693
+ if (row.startsWith('event:')) eventName = row.slice(6).trim();
23694
+ else if (row.startsWith('data:')) dataLine = row.slice(5).trim();
23695
+ }
23696
+ if (!dataLine) continue;
23282
23697
  let payload;
23283
- try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
23698
+ try { payload = JSON.parse(dataLine); } catch { payload = null; }
23699
+ if (!payload) continue;
23700
+ if (eventName === 'meta') {
23701
+ petChatMood = String(payload.mood || 'neutral');
23702
+ petChatSpeechRate = Number.isFinite(Number(payload.rate)) ? Number(payload.rate) : 0;
23703
+ continue;
23704
+ }
23705
+ if (eventName === 'action') {
23706
+ // 不 await:继续读流,宿主在收到 /tool-result 后才发后续 delta/done。
23707
+ void petChatHandleAction(payload);
23708
+ continue;
23709
+ }
23710
+ if (eventName === 'done') {
23711
+ if (Number.isFinite(Number(payload.rate))) petChatSpeechRate = Number(payload.rate);
23712
+ continue;
23713
+ }
23284
23714
  // 防兜底:模型偶尔仍会输出 {"reply":"…","emotion":"…"} 信封,
23285
23715
  // 这里只把 reply 的正文喂给气泡(不显示大括号/字段名/emotion)。
23286
- if (payload && typeof payload.t === 'string') {
23716
+ if (typeof payload.t === 'string') {
23287
23717
  rawReply += payload.t;
23288
23718
  let piece = payload.t;
23289
23719
  if (!replyStarted) {
@@ -23323,11 +23753,13 @@ window.__ModuleLoader__.load({
23323
23753
  }
23324
23754
  petChatContinuousRounds += 1;
23325
23755
  petChatContinuousSilent = 0;
23756
+ petChatPublishContinuousState();
23326
23757
  if (!queuedSpeech) petChatContinuousArm();
23327
23758
  }
23328
23759
  // 没有任何一句进入朗读(静音 / 合成不可用)⇒ 沿用旧行为:整段文字 3 秒后淡出。
23329
23760
  // 有朗读时由 petTts 的 onIdle 在念完后淡出(按句字幕不会被提前清掉)。
23330
23761
  if (!queuedSpeech) petBubble.hide(3000);
23762
+ petChatTurnEnd();
23331
23763
  },
23332
23764
  // P4:用户自己的话**不进**气泡(那是回声);只显示 assistant 的 SSE delta
23333
23765
  onText: () => {},
@@ -23424,7 +23856,7 @@ window.__ModuleLoader__.load({
23424
23856
  const seq = ++petChatWakeSeq;
23425
23857
  if (petChatContinuousActive || petChatContinuousTimer != null) {
23426
23858
  petChatVoiceAbort = true;
23427
- petChatContinuousStop(weT('连续对话已暂停,点桌宠继续'), false);
23859
+ petChatContinuousStop(weT('⏸ 连续对话已暂停(点桌宠继续)'), false);
23428
23860
  petBubble.hide(0);
23429
23861
  petBubble.hideStatus(0);
23430
23862
  petVoiceIn.stop();
@@ -23519,10 +23951,26 @@ window.__ModuleLoader__.load({
23519
23951
 
23520
23952
  window.addEventListener('we-pet-talk', onTalkEvent);
23521
23953
  window.addEventListener('we-pet-speak', onSpeakEvent);
23954
+ // pre.63:右键菜单的连续对话开关/暂停/继续(与设置页共用 voice.continuous)。
23955
+ const onContinuousEvent = (event) => { petChatOnContinuousCommand(event); };
23956
+ window.addEventListener('we-pet-continuous', onContinuousEvent);
23957
+ // 页面隐藏:自动暂停连续对话(不偷偷在后台开麦)。
23958
+ const onVisibility = () => {
23959
+ if (typeof document === 'undefined' || document.visibilityState !== 'hidden') return;
23960
+ if (petChatContinuousActive && !petChatContinuousPaused) {
23961
+ petChatContinuousPause(weT('页面隐藏,连续对话已暂停'));
23962
+ }
23963
+ };
23964
+ document.addEventListener('visibilitychange', onVisibility);
23522
23965
  document.addEventListener('click', onDocumentClick, true);
23523
23966
  document.addEventListener('keydown', onKeyDown, true);
23524
- void petChatRefreshVoice();
23967
+ void petChatRefreshVoice().then(() => petChatPublishContinuousState()).catch(() => {});
23525
23968
  petChatEventsStart();
23969
+ // v2 主动发起:壁纸变化 → 30 秒后点评;连续工作 45 分钟 → 休息提醒;挂载后试早晚问候。
23970
+ // 三条都受“正在朗读 / 正在听 / 一轮回答中 / 页面隐藏”约束(见 petChatProactiveAllowed)。
23971
+ petChatWallpaperTimer = petChatWatchWallpaper();
23972
+ petChatWorkTimer = petChatWatchWork();
23973
+ petChatGreetingTimer = petChatMaybeGreet();
23526
23974
  // 对外通道:`speak(text)` 供待办/提醒直接调用(不打开任何窗口)
23527
23975
  try {
23528
23976
  window.__dshFoliaPet = {
@@ -23535,8 +23983,16 @@ window.__ModuleLoader__.load({
23535
23983
  return () => {
23536
23984
  window.removeEventListener('we-pet-talk', onTalkEvent);
23537
23985
  window.removeEventListener('we-pet-speak', onSpeakEvent);
23986
+ window.removeEventListener('we-pet-continuous', onContinuousEvent);
23538
23987
  document.removeEventListener('click', onDocumentClick, true);
23539
23988
  document.removeEventListener('keydown', onKeyDown, true);
23989
+ document.removeEventListener('visibilitychange', onVisibility);
23990
+ if (petChatWallpaperTimer != null) clearInterval(petChatWallpaperTimer);
23991
+ if (petChatWorkTimer != null) clearInterval(petChatWorkTimer);
23992
+ if (petChatGreetingTimer != null) clearTimeout(petChatGreetingTimer);
23993
+ petChatWallpaperTimer = null;
23994
+ petChatWorkTimer = null;
23995
+ petChatGreetingTimer = null;
23540
23996
  petChatEventsStop();
23541
23997
  petSpeakStop();
23542
23998
  try { if (window.__dshFoliaPet) delete window.__dshFoliaPet; } catch { /* ignore */ }