dsh-folia 4.25.5 → 4.26.0-pre.2
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 +911 -0
- package/lib/features.js +8 -0
- package/lib/index.js +5 -0
- package/lib/pet-chat-memory.js +147 -0
- package/lib/pet-chat-proactive.js +156 -0
- package/lib/route-registry.js +11 -0
- package/lib/routes/pet-chat.js +727 -0
- package/lib/settings/ownership.js +5 -3
- package/lib/settings-schema.js +115 -0
- package/package.json +4 -1
package/lib/client.js
CHANGED
|
@@ -8069,6 +8069,39 @@ window.__ModuleLoader__.load({
|
|
|
8069
8069
|
// 之后退皮肤永远放不回来(审查 P3)。空串 / false = 没有待恢复的选择。
|
|
8070
8070
|
skinYieldRestoreId: '', // 让路前的壁纸 id(str 档,与壁纸 id 同一口径)
|
|
8071
8071
|
skinYieldRestoreRotation: false, // 让路前的轮播开关
|
|
8072
|
+
|
|
8073
|
+
// ── 桌宠对话(门 2):点宠物 -> 气泡 -> 用户自己的模型 ──────────────────────
|
|
8074
|
+
// 整包一个对象(`kind: 'petChat'`,见 readPetChat),因为它是一个功能的一组参数,
|
|
8075
|
+
// 拆成十个顶层键只会让归属表更难读。
|
|
8076
|
+
// ⚠️ `apiKey` **只存本机 profile**:不打印、不进日志、不上传站点(门 2 自检 S5 用 grep 守)。
|
|
8077
|
+
// `enabled` 默认 **false**:不点不连、不给没配置的人弹错误;关掉即回到预设台词库。
|
|
8078
|
+
petChat: {
|
|
8079
|
+
enabled: false,
|
|
8080
|
+
// 默认走用户自己的 DeepSeek(工单 A1):key 由用户在设置里填,不预置任何凭据。
|
|
8081
|
+
provider: 'openai', // 'ollama' | 'openai'(openai = 任何 OpenAI 兼容端点)
|
|
8082
|
+
baseUrl: 'https://api.deepseek.com',
|
|
8083
|
+
apiKey: '', // 用户自己填;本机 Ollama 不需要
|
|
8084
|
+
model: 'deepseek-chat',
|
|
8085
|
+
// 人设默认值(工单 A3):可在设置里改;这三段会进 system prompt。
|
|
8086
|
+
persona: { name: 'Folia', style: '元气、短句、偶尔颜文字、不说教', traits: '喜欢壁纸和游戏,被夸会害羞' },
|
|
8087
|
+
maxTurns: 8, // 上下文轮数上限(工单:默认 8,上限 12)
|
|
8088
|
+
maxChars: 80, // 单条回复字数上限(工单:默认 80,上限 160)
|
|
8089
|
+
// ── B:长期偏好记忆(只存结论,不存聊天原文)──
|
|
8090
|
+
memoryEnabled: true,
|
|
8091
|
+
memoryEveryTurns: 10,
|
|
8092
|
+
// ── C:主动闲聊(默认关;开启后还要同时满足五个条件)──
|
|
8093
|
+
proactiveEnabled: false,
|
|
8094
|
+
proactiveDailyLimit: 10,
|
|
8095
|
+
proactiveMinGapMin: 120,
|
|
8096
|
+
quietHours: '22:00-08:00',
|
|
8097
|
+
// ── 语音输入(默认关):真正干活的转写由 DSH 宿主的 speechToText 服务承担,
|
|
8098
|
+
// 模型由那个 provider 自己下载/校验 —— 插件这边只负责录音与回填。
|
|
8099
|
+
voiceEnabled: false,
|
|
8100
|
+
// ── 朗读回答(TTS):**默认开**;走系统 speechSynthesis,零依赖零 token。
|
|
8101
|
+
// enabled 与"宠物音效"完全无关(音效开关不影响朗读,反之亦然)。
|
|
8102
|
+
// voiceURI 空 = 自动挑中文音色(zh / Chinese / Huihui / Xiaoxiao …)。
|
|
8103
|
+
voiceOut: { enabled: true, rate: 1, pitch: 1, volume: 1, voiceURI: '' },
|
|
8104
|
+
},
|
|
8072
8105
|
};
|
|
8073
8106
|
|
|
8074
8107
|
// 只做默认值、既不 sanitize 也不持久化的键(纯展示态字段)。
|
|
@@ -8304,6 +8337,8 @@ window.__ModuleLoader__.load({
|
|
|
8304
8337
|
// 皮肤互操作的落盘记忆:id 走与壁纸 id 同一个 str 档,轮播开关走 boolFalse。
|
|
8305
8338
|
skinYieldRestoreId: { kind: 'str' },
|
|
8306
8339
|
skinYieldRestoreRotation: { kind: 'boolFalse' },
|
|
8340
|
+
// 桌宠对话(门 2):整包一个键,子字段的校验在 readPetChat 里(见该函数)。
|
|
8341
|
+
petChat: { kind: 'petChat' },
|
|
8307
8342
|
};
|
|
8308
8343
|
|
|
8309
8344
|
// ── 整机配置快照 · 派生段(`PROFILE_PRESET_KEYS` 必须由 `KINDS` 派生,见上方四段注释)──
|
|
@@ -8771,6 +8806,85 @@ window.__ModuleLoader__.load({
|
|
|
8771
8806
|
return base;
|
|
8772
8807
|
}
|
|
8773
8808
|
|
|
8809
|
+
// ── 桌宠对话(门 2)──────────────────────────────────────────────────────────
|
|
8810
|
+
// 整包一个设置键;子字段在这里消毒(客户端与宿主共用同一条路径)。
|
|
8811
|
+
const PET_CHAT_PROVIDER_VALUES = ['ollama', 'openai'];
|
|
8812
|
+
const PET_CHAT_MAX_TURNS = 12; // 工单:默认 8、上限 12
|
|
8813
|
+
const PET_CHAT_MAX_CHARS = 160; // 工单:默认 80、上限 160
|
|
8814
|
+
const PET_CHAT_MIN_CHARS = 20;
|
|
8815
|
+
const PET_CHAT_BASE_URL_MAX = 300;
|
|
8816
|
+
const PET_CHAT_API_KEY_MAX = 400;
|
|
8817
|
+
const PET_CHAT_MODEL_MAX = 120;
|
|
8818
|
+
const PET_CHAT_PERSONA_MAX = 200;
|
|
8819
|
+
|
|
8820
|
+
const petChatStr = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
|
|
8821
|
+
const petChatFloat = (v, lo, hi, fallback) => {
|
|
8822
|
+
const n = Number(v);
|
|
8823
|
+
return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : fallback;
|
|
8824
|
+
};
|
|
8825
|
+
const petChatInt = (v, lo, hi, fallback) => {
|
|
8826
|
+
const n = Number(v);
|
|
8827
|
+
return Number.isFinite(n) ? Math.min(hi, Math.max(lo, Math.round(n))) : fallback;
|
|
8828
|
+
};
|
|
8829
|
+
|
|
8830
|
+
/**
|
|
8831
|
+
* 桌宠对话设置的消毒。
|
|
8832
|
+
*
|
|
8833
|
+
* 口径与全表一致:**不"修好它"** —— 认不出的值即回落默认,而不是猜一个近似值。
|
|
8834
|
+
* `baseUrl` 只认 `http(s)://` 或空串(空 = 用该 provider 的默认端点,见 routes/pet-chat.js):
|
|
8835
|
+
* 主机名拼错的 URL 与其"修好",不如让用户重新填一次。
|
|
8836
|
+
* `apiKey` 原样保留(只在本机 profile 里),但**限长**,避免设置文件被灌爆。
|
|
8837
|
+
*/
|
|
8838
|
+
/**
|
|
8839
|
+
* 朗读设置(TTS)的消毒。
|
|
8840
|
+
*
|
|
8841
|
+
* `enabled` 默认 **true**(工单要求默认开),所以判据是 `!== false` 而不是 `=== true` ——
|
|
8842
|
+
* 老档里没有这个键的人也会直接得到"开"。
|
|
8843
|
+
* rate/pitch/volume 走 clamp;voiceURI 只做长度限制(音色由运行时按 URI/中文名挑)。
|
|
8844
|
+
*/
|
|
8845
|
+
function readVoiceOut(raw) {
|
|
8846
|
+
const def = DEFAULTS.petChat.voiceOut;
|
|
8847
|
+
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8848
|
+
return {
|
|
8849
|
+
enabled: src.enabled !== false,
|
|
8850
|
+
rate: petChatFloat(src.rate, 0.5, 2, def.rate),
|
|
8851
|
+
pitch: petChatFloat(src.pitch, 0, 2, def.pitch),
|
|
8852
|
+
volume: petChatFloat(src.volume, 0, 1, def.volume),
|
|
8853
|
+
voiceURI: petChatStr(src.voiceURI, 200).trim(),
|
|
8854
|
+
};
|
|
8855
|
+
}
|
|
8856
|
+
|
|
8857
|
+
function readPetChat(raw) {
|
|
8858
|
+
const def = DEFAULTS.petChat;
|
|
8859
|
+
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8860
|
+
const persona = src.persona && typeof src.persona === 'object' && !Array.isArray(src.persona) ? src.persona : {};
|
|
8861
|
+
const baseUrl = petChatStr(src.baseUrl, PET_CHAT_BASE_URL_MAX).trim();
|
|
8862
|
+
return {
|
|
8863
|
+
enabled: src.enabled === true,
|
|
8864
|
+
provider: PET_CHAT_PROVIDER_VALUES.includes(src.provider) ? src.provider : def.provider,
|
|
8865
|
+
baseUrl: baseUrl === '' || /^https?:\/\//i.test(baseUrl) ? baseUrl : '',
|
|
8866
|
+
apiKey: petChatStr(src.apiKey, PET_CHAT_API_KEY_MAX),
|
|
8867
|
+
model: petChatStr(src.model, PET_CHAT_MODEL_MAX).trim(),
|
|
8868
|
+
persona: {
|
|
8869
|
+
name: petChatStr(persona.name, PET_CHAT_PERSONA_MAX) || def.persona.name,
|
|
8870
|
+
style: petChatStr(persona.style, PET_CHAT_PERSONA_MAX) || def.persona.style,
|
|
8871
|
+
traits: petChatStr(persona.traits, PET_CHAT_PERSONA_MAX) || def.persona.traits,
|
|
8872
|
+
},
|
|
8873
|
+
maxTurns: petChatInt(src.maxTurns, 1, PET_CHAT_MAX_TURNS, def.maxTurns),
|
|
8874
|
+
maxChars: petChatInt(src.maxChars, PET_CHAT_MIN_CHARS, PET_CHAT_MAX_CHARS, def.maxChars),
|
|
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),
|
|
8885
|
+
};
|
|
8886
|
+
}
|
|
8887
|
+
|
|
8774
8888
|
/** 壁纸属性:只收标量值,字符串限长(防设置文件被灌爆)。 */
|
|
8775
8889
|
function readUserProps(raw) {
|
|
8776
8890
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
|
@@ -8838,6 +8952,7 @@ window.__ModuleLoader__.load({
|
|
|
8838
8952
|
return (bw >= 1 && bw <= MASCOT_BOX_MAX_W && bh >= 1 && bh <= MASCOT_BOX_MAX_H) ? v : def;
|
|
8839
8953
|
}
|
|
8840
8954
|
case 'map': return (v && typeof v === 'object' && !Array.isArray(v)) ? Object.assign({}, v) : {};
|
|
8955
|
+
case 'petChat': return readPetChat(v);
|
|
8841
8956
|
// ⚠️ `def` **必须**传进去(见 readModeMap 头注释):丢掉它等于把这个键的默认值变成
|
|
8842
8957
|
// 死代码 —— 真实会话里恒为 `{}`,那就是"控件在、开关滑杆动了没反应"的根因。
|
|
8843
8958
|
case 'modeMap': return readModeMap(v, def);
|
|
@@ -20168,6 +20283,800 @@ window.__ModuleLoader__.load({
|
|
|
20168
20283
|
} catch { return () => {}; }
|
|
20169
20284
|
}
|
|
20170
20285
|
|
|
20286
|
+
// ── 内联模块:src/pet-chat-tts.js —— 朗读回答:speechSynthesis 薄封装(整段读 / 流式按句读 / 取消),不碰 DOM、不改文字(构建期注入;勿手改本段)──
|
|
20287
|
+
/**
|
|
20288
|
+
* pet-chat-tts.js — **朗读回答**(浏览器 / Electron 内置 speechSynthesis 的薄封装)。
|
|
20289
|
+
*
|
|
20290
|
+
* 三条铁律(来自工单):
|
|
20291
|
+
* ① **文字照常显示**:本模块只调 `speechSynthesis`,**不碰 DOM、不改文本** ——
|
|
20292
|
+
* 朗读是叠加,不是替换(气泡 + 打字机该显示什么还显示什么)。
|
|
20293
|
+
* ② **零依赖零 token**:走系统语音(Electron 下是 Windows SAPI);没有就说没有。
|
|
20294
|
+
* ③ 与宠物"音效"开关**无关**:这里只看 `petChat.voiceOut.enabled`。
|
|
20295
|
+
*
|
|
20296
|
+
* 朗读节奏:
|
|
20297
|
+
* · 整段到达(非流式 / 预设台词)⇒ `finish(text)` 整段读一次;
|
|
20298
|
+
* · 流式增量 ⇒ `push(chunk)`,凑满句末标点就按句读(不打断打字机)。
|
|
20299
|
+
*
|
|
20300
|
+
* 为什么要做成工厂并把 speechSynthesis / Utterance 注入进来:
|
|
20301
|
+
* 判据要能 mock(`test/verify-pet-chat.mjs` 的 6 条),而渲染进程的真实实现
|
|
20302
|
+
* 就是 `window.speechSynthesis` + `window.SpeechSynthesisUtterance`。
|
|
20303
|
+
*/
|
|
20304
|
+
|
|
20305
|
+
/** 句末标点(中英混排;省略号也算一句的结尾)。 */
|
|
20306
|
+
const PET_CHAT_TTS_SENTENCE_END = /[。!?!?;;…]+/;
|
|
20307
|
+
|
|
20308
|
+
/**
|
|
20309
|
+
* 按句末标点切句(保留标点)。
|
|
20310
|
+
* 单句过长(>120 字)时按逗号再切一次,避免一口气念 300 字。
|
|
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
|
+
}
|
|
20323
|
+
}
|
|
20324
|
+
if (buffer.trim()) out.push(buffer.trim());
|
|
20325
|
+
// 保险:单句 >120 字再按逗号切
|
|
20326
|
+
const final = [];
|
|
20327
|
+
for (const sentence of out) {
|
|
20328
|
+
if (sentence.length <= 120) { final.push(sentence); continue; }
|
|
20329
|
+
let piece = '';
|
|
20330
|
+
for (const char of sentence) {
|
|
20331
|
+
piece += char;
|
|
20332
|
+
if (char === ',' || char === ',' ) { final.push(piece); piece = ''; }
|
|
20333
|
+
}
|
|
20334
|
+
if (piece.trim()) final.push(piece);
|
|
20335
|
+
}
|
|
20336
|
+
return final;
|
|
20337
|
+
}
|
|
20338
|
+
|
|
20339
|
+
/** 中文音色识别:`zh-*`、名字里带 Chinese / Huihui / Xiaoxiao。 */
|
|
20340
|
+
function petChatTtsIsChinese(voice) {
|
|
20341
|
+
if (!voice) return false;
|
|
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);
|
|
20345
|
+
}
|
|
20346
|
+
|
|
20347
|
+
/**
|
|
20348
|
+
* 造一个朗读引擎。
|
|
20349
|
+
*
|
|
20350
|
+
* @param {object} deps
|
|
20351
|
+
* @param {() => any} deps.getSpeech 返回 speechSynthesis(可能不存在)
|
|
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] 一次性提示回调
|
|
20356
|
+
*/
|
|
20357
|
+
function petChatTtsCreate(deps) {
|
|
20358
|
+
const options = deps || {};
|
|
20359
|
+
const getSpeech = typeof options.getSpeech === 'function' ? options.getSpeech : () => null;
|
|
20360
|
+
const getVoices = typeof options.getVoices === 'function' ? options.getVoices : () => [];
|
|
20361
|
+
const getConfig = typeof options.getConfig === 'function' ? options.getConfig : () => ({ enabled: false });
|
|
20362
|
+
const onHint = typeof options.onHint === 'function' ? options.onHint : () => {};
|
|
20363
|
+
const Utterance = options.Utterance;
|
|
20364
|
+
|
|
20365
|
+
let pending = ''; // 流式未成句的尾巴
|
|
20366
|
+
let spokenInTurn = 0; // 本回合已经读了几段(决定 finish 要不要整段读)
|
|
20367
|
+
let hintShown = {}; // 一次性提示去重(按 code)
|
|
20368
|
+
|
|
20369
|
+
const hintOnce = (code, message) => {
|
|
20370
|
+
if (hintShown[code]) return;
|
|
20371
|
+
hintShown[code] = true;
|
|
20372
|
+
onHint(code, message);
|
|
20373
|
+
};
|
|
20374
|
+
|
|
20375
|
+
/** 选音色:voiceURI 优先,其次第一个中文音色;都没有返回 null(并提示一次)。 */
|
|
20376
|
+
function pickVoice(config, voices) {
|
|
20377
|
+
const list = Array.isArray(voices) ? voices : [];
|
|
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;
|
|
20387
|
+
}
|
|
20388
|
+
|
|
20389
|
+
/** 读一段(内部):config 关了就什么都不做。 */
|
|
20390
|
+
function speakOne(text, speech, config, voices) {
|
|
20391
|
+
const trimmed = String(text ?? '').trim();
|
|
20392
|
+
if (!trimmed) return false;
|
|
20393
|
+
if (typeof Utterance !== 'function') return false;
|
|
20394
|
+
const utterance = new Utterance(trimmed);
|
|
20395
|
+
utterance.rate = Number.isFinite(Number(config.rate)) ? Number(config.rate) : 1;
|
|
20396
|
+
utterance.pitch = Number.isFinite(Number(config.pitch)) ? Number(config.pitch) : 1;
|
|
20397
|
+
utterance.volume = Number.isFinite(Number(config.volume)) ? Number(config.volume) : 1;
|
|
20398
|
+
const voice = pickVoice(config, voices);
|
|
20399
|
+
if (voice) utterance.voice = voice;
|
|
20400
|
+
speech.speak(utterance);
|
|
20401
|
+
if (!hintShown['first-speak']) {
|
|
20402
|
+
hintShown['first-speak'] = true;
|
|
20403
|
+
hintOnce('first-speak', '使用系统语音,无需下载 / 不耗 token');
|
|
20404
|
+
}
|
|
20405
|
+
return true;
|
|
20406
|
+
}
|
|
20407
|
+
|
|
20408
|
+
/** 新回合开始:停掉上一段朗读,清空缓冲。 */
|
|
20409
|
+
function start() {
|
|
20410
|
+
pending = '';
|
|
20411
|
+
spokenInTurn = 0;
|
|
20412
|
+
cancel();
|
|
20413
|
+
}
|
|
20414
|
+
|
|
20415
|
+
/** 取消朗读(关闭气泡 / 点停止 / 新消息)。 */
|
|
20416
|
+
function cancel() {
|
|
20417
|
+
const speech = getSpeech();
|
|
20418
|
+
if (speech && typeof speech.cancel === 'function') speech.cancel();
|
|
20419
|
+
}
|
|
20420
|
+
|
|
20421
|
+
/** 流式增量:凑满整句就先读(保证"边出字边读",但不打断打字机)。 */
|
|
20422
|
+
function push(chunk) {
|
|
20423
|
+
const config = getConfig() || {};
|
|
20424
|
+
if (config.enabled !== true) return;
|
|
20425
|
+
const speech = getSpeech();
|
|
20426
|
+
if (!speech || typeof speech.speak !== 'function') return; // ⑤ 没有 speechSynthesis ⇒ 静默跳过
|
|
20427
|
+
const text = String(chunk ?? '');
|
|
20428
|
+
if (!text) return;
|
|
20429
|
+
pending += text;
|
|
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;
|
|
20439
|
+
}
|
|
20440
|
+
|
|
20441
|
+
/**
|
|
20442
|
+
* 回复结束:整段朗读。
|
|
20443
|
+
* 已经边流边读过句子的,这里只读剩下的尾巴;从没读过 ⇒ 整段读一次(判据①)。
|
|
20444
|
+
*/
|
|
20445
|
+
function finish(fullText) {
|
|
20446
|
+
const config = getConfig() || {};
|
|
20447
|
+
if (config.enabled !== true) return;
|
|
20448
|
+
const speech = getSpeech();
|
|
20449
|
+
if (!speech || typeof speech.speak !== 'function') return;
|
|
20450
|
+
const whole = String(fullText ?? '');
|
|
20451
|
+
const tail = pending;
|
|
20452
|
+
pending = '';
|
|
20453
|
+
const voices = getVoices();
|
|
20454
|
+
if (spokenInTurn === 0) {
|
|
20455
|
+
// 整段一次读完(气泡里显示的还是同一段文字,这里只是读它)
|
|
20456
|
+
if (whole.trim()) speakOne(whole.trim(), speech, config, voices);
|
|
20457
|
+
return;
|
|
20458
|
+
}
|
|
20459
|
+
if (tail.trim()) speakOne(tail.trim(), speech, config, voices);
|
|
20460
|
+
}
|
|
20461
|
+
|
|
20462
|
+
return { start, push, finish, cancel, split: petChatTtsSplit };
|
|
20463
|
+
}
|
|
20464
|
+
|
|
20465
|
+
// ── 内联模块:src/pet-chat.js —— 桌宠对话气泡:点宠物出输入框,走宿主 /folia/pet-chat/* 的 SSE;没配模型时给预设台词(构建期注入;勿手改本段)──
|
|
20466
|
+
/**
|
|
20467
|
+
* pet-chat.js(客户端)— **桌宠对话气泡**(门 2 / 任务 A3)。
|
|
20468
|
+
*
|
|
20469
|
+
* 契约:宿主 `/folia/pet-chat/*`(见 lib/routes/pet-chat.js)。
|
|
20470
|
+
* · 点桌面上的宠物 → 气泡(输入框 + 最近 6 条);Enter 发送 / Esc 关闭 / Ctrl+Alt+P 唤起
|
|
20471
|
+
* · 回复走 SSE(delta 逐字追加),done 里带 emotion → 映射成宠物动作
|
|
20472
|
+
* · 设置里没开(enabled=false)⇒ 不谈模型,直接给**预设台词库**(30+ 句,按情绪分组)
|
|
20473
|
+
*
|
|
20474
|
+
* 为什么自己读 SSE 而不用 EventSource:聊天是 POST(要带请求体),EventSource 只支持 GET。
|
|
20475
|
+
* 所以用 fetch + response.body 的 reader,按 `\n\n` 切帧自己解 —— 二十来行,换来不被协议绑死。
|
|
20476
|
+
*
|
|
20477
|
+
* 不变量:
|
|
20478
|
+
* · **不碰模型的 key**:key 只在宿主设置里,客户端连读都不读。
|
|
20479
|
+
* · **不自己拼模型端点**:所有请求都打本机 `/folia/pet-chat/*`。
|
|
20480
|
+
* · 气泡是 `position: fixed` 的独立层,不参与面板重渲染(与 pet-layer 同一套思路)。
|
|
20481
|
+
*/
|
|
20482
|
+
/**
|
|
20483
|
+
* 预设台词库(工单 A4):**五组 ≥30 句**。
|
|
20484
|
+
* `enabled=false`(没配模型)与宿主回 `no-model` 两条路径都从这里取,按组轮换。
|
|
20485
|
+
*/
|
|
20486
|
+
const PET_CHAT_PRESET_LINES = {
|
|
20487
|
+
// 问候(6)
|
|
20488
|
+
greeting: ['你来啦!', '在的,随时找我。', '今天也一起看壁纸吧。', '嗨,我在角落待着呢。', '好久没见,忙完了吗?', '我在,有事说一声。'],
|
|
20489
|
+
// 壁纸相关(8)
|
|
20490
|
+
wallpaper: [
|
|
20491
|
+
'这张的配色我挺喜欢的。', '要不要试试轮播?每半小时换一张。', '4K 那张看着真舒服。',
|
|
20492
|
+
'这张有点糊,要换吗?', '桌面空着也行,等你挑到喜欢的。', '夜里的壁纸挑暗一点更护眼。',
|
|
20493
|
+
'刚换的那张,我盯了好一会儿。', '要不要把喜欢的几张放进一个分组?',
|
|
20494
|
+
],
|
|
20495
|
+
// 陪伴与鼓励(8)
|
|
20496
|
+
company: [
|
|
20497
|
+
'慢慢来,不急。', '今天辛苦了。', '喝水了吗?', '卡住就歇五分钟。',
|
|
20498
|
+
'你做得比你以为的好。', '我在这儿,安静陪着也行。', '忙完记得伸个懒腰。',
|
|
20499
|
+
'有我看着桌面,你专心干活。',
|
|
20500
|
+
],
|
|
20501
|
+
// 空状态与失败兜底(5)
|
|
20502
|
+
fallback: [
|
|
20503
|
+
'(还没接上模型,先陪你聊聊天)', '(在设置里填 API Key,我就能正经回你了)',
|
|
20504
|
+
'(模型没回应,等一下再试?)', '(这条没听懂,再说一次?)', '(我在这儿,只是暂时说不上话)',
|
|
20505
|
+
],
|
|
20506
|
+
// 夜间(3)
|
|
20507
|
+
night: ['夜深了,早点休息。', '要不要换张暗一点的壁纸?', '我先趴一会儿,晚安。'],
|
|
20508
|
+
};
|
|
20509
|
+
|
|
20510
|
+
/** 情绪 → 宠物动作轨道(缺轨道时回落 idle,见 petApplyEmotion)。 */
|
|
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
|
+
/** 五组台词按顺序轮换(同一次会话里不重复同一组,比纯随机更像"有人在")。 */
|
|
20679
|
+
let petChatPresetCursor = 0;
|
|
20680
|
+
function petChatPresetLine() {
|
|
20681
|
+
const groups = Object.keys(PET_CHAT_PRESET_LINES);
|
|
20682
|
+
const group = groups[petChatPresetCursor % groups.length];
|
|
20683
|
+
petChatPresetCursor += 1;
|
|
20684
|
+
const lines = PET_CHAT_PRESET_LINES[group] || [];
|
|
20685
|
+
return lines[Math.floor(Math.random() * lines.length)] || '……';
|
|
20686
|
+
}
|
|
20687
|
+
|
|
20688
|
+
/** A2:清空记忆(宿主那边清会话记忆 + 长期偏好)。 */
|
|
20689
|
+
async function petChatResetMemory() {
|
|
20690
|
+
try {
|
|
20691
|
+
const res = await apiPostJson('/pet-chat/reset', {}, { parse: 'always' });
|
|
20692
|
+
if (res && res.ok) petChatStatus(weT('已清空'));
|
|
20693
|
+
else petChatStatus(weT('清空失败'));
|
|
20694
|
+
} catch {
|
|
20695
|
+
petChatStatus(weT('清空失败'));
|
|
20696
|
+
}
|
|
20697
|
+
}
|
|
20698
|
+
|
|
20699
|
+
/** 问宿主"配好没"(失败就当作没配,不弹错误框)。 */
|
|
20700
|
+
async function petChatSyncState() {
|
|
20701
|
+
try {
|
|
20702
|
+
const probe = await apiJson('/pet-chat/state', { parse: 'always' });
|
|
20703
|
+
const doc = probe && probe.data;
|
|
20704
|
+
// 语音输入开关由宿主带回来:false ⇒ 按麦克风只提示"先去 DSH 开",不弹权限框
|
|
20705
|
+
petChatVoiceEnabled = doc && doc.voiceEnabled === true;
|
|
20706
|
+
if (doc && doc.voiceOut && typeof doc.voiceOut === 'object') petChatVoiceOut = doc.voiceOut;
|
|
20707
|
+
if (!doc || doc.enabled !== true) {
|
|
20708
|
+
petChatStatus(weT('未开启对话(设置 → 桌宠 → 桌宠对话)'));
|
|
20709
|
+
return null;
|
|
20710
|
+
}
|
|
20711
|
+
if (doc.reachable === false) {
|
|
20712
|
+
petChatStatus(weT('连不上模型端点') + (doc.lastError ? ':' + doc.lastError : ''));
|
|
20713
|
+
return doc;
|
|
20714
|
+
}
|
|
20715
|
+
petChatStatus(weT('已连接') + ' · ' + String(doc.provider || '') + ' · ' + String(doc.model || ''));
|
|
20716
|
+
return doc;
|
|
20717
|
+
} catch {
|
|
20718
|
+
petChatStatus(weT('宿主没有响应'));
|
|
20719
|
+
return null;
|
|
20720
|
+
}
|
|
20721
|
+
}
|
|
20722
|
+
|
|
20723
|
+
/** 情绪 → 动作:优先用宿主暴露的播放钩子,没有就保持 idle(不报错)。 */
|
|
20724
|
+
function petChatApplyEmotion(emotion) {
|
|
20725
|
+
const track = PET_CHAT_EMOTION_TRACK[emotion] || 'idle';
|
|
20726
|
+
const host = typeof window !== 'undefined' ? window : null;
|
|
20727
|
+
if (!host) return;
|
|
20728
|
+
try {
|
|
20729
|
+
if (typeof host.__wePetPlay === 'function') host.__wePetPlay(track);
|
|
20730
|
+
} catch { /* 播放失败不影响聊天 */ }
|
|
20731
|
+
}
|
|
20732
|
+
|
|
20733
|
+
/** 按 `\n\n` 切 SSE 帧;每帧里 `event: x` + `data: {...}`。 */
|
|
20734
|
+
function petChatParseFrame(frame) {
|
|
20735
|
+
let event = 'message';
|
|
20736
|
+
const dataLines = [];
|
|
20737
|
+
for (const line of frame.split('\n')) {
|
|
20738
|
+
if (line.startsWith('event:')) event = line.slice(6).trim();
|
|
20739
|
+
else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
|
|
20740
|
+
}
|
|
20741
|
+
if (!dataLines.length) return null;
|
|
20742
|
+
try { return { event, data: JSON.parse(dataLines.join('\n')) }; } catch { return null; }
|
|
20743
|
+
}
|
|
20744
|
+
|
|
20745
|
+
/** 发送一句(SSE 流式)。 */
|
|
20746
|
+
async function petChatSend() {
|
|
20747
|
+
if (petChatBusy) return;
|
|
20748
|
+
const els = petChatBuild();
|
|
20749
|
+
if (!els) return;
|
|
20750
|
+
const text = String(els.input.value || '').trim();
|
|
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;
|
|
20785
|
+
return;
|
|
20786
|
+
}
|
|
20787
|
+
const reader = response.body.getReader();
|
|
20788
|
+
const decoder = new TextDecoder();
|
|
20789
|
+
let buffer = '';
|
|
20790
|
+
for (;;) {
|
|
20791
|
+
// eslint-disable-next-line no-await-in-loop -- 流式读取必须逐块等
|
|
20792
|
+
const { value, done } = await reader.read();
|
|
20793
|
+
if (done) break;
|
|
20794
|
+
buffer += decoder.decode(value, { stream: true });
|
|
20795
|
+
const frames = buffer.split('\n\n');
|
|
20796
|
+
buffer = frames.pop() ?? '';
|
|
20797
|
+
for (const frame of frames) {
|
|
20798
|
+
const parsed = petChatParseFrame(frame);
|
|
20799
|
+
if (!parsed) continue;
|
|
20800
|
+
if (parsed.event === 'delta' && parsed.data && typeof parsed.data.t === 'string') {
|
|
20801
|
+
assistant += parsed.data.t;
|
|
20802
|
+
ensureBubble();
|
|
20803
|
+
petChatTts.push(parsed.data.t);
|
|
20804
|
+
petChatLines[petChatLines.length - 1] = { role: 'assistant', text: assistant };
|
|
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
|
+
}
|
|
20816
|
+
}
|
|
20817
|
+
}
|
|
20818
|
+
} catch {
|
|
20819
|
+
petChatStatus(weT('发送失败,重试一次?'));
|
|
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() : [];
|
|
20895
|
+
},
|
|
20896
|
+
getConfig: () => petChatVoiceOut,
|
|
20897
|
+
Utterance: typeof window !== 'undefined' ? window.SpeechSynthesisUtterance : undefined,
|
|
20898
|
+
onHint: (code, message) => petChatStatus(message),
|
|
20899
|
+
});
|
|
20900
|
+
|
|
20901
|
+
/** Float32 PCM → 16kHz 单声道 PCM16 WAV。 */
|
|
20902
|
+
function petChatEncodeWav(samples, sampleRate) {
|
|
20903
|
+
const rate = 16000;
|
|
20904
|
+
const ratio = sampleRate / rate;
|
|
20905
|
+
const frames = Math.max(1, Math.floor(samples.length / ratio));
|
|
20906
|
+
const buffer = new ArrayBuffer(44 + frames * 2);
|
|
20907
|
+
const view = new DataView(buffer);
|
|
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);
|
|
20959
|
+
};
|
|
20960
|
+
source.connect(node);
|
|
20961
|
+
node.connect(ctx.destination);
|
|
20962
|
+
petChatVoice = { stream: media, ctx, node, source, chunks, sampleRate: ctx.sampleRate };
|
|
20963
|
+
petChatStatus(weT('正在听…松手结束'));
|
|
20964
|
+
return true;
|
|
20965
|
+
} catch {
|
|
20966
|
+
// 最典型的是权限被拒(NotAllowedError):提示一行,允许继续打字
|
|
20967
|
+
petChatStatus(weT('没有麦克风权限(或未授权),可以继续打字'));
|
|
20968
|
+
return false;
|
|
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
|
+
}
|
|
21007
|
+
|
|
21008
|
+
/**
|
|
21009
|
+
* C1:每 5 分钟问一次"现在能主动说话吗"。
|
|
21010
|
+
*
|
|
21011
|
+
* 五条件里渲染进程能拿到的事实:开关/计数/间隔/静默时段由宿主判,
|
|
21012
|
+
* 客户端只提供 `fullscreen`(document.fullscreenElement)、`focused`(document.hasFocus())
|
|
21013
|
+
* 和 `idleMinutes`(**窗口内**最近一次键鼠事件距现在多久)。
|
|
21014
|
+
* ⚠️ 这不是系统全局空闲(Electron 的 powerMonitor.getSystemIdleTime 在渲染进程拿不到),
|
|
21015
|
+
* 只是"这个窗口最近有没有人动"的近似 —— 已在 docs/PET-CHAT-DONE.md 写明。
|
|
21016
|
+
*/
|
|
21017
|
+
async function petChatProactiveCheck() {
|
|
21018
|
+
if (petChatBusy) return;
|
|
21019
|
+
const idleMinutes = (Date.now() - petChatLastActivityAt) / 60000;
|
|
21020
|
+
const fullscreen = typeof document !== 'undefined' && Boolean(document.fullscreenElement);
|
|
21021
|
+
const focused = typeof document !== 'undefined' && typeof document.hasFocus === 'function' ? document.hasFocus() : true;
|
|
21022
|
+
try {
|
|
21023
|
+
const res = await apiPostJson('/pet-chat/proactive/tick', { idleMinutes, fullscreen, focused, randomHit: Math.random() < 0.25 }, { parse: 'always' });
|
|
21024
|
+
const doc = (res && res.data) || {};
|
|
21025
|
+
if (doc.line) {
|
|
21026
|
+
petChatShow();
|
|
21027
|
+
petChatPush('assistant', doc.line);
|
|
21028
|
+
}
|
|
21029
|
+
await petChatRefreshUsage();
|
|
21030
|
+
} catch { /* 主动闲聊失败不打扰用户 */ }
|
|
21031
|
+
}
|
|
21032
|
+
|
|
21033
|
+
/** 最近一次窗口内活动的时间(C1 的 idleMinutes 来自它)。 */
|
|
21034
|
+
let petChatLastActivityAt = Date.now();
|
|
21035
|
+
/** 5 分钟检查定时器(渲染进程能拿到的事实,仅窗口内)。 */
|
|
21036
|
+
const PET_CHAT_CHECK_INTERVAL_MS = 5 * 60 * 1000;
|
|
21037
|
+
|
|
21038
|
+
function mountPetChat() {
|
|
21039
|
+
// 宿主 / 测试替身里可能没有 DOM 能力:没有就安静地不挂,而不是让装配层炸掉
|
|
21040
|
+
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function'
|
|
21041
|
+
|| typeof document.createElement !== 'function') {
|
|
21042
|
+
return () => {};
|
|
21043
|
+
}
|
|
21044
|
+
const onDocumentClick = (event) => {
|
|
21045
|
+
const target = event.target;
|
|
21046
|
+
if (!target || typeof target.closest !== 'function') return;
|
|
21047
|
+
if (target.closest('#we-pet-layer')) petChatShow();
|
|
21048
|
+
};
|
|
21049
|
+
const onKeyDown = (event) => {
|
|
21050
|
+
if (event.altKey && event.ctrlKey && String(event.key).toLowerCase() === 'p') {
|
|
21051
|
+
event.preventDefault();
|
|
21052
|
+
petChatToggle();
|
|
21053
|
+
return;
|
|
21054
|
+
}
|
|
21055
|
+
if (event.key === 'Escape' && petChatEls && petChatEls.root.style.display === 'flex') petChatHide();
|
|
21056
|
+
};
|
|
21057
|
+
// C1 的"窗口内活动":键鼠/滚轮/触摸都算(passive,不拦截任何默认行为)
|
|
21058
|
+
const markActivity = () => { petChatLastActivityAt = Date.now(); };
|
|
21059
|
+
const activityEvents = ['mousemove', 'mousedown', 'keydown', 'wheel', 'touchstart'];
|
|
21060
|
+
document.addEventListener('click', onDocumentClick, true);
|
|
21061
|
+
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
|
+
return () => {
|
|
21070
|
+
if (timer && typeof clearInterval === 'function') clearInterval(timer);
|
|
21071
|
+
document.removeEventListener('click', onDocumentClick, true);
|
|
21072
|
+
document.removeEventListener('keydown', onKeyDown, true);
|
|
21073
|
+
for (const name of activityEvents) window.removeEventListener(name, markActivity);
|
|
21074
|
+
if (petChatEls && petChatEls.root.parentNode) petChatEls.root.parentNode.removeChild(petChatEls.root);
|
|
21075
|
+
petChatEls = null;
|
|
21076
|
+
petChatLines = [];
|
|
21077
|
+
};
|
|
21078
|
+
}
|
|
21079
|
+
|
|
20171
21080
|
// ── 内联模块:src/features.js —— 客户端功能注册表:页签条 / 整区面板 / 常驻挂载层。装配点(quick-panel、client.js)只查表,不写功能名(构建期注入;勿手改本段)──
|
|
20172
21081
|
/**
|
|
20173
21082
|
* features.js(客户端)— **功能注册表**:页签声明、面板工厂、挂载钩子。
|
|
@@ -20246,6 +21155,8 @@ window.__ModuleLoader__.load({
|
|
|
20246
21155
|
*/
|
|
20247
21156
|
const WE_FEATURE_MOUNTS = [
|
|
20248
21157
|
{ id: "pets", mount: mountPetLayer },
|
|
21158
|
+
// 桌宠对话的气泡层:点宠物才出现,不点就只是两条监听。
|
|
21159
|
+
{ id: "pet-chat", mount: mountPetChat },
|
|
20249
21160
|
// 皮肤兼容层:补写 `data-pane` / `data-dsh-frame`(皮肤包写的是 web-all 的 compat 词表)。
|
|
20250
21161
|
// 它只写自己的惰性属性、幂等、可失败,所以随墙纸引擎常驻,不依赖皮肤是否在台上。
|
|
20251
21162
|
{ id: "skin-compat", mount: installSkinCompat },
|