dsh-folia 4.26.0-pre.6 → 4.26.0-pre.8
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 +476 -973
- package/lib/index.js +0 -2
- package/lib/pet-chat-proactive.js +112 -112
- package/lib/route-registry.js +1 -1
- package/lib/routes/pet-chat.js +128 -168
- package/lib/settings-schema.js +42 -52
- package/lib/tts/tts-worker.cjs +129 -0
- package/package.json +2 -2
- package/lib/pet-chat-edge-tts.js +0 -105
package/lib/client.js
CHANGED
|
@@ -8082,27 +8082,21 @@ window.__ModuleLoader__.load({
|
|
|
8082
8082
|
baseUrl: 'https://api.deepseek.com',
|
|
8083
8083
|
apiKey: '', // 用户自己填;本机 Ollama 不需要
|
|
8084
8084
|
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: '' },
|
|
8104
|
-
// 朗读引擎:system = 系统音色(默认、离线);edge = 在线情感朗读(文本经微软,需联网)
|
|
8105
|
-
voiceEngine: 'system',
|
|
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):能力常开,用户只能在右键里查看/清空
|
|
8106
8100
|
},
|
|
8107
8101
|
};
|
|
8108
8102
|
|
|
@@ -8481,6 +8475,10 @@ window.__ModuleLoader__.load({
|
|
|
8481
8475
|
// 扩展:三个模块(与 RESET_GROUPS 同集,这里只是把它挂进页签划分)。
|
|
8482
8476
|
extensions: Object.keys(KINDS).filter((k) => (k.indexOf('avatar') === 0 || k.indexOf('fx') === 0
|
|
8483
8477
|
|| k.indexOf('parallax') === 0) && !DEFAULTS_ONLY.includes(k) && !CLIENT_ONLY.includes(k)),
|
|
8478
|
+
// 桌宠对话(门 2):整包一个键。**必须在这里登记** —— 客户端差量保存走 `PUT /settings/<ns>`,
|
|
8479
|
+
// 键不在任何簇里时 `ns` 落空 ⇒ 宿主回 404 `unknown settings namespace`
|
|
8480
|
+
// ⇒ 表现就是"第一次保存成功、之后每次保存都失败"。
|
|
8481
|
+
petChat: ['petChat'],
|
|
8484
8482
|
};
|
|
8485
8483
|
|
|
8486
8484
|
/**
|
|
@@ -8838,28 +8836,25 @@ window.__ModuleLoader__.load({
|
|
|
8838
8836
|
* `apiKey` 原样保留(只在本机 profile 里),但**限长**,避免设置文件被灌爆。
|
|
8839
8837
|
*/
|
|
8840
8838
|
/**
|
|
8841
|
-
*
|
|
8839
|
+
* 朗读音色(v0.1 收敛:只剩 name + muted)。
|
|
8842
8840
|
*
|
|
8843
|
-
* `
|
|
8844
|
-
*
|
|
8845
|
-
*
|
|
8841
|
+
* 迁移:老档里的 `voiceOut.voiceURI` / `voiceOut.enabled` / `voiceEngine` 在这里被吸收 ——
|
|
8842
|
+
* `voiceURI` 非空就当作用户选过的音色;`enabled:false` 等价于 `muted:true`。
|
|
8843
|
+
* 这样升级不会丢用户已经选过的音色,也不会把静音的人突然打开。
|
|
8846
8844
|
*/
|
|
8847
|
-
function
|
|
8848
|
-
const def = DEFAULTS.petChat.
|
|
8845
|
+
function readVoice(raw, legacy) {
|
|
8846
|
+
const def = DEFAULTS.petChat.voice;
|
|
8849
8847
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8850
|
-
|
|
8851
|
-
|
|
8852
|
-
|
|
8853
|
-
|
|
8854
|
-
volume: petChatFloat(src.volume, 0, 1, def.volume),
|
|
8855
|
-
voiceURI: petChatStr(src.voiceURI, 200).trim(),
|
|
8856
|
-
};
|
|
8848
|
+
const old = legacy && typeof legacy === 'object' && !Array.isArray(legacy) ? legacy : {};
|
|
8849
|
+
const name = petChatStr(src.name, 120).trim() || petChatStr(old.voiceURI, 200).trim() || def.name;
|
|
8850
|
+
const muted = typeof src.muted === 'boolean' ? src.muted : old.enabled === false;
|
|
8851
|
+
return { name, muted };
|
|
8857
8852
|
}
|
|
8858
|
-
|
|
8859
8853
|
function readPetChat(raw) {
|
|
8860
8854
|
const def = DEFAULTS.petChat;
|
|
8861
8855
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8862
8856
|
const persona = src.persona && typeof src.persona === 'object' && !Array.isArray(src.persona) ? src.persona : {};
|
|
8857
|
+
const wake = src.wake && typeof src.wake === 'object' && !Array.isArray(src.wake) ? src.wake : {};
|
|
8863
8858
|
const baseUrl = petChatStr(src.baseUrl, PET_CHAT_BASE_URL_MAX).trim();
|
|
8864
8859
|
return {
|
|
8865
8860
|
enabled: src.enabled === true,
|
|
@@ -8867,24 +8862,18 @@ window.__ModuleLoader__.load({
|
|
|
8867
8862
|
baseUrl: baseUrl === '' || /^https?:\/\//i.test(baseUrl) ? baseUrl : '',
|
|
8868
8863
|
apiKey: petChatStr(src.apiKey, PET_CHAT_API_KEY_MAX),
|
|
8869
8864
|
model: petChatStr(src.model, PET_CHAT_MODEL_MAX).trim(),
|
|
8870
|
-
persona
|
|
8871
|
-
|
|
8872
|
-
|
|
8873
|
-
|
|
8865
|
+
// 名字:新键优先;老档的 persona.name 迁移过来(不丢用户起过的名字)
|
|
8866
|
+
petName: petChatStr(src.petName, PET_CHAT_PERSONA_MAX).trim()
|
|
8867
|
+
|| petChatStr(persona.name, PET_CHAT_PERSONA_MAX).trim(),
|
|
8868
|
+
ownerName: petChatStr(src.ownerName, PET_CHAT_PERSONA_MAX).trim(),
|
|
8869
|
+
voice: readVoice(src.voice, src.voiceOut),
|
|
8870
|
+
wake: {
|
|
8871
|
+
click: wake.click !== false,
|
|
8872
|
+
name: wake.name === true,
|
|
8873
|
+
keyword: petChatStr(wake.keyword, 40).trim(),
|
|
8874
8874
|
},
|
|
8875
|
-
|
|
8876
|
-
|
|
8877
|
-
// B/C 的开关也在同一包里消毒:默认值来自 DEFAULTS,非法值回落默认。
|
|
8878
|
-
memoryEnabled: src.memoryEnabled !== false,
|
|
8879
|
-
memoryEveryTurns: petChatInt(src.memoryEveryTurns, 1, 50, def.memoryEveryTurns),
|
|
8880
|
-
proactiveEnabled: src.proactiveEnabled === true,
|
|
8881
|
-
proactiveDailyLimit: petChatInt(src.proactiveDailyLimit, 1, 20, def.proactiveDailyLimit),
|
|
8882
|
-
proactiveMinGapMin: petChatInt(src.proactiveMinGapMin, 30, 720, def.proactiveMinGapMin),
|
|
8883
|
-
quietHours: (typeof src.quietHours === 'string' && /^\d{2}:\d{2}-\d{2}:\d{2}$/.test(src.quietHours))
|
|
8884
|
-
? src.quietHours : def.quietHours,
|
|
8885
|
-
voiceEnabled: src.voiceEnabled === true,
|
|
8886
|
-
voiceOut: readVoiceOut(src.voiceOut),
|
|
8887
|
-
voiceEngine: src.voiceEngine === 'edge' ? 'edge' : 'system',
|
|
8875
|
+
// 记忆常开:设置里没有这个开关(追加决定 1),旧档里的 false 也不再尊重
|
|
8876
|
+
memoryEnabled: true,
|
|
8888
8877
|
};
|
|
8889
8878
|
}
|
|
8890
8879
|
|
|
@@ -18642,34 +18631,27 @@ window.__ModuleLoader__.load({
|
|
|
18642
18631
|
/* ── 桌宠对话设置区 ─────────────────────────────────────────────────────── */
|
|
18643
18632
|
|
|
18644
18633
|
const CHAT_DEFAULTS = {
|
|
18645
|
-
enabled: false,
|
|
18646
18634
|
provider: 'openai',
|
|
18647
18635
|
baseUrl: 'https://api.deepseek.com',
|
|
18648
18636
|
model: 'deepseek-chat',
|
|
18649
18637
|
apiKey: '',
|
|
18650
18638
|
apiKeyMasked: '',
|
|
18651
18639
|
hasApiKey: false,
|
|
18652
|
-
|
|
18653
|
-
|
|
18654
|
-
maxChars: 80,
|
|
18655
|
-
voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
|
|
18656
|
-
voiceEngine: 'system',
|
|
18657
|
-
memoryEnabled: true,
|
|
18658
|
-
proactive: { enabled: false, dailyLimit: 10, minGapMin: 120, quietHours: '22:00-08:00' },
|
|
18659
|
-
voiceEnabled: false,
|
|
18660
|
-
};
|
|
18661
|
-
|
|
18662
|
-
const PROVIDER_PRESETS = {
|
|
18663
|
-
openai: { baseUrl: 'https://api.deepseek.com', model: 'deepseek-chat' },
|
|
18664
|
-
ollama: { baseUrl: 'http://127.0.0.1:11434/v1', model: 'llama3.1' },
|
|
18640
|
+
petName: '',
|
|
18641
|
+
ownerName: '',
|
|
18665
18642
|
};
|
|
18666
18643
|
|
|
18644
|
+
/**
|
|
18645
|
+
* 设置页(v0.1 验收口径):**三项,无开关**。
|
|
18646
|
+
* 1) 模型 Key 2) 名字(桌宠名 = 唤醒词 + 你的称呼) 3) 音色(v0.2 占位,灰色只读)
|
|
18647
|
+
*
|
|
18648
|
+
* 为什么连"开启对话"都没有:工单要求用户不做选择 —— 填了 Key 就等于启用,
|
|
18649
|
+
* 主动搭话/记忆都是固定策略。删除任何开关,就少一次"用户要不要打开"的决策。
|
|
18650
|
+
*/
|
|
18667
18651
|
function PetChatSettings() {
|
|
18668
18652
|
const [draft, setDraft] = React.useState(CHAT_DEFAULTS);
|
|
18669
18653
|
const [status, setStatus] = React.useState({ ok: null, text: '' });
|
|
18670
18654
|
const [note, setNote] = React.useState(null);
|
|
18671
|
-
const [showKey, setShowKey] = React.useState(false);
|
|
18672
|
-
const [memory, setMemory] = React.useState(null);
|
|
18673
18655
|
const [busy, setBusy] = React.useState(false);
|
|
18674
18656
|
const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
|
|
18675
18657
|
|
|
@@ -18683,18 +18665,16 @@ window.__ModuleLoader__.load({
|
|
|
18683
18665
|
? { ok: true, text: weT('已保存的 Key:{mask}', { mask: doc.apiKeyMasked || '••••' }) }
|
|
18684
18666
|
: { ok: null, text: weT('还没有填 API Key') });
|
|
18685
18667
|
}
|
|
18686
|
-
} catch { /*
|
|
18668
|
+
} catch { /* 首次加载失败不打扰 */ }
|
|
18687
18669
|
}, []);
|
|
18688
18670
|
React.useEffect(() => { void load(); }, [load]);
|
|
18689
18671
|
|
|
18690
18672
|
const save = async () => {
|
|
18691
18673
|
setBusy(true);
|
|
18692
18674
|
try {
|
|
18693
|
-
|
|
18694
|
-
|
|
18695
|
-
|
|
18696
|
-
parse: 'always',
|
|
18697
|
-
});
|
|
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' });
|
|
18698
18678
|
const doc = (resp && resp.data) || {};
|
|
18699
18679
|
if (doc.saved) {
|
|
18700
18680
|
setNote({ ok: true, text: weT('已保存') });
|
|
@@ -18702,182 +18682,50 @@ window.__ModuleLoader__.load({
|
|
|
18702
18682
|
const state = await apiJson('/pet-chat/state', { parse: 'always' });
|
|
18703
18683
|
const sdoc = (state && state.data) || {};
|
|
18704
18684
|
setStatus(sdoc.reachable
|
|
18705
|
-
? { ok: true, text: weT('已连接 · {
|
|
18685
|
+
? { ok: true, text: weT('已连接 · {m}', { m: sdoc.model || draft.model }) }
|
|
18706
18686
|
: { ok: false, text: sdoc.lastError ? weT('未连接:{e}', { e: sdoc.lastError }) : weT('已保存,但还没连上') });
|
|
18707
|
-
} else {
|
|
18708
|
-
setNote({ ok: false, text: weT('保存失败') });
|
|
18709
|
-
}
|
|
18687
|
+
} else setNote({ ok: false, text: weT('保存失败') });
|
|
18710
18688
|
} catch (e) {
|
|
18711
18689
|
setNote({ ok: false, text: weT('保存失败:{msg}', { msg: (e && e.message) || '' }) });
|
|
18712
18690
|
} finally { setBusy(false); }
|
|
18713
18691
|
};
|
|
18714
18692
|
|
|
18715
|
-
const
|
|
18716
|
-
|
|
18717
|
-
|
|
18718
|
-
const resp = await apiJson('/pet-chat/test', {
|
|
18719
|
-
method: 'POST',
|
|
18720
|
-
body: { provider: draft.provider, baseUrl: draft.baseUrl, apiKey: draft.apiKey || '' },
|
|
18721
|
-
parse: 'always',
|
|
18722
|
-
});
|
|
18723
|
-
const doc = (resp && resp.data) || {};
|
|
18724
|
-
setStatus(doc.ok
|
|
18725
|
-
? { ok: true, text: weT('已连接 · {p}', { p: doc.provider || draft.provider }) }
|
|
18726
|
-
: { ok: false, text: doc.message || weT('连接失败') });
|
|
18727
|
-
} catch (e) {
|
|
18728
|
-
setStatus({ ok: false, text: weT('连接失败:{msg}', { msg: (e && e.message) || '' }) });
|
|
18729
|
-
} finally { setBusy(false); }
|
|
18730
|
-
};
|
|
18731
|
-
|
|
18732
|
-
const switchProvider = (provider) => {
|
|
18733
|
-
const preset = PROVIDER_PRESETS[provider] || PROVIDER_PRESETS.openai;
|
|
18734
|
-
update({ provider, baseUrl: preset.baseUrl, model: preset.model, ...(provider === 'ollama' ? { apiKey: '' } : {}) });
|
|
18735
|
-
};
|
|
18736
|
-
|
|
18737
|
-
const voices = (() => {
|
|
18738
|
-
try {
|
|
18739
|
-
const list = typeof window !== 'undefined' && window.speechSynthesis && window.speechSynthesis.getVoices
|
|
18740
|
-
? window.speechSynthesis.getVoices() : [];
|
|
18741
|
-
return Array.isArray(list) ? list : [];
|
|
18742
|
-
} catch { return []; }
|
|
18743
|
-
})();
|
|
18744
|
-
|
|
18745
|
-
const row = (label, node) => React.createElement('label', { key: label, style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
|
|
18746
|
-
weT(label), node);
|
|
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);
|
|
18747
18696
|
|
|
18748
18697
|
const child = [];
|
|
18749
|
-
child.push(React.createElement('div', { key: 'title', style: { fontWeight: 600, margin: '14px 0
|
|
18750
|
-
child.push(
|
|
18751
|
-
|
|
18752
|
-
|
|
18753
|
-
})));
|
|
18754
|
-
child.push(row('模型来源', React.createElement('select', {
|
|
18755
|
-
value: draft.provider, disabled: busy,
|
|
18756
|
-
onChange: (e) => switchProvider(e.target.value),
|
|
18757
|
-
},
|
|
18758
|
-
React.createElement('option', { value: 'openai' }, 'OpenAI 兼容'),
|
|
18759
|
-
React.createElement('option', { value: 'ollama' }, weT('本机 Ollama')))));
|
|
18760
|
-
child.push(row('接口地址', React.createElement('input', {
|
|
18761
|
-
type: 'text', value: draft.baseUrl, disabled: busy || draft.provider === 'ollama',
|
|
18762
|
-
style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ baseUrl: e.target.value }),
|
|
18763
|
-
})));
|
|
18764
|
-
child.push(row('模型名', React.createElement('input', {
|
|
18765
|
-
type: 'text', value: draft.model, disabled: busy,
|
|
18766
|
-
style: { flex: 1, minWidth: 0 }, onChange: (e) => update({ model: e.target.value }),
|
|
18767
|
-
})));
|
|
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
|
+
|
|
18768
18702
|
child.push(React.createElement('div', { key: 'key', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
|
|
18769
|
-
weT('
|
|
18703
|
+
weT('模型 Key'),
|
|
18770
18704
|
React.createElement('input', {
|
|
18771
|
-
type:
|
|
18772
|
-
|
|
18773
|
-
|
|
18774
|
-
disabled: busy || draft.provider === 'ollama',
|
|
18775
|
-
style: { flex: 1, minWidth: 0 },
|
|
18705
|
+
type: 'password', value: draft.apiKey || '',
|
|
18706
|
+
placeholder: draft.hasApiKey ? (draft.apiKeyMasked || '••••••••') : weT('填 DeepSeek API Key'),
|
|
18707
|
+
disabled: busy, style: { flex: 1, minWidth: 0 },
|
|
18776
18708
|
onChange: (e) => update({ apiKey: e.target.value }),
|
|
18777
18709
|
}),
|
|
18778
|
-
React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: () => setShowKey((v) => !v) }, showKey ? weT('隐藏') : weT('显示')),
|
|
18779
|
-
React.createElement('button', { type: 'button', className: 'we-picker__btn', disabled: busy, onClick: testConnection }, weT('测试连接')),
|
|
18780
18710
|
));
|
|
18781
18711
|
|
|
18782
|
-
child.push(
|
|
18783
|
-
weT('
|
|
18784
|
-
|
|
18785
|
-
|
|
18786
|
-
|
|
18787
|
-
|
|
18788
|
-
|
|
18789
|
-
|
|
18790
|
-
React.createElement('input', { type: 'number', min: 1, max: 12, value: draft.maxTurns, style: { width: '64px' }, disabled: busy, onChange: (e) => update({ maxTurns: Number(e.target.value) }) }),
|
|
18791
|
-
weT('字数上限'),
|
|
18792
|
-
React.createElement('input', { type: 'number', min: 20, max: 160, value: draft.maxChars, style: { width: '64px' }, disabled: busy, onChange: (e) => update({ maxChars: Number(e.target.value) }) }),
|
|
18793
|
-
));
|
|
18794
|
-
|
|
18795
|
-
child.push(React.createElement('div', { key: 'voice', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '6px 0 0', flexWrap: 'wrap' } },
|
|
18796
|
-
React.createElement('label', { style: { display: 'flex', gap: '4px', alignItems: 'center' } },
|
|
18797
|
-
React.createElement('input', { type: 'checkbox', checked: Boolean(draft.voiceOut && draft.voiceOut.enabled), disabled: busy, onChange: (e) => update({ voiceOut: { ...draft.voiceOut, enabled: e.target.checked } }) }),
|
|
18798
|
-
weT('朗读回答')),
|
|
18799
|
-
weT('音色'),
|
|
18800
|
-
React.createElement('select', {
|
|
18801
|
-
className: 'we-picker__playlist-select', value: (draft.voiceOut && draft.voiceOut.voiceURI) || '', disabled: busy,
|
|
18802
|
-
onChange: (e) => update({ voiceOut: { ...draft.voiceOut, voiceURI: e.target.value } }),
|
|
18803
|
-
}, React.createElement('option', { value: '' }, weT('自动(中文)')), voices.slice(0, 40).map((v) => React.createElement('option', { key: v.voiceURI, value: v.voiceURI }, v.name))),
|
|
18804
|
-
weT('语速'),
|
|
18805
|
-
React.createElement('input', { type: 'range', min: 0.5, max: 2, step: 0.1, value: (draft.voiceOut && draft.voiceOut.rate) || 1, disabled: busy, style: { width: '80px' }, onChange: (e) => update({ voiceOut: { ...draft.voiceOut, rate: Number(e.target.value) } }) }),
|
|
18806
|
-
weT('音量'),
|
|
18807
|
-
React.createElement('input', { type: 'range', min: 0, max: 1, step: 0.1, value: (draft.voiceOut && draft.voiceOut.volume) || 1, disabled: busy, style: { width: '80px' }, onChange: (e) => update({ voiceOut: { ...draft.voiceOut, volume: Number(e.target.value) } }) }),
|
|
18808
|
-
React.createElement('button', {
|
|
18809
|
-
type: 'button', className: 'we-picker__btn', disabled: busy,
|
|
18810
|
-
onClick: () => {
|
|
18811
|
-
try {
|
|
18812
|
-
const synth = window.speechSynthesis;
|
|
18813
|
-
if (!synth) { setNote({ ok: false, text: weT('这台机器没有系统语音') }); return; }
|
|
18814
|
-
synth.cancel();
|
|
18815
|
-
const utter = new window.SpeechSynthesisUtterance(weT('你好,我是你的桌宠。'));
|
|
18816
|
-
utter.rate = (draft.voiceOut && draft.voiceOut.rate) || 1;
|
|
18817
|
-
utter.volume = (draft.voiceOut && draft.voiceOut.volume) || 1;
|
|
18818
|
-
synth.speak(utter);
|
|
18819
|
-
} catch { setNote({ ok: false, text: weT('试听失败') }); }
|
|
18820
|
-
},
|
|
18821
|
-
}, weT('试听')),
|
|
18822
|
-
));
|
|
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
|
+
})));
|
|
18823
18720
|
|
|
18824
|
-
|
|
18825
|
-
|
|
18826
|
-
|
|
18721
|
+
// 音色:v0.2 占位(灰色、不可改),避免用户以为现在能选
|
|
18722
|
+
child.push(row('voice', '音色', React.createElement('select', {
|
|
18723
|
+
className: 'we-picker__playlist-select', disabled: true, value: 'zh-CN-XiaoxiaoNeural',
|
|
18827
18724
|
},
|
|
18828
|
-
React.createElement('option', { value: '
|
|
18829
|
-
|
|
18830
|
-
|
|
18831
|
-
child.push(React.createElement('div', { key: 'memory', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0' } },
|
|
18832
|
-
React.createElement('label', { style: { display: 'flex', gap: '4px', alignItems: 'center' } },
|
|
18833
|
-
React.createElement('input', { type: 'checkbox', checked: draft.memoryEnabled !== false, disabled: busy, onChange: (e) => update({ memoryEnabled: e.target.checked }) }),
|
|
18834
|
-
weT('长期记忆')),
|
|
18835
|
-
React.createElement('button', {
|
|
18836
|
-
type: 'button', className: 'we-picker__btn', disabled: busy,
|
|
18837
|
-
onClick: async () => {
|
|
18838
|
-
try {
|
|
18839
|
-
const resp = await apiJson('/pet-chat/memory', { parse: 'always' });
|
|
18840
|
-
setMemory(((resp && resp.data) || {}).memory || {});
|
|
18841
|
-
} catch { setNote({ ok: false, text: weT('读取记忆失败') }); }
|
|
18842
|
-
},
|
|
18843
|
-
}, weT('查看记忆')),
|
|
18844
|
-
React.createElement('button', {
|
|
18845
|
-
type: 'button', className: 'we-picker__btn', disabled: busy,
|
|
18846
|
-
onClick: async () => {
|
|
18847
|
-
try {
|
|
18848
|
-
await apiJson('/pet-chat/memory', { method: 'DELETE', parse: 'always' });
|
|
18849
|
-
setMemory(null);
|
|
18850
|
-
setNote({ ok: true, text: weT('记忆已清空') });
|
|
18851
|
-
} catch { setNote({ ok: false, text: weT('清空失败') }); }
|
|
18852
|
-
},
|
|
18853
|
-
}, weT('清空记忆')),
|
|
18854
|
-
));
|
|
18855
|
-
if (memory) {
|
|
18856
|
-
const parts = [];
|
|
18857
|
-
if (memory.nickname) parts.push(weT('称呼') + ':' + memory.nickname);
|
|
18858
|
-
if (Array.isArray(memory.likes) && memory.likes.length) parts.push(weT('喜欢') + ':' + memory.likes.join('、'));
|
|
18859
|
-
if (Array.isArray(memory.notes) && memory.notes.length) parts.push(weT('备注') + ':' + memory.notes.join('、'));
|
|
18860
|
-
child.push(React.createElement('div', { key: 'memoryView', className: 'we-picker__hint', style: { margin: '2px 0 6px' } }, parts.length ? parts.join(' · ') : weT('还没有记住任何偏好')));
|
|
18861
|
-
}
|
|
18862
|
-
|
|
18863
|
-
child.push(React.createElement('div', { key: 'proactive', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0', flexWrap: 'wrap' } },
|
|
18864
|
-
React.createElement('label', { style: { display: 'flex', gap: '4px', alignItems: 'center' } },
|
|
18865
|
-
React.createElement('input', { type: 'checkbox', checked: Boolean(draft.proactive && draft.proactive.enabled), disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, enabled: e.target.checked } }) }),
|
|
18866
|
-
weT('主动闲聊')),
|
|
18867
|
-
weT('每日'),
|
|
18868
|
-
React.createElement('input', { type: 'number', min: 1, max: 20, value: (draft.proactive && draft.proactive.dailyLimit) || 10, style: { width: '56px' }, disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, dailyLimit: Number(e.target.value) } }) }),
|
|
18869
|
-
weT('间隔(分)'),
|
|
18870
|
-
React.createElement('input', { type: 'number', min: 30, max: 720, value: (draft.proactive && draft.proactive.minGapMin) || 120, style: { width: '64px' }, disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, minGapMin: Number(e.target.value) } }) }),
|
|
18871
|
-
weT('夜间静默'),
|
|
18872
|
-
React.createElement('input', { type: 'text', value: (draft.proactive && draft.proactive.quietHours) || '22:00-08:00', style: { width: '110px' }, disabled: busy, onChange: (e) => update({ proactive: { ...draft.proactive, quietHours: e.target.value } }) }),
|
|
18873
|
-
));
|
|
18874
|
-
|
|
18875
|
-
child.push(React.createElement('label', { key: 'asr', style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', margin: '4px 0 8px', opacity: 0.7 } },
|
|
18876
|
-
React.createElement('input', { type: 'checkbox', checked: Boolean(draft.voiceEnabled), disabled: true }),
|
|
18877
|
-
weT('语音输入(需先在 DSH 开启)'),
|
|
18878
|
-
));
|
|
18725
|
+
React.createElement('option', { value: 'zh-CN-XiaoxiaoNeural' }, weT('晓晓(v0.2 可选)')),
|
|
18726
|
+
)));
|
|
18879
18727
|
|
|
18880
|
-
child.push(React.createElement('div', { key: 'status', className: 'we-picker__hint', style: { margin: '
|
|
18728
|
+
child.push(React.createElement('div', { key: 'status', className: 'we-picker__hint', style: { margin: '6px 0', color: status.ok === false ? '#f87171' : undefined } },
|
|
18881
18729
|
status.text || weT('未连接')));
|
|
18882
18730
|
if (note && note.text) {
|
|
18883
18731
|
child.push(React.createElement('div', { key: 'note', className: 'we-picker__hint', style: { color: note.ok ? undefined : '#f87171' } }, note.text));
|
|
@@ -20540,825 +20388,480 @@ window.__ModuleLoader__.load({
|
|
|
20540
20388
|
} catch { return () => {}; }
|
|
20541
20389
|
}
|
|
20542
20390
|
|
|
20543
|
-
// ── 内联模块:src/pet-
|
|
20391
|
+
// ── 内联模块:src/pet-voice-input.js —— 语音输入:getUserMedia + PCM 采集 + 静音 1.2s / 15s 上限 + 16k WAV + 转录 + SSE 回填(构建期注入;勿手改本段)──
|
|
20544
20392
|
/**
|
|
20545
|
-
* pet-
|
|
20393
|
+
* pet-voice-input.js — 桌宠语音输入(v0.1 核心链路)。
|
|
20546
20394
|
*
|
|
20547
|
-
*
|
|
20548
|
-
*
|
|
20549
|
-
* 朗读是叠加,不是替换(气泡 + 打字机该显示什么还显示什么)。
|
|
20550
|
-
* ② **零依赖零 token**:走系统语音(Electron 下是 Windows SAPI);没有就说没有。
|
|
20551
|
-
* ③ 与宠物"音效"开关**无关**:这里只看 `petChat.voiceOut.enabled`。
|
|
20395
|
+
* 流程:唤醒 → getUserMedia → AudioWorklet(没有就 ScriptProcessor 兜底)采 PCM
|
|
20396
|
+
* → 静音 1.2s 或满 15s 自动停 → 16kHz 单声道 WAV → /transcribe → /chat(SSE) → 气泡逐字。
|
|
20552
20397
|
*
|
|
20553
|
-
*
|
|
20554
|
-
*
|
|
20555
|
-
* · 流式增量 ⇒ `push(chunk)`,凑满句末标点就按句读(不打断打字机)。
|
|
20556
|
-
*
|
|
20557
|
-
* 为什么要做成工厂并把 speechSynthesis / Utterance 注入进来:
|
|
20558
|
-
* 判据要能 mock(`test/verify-pet-chat.mjs` 的 6 条),而渲染进程的真实实现
|
|
20559
|
-
* 就是 `window.speechSynthesis` + `window.SpeechSynthesisUtterance`。
|
|
20398
|
+
* 为什么全部注入:录音依赖浏览器 API,Node 里跑不了;把 getUserMedia / AudioContext /
|
|
20399
|
+
* 两个 HTTP 调用都做成依赖,判据就能在假实现上跑完整链路(含权限拒绝、asr-not-ready、超时)。
|
|
20560
20400
|
*/
|
|
20561
|
-
|
|
20562
|
-
|
|
20563
|
-
|
|
20564
|
-
|
|
20565
|
-
|
|
20566
|
-
|
|
20567
|
-
|
|
20568
|
-
|
|
20569
|
-
|
|
20570
|
-
const
|
|
20571
|
-
|
|
20572
|
-
const
|
|
20573
|
-
|
|
20574
|
-
|
|
20575
|
-
|
|
20576
|
-
|
|
20577
|
-
|
|
20578
|
-
|
|
20401
|
+
function petVoiceInputCreate(deps) {
|
|
20402
|
+
const options = deps || {};
|
|
20403
|
+
const getUserMedia = options.getUserMedia;
|
|
20404
|
+
const createContext = options.createContext;
|
|
20405
|
+
const postTranscribe = options.postTranscribe;
|
|
20406
|
+
const postChat = options.postChat;
|
|
20407
|
+
const now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
20408
|
+
const onText = typeof options.onText === 'function' ? options.onText : () => {};
|
|
20409
|
+
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
20410
|
+
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
20411
|
+
|
|
20412
|
+
const SILENCE_MS = 1200;
|
|
20413
|
+
const MAX_MS = 15000;
|
|
20414
|
+
const SILENCE_RMS = 0.012;
|
|
20415
|
+
|
|
20416
|
+
let ctx = null;
|
|
20417
|
+
let node = null;
|
|
20418
|
+
let stream = null;
|
|
20419
|
+
let chunks = [];
|
|
20420
|
+
let sampleRate = 48000;
|
|
20421
|
+
let startedAt = 0;
|
|
20422
|
+
let silenceSince = 0;
|
|
20423
|
+
let active = false;
|
|
20424
|
+
let finishing = false;
|
|
20425
|
+
|
|
20426
|
+
function hardStop() {
|
|
20427
|
+
try { if (node) node.disconnect(); } catch { /* ignore */ }
|
|
20428
|
+
try { if (ctx && typeof ctx.close === 'function') void ctx.close(); } catch { /* ignore */ }
|
|
20429
|
+
try { if (stream && stream.getTracks) stream.getTracks().forEach((track) => track.stop()); } catch { /* ignore */ }
|
|
20430
|
+
ctx = null; node = null; stream = null;
|
|
20431
|
+
}
|
|
20432
|
+
|
|
20433
|
+
/** Float32 PCM → 16kHz 单声道 PCM16 WAV(44 字节头自写)。 */
|
|
20434
|
+
function encodeWav(samples, rate) {
|
|
20435
|
+
const target = 16000;
|
|
20436
|
+
const ratio = rate / target;
|
|
20437
|
+
const frames = Math.max(1, Math.floor(samples.length / ratio));
|
|
20438
|
+
const buffer = new ArrayBuffer(44 + frames * 2);
|
|
20439
|
+
const view = new DataView(buffer);
|
|
20440
|
+
const put = (offset, text) => { for (let i = 0; i < text.length; i += 1) view.setUint8(offset + i, text.charCodeAt(i)); };
|
|
20441
|
+
put(0, 'RIFF'); view.setUint32(4, 36 + frames * 2, true); put(8, 'WAVE');
|
|
20442
|
+
put(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
|
|
20443
|
+
view.setUint32(24, target, true); view.setUint32(28, target * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
|
|
20444
|
+
put(36, 'data'); view.setUint32(40, frames * 2, true);
|
|
20445
|
+
let offset = 44;
|
|
20446
|
+
for (let i = 0; i < frames; i += 1) {
|
|
20447
|
+
const index = Math.min(samples.length - 1, Math.floor(i * ratio));
|
|
20448
|
+
const value = Math.max(-1, Math.min(1, samples[index] || 0));
|
|
20449
|
+
view.setInt16(offset, value < 0 ? value * 0x8000 : value * 0x7fff, true);
|
|
20450
|
+
offset += 2;
|
|
20451
|
+
}
|
|
20452
|
+
return new Uint8Array(buffer);
|
|
20453
|
+
}
|
|
20454
|
+
|
|
20455
|
+
function base64(bytes) {
|
|
20456
|
+
let binary = '';
|
|
20457
|
+
for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
|
|
20458
|
+
if (typeof btoa === 'function') return btoa(binary);
|
|
20459
|
+
return Buffer.from(bytes).toString('base64');
|
|
20460
|
+
}
|
|
20461
|
+
|
|
20462
|
+
/** 静音判定:连续 SILENCE_MS 低于阈值 ⇒ 认为说完(每帧 update)。 */
|
|
20463
|
+
function feed(samples) {
|
|
20464
|
+
if (!active || finishing) return;
|
|
20465
|
+
chunks.push(samples);
|
|
20466
|
+
let sum = 0;
|
|
20467
|
+
for (let i = 0; i < samples.length; i += 1) sum += samples[i] * samples[i];
|
|
20468
|
+
const rms = Math.sqrt(sum / Math.max(1, samples.length));
|
|
20469
|
+
const at = now();
|
|
20470
|
+
if (rms < SILENCE_RMS) {
|
|
20471
|
+
if (!silenceSince) silenceSince = at;
|
|
20472
|
+
if (at - silenceSince >= SILENCE_MS) void finish('silence');
|
|
20473
|
+
} else {
|
|
20474
|
+
silenceSince = 0;
|
|
20475
|
+
}
|
|
20476
|
+
if (at - startedAt >= MAX_MS) void finish('max');
|
|
20477
|
+
}
|
|
20478
|
+
|
|
20479
|
+
async function finish(reason) {
|
|
20480
|
+
if (!active || finishing) return;
|
|
20481
|
+
finishing = true;
|
|
20482
|
+
active = false;
|
|
20483
|
+
onState({ state: 'transcribing', reason });
|
|
20484
|
+
const merged = chunks.reduce((acc, item) => acc + item.length, 0);
|
|
20485
|
+
const samples = new Float32Array(merged);
|
|
20486
|
+
let offset = 0;
|
|
20487
|
+
for (const chunk of chunks) { samples.set(chunk, offset); offset += chunk.length; }
|
|
20488
|
+
chunks = [];
|
|
20489
|
+
hardStop();
|
|
20490
|
+
const wav = encodeWav(samples, sampleRate);
|
|
20491
|
+
try {
|
|
20492
|
+
const result = await postTranscribe(base64(wav));
|
|
20493
|
+
const doc = result || {};
|
|
20494
|
+
if (doc.ok !== true) {
|
|
20495
|
+
onError({ code: doc.code || 'transcribe-failed', message: doc.hint || '' });
|
|
20496
|
+
return;
|
|
20497
|
+
}
|
|
20498
|
+
onText(String(doc.text || ''));
|
|
20499
|
+
if (typeof postChat === 'function' && doc.text) await postChat(String(doc.text), onState);
|
|
20500
|
+
} catch (error) {
|
|
20501
|
+
onError({ code: (error && error.code) || 'network', message: String((error && error.message) || error) });
|
|
20502
|
+
} finally {
|
|
20503
|
+
finishing = false;
|
|
20579
20504
|
}
|
|
20580
20505
|
}
|
|
20581
|
-
|
|
20582
|
-
|
|
20583
|
-
|
|
20584
|
-
|
|
20585
|
-
|
|
20586
|
-
|
|
20587
|
-
|
|
20588
|
-
|
|
20589
|
-
|
|
20506
|
+
|
|
20507
|
+
async function start() {
|
|
20508
|
+
if (active) return true;
|
|
20509
|
+
onState({ state: 'listening' });
|
|
20510
|
+
try {
|
|
20511
|
+
stream = await getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } });
|
|
20512
|
+
} catch {
|
|
20513
|
+
onError({ code: 'permission', message: '没有麦克风权限' });
|
|
20514
|
+
return false;
|
|
20590
20515
|
}
|
|
20591
|
-
|
|
20516
|
+
try {
|
|
20517
|
+
const created = createContext(stream);
|
|
20518
|
+
ctx = created.context;
|
|
20519
|
+
sampleRate = Number(created.sampleRate) || 48000;
|
|
20520
|
+
node = created.node;
|
|
20521
|
+
node.onaudioprocess = (event) => {
|
|
20522
|
+
const data = event && event.inputBuffer ? event.inputBuffer.getChannelData(0) : null;
|
|
20523
|
+
if (data) feed(data);
|
|
20524
|
+
};
|
|
20525
|
+
node.connect(ctx.destination);
|
|
20526
|
+
} catch {
|
|
20527
|
+
onError({ code: 'no-mic', message: '打不开麦克风' });
|
|
20528
|
+
hardStop();
|
|
20529
|
+
return false;
|
|
20530
|
+
}
|
|
20531
|
+
active = true;
|
|
20532
|
+
startedAt = now();
|
|
20533
|
+
silenceSince = 0;
|
|
20534
|
+
return true;
|
|
20592
20535
|
}
|
|
20593
|
-
return final;
|
|
20594
|
-
}
|
|
20595
20536
|
|
|
20596
|
-
|
|
20597
|
-
|
|
20598
|
-
|
|
20599
|
-
|
|
20600
|
-
|
|
20601
|
-
|
|
20537
|
+
function stop() {
|
|
20538
|
+
if (!active) return;
|
|
20539
|
+
active = false;
|
|
20540
|
+
hardStop();
|
|
20541
|
+
onState({ state: 'idle' });
|
|
20542
|
+
}
|
|
20543
|
+
|
|
20544
|
+
return { start, stop, feed, finish, isActive: () => active, encodeWav };
|
|
20602
20545
|
}
|
|
20603
20546
|
|
|
20547
|
+
// ── 内联模块:src/pet-bubble.js —— 头顶气泡:锚定桌宠头顶、跟随位置/缩放、逐字显示、最多 6 行、朗读结束 +3s 淡出(构建期注入;勿手改本段)──
|
|
20604
20548
|
/**
|
|
20605
|
-
*
|
|
20549
|
+
* pet-bubble.js — 头顶气泡(v0.1 S2)。
|
|
20550
|
+
*
|
|
20551
|
+
* 与旧面板的区别:**只显示**,不承载输入框 / 历史列表 / 关闭按钮;输入走右键「打字说…」,
|
|
20552
|
+
* 语音走唤醒链路(S3)。这样做是因为旧面板把"窗口"和"助手"混在一起,
|
|
20553
|
+
* 用户点桌宠时弹出一个像聊天软件的窗口,与"桌宠在旁边说话"的产品形态冲突。
|
|
20606
20554
|
*
|
|
20607
|
-
*
|
|
20608
|
-
*
|
|
20609
|
-
* @param {() => any[]} deps.getVoices 返回音色列表(可能为空)
|
|
20610
|
-
* @param {() => object} deps.getConfig 返回 `{ enabled, rate, pitch, volume, voiceURI }`
|
|
20611
|
-
* @param {Function} [deps.Utterance] `SpeechSynthesisUtterance` 构造器
|
|
20612
|
-
* @param {(code:string, message:string) => void} [deps.onHint] 一次性提示回调
|
|
20555
|
+
* 依赖全部注入(document / 定时器 / 锚点),这样 Node 里能用假 DOM 跑判据;
|
|
20556
|
+
* 浏览器侧由 pet-chat.js 用真实 window 构造。
|
|
20613
20557
|
*/
|
|
20614
|
-
function
|
|
20558
|
+
function petBubbleCreate(deps) {
|
|
20615
20559
|
const options = deps || {};
|
|
20616
|
-
const
|
|
20617
|
-
|
|
20618
|
-
|
|
20619
|
-
const
|
|
20620
|
-
|
|
20621
|
-
|
|
20622
|
-
|
|
20623
|
-
|
|
20624
|
-
|
|
20625
|
-
|
|
20626
|
-
|
|
20627
|
-
|
|
20628
|
-
|
|
20629
|
-
|
|
20630
|
-
|
|
20560
|
+
const doc = options.document;
|
|
20561
|
+
// 没有定时器的环境(极简 DOM 替身的冒烟测试)不能因为裸 setTimeout 直接炸:
|
|
20562
|
+
// 退化成立即执行 / 空取消,气泡仍能显示,只是没有延迟淡出。
|
|
20563
|
+
const setTimer = typeof options.setTimeout === 'function'
|
|
20564
|
+
? options.setTimeout
|
|
20565
|
+
: (typeof setTimeout === 'function' ? setTimeout : (fn) => { if (typeof fn === 'function') fn(); return 0; });
|
|
20566
|
+
const clearTimer = typeof options.clearTimeout === 'function'
|
|
20567
|
+
? options.clearTimeout
|
|
20568
|
+
: (typeof clearTimeout === 'function' ? clearTimeout : () => {});
|
|
20569
|
+
const getAnchor = typeof options.getAnchor === 'function' ? options.getAnchor : () => null;
|
|
20570
|
+
/** 最多显示几行(超出用 CSS 行钳制,见 lineClamp 样式)。 */
|
|
20571
|
+
const MAX_LINES = 6;
|
|
20572
|
+
|
|
20573
|
+
let el = null;
|
|
20574
|
+
let text = '';
|
|
20575
|
+
let visible = false;
|
|
20576
|
+
let fadeTimer = null;
|
|
20577
|
+
|
|
20578
|
+
/** 锚点 → 气泡位置:水平居中于桌宠,垂直贴在头顶上方。 */
|
|
20579
|
+
function place() {
|
|
20580
|
+
if (!el) return;
|
|
20581
|
+
const anchor = getAnchor();
|
|
20582
|
+
if (!anchor) return;
|
|
20583
|
+
const width = Number(anchor.width) || 0;
|
|
20584
|
+
const height = Number(anchor.height) || 0;
|
|
20585
|
+
const left = Math.round(Number(anchor.left || 0) + width / 2);
|
|
20586
|
+
const top = Math.round(Number(anchor.top || 0) - 8);
|
|
20587
|
+
el.style.left = `${left}px`;
|
|
20588
|
+
el.style.top = `${top}px`;
|
|
20589
|
+
// 锚点也跟着缩放:桌宠放大时气泡不要贴在旧位置
|
|
20590
|
+
el.style.transform = `translate(-50%, -100%) scale(${Number(anchor.scale) || 1})`;
|
|
20591
|
+
}
|
|
20592
|
+
|
|
20593
|
+
function ensure() {
|
|
20594
|
+
if (el || !doc || typeof doc.createElement !== 'function') return el;
|
|
20595
|
+
el = doc.createElement('div');
|
|
20596
|
+
el.className = 'we-pet-bubble';
|
|
20597
|
+
el.style.position = 'fixed';
|
|
20598
|
+
el.style.zIndex = '9999';
|
|
20599
|
+
el.style.maxWidth = '260px';
|
|
20600
|
+
el.style.padding = '8px 10px';
|
|
20601
|
+
el.style.borderRadius = '12px';
|
|
20602
|
+
el.style.background = 'rgba(24,24,28,.92)';
|
|
20603
|
+
el.style.color = '#f2f2f5';
|
|
20604
|
+
el.style.fontSize = '12px';
|
|
20605
|
+
el.style.lineHeight = '1.5';
|
|
20606
|
+
el.style.pointerEvents = 'none';
|
|
20607
|
+
el.style.opacity = '0';
|
|
20608
|
+
el.style.transition = 'opacity .18s ease';
|
|
20609
|
+
// 超过 6 行省略:气泡永远不长大到挡住桌宠
|
|
20610
|
+
el.style.display = '-webkit-box';
|
|
20611
|
+
el.style.webkitLineClamp = String(MAX_LINES);
|
|
20612
|
+
el.style.webkitBoxOrient = 'vertical';
|
|
20613
|
+
el.style.overflow = 'hidden';
|
|
20614
|
+
el.style.whiteSpace = 'pre-wrap';
|
|
20615
|
+
if (doc.body && typeof doc.body.appendChild === 'function') doc.body.appendChild(el);
|
|
20616
|
+
return el;
|
|
20617
|
+
}
|
|
20631
20618
|
|
|
20632
|
-
|
|
20633
|
-
|
|
20634
|
-
const list = Array.isArray(voices) ? voices : [];
|
|
20635
|
-
const wanted = String(config.voiceURI || '').trim();
|
|
20636
|
-
if (wanted) {
|
|
20637
|
-
const hit = list.find((voice) => voice && (voice.voiceURI === wanted || voice.name === wanted));
|
|
20638
|
-
if (hit) return hit;
|
|
20639
|
-
}
|
|
20640
|
-
const chinese = list.find((voice) => petChatTtsIsChinese(voice));
|
|
20641
|
-
if (chinese) return chinese;
|
|
20642
|
-
if (list.length) hintOnce('no-chinese-voice', '系统里没有中文音色,朗读可能不自然');
|
|
20643
|
-
return null;
|
|
20619
|
+
function cancelFade() {
|
|
20620
|
+
if (fadeTimer != null) { clearTimer(fadeTimer); fadeTimer = null; }
|
|
20644
20621
|
}
|
|
20645
20622
|
|
|
20646
|
-
/**
|
|
20647
|
-
function
|
|
20648
|
-
|
|
20649
|
-
|
|
20650
|
-
|
|
20651
|
-
|
|
20652
|
-
|
|
20653
|
-
|
|
20654
|
-
|
|
20655
|
-
const voice = pickVoice(config, voices);
|
|
20656
|
-
if (voice) utterance.voice = voice;
|
|
20657
|
-
speech.speak(utterance);
|
|
20658
|
-
if (!hintShown['first-speak']) {
|
|
20659
|
-
hintShown['first-speak'] = true;
|
|
20660
|
-
hintOnce('first-speak', '使用系统语音,无需下载 / 不耗 token');
|
|
20661
|
-
}
|
|
20662
|
-
return true;
|
|
20623
|
+
/** 显示(或继续显示)一段文本;重复调用会重排文本而不是叠出第二个气泡。 */
|
|
20624
|
+
function show(nextText) {
|
|
20625
|
+
if (!ensure()) return;
|
|
20626
|
+
cancelFade();
|
|
20627
|
+
text = String(nextText == null ? '' : nextText);
|
|
20628
|
+
el.textContent = text;
|
|
20629
|
+
el.style.opacity = '1';
|
|
20630
|
+
visible = true;
|
|
20631
|
+
place();
|
|
20663
20632
|
}
|
|
20664
20633
|
|
|
20665
|
-
/**
|
|
20666
|
-
function
|
|
20667
|
-
|
|
20668
|
-
|
|
20669
|
-
|
|
20634
|
+
/** 逐字/逐段追加(SSE 每个 chunk 调一次)。 */
|
|
20635
|
+
function append(chunk) {
|
|
20636
|
+
if (!ensure()) return;
|
|
20637
|
+
cancelFade();
|
|
20638
|
+
text += String(chunk == null ? '' : chunk);
|
|
20639
|
+
el.textContent = text;
|
|
20640
|
+
el.style.opacity = '1';
|
|
20641
|
+
visible = true;
|
|
20642
|
+
place();
|
|
20670
20643
|
}
|
|
20671
20644
|
|
|
20672
|
-
/**
|
|
20673
|
-
function
|
|
20674
|
-
|
|
20675
|
-
|
|
20676
|
-
|
|
20677
|
-
|
|
20678
|
-
|
|
20679
|
-
|
|
20680
|
-
|
|
20681
|
-
|
|
20682
|
-
|
|
20683
|
-
|
|
20684
|
-
const text = String(chunk ?? '');
|
|
20685
|
-
if (!text) return;
|
|
20686
|
-
pending += text;
|
|
20687
|
-
const sentences = petChatTtsSplit(pending);
|
|
20688
|
-
// 只有"以标点结尾"的才算成句;最后一段若不以标点结尾,留到下次
|
|
20689
|
-
const endsWithPunct = PET_CHAT_TTS_SENTENCE_END.test(pending.slice(-1));
|
|
20690
|
-
const ready = endsWithPunct ? sentences : sentences.slice(0, -1);
|
|
20691
|
-
if (!ready.length) return;
|
|
20692
|
-
if (endsWithPunct) pending = '';
|
|
20693
|
-
else pending = sentences[sentences.length - 1] || '';
|
|
20694
|
-
const voices = getVoices();
|
|
20695
|
-
for (const sentence of ready) if (speakOne(sentence, speech, config, voices)) spokenInTurn += 1;
|
|
20645
|
+
/** 隐藏;带 delay 时先挂着,到点淡出(朗读结束后 +3s 用这个)。 */
|
|
20646
|
+
function hide(delayMs) {
|
|
20647
|
+
if (!el) return;
|
|
20648
|
+
cancelFade();
|
|
20649
|
+
const delay = Number(delayMs) || 0;
|
|
20650
|
+
const doHide = () => {
|
|
20651
|
+
fadeTimer = null;
|
|
20652
|
+
el.style.opacity = '0';
|
|
20653
|
+
visible = false;
|
|
20654
|
+
};
|
|
20655
|
+
if (delay > 0) { fadeTimer = setTimer(doHide, delay); return; }
|
|
20656
|
+
doHide();
|
|
20696
20657
|
}
|
|
20697
20658
|
|
|
20698
|
-
/**
|
|
20699
|
-
|
|
20700
|
-
|
|
20701
|
-
|
|
20702
|
-
|
|
20703
|
-
|
|
20704
|
-
|
|
20705
|
-
|
|
20706
|
-
|
|
20707
|
-
|
|
20708
|
-
|
|
20709
|
-
|
|
20710
|
-
|
|
20711
|
-
|
|
20712
|
-
|
|
20713
|
-
if (whole.trim()) speakOne(whole.trim(), speech, config, voices);
|
|
20714
|
-
return;
|
|
20715
|
-
}
|
|
20716
|
-
if (tail.trim()) speakOne(tail.trim(), speech, config, voices);
|
|
20659
|
+
/** 状态:听 / 想 / 答(客户端据此换桌宠动作、给气泡配色)。 */
|
|
20660
|
+
function setState(kind) {
|
|
20661
|
+
if (!el) return;
|
|
20662
|
+
el.dataset = el.dataset || {};
|
|
20663
|
+
el.dataset.state = String(kind || '');
|
|
20664
|
+
}
|
|
20665
|
+
|
|
20666
|
+
function isVisible() { return visible; }
|
|
20667
|
+
|
|
20668
|
+
function dispose() {
|
|
20669
|
+
cancelFade();
|
|
20670
|
+
if (el && typeof el.remove === 'function') el.remove();
|
|
20671
|
+
el = null;
|
|
20672
|
+
text = '';
|
|
20673
|
+
visible = false;
|
|
20717
20674
|
}
|
|
20718
20675
|
|
|
20719
|
-
return {
|
|
20676
|
+
return {
|
|
20677
|
+
show, append, hide, setState, place, isVisible, dispose,
|
|
20678
|
+
// 判据要读的内部状态
|
|
20679
|
+
get text() { return text; },
|
|
20680
|
+
get element() { return el; },
|
|
20681
|
+
MAX_LINES,
|
|
20682
|
+
};
|
|
20720
20683
|
}
|
|
20721
20684
|
|
|
20722
|
-
// ── 内联模块:src/pet-chat.js ——
|
|
20685
|
+
// ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
|
|
20723
20686
|
/**
|
|
20724
|
-
* pet-chat.js
|
|
20687
|
+
* pet-chat.js — 桌宠语音助手(v0.1 客户端)。
|
|
20725
20688
|
*
|
|
20726
|
-
*
|
|
20727
|
-
*
|
|
20728
|
-
* · 回复走 SSE(delta 逐字追加),done 里带 emotion → 映射成宠物动作
|
|
20729
|
-
* · 设置里没开(enabled=false)⇒ 不谈模型,直接给**预设台词库**(30+ 句,按情绪分组)
|
|
20689
|
+
* v0.1 范围(docs/PET-V01-ACCEPTANCE.md):**语音输入 + 头顶文字气泡 + 名字/记忆 + 主动搭话**,
|
|
20690
|
+
* **不含任何朗读/TTS**(v0.2 再做)。所以这里没有 speechSynthesis、没有 /pet-chat/speak 调用。
|
|
20730
20691
|
*
|
|
20731
|
-
*
|
|
20732
|
-
*
|
|
20733
|
-
*
|
|
20734
|
-
* 不变量:
|
|
20735
|
-
* · **不碰模型的 key**:key 只在宿主设置里,客户端连读都不读。
|
|
20736
|
-
* · **不自己拼模型端点**:所有请求都打本机 `/folia/pet-chat/*`。
|
|
20737
|
-
* · 气泡是 `position: fixed` 的独立层,不参与面板重渲染(与 pet-layer 同一套思路)。
|
|
20738
|
-
*/
|
|
20739
|
-
/**
|
|
20740
|
-
* 预设台词库(工单 A4):**五组 ≥30 句**。
|
|
20741
|
-
* `enabled=false`(没配模型)与宿主回 `no-model` 两条路径都从这里取,按组轮换。
|
|
20692
|
+
* 交互:点桌宠 = 唤醒 → 气泡显示它的话(3 秒后淡出,点一下立刻收起)。
|
|
20693
|
+
* 没有聊天窗口:无输入框、无历史列表、无开关按钮。
|
|
20742
20694
|
*/
|
|
20743
20695
|
const PET_CHAT_PRESET_LINES = {
|
|
20744
|
-
|
|
20745
|
-
|
|
20746
|
-
|
|
20696
|
+
greeting: [
|
|
20697
|
+
'我在呢。',
|
|
20698
|
+
'叫我就来。',
|
|
20699
|
+
'嗯?我在听。',
|
|
20700
|
+
'你回来啦。',
|
|
20701
|
+
'有我在,别急。',
|
|
20702
|
+
'今天想聊点什么?',
|
|
20703
|
+
],
|
|
20747
20704
|
wallpaper: [
|
|
20748
|
-
'
|
|
20749
|
-
'
|
|
20750
|
-
'
|
|
20705
|
+
'要不要换张壁纸?',
|
|
20706
|
+
'这张看久了,换一张吧。',
|
|
20707
|
+
'桌面有点暗,换个亮一点的?',
|
|
20708
|
+
'轮播开着,让它自己换吧。',
|
|
20709
|
+
'我给你挑一张安静的。',
|
|
20710
|
+
'这张当壁纸挺合适。',
|
|
20711
|
+
'换张清爽的,眼睛舒服点。',
|
|
20712
|
+
'需要我记住你喜欢的风格吗?',
|
|
20751
20713
|
],
|
|
20752
|
-
// 陪伴与鼓励(8)
|
|
20753
20714
|
company: [
|
|
20754
|
-
'
|
|
20755
|
-
'
|
|
20756
|
-
'
|
|
20715
|
+
'我在这儿待着。',
|
|
20716
|
+
'忙你的,我不吵。',
|
|
20717
|
+
'要喝水吗?我提醒你。',
|
|
20718
|
+
'坐久了,起来动一动。',
|
|
20719
|
+
'累了就歇会儿。',
|
|
20720
|
+
'今天也辛苦了。',
|
|
20721
|
+
'我陪着你。',
|
|
20722
|
+
'慢慢来,不急。',
|
|
20757
20723
|
],
|
|
20758
|
-
// 空状态与失败兜底(5)
|
|
20759
20724
|
fallback: [
|
|
20760
|
-
'
|
|
20761
|
-
'
|
|
20725
|
+
'这个我还不会,等我学学。',
|
|
20726
|
+
'没听清,再说一次?',
|
|
20727
|
+
'换个说法试试?',
|
|
20728
|
+
'我先记下来。',
|
|
20729
|
+
'这个得你来定。',
|
|
20730
|
+
],
|
|
20731
|
+
night: [
|
|
20732
|
+
'夜深了,早点睡。',
|
|
20733
|
+
'我先安静一会儿。',
|
|
20734
|
+
'明天见。',
|
|
20762
20735
|
],
|
|
20763
|
-
// 夜间(3)
|
|
20764
|
-
night: ['夜深了,早点休息。', '要不要换张暗一点的壁纸?', '我先趴一会儿,晚安。'],
|
|
20765
20736
|
};
|
|
20766
20737
|
|
|
20767
|
-
/**
|
|
20768
|
-
const PET_CHAT_EMOTION_TRACK = { happy: 'wave', tired: 'sleep', angry: 'idle', calm: 'idle' };
|
|
20769
|
-
/** 气泡里保留的最近条数(工单:最近 6 条)。 */
|
|
20770
|
-
const PET_CHAT_KEEP_LINES = 6;
|
|
20771
|
-
|
|
20772
|
-
|
|
20773
|
-
/** 极简 DOM 替身可能没有 append / addEventListener:统一走这两个助手,坏环境里安静跳过。 */
|
|
20774
|
-
function petChatAppend(el, ...kids) {
|
|
20775
|
-
if (!el) return;
|
|
20776
|
-
if (typeof el.append === 'function') { el.append(...kids); return; }
|
|
20777
|
-
if (typeof el.appendChild === 'function') { for (const kid of kids) el.appendChild(kid); }
|
|
20778
|
-
}
|
|
20779
|
-
function petChatOn(el, type, fn) {
|
|
20780
|
-
if (el && typeof el.addEventListener === 'function') el.addEventListener(type, fn);
|
|
20781
|
-
}
|
|
20782
|
-
|
|
20783
|
-
let petChatEls = null;
|
|
20784
|
-
let petChatLines = [];
|
|
20785
|
-
let petChatBusy = false;
|
|
20786
|
-
|
|
20787
|
-
/** 气泡 DOM(懒建:不点宠物就不建,免得影响启动)。 */
|
|
20788
|
-
function petChatBuild() {
|
|
20789
|
-
if (petChatEls) return petChatEls;
|
|
20790
|
-
try {
|
|
20791
|
-
const root = document.createElement('div');
|
|
20792
|
-
root.id = 'we-pet-chat';
|
|
20793
|
-
root.style.cssText = [
|
|
20794
|
-
'position:fixed', 'right:24px', 'bottom:172px', 'width:320px', 'max-height:420px',
|
|
20795
|
-
'display:none', 'flex-direction:column', 'gap:8px', 'padding:12px', 'z-index:2147483000',
|
|
20796
|
-
'background:rgba(24,24,28,.92)', 'color:#f2f2f5', 'border:1px solid rgba(255,255,255,.12)',
|
|
20797
|
-
'border-radius:14px', 'box-shadow:0 12px 32px rgba(0,0,0,.45)', 'backdrop-filter:blur(10px)',
|
|
20798
|
-
'font-size:13px', 'line-height:1.5',
|
|
20799
|
-
].join(';');
|
|
20800
|
-
|
|
20801
|
-
const head = document.createElement('div');
|
|
20802
|
-
head.style.cssText = 'display:flex;align-items:center;justify-content:space-between;gap:8px';
|
|
20803
|
-
const title = document.createElement('strong');
|
|
20804
|
-
title.textContent = weT('桌宠对话');
|
|
20805
|
-
const tools = document.createElement('div');
|
|
20806
|
-
tools.style.cssText = 'display:flex;align-items:center;gap:6px';
|
|
20807
|
-
// 麦克风:**按住说话**(pointerdown 开始 / pointerup 或移出结束),松手上传
|
|
20808
|
-
const voiceBtn = document.createElement('button');
|
|
20809
|
-
voiceBtn.type = 'button';
|
|
20810
|
-
voiceBtn.textContent = weT('按住说话');
|
|
20811
|
-
voiceBtn.title = weT('按住说话,松手识别(需先在 DSH 开启语音输入)');
|
|
20812
|
-
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';
|
|
20813
|
-
petChatOn(voiceBtn, 'pointerdown', (event) => { if (event && event.preventDefault) event.preventDefault(); void petChatVoiceStart(); });
|
|
20814
|
-
petChatOn(voiceBtn, 'pointerup', () => { void petChatVoiceStop(); });
|
|
20815
|
-
petChatOn(voiceBtn, 'pointerleave', () => { if (petChatVoice) void petChatVoiceStop(); });
|
|
20816
|
-
// 停止朗读:只停语音,不动文字(文字已经显示在气泡里)
|
|
20817
|
-
const stopBtn = document.createElement('button');
|
|
20818
|
-
stopBtn.type = 'button';
|
|
20819
|
-
stopBtn.textContent = weT('停止朗读');
|
|
20820
|
-
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';
|
|
20821
|
-
petChatOn(stopBtn, 'click', () => petChatTts.cancel());
|
|
20822
|
-
const memoryBtn = document.createElement('button');
|
|
20823
|
-
memoryBtn.type = 'button';
|
|
20824
|
-
memoryBtn.textContent = weT('查看记忆');
|
|
20825
|
-
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';
|
|
20826
|
-
petChatOn(memoryBtn, 'click', () => petChatShowMemory());
|
|
20827
|
-
const clear = document.createElement('button');
|
|
20828
|
-
clear.type = 'button';
|
|
20829
|
-
clear.textContent = weT('清空记忆');
|
|
20830
|
-
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';
|
|
20831
|
-
petChatOn(clear, 'click', () => petChatResetMemory());
|
|
20832
|
-
const close = document.createElement('button');
|
|
20833
|
-
close.type = 'button';
|
|
20834
|
-
close.textContent = '×';
|
|
20835
|
-
close.title = weT('关闭');
|
|
20836
|
-
close.style.cssText = 'background:none;border:0;color:#c9c9d1;font-size:18px;cursor:pointer;line-height:1';
|
|
20837
|
-
petChatOn(close, 'click', () => petChatHide());
|
|
20838
|
-
petChatAppend(tools, voiceBtn, stopBtn, memoryBtn, clear, close);
|
|
20839
|
-
petChatAppend(head, title, tools);
|
|
20840
|
-
|
|
20841
|
-
const log = document.createElement('div');
|
|
20842
|
-
log.style.cssText = 'flex:1 1 auto;overflow:auto;display:flex;flex-direction:column;gap:6px;min-height:80px';
|
|
20843
|
-
|
|
20844
|
-
// C2:今日已说 N/10 + 「今天别说了」(只有开启主动闲聊时才显示整行)
|
|
20845
|
-
const usage = document.createElement('div');
|
|
20846
|
-
usage.style.cssText = 'display:none;align-items:center;justify-content:space-between;gap:6px;font-size:11px;color:#9a9aa5';
|
|
20847
|
-
const usageText = document.createElement('span');
|
|
20848
|
-
const skipBtn = document.createElement('button');
|
|
20849
|
-
skipBtn.type = 'button';
|
|
20850
|
-
skipBtn.textContent = weT('今天别说了');
|
|
20851
|
-
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';
|
|
20852
|
-
petChatOn(skipBtn, 'click', () => petChatSkipToday());
|
|
20853
|
-
petChatAppend(usage, usageText, skipBtn);
|
|
20854
|
-
|
|
20855
|
-
const status = document.createElement('div');
|
|
20856
|
-
status.style.cssText = 'font-size:11px;color:#9a9aa5;min-height:14px';
|
|
20857
|
-
|
|
20858
|
-
const row = document.createElement('div');
|
|
20859
|
-
row.style.cssText = 'display:flex;gap:6px';
|
|
20860
|
-
const input = document.createElement('input');
|
|
20861
|
-
input.type = 'text';
|
|
20862
|
-
input.placeholder = weT('和我说点什么…');
|
|
20863
|
-
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';
|
|
20864
|
-
const send = document.createElement('button');
|
|
20865
|
-
send.type = 'button';
|
|
20866
|
-
send.textContent = weT('发送');
|
|
20867
|
-
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';
|
|
20868
|
-
petChatOn(send, 'click', () => petChatSend());
|
|
20869
|
-
petChatOn(input, 'keydown', (event) => {
|
|
20870
|
-
if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); petChatSend(); }
|
|
20871
|
-
});
|
|
20872
|
-
petChatAppend(row, input, send);
|
|
20873
|
-
|
|
20874
|
-
petChatAppend(root, head, usage, log, status, row);
|
|
20875
|
-
petChatAppend(document.body, root);
|
|
20876
|
-
petChatEls = { root, log, status, input, send, usage, usageText };
|
|
20877
|
-
return petChatEls;
|
|
20878
|
-
} catch {
|
|
20879
|
-
// 替身 DOM 撑不起这套结构:当成"没有气泡",不影响其它功能
|
|
20880
|
-
return null;
|
|
20881
|
-
}
|
|
20882
|
-
}
|
|
20883
|
-
|
|
20884
|
-
/** 渲染最近 N 条(role=user 靠右、assistant 靠左)。 */
|
|
20885
|
-
function petChatRender() {
|
|
20886
|
-
const els = petChatBuild();
|
|
20887
|
-
if (!els) return;
|
|
20888
|
-
els.log.textContent = '';
|
|
20889
|
-
for (const line of petChatLines) {
|
|
20890
|
-
const bubble = document.createElement('div');
|
|
20891
|
-
bubble.textContent = line.text;
|
|
20892
|
-
bubble.style.cssText = 'max-width:86%;padding:6px 9px;border-radius:10px;white-space:pre-wrap;word-break:break-word;'
|
|
20893
|
-
+ (line.role === 'user'
|
|
20894
|
-
? 'align-self:flex-end;background:rgba(124,92,255,.42)'
|
|
20895
|
-
: 'align-self:flex-start;background:rgba(255,255,255,.08)');
|
|
20896
|
-
els.log.appendChild(bubble);
|
|
20897
|
-
}
|
|
20898
|
-
els.log.scrollTop = els.log.scrollHeight;
|
|
20899
|
-
}
|
|
20900
|
-
|
|
20901
|
-
function petChatPush(role, text) {
|
|
20902
|
-
petChatLines.push({ role, text });
|
|
20903
|
-
if (petChatLines.length > PET_CHAT_KEEP_LINES) petChatLines = petChatLines.slice(-PET_CHAT_KEEP_LINES);
|
|
20904
|
-
petChatRender();
|
|
20905
|
-
}
|
|
20906
|
-
|
|
20907
|
-
function petChatStatus(text) {
|
|
20908
|
-
const els = petChatBuild();
|
|
20909
|
-
if (!els) return;
|
|
20910
|
-
els.status.textContent = text || '';
|
|
20911
|
-
}
|
|
20912
|
-
|
|
20913
|
-
function petChatShow() {
|
|
20914
|
-
// 「关闭对话」时点宠物**不弹气泡**(判据⑥):开关是显式 false 才拦,
|
|
20915
|
-
// 还没探测过(null)时照常打开 —— 首次点击要能触发一次 /state 探测。
|
|
20916
|
-
if (petChatVoiceOut && petChatChatEnabled === false) return;
|
|
20917
|
-
const els = petChatBuild();
|
|
20918
|
-
if (!els) return;
|
|
20919
|
-
els.root.style.display = 'flex';
|
|
20920
|
-
if (typeof els.input.focus === 'function') els.input.focus();
|
|
20921
|
-
petChatSyncState();
|
|
20922
|
-
petChatRefreshUsage();
|
|
20923
|
-
}
|
|
20924
|
-
|
|
20925
|
-
function petChatHide() {
|
|
20926
|
-
if (!petChatEls) return;
|
|
20927
|
-
petChatTts.cancel(); // 关闭气泡:立刻停读
|
|
20928
|
-
if (petChatAudioPlayer) { try { petChatAudioPlayer.pause(); } catch { /* ignore */ } petChatAudioPlayer = null; }
|
|
20929
|
-
petChatEls.root.style.display = 'none';
|
|
20930
|
-
}
|
|
20931
|
-
|
|
20932
|
-
function petChatToggle() {
|
|
20933
|
-
const els = petChatBuild();
|
|
20934
|
-
if (!els) return;
|
|
20935
|
-
if (els.root.style.display === 'none' || !els.root.style.display) petChatShow();
|
|
20936
|
-
else petChatHide();
|
|
20937
|
-
}
|
|
20938
|
-
|
|
20939
|
-
/** 五组台词按顺序轮换(同一次会话里不重复同一组,比纯随机更像"有人在")。 */
|
|
20738
|
+
/** 轮流取一句预设台词(分组轮换,避免总说同一组)。 */
|
|
20940
20739
|
let petChatPresetCursor = 0;
|
|
20740
|
+
const PET_CHAT_PRESET_ORDER = ['greeting', 'wallpaper', 'company', 'fallback', 'night'];
|
|
20941
20741
|
function petChatPresetLine() {
|
|
20942
|
-
const
|
|
20943
|
-
const group = groups[petChatPresetCursor % groups.length];
|
|
20742
|
+
const group = PET_CHAT_PRESET_LINES[PET_CHAT_PRESET_ORDER[petChatPresetCursor % PET_CHAT_PRESET_ORDER.length]];
|
|
20944
20743
|
petChatPresetCursor += 1;
|
|
20945
|
-
|
|
20946
|
-
return lines[Math.floor(Math.random() * lines.length)] || '……';
|
|
20947
|
-
}
|
|
20948
|
-
|
|
20949
|
-
/** A2:清空记忆(宿主那边清会话记忆 + 长期偏好)。 */
|
|
20950
|
-
async function petChatResetMemory() {
|
|
20951
|
-
try {
|
|
20952
|
-
const res = await apiPostJson('/pet-chat/reset', {}, { parse: 'always' });
|
|
20953
|
-
if (res && res.ok) petChatStatus(weT('已清空'));
|
|
20954
|
-
else petChatStatus(weT('清空失败'));
|
|
20955
|
-
} catch {
|
|
20956
|
-
petChatStatus(weT('清空失败'));
|
|
20957
|
-
}
|
|
20958
|
-
}
|
|
20959
|
-
|
|
20960
|
-
/** 问宿主"配好没"(失败就当作没配,不弹错误框)。 */
|
|
20961
|
-
async function petChatSyncState() {
|
|
20962
|
-
try {
|
|
20963
|
-
const probe = await apiJson('/pet-chat/state', { parse: 'always' });
|
|
20964
|
-
const doc = probe && probe.data;
|
|
20965
|
-
// 语音输入开关由宿主带回来:false ⇒ 按麦克风只提示"先去 DSH 开",不弹权限框
|
|
20966
|
-
petChatVoiceEnabled = doc && doc.voiceEnabled === true;
|
|
20967
|
-
// 对话总开关:显式 false ⇒ 点宠物不弹气泡(判据⑥)
|
|
20968
|
-
petChatChatEnabled = Boolean(doc && doc.enabled === true);
|
|
20969
|
-
if (doc && doc.voiceOut && typeof doc.voiceOut === 'object') petChatVoiceOut = doc.voiceOut;
|
|
20970
|
-
if (!doc || doc.enabled !== true) {
|
|
20971
|
-
petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
|
|
20972
|
-
return null;
|
|
20973
|
-
}
|
|
20974
|
-
if (doc.reachable === false) {
|
|
20975
|
-
petChatStatus(weT('连不上模型端点') + (doc.lastError ? ':' + doc.lastError : ''));
|
|
20976
|
-
return doc;
|
|
20977
|
-
}
|
|
20978
|
-
petChatStatus(weT('已连接') + ' · ' + String(doc.provider || '') + ' · ' + String(doc.model || ''));
|
|
20979
|
-
return doc;
|
|
20980
|
-
} catch {
|
|
20981
|
-
petChatStatus(weT('宿主没有响应'));
|
|
20982
|
-
return null;
|
|
20983
|
-
}
|
|
20744
|
+
return group[Math.floor(Math.random() * group.length)];
|
|
20984
20745
|
}
|
|
20985
20746
|
|
|
20986
|
-
/**
|
|
20987
|
-
|
|
20988
|
-
|
|
20989
|
-
|
|
20990
|
-
|
|
20991
|
-
|
|
20992
|
-
|
|
20993
|
-
|
|
20994
|
-
|
|
20995
|
-
|
|
20996
|
-
|
|
20997
|
-
|
|
20998
|
-
|
|
20999
|
-
|
|
21000
|
-
for (const line of frame.split('\n')) {
|
|
21001
|
-
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
21002
|
-
else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
|
|
21003
|
-
}
|
|
21004
|
-
if (!dataLines.length) return null;
|
|
21005
|
-
try { return { event, data: JSON.parse(dataLines.join('\n')) }; } catch { return null; }
|
|
21006
|
-
}
|
|
21007
|
-
|
|
21008
|
-
/** 发送一句(SSE 流式)。 */
|
|
21009
|
-
async function petChatSend() {
|
|
21010
|
-
if (petChatBusy) return;
|
|
21011
|
-
const els = petChatBuild();
|
|
21012
|
-
if (!els) return;
|
|
21013
|
-
const text = String(els.input.value || '').trim();
|
|
21014
|
-
if (!text) return;
|
|
21015
|
-
if ([...text].length > 400) { petChatStatus(weT('一次最多 400 字')); return; }
|
|
21016
|
-
els.input.value = '';
|
|
21017
|
-
petChatPush('user', text);
|
|
21018
|
-
petChatTts.start(); // 新消息:停掉上一段朗读
|
|
21019
|
-
petChatBusy = true;
|
|
21020
|
-
petChatStatus(weT('思考中…'));
|
|
21021
|
-
|
|
21022
|
-
const state = await petChatSyncState();
|
|
21023
|
-
if (!state || state.enabled !== true) {
|
|
21024
|
-
// 没有模型:不假装在对话,直接给预设台词
|
|
21025
|
-
const presetLine = petChatPresetLine();
|
|
21026
|
-
petChatPush('assistant', presetLine);
|
|
21027
|
-
void petChatSpeak(presetLine, 'calm');
|
|
21028
|
-
petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
|
|
21029
|
-
petChatBusy = false;
|
|
21030
|
-
return;
|
|
21031
|
-
}
|
|
20747
|
+
/** 头顶气泡实例:锚点取桌宠层矩形,跟随位置与缩放。 */
|
|
20748
|
+
const petBubble = petBubbleCreate({
|
|
20749
|
+
document: typeof document !== 'undefined' ? document : undefined,
|
|
20750
|
+
getAnchor: () => {
|
|
20751
|
+
try {
|
|
20752
|
+
const layer = document && document.querySelector ? document.querySelector('#we-pet-layer') : null;
|
|
20753
|
+
if (!layer || typeof layer.getBoundingClientRect !== 'function') return null;
|
|
20754
|
+
const rect = layer.getBoundingClientRect();
|
|
20755
|
+
const style = window.getComputedStyle(layer);
|
|
20756
|
+
const scale = Number(style.getPropertyValue('--we-pet-scale')) || 1;
|
|
20757
|
+
return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, scale };
|
|
20758
|
+
} catch { return null; }
|
|
20759
|
+
},
|
|
20760
|
+
});
|
|
21032
20761
|
|
|
21033
|
-
|
|
21034
|
-
|
|
21035
|
-
|
|
21036
|
-
|
|
21037
|
-
|
|
21038
|
-
const
|
|
21039
|
-
|
|
21040
|
-
|
|
21041
|
-
|
|
21042
|
-
|
|
20762
|
+
/** 语音输入(v0.1 核心):点桌宠即开始听,静音 1.2s 或满 15s 自动结束。 */
|
|
20763
|
+
const petVoiceIn = petVoiceInputCreate({
|
|
20764
|
+
now: () => Date.now(),
|
|
20765
|
+
getUserMedia: (constraints) => navigator.mediaDevices.getUserMedia(constraints),
|
|
20766
|
+
createContext: (stream) => {
|
|
20767
|
+
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
|
20768
|
+
const ctx = new AudioCtx();
|
|
20769
|
+
const source = ctx.createMediaStreamSource(stream);
|
|
20770
|
+
// ScriptProcessor 是兜底路径(AudioWorklet 要额外加载模块文件,v0.1 先用它)
|
|
20771
|
+
const node = ctx.createScriptProcessor(4096, 1, 1);
|
|
20772
|
+
source.connect(node);
|
|
20773
|
+
return { context: ctx, node, sampleRate: ctx.sampleRate };
|
|
20774
|
+
},
|
|
20775
|
+
postTranscribe: async (audio) => {
|
|
20776
|
+
const res = await apiPostJson('/pet-chat/transcribe', { audio, language: 'zh' }, { parse: 'always' });
|
|
20777
|
+
return (res && res.data) || {};
|
|
20778
|
+
},
|
|
20779
|
+
postChat: async (text, onState) => {
|
|
20780
|
+
petBubble.setState('answer');
|
|
20781
|
+
const res = await apiFetch('/pet-chat/chat', {
|
|
20782
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }),
|
|
21043
20783
|
});
|
|
21044
|
-
const
|
|
21045
|
-
if (!call || !call.ok || !response || !response.body) {
|
|
21046
|
-
petChatStatus(weT('宿主拒绝了这次请求') + '(HTTP ' + response.status + ')');
|
|
21047
|
-
petChatBusy = false;
|
|
21048
|
-
return;
|
|
21049
|
-
}
|
|
21050
|
-
const reader = response.body.getReader();
|
|
20784
|
+
const reader = res.body.getReader();
|
|
21051
20785
|
const decoder = new TextDecoder();
|
|
21052
20786
|
let buffer = '';
|
|
21053
20787
|
for (;;) {
|
|
21054
|
-
// eslint-disable-
|
|
21055
|
-
const { value, done } = await reader.read();
|
|
20788
|
+
const { value, done } = await reader.read(); // eslint-disable-line no-await-in-loop
|
|
21056
20789
|
if (done) break;
|
|
21057
20790
|
buffer += decoder.decode(value, { stream: true });
|
|
21058
|
-
|
|
21059
|
-
|
|
21060
|
-
|
|
21061
|
-
const
|
|
21062
|
-
|
|
21063
|
-
|
|
21064
|
-
|
|
21065
|
-
|
|
21066
|
-
|
|
21067
|
-
|
|
21068
|
-
petChatRender();
|
|
21069
|
-
} else if (parsed.event === 'done') {
|
|
21070
|
-
void petChatSpeak(assistant, parsed.data && parsed.data.emotion);
|
|
21071
|
-
petChatApplyEmotion(parsed.data && parsed.data.emotion);
|
|
21072
|
-
petChatStatus('');
|
|
21073
|
-
} else if (parsed.event === 'error') {
|
|
21074
|
-
const code = parsed.data && parsed.data.code ? parsed.data.code : 'error';
|
|
21075
|
-
const hint = parsed.data && parsed.data.hint ? parsed.data.hint : '';
|
|
21076
|
-
petChatStatus(hint || code);
|
|
21077
|
-
if (code === 'no-model') petChatPush('assistant', petChatPresetLine());
|
|
21078
|
-
}
|
|
20791
|
+
for (;;) {
|
|
20792
|
+
const cut = buffer.indexOf('\n\n');
|
|
20793
|
+
if (cut < 0) break;
|
|
20794
|
+
const frame = buffer.slice(0, cut);
|
|
20795
|
+
buffer = buffer.slice(cut + 2);
|
|
20796
|
+
const line = frame.split('\n').find((item) => item.startsWith('data:'));
|
|
20797
|
+
if (!line) continue;
|
|
20798
|
+
let payload = null;
|
|
20799
|
+
try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
|
|
20800
|
+
if (payload && typeof payload.t === 'string') petBubble.append(payload.t);
|
|
21079
20801
|
}
|
|
21080
20802
|
}
|
|
21081
|
-
|
|
21082
|
-
|
|
21083
|
-
}
|
|
21084
|
-
|
|
21085
|
-
|
|
21086
|
-
|
|
21087
|
-
|
|
21088
|
-
|
|
21089
|
-
|
|
21090
|
-
|
|
21091
|
-
|
|
21092
|
-
|
|
21093
|
-
|
|
21094
|
-
|
|
21095
|
-
|
|
21096
|
-
|
|
21097
|
-
const doc = (res && res.data) || {};
|
|
21098
|
-
if (!doc.ok) { petChatStatus(weT('读取记忆失败')); return; }
|
|
21099
|
-
if (doc.enabled === false) { petChatStatus(weT('记忆已关闭(设置 → 桌宠对话)')); return; }
|
|
21100
|
-
const m = doc.memory || {};
|
|
21101
|
-
const parts = [];
|
|
21102
|
-
if (m.nickname) parts.push('称呼:' + m.nickname);
|
|
21103
|
-
if (Array.isArray(m.likes) && m.likes.length) parts.push('喜欢:' + m.likes.join('、'));
|
|
21104
|
-
if (Array.isArray(m.dislikes) && m.dislikes.length) parts.push('不喜欢:' + m.dislikes.join('、'));
|
|
21105
|
-
if (m.style) parts.push('说话风格:' + m.style);
|
|
21106
|
-
if (Array.isArray(m.notes) && m.notes.length) parts.push('备注:' + m.notes.join('、'));
|
|
21107
|
-
petChatPush('assistant', parts.length ? parts.join('\n') : weT('还没有记住任何偏好'));
|
|
21108
|
-
petChatStatus(parts.length ? weT('点「清空记忆」可以全部忘掉') : '');
|
|
21109
|
-
} catch {
|
|
21110
|
-
petChatStatus(weT('读取记忆失败'));
|
|
21111
|
-
}
|
|
21112
|
-
}
|
|
21113
|
-
|
|
21114
|
-
/** C2「今天别说了」:当天不再主动。 */
|
|
21115
|
-
async function petChatSkipToday() {
|
|
21116
|
-
try {
|
|
21117
|
-
const res = await apiPostJson('/pet-chat/skip', {}, { parse: 'always' });
|
|
21118
|
-
petChatStatus(res && res.ok ? weT('今天不主动打扰了') : weT('操作失败'));
|
|
21119
|
-
await petChatRefreshUsage();
|
|
21120
|
-
} catch {
|
|
21121
|
-
petChatStatus(weT('操作失败'));
|
|
21122
|
-
}
|
|
21123
|
-
}
|
|
21124
|
-
|
|
21125
|
-
/** 刷新「今日已说 N/10」(开启主动闲聊时显示)。 */
|
|
21126
|
-
async function petChatRefreshUsage() {
|
|
21127
|
-
const els = petChatEls || petChatBuild();
|
|
21128
|
-
if (!els || !els.usage) return;
|
|
21129
|
-
try {
|
|
21130
|
-
const res = await apiJson('/pet-chat/proactive', { parse: 'always' });
|
|
21131
|
-
const doc = (res && res.data) || {};
|
|
21132
|
-
if (!doc.enabled) { els.usage.style.display = 'none'; return; }
|
|
21133
|
-
const usage = doc.usage || {};
|
|
21134
|
-
els.usageText.textContent = `今日已说 ${Number(usage.said) || 0}/${Number(usage.limit) || 0}`;
|
|
21135
|
-
els.usage.style.display = 'flex';
|
|
21136
|
-
} catch {
|
|
21137
|
-
els.usage.style.display = 'none';
|
|
21138
|
-
}
|
|
21139
|
-
}
|
|
21140
|
-
|
|
21141
|
-
/* ── 语音输入(按住说话)──────────────────────────────────────────────────────
|
|
21142
|
-
* 三层分工:
|
|
21143
|
-
* ① 录音(这里):getUserMedia + AudioWorklet 采 PCM → 16kHz 单声道 PCM16 WAV;
|
|
21144
|
-
* ② 转写(宿主):POST /pet-chat/transcribe → DSH 的 speechToText(provider 自己管模型);
|
|
21145
|
-
* ③ 回填(这里):**只写输入框**,绝不自动发送 —— 识别难免错,得让用户改完再发。
|
|
21146
|
-
* 失败一律回落打字(只给一行状态提示,不弹错误框)。
|
|
21147
|
-
*/
|
|
21148
|
-
const PET_CHAT_VOICE_MAX_SECONDS = 15;
|
|
21149
|
-
let petChatVoice = null;
|
|
21150
|
-
let petChatVoiceEnabled = null;
|
|
21151
|
-
// 对话总开关:/state 带回;显式 false 时点宠物不弹气泡(判据⑥)
|
|
21152
|
-
let petChatChatEnabled = null;
|
|
21153
|
-
// 朗读(TTS):默认开;配置由 /state 带回,没拿到时按默认值(开)
|
|
21154
|
-
/** 朗读入口:engine=edge 走宿主合成,其余(或失败)走系统音色。 */
|
|
21155
|
-
async function petChatSpeak(text, emotion) {
|
|
21156
|
-
const config = petChatVoiceOut || {};
|
|
21157
|
-
if (config.enabled !== true) return;
|
|
21158
|
-
if (config.engine === 'edge') {
|
|
21159
|
-
try {
|
|
21160
|
-
const res = await apiPostJson('/pet-chat/speak', { text, emotion: emotion || 'calm' }, { parse: 'always' });
|
|
21161
|
-
const doc = (res && res.data) || {};
|
|
21162
|
-
if (doc.ok && doc.engine === 'edge' && doc.audio) {
|
|
21163
|
-
const player = new Audio('data:' + (doc.mime || 'audio/mpeg') + ';base64,' + doc.audio);
|
|
21164
|
-
petChatAudioPlayer = player;
|
|
21165
|
-
void player.play();
|
|
21166
|
-
return;
|
|
21167
|
-
}
|
|
21168
|
-
// doc.engine==='system'(含回落)⇒ 往下走系统音色
|
|
21169
|
-
} catch { /* 网络问题一律回落系统音色 */ }
|
|
21170
|
-
}
|
|
21171
|
-
petChatTts.finish(text);
|
|
21172
|
-
}
|
|
21173
|
-
let petChatAudioPlayer = null;
|
|
21174
|
-
let petChatVoiceOut = { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' };
|
|
21175
|
-
const petChatTts = petChatTtsCreate({
|
|
21176
|
-
getSpeech: () => (typeof window !== 'undefined' ? window.speechSynthesis : null),
|
|
21177
|
-
getVoices: () => {
|
|
21178
|
-
const speech = typeof window !== 'undefined' ? window.speechSynthesis : null;
|
|
21179
|
-
return speech && typeof speech.getVoices === 'function' ? speech.getVoices() : [];
|
|
20803
|
+
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
20804
|
+
petBubble.hide(3000);
|
|
20805
|
+
},
|
|
20806
|
+
onText: (text) => { petBubble.append(text); },
|
|
20807
|
+
onError: (error) => {
|
|
20808
|
+
// 失败一律回落打字:只给一行提示,不弹错误框(工单 S3)
|
|
20809
|
+
const map = {
|
|
20810
|
+
permission: '没拿到麦克风权限,先打字吧',
|
|
20811
|
+
'no-mic': '打不开麦克风,先打字吧',
|
|
20812
|
+
'asr-not-ready': '语音输入还没就绪:去 DSH 设置里开启(需下载模型)',
|
|
20813
|
+
timeout: '这次没听清,再说一次或直接打字',
|
|
20814
|
+
network: '网络不太顺,重试或直接打字',
|
|
20815
|
+
};
|
|
20816
|
+
const message = map[error && error.code] || '没听清,直接打字也行';
|
|
20817
|
+
petBubble.show(message);
|
|
20818
|
+
petBubble.hide(3000);
|
|
21180
20819
|
},
|
|
21181
|
-
getConfig: () => petChatVoiceOut,
|
|
21182
|
-
Utterance: typeof window !== 'undefined' ? window.SpeechSynthesisUtterance : undefined,
|
|
21183
|
-
onHint: (code, message) => petChatStatus(message),
|
|
21184
20820
|
});
|
|
21185
20821
|
|
|
21186
|
-
/**
|
|
21187
|
-
|
|
21188
|
-
|
|
21189
|
-
|
|
21190
|
-
const
|
|
21191
|
-
|
|
21192
|
-
|
|
21193
|
-
|
|
21194
|
-
put(0, 'RIFF'); view.setUint32(4, 36 + frames * 2, true); put(8, 'WAVE');
|
|
21195
|
-
put(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
|
|
21196
|
-
view.setUint32(24, rate, true); view.setUint32(28, rate * 2, true); view.setUint16(32, 2, true); view.setUint16(34, 16, true);
|
|
21197
|
-
put(36, 'data'); view.setUint32(40, frames * 2, true);
|
|
21198
|
-
let offset = 44;
|
|
21199
|
-
for (let i = 0; i < frames; i += 1) {
|
|
21200
|
-
const index = Math.min(samples.length - 1, Math.floor(i * ratio));
|
|
21201
|
-
const clamped = Math.max(-1, Math.min(1, samples[index]));
|
|
21202
|
-
view.setInt16(offset, clamped < 0 ? clamped * 0x8000 : clamped * 0x7fff, true);
|
|
21203
|
-
offset += 2;
|
|
21204
|
-
}
|
|
21205
|
-
return new Uint8Array(buffer);
|
|
21206
|
-
}
|
|
21207
|
-
|
|
21208
|
-
/** Uint8Array → base64(浏览器与 Node 都可用)。 */
|
|
21209
|
-
function petChatToBase64(bytes) {
|
|
21210
|
-
let binary = '';
|
|
21211
|
-
for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i]);
|
|
21212
|
-
if (typeof btoa === 'function') return btoa(binary);
|
|
21213
|
-
return Buffer.from(bytes).toString('base64');
|
|
21214
|
-
}
|
|
21215
|
-
|
|
21216
|
-
/** 开始录音。返回是否真的开始了。 */
|
|
21217
|
-
async function petChatVoiceStart() {
|
|
21218
|
-
if (petChatVoice) return true;
|
|
21219
|
-
if (petChatVoiceEnabled === false) {
|
|
21220
|
-
petChatStatus(weT('语音输入未开启:请先在 DSH 设置里启用(需下载模型)'));
|
|
21221
|
-
return false;
|
|
21222
|
-
}
|
|
21223
|
-
try {
|
|
21224
|
-
const media = navigator.mediaDevices && navigator.mediaDevices.getUserMedia
|
|
21225
|
-
? await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, sampleRate: 16000 } })
|
|
21226
|
-
: null;
|
|
21227
|
-
const AudioCtx = window.AudioContext || window.webkitAudioContext;
|
|
21228
|
-
if (!media || !AudioCtx) {
|
|
21229
|
-
if (media) media.getTracks().forEach((track) => track.stop());
|
|
21230
|
-
petChatStatus(weT('打不开麦克风,可以继续打字'));
|
|
21231
|
-
return false;
|
|
21232
|
-
}
|
|
21233
|
-
const ctx = new AudioCtx();
|
|
21234
|
-
const source = ctx.createMediaStreamSource(media);
|
|
21235
|
-
const chunks = [];
|
|
21236
|
-
// AudioWorklet:每帧 Float32 丢回主线程(不阻塞渲染)
|
|
21237
|
-
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);';
|
|
21238
|
-
const url = URL.createObjectURL(new Blob([code], { type: 'application/javascript' }));
|
|
21239
|
-
await ctx.audioWorklet.addModule(url);
|
|
21240
|
-
URL.revokeObjectURL(url);
|
|
21241
|
-
const node = new AudioWorkletNode(ctx, 'pet-chat-pcm');
|
|
21242
|
-
node.port.onmessage = (event) => {
|
|
21243
|
-
if (petChatVoice && chunks.length * 1024 < 16000 * PET_CHAT_VOICE_MAX_SECONDS * 8) chunks.push(event.data);
|
|
21244
|
-
};
|
|
21245
|
-
source.connect(node);
|
|
21246
|
-
node.connect(ctx.destination);
|
|
21247
|
-
petChatVoice = { stream: media, ctx, node, source, chunks, sampleRate: ctx.sampleRate };
|
|
21248
|
-
petChatStatus(weT('正在听…松手结束'));
|
|
21249
|
-
return true;
|
|
21250
|
-
} catch {
|
|
21251
|
-
// 最典型的是权限被拒(NotAllowedError):提示一行,允许继续打字
|
|
21252
|
-
petChatStatus(weT('没有麦克风权限(或未授权),可以继续打字'));
|
|
21253
|
-
return false;
|
|
21254
|
-
}
|
|
20822
|
+
/** 说一句:气泡显示 + 3 秒后淡出。
|
|
20823
|
+
* v0.1 不朗读 —— 这里刻意不做音频(验收⑦:lib/ 里不允许出现 speechSynthesis)。
|
|
20824
|
+
*/
|
|
20825
|
+
function petChatSay(text) {
|
|
20826
|
+
const line = String(text || '').trim();
|
|
20827
|
+
if (!line) return;
|
|
20828
|
+
petBubble.show(line);
|
|
20829
|
+
petBubble.hide(3000);
|
|
21255
20830
|
}
|
|
21256
20831
|
|
|
21257
|
-
/**
|
|
21258
|
-
|
|
21259
|
-
|
|
21260
|
-
|
|
21261
|
-
|
|
21262
|
-
|
|
21263
|
-
|
|
21264
|
-
|
|
21265
|
-
voice.node.disconnect();
|
|
21266
|
-
voice.stream.getTracks().forEach((track) => track.stop());
|
|
21267
|
-
await voice.ctx.close();
|
|
21268
|
-
} catch { /* 收尾失败不影响转写 */ }
|
|
21269
|
-
|
|
21270
|
-
const total = voice.chunks.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
21271
|
-
if (!total) { petChatStatus(weT('没听到声音,再试一次?')); return; }
|
|
21272
|
-
const merged = new Float32Array(total);
|
|
21273
|
-
let offset = 0;
|
|
21274
|
-
for (const chunk of voice.chunks) { merged.set(chunk, offset); offset += chunk.length; }
|
|
21275
|
-
const wav = petChatEncodeWav(merged, voice.sampleRate);
|
|
21276
|
-
|
|
21277
|
-
petChatStatus(weT('识别中…'));
|
|
21278
|
-
// ↓ 这一段是 D⑥ 的判据面:只写 input.value,绝不调用 petChatSend
|
|
21279
|
-
const res = await apiPostJson('/pet-chat/transcribe', { audio: petChatToBase64(wav), language: 'zh' }, { parse: 'always' });
|
|
21280
|
-
const doc = (res && res.data) || {};
|
|
21281
|
-
const els = petChatEls || petChatBuild();
|
|
21282
|
-
if (!doc.ok) {
|
|
21283
|
-
petChatStatus(weT('这次没听清,可以继续打字') + (doc.hint ? '(' + doc.hint + ')' : ''));
|
|
21284
|
-
return;
|
|
21285
|
-
}
|
|
21286
|
-
if (els && typeof doc.text === 'string') {
|
|
21287
|
-
els.input.value = doc.text;
|
|
21288
|
-
if (typeof els.input.focus === 'function') els.input.focus();
|
|
21289
|
-
petChatStatus(weT('识别完成,确认后按发送'));
|
|
21290
|
-
}
|
|
20832
|
+
/** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音);否则唤醒并开始听。 */
|
|
20833
|
+
function petChatWake() {
|
|
20834
|
+
if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
|
|
20835
|
+
petBubble.setState('listen');
|
|
20836
|
+
void petVoiceIn.start().then((started) => {
|
|
20837
|
+
if (!started) return; // 失败分支已经由 onError 提示(回落打字)
|
|
20838
|
+
petBubble.show('我在听…');
|
|
20839
|
+
});
|
|
21291
20840
|
}
|
|
21292
20841
|
|
|
21293
20842
|
/**
|
|
21294
|
-
*
|
|
21295
|
-
*
|
|
21296
|
-
* 五条件里渲染进程能拿到的事实:开关/计数/间隔/静默时段由宿主判,
|
|
21297
|
-
* 客户端只提供 `fullscreen`(document.fullscreenElement)、`focused`(document.hasFocus())
|
|
21298
|
-
* 和 `idleMinutes`(**窗口内**最近一次键鼠事件距现在多久)。
|
|
21299
|
-
* ⚠️ 这不是系统全局空闲(Electron 的 powerMonitor.getSystemIdleTime 在渲染进程拿不到),
|
|
21300
|
-
* 只是"这个窗口最近有没有人动"的近似 —— 已在 docs/PET-CHAT-DONE.md 写明。
|
|
20843
|
+
* 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点桌宠 / 快捷键。
|
|
20844
|
+
* 返回 cleanup —— 卸载时摘监听、销毁气泡。
|
|
21301
20845
|
*/
|
|
21302
|
-
async function petChatProactiveCheck() {
|
|
21303
|
-
if (petChatBusy) return;
|
|
21304
|
-
const idleMinutes = (Date.now() - petChatLastActivityAt) / 60000;
|
|
21305
|
-
const fullscreen = typeof document !== 'undefined' && Boolean(document.fullscreenElement);
|
|
21306
|
-
const focused = typeof document !== 'undefined' && typeof document.hasFocus === 'function' ? document.hasFocus() : true;
|
|
21307
|
-
try {
|
|
21308
|
-
const res = await apiPostJson('/pet-chat/proactive/tick', { idleMinutes, fullscreen, focused, randomHit: Math.random() < 0.25 }, { parse: 'always' });
|
|
21309
|
-
const doc = (res && res.data) || {};
|
|
21310
|
-
if (doc.line) {
|
|
21311
|
-
petChatShow();
|
|
21312
|
-
petChatPush('assistant', doc.line);
|
|
21313
|
-
}
|
|
21314
|
-
await petChatRefreshUsage();
|
|
21315
|
-
} catch { /* 主动闲聊失败不打扰用户 */ }
|
|
21316
|
-
}
|
|
21317
|
-
|
|
21318
|
-
/** 最近一次窗口内活动的时间(C1 的 idleMinutes 来自它)。 */
|
|
21319
|
-
let petChatLastActivityAt = Date.now();
|
|
21320
|
-
/** 5 分钟检查定时器(渲染进程能拿到的事实,仅窗口内)。 */
|
|
21321
|
-
const PET_CHAT_CHECK_INTERVAL_MS = 5 * 60 * 1000;
|
|
21322
|
-
|
|
21323
20846
|
function mountPetChat() {
|
|
21324
|
-
|
|
21325
|
-
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function'
|
|
21326
|
-
|| typeof document.createElement !== 'function') {
|
|
21327
|
-
return () => {};
|
|
21328
|
-
}
|
|
20847
|
+
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return () => {};
|
|
21329
20848
|
const onDocumentClick = (event) => {
|
|
21330
20849
|
const target = event.target;
|
|
21331
20850
|
if (!target || typeof target.closest !== 'function') return;
|
|
21332
|
-
if (target.closest('#we-pet-layer'))
|
|
20851
|
+
if (target.closest('#we-pet-layer')) petChatWake();
|
|
21333
20852
|
};
|
|
21334
20853
|
const onKeyDown = (event) => {
|
|
21335
20854
|
if (event.altKey && event.ctrlKey && String(event.key).toLowerCase() === 'p') {
|
|
21336
20855
|
event.preventDefault();
|
|
21337
|
-
|
|
21338
|
-
return;
|
|
20856
|
+
petChatWake();
|
|
21339
20857
|
}
|
|
21340
|
-
if (event.key === 'Escape' && petChatEls && petChatEls.root.style.display === 'flex') petChatHide();
|
|
21341
20858
|
};
|
|
21342
|
-
// C1 的"窗口内活动":键鼠/滚轮/触摸都算(passive,不拦截任何默认行为)
|
|
21343
|
-
const markActivity = () => { petChatLastActivityAt = Date.now(); };
|
|
21344
|
-
const activityEvents = ['mousemove', 'mousedown', 'keydown', 'wheel', 'touchstart'];
|
|
21345
20859
|
document.addEventListener('click', onDocumentClick, true);
|
|
21346
20860
|
document.addEventListener('keydown', onKeyDown, true);
|
|
21347
|
-
for (const name of activityEvents) window.addEventListener(name, markActivity, { passive: true });
|
|
21348
|
-
// 每 5 分钟问一次(不是每秒):拿不到系统级空闲,用窗口内活动近似。
|
|
21349
|
-
// 替身环境里没有 setInterval ⇒ 跳过(只影响主动闲聊,不影响聊天本身)
|
|
21350
|
-
const timer = typeof setInterval === 'function'
|
|
21351
|
-
? setInterval(() => { void petChatProactiveCheck(); }, PET_CHAT_CHECK_INTERVAL_MS)
|
|
21352
|
-
: null;
|
|
21353
|
-
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
21354
20861
|
return () => {
|
|
21355
|
-
if (timer && typeof clearInterval === 'function') clearInterval(timer);
|
|
21356
20862
|
document.removeEventListener('click', onDocumentClick, true);
|
|
21357
20863
|
document.removeEventListener('keydown', onKeyDown, true);
|
|
21358
|
-
|
|
21359
|
-
if (petChatEls && petChatEls.root.parentNode) petChatEls.root.parentNode.removeChild(petChatEls.root);
|
|
21360
|
-
petChatEls = null;
|
|
21361
|
-
petChatLines = [];
|
|
20864
|
+
petBubble.dispose();
|
|
21362
20865
|
};
|
|
21363
20866
|
}
|
|
21364
20867
|
|