dsh-folia 4.26.0-pre.1 → 4.26.0-pre.10

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
@@ -8082,21 +8082,21 @@ window.__ModuleLoader__.load({
8082
8082
  baseUrl: 'https://api.deepseek.com',
8083
8083
  apiKey: '', // 用户自己填;本机 Ollama 不需要
8084
8084
  model: 'deepseek-chat',
8085
- // 人设默认值(工单 A3):可在设置里改;这三段会进 system prompt。
8086
- persona: { name: 'Folia', style: '元气、短句、偶尔颜文字、不说教', traits: '喜欢壁纸和游戏,被夸会害羞' },
8087
- maxTurns: 8, // 上下文轮数上限(工单:默认 8,上限 12)
8088
- maxChars: 80, // 单条回复字数上限(工单:默认 80,上限 160)
8089
- // ── B:长期偏好记忆(只存结论,不存聊天原文)──
8090
- memoryEnabled: true,
8091
- memoryEveryTurns: 10,
8092
- // ── C:主动闲聊(默认关;开启后还要同时满足五个条件)──
8093
- proactiveEnabled: false,
8094
- proactiveDailyLimit: 10,
8095
- proactiveMinGapMin: 120,
8096
- quietHours: '22:00-08:00',
8097
- // ── 语音输入(默认关):真正干活的转写由 DSH 宿主的 speechToText 服务承担,
8098
- // 模型由那个 provider 自己下载/校验 —— 插件这边只负责录音与回填。
8099
- voiceEnabled: false,
8085
+ /**
8086
+ * v0.1 设置收敛:**只有一个对象、一套键**(工单 §5「配置单一真源」)。
8087
+ *
8088
+ * 旧键(persona / maxTurns / maxChars / voiceOut / voiceEngine / voiceEnabled)
8089
+ * 读入时由 readPetChat() 映射成这里的结构,写回只写新结构 —— 不再有第二套。
8090
+ * 上下文轮数 / 字数上限这两个"实现细节"降级为代码常量(见 DEFAULT_MAX_TURNS/CHARS),
8091
+ * 用户不再需要知道它们。
8092
+ */
8093
+ petName: '', // 桌宠名字(空 ⇒ 用宠物包 displayName);同时是唤醒词
8094
+ ownerName: '', // 用户希望被怎么称呼
8095
+ // 朗读:只有一个音色 + 一个静音开关(不再有 rate/pitch/volume/voiceURI 五件套)
8096
+ voice: { name: 'zh-CN-XiaoxiaoNeural', muted: false },
8097
+ // 唤醒:点一下默认开;叫名字默认关(S6 才实现,先在设置里留位)
8098
+ wake: { click: true, name: false, keyword: '' },
8099
+ // 对话记忆默认开启且**不暴露开关**(追加决定 1):能力常开,用户只能在右键里查看/清空
8100
8100
  },
8101
8101
  };
8102
8102
 
@@ -8814,6 +8814,10 @@ window.__ModuleLoader__.load({
8814
8814
  const PET_CHAT_PERSONA_MAX = 200;
8815
8815
 
8816
8816
  const petChatStr = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
8817
+ const petChatFloat = (v, lo, hi, fallback) => {
8818
+ const n = Number(v);
8819
+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
8820
+ };
8817
8821
  const petChatInt = (v, lo, hi, fallback) => {
8818
8822
  const n = Number(v);
8819
8823
  return Number.isFinite(n) ? Math.min(hi, Math.max(lo, Math.round(n))) : fallback;
@@ -8827,10 +8831,26 @@ window.__ModuleLoader__.load({
8827
8831
  * 主机名拼错的 URL 与其"修好",不如让用户重新填一次。
8828
8832
  * `apiKey` 原样保留(只在本机 profile 里),但**限长**,避免设置文件被灌爆。
8829
8833
  */
8834
+ /**
8835
+ * 朗读音色(v0.1 收敛:只剩 name + muted)。
8836
+ *
8837
+ * 迁移:老档里的 `voiceOut.voiceURI` / `voiceOut.enabled` / `voiceEngine` 在这里被吸收 ——
8838
+ * `voiceURI` 非空就当作用户选过的音色;`enabled:false` 等价于 `muted:true`。
8839
+ * 这样升级不会丢用户已经选过的音色,也不会把静音的人突然打开。
8840
+ */
8841
+ function readVoice(raw, legacy) {
8842
+ const def = DEFAULTS.petChat.voice;
8843
+ const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
8844
+ const old = legacy && typeof legacy === 'object' && !Array.isArray(legacy) ? legacy : {};
8845
+ const name = petChatStr(src.name, 120).trim() || petChatStr(old.voiceURI, 200).trim() || def.name;
8846
+ const muted = typeof src.muted === 'boolean' ? src.muted : old.enabled === false;
8847
+ return { name, muted };
8848
+ }
8830
8849
  function readPetChat(raw) {
8831
8850
  const def = DEFAULTS.petChat;
8832
8851
  const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
8833
8852
  const persona = src.persona && typeof src.persona === 'object' && !Array.isArray(src.persona) ? src.persona : {};
8853
+ const wake = src.wake && typeof src.wake === 'object' && !Array.isArray(src.wake) ? src.wake : {};
8834
8854
  const baseUrl = petChatStr(src.baseUrl, PET_CHAT_BASE_URL_MAX).trim();
8835
8855
  return {
8836
8856
  enabled: src.enabled === true,
@@ -8838,22 +8858,18 @@ window.__ModuleLoader__.load({
8838
8858
  baseUrl: baseUrl === '' || /^https?:\/\//i.test(baseUrl) ? baseUrl : '',
8839
8859
  apiKey: petChatStr(src.apiKey, PET_CHAT_API_KEY_MAX),
8840
8860
  model: petChatStr(src.model, PET_CHAT_MODEL_MAX).trim(),
8841
- persona: {
8842
- name: petChatStr(persona.name, PET_CHAT_PERSONA_MAX) || def.persona.name,
8843
- style: petChatStr(persona.style, PET_CHAT_PERSONA_MAX) || def.persona.style,
8844
- traits: petChatStr(persona.traits, PET_CHAT_PERSONA_MAX) || def.persona.traits,
8861
+ // 名字:新键优先;老档的 persona.name 迁移过来(不丢用户起过的名字)
8862
+ petName: petChatStr(src.petName, PET_CHAT_PERSONA_MAX).trim()
8863
+ || petChatStr(persona.name, PET_CHAT_PERSONA_MAX).trim(),
8864
+ ownerName: petChatStr(src.ownerName, PET_CHAT_PERSONA_MAX).trim(),
8865
+ voice: readVoice(src.voice, src.voiceOut),
8866
+ wake: {
8867
+ click: wake.click !== false,
8868
+ name: wake.name === true,
8869
+ keyword: petChatStr(wake.keyword, 40).trim(),
8845
8870
  },
8846
- maxTurns: petChatInt(src.maxTurns, 1, PET_CHAT_MAX_TURNS, def.maxTurns),
8847
- maxChars: petChatInt(src.maxChars, PET_CHAT_MIN_CHARS, PET_CHAT_MAX_CHARS, def.maxChars),
8848
- // B/C 的开关也在同一包里消毒:默认值来自 DEFAULTS,非法值回落默认。
8849
- memoryEnabled: src.memoryEnabled !== false,
8850
- memoryEveryTurns: petChatInt(src.memoryEveryTurns, 1, 50, def.memoryEveryTurns),
8851
- proactiveEnabled: src.proactiveEnabled === true,
8852
- proactiveDailyLimit: petChatInt(src.proactiveDailyLimit, 1, 20, def.proactiveDailyLimit),
8853
- proactiveMinGapMin: petChatInt(src.proactiveMinGapMin, 30, 720, def.proactiveMinGapMin),
8854
- quietHours: (typeof src.quietHours === 'string' && /^\d{2}:\d{2}-\d{2}:\d{2}$/.test(src.quietHours))
8855
- ? src.quietHours : def.quietHours,
8856
- voiceEnabled: src.voiceEnabled === true,
8871
+ // 记忆常开:设置里没有这个开关(追加决定 1),旧档里的 false 也不再尊重
8872
+ memoryEnabled: true,
8857
8873
  };
8858
8874
  }
8859
8875
 
@@ -9164,6 +9180,10 @@ window.__ModuleLoader__.load({
9164
9180
  ],
9165
9181
  // 适配器 + 媒体集成(`adapterTarget` 是跨簇共用键,归这里)
9166
9182
  media: ['audioSource', 'adapterTarget', 'mediaIntegration', 'mediaLyricsOnline'],
9183
+ // 桌宠对话(整包一个键)。**必须登记进这个对象**(`SETTINGS_NAMESPACE_NAMES` 就是它的键):
9184
+ // 客户端差量保存走 `PUT /settings/<ns>`,ns 不在名单里 ⇒ 宿主回 404
9185
+ // `unknown settings namespace` ⇒ 表现为"点保存一直失败"。
9186
+ petChat: ['petChat'],
9167
9187
  };
9168
9188
 
9169
9189
  /** 组件簇名(**只有这 7 个有路由**:`meta` 不在这张表里 ⇒ `/settings/meta` 是未知 ns ⇒ 404)。 */
@@ -18601,9 +18621,122 @@ window.__ModuleLoader__.load({
18601
18621
  weT("站点上还没有桌宠。")));
18602
18622
  }
18603
18623
 
18624
+ // ── 桌宠对话(/folia/pet-chat/*)────────────────────────────────────────
18625
+ // 放在页签底部,紧跟「显示桌宠 / 声音 / 音量 / 复位位置 / 大小」之后。
18626
+ children.push(React.createElement(PetChatSettings, { key: "petChat" }));
18627
+
18604
18628
  return React.createElement("div", { className: "we-picker__section" }, children);
18605
18629
  }
18606
18630
 
18631
+ /* ── 桌宠对话设置区 ─────────────────────────────────────────────────────── */
18632
+
18633
+ const CHAT_DEFAULTS = {
18634
+ provider: 'openai',
18635
+ baseUrl: 'https://api.deepseek.com',
18636
+ model: 'deepseek-chat',
18637
+ apiKey: '',
18638
+ apiKeyMasked: '',
18639
+ hasApiKey: false,
18640
+ petName: '',
18641
+ ownerName: '',
18642
+ };
18643
+
18644
+ /**
18645
+ * 设置页(v0.1 验收口径):**三项,无开关**。
18646
+ * 1) 模型 Key 2) 名字(桌宠名 = 唤醒词 + 你的称呼) 3) 音色(v0.2 占位,灰色只读)
18647
+ *
18648
+ * 为什么连"开启对话"都没有:工单要求用户不做选择 —— 填了 Key 就等于启用,
18649
+ * 主动搭话/记忆都是固定策略。删除任何开关,就少一次"用户要不要打开"的决策。
18650
+ */
18651
+ function PetChatSettings() {
18652
+ const [draft, setDraft] = React.useState(CHAT_DEFAULTS);
18653
+ const [status, setStatus] = React.useState({ ok: null, text: '' });
18654
+ const [note, setNote] = React.useState(null);
18655
+ const [busy, setBusy] = React.useState(false);
18656
+ const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
18657
+
18658
+ const load = React.useCallback(async () => {
18659
+ try {
18660
+ const resp = await apiJson('/pet-chat/config', { parse: 'always' });
18661
+ const doc = (resp && resp.data) || null;
18662
+ if (doc && doc.ok !== false) {
18663
+ setDraft({ ...CHAT_DEFAULTS, ...doc, apiKey: '' });
18664
+ setStatus(doc.hasApiKey
18665
+ ? { ok: true, text: weT('已保存的 Key:{mask}', { mask: doc.apiKeyMasked || '••••' }) }
18666
+ : { ok: null, text: weT('还没有填 API Key') });
18667
+ }
18668
+ } catch { /* 首次加载失败不打扰 */ }
18669
+ }, []);
18670
+ React.useEffect(() => { void load(); }, [load]);
18671
+
18672
+ const save = async () => {
18673
+ setBusy(true);
18674
+ try {
18675
+ // 填了 Key 就启用:面板不放任何开关,语义由 Key 的有无决定
18676
+ const body = { ...draft, apiKey: draft.apiKey || '', enabled: Boolean(draft.apiKey) || Boolean(draft.hasApiKey) };
18677
+ const resp = await apiJson('/pet-chat/config', { method: 'POST', body, parse: 'always' });
18678
+ const doc = (resp && resp.data) || {};
18679
+ if (doc.saved) {
18680
+ setNote({ ok: true, text: weT('已保存') });
18681
+ await load();
18682
+ const state = await apiJson('/pet-chat/state', { parse: 'always' });
18683
+ const sdoc = (state && state.data) || {};
18684
+ setStatus(sdoc.reachable
18685
+ ? { ok: true, text: weT('已连接 · {m}', { m: sdoc.model || draft.model }) }
18686
+ : { ok: false, text: sdoc.lastError ? weT('未连接:{e}', { e: sdoc.lastError }) : weT('已保存,但还没连上') });
18687
+ } else setNote({ ok: false, text: weT('保存失败') });
18688
+ } catch (e) {
18689
+ setNote({ ok: false, text: weT('保存失败:{msg}', { msg: (e && e.message) || '' }) });
18690
+ } finally { setBusy(false); }
18691
+ };
18692
+
18693
+ const row = (key, label, node) => React.createElement('label', {
18694
+ key, style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' },
18695
+ }, weT(label), node);
18696
+
18697
+ const child = [];
18698
+ child.push(React.createElement('div', { key: 'title', style: { fontWeight: 600, margin: '14px 0 4px', fontSize: '13px' } }, weT('桌宠语音助手')));
18699
+ child.push(React.createElement('div', { key: 'hint', className: 'we-picker__hint', style: { margin: '0 0 6px' } },
18700
+ weT('三项就够:填 Key、起名字、选音色。主动搭话与记忆是固定策略;停止/恢复对它说一声就行。')));
18701
+
18702
+ child.push(React.createElement('div', { key: 'key', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
18703
+ weT('模型 Key'),
18704
+ React.createElement('input', {
18705
+ type: 'password', value: draft.apiKey || '',
18706
+ placeholder: draft.hasApiKey ? (draft.apiKeyMasked || '••••••••') : weT('填 DeepSeek API Key'),
18707
+ disabled: busy, style: { flex: 1, minWidth: 0 },
18708
+ onChange: (e) => update({ apiKey: e.target.value }),
18709
+ }),
18710
+ ));
18711
+
18712
+ child.push(row('name', '名字', React.createElement('input', {
18713
+ type: 'text', value: draft.petName || '', placeholder: weT('桌宠叫什么(也是唤醒词)'), disabled: busy,
18714
+ style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ petName: e.target.value }),
18715
+ })));
18716
+ child.push(row('owner', '称呼', React.createElement('input', {
18717
+ type: 'text', value: draft.ownerName || '', placeholder: weT('它该怎么称呼你'), disabled: busy,
18718
+ style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ ownerName: e.target.value }),
18719
+ })));
18720
+
18721
+ // 音色:v0.2 占位(灰色、不可改),避免用户以为现在能选
18722
+ child.push(row('voice', '音色', React.createElement('select', {
18723
+ className: 'we-picker__playlist-select', disabled: true, value: 'zh-CN-XiaoxiaoNeural',
18724
+ },
18725
+ React.createElement('option', { value: 'zh-CN-XiaoxiaoNeural' }, weT('晓晓(v0.2 可选)')),
18726
+ )));
18727
+
18728
+ child.push(React.createElement('div', { key: 'status', className: 'we-picker__hint', style: { margin: '6px 0', color: status.ok === false ? '#f87171' : undefined } },
18729
+ status.text || weT('未连接')));
18730
+ if (note && note.text) {
18731
+ child.push(React.createElement('div', { key: 'note', className: 'we-picker__hint', style: { color: note.ok ? undefined : '#f87171' } }, note.text));
18732
+ }
18733
+ child.push(React.createElement('div', { key: 'save', style: { display: 'flex', gap: '6px', marginTop: '4px' } },
18734
+ React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: save }, weT('保存')),
18735
+ ));
18736
+
18737
+ return React.createElement('div', { style: { ...PET_STYLE.card, marginTop: '10px' } }, child);
18738
+ }
18739
+
18607
18740
  /** 页签组装点调用它。 */
18608
18741
  function renderPetsTab() {
18609
18742
  return React.createElement(PetsTabPanel, null);
@@ -20255,593 +20388,418 @@ window.__ModuleLoader__.load({
20255
20388
  } catch { return () => {}; }
20256
20389
  }
20257
20390
 
20258
- // ── 内联模块:src/pet-chat.js —— 桌宠对话气泡:点宠物出输入框,走宿主 /folia/pet-chat/* 的 SSE;没配模型时给预设台词(构建期注入;勿手改本段)──
20391
+ // ── 内联模块:src/pet-voice-input.js —— 语音输入(宿主录音版):POST /pet-chat/record → text → /chat SSE 回填,前端不碰媒体 API(构建期注入;勿手改本段)──
20259
20392
  /**
20260
- * pet-chat.js(客户端)— **桌宠对话气泡**(门 2 / 任务 A3)。
20261
- *
20262
- * 契约:宿主 `/folia/pet-chat/*`(见 lib/routes/pet-chat.js)。
20263
- * · 点桌面上的宠物 → 气泡(输入框 + 最近 6 条);Enter 发送 / Esc 关闭 / Ctrl+Alt+P 唤起
20264
- * · 回复走 SSE(delta 逐字追加),done 里带 emotion → 映射成宠物动作
20265
- * · 设置里没开(enabled=false)⇒ 不谈模型,直接给**预设台词库**(30+ 句,按情绪分组)
20393
+ * pet-voice-input.js — 桌宠语音输入(v0.1,宿主侧录音版)。
20266
20394
  *
20267
- * 为什么自己读 SSE 而不用 EventSource:聊天是 POST(要带请求体),EventSource 只支持 GET。
20268
- * 所以用 fetch + response.body 的 reader,按 `\n\n` 切帧自己解 —— 二十来行,换来不被协议绑死。
20395
+ * 为什么不在前端录:DSH 的 Electron 只放行 clipboard/notifications 权限,
20396
+ * 音频采集在 Electron 里被权限层拒绝且没有弹窗(工单「追加决定 3」)。所以这里**不碰任何
20397
+ * media API**:点一下 → 让宿主录(ffmpeg dshow)→ 拿 text → 走 SSE 逐字回气泡。
20269
20398
  *
20270
- * 不变量:
20271
- * · **不碰模型的 key**:key 只在宿主设置里,客户端连读都不读。
20272
- * · **不自己拼模型端点**:所有请求都打本机 `/folia/pet-chat/*`。
20273
- * · 气泡是 `position: fixed` 的独立层,不参与面板重渲染(与 pet-layer 同一套思路)。
20399
+ * 判据(test/verify-pet-voice.mjs)用假 postRecord/postChat 覆盖全链路与失败码。
20274
20400
  */
20275
- /**
20276
- * 预设台词库(工单 A4):**五组 ≥30 句**。
20277
- * `enabled=false`(没配模型)与宿主回 `no-model` 两条路径都从这里取,按组轮换。
20278
- */
20279
- const PET_CHAT_PRESET_LINES = {
20280
- // 问候(6)
20281
- greeting: ['你来啦!', '在的,随时找我。', '今天也一起看壁纸吧。', '嗨,我在角落待着呢。', '好久没见,忙完了吗?', '我在,有事说一声。'],
20282
- // 壁纸相关(8)
20283
- wallpaper: [
20284
- '这张的配色我挺喜欢的。', '要不要试试轮播?每半小时换一张。', '4K 那张看着真舒服。',
20285
- '这张有点糊,要换吗?', '桌面空着也行,等你挑到喜欢的。', '夜里的壁纸挑暗一点更护眼。',
20286
- '刚换的那张,我盯了好一会儿。', '要不要把喜欢的几张放进一个分组?',
20287
- ],
20288
- // 陪伴与鼓励(8)
20289
- company: [
20290
- '慢慢来,不急。', '今天辛苦了。', '喝水了吗?', '卡住就歇五分钟。',
20291
- '你做得比你以为的好。', '我在这儿,安静陪着也行。', '忙完记得伸个懒腰。',
20292
- '有我看着桌面,你专心干活。',
20293
- ],
20294
- // 空状态与失败兜底(5)
20295
- fallback: [
20296
- '(还没接上模型,先陪你聊聊天)', '(在设置里填 API Key,我就能正经回你了)',
20297
- '(模型没回应,等一下再试?)', '(这条没听懂,再说一次?)', '(我在这儿,只是暂时说不上话)',
20298
- ],
20299
- // 夜间(3)
20300
- night: ['夜深了,早点休息。', '要不要换张暗一点的壁纸?', '我先趴一会儿,晚安。'],
20301
- };
20401
+ function petVoiceInputCreate(deps) {
20402
+ const options = deps || {};
20403
+ const postRecord = options.postRecord;
20404
+ const postChat = options.postChat;
20405
+ const onText = typeof options.onText === 'function' ? options.onText : () => {};
20406
+ const onError = typeof options.onError === 'function' ? options.onError : () => {};
20407
+ const onState = typeof options.onState === 'function' ? options.onState : () => {};
20302
20408
 
20303
- /** 情绪 → 宠物动作轨道(缺轨道时回落 idle,见 petApplyEmotion)。 */
20304
- const PET_CHAT_EMOTION_TRACK = { happy: 'wave', tired: 'sleep', angry: 'idle', calm: 'idle' };
20305
- /** 气泡里保留的最近条数(工单:最近 6 条)。 */
20306
- const PET_CHAT_KEEP_LINES = 6;
20409
+ let active = false;
20307
20410
 
20411
+ async function finishWithText(text) {
20412
+ if (!text) return;
20413
+ onText(text);
20414
+ if (typeof postChat === 'function') await postChat(text, onState);
20415
+ }
20308
20416
 
20309
- /** 极简 DOM 替身可能没有 append / addEventListener:统一走这两个助手,坏环境里安静跳过。 */
20310
- function petChatAppend(el, ...kids) {
20311
- if (!el) return;
20312
- if (typeof el.append === 'function') { el.append(...kids); return; }
20313
- if (typeof el.appendChild === 'function') { for (const kid of kids) el.appendChild(kid); }
20314
- }
20315
- function petChatOn(el, type, fn) {
20316
- if (el && typeof el.addEventListener === 'function') el.addEventListener(type, fn);
20417
+ async function start() {
20418
+ if (active) return true;
20419
+ active = true;
20420
+ onState({ state: 'listening' });
20421
+ let result;
20422
+ try {
20423
+ result = await postRecord({});
20424
+ } catch (error) {
20425
+ active = false;
20426
+ onError({ code: (error && error.code) || 'network', message: String((error && error.message) || error) });
20427
+ return false;
20428
+ }
20429
+ const doc = result || {};
20430
+ if (doc.ok !== true) {
20431
+ active = false;
20432
+ onError({ code: doc.code || 'record-failed', message: doc.hint || '' });
20433
+ return false;
20434
+ }
20435
+ onState({ state: 'transcribing', text: doc.text });
20436
+ try {
20437
+ await finishWithText(String(doc.text || ''));
20438
+ } catch (error) {
20439
+ onError({ code: 'network', message: String((error && error.message) || error) });
20440
+ return false;
20441
+ } finally {
20442
+ active = false;
20443
+ onState({ state: 'idle' });
20444
+ }
20445
+ return true;
20446
+ }
20447
+
20448
+ function stop() { active = false; onState({ state: 'idle' }); }
20449
+
20450
+ return { start, stop, isActive: () => active };
20317
20451
  }
20318
20452
 
20319
- let petChatEls = null;
20320
- let petChatLines = [];
20321
- let petChatBusy = false;
20453
+ // ── 内联模块:src/pet-bubble.js —— 头顶气泡:锚定桌宠头顶、跟随位置/缩放、逐字显示、最多 6 行、朗读结束 +3s 淡出(构建期注入;勿手改本段)──
20454
+ /**
20455
+ * pet-bubble.js — 头顶气泡(v0.1 S2)。
20456
+ *
20457
+ * 与旧面板的区别:**只显示**,不承载输入框 / 历史列表 / 关闭按钮;输入走右键「打字说…」,
20458
+ * 语音走唤醒链路(S3)。这样做是因为旧面板把"窗口"和"助手"混在一起,
20459
+ * 用户点桌宠时弹出一个像聊天软件的窗口,与"桌宠在旁边说话"的产品形态冲突。
20460
+ *
20461
+ * 依赖全部注入(document / 定时器 / 锚点),这样 Node 里能用假 DOM 跑判据;
20462
+ * 浏览器侧由 pet-chat.js 用真实 window 构造。
20463
+ */
20464
+ function petBubbleCreate(deps) {
20465
+ const options = deps || {};
20466
+ const doc = options.document;
20467
+ // 没有定时器的环境(极简 DOM 替身的冒烟测试)不能因为裸 setTimeout 直接炸:
20468
+ // 退化成立即执行 / 空取消,气泡仍能显示,只是没有延迟淡出。
20469
+ const setTimer = typeof options.setTimeout === 'function'
20470
+ ? options.setTimeout
20471
+ : (typeof setTimeout === 'function' ? setTimeout : (fn) => { if (typeof fn === 'function') fn(); return 0; });
20472
+ const clearTimer = typeof options.clearTimeout === 'function'
20473
+ ? options.clearTimeout
20474
+ : (typeof clearTimeout === 'function' ? clearTimeout : () => {});
20475
+ const getAnchor = typeof options.getAnchor === 'function' ? options.getAnchor : () => null;
20476
+ /** 最多显示几行(超出用 CSS 行钳制,见 lineClamp 样式)。 */
20477
+ const MAX_LINES = 6;
20478
+
20479
+ let el = null;
20480
+ let text = '';
20481
+ let visible = false;
20482
+ let fadeTimer = null;
20322
20483
 
20323
- /** 气泡 DOM(懒建:不点宠物就不建,免得影响启动)。 */
20324
- function petChatBuild() {
20325
- if (petChatEls) return petChatEls;
20326
- try {
20327
- const root = document.createElement('div');
20328
- root.id = 'we-pet-chat';
20329
- root.style.cssText = [
20330
- 'position:fixed', 'right:24px', 'bottom:172px', 'width:320px', 'max-height:420px',
20331
- 'display:none', 'flex-direction:column', 'gap:8px', 'padding:12px', 'z-index:2147483000',
20332
- 'background:rgba(24,24,28,.92)', 'color:#f2f2f5', 'border:1px solid rgba(255,255,255,.12)',
20333
- 'border-radius:14px', 'box-shadow:0 12px 32px rgba(0,0,0,.45)', 'backdrop-filter:blur(10px)',
20334
- 'font-size:13px', 'line-height:1.5',
20335
- ].join(';');
20336
-
20337
- const head = document.createElement('div');
20338
- head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:8px';
20339
- const title = document.createElement('strong');
20340
- title.textContent = weT('桌宠对话');
20341
- const tools = document.createElement('div');
20342
- tools.style.cssText = 'display:flex;align-items:center;gap:6px';
20343
- // 麦克风:**按住说话**(pointerdown 开始 / pointerup 或移出结束),松手上传
20344
- const voiceBtn = document.createElement('button');
20345
- voiceBtn.type = 'button';
20346
- voiceBtn.textContent = weT('按住说话');
20347
- voiceBtn.title = weT('按住说话,松手识别(需先在 DSH 开启语音输入)');
20348
- voiceBtn.style.cssText = 'background:none;border:1px solid rgba(255,255,255,.14);border-radius:7px;color:#c9c9d1;font-size:11px;padding:2px 6px;cursor:pointer;user-select:none';
20349
- petChatOn(voiceBtn, 'pointerdown', (event) => { if (event && event.preventDefault) event.preventDefault(); void petChatVoiceStart(); });
20350
- petChatOn(voiceBtn, 'pointerup', () => { void petChatVoiceStop(); });
20351
- petChatOn(voiceBtn, 'pointerleave', () => { if (petChatVoice) void petChatVoiceStop(); });
20352
- const memoryBtn = document.createElement('button');
20353
- memoryBtn.type = 'button';
20354
- memoryBtn.textContent = weT('查看记忆');
20355
- memoryBtn.style.cssText = 'background:none;border:1px solid rgba(255,255,255,.14);border-radius:7px;color:#c9c9d1;font-size:11px;padding:2px 6px;cursor:pointer';
20356
- petChatOn(memoryBtn, 'click', () => petChatShowMemory());
20357
- const clear = document.createElement('button');
20358
- clear.type = 'button';
20359
- clear.textContent = weT('清空记忆');
20360
- clear.style.cssText = 'background:none;border:1px solid rgba(255,255,255,.14);border-radius:7px;color:#c9c9d1;font-size:11px;padding:2px 6px;cursor:pointer';
20361
- petChatOn(clear, 'click', () => petChatResetMemory());
20362
- const close = document.createElement('button');
20363
- close.type = 'button';
20364
- close.textContent = '×';
20365
- close.title = weT('关闭');
20366
- close.style.cssText = 'background:none;border:0;color:#c9c9d1;font-size:18px;cursor:pointer;line-height:1';
20367
- petChatOn(close, 'click', () => petChatHide());
20368
- petChatAppend(tools, voiceBtn, memoryBtn, clear, close);
20369
- petChatAppend(head, title, tools);
20370
-
20371
- const log = document.createElement('div');
20372
- log.style.cssText = 'flex:1 1 auto;overflow:auto;display:flex;flex-direction:column;gap:6px;min-height:80px';
20373
-
20374
- // C2:今日已说 N/10 + 「今天别说了」(只有开启主动闲聊时才显示整行)
20375
- const usage = document.createElement('div');
20376
- usage.style.cssText = 'display:none;align-items:center;justify-content:space-between;gap:6px;font-size:11px;color:#9a9aa5';
20377
- const usageText = document.createElement('span');
20378
- const skipBtn = document.createElement('button');
20379
- skipBtn.type = 'button';
20380
- skipBtn.textContent = weT('今天别说了');
20381
- skipBtn.style.cssText = 'background:none;border:1px solid rgba(255,255,255,.14);border-radius:7px;color:#c9c9d1;font-size:11px;padding:1px 6px;cursor:pointer';
20382
- petChatOn(skipBtn, 'click', () => petChatSkipToday());
20383
- petChatAppend(usage, usageText, skipBtn);
20384
-
20385
- const status = document.createElement('div');
20386
- status.style.cssText = 'font-size:11px;color:#9a9aa5;min-height:14px';
20387
-
20388
- const row = document.createElement('div');
20389
- row.style.cssText = 'display:flex;gap:6px';
20390
- const input = document.createElement('input');
20391
- input.type = 'text';
20392
- input.placeholder = weT('和我说点什么…');
20393
- input.style.cssText = 'flex:1 1 auto;min-width:0;padding:6px 8px;border-radius:8px;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.06);color:inherit;outline:none';
20394
- const send = document.createElement('button');
20395
- send.type = 'button';
20396
- send.textContent = weT('发送');
20397
- send.style.cssText = 'padding:6px 10px;border-radius:8px;border:1px solid rgba(255,255,255,.16);background:rgba(124,92,255,.35);color:inherit;cursor:pointer';
20398
- petChatOn(send, 'click', () => petChatSend());
20399
- petChatOn(input, 'keydown', (event) => {
20400
- if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); petChatSend(); }
20401
- });
20402
- petChatAppend(row, input, send);
20484
+ /** 锚点 → 气泡位置:水平居中于桌宠,垂直贴在头顶上方。 */
20485
+ function place() {
20486
+ if (!el) return;
20487
+ const anchor = getAnchor();
20488
+ if (!anchor) return;
20489
+ const width = Number(anchor.width) || 0;
20490
+ const height = Number(anchor.height) || 0;
20491
+ const left = Math.round(Number(anchor.left || 0) + width / 2);
20492
+ const top = Math.round(Number(anchor.top || 0) - 8);
20493
+ el.style.left = `${left}px`;
20494
+ el.style.top = `${top}px`;
20495
+ // 锚点也跟着缩放:桌宠放大时气泡不要贴在旧位置
20496
+ el.style.transform = `translate(-50%, -100%) scale(${Number(anchor.scale) || 1})`;
20497
+ }
20498
+
20499
+ function ensure() {
20500
+ if (el || !doc || typeof doc.createElement !== 'function') return el;
20501
+ el = doc.createElement('div');
20502
+ el.className = 'we-pet-bubble';
20503
+ el.style.position = 'fixed';
20504
+ el.style.zIndex = '9999';
20505
+ el.style.maxWidth = '260px';
20506
+ el.style.padding = '8px 10px';
20507
+ el.style.borderRadius = '12px';
20508
+ el.style.background = 'rgba(24,24,28,.92)';
20509
+ el.style.color = '#f2f2f5';
20510
+ el.style.fontSize = '12px';
20511
+ el.style.lineHeight = '1.5';
20512
+ el.style.pointerEvents = 'none';
20513
+ el.style.opacity = '0';
20514
+ el.style.transition = 'opacity .18s ease';
20515
+ // 超过 6 行省略:气泡永远不长大到挡住桌宠
20516
+ el.style.display = '-webkit-box';
20517
+ el.style.webkitLineClamp = String(MAX_LINES);
20518
+ el.style.webkitBoxOrient = 'vertical';
20519
+ el.style.overflow = 'hidden';
20520
+ el.style.whiteSpace = 'pre-wrap';
20521
+ if (doc.body && typeof doc.body.appendChild === 'function') doc.body.appendChild(el);
20522
+ return el;
20523
+ }
20403
20524
 
20404
- petChatAppend(root, head, usage, log, status, row);
20405
- petChatAppend(document.body, root);
20406
- petChatEls = { root, log, status, input, send, usage, usageText };
20407
- return petChatEls;
20408
- } catch {
20409
- // 替身 DOM 撑不起这套结构:当成"没有气泡",不影响其它功能
20410
- return null;
20525
+ function cancelFade() {
20526
+ if (fadeTimer != null) { clearTimer(fadeTimer); fadeTimer = null; }
20411
20527
  }
20412
- }
20413
20528
 
20414
- /** 渲染最近 N 条(role=user 靠右、assistant 靠左)。 */
20415
- function petChatRender() {
20416
- const els = petChatBuild();
20417
- if (!els) return;
20418
- els.log.textContent = '';
20419
- for (const line of petChatLines) {
20420
- const bubble = document.createElement('div');
20421
- bubble.textContent = line.text;
20422
- bubble.style.cssText = 'max-width:86%;padding:6px 9px;border-radius:10px;white-space:pre-wrap;word-break:break-word;'
20423
- + (line.role === 'user'
20424
- ? 'align-self:flex-end;background:rgba(124,92,255,.42)'
20425
- : 'align-self:flex-start;background:rgba(255,255,255,.08)');
20426
- els.log.appendChild(bubble);
20529
+ /** 显示(或继续显示)一段文本;重复调用会重排文本而不是叠出第二个气泡。 */
20530
+ function show(nextText) {
20531
+ if (!ensure()) return;
20532
+ cancelFade();
20533
+ text = String(nextText == null ? '' : nextText);
20534
+ el.textContent = text;
20535
+ el.style.opacity = '1';
20536
+ visible = true;
20537
+ place();
20427
20538
  }
20428
- els.log.scrollTop = els.log.scrollHeight;
20429
- }
20430
20539
 
20431
- function petChatPush(role, text) {
20432
- petChatLines.push({ role, text });
20433
- if (petChatLines.length > PET_CHAT_KEEP_LINES) petChatLines = petChatLines.slice(-PET_CHAT_KEEP_LINES);
20434
- petChatRender();
20435
- }
20540
+ /** 逐字/逐段追加(SSE 每个 chunk 调一次)。 */
20541
+ function append(chunk) {
20542
+ if (!ensure()) return;
20543
+ cancelFade();
20544
+ text += String(chunk == null ? '' : chunk);
20545
+ el.textContent = text;
20546
+ el.style.opacity = '1';
20547
+ visible = true;
20548
+ place();
20549
+ }
20436
20550
 
20437
- function petChatStatus(text) {
20438
- const els = petChatBuild();
20439
- if (!els) return;
20440
- els.status.textContent = text || '';
20441
- }
20551
+ /** 隐藏;带 delay 时先挂着,到点淡出(朗读结束后 +3s 用这个)。 */
20552
+ function hide(delayMs) {
20553
+ if (!el) return;
20554
+ cancelFade();
20555
+ const delay = Number(delayMs) || 0;
20556
+ const doHide = () => {
20557
+ fadeTimer = null;
20558
+ el.style.opacity = '0';
20559
+ visible = false;
20560
+ };
20561
+ if (delay > 0) { fadeTimer = setTimer(doHide, delay); return; }
20562
+ doHide();
20563
+ }
20442
20564
 
20443
- function petChatShow() {
20444
- const els = petChatBuild();
20445
- if (!els) return;
20446
- els.root.style.display = 'flex';
20447
- if (typeof els.input.focus === 'function') els.input.focus();
20448
- petChatSyncState();
20449
- petChatRefreshUsage();
20450
- }
20565
+ /** 状态:听 / 想 / 答(客户端据此换桌宠动作、给气泡配色)。 */
20566
+ function setState(kind) {
20567
+ if (!el) return;
20568
+ el.dataset = el.dataset || {};
20569
+ el.dataset.state = String(kind || '');
20570
+ }
20451
20571
 
20452
- function petChatHide() {
20453
- if (!petChatEls) return;
20454
- petChatEls.root.style.display = 'none';
20455
- }
20572
+ function isVisible() { return visible; }
20456
20573
 
20457
- function petChatToggle() {
20458
- const els = petChatBuild();
20459
- if (!els) return;
20460
- if (els.root.style.display === 'none' || !els.root.style.display) petChatShow();
20461
- else petChatHide();
20574
+ function dispose() {
20575
+ cancelFade();
20576
+ if (el && typeof el.remove === 'function') el.remove();
20577
+ el = null;
20578
+ text = '';
20579
+ visible = false;
20580
+ }
20581
+
20582
+ return {
20583
+ show, append, hide, setState, place, isVisible, dispose,
20584
+ // 判据要读的内部状态
20585
+ get text() { return text; },
20586
+ get element() { return el; },
20587
+ MAX_LINES,
20588
+ };
20462
20589
  }
20463
20590
 
20464
- /** 五组台词按顺序轮换(同一次会话里不重复同一组,比纯随机更像"有人在")。 */
20591
+ // ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
20592
+ /**
20593
+ * pet-chat.js — 桌宠语音助手(v0.1 客户端)。
20594
+ *
20595
+ * v0.1 范围(docs/PET-V01-ACCEPTANCE.md):**语音输入 + 头顶文字气泡 + 名字/记忆 + 主动搭话**,
20596
+ * **不含任何朗读/TTS**(v0.2 再做)。所以这里没有 speechSynthesis、没有 /pet-chat/speak 调用。
20597
+ *
20598
+ * 交互:点桌宠 = 唤醒 → 气泡显示它的话(3 秒后淡出,点一下立刻收起)。
20599
+ * 没有聊天窗口:无输入框、无历史列表、无开关按钮。
20600
+ */
20601
+ const PET_CHAT_PRESET_LINES = {
20602
+ greeting: [
20603
+ '我在呢。',
20604
+ '叫我就来。',
20605
+ '嗯?我在听。',
20606
+ '你回来啦。',
20607
+ '有我在,别急。',
20608
+ '今天想聊点什么?',
20609
+ ],
20610
+ wallpaper: [
20611
+ '要不要换张壁纸?',
20612
+ '这张看久了,换一张吧。',
20613
+ '桌面有点暗,换个亮一点的?',
20614
+ '轮播开着,让它自己换吧。',
20615
+ '我给你挑一张安静的。',
20616
+ '这张当壁纸挺合适。',
20617
+ '换张清爽的,眼睛舒服点。',
20618
+ '需要我记住你喜欢的风格吗?',
20619
+ ],
20620
+ company: [
20621
+ '我在这儿待着。',
20622
+ '忙你的,我不吵。',
20623
+ '要喝水吗?我提醒你。',
20624
+ '坐久了,起来动一动。',
20625
+ '累了就歇会儿。',
20626
+ '今天也辛苦了。',
20627
+ '我陪着你。',
20628
+ '慢慢来,不急。',
20629
+ ],
20630
+ fallback: [
20631
+ '这个我还不会,等我学学。',
20632
+ '没听清,再说一次?',
20633
+ '换个说法试试?',
20634
+ '我先记下来。',
20635
+ '这个得你来定。',
20636
+ ],
20637
+ night: [
20638
+ '夜深了,早点睡。',
20639
+ '我先安静一会儿。',
20640
+ '明天见。',
20641
+ ],
20642
+ };
20643
+
20644
+ /** 轮流取一句预设台词(分组轮换,避免总说同一组)。 */
20465
20645
  let petChatPresetCursor = 0;
20646
+ const PET_CHAT_PRESET_ORDER = ['greeting', 'wallpaper', 'company', 'fallback', 'night'];
20466
20647
  function petChatPresetLine() {
20467
- const groups = Object.keys(PET_CHAT_PRESET_LINES);
20468
- const group = groups[petChatPresetCursor % groups.length];
20648
+ const group = PET_CHAT_PRESET_LINES[PET_CHAT_PRESET_ORDER[petChatPresetCursor % PET_CHAT_PRESET_ORDER.length]];
20469
20649
  petChatPresetCursor += 1;
20470
- const lines = PET_CHAT_PRESET_LINES[group] || [];
20471
- return lines[Math.floor(Math.random() * lines.length)] || '……';
20472
- }
20473
-
20474
- /** A2:清空记忆(宿主那边清会话记忆 + 长期偏好)。 */
20475
- async function petChatResetMemory() {
20476
- try {
20477
- const res = await apiPostJson('/pet-chat/reset', {}, { parse: 'always' });
20478
- if (res && res.ok) petChatStatus(weT('已清空'));
20479
- else petChatStatus(weT('清空失败'));
20480
- } catch {
20481
- petChatStatus(weT('清空失败'));
20482
- }
20650
+ return group[Math.floor(Math.random() * group.length)];
20483
20651
  }
20484
20652
 
20485
- /** 问宿主"配好没"(失败就当作没配,不弹错误框)。 */
20486
- async function petChatSyncState() {
20487
- try {
20488
- const probe = await apiJson('/pet-chat/state', { parse: 'always' });
20489
- const doc = probe && probe.data;
20490
- // 语音输入开关由宿主带回来:false ⇒ 按麦克风只提示"先去 DSH 开",不弹权限框
20491
- petChatVoiceEnabled = doc && doc.voiceEnabled === true;
20492
- if (!doc || doc.enabled !== true) {
20493
- petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
20494
- return null;
20495
- }
20496
- if (doc.reachable === false) {
20497
- petChatStatus(weT('连不上模型端点') + (doc.lastError ? ':' + doc.lastError : ''));
20498
- return doc;
20499
- }
20500
- petChatStatus(weT('已连接') + ' · ' + String(doc.provider || '') + ' · ' + String(doc.model || ''));
20501
- return doc;
20502
- } catch {
20503
- petChatStatus(weT('宿主没有响应'));
20504
- return null;
20505
- }
20506
- }
20507
-
20508
- /** 情绪 → 动作:优先用宿主暴露的播放钩子,没有就保持 idle(不报错)。 */
20509
- function petChatApplyEmotion(emotion) {
20510
- const track = PET_CHAT_EMOTION_TRACK[emotion] || 'idle';
20511
- const host = typeof window !== 'undefined' ? window : null;
20512
- if (!host) return;
20513
- try {
20514
- if (typeof host.__wePetPlay === 'function') host.__wePetPlay(track);
20515
- } catch { /* 播放失败不影响聊天 */ }
20516
- }
20517
-
20518
- /** 按 `\n\n` 切 SSE 帧;每帧里 `event: x` + `data: {...}`。 */
20519
- function petChatParseFrame(frame) {
20520
- let event = 'message';
20521
- const dataLines = [];
20522
- for (const line of frame.split('\n')) {
20523
- if (line.startsWith('event:')) event = line.slice(6).trim();
20524
- else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
20525
- }
20526
- if (!dataLines.length) return null;
20527
- try { return { event, data: JSON.parse(dataLines.join('\n')) }; } catch { return null; }
20528
- }
20529
-
20530
- /** 发送一句(SSE 流式)。 */
20531
- async function petChatSend() {
20532
- if (petChatBusy) return;
20533
- const els = petChatBuild();
20534
- if (!els) return;
20535
- const text = String(els.input.value || '').trim();
20536
- if (!text) return;
20537
- if ([...text].length > 400) { petChatStatus(weT('一次最多 400 字')); return; }
20538
- els.input.value = '';
20539
- petChatPush('user', text);
20540
- petChatBusy = true;
20541
- petChatStatus(weT('思考中…'));
20542
-
20543
- const state = await petChatSyncState();
20544
- if (!state || state.enabled !== true) {
20545
- // 没有模型:不假装在对话,直接给预设台词
20546
- petChatPush('assistant', petChatPresetLine());
20547
- petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
20548
- petChatBusy = false;
20549
- return;
20550
- }
20653
+ /** 头顶气泡实例:锚点取桌宠层矩形,跟随位置与缩放。 */
20654
+ const petBubble = petBubbleCreate({
20655
+ document: typeof document !== 'undefined' ? document : undefined,
20656
+ getAnchor: () => {
20657
+ try {
20658
+ const layer = document && document.querySelector ? document.querySelector('#we-pet-layer') : null;
20659
+ if (!layer || typeof layer.getBoundingClientRect !== 'function') return null;
20660
+ const rect = layer.getBoundingClientRect();
20661
+ const style = window.getComputedStyle(layer);
20662
+ const scale = Number(style.getPropertyValue('--we-pet-scale')) || 1;
20663
+ return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, scale };
20664
+ } catch { return null; }
20665
+ },
20666
+ });
20551
20667
 
20552
- let assistant = '';
20553
- const ensureBubble = () => {
20554
- if (!assistant) { petChatPush('assistant', ''); }
20555
- };
20556
- try {
20557
- const call = await apiFetch('/pet-chat/chat', {
20558
- method: 'POST',
20559
- headers: { 'content-type': 'application/json' },
20560
- body: JSON.stringify({ text }),
20561
- parse: false,
20668
+ /** 语音输入(v0.1):前端不碰麦克风 —— 宿主用 ffmpeg 录,这里只发请求、收文本。 */
20669
+ const petVoiceIn = petVoiceInputCreate({
20670
+ postRecord: async () => {
20671
+ const res = await apiPostJson('/pet-chat/record', { language: 'zh' }, { parse: 'always' });
20672
+ return (res && res.data) || {};
20673
+ },
20674
+ postChat: async (text, onState) => {
20675
+ petBubble.setState('answer');
20676
+ const res = await apiFetch('/pet-chat/chat', {
20677
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }),
20562
20678
  });
20563
- const response = call && call.response;
20564
- if (!call || !call.ok || !response || !response.body) {
20565
- petChatStatus(weT('宿主拒绝了这次请求') + '(HTTP ' + response.status + ')');
20566
- petChatBusy = false;
20567
- return;
20568
- }
20569
- const reader = response.body.getReader();
20679
+ const reader = res.body.getReader();
20570
20680
  const decoder = new TextDecoder();
20571
20681
  let buffer = '';
20572
20682
  for (;;) {
20573
- // eslint-disable-next-line no-await-in-loop -- 流式读取必须逐块等
20574
- const { value, done } = await reader.read();
20683
+ const { value, done } = await reader.read(); // eslint-disable-line no-await-in-loop
20575
20684
  if (done) break;
20576
20685
  buffer += decoder.decode(value, { stream: true });
20577
- const frames = buffer.split('\n\n');
20578
- buffer = frames.pop() ?? '';
20579
- for (const frame of frames) {
20580
- const parsed = petChatParseFrame(frame);
20581
- if (!parsed) continue;
20582
- if (parsed.event === 'delta' && parsed.data && typeof parsed.data.t === 'string') {
20583
- assistant += parsed.data.t;
20584
- ensureBubble();
20585
- petChatLines[petChatLines.length - 1] = { role: 'assistant', text: assistant };
20586
- petChatRender();
20587
- } else if (parsed.event === 'done') {
20588
- petChatApplyEmotion(parsed.data && parsed.data.emotion);
20589
- petChatStatus('');
20590
- } else if (parsed.event === 'error') {
20591
- const code = parsed.data && parsed.data.code ? parsed.data.code : 'error';
20592
- const hint = parsed.data && parsed.data.hint ? parsed.data.hint : '';
20593
- petChatStatus(hint || code);
20594
- if (code === 'no-model') petChatPush('assistant', petChatPresetLine());
20595
- }
20686
+ for (;;) {
20687
+ const cut = buffer.indexOf('\n\n');
20688
+ if (cut < 0) break;
20689
+ const frame = buffer.slice(0, cut);
20690
+ buffer = buffer.slice(cut + 2);
20691
+ const line = frame.split('\n').find((item) => item.startsWith('data:'));
20692
+ if (!line) continue;
20693
+ let payload = null;
20694
+ try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
20695
+ if (payload && typeof payload.t === 'string') petBubble.append(payload.t);
20596
20696
  }
20597
20697
  }
20598
- } catch {
20599
- petChatStatus(weT('发送失败,重试一次?'));
20600
- } finally {
20601
- petChatBusy = false;
20602
- if (!assistant) petChatStatus('');
20603
- }
20604
- }
20698
+ if (typeof onState === 'function') onState({ state: 'idle' });
20699
+ petBubble.hide(3000);
20700
+ },
20701
+ onText: (text) => { petBubble.append(text); },
20702
+ onError: (error) => {
20703
+ // 失败一律回落打字:只给一行提示,不弹错误框
20704
+ const map = {
20705
+ 'no-device': '没找到麦克风,先打字吧',
20706
+ 'ffmpeg-missing': '缺少 ffmpeg,先打字吧',
20707
+ 'asr-not-ready': '语音输入还没就绪:去 DSH 设置里开启(需下载模型)',
20708
+ timeout: '这次没听清,再说一次或直接打字',
20709
+ 'no-speech': '没听到声音,再说一次或直接打字',
20710
+ network: '网络不太顺,重试或直接打字',
20711
+ };
20712
+ const message = map[error && error.code] || '没听清,直接打字也行';
20713
+ petBubble.show(message);
20714
+ petBubble.hide(3000);
20715
+ petChatOpenTyping({ hint: message });
20716
+ },
20717
+ });
20605
20718
 
20606
20719
  /**
20607
- * 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点宠物 / 快捷键。
20608
- * 返回 cleanup —— 卸载时要摘掉监听、删掉 DOM。
20720
+ * 打字兜底(右键 → 打字说…):一个小输入条挂在桌宠上方,回车发 /chat。
20721
+ * 为什么不用 window.prompt:Electron 里 prompt 返回 null,用户会以为坏了。
20609
20722
  */
20610
- /** B4「查看记忆」:拉偏好摘要显示在气泡里(只显示结论,不含原文)。 */
20611
- async function petChatShowMemory() {
20612
- try {
20613
- const res = await apiJson('/pet-chat/memory', { parse: 'always' });
20614
- const doc = (res && res.data) || {};
20615
- if (!doc.ok) { petChatStatus(weT('读取记忆失败')); return; }
20616
- if (doc.enabled === false) { petChatStatus(weT('记忆已关闭(设置 → 桌宠对话)')); return; }
20617
- const m = doc.memory || {};
20618
- const parts = [];
20619
- if (m.nickname) parts.push('称呼:' + m.nickname);
20620
- if (Array.isArray(m.likes) && m.likes.length) parts.push('喜欢:' + m.likes.join('、'));
20621
- if (Array.isArray(m.dislikes) && m.dislikes.length) parts.push('不喜欢:' + m.dislikes.join('、'));
20622
- if (m.style) parts.push('说话风格:' + m.style);
20623
- if (Array.isArray(m.notes) && m.notes.length) parts.push('备注:' + m.notes.join('、'));
20624
- petChatPush('assistant', parts.length ? parts.join('\n') : weT('还没有记住任何偏好'));
20625
- petChatStatus(parts.length ? weT('点「清空记忆」可以全部忘掉') : '');
20626
- } catch {
20627
- petChatStatus(weT('读取记忆失败'));
20628
- }
20629
- }
20630
-
20631
- /** C2「今天别说了」:当天不再主动。 */
20632
- async function petChatSkipToday() {
20633
- try {
20634
- const res = await apiPostJson('/pet-chat/skip', {}, { parse: 'always' });
20635
- petChatStatus(res && res.ok ? weT('今天不主动打扰了') : weT('操作失败'));
20636
- await petChatRefreshUsage();
20637
- } catch {
20638
- petChatStatus(weT('操作失败'));
20639
- }
20723
+ function petChatOpenTyping(extra = {}) {
20724
+ if (typeof document === 'undefined' || !document.createElement) return;
20725
+ const existed = document.querySelector('#we-pet-typing');
20726
+ if (existed) { existed.focus(); return; }
20727
+ const box = document.createElement('div');
20728
+ box.id = 'we-pet-typing';
20729
+ box.style.cssText = 'position:fixed;z-index:10000;left:50%;bottom:120px;transform:translateX(-50%);'
20730
+ + 'display:flex;gap:6px;background:rgba(24,24,28,.95);padding:8px;border-radius:10px;';
20731
+ const input = document.createElement('input');
20732
+ input.type = 'text';
20733
+ input.placeholder = (extra && extra.hint) || '打字说…(回车发送)';
20734
+ input.style.cssText = 'width:240px;padding:6px 8px;border-radius:8px;border:1px solid #444;background:#111;color:#eee;';
20735
+ const send = () => {
20736
+ const text = String(input.value || '').trim();
20737
+ if (!text) return;
20738
+ box.remove();
20739
+ petBubble.show(text);
20740
+ void petVoiceIn.postChat(text);
20741
+ };
20742
+ input.addEventListener('keydown', (event) => {
20743
+ if (event.key === 'Enter') send();
20744
+ if (event.key === 'Escape') box.remove();
20745
+ });
20746
+ box.appendChild(input);
20747
+ document.body.appendChild(box);
20748
+ input.focus();
20640
20749
  }
20641
20750
 
20642
- /** 刷新「今日已说 N/10」(开启主动闲聊时显示)。 */
20643
- async function petChatRefreshUsage() {
20644
- const els = petChatEls || petChatBuild();
20645
- if (!els || !els.usage) return;
20646
- try {
20647
- const res = await apiJson('/pet-chat/proactive', { parse: 'always' });
20648
- const doc = (res && res.data) || {};
20649
- if (!doc.enabled) { els.usage.style.display = 'none'; return; }
20650
- const usage = doc.usage || {};
20651
- els.usageText.textContent = `今日已说 ${Number(usage.said) || 0}/${Number(usage.limit) || 0}`;
20652
- els.usage.style.display = 'flex';
20653
- } catch {
20654
- els.usage.style.display = 'none';
20655
- }
20656
- }
20657
-
20658
- /* ── 语音输入(按住说话)──────────────────────────────────────────────────────
20659
- * 三层分工:
20660
- * ① 录音(这里):getUserMedia + AudioWorklet 采 PCM → 16kHz 单声道 PCM16 WAV;
20661
- * ② 转写(宿主):POST /pet-chat/transcribe → DSH 的 speechToText(provider 自己管模型);
20662
- * ③ 回填(这里):**只写输入框**,绝不自动发送 —— 识别难免错,得让用户改完再发。
20663
- * 失败一律回落打字(只给一行状态提示,不弹错误框)。
20664
- */
20665
- const PET_CHAT_VOICE_MAX_SECONDS = 15;
20666
- let petChatVoice = null;
20667
- let petChatVoiceEnabled = null;
20668
-
20669
- /** Float32 PCM → 16kHz 单声道 PCM16 WAV。 */
20670
- function petChatEncodeWav(samples, sampleRate) {
20671
- const rate = 16000;
20672
- const ratio = sampleRate / rate;
20673
- const frames = Math.max(1, Math.floor(samples.length / ratio));
20674
- const buffer = new ArrayBuffer(44 + frames * 2);
20675
- const view = new DataView(buffer);
20676
- const put = (offset, text) => { for (let i = 0; i < text.length; i += 1) view.setUint8(offset + i, text.charCodeAt(i)); };
20677
- put(0, 'RIFF'); view.setUint32(4, 36 + frames * 2, true); put(8, 'WAVE');
20678
- put(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
20679
- view.setUint32(24, rate, true); view.setUint32(28, rate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
20680
- put(36, 'data'); view.setUint32(40, frames * 2, true);
20681
- let offset = 44;
20682
- for (let i = 0; i < frames; i += 1) {
20683
- const index = Math.min(samples.length - 1, Math.floor(i * ratio));
20684
- const clamped = Math.max(-1, Math.min(1, samples[index]));
20685
- view.setInt16(offset, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
20686
- offset += 2;
20687
- }
20688
- return new Uint8Array(buffer);
20689
- }
20690
-
20691
- /** Uint8Array → base64(浏览器与 Node 都可用)。 */
20692
- function petChatToBase64(bytes) {
20693
- let binary = '';
20694
- for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
20695
- if (typeof btoa === 'function') return btoa(binary);
20696
- return Buffer.from(bytes).toString('base64');
20697
- }
20698
-
20699
- /** 开始录音。返回是否真的开始了。 */
20700
- async function petChatVoiceStart() {
20701
- if (petChatVoice) return true;
20702
- if (petChatVoiceEnabled === false) {
20703
- petChatStatus(weT('语音输入未开启:请先在 DSH 设置里启用(需下载模型)'));
20704
- return false;
20705
- }
20706
- try {
20707
- const media = navigator.mediaDevices && navigator.mediaDevices.getUserMedia
20708
- ? await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, sampleRate: 16000 } })
20709
- : null;
20710
- const AudioCtx = window.AudioContext || window.webkitAudioContext;
20711
- if (!media || !AudioCtx) {
20712
- if (media) media.getTracks().forEach((track) => track.stop());
20713
- petChatStatus(weT('打不开麦克风,可以继续打字'));
20714
- return false;
20715
- }
20716
- const ctx = new AudioCtx();
20717
- const source = ctx.createMediaStreamSource(media);
20718
- const chunks = [];
20719
- // AudioWorklet:每帧 Float32 丢回主线程(不阻塞渲染)
20720
- const code = 'class P extends AudioWorkletProcessor{process(inputs){const ch=inputs[0]&&inputs[0][0];if(ch)this.port.postMessage(ch.slice(0));return true;}}registerProcessor("pet-chat-pcm",P);';
20721
- const url = URL.createObjectURL(new Blob([code], { type: 'application/javascript' }));
20722
- await ctx.audioWorklet.addModule(url);
20723
- URL.revokeObjectURL(url);
20724
- const node = new AudioWorkletNode(ctx, 'pet-chat-pcm');
20725
- node.port.onmessage = (event) => {
20726
- if (petChatVoice && chunks.length * 1024 < 16000 * PET_CHAT_VOICE_MAX_SECONDS * 8) chunks.push(event.data);
20727
- };
20728
- source.connect(node);
20729
- node.connect(ctx.destination);
20730
- petChatVoice = { stream: media, ctx, node, source, chunks, sampleRate: ctx.sampleRate };
20731
- petChatStatus(weT('正在听…松手结束'));
20732
- return true;
20733
- } catch {
20734
- // 最典型的是权限被拒(NotAllowedError):提示一行,允许继续打字
20735
- petChatStatus(weT('没有麦克风权限(或未授权),可以继续打字'));
20736
- return false;
20737
- }
20751
+ /** 说一句:气泡显示 + 3 秒后淡出。
20752
+ * v0.1 不朗读 —— 这里刻意不做音频(验收⑦:lib/ 里不允许出现 speechSynthesis)。
20753
+ */
20754
+ function petChatSay(text) {
20755
+ const line = String(text || '').trim();
20756
+ if (!line) return;
20757
+ petBubble.show(line);
20758
+ petBubble.hide(3000);
20738
20759
  }
20739
20760
 
20740
- /** 结束录音 → 编码 → 上传 → **只回填输入框**。 */
20741
- async function petChatVoiceStop() {
20742
- const voice = petChatVoice;
20743
- if (!voice) return;
20744
- petChatVoice = null;
20745
- try {
20746
- voice.node.port.onmessage = null;
20747
- voice.source.disconnect();
20748
- voice.node.disconnect();
20749
- voice.stream.getTracks().forEach((track) => track.stop());
20750
- await voice.ctx.close();
20751
- } catch { /* 收尾失败不影响转写 */ }
20752
-
20753
- const total = voice.chunks.reduce((sum, chunk) => sum + chunk.length, 0);
20754
- if (!total) { petChatStatus(weT('没听到声音,再试一次?')); return; }
20755
- const merged = new Float32Array(total);
20756
- let offset = 0;
20757
- for (const chunk of voice.chunks) { merged.set(chunk, offset); offset += chunk.length; }
20758
- const wav = petChatEncodeWav(merged, voice.sampleRate);
20759
-
20760
- petChatStatus(weT('识别中…'));
20761
- // ↓ 这一段是 D⑥ 的判据面:只写 input.value,绝不调用 petChatSend
20762
- const res = await apiPostJson('/pet-chat/transcribe', { audio: petChatToBase64(wav), language: 'zh' }, { parse: 'always' });
20763
- const doc = (res && res.data) || {};
20764
- const els = petChatEls || petChatBuild();
20765
- if (!doc.ok) {
20766
- petChatStatus(weT('这次没听清,可以继续打字') + (doc.hint ? '(' + doc.hint + ')' : ''));
20767
- return;
20768
- }
20769
- if (els && typeof doc.text === 'string') {
20770
- els.input.value = doc.text;
20771
- if (typeof els.input.focus === 'function') els.input.focus();
20772
- petChatStatus(weT('识别完成,确认后按发送'));
20773
- }
20761
+ /** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音);否则唤醒并开始听。 */
20762
+ function petChatWake() {
20763
+ if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
20764
+ petBubble.setState('listen');
20765
+ void petVoiceIn.start().then((started) => {
20766
+ if (!started) return; // 失败分支已经由 onError 提示(回落打字)
20767
+ petBubble.show('我在听…');
20768
+ });
20774
20769
  }
20775
20770
 
20776
20771
  /**
20777
- * C1:每 5 分钟问一次"现在能主动说话吗"。
20778
- *
20779
- * 五条件里渲染进程能拿到的事实:开关/计数/间隔/静默时段由宿主判,
20780
- * 客户端只提供 `fullscreen`(document.fullscreenElement)、`focused`(document.hasFocus())
20781
- * 和 `idleMinutes`(**窗口内**最近一次键鼠事件距现在多久)。
20782
- * ⚠️ 这不是系统全局空闲(Electron 的 powerMonitor.getSystemIdleTime 在渲染进程拿不到),
20783
- * 只是"这个窗口最近有没有人动"的近似 —— 已在 docs/PET-CHAT-DONE.md 写明。
20772
+ * 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点桌宠 / 快捷键。
20773
+ * 返回 cleanup —— 卸载时摘监听、销毁气泡。
20784
20774
  */
20785
- async function petChatProactiveCheck() {
20786
- if (petChatBusy) return;
20787
- const idleMinutes = (Date.now() - petChatLastActivityAt) / 60000;
20788
- const fullscreen = typeof document !== 'undefined' && Boolean(document.fullscreenElement);
20789
- const focused = typeof document !== 'undefined' && typeof document.hasFocus === 'function' ? document.hasFocus() : true;
20790
- try {
20791
- const res = await apiPostJson('/pet-chat/proactive/tick', { idleMinutes, fullscreen, focused, randomHit: Math.random() < 0.25 }, { parse: 'always' });
20792
- const doc = (res && res.data) || {};
20793
- if (doc.line) {
20794
- petChatShow();
20795
- petChatPush('assistant', doc.line);
20796
- }
20797
- await petChatRefreshUsage();
20798
- } catch { /* 主动闲聊失败不打扰用户 */ }
20799
- }
20800
-
20801
- /** 最近一次窗口内活动的时间(C1 的 idleMinutes 来自它)。 */
20802
- let petChatLastActivityAt = Date.now();
20803
- /** 5 分钟检查定时器(渲染进程能拿到的事实,仅窗口内)。 */
20804
- const PET_CHAT_CHECK_INTERVAL_MS = 5 * 60 * 1000;
20805
-
20806
20775
  function mountPetChat() {
20807
- // 宿主 / 测试替身里可能没有 DOM 能力:没有就安静地不挂,而不是让装配层炸掉
20808
- if (typeof document === 'undefined' || typeof document.addEventListener !== 'function'
20809
- || typeof document.createElement !== 'function') {
20810
- return () => {};
20811
- }
20776
+ if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return () => {};
20812
20777
  const onDocumentClick = (event) => {
20813
20778
  const target = event.target;
20814
20779
  if (!target || typeof target.closest !== 'function') return;
20815
- if (target.closest('#we-pet-layer')) petChatShow();
20780
+ if (target.closest('#we-pet-layer')) petChatWake();
20816
20781
  };
20817
20782
  const onKeyDown = (event) => {
20818
20783
  if (event.altKey && event.ctrlKey && String(event.key).toLowerCase() === 'p') {
20819
20784
  event.preventDefault();
20820
- petChatToggle();
20821
- return;
20785
+ petChatWake();
20822
20786
  }
20823
- if (event.key === 'Escape' && petChatEls && petChatEls.root.style.display === 'flex') petChatHide();
20824
20787
  };
20825
- // C1 的"窗口内活动":键鼠/滚轮/触摸都算(passive,不拦截任何默认行为)
20826
- const markActivity = () => { petChatLastActivityAt = Date.now(); };
20827
- const activityEvents = ['mousemove', 'mousedown', 'keydown', 'wheel', 'touchstart'];
20788
+ const onContextMenu = (event) => {
20789
+ const target = event.target;
20790
+ if (!target || typeof target.closest !== 'function') return;
20791
+ if (!target.closest('#we-pet-layer')) return;
20792
+ event.preventDefault();
20793
+ petChatOpenTyping();
20794
+ };
20795
+ document.addEventListener('contextmenu', onContextMenu, true);
20828
20796
  document.addEventListener('click', onDocumentClick, true);
20829
20797
  document.addEventListener('keydown', onKeyDown, true);
20830
- for (const name of activityEvents) window.addEventListener(name, markActivity, { passive: true });
20831
- // 每 5 分钟问一次(不是每秒):拿不到系统级空闲,用窗口内活动近似。
20832
- // 替身环境里没有 setInterval ⇒ 跳过(只影响主动闲聊,不影响聊天本身)
20833
- const timer = typeof setInterval === 'function'
20834
- ? setInterval(() => { void petChatProactiveCheck(); }, PET_CHAT_CHECK_INTERVAL_MS)
20835
- : null;
20836
- if (timer && typeof timer.unref === 'function') timer.unref();
20837
20798
  return () => {
20838
- if (timer && typeof clearInterval === 'function') clearInterval(timer);
20799
+ document.removeEventListener('contextmenu', onContextMenu, true);
20839
20800
  document.removeEventListener('click', onDocumentClick, true);
20840
20801
  document.removeEventListener('keydown', onKeyDown, true);
20841
- for (const name of activityEvents) window.removeEventListener(name, markActivity);
20842
- if (petChatEls && petChatEls.root.parentNode) petChatEls.root.parentNode.removeChild(petChatEls.root);
20843
- petChatEls = null;
20844
- petChatLines = [];
20802
+ petBubble.dispose();
20845
20803
  };
20846
20804
  }
20847
20805