dsh-folia 4.26.0-pre.2 → 4.26.0-pre.21
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/asr/asr-local.js +166 -0
- package/lib/asr/asr-worker.cjs +169 -0
- package/lib/client.js +616 -757
- package/lib/index.js +5 -1
- package/lib/pet-chat-proactive.js +147 -74
- package/lib/routes/pet-chat.js +555 -74
- package/lib/routes/pets.js +30 -2
- package/lib/settings-schema.js +2161 -2168
- package/lib/tts/tts-worker.cjs +129 -0
- package/lib/voice/record.js +217 -0
- package/package.json +5 -1
package/lib/client.js
CHANGED
|
@@ -761,6 +761,7 @@ window.__ModuleLoader__.load({
|
|
|
761
761
|
"再小一点": "Smaller",
|
|
762
762
|
"回右下角": "Back to corner",
|
|
763
763
|
"不显示它": "Hide it",
|
|
764
|
+
"对话": "Chat",
|
|
764
765
|
"站点上还没有桌宠。": "No pets on the site yet.",
|
|
765
766
|
"站点不可达": "Site unreachable",
|
|
766
767
|
"预览尺寸": "Preview-size",
|
|
@@ -8082,25 +8083,21 @@ window.__ModuleLoader__.load({
|
|
|
8082
8083
|
baseUrl: 'https://api.deepseek.com',
|
|
8083
8084
|
apiKey: '', // 用户自己填;本机 Ollama 不需要
|
|
8084
8085
|
model: 'deepseek-chat',
|
|
8085
|
-
|
|
8086
|
-
|
|
8087
|
-
|
|
8088
|
-
|
|
8089
|
-
|
|
8090
|
-
|
|
8091
|
-
|
|
8092
|
-
|
|
8093
|
-
|
|
8094
|
-
|
|
8095
|
-
|
|
8096
|
-
|
|
8097
|
-
//
|
|
8098
|
-
|
|
8099
|
-
|
|
8100
|
-
// ── 朗读回答(TTS):**默认开**;走系统 speechSynthesis,零依赖零 token。
|
|
8101
|
-
// enabled 与"宠物音效"完全无关(音效开关不影响朗读,反之亦然)。
|
|
8102
|
-
// voiceURI 空 = 自动挑中文音色(zh / Chinese / Huihui / Xiaoxiao …)。
|
|
8103
|
-
voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
|
|
8086
|
+
/**
|
|
8087
|
+
* v0.1 设置收敛:**只有一个对象、一套键**(工单 §5「配置单一真源」)。
|
|
8088
|
+
*
|
|
8089
|
+
* 旧键(persona / maxTurns / maxChars / voiceOut / voiceEngine / voiceEnabled)
|
|
8090
|
+
* 读入时由 readPetChat() 映射成这里的结构,写回只写新结构 —— 不再有第二套。
|
|
8091
|
+
* 上下文轮数 / 字数上限这两个"实现细节"降级为代码常量(见 DEFAULT_MAX_TURNS/CHARS),
|
|
8092
|
+
* 用户不再需要知道它们。
|
|
8093
|
+
*/
|
|
8094
|
+
petName: '', // 桌宠名字(空 ⇒ 用宠物包 displayName);同时是唤醒词
|
|
8095
|
+
ownerName: '', // 用户希望被怎么称呼
|
|
8096
|
+
// 朗读:只有一个音色 + 一个静音开关(不再有 rate/pitch/volume/voiceURI 五件套)
|
|
8097
|
+
voice: { name: 'zh-CN-XiaoxiaoNeural', muted: false },
|
|
8098
|
+
// 唤醒:点一下默认开;叫名字默认关(S6 才实现,先在设置里留位)
|
|
8099
|
+
wake: { click: true, name: false, keyword: '' },
|
|
8100
|
+
// 对话记忆默认开启且**不暴露开关**(追加决定 1):能力常开,用户只能在右键里查看/清空
|
|
8104
8101
|
},
|
|
8105
8102
|
};
|
|
8106
8103
|
|
|
@@ -8836,28 +8833,25 @@ window.__ModuleLoader__.load({
|
|
|
8836
8833
|
* `apiKey` 原样保留(只在本机 profile 里),但**限长**,避免设置文件被灌爆。
|
|
8837
8834
|
*/
|
|
8838
8835
|
/**
|
|
8839
|
-
*
|
|
8836
|
+
* 朗读音色(v0.1 收敛:只剩 name + muted)。
|
|
8840
8837
|
*
|
|
8841
|
-
* `
|
|
8842
|
-
*
|
|
8843
|
-
*
|
|
8838
|
+
* 迁移:老档里的 `voiceOut.voiceURI` / `voiceOut.enabled` / `voiceEngine` 在这里被吸收 ——
|
|
8839
|
+
* `voiceURI` 非空就当作用户选过的音色;`enabled:false` 等价于 `muted:true`。
|
|
8840
|
+
* 这样升级不会丢用户已经选过的音色,也不会把静音的人突然打开。
|
|
8844
8841
|
*/
|
|
8845
|
-
function
|
|
8846
|
-
const def = DEFAULTS.petChat.
|
|
8842
|
+
function readVoice(raw, legacy) {
|
|
8843
|
+
const def = DEFAULTS.petChat.voice;
|
|
8847
8844
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8848
|
-
|
|
8849
|
-
|
|
8850
|
-
|
|
8851
|
-
|
|
8852
|
-
volume: petChatFloat(src.volume, 0, 1, def.volume),
|
|
8853
|
-
voiceURI: petChatStr(src.voiceURI, 200).trim(),
|
|
8854
|
-
};
|
|
8845
|
+
const old = legacy && typeof legacy === 'object' && !Array.isArray(legacy) ? legacy : {};
|
|
8846
|
+
const name = petChatStr(src.name, 120).trim() || petChatStr(old.voiceURI, 200).trim() || def.name;
|
|
8847
|
+
const muted = typeof src.muted === 'boolean' ? src.muted : old.enabled === false;
|
|
8848
|
+
return { name, muted };
|
|
8855
8849
|
}
|
|
8856
|
-
|
|
8857
8850
|
function readPetChat(raw) {
|
|
8858
8851
|
const def = DEFAULTS.petChat;
|
|
8859
8852
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8860
8853
|
const persona = src.persona && typeof src.persona === 'object' && !Array.isArray(src.persona) ? src.persona : {};
|
|
8854
|
+
const wake = src.wake && typeof src.wake === 'object' && !Array.isArray(src.wake) ? src.wake : {};
|
|
8861
8855
|
const baseUrl = petChatStr(src.baseUrl, PET_CHAT_BASE_URL_MAX).trim();
|
|
8862
8856
|
return {
|
|
8863
8857
|
enabled: src.enabled === true,
|
|
@@ -8865,23 +8859,18 @@ window.__ModuleLoader__.load({
|
|
|
8865
8859
|
baseUrl: baseUrl === '' || /^https?:\/\//i.test(baseUrl) ? baseUrl : '',
|
|
8866
8860
|
apiKey: petChatStr(src.apiKey, PET_CHAT_API_KEY_MAX),
|
|
8867
8861
|
model: petChatStr(src.model, PET_CHAT_MODEL_MAX).trim(),
|
|
8868
|
-
persona
|
|
8869
|
-
|
|
8870
|
-
|
|
8871
|
-
|
|
8862
|
+
// 名字:新键优先;老档的 persona.name 迁移过来(不丢用户起过的名字)
|
|
8863
|
+
petName: petChatStr(src.petName, PET_CHAT_PERSONA_MAX).trim()
|
|
8864
|
+
|| petChatStr(persona.name, PET_CHAT_PERSONA_MAX).trim(),
|
|
8865
|
+
ownerName: petChatStr(src.ownerName, PET_CHAT_PERSONA_MAX).trim(),
|
|
8866
|
+
voice: readVoice(src.voice, src.voiceOut),
|
|
8867
|
+
wake: {
|
|
8868
|
+
click: wake.click !== false,
|
|
8869
|
+
name: wake.name === true,
|
|
8870
|
+
keyword: petChatStr(wake.keyword, 40).trim(),
|
|
8872
8871
|
},
|
|
8873
|
-
|
|
8874
|
-
|
|
8875
|
-
// B/C 的开关也在同一包里消毒:默认值来自 DEFAULTS,非法值回落默认。
|
|
8876
|
-
memoryEnabled: src.memoryEnabled !== false,
|
|
8877
|
-
memoryEveryTurns: petChatInt(src.memoryEveryTurns, 1, 50, def.memoryEveryTurns),
|
|
8878
|
-
proactiveEnabled: src.proactiveEnabled === true,
|
|
8879
|
-
proactiveDailyLimit: petChatInt(src.proactiveDailyLimit, 1, 20, def.proactiveDailyLimit),
|
|
8880
|
-
proactiveMinGapMin: petChatInt(src.proactiveMinGapMin, 30, 720, def.proactiveMinGapMin),
|
|
8881
|
-
quietHours: (typeof src.quietHours === 'string' && /^\d{2}:\d{2}-\d{2}:\d{2}$/.test(src.quietHours))
|
|
8882
|
-
? src.quietHours : def.quietHours,
|
|
8883
|
-
voiceEnabled: src.voiceEnabled === true,
|
|
8884
|
-
voiceOut: readVoiceOut(src.voiceOut),
|
|
8872
|
+
// 记忆常开:设置里没有这个开关(追加决定 1),旧档里的 false 也不再尊重
|
|
8873
|
+
memoryEnabled: true,
|
|
8885
8874
|
};
|
|
8886
8875
|
}
|
|
8887
8876
|
|
|
@@ -9192,6 +9181,10 @@ window.__ModuleLoader__.load({
|
|
|
9192
9181
|
],
|
|
9193
9182
|
// 适配器 + 媒体集成(`adapterTarget` 是跨簇共用键,归这里)
|
|
9194
9183
|
media: ['audioSource', 'adapterTarget', 'mediaIntegration', 'mediaLyricsOnline'],
|
|
9184
|
+
// 桌宠对话(整包一个键)。**必须登记进这个对象**(`SETTINGS_NAMESPACE_NAMES` 就是它的键):
|
|
9185
|
+
// 客户端差量保存走 `PUT /settings/<ns>`,ns 不在名单里 ⇒ 宿主回 404
|
|
9186
|
+
// `unknown settings namespace` ⇒ 表现为"点保存一直失败"。
|
|
9187
|
+
petChat: ['petChat'],
|
|
9195
9188
|
};
|
|
9196
9189
|
|
|
9197
9190
|
/** 组件簇名(**只有这 7 个有路由**:`meta` 不在这张表里 ⇒ `/settings/meta` 是未知 ns ⇒ 404)。 */
|
|
@@ -18629,9 +18622,128 @@ window.__ModuleLoader__.load({
|
|
|
18629
18622
|
weT("站点上还没有桌宠。")));
|
|
18630
18623
|
}
|
|
18631
18624
|
|
|
18625
|
+
// ── 桌宠对话(/folia/pet-chat/*)────────────────────────────────────────
|
|
18626
|
+
// 放在页签底部,紧跟「显示桌宠 / 声音 / 音量 / 复位位置 / 大小」之后。
|
|
18627
|
+
children.push(React.createElement(PetChatSettings, { key: "petChat" }));
|
|
18628
|
+
|
|
18632
18629
|
return React.createElement("div", { className: "we-picker__section" }, children);
|
|
18633
18630
|
}
|
|
18634
18631
|
|
|
18632
|
+
/* ── 桌宠对话设置区 ─────────────────────────────────────────────────────── */
|
|
18633
|
+
|
|
18634
|
+
const CHAT_DEFAULTS = {
|
|
18635
|
+
provider: 'openai',
|
|
18636
|
+
baseUrl: 'https://api.deepseek.com',
|
|
18637
|
+
model: 'deepseek-chat',
|
|
18638
|
+
apiKey: '',
|
|
18639
|
+
apiKeyMasked: '',
|
|
18640
|
+
hasApiKey: false,
|
|
18641
|
+
petName: '',
|
|
18642
|
+
ownerName: '',
|
|
18643
|
+
};
|
|
18644
|
+
|
|
18645
|
+
/**
|
|
18646
|
+
* 设置页(v0.1 验收口径):**三项,无开关**。
|
|
18647
|
+
* 1) 模型 Key 2) 名字(桌宠名 = 唤醒词 + 你的称呼) 3) 音色(v0.2 占位,灰色只读)
|
|
18648
|
+
*
|
|
18649
|
+
* 为什么连"开启对话"都没有:工单要求用户不做选择 —— 填了 Key 就等于启用,
|
|
18650
|
+
* 主动搭话/记忆都是固定策略。删除任何开关,就少一次"用户要不要打开"的决策。
|
|
18651
|
+
*/
|
|
18652
|
+
/** apiJson 的返回是 { ok, status, data },而 /pet-chat/* 的 data 里还套一层 { ok, data }。
|
|
18653
|
+
* 各调用点各写一遍「多解一层」就是 P1 那个"保存成功却显示保存失败"的来源 —— 统一到这里解。 */
|
|
18654
|
+
const unwrapPetChat = (resp) => (resp && resp.data && resp.data.data) || (resp && resp.data) || {};
|
|
18655
|
+
|
|
18656
|
+
function PetChatSettings() {
|
|
18657
|
+
const [draft, setDraft] = React.useState(CHAT_DEFAULTS);
|
|
18658
|
+
const [status, setStatus] = React.useState({ ok: null, text: '' });
|
|
18659
|
+
const [note, setNote] = React.useState(null);
|
|
18660
|
+
const [busy, setBusy] = React.useState(false);
|
|
18661
|
+
const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
|
|
18662
|
+
|
|
18663
|
+
const load = React.useCallback(async () => {
|
|
18664
|
+
try {
|
|
18665
|
+
const resp = await apiJson('/pet-chat/config', { parse: 'always' });
|
|
18666
|
+
const doc = unwrapPetChat(resp);
|
|
18667
|
+
if (doc && doc.ok !== false) {
|
|
18668
|
+
setDraft({ ...CHAT_DEFAULTS, ...doc, apiKey: '' });
|
|
18669
|
+
setStatus(doc.hasApiKey
|
|
18670
|
+
? { ok: true, text: weT('已保存的 Key:{mask}', { mask: doc.apiKeyMasked || '••••' }) }
|
|
18671
|
+
: { ok: null, text: weT('还没有填 API Key') });
|
|
18672
|
+
}
|
|
18673
|
+
} catch { /* 首次加载失败不打扰 */ }
|
|
18674
|
+
}, []);
|
|
18675
|
+
React.useEffect(() => { void load(); }, [load]);
|
|
18676
|
+
|
|
18677
|
+
const save = async () => {
|
|
18678
|
+
setBusy(true);
|
|
18679
|
+
try {
|
|
18680
|
+
// 填了 Key 就启用:面板不放任何开关,语义由 Key 的有无决定
|
|
18681
|
+
const body = { ...draft, apiKey: draft.apiKey || '', enabled: Boolean(draft.apiKey) || Boolean(draft.hasApiKey) };
|
|
18682
|
+
// ⚠️ 必须用 apiPostJson:apiJson 只拼 URL,不做 JSON.stringify,
|
|
18683
|
+
// 传对象会被浏览器发成 "[object Object]" ⇒ 宿主回 400 bad-json ⇒ 界面永远"保存失败"。
|
|
18684
|
+
const resp = await apiPostJson('/pet-chat/config', body, { parse: 'always' });
|
|
18685
|
+
const doc = unwrapPetChat(resp);
|
|
18686
|
+
if (doc.saved) {
|
|
18687
|
+
setNote({ ok: true, text: weT('已保存') });
|
|
18688
|
+
await load();
|
|
18689
|
+
const state = await apiJson('/pet-chat/state', { parse: 'always' });
|
|
18690
|
+
const sdoc = unwrapPetChat(state);
|
|
18691
|
+
setStatus(sdoc.reachable
|
|
18692
|
+
? { ok: true, text: weT('已连接 · {m}', { m: sdoc.model || draft.model }) }
|
|
18693
|
+
: { ok: false, text: sdoc.lastError ? weT('未连接:{e}', { e: sdoc.lastError }) : weT('已保存,但还没连上') });
|
|
18694
|
+
} else setNote({ ok: false, text: weT('保存失败') });
|
|
18695
|
+
} catch (e) {
|
|
18696
|
+
setNote({ ok: false, text: weT('保存失败:{msg}', { msg: (e && e.message) || '' }) });
|
|
18697
|
+
} finally { setBusy(false); }
|
|
18698
|
+
};
|
|
18699
|
+
|
|
18700
|
+
const row = (key, label, node) => React.createElement('label', {
|
|
18701
|
+
key, style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' },
|
|
18702
|
+
}, weT(label), node);
|
|
18703
|
+
|
|
18704
|
+
const child = [];
|
|
18705
|
+
child.push(React.createElement('div', { key: 'title', style: { fontWeight: 600, margin: '14px 0 4px', fontSize: '13px' } }, weT('桌宠语音助手')));
|
|
18706
|
+
child.push(React.createElement('div', { key: 'hint', className: 'we-picker__hint', style: { margin: '0 0 6px' } },
|
|
18707
|
+
weT('三项就够:填 Key、起名字、选音色。主动搭话与记忆是固定策略;停止/恢复对它说一声就行。')));
|
|
18708
|
+
|
|
18709
|
+
child.push(React.createElement('div', { key: 'key', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
|
|
18710
|
+
weT('模型 Key'),
|
|
18711
|
+
React.createElement('input', {
|
|
18712
|
+
type: 'password', value: draft.apiKey || '',
|
|
18713
|
+
placeholder: draft.hasApiKey ? (draft.apiKeyMasked || '••••••••') : weT('填 DeepSeek API Key'),
|
|
18714
|
+
disabled: busy, style: { flex: 1, minWidth: 0 },
|
|
18715
|
+
onChange: (e) => update({ apiKey: e.target.value }),
|
|
18716
|
+
}),
|
|
18717
|
+
));
|
|
18718
|
+
|
|
18719
|
+
child.push(row('name', '名字', React.createElement('input', {
|
|
18720
|
+
type: 'text', value: draft.petName || '', placeholder: weT('桌宠叫什么(也是唤醒词)'), disabled: busy,
|
|
18721
|
+
style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ petName: e.target.value }),
|
|
18722
|
+
})));
|
|
18723
|
+
child.push(row('owner', '称呼', React.createElement('input', {
|
|
18724
|
+
type: 'text', value: draft.ownerName || '', placeholder: weT('它该怎么称呼你'), disabled: busy,
|
|
18725
|
+
style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ ownerName: e.target.value }),
|
|
18726
|
+
})));
|
|
18727
|
+
|
|
18728
|
+
// 音色:v0.2 占位(灰色、不可改),避免用户以为现在能选
|
|
18729
|
+
child.push(row('voice', '音色', React.createElement('select', {
|
|
18730
|
+
className: 'we-picker__playlist-select', disabled: true, value: 'zh-CN-XiaoxiaoNeural',
|
|
18731
|
+
},
|
|
18732
|
+
React.createElement('option', { value: 'zh-CN-XiaoxiaoNeural' }, weT('晓晓(v0.2 可选)')),
|
|
18733
|
+
)));
|
|
18734
|
+
|
|
18735
|
+
child.push(React.createElement('div', { key: 'status', className: 'we-picker__hint', style: { margin: '6px 0', color: status.ok === false ? '#f87171' : undefined } },
|
|
18736
|
+
status.text || weT('未连接')));
|
|
18737
|
+
if (note && note.text) {
|
|
18738
|
+
child.push(React.createElement('div', { key: 'note', className: 'we-picker__hint', style: { color: note.ok ? undefined : '#f87171' } }, note.text));
|
|
18739
|
+
}
|
|
18740
|
+
child.push(React.createElement('div', { key: 'save', style: { display: 'flex', gap: '6px', marginTop: '4px' } },
|
|
18741
|
+
React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: save }, weT('保存')),
|
|
18742
|
+
));
|
|
18743
|
+
|
|
18744
|
+
return React.createElement('div', { style: { ...PET_STYLE.card, marginTop: '10px' } }, child);
|
|
18745
|
+
}
|
|
18746
|
+
|
|
18635
18747
|
/** 页签组装点调用它。 */
|
|
18636
18748
|
function renderPetsTab() {
|
|
18637
18749
|
return React.createElement(PetsTabPanel, null);
|
|
@@ -19098,6 +19210,11 @@ window.__ModuleLoader__.load({
|
|
|
19098
19210
|
const hr = document.createElement("div");
|
|
19099
19211
|
hr.style.cssText = "height:1px;margin:6px 0;background:rgba(255,255,255,0.14)";
|
|
19100
19212
|
menu.appendChild(hr);
|
|
19213
|
+
// 「对话」:打开桌宠对话的输入条(由 pet-chat 特性监听该事件;没装该特性时点了无副作用)
|
|
19214
|
+
menu.appendChild(buildMenuItem(weT("对话"), () => {
|
|
19215
|
+
try { window.dispatchEvent(new CustomEvent("we-pet-talk")); } catch { /* ignore */ }
|
|
19216
|
+
closeMenu();
|
|
19217
|
+
}));
|
|
19101
19218
|
menu.appendChild(buildMenuItem(weT("再大一点"), () => { applyScale(scale + 0.2); closeMenu(); }));
|
|
19102
19219
|
menu.appendChild(buildMenuItem(weT("再小一点"), () => { applyScale(Math.max(0.5, scale - 0.2)); closeMenu(); }));
|
|
19103
19220
|
menu.appendChild(buildMenuItem(weT("回右下角"), () => {
|
|
@@ -20283,797 +20400,539 @@ window.__ModuleLoader__.load({
|
|
|
20283
20400
|
} catch { return () => {}; }
|
|
20284
20401
|
}
|
|
20285
20402
|
|
|
20286
|
-
// ── 内联模块:src/pet-
|
|
20403
|
+
// ── 内联模块:src/pet-voice-input.js —— 语音输入(宿主录音版):POST /pet-chat/record → text → /chat SSE 回填,前端不碰媒体 API(构建期注入;勿手改本段)──
|
|
20287
20404
|
/**
|
|
20288
|
-
* pet-
|
|
20405
|
+
* pet-voice-input.js — 桌宠语音输入(v0.1,宿主侧录音版)。
|
|
20289
20406
|
*
|
|
20290
|
-
*
|
|
20291
|
-
*
|
|
20292
|
-
*
|
|
20293
|
-
* ② **零依赖零 token**:走系统语音(Electron 下是 Windows SAPI);没有就说没有。
|
|
20294
|
-
* ③ 与宠物"音效"开关**无关**:这里只看 `petChat.voiceOut.enabled`。
|
|
20407
|
+
* 为什么不在前端录:DSH 的 Electron 只放行 clipboard/notifications 权限,
|
|
20408
|
+
* 音频采集在 Electron 里被权限层拒绝且没有弹窗(工单「追加决定 3」)。所以这里**不碰任何
|
|
20409
|
+
* media API**:点一下 → 让宿主录(ffmpeg dshow)→ 拿 text → 走 SSE 逐字回气泡。
|
|
20295
20410
|
*
|
|
20296
|
-
*
|
|
20297
|
-
* · 整段到达(非流式 / 预设台词)⇒ `finish(text)` 整段读一次;
|
|
20298
|
-
* · 流式增量 ⇒ `push(chunk)`,凑满句末标点就按句读(不打断打字机)。
|
|
20299
|
-
*
|
|
20300
|
-
* 为什么要做成工厂并把 speechSynthesis / Utterance 注入进来:
|
|
20301
|
-
* 判据要能 mock(`test/verify-pet-chat.mjs` 的 6 条),而渲染进程的真实实现
|
|
20302
|
-
* 就是 `window.speechSynthesis` + `window.SpeechSynthesisUtterance`。
|
|
20411
|
+
* 判据(test/verify-pet-voice.mjs)用假 postRecord/postChat 覆盖全链路与失败码。
|
|
20303
20412
|
*/
|
|
20413
|
+
function petVoiceInputCreate(deps) {
|
|
20414
|
+
const options = deps || {};
|
|
20415
|
+
const postRecord = options.postRecord;
|
|
20416
|
+
const postChat = options.postChat;
|
|
20417
|
+
const onText = typeof options.onText === 'function' ? options.onText : () => {};
|
|
20418
|
+
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
20419
|
+
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
20304
20420
|
|
|
20305
|
-
|
|
20306
|
-
const PET_CHAT_TTS_SENTENCE_END = /[。!?!?;;…]+/;
|
|
20421
|
+
let active = false;
|
|
20307
20422
|
|
|
20308
|
-
|
|
20309
|
-
|
|
20310
|
-
|
|
20311
|
-
|
|
20312
|
-
function petChatTtsSplit(text) {
|
|
20313
|
-
const raw = String(text ?? '');
|
|
20314
|
-
if (!raw.trim()) return [];
|
|
20315
|
-
const out = [];
|
|
20316
|
-
let buffer = '';
|
|
20317
|
-
for (const char of raw) {
|
|
20318
|
-
buffer += char;
|
|
20319
|
-
if (PET_CHAT_TTS_SENTENCE_END.test(char)) {
|
|
20320
|
-
if (buffer.trim()) out.push(buffer.trim());
|
|
20321
|
-
buffer = '';
|
|
20322
|
-
}
|
|
20423
|
+
async function finishWithText(text) {
|
|
20424
|
+
if (!text) return;
|
|
20425
|
+
onText(text);
|
|
20426
|
+
if (typeof postChat === 'function') await postChat(text, onState);
|
|
20323
20427
|
}
|
|
20324
|
-
|
|
20325
|
-
|
|
20326
|
-
|
|
20327
|
-
|
|
20328
|
-
|
|
20329
|
-
let
|
|
20330
|
-
|
|
20331
|
-
|
|
20332
|
-
|
|
20428
|
+
|
|
20429
|
+
async function start() {
|
|
20430
|
+
if (active) return true;
|
|
20431
|
+
active = true;
|
|
20432
|
+
onState({ state: 'listening' });
|
|
20433
|
+
let result;
|
|
20434
|
+
try {
|
|
20435
|
+
result = await postRecord({});
|
|
20436
|
+
} catch (error) {
|
|
20437
|
+
active = false;
|
|
20438
|
+
onError({ code: (error && error.code) || 'network', message: String((error && error.message) || error) });
|
|
20439
|
+
return false;
|
|
20440
|
+
}
|
|
20441
|
+
const doc = result || {};
|
|
20442
|
+
if (doc.ok !== true) {
|
|
20443
|
+
active = false;
|
|
20444
|
+
onError({ code: doc.code || 'record-failed', message: doc.hint || '' });
|
|
20445
|
+
return false;
|
|
20446
|
+
}
|
|
20447
|
+
onState({ state: 'transcribing', text: doc.text });
|
|
20448
|
+
try {
|
|
20449
|
+
await finishWithText(String(doc.text || ''));
|
|
20450
|
+
} catch (error) {
|
|
20451
|
+
onError({ code: 'network', message: String((error && error.message) || error) });
|
|
20452
|
+
return false;
|
|
20453
|
+
} finally {
|
|
20454
|
+
active = false;
|
|
20455
|
+
onState({ state: 'idle' });
|
|
20333
20456
|
}
|
|
20334
|
-
|
|
20457
|
+
return true;
|
|
20335
20458
|
}
|
|
20336
|
-
return final;
|
|
20337
|
-
}
|
|
20338
20459
|
|
|
20339
|
-
|
|
20340
|
-
|
|
20341
|
-
|
|
20342
|
-
const lang = String(voice.lang || '').toLowerCase();
|
|
20343
|
-
const name = String(voice.name || '');
|
|
20344
|
-
return lang.startsWith('zh') || /chinese|huihui|xiaoxiao|kangkang|yaoyao|tingting|hanhan/i.test(name);
|
|
20460
|
+
function stop() { active = false; onState({ state: 'idle' }); }
|
|
20461
|
+
|
|
20462
|
+
return { start, stop, isActive: () => active };
|
|
20345
20463
|
}
|
|
20346
20464
|
|
|
20465
|
+
// ── 内联模块:src/pet-bubble.js —— 头顶气泡:锚定桌宠头顶、跟随位置/缩放、逐字显示、最多 6 行、朗读结束 +3s 淡出(构建期注入;勿手改本段)──
|
|
20347
20466
|
/**
|
|
20348
|
-
*
|
|
20467
|
+
* pet-bubble.js — 头顶气泡(v0.1 S2)。
|
|
20468
|
+
*
|
|
20469
|
+
* 与旧面板的区别:**只显示**,不承载输入框 / 历史列表 / 关闭按钮;输入走右键「打字说…」,
|
|
20470
|
+
* 语音走唤醒链路(S3)。这样做是因为旧面板把"窗口"和"助手"混在一起,
|
|
20471
|
+
* 用户点桌宠时弹出一个像聊天软件的窗口,与"桌宠在旁边说话"的产品形态冲突。
|
|
20349
20472
|
*
|
|
20350
|
-
*
|
|
20351
|
-
*
|
|
20352
|
-
* @param {() => any[]} deps.getVoices 返回音色列表(可能为空)
|
|
20353
|
-
* @param {() => object} deps.getConfig 返回 `{ enabled, rate, pitch, volume, voiceURI }`
|
|
20354
|
-
* @param {Function} [deps.Utterance] `SpeechSynthesisUtterance` 构造器
|
|
20355
|
-
* @param {(code:string, message:string) => void} [deps.onHint] 一次性提示回调
|
|
20473
|
+
* 依赖全部注入(document / 定时器 / 锚点),这样 Node 里能用假 DOM 跑判据;
|
|
20474
|
+
* 浏览器侧由 pet-chat.js 用真实 window 构造。
|
|
20356
20475
|
*/
|
|
20357
|
-
function
|
|
20476
|
+
function petBubbleCreate(deps) {
|
|
20358
20477
|
const options = deps || {};
|
|
20359
|
-
const
|
|
20360
|
-
|
|
20361
|
-
|
|
20362
|
-
const
|
|
20363
|
-
|
|
20364
|
-
|
|
20365
|
-
|
|
20366
|
-
|
|
20367
|
-
|
|
20368
|
-
|
|
20369
|
-
|
|
20370
|
-
|
|
20371
|
-
|
|
20372
|
-
|
|
20373
|
-
|
|
20478
|
+
const doc = options.document;
|
|
20479
|
+
// 没有定时器的环境(极简 DOM 替身的冒烟测试)不能因为裸 setTimeout 直接炸:
|
|
20480
|
+
// 退化成立即执行 / 空取消,气泡仍能显示,只是没有延迟淡出。
|
|
20481
|
+
const setTimer = typeof options.setTimeout === 'function'
|
|
20482
|
+
? options.setTimeout
|
|
20483
|
+
: (typeof setTimeout === 'function' ? setTimeout : (fn) => { if (typeof fn === 'function') fn(); return 0; });
|
|
20484
|
+
const clearTimer = typeof options.clearTimeout === 'function'
|
|
20485
|
+
? options.clearTimeout
|
|
20486
|
+
: (typeof clearTimeout === 'function' ? clearTimeout : () => {});
|
|
20487
|
+
const getAnchor = typeof options.getAnchor === 'function' ? options.getAnchor : () => null;
|
|
20488
|
+
/** 最多显示几行(超出用 CSS 行钳制,见 lineClamp 样式)。 */
|
|
20489
|
+
const MAX_LINES = 6;
|
|
20490
|
+
|
|
20491
|
+
const raf = typeof options.requestAnimationFrame === 'function' ? options.requestAnimationFrame : null;
|
|
20492
|
+
const cancelRaf = typeof options.cancelAnimationFrame === 'function' ? options.cancelAnimationFrame : null;
|
|
20493
|
+
let rafId = null;
|
|
20494
|
+
const onClose = typeof options.onClose === 'function' ? options.onClose : () => {};
|
|
20495
|
+
|
|
20496
|
+
/** P3:打开期间每帧跟一次(拖动/缩放/窗口变化都能跟上),关闭时停。 */
|
|
20497
|
+
function startFollow() {
|
|
20498
|
+
if (!raf || rafId != null) return;
|
|
20499
|
+
const step = () => {
|
|
20500
|
+
place();
|
|
20501
|
+
rafId = raf(step);
|
|
20502
|
+
};
|
|
20503
|
+
rafId = raf(step);
|
|
20504
|
+
}
|
|
20374
20505
|
|
|
20375
|
-
|
|
20376
|
-
|
|
20377
|
-
|
|
20378
|
-
const wanted = String(config.voiceURI || '').trim();
|
|
20379
|
-
if (wanted) {
|
|
20380
|
-
const hit = list.find((voice) => voice && (voice.voiceURI === wanted || voice.name === wanted));
|
|
20381
|
-
if (hit) return hit;
|
|
20382
|
-
}
|
|
20383
|
-
const chinese = list.find((voice) => petChatTtsIsChinese(voice));
|
|
20384
|
-
if (chinese) return chinese;
|
|
20385
|
-
if (list.length) hintOnce('no-chinese-voice', '系统里没有中文音色,朗读可能不自然');
|
|
20386
|
-
return null;
|
|
20506
|
+
function stopFollow() {
|
|
20507
|
+
if (rafId != null && cancelRaf) { try { cancelRaf(rafId); } catch { /* ignore */ } }
|
|
20508
|
+
rafId = null;
|
|
20387
20509
|
}
|
|
20388
20510
|
|
|
20389
|
-
|
|
20390
|
-
|
|
20391
|
-
|
|
20392
|
-
|
|
20393
|
-
|
|
20394
|
-
|
|
20395
|
-
|
|
20396
|
-
|
|
20397
|
-
|
|
20398
|
-
|
|
20399
|
-
|
|
20400
|
-
|
|
20401
|
-
|
|
20402
|
-
|
|
20403
|
-
|
|
20404
|
-
}
|
|
20405
|
-
|
|
20511
|
+
let el = null;
|
|
20512
|
+
let text = '';
|
|
20513
|
+
let visible = false;
|
|
20514
|
+
let fadeTimer = null;
|
|
20515
|
+
|
|
20516
|
+
/** 锚点 → 气泡位置:水平居中于桌宠,垂直贴在头顶上方。 */
|
|
20517
|
+
function place() {
|
|
20518
|
+
if (!el) return;
|
|
20519
|
+
const anchor = getAnchor();
|
|
20520
|
+
if (!anchor) return;
|
|
20521
|
+
const width = Number(anchor.width) || 0;
|
|
20522
|
+
const height = Number(anchor.height) || 0;
|
|
20523
|
+
const left = Math.round(Number(anchor.left || 0) + width / 2);
|
|
20524
|
+
const top = Math.round(Number(anchor.top || 0) - 8);
|
|
20525
|
+
el.style.left = `${left}px`;
|
|
20526
|
+
el.style.top = `${top}px`;
|
|
20527
|
+
// 锚点也跟着缩放:桌宠放大时气泡不要贴在旧位置
|
|
20528
|
+
el.style.transform = `translate(-50%, -100%) scale(${Number(anchor.scale) || 1})`;
|
|
20529
|
+
}
|
|
20530
|
+
|
|
20531
|
+
function ensure() {
|
|
20532
|
+
if (el || !doc || typeof doc.createElement !== 'function') return el;
|
|
20533
|
+
el = doc.createElement('div');
|
|
20534
|
+
el.className = 'we-pet-bubble';
|
|
20535
|
+
el.style.position = 'fixed';
|
|
20536
|
+
el.style.zIndex = '9999';
|
|
20537
|
+
el.style.maxWidth = '260px';
|
|
20538
|
+
el.style.padding = '8px 10px';
|
|
20539
|
+
el.style.borderRadius = '12px';
|
|
20540
|
+
el.style.background = 'rgba(24,24,28,.92)';
|
|
20541
|
+
el.style.color = '#f2f2f5';
|
|
20542
|
+
el.style.fontSize = '12px';
|
|
20543
|
+
el.style.lineHeight = '1.5';
|
|
20544
|
+
el.style.pointerEvents = 'none';
|
|
20545
|
+
el.style.opacity = '0';
|
|
20546
|
+
el.style.transition = 'opacity .18s ease';
|
|
20547
|
+
// 超过 6 行省略:气泡永远不长大到挡住桌宠
|
|
20548
|
+
el.style.display = '-webkit-box';
|
|
20549
|
+
el.style.webkitLineClamp = String(MAX_LINES);
|
|
20550
|
+
el.style.webkitBoxOrient = 'vertical';
|
|
20551
|
+
el.style.overflow = 'hidden';
|
|
20552
|
+
el.style.whiteSpace = 'pre-wrap';
|
|
20553
|
+
if (doc && typeof doc.createElement === 'function') {
|
|
20554
|
+
const close = doc.createElement('button');
|
|
20555
|
+
close.className = 'pet-bubble-close';
|
|
20556
|
+
close.setAttribute('aria-label', '关闭');
|
|
20557
|
+
close.textContent = '×';
|
|
20558
|
+
close.style.cssText = 'position:absolute;top:-6px;right:-6px;width:18px;height:18px;border-radius:50%;border:none;background:#333;color:#ddd;font-size:12px;line-height:1;cursor:pointer;pointer-events:auto;';
|
|
20559
|
+
close.addEventListener('click', () => { hide(0); onClose(); });
|
|
20560
|
+
if (typeof el.appendChild === 'function') el.appendChild(close);
|
|
20561
|
+
}
|
|
20562
|
+
el.style.position = 'fixed';
|
|
20563
|
+
if (doc.body && typeof doc.body.appendChild === 'function') doc.body.appendChild(el);
|
|
20564
|
+
return el;
|
|
20406
20565
|
}
|
|
20407
20566
|
|
|
20408
|
-
|
|
20409
|
-
|
|
20410
|
-
pending = '';
|
|
20411
|
-
spokenInTurn = 0;
|
|
20412
|
-
cancel();
|
|
20567
|
+
function cancelFade() {
|
|
20568
|
+
if (fadeTimer != null) { clearTimer(fadeTimer); fadeTimer = null; }
|
|
20413
20569
|
}
|
|
20414
20570
|
|
|
20415
|
-
/**
|
|
20416
|
-
function
|
|
20417
|
-
|
|
20418
|
-
|
|
20571
|
+
/** 显示(或继续显示)一段文本;重复调用会重排文本而不是叠出第二个气泡。 */
|
|
20572
|
+
function show(nextText) {
|
|
20573
|
+
if (!ensure()) return;
|
|
20574
|
+
cancelFade();
|
|
20575
|
+
text = String(nextText == null ? '' : nextText);
|
|
20576
|
+
el.textContent = text;
|
|
20577
|
+
el.style.opacity = '1';
|
|
20578
|
+
visible = true;
|
|
20579
|
+
place();
|
|
20580
|
+
startFollow();
|
|
20419
20581
|
}
|
|
20420
20582
|
|
|
20421
|
-
/**
|
|
20422
|
-
function
|
|
20423
|
-
|
|
20424
|
-
|
|
20425
|
-
|
|
20426
|
-
|
|
20427
|
-
|
|
20428
|
-
|
|
20429
|
-
|
|
20430
|
-
const sentences = petChatTtsSplit(pending);
|
|
20431
|
-
// 只有"以标点结尾"的才算成句;最后一段若不以标点结尾,留到下次
|
|
20432
|
-
const endsWithPunct = PET_CHAT_TTS_SENTENCE_END.test(pending.slice(-1));
|
|
20433
|
-
const ready = endsWithPunct ? sentences : sentences.slice(0, -1);
|
|
20434
|
-
if (!ready.length) return;
|
|
20435
|
-
if (endsWithPunct) pending = '';
|
|
20436
|
-
else pending = sentences[sentences.length - 1] || '';
|
|
20437
|
-
const voices = getVoices();
|
|
20438
|
-
for (const sentence of ready) if (speakOne(sentence, speech, config, voices)) spokenInTurn += 1;
|
|
20583
|
+
/** 逐字/逐段追加(SSE 每个 chunk 调一次)。 */
|
|
20584
|
+
function append(chunk) {
|
|
20585
|
+
if (!ensure()) return;
|
|
20586
|
+
cancelFade();
|
|
20587
|
+
text += String(chunk == null ? '' : chunk);
|
|
20588
|
+
el.textContent = text;
|
|
20589
|
+
el.style.opacity = '1';
|
|
20590
|
+
visible = true;
|
|
20591
|
+
startFollow();
|
|
20439
20592
|
}
|
|
20440
20593
|
|
|
20441
|
-
/**
|
|
20442
|
-
|
|
20443
|
-
|
|
20444
|
-
|
|
20445
|
-
|
|
20446
|
-
const
|
|
20447
|
-
|
|
20448
|
-
|
|
20449
|
-
|
|
20450
|
-
|
|
20451
|
-
|
|
20452
|
-
|
|
20453
|
-
|
|
20454
|
-
|
|
20455
|
-
|
|
20456
|
-
|
|
20457
|
-
|
|
20458
|
-
|
|
20459
|
-
|
|
20594
|
+
/** 隐藏;带 delay 时先挂着,到点淡出(朗读结束后 +3s 用这个)。 */
|
|
20595
|
+
function hide(delayMs) {
|
|
20596
|
+
if (!el) return;
|
|
20597
|
+
cancelFade();
|
|
20598
|
+
const delay = Number(delayMs) || 0;
|
|
20599
|
+
const doHide = () => {
|
|
20600
|
+
fadeTimer = null;
|
|
20601
|
+
stopFollow();
|
|
20602
|
+
el.style.opacity = '0';
|
|
20603
|
+
visible = false;
|
|
20604
|
+
};
|
|
20605
|
+
if (delay > 0) { fadeTimer = setTimer(doHide, delay); return; }
|
|
20606
|
+
doHide();
|
|
20607
|
+
}
|
|
20608
|
+
|
|
20609
|
+
/** 状态:听 / 想 / 答(客户端据此换桌宠动作、给气泡配色)。 */
|
|
20610
|
+
function setState(kind) {
|
|
20611
|
+
if (!el) return;
|
|
20612
|
+
el.dataset = el.dataset || {};
|
|
20613
|
+
el.dataset.state = String(kind || '');
|
|
20614
|
+
}
|
|
20615
|
+
|
|
20616
|
+
function isVisible() { return visible; }
|
|
20617
|
+
|
|
20618
|
+
function dispose() {
|
|
20619
|
+
cancelFade();
|
|
20620
|
+
stopFollow();
|
|
20621
|
+
if (el && typeof el.remove === 'function') el.remove();
|
|
20622
|
+
el = null;
|
|
20623
|
+
text = '';
|
|
20624
|
+
visible = false;
|
|
20460
20625
|
}
|
|
20461
20626
|
|
|
20462
|
-
return {
|
|
20627
|
+
return {
|
|
20628
|
+
show, append, hide, setState, place, isVisible, dispose,
|
|
20629
|
+
get following() { return rafId != null; },
|
|
20630
|
+
// 判据要读的内部状态
|
|
20631
|
+
get text() { return text; },
|
|
20632
|
+
get element() { return el; },
|
|
20633
|
+
MAX_LINES,
|
|
20634
|
+
};
|
|
20463
20635
|
}
|
|
20464
20636
|
|
|
20465
|
-
// ── 内联模块:src/pet-chat.js ——
|
|
20637
|
+
// ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
|
|
20466
20638
|
/**
|
|
20467
|
-
* pet-chat.js
|
|
20639
|
+
* pet-chat.js — 桌宠语音助手(v0.1 客户端)。
|
|
20468
20640
|
*
|
|
20469
|
-
*
|
|
20470
|
-
*
|
|
20471
|
-
* · 回复走 SSE(delta 逐字追加),done 里带 emotion → 映射成宠物动作
|
|
20472
|
-
* · 设置里没开(enabled=false)⇒ 不谈模型,直接给**预设台词库**(30+ 句,按情绪分组)
|
|
20641
|
+
* v0.1 范围(docs/PET-V01-ACCEPTANCE.md):**语音输入 + 头顶文字气泡 + 名字/记忆 + 主动搭话**,
|
|
20642
|
+
* **不含任何朗读/TTS**(v0.2 再做)。所以这里没有 speechSynthesis、没有 /pet-chat/speak 调用。
|
|
20473
20643
|
*
|
|
20474
|
-
*
|
|
20475
|
-
*
|
|
20476
|
-
*
|
|
20477
|
-
* 不变量:
|
|
20478
|
-
* · **不碰模型的 key**:key 只在宿主设置里,客户端连读都不读。
|
|
20479
|
-
* · **不自己拼模型端点**:所有请求都打本机 `/folia/pet-chat/*`。
|
|
20480
|
-
* · 气泡是 `position: fixed` 的独立层,不参与面板重渲染(与 pet-layer 同一套思路)。
|
|
20481
|
-
*/
|
|
20482
|
-
/**
|
|
20483
|
-
* 预设台词库(工单 A4):**五组 ≥30 句**。
|
|
20484
|
-
* `enabled=false`(没配模型)与宿主回 `no-model` 两条路径都从这里取,按组轮换。
|
|
20644
|
+
* 交互:点桌宠 = 唤醒 → 气泡显示它的话(3 秒后淡出,点一下立刻收起)。
|
|
20645
|
+
* 没有聊天窗口:无输入框、无历史列表、无开关按钮。
|
|
20485
20646
|
*/
|
|
20486
20647
|
const PET_CHAT_PRESET_LINES = {
|
|
20487
|
-
|
|
20488
|
-
|
|
20489
|
-
|
|
20648
|
+
greeting: [
|
|
20649
|
+
'我在呢。',
|
|
20650
|
+
'叫我就来。',
|
|
20651
|
+
'嗯?我在听。',
|
|
20652
|
+
'你回来啦。',
|
|
20653
|
+
'有我在,别急。',
|
|
20654
|
+
'今天想聊点什么?',
|
|
20655
|
+
],
|
|
20490
20656
|
wallpaper: [
|
|
20491
|
-
'
|
|
20492
|
-
'
|
|
20493
|
-
'
|
|
20657
|
+
'要不要换张壁纸?',
|
|
20658
|
+
'这张看久了,换一张吧。',
|
|
20659
|
+
'桌面有点暗,换个亮一点的?',
|
|
20660
|
+
'轮播开着,让它自己换吧。',
|
|
20661
|
+
'我给你挑一张安静的。',
|
|
20662
|
+
'这张当壁纸挺合适。',
|
|
20663
|
+
'换张清爽的,眼睛舒服点。',
|
|
20664
|
+
'需要我记住你喜欢的风格吗?',
|
|
20494
20665
|
],
|
|
20495
|
-
// 陪伴与鼓励(8)
|
|
20496
20666
|
company: [
|
|
20497
|
-
'
|
|
20498
|
-
'
|
|
20499
|
-
'
|
|
20667
|
+
'我在这儿待着。',
|
|
20668
|
+
'忙你的,我不吵。',
|
|
20669
|
+
'要喝水吗?我提醒你。',
|
|
20670
|
+
'坐久了,起来动一动。',
|
|
20671
|
+
'累了就歇会儿。',
|
|
20672
|
+
'今天也辛苦了。',
|
|
20673
|
+
'我陪着你。',
|
|
20674
|
+
'慢慢来,不急。',
|
|
20500
20675
|
],
|
|
20501
|
-
// 空状态与失败兜底(5)
|
|
20502
20676
|
fallback: [
|
|
20503
|
-
'
|
|
20504
|
-
'
|
|
20677
|
+
'这个我还不会,等我学学。',
|
|
20678
|
+
'没听清,再说一次?',
|
|
20679
|
+
'换个说法试试?',
|
|
20680
|
+
'我先记下来。',
|
|
20681
|
+
'这个得你来定。',
|
|
20682
|
+
],
|
|
20683
|
+
night: [
|
|
20684
|
+
'夜深了,早点睡。',
|
|
20685
|
+
'我先安静一会儿。',
|
|
20686
|
+
'明天见。',
|
|
20505
20687
|
],
|
|
20506
|
-
// 夜间(3)
|
|
20507
|
-
night: ['夜深了,早点休息。', '要不要换张暗一点的壁纸?', '我先趴一会儿,晚安。'],
|
|
20508
20688
|
};
|
|
20509
20689
|
|
|
20510
|
-
/**
|
|
20511
|
-
const PET_CHAT_EMOTION_TRACK = { happy: 'wave', tired: 'sleep', angry: 'idle', calm: 'idle' };
|
|
20512
|
-
/** 气泡里保留的最近条数(工单:最近 6 条)。 */
|
|
20513
|
-
const PET_CHAT_KEEP_LINES = 6;
|
|
20514
|
-
|
|
20515
|
-
|
|
20516
|
-
/** 极简 DOM 替身可能没有 append / addEventListener:统一走这两个助手,坏环境里安静跳过。 */
|
|
20517
|
-
function petChatAppend(el, ...kids) {
|
|
20518
|
-
if (!el) return;
|
|
20519
|
-
if (typeof el.append === 'function') { el.append(...kids); return; }
|
|
20520
|
-
if (typeof el.appendChild === 'function') { for (const kid of kids) el.appendChild(kid); }
|
|
20521
|
-
}
|
|
20522
|
-
function petChatOn(el, type, fn) {
|
|
20523
|
-
if (el && typeof el.addEventListener === 'function') el.addEventListener(type, fn);
|
|
20524
|
-
}
|
|
20525
|
-
|
|
20526
|
-
let petChatEls = null;
|
|
20527
|
-
let petChatLines = [];
|
|
20528
|
-
let petChatBusy = false;
|
|
20529
|
-
|
|
20530
|
-
/** 气泡 DOM(懒建:不点宠物就不建,免得影响启动)。 */
|
|
20531
|
-
function petChatBuild() {
|
|
20532
|
-
if (petChatEls) return petChatEls;
|
|
20533
|
-
try {
|
|
20534
|
-
const root = document.createElement('div');
|
|
20535
|
-
root.id = 'we-pet-chat';
|
|
20536
|
-
root.style.cssText = [
|
|
20537
|
-
'position:fixed', 'right:24px', 'bottom:172px', 'width:320px', 'max-height:420px',
|
|
20538
|
-
'display:none', 'flex-direction:column', 'gap:8px', 'padding:12px', 'z-index:2147483000',
|
|
20539
|
-
'background:rgba(24,24,28,.92)', 'color:#f2f2f5', 'border:1px solid rgba(255,255,255,.12)',
|
|
20540
|
-
'border-radius:14px', 'box-shadow:0 12px 32px rgba(0,0,0,.45)', 'backdrop-filter:blur(10px)',
|
|
20541
|
-
'font-size:13px', 'line-height:1.5',
|
|
20542
|
-
].join(';');
|
|
20543
|
-
|
|
20544
|
-
const head = document.createElement('div');
|
|
20545
|
-
head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:8px';
|
|
20546
|
-
const title = document.createElement('strong');
|
|
20547
|
-
title.textContent = weT('桌宠对话');
|
|
20548
|
-
const tools = document.createElement('div');
|
|
20549
|
-
tools.style.cssText = 'display:flex;align-items:center;gap:6px';
|
|
20550
|
-
// 麦克风:**按住说话**(pointerdown 开始 / pointerup 或移出结束),松手上传
|
|
20551
|
-
const voiceBtn = document.createElement('button');
|
|
20552
|
-
voiceBtn.type = 'button';
|
|
20553
|
-
voiceBtn.textContent = weT('按住说话');
|
|
20554
|
-
voiceBtn.title = weT('按住说话,松手识别(需先在 DSH 开启语音输入)');
|
|
20555
|
-
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';
|
|
20556
|
-
petChatOn(voiceBtn, 'pointerdown', (event) => { if (event && event.preventDefault) event.preventDefault(); void petChatVoiceStart(); });
|
|
20557
|
-
petChatOn(voiceBtn, 'pointerup', () => { void petChatVoiceStop(); });
|
|
20558
|
-
petChatOn(voiceBtn, 'pointerleave', () => { if (petChatVoice) void petChatVoiceStop(); });
|
|
20559
|
-
// 停止朗读:只停语音,不动文字(文字已经显示在气泡里)
|
|
20560
|
-
const stopBtn = document.createElement('button');
|
|
20561
|
-
stopBtn.type = 'button';
|
|
20562
|
-
stopBtn.textContent = weT('停止朗读');
|
|
20563
|
-
stopBtn.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';
|
|
20564
|
-
petChatOn(stopBtn, 'click', () => petChatTts.cancel());
|
|
20565
|
-
const memoryBtn = document.createElement('button');
|
|
20566
|
-
memoryBtn.type = 'button';
|
|
20567
|
-
memoryBtn.textContent = weT('查看记忆');
|
|
20568
|
-
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';
|
|
20569
|
-
petChatOn(memoryBtn, 'click', () => petChatShowMemory());
|
|
20570
|
-
const clear = document.createElement('button');
|
|
20571
|
-
clear.type = 'button';
|
|
20572
|
-
clear.textContent = weT('清空记忆');
|
|
20573
|
-
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';
|
|
20574
|
-
petChatOn(clear, 'click', () => petChatResetMemory());
|
|
20575
|
-
const close = document.createElement('button');
|
|
20576
|
-
close.type = 'button';
|
|
20577
|
-
close.textContent = '×';
|
|
20578
|
-
close.title = weT('关闭');
|
|
20579
|
-
close.style.cssText = 'background:none;border:0;color:#c9c9d1;font-size:18px;cursor:pointer;line-height:1';
|
|
20580
|
-
petChatOn(close, 'click', () => petChatHide());
|
|
20581
|
-
petChatAppend(tools, voiceBtn, stopBtn, memoryBtn, clear, close);
|
|
20582
|
-
petChatAppend(head, title, tools);
|
|
20583
|
-
|
|
20584
|
-
const log = document.createElement('div');
|
|
20585
|
-
log.style.cssText = 'flex:1 1 auto;overflow:auto;display:flex;flex-direction:column;gap:6px;min-height:80px';
|
|
20586
|
-
|
|
20587
|
-
// C2:今日已说 N/10 + 「今天别说了」(只有开启主动闲聊时才显示整行)
|
|
20588
|
-
const usage = document.createElement('div');
|
|
20589
|
-
usage.style.cssText = 'display:none;align-items:center;justify-content:space-between;gap:6px;font-size:11px;color:#9a9aa5';
|
|
20590
|
-
const usageText = document.createElement('span');
|
|
20591
|
-
const skipBtn = document.createElement('button');
|
|
20592
|
-
skipBtn.type = 'button';
|
|
20593
|
-
skipBtn.textContent = weT('今天别说了');
|
|
20594
|
-
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';
|
|
20595
|
-
petChatOn(skipBtn, 'click', () => petChatSkipToday());
|
|
20596
|
-
petChatAppend(usage, usageText, skipBtn);
|
|
20597
|
-
|
|
20598
|
-
const status = document.createElement('div');
|
|
20599
|
-
status.style.cssText = 'font-size:11px;color:#9a9aa5;min-height:14px';
|
|
20600
|
-
|
|
20601
|
-
const row = document.createElement('div');
|
|
20602
|
-
row.style.cssText = 'display:flex;gap:6px';
|
|
20603
|
-
const input = document.createElement('input');
|
|
20604
|
-
input.type = 'text';
|
|
20605
|
-
input.placeholder = weT('和我说点什么…');
|
|
20606
|
-
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';
|
|
20607
|
-
const send = document.createElement('button');
|
|
20608
|
-
send.type = 'button';
|
|
20609
|
-
send.textContent = weT('发送');
|
|
20610
|
-
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';
|
|
20611
|
-
petChatOn(send, 'click', () => petChatSend());
|
|
20612
|
-
petChatOn(input, 'keydown', (event) => {
|
|
20613
|
-
if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); petChatSend(); }
|
|
20614
|
-
});
|
|
20615
|
-
petChatAppend(row, input, send);
|
|
20616
|
-
|
|
20617
|
-
petChatAppend(root, head, usage, log, status, row);
|
|
20618
|
-
petChatAppend(document.body, root);
|
|
20619
|
-
petChatEls = { root, log, status, input, send, usage, usageText };
|
|
20620
|
-
return petChatEls;
|
|
20621
|
-
} catch {
|
|
20622
|
-
// 替身 DOM 撑不起这套结构:当成"没有气泡",不影响其它功能
|
|
20623
|
-
return null;
|
|
20624
|
-
}
|
|
20625
|
-
}
|
|
20626
|
-
|
|
20627
|
-
/** 渲染最近 N 条(role=user 靠右、assistant 靠左)。 */
|
|
20628
|
-
function petChatRender() {
|
|
20629
|
-
const els = petChatBuild();
|
|
20630
|
-
if (!els) return;
|
|
20631
|
-
els.log.textContent = '';
|
|
20632
|
-
for (const line of petChatLines) {
|
|
20633
|
-
const bubble = document.createElement('div');
|
|
20634
|
-
bubble.textContent = line.text;
|
|
20635
|
-
bubble.style.cssText = 'max-width:86%;padding:6px 9px;border-radius:10px;white-space:pre-wrap;word-break:break-word;'
|
|
20636
|
-
+ (line.role === 'user'
|
|
20637
|
-
? 'align-self:flex-end;background:rgba(124,92,255,.42)'
|
|
20638
|
-
: 'align-self:flex-start;background:rgba(255,255,255,.08)');
|
|
20639
|
-
els.log.appendChild(bubble);
|
|
20640
|
-
}
|
|
20641
|
-
els.log.scrollTop = els.log.scrollHeight;
|
|
20642
|
-
}
|
|
20643
|
-
|
|
20644
|
-
function petChatPush(role, text) {
|
|
20645
|
-
petChatLines.push({ role, text });
|
|
20646
|
-
if (petChatLines.length > PET_CHAT_KEEP_LINES) petChatLines = petChatLines.slice(-PET_CHAT_KEEP_LINES);
|
|
20647
|
-
petChatRender();
|
|
20648
|
-
}
|
|
20649
|
-
|
|
20650
|
-
function petChatStatus(text) {
|
|
20651
|
-
const els = petChatBuild();
|
|
20652
|
-
if (!els) return;
|
|
20653
|
-
els.status.textContent = text || '';
|
|
20654
|
-
}
|
|
20655
|
-
|
|
20656
|
-
function petChatShow() {
|
|
20657
|
-
const els = petChatBuild();
|
|
20658
|
-
if (!els) return;
|
|
20659
|
-
els.root.style.display = 'flex';
|
|
20660
|
-
if (typeof els.input.focus === 'function') els.input.focus();
|
|
20661
|
-
petChatSyncState();
|
|
20662
|
-
petChatRefreshUsage();
|
|
20663
|
-
}
|
|
20664
|
-
|
|
20665
|
-
function petChatHide() {
|
|
20666
|
-
if (!petChatEls) return;
|
|
20667
|
-
petChatTts.cancel(); // 关闭气泡:立刻停读
|
|
20668
|
-
petChatEls.root.style.display = 'none';
|
|
20669
|
-
}
|
|
20670
|
-
|
|
20671
|
-
function petChatToggle() {
|
|
20672
|
-
const els = petChatBuild();
|
|
20673
|
-
if (!els) return;
|
|
20674
|
-
if (els.root.style.display === 'none' || !els.root.style.display) petChatShow();
|
|
20675
|
-
else petChatHide();
|
|
20676
|
-
}
|
|
20677
|
-
|
|
20678
|
-
/** 五组台词按顺序轮换(同一次会话里不重复同一组,比纯随机更像"有人在")。 */
|
|
20690
|
+
/** 轮流取一句预设台词(分组轮换,避免总说同一组)。 */
|
|
20679
20691
|
let petChatPresetCursor = 0;
|
|
20692
|
+
const PET_CHAT_PRESET_ORDER = ['greeting', 'wallpaper', 'company', 'fallback', 'night'];
|
|
20680
20693
|
function petChatPresetLine() {
|
|
20681
|
-
const
|
|
20682
|
-
const group = groups[petChatPresetCursor % groups.length];
|
|
20694
|
+
const group = PET_CHAT_PRESET_LINES[PET_CHAT_PRESET_ORDER[petChatPresetCursor % PET_CHAT_PRESET_ORDER.length]];
|
|
20683
20695
|
petChatPresetCursor += 1;
|
|
20684
|
-
|
|
20685
|
-
|
|
20686
|
-
|
|
20687
|
-
|
|
20688
|
-
|
|
20689
|
-
|
|
20690
|
-
|
|
20691
|
-
|
|
20692
|
-
|
|
20693
|
-
|
|
20694
|
-
|
|
20695
|
-
|
|
20696
|
-
|
|
20697
|
-
|
|
20696
|
+
return group[Math.floor(Math.random() * group.length)];
|
|
20697
|
+
}
|
|
20698
|
+
|
|
20699
|
+
/** 头顶气泡实例:锚点取桌宠层矩形,跟随位置与缩放。 */
|
|
20700
|
+
const petBubble = petBubbleCreate({
|
|
20701
|
+
document: typeof document !== 'undefined' ? document : undefined,
|
|
20702
|
+
// 跟随桌宠:把宿主环境的 rAF 交给气泡,打开期间每帧按 getAnchor() 重定位
|
|
20703
|
+
requestAnimationFrame: typeof requestAnimationFrame === 'function'
|
|
20704
|
+
? (cb) => requestAnimationFrame(cb)
|
|
20705
|
+
: undefined,
|
|
20706
|
+
cancelAnimationFrame: typeof cancelAnimationFrame === 'function'
|
|
20707
|
+
? (id) => cancelAnimationFrame(id)
|
|
20708
|
+
: undefined,
|
|
20709
|
+
getAnchor: () => {
|
|
20710
|
+
try {
|
|
20711
|
+
const layer = document && document.querySelector ? document.querySelector('#we-pet-layer') : null;
|
|
20712
|
+
if (!layer || typeof layer.getBoundingClientRect !== 'function') return null;
|
|
20713
|
+
const rect = layer.getBoundingClientRect();
|
|
20714
|
+
const style = window.getComputedStyle(layer);
|
|
20715
|
+
const scale = Number(style.getPropertyValue('--we-pet-scale')) || 1;
|
|
20716
|
+
return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, scale };
|
|
20717
|
+
} catch { return null; }
|
|
20718
|
+
},
|
|
20719
|
+
});
|
|
20698
20720
|
|
|
20699
|
-
/**
|
|
20700
|
-
|
|
20721
|
+
/**
|
|
20722
|
+
* 语音模型(SenseVoice)自举:调宿主 /pet-chat/asr(它会 speechToText.prepare),
|
|
20723
|
+
* 然后轮询 /pet-chat/asr 把下载进度显示在气泡里。
|
|
20724
|
+
* 这样用户装完插件直接说话就行,不需要去 DSH 设置里找「语音输入」开关。
|
|
20725
|
+
*/
|
|
20726
|
+
async function ensureAsrReady() {
|
|
20727
|
+
petBubble.setState('think');
|
|
20701
20728
|
try {
|
|
20702
|
-
|
|
20703
|
-
|
|
20704
|
-
|
|
20705
|
-
|
|
20706
|
-
|
|
20707
|
-
|
|
20708
|
-
|
|
20709
|
-
|
|
20710
|
-
|
|
20711
|
-
|
|
20712
|
-
|
|
20713
|
-
|
|
20714
|
-
|
|
20715
|
-
|
|
20716
|
-
|
|
20717
|
-
|
|
20718
|
-
|
|
20719
|
-
|
|
20729
|
+
await apiPostJson('/pet-chat/asr', {}, { parse: 'always' });
|
|
20730
|
+
} catch { /* 触发失败也要继续轮询看状态 */ }
|
|
20731
|
+
for (let i = 0; i < 240; i += 1) {
|
|
20732
|
+
await new Promise((resolve) => { setTimeout(resolve, 1500); });
|
|
20733
|
+
const resp = await apiJson('/pet-chat/asr', { parse: 'always' }).catch(() => null);
|
|
20734
|
+
const doc = (resp && resp.data) || {};
|
|
20735
|
+
if (doc.ready) {
|
|
20736
|
+
petBubble.show('语音准备好了,点我再说一次');
|
|
20737
|
+
petBubble.hide(3000);
|
|
20738
|
+
return;
|
|
20739
|
+
}
|
|
20740
|
+
if (doc.available === false) {
|
|
20741
|
+
petBubble.show('这个 DSH 版本没有语音转写服务,先打字吧');
|
|
20742
|
+
petBubble.hide(3000);
|
|
20743
|
+
return;
|
|
20744
|
+
}
|
|
20745
|
+
if (doc.phase === 'failed') {
|
|
20746
|
+
petBubble.show('语音模型下载失败,稍后再点我试试');
|
|
20747
|
+
petBubble.hide(3000);
|
|
20748
|
+
return;
|
|
20749
|
+
}
|
|
20750
|
+
const pct = doc.totalBytes > 0 && doc.completedBytes >= 0
|
|
20751
|
+
? Math.max(0, Math.min(100, Math.round((doc.completedBytes / doc.totalBytes) * 100)))
|
|
20752
|
+
: null;
|
|
20753
|
+
petBubble.show(pct === null ? '语音模型准备中…' : `语音模型下载中 ${pct}%`);
|
|
20720
20754
|
}
|
|
20755
|
+
petBubble.show('语音模型还没下完,过一会儿再点我');
|
|
20756
|
+
petBubble.hide(3000);
|
|
20721
20757
|
}
|
|
20722
20758
|
|
|
20723
|
-
/**
|
|
20724
|
-
|
|
20725
|
-
|
|
20726
|
-
|
|
20727
|
-
|
|
20728
|
-
|
|
20729
|
-
|
|
20730
|
-
|
|
20731
|
-
|
|
20732
|
-
|
|
20733
|
-
|
|
20734
|
-
|
|
20735
|
-
|
|
20736
|
-
|
|
20737
|
-
|
|
20738
|
-
|
|
20739
|
-
|
|
20740
|
-
|
|
20741
|
-
|
|
20742
|
-
|
|
20743
|
-
|
|
20744
|
-
|
|
20745
|
-
|
|
20746
|
-
|
|
20747
|
-
|
|
20748
|
-
|
|
20749
|
-
|
|
20750
|
-
|
|
20751
|
-
if (!text) return;
|
|
20752
|
-
if ([...text].length > 400) { petChatStatus(weT('一次最多 400 字')); return; }
|
|
20753
|
-
els.input.value = '';
|
|
20754
|
-
petChatPush('user', text);
|
|
20755
|
-
petChatTts.start(); // 新消息:停掉上一段朗读
|
|
20756
|
-
petChatBusy = true;
|
|
20757
|
-
petChatStatus(weT('思考中…'));
|
|
20758
|
-
|
|
20759
|
-
const state = await petChatSyncState();
|
|
20760
|
-
if (!state || state.enabled !== true) {
|
|
20761
|
-
// 没有模型:不假装在对话,直接给预设台词
|
|
20762
|
-
const presetLine = petChatPresetLine();
|
|
20763
|
-
petChatPush('assistant', presetLine);
|
|
20764
|
-
petChatTts.finish(presetLine);
|
|
20765
|
-
petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
|
|
20766
|
-
petChatBusy = false;
|
|
20767
|
-
return;
|
|
20768
|
-
}
|
|
20769
|
-
|
|
20770
|
-
let assistant = '';
|
|
20771
|
-
const ensureBubble = () => {
|
|
20772
|
-
if (!assistant) { petChatPush('assistant', ''); }
|
|
20773
|
-
};
|
|
20774
|
-
try {
|
|
20775
|
-
const call = await apiFetch('/pet-chat/chat', {
|
|
20776
|
-
method: 'POST',
|
|
20777
|
-
headers: { 'content-type': 'application/json' },
|
|
20778
|
-
body: JSON.stringify({ text }),
|
|
20779
|
-
parse: false,
|
|
20780
|
-
});
|
|
20781
|
-
const response = call && call.response;
|
|
20782
|
-
if (!call || !call.ok || !response || !response.body) {
|
|
20783
|
-
petChatStatus(weT('宿主拒绝了这次请求') + '(HTTP ' + response.status + ')');
|
|
20784
|
-
petChatBusy = false;
|
|
20759
|
+
/** 语音输入(v0.1):前端不碰麦克风 —— 宿主用 ffmpeg 录,这里只发请求、收文本。 */
|
|
20760
|
+
const petVoiceIn = petVoiceInputCreate({
|
|
20761
|
+
postRecord: async () => {
|
|
20762
|
+
const res = await apiPostJson('/pet-chat/record', { language: 'zh' }, { parse: 'always' });
|
|
20763
|
+
return (res && res.data) || {};
|
|
20764
|
+
},
|
|
20765
|
+
postChat: async (text, onState) => {
|
|
20766
|
+
petBubble.setState('answer');
|
|
20767
|
+
// ⚠️ apiFetch 的返回值里**已经带上了原始 Response**(字段 `response`)。
|
|
20768
|
+
// 上一版误写成 `res.body.getReader()`:res 是 { ok, status, data, response },
|
|
20769
|
+
// res.body 恒为 undefined ⇒ 抛 TypeError ⇒ 读流代码一行都跑不到
|
|
20770
|
+
// (真机症状:输入后气泡停在 answer 状态、一个字都不出)。
|
|
20771
|
+
// 也不要用裸 fetch —— 守卫 verify-api-client 要求客户端零裸 fetch。
|
|
20772
|
+
let res;
|
|
20773
|
+
try {
|
|
20774
|
+
res = await apiFetch('/pet-chat/chat', {
|
|
20775
|
+
method: 'POST',
|
|
20776
|
+
headers: { 'content-type': 'application/json' },
|
|
20777
|
+
body: JSON.stringify({ text }),
|
|
20778
|
+
// ⚠️ 必须 parse:'none'。默认路径会 await response.json(),
|
|
20779
|
+
// 那会把 SSE 流**整个消费掉**(等到生成结束、再解析失败),
|
|
20780
|
+
// 之后 res.response.body 已 used ⇒ getReader() 抛错 ⇒ 气泡一个字都不出。
|
|
20781
|
+
parse: 'none',
|
|
20782
|
+
});
|
|
20783
|
+
} catch {
|
|
20784
|
+
petBubble.show('连不上宿主,稍后再试');
|
|
20785
|
+
petBubble.hide(3000);
|
|
20786
|
+
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
20785
20787
|
return;
|
|
20786
20788
|
}
|
|
20787
|
-
const
|
|
20789
|
+
const stream = res && res.response;
|
|
20790
|
+
if (!res || !res.ok || !stream || !stream.body) {
|
|
20791
|
+
petBubble.show(res && res.status === 401 ? '模型 Key 无效,去设置里换一把' : '这次没答上来,再试一次');
|
|
20792
|
+
petBubble.hide(3000);
|
|
20793
|
+
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
20794
|
+
return;
|
|
20795
|
+
}
|
|
20796
|
+
const reader = stream.body.getReader();
|
|
20788
20797
|
const decoder = new TextDecoder();
|
|
20789
20798
|
let buffer = '';
|
|
20790
20799
|
for (;;) {
|
|
20791
|
-
// eslint-disable-
|
|
20792
|
-
const { value, done } = await reader.read();
|
|
20800
|
+
const { value, done } = await reader.read(); // eslint-disable-line no-await-in-loop
|
|
20793
20801
|
if (done) break;
|
|
20794
20802
|
buffer += decoder.decode(value, { stream: true });
|
|
20795
|
-
|
|
20796
|
-
|
|
20797
|
-
|
|
20798
|
-
const
|
|
20799
|
-
|
|
20800
|
-
|
|
20801
|
-
|
|
20802
|
-
|
|
20803
|
-
|
|
20804
|
-
|
|
20805
|
-
petChatRender();
|
|
20806
|
-
} else if (parsed.event === 'done') {
|
|
20807
|
-
petChatTts.finish(assistant);
|
|
20808
|
-
petChatApplyEmotion(parsed.data && parsed.data.emotion);
|
|
20809
|
-
petChatStatus('');
|
|
20810
|
-
} else if (parsed.event === 'error') {
|
|
20811
|
-
const code = parsed.data && parsed.data.code ? parsed.data.code : 'error';
|
|
20812
|
-
const hint = parsed.data && parsed.data.hint ? parsed.data.hint : '';
|
|
20813
|
-
petChatStatus(hint || code);
|
|
20814
|
-
if (code === 'no-model') petChatPush('assistant', petChatPresetLine());
|
|
20815
|
-
}
|
|
20803
|
+
for (;;) {
|
|
20804
|
+
const cut = buffer.indexOf('\n\n');
|
|
20805
|
+
if (cut < 0) break;
|
|
20806
|
+
const frame = buffer.slice(0, cut);
|
|
20807
|
+
buffer = buffer.slice(cut + 2);
|
|
20808
|
+
const line = frame.split('\n').find((item) => item.startsWith('data:'));
|
|
20809
|
+
if (!line) continue;
|
|
20810
|
+
let payload = null;
|
|
20811
|
+
try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
|
|
20812
|
+
if (payload && typeof payload.t === 'string') petBubble.append(payload.t);
|
|
20816
20813
|
}
|
|
20817
20814
|
}
|
|
20818
|
-
|
|
20819
|
-
|
|
20820
|
-
} finally {
|
|
20821
|
-
petChatBusy = false;
|
|
20822
|
-
if (!assistant) petChatStatus('');
|
|
20823
|
-
}
|
|
20824
|
-
}
|
|
20825
|
-
|
|
20826
|
-
/**
|
|
20827
|
-
* 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点宠物 / 快捷键。
|
|
20828
|
-
* 返回 cleanup —— 卸载时要摘掉监听、删掉 DOM。
|
|
20829
|
-
*/
|
|
20830
|
-
/** B4「查看记忆」:拉偏好摘要显示在气泡里(只显示结论,不含原文)。 */
|
|
20831
|
-
async function petChatShowMemory() {
|
|
20832
|
-
try {
|
|
20833
|
-
const res = await apiJson('/pet-chat/memory', { parse: 'always' });
|
|
20834
|
-
const doc = (res && res.data) || {};
|
|
20835
|
-
if (!doc.ok) { petChatStatus(weT('读取记忆失败')); return; }
|
|
20836
|
-
if (doc.enabled === false) { petChatStatus(weT('记忆已关闭(设置 → 桌宠对话)')); return; }
|
|
20837
|
-
const m = doc.memory || {};
|
|
20838
|
-
const parts = [];
|
|
20839
|
-
if (m.nickname) parts.push('称呼:' + m.nickname);
|
|
20840
|
-
if (Array.isArray(m.likes) && m.likes.length) parts.push('喜欢:' + m.likes.join('、'));
|
|
20841
|
-
if (Array.isArray(m.dislikes) && m.dislikes.length) parts.push('不喜欢:' + m.dislikes.join('、'));
|
|
20842
|
-
if (m.style) parts.push('说话风格:' + m.style);
|
|
20843
|
-
if (Array.isArray(m.notes) && m.notes.length) parts.push('备注:' + m.notes.join('、'));
|
|
20844
|
-
petChatPush('assistant', parts.length ? parts.join('\n') : weT('还没有记住任何偏好'));
|
|
20845
|
-
petChatStatus(parts.length ? weT('点「清空记忆」可以全部忘掉') : '');
|
|
20846
|
-
} catch {
|
|
20847
|
-
petChatStatus(weT('读取记忆失败'));
|
|
20848
|
-
}
|
|
20849
|
-
}
|
|
20850
|
-
|
|
20851
|
-
/** C2「今天别说了」:当天不再主动。 */
|
|
20852
|
-
async function petChatSkipToday() {
|
|
20853
|
-
try {
|
|
20854
|
-
const res = await apiPostJson('/pet-chat/skip', {}, { parse: 'always' });
|
|
20855
|
-
petChatStatus(res && res.ok ? weT('今天不主动打扰了') : weT('操作失败'));
|
|
20856
|
-
await petChatRefreshUsage();
|
|
20857
|
-
} catch {
|
|
20858
|
-
petChatStatus(weT('操作失败'));
|
|
20859
|
-
}
|
|
20860
|
-
}
|
|
20861
|
-
|
|
20862
|
-
/** 刷新「今日已说 N/10」(开启主动闲聊时显示)。 */
|
|
20863
|
-
async function petChatRefreshUsage() {
|
|
20864
|
-
const els = petChatEls || petChatBuild();
|
|
20865
|
-
if (!els || !els.usage) return;
|
|
20866
|
-
try {
|
|
20867
|
-
const res = await apiJson('/pet-chat/proactive', { parse: 'always' });
|
|
20868
|
-
const doc = (res && res.data) || {};
|
|
20869
|
-
if (!doc.enabled) { els.usage.style.display = 'none'; return; }
|
|
20870
|
-
const usage = doc.usage || {};
|
|
20871
|
-
els.usageText.textContent = `今日已说 ${Number(usage.said) || 0}/${Number(usage.limit) || 0}`;
|
|
20872
|
-
els.usage.style.display = 'flex';
|
|
20873
|
-
} catch {
|
|
20874
|
-
els.usage.style.display = 'none';
|
|
20875
|
-
}
|
|
20876
|
-
}
|
|
20877
|
-
|
|
20878
|
-
/* ── 语音输入(按住说话)──────────────────────────────────────────────────────
|
|
20879
|
-
* 三层分工:
|
|
20880
|
-
* ① 录音(这里):getUserMedia + AudioWorklet 采 PCM → 16kHz 单声道 PCM16 WAV;
|
|
20881
|
-
* ② 转写(宿主):POST /pet-chat/transcribe → DSH 的 speechToText(provider 自己管模型);
|
|
20882
|
-
* ③ 回填(这里):**只写输入框**,绝不自动发送 —— 识别难免错,得让用户改完再发。
|
|
20883
|
-
* 失败一律回落打字(只给一行状态提示,不弹错误框)。
|
|
20884
|
-
*/
|
|
20885
|
-
const PET_CHAT_VOICE_MAX_SECONDS = 15;
|
|
20886
|
-
let petChatVoice = null;
|
|
20887
|
-
let petChatVoiceEnabled = null;
|
|
20888
|
-
// 朗读(TTS):默认开;配置由 /state 带回,没拿到时按默认值(开)
|
|
20889
|
-
let petChatVoiceOut = { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' };
|
|
20890
|
-
const petChatTts = petChatTtsCreate({
|
|
20891
|
-
getSpeech: () => (typeof window !== 'undefined' ? window.speechSynthesis : null),
|
|
20892
|
-
getVoices: () => {
|
|
20893
|
-
const speech = typeof window !== 'undefined' ? window.speechSynthesis : null;
|
|
20894
|
-
return speech && typeof speech.getVoices === 'function' ? speech.getVoices() : [];
|
|
20815
|
+
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
20816
|
+
petBubble.hide(3000);
|
|
20895
20817
|
},
|
|
20896
|
-
|
|
20897
|
-
|
|
20898
|
-
|
|
20899
|
-
|
|
20900
|
-
|
|
20901
|
-
|
|
20902
|
-
|
|
20903
|
-
|
|
20904
|
-
|
|
20905
|
-
|
|
20906
|
-
|
|
20907
|
-
|
|
20908
|
-
const put = (offset, text) => { for (let i = 0; i < text.length; i += 1) view.setUint8(offset + i, text.charCodeAt(i)); };
|
|
20909
|
-
put(0, 'RIFF'); view.setUint32(4, 36 + frames * 2, true); put(8, 'WAVE');
|
|
20910
|
-
put(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
|
|
20911
|
-
view.setUint32(24, rate, true); view.setUint32(28, rate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
|
|
20912
|
-
put(36, 'data'); view.setUint32(40, frames * 2, true);
|
|
20913
|
-
let offset = 44;
|
|
20914
|
-
for (let i = 0; i < frames; i += 1) {
|
|
20915
|
-
const index = Math.min(samples.length - 1, Math.floor(i * ratio));
|
|
20916
|
-
const clamped = Math.max(-1, Math.min(1, samples[index]));
|
|
20917
|
-
view.setInt16(offset, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
|
|
20918
|
-
offset += 2;
|
|
20919
|
-
}
|
|
20920
|
-
return new Uint8Array(buffer);
|
|
20921
|
-
}
|
|
20922
|
-
|
|
20923
|
-
/** Uint8Array → base64(浏览器与 Node 都可用)。 */
|
|
20924
|
-
function petChatToBase64(bytes) {
|
|
20925
|
-
let binary = '';
|
|
20926
|
-
for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
|
|
20927
|
-
if (typeof btoa === 'function') return btoa(binary);
|
|
20928
|
-
return Buffer.from(bytes).toString('base64');
|
|
20929
|
-
}
|
|
20930
|
-
|
|
20931
|
-
/** 开始录音。返回是否真的开始了。 */
|
|
20932
|
-
async function petChatVoiceStart() {
|
|
20933
|
-
if (petChatVoice) return true;
|
|
20934
|
-
if (petChatVoiceEnabled === false) {
|
|
20935
|
-
petChatStatus(weT('语音输入未开启:请先在 DSH 设置里启用(需下载模型)'));
|
|
20936
|
-
return false;
|
|
20937
|
-
}
|
|
20938
|
-
try {
|
|
20939
|
-
const media = navigator.mediaDevices && navigator.mediaDevices.getUserMedia
|
|
20940
|
-
? await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, sampleRate: 16000 } })
|
|
20941
|
-
: null;
|
|
20942
|
-
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
|
20943
|
-
if (!media || !AudioCtx) {
|
|
20944
|
-
if (media) media.getTracks().forEach((track) => track.stop());
|
|
20945
|
-
petChatStatus(weT('打不开麦克风,可以继续打字'));
|
|
20946
|
-
return false;
|
|
20947
|
-
}
|
|
20948
|
-
const ctx = new AudioCtx();
|
|
20949
|
-
const source = ctx.createMediaStreamSource(media);
|
|
20950
|
-
const chunks = [];
|
|
20951
|
-
// AudioWorklet:每帧 Float32 丢回主线程(不阻塞渲染)
|
|
20952
|
-
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);';
|
|
20953
|
-
const url = URL.createObjectURL(new Blob([code], { type: 'application/javascript' }));
|
|
20954
|
-
await ctx.audioWorklet.addModule(url);
|
|
20955
|
-
URL.revokeObjectURL(url);
|
|
20956
|
-
const node = new AudioWorkletNode(ctx, 'pet-chat-pcm');
|
|
20957
|
-
node.port.onmessage = (event) => {
|
|
20958
|
-
if (petChatVoice && chunks.length * 1024 < 16000 * PET_CHAT_VOICE_MAX_SECONDS * 8) chunks.push(event.data);
|
|
20818
|
+
// P4:用户自己的话**不进**气泡(那是回声);只显示 assistant 的 SSE delta
|
|
20819
|
+
onText: () => {},
|
|
20820
|
+
onError: (error) => {
|
|
20821
|
+
// 失败一律回落打字:只给一行提示,不弹错误框
|
|
20822
|
+
const map = {
|
|
20823
|
+
'no-device': '没找到麦克风,先打字吧',
|
|
20824
|
+
'ffmpeg-missing': '缺少 ffmpeg,先打字吧',
|
|
20825
|
+
'unsupported-platform': '这个系统不支持桌面录音,用浏览器打开 DSH 才能语音',
|
|
20826
|
+
'asr-not-ready': '语音模型还没下载,我来准备一下…',
|
|
20827
|
+
timeout: '这次没听清,再说一次或直接打字',
|
|
20828
|
+
'no-speech': '没听到声音,再说一次或直接打字',
|
|
20829
|
+
network: '网络不太顺,重试或直接打字',
|
|
20959
20830
|
};
|
|
20960
|
-
|
|
20961
|
-
|
|
20962
|
-
|
|
20963
|
-
|
|
20964
|
-
|
|
20965
|
-
|
|
20966
|
-
|
|
20967
|
-
|
|
20968
|
-
|
|
20969
|
-
|
|
20970
|
-
|
|
20971
|
-
|
|
20972
|
-
|
|
20973
|
-
async function petChatVoiceStop() {
|
|
20974
|
-
const voice = petChatVoice;
|
|
20975
|
-
if (!voice) return;
|
|
20976
|
-
petChatVoice = null;
|
|
20977
|
-
try {
|
|
20978
|
-
voice.node.port.onmessage = null;
|
|
20979
|
-
voice.source.disconnect();
|
|
20980
|
-
voice.node.disconnect();
|
|
20981
|
-
voice.stream.getTracks().forEach((track) => track.stop());
|
|
20982
|
-
await voice.ctx.close();
|
|
20983
|
-
} catch { /* 收尾失败不影响转写 */ }
|
|
20984
|
-
|
|
20985
|
-
const total = voice.chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
20986
|
-
if (!total) { petChatStatus(weT('没听到声音,再试一次?')); return; }
|
|
20987
|
-
const merged = new Float32Array(total);
|
|
20988
|
-
let offset = 0;
|
|
20989
|
-
for (const chunk of voice.chunks) { merged.set(chunk, offset); offset += chunk.length; }
|
|
20990
|
-
const wav = petChatEncodeWav(merged, voice.sampleRate);
|
|
20991
|
-
|
|
20992
|
-
petChatStatus(weT('识别中…'));
|
|
20993
|
-
// ↓ 这一段是 D⑥ 的判据面:只写 input.value,绝不调用 petChatSend
|
|
20994
|
-
const res = await apiPostJson('/pet-chat/transcribe', { audio: petChatToBase64(wav), language: 'zh' }, { parse: 'always' });
|
|
20995
|
-
const doc = (res && res.data) || {};
|
|
20996
|
-
const els = petChatEls || petChatBuild();
|
|
20997
|
-
if (!doc.ok) {
|
|
20998
|
-
petChatStatus(weT('这次没听清,可以继续打字') + (doc.hint ? '(' + doc.hint + ')' : ''));
|
|
20999
|
-
return;
|
|
21000
|
-
}
|
|
21001
|
-
if (els && typeof doc.text === 'string') {
|
|
21002
|
-
els.input.value = doc.text;
|
|
21003
|
-
if (typeof els.input.focus === 'function') els.input.focus();
|
|
21004
|
-
petChatStatus(weT('识别完成,确认后按发送'));
|
|
21005
|
-
}
|
|
21006
|
-
}
|
|
20831
|
+
const message = map[error && error.code] || '没听清,直接打字也行';
|
|
20832
|
+
petBubble.show(message);
|
|
20833
|
+
// asr-not-ready:自动触发模型下载并在气泡里显示进度,用户不用去 DSH 设置里找开关
|
|
20834
|
+
if (error && error.code === 'asr-not-ready') {
|
|
20835
|
+
void ensureAsrReady();
|
|
20836
|
+
return;
|
|
20837
|
+
}
|
|
20838
|
+
// ⚠️ 失败**不要自动弹输入框**(用户会以为"点一下就变对话框")。
|
|
20839
|
+
// 打字入口只从右键菜单「对话」进;这里只给一行提示 + 引导。
|
|
20840
|
+
petBubble.show(`${message}(右键 → 对话)`);
|
|
20841
|
+
petBubble.hide(4000);
|
|
20842
|
+
},
|
|
20843
|
+
});
|
|
21007
20844
|
|
|
21008
20845
|
/**
|
|
21009
|
-
*
|
|
21010
|
-
*
|
|
21011
|
-
* 五条件里渲染进程能拿到的事实:开关/计数/间隔/静默时段由宿主判,
|
|
21012
|
-
* 客户端只提供 `fullscreen`(document.fullscreenElement)、`focused`(document.hasFocus())
|
|
21013
|
-
* 和 `idleMinutes`(**窗口内**最近一次键鼠事件距现在多久)。
|
|
21014
|
-
* ⚠️ 这不是系统全局空闲(Electron 的 powerMonitor.getSystemIdleTime 在渲染进程拿不到),
|
|
21015
|
-
* 只是"这个窗口最近有没有人动"的近似 —— 已在 docs/PET-CHAT-DONE.md 写明。
|
|
20846
|
+
* 打字兜底(右键 → 打字说…):一个小输入条挂在桌宠上方,回车发 /chat。
|
|
20847
|
+
* 为什么不用 window.prompt:Electron 里 prompt 返回 null,用户会以为坏了。
|
|
21016
20848
|
*/
|
|
21017
|
-
|
|
21018
|
-
if (
|
|
21019
|
-
const
|
|
21020
|
-
|
|
21021
|
-
const
|
|
21022
|
-
|
|
21023
|
-
|
|
21024
|
-
|
|
21025
|
-
|
|
21026
|
-
|
|
21027
|
-
|
|
21028
|
-
|
|
21029
|
-
|
|
21030
|
-
|
|
20849
|
+
function petChatOpenTyping(extra = {}) {
|
|
20850
|
+
if (typeof document === 'undefined' || !document.createElement) return;
|
|
20851
|
+
const existed = document.querySelector('#we-pet-typing');
|
|
20852
|
+
if (existed) { existed.focus(); return; }
|
|
20853
|
+
const box = document.createElement('div');
|
|
20854
|
+
box.id = 'we-pet-typing';
|
|
20855
|
+
box.style.cssText = 'position:fixed;z-index:10000;left:50%;bottom:120px;transform:translateX(-50%);'
|
|
20856
|
+
+ 'display:flex;gap:6px;background:rgba(24,24,28,.95);padding:8px;border-radius:10px;';
|
|
20857
|
+
const input = document.createElement('input');
|
|
20858
|
+
input.type = 'text';
|
|
20859
|
+
input.placeholder = (extra && extra.hint) || '打字说…(回车发送)';
|
|
20860
|
+
input.style.cssText = 'width:240px;padding:6px 8px;border-radius:8px;border:1px solid #444;background:#111;color:#eee;';
|
|
20861
|
+
const send = () => {
|
|
20862
|
+
const text = String(input.value || '').trim();
|
|
20863
|
+
if (!text) return;
|
|
20864
|
+
box.remove();
|
|
20865
|
+
// 打字说的文本**不上气泡**(P4 同理:气泡只显示助手的回答)。
|
|
20866
|
+
// 这里只把状态切成"思考中",等 SSE 的 delta 逐字填进来。
|
|
20867
|
+
petBubble.setState('think');
|
|
20868
|
+
void petVoiceIn.postChat(text);
|
|
20869
|
+
};
|
|
20870
|
+
input.addEventListener('keydown', (event) => {
|
|
20871
|
+
if (event.key === 'Enter') send();
|
|
20872
|
+
if (event.key === 'Escape') box.remove();
|
|
20873
|
+
});
|
|
20874
|
+
box.appendChild(input);
|
|
20875
|
+
document.body.appendChild(box);
|
|
20876
|
+
input.focus();
|
|
20877
|
+
}
|
|
20878
|
+
|
|
20879
|
+
/** 说一句:气泡显示 + 3 秒后淡出。
|
|
20880
|
+
* v0.1 不朗读 —— 这里刻意不做音频(验收⑦:lib/ 里不允许出现 speechSynthesis)。
|
|
20881
|
+
*/
|
|
20882
|
+
function petChatSay(text) {
|
|
20883
|
+
const line = String(text || '').trim();
|
|
20884
|
+
if (!line) return;
|
|
20885
|
+
petBubble.show(line);
|
|
20886
|
+
petBubble.hide(3000);
|
|
20887
|
+
}
|
|
20888
|
+
|
|
20889
|
+
/** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音);否则唤醒并开始听。 */
|
|
20890
|
+
function petChatWake() {
|
|
20891
|
+
if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
|
|
20892
|
+
petBubble.setState('listen');
|
|
20893
|
+
// 先看语音模型是否就绪;没就绪就**立刻**开始下载并在气泡里显示进度,
|
|
20894
|
+
// 不要等用户先撞一次 asr-not-ready 才被动触发(那之前会像"没反应")。
|
|
20895
|
+
void (async () => {
|
|
20896
|
+
const resp = await apiJson('/pet-chat/asr', { parse: 'always' }).catch(() => null);
|
|
20897
|
+
const doc = (resp && resp.data) || {};
|
|
20898
|
+
if (doc.ready) return;
|
|
20899
|
+
if (doc.available === false) return; // 该 DSH 没转写服务,交给 record 的失败分支提示
|
|
20900
|
+
await ensureAsrReady();
|
|
20901
|
+
})();
|
|
20902
|
+
void petVoiceIn.start().then((started) => {
|
|
20903
|
+
if (!started) return; // 失败分支已经由 onError 提示(回落打字)
|
|
20904
|
+
petBubble.show('我在听…');
|
|
20905
|
+
});
|
|
21031
20906
|
}
|
|
21032
20907
|
|
|
21033
|
-
/**
|
|
21034
|
-
|
|
21035
|
-
|
|
21036
|
-
|
|
21037
|
-
|
|
20908
|
+
/**
|
|
20909
|
+
* 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点桌宠 / 快捷键。
|
|
20910
|
+
* 返回 cleanup —— 卸载时摘监听、销毁气泡。
|
|
20911
|
+
*/
|
|
21038
20912
|
function mountPetChat() {
|
|
21039
|
-
|
|
21040
|
-
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function'
|
|
21041
|
-
|| typeof document.createElement !== 'function') {
|
|
21042
|
-
return () => {};
|
|
21043
|
-
}
|
|
20913
|
+
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return () => {};
|
|
21044
20914
|
const onDocumentClick = (event) => {
|
|
21045
20915
|
const target = event.target;
|
|
21046
20916
|
if (!target || typeof target.closest !== 'function') return;
|
|
21047
|
-
if (target.closest('#we-pet-layer'))
|
|
20917
|
+
if (target.closest('#we-pet-layer')) petChatWake();
|
|
21048
20918
|
};
|
|
21049
20919
|
const onKeyDown = (event) => {
|
|
21050
20920
|
if (event.altKey && event.ctrlKey && String(event.key).toLowerCase() === 'p') {
|
|
21051
20921
|
event.preventDefault();
|
|
21052
|
-
|
|
21053
|
-
return;
|
|
20922
|
+
petChatWake();
|
|
21054
20923
|
}
|
|
21055
|
-
if (event.key === 'Escape' && petChatEls && petChatEls.root.style.display === 'flex') petChatHide();
|
|
21056
20924
|
};
|
|
21057
|
-
//
|
|
21058
|
-
|
|
21059
|
-
const
|
|
20925
|
+
// 打字入口只从**右键菜单「对话」**进:pet-layer 的菜单项派发 `we-pet-talk`。
|
|
20926
|
+
// 不再劫持 contextmenu —— 那会让右键弹不出桌宠原生菜单(试演动作/缩放…)。
|
|
20927
|
+
const onTalkEvent = () => { petChatOpenTyping(); };
|
|
20928
|
+
window.addEventListener('we-pet-talk', onTalkEvent);
|
|
21060
20929
|
document.addEventListener('click', onDocumentClick, true);
|
|
21061
20930
|
document.addEventListener('keydown', onKeyDown, true);
|
|
21062
|
-
for (const name of activityEvents) window.addEventListener(name, markActivity, { passive: true });
|
|
21063
|
-
// 每 5 分钟问一次(不是每秒):拿不到系统级空闲,用窗口内活动近似。
|
|
21064
|
-
// 替身环境里没有 setInterval ⇒ 跳过(只影响主动闲聊,不影响聊天本身)
|
|
21065
|
-
const timer = typeof setInterval === 'function'
|
|
21066
|
-
? setInterval(() => { void petChatProactiveCheck(); }, PET_CHAT_CHECK_INTERVAL_MS)
|
|
21067
|
-
: null;
|
|
21068
|
-
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
21069
20931
|
return () => {
|
|
21070
|
-
|
|
20932
|
+
window.removeEventListener('we-pet-talk', onTalkEvent);
|
|
21071
20933
|
document.removeEventListener('click', onDocumentClick, true);
|
|
21072
20934
|
document.removeEventListener('keydown', onKeyDown, true);
|
|
21073
|
-
|
|
21074
|
-
if (petChatEls && petChatEls.root.parentNode) petChatEls.root.parentNode.removeChild(petChatEls.root);
|
|
21075
|
-
petChatEls = null;
|
|
21076
|
-
petChatLines = [];
|
|
20935
|
+
petBubble.dispose();
|
|
21077
20936
|
};
|
|
21078
20937
|
}
|
|
21079
20938
|
|