dsh-folia 4.26.0-pre.44 → 4.26.0-pre.46
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 +633 -41
- package/lib/routes/pet-chat.js +317 -92
- package/lib/tts/tts-worker.cjs +504 -98
- package/lib/tts/tts.js +409 -0
- package/lib/voice/record.js +91 -14
- package/package.json +2 -2
package/lib/client.js
CHANGED
|
@@ -946,6 +946,9 @@ window.__ModuleLoader__.load({
|
|
|
946
946
|
"提交中…(正在准备)": "Submitting… (preparing)",
|
|
947
947
|
"已等待 {s} 秒": "Waiting {s}s",
|
|
948
948
|
"解压/落位中…": "Extracting…",
|
|
949
|
+
// pre.46:挂载自愈的 3 次退避重试期间,卡片显示“正在补收尾…”而不是干等 90 秒。
|
|
950
|
+
"正在补收尾…": "Finishing install…",
|
|
951
|
+
"第 {a}/{t} 次 · 下载已完成,正在补落地": "Attempt {a}/{t} · download finished, finishing install",
|
|
949
952
|
// ── 「下载已完成但安装没落地」的自愈(4.23.6)──────────────────────────────
|
|
950
953
|
// 死锁形态:job=done、落地没发生、卡片永远「解压/落位中…」。两类文案:
|
|
951
954
|
// ① 超时之后**结果**(失败原因,卡片上的红字 +「重试」);
|
|
@@ -18025,18 +18028,23 @@ window.__ModuleLoader__.load({
|
|
|
18025
18028
|
doneOf: (c) => Boolean(c.installed),
|
|
18026
18029
|
path: "/boot/download",
|
|
18027
18030
|
body: (c) => ({ id: c.id }),
|
|
18028
|
-
|
|
18031
|
+
// pre.46:一次 → 0s / 3s / 8s 三次退避;全部失败才把原因写到卡片上。
|
|
18032
|
+
attempts: 3,
|
|
18033
|
+
backoff: [3000, 8000],
|
|
18034
|
+
onTry: (c, attempt, total) => {
|
|
18029
18035
|
if (!alive) return;
|
|
18036
|
+
cards.heal(c.id, attempt, total);
|
|
18030
18037
|
setNote({ ok: true, text: weT("下载已完成但没落地,正在自动收尾:{name}", { name: c.title || c.id }) });
|
|
18031
18038
|
},
|
|
18032
18039
|
onOk: (c) => {
|
|
18033
18040
|
if (!alive) return;
|
|
18041
|
+
cards.healOk(c.id);
|
|
18034
18042
|
setNote({ ok: true, text: weT("下载已完成,已自动收尾:{name}", { name: c.title || c.id }) });
|
|
18035
18043
|
load(true);
|
|
18036
18044
|
},
|
|
18037
18045
|
onFail: (c, code) => {
|
|
18038
18046
|
if (!alive) return;
|
|
18039
|
-
cards.
|
|
18047
|
+
cards.healFail(c.id, code);
|
|
18040
18048
|
setNote({ ok: false, text: weT("自动收尾失败:{why}", { why: dlFailReason(code) }) });
|
|
18041
18049
|
},
|
|
18042
18050
|
}).catch(() => { /* dlHealStuck 内部已兜住 */ });
|
|
@@ -20086,19 +20094,23 @@ window.__ModuleLoader__.load({
|
|
|
20086
20094
|
doneOf: (it) => Boolean(it.installed) || cards.okOf(it.id),
|
|
20087
20095
|
path: "/skins/install",
|
|
20088
20096
|
body: (it) => ({ id: it.id, url: it.url }),
|
|
20089
|
-
|
|
20097
|
+
// pre.46:一次 → 0s / 3s / 8s 三次退避;全部失败才把原因写到卡片上。
|
|
20098
|
+
attempts: 3,
|
|
20099
|
+
backoff: [3000, 8000],
|
|
20100
|
+
onTry: (it, attempt, total) => {
|
|
20090
20101
|
if (!alive) return;
|
|
20102
|
+
cards.heal(it.id, attempt, total);
|
|
20091
20103
|
setNote({ ok: true, text: weT("下载已完成但没落地,正在自动补装:{name}", { name: it.title || it.id }) });
|
|
20092
20104
|
},
|
|
20093
20105
|
onOk: (it) => {
|
|
20094
20106
|
if (!alive) return;
|
|
20095
|
-
cards.
|
|
20107
|
+
cards.healOk(it.id);
|
|
20096
20108
|
setNote({ ok: true, text: weT("下载已完成,已自动补装:{name} —— 点「应用」就能切换", { name: it.title || it.id }) });
|
|
20097
20109
|
load(true);
|
|
20098
20110
|
},
|
|
20099
20111
|
onFail: (it, code) => {
|
|
20100
20112
|
if (!alive) return;
|
|
20101
|
-
cards.
|
|
20113
|
+
cards.healFail(it.id, code);
|
|
20102
20114
|
setNote({ ok: false, text: weT("自动补装失败:{why}", { why: dlFailReason(code) }) });
|
|
20103
20115
|
},
|
|
20104
20116
|
}).catch(() => { /* dlHealStuck 内部已兜住;这里只防未处理的 rejection */ });
|
|
@@ -20924,6 +20936,12 @@ window.__ModuleLoader__.load({
|
|
|
20924
20936
|
const onText = typeof options.onText === 'function' ? options.onText : () => {};
|
|
20925
20937
|
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
20926
20938
|
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
20939
|
+
/**
|
|
20940
|
+
* barge-in(P1):**录音一开始**先停掉正在播的朗读。
|
|
20941
|
+
* 做成注入点而不是在这里直接引用 petSpeakStop:模块在构建期被内联进同一作用域,
|
|
20942
|
+
* 直接引用会把“朗读”与“录音”焊死;注入后判据也能用假函数断言调用顺序。
|
|
20943
|
+
*/
|
|
20944
|
+
const onBeforeRecord = typeof options.onBeforeRecord === 'function' ? options.onBeforeRecord : () => {};
|
|
20927
20945
|
|
|
20928
20946
|
let active = false;
|
|
20929
20947
|
|
|
@@ -20936,6 +20954,8 @@ window.__ModuleLoader__.load({
|
|
|
20936
20954
|
async function start() {
|
|
20937
20955
|
if (active) return true;
|
|
20938
20956
|
active = true;
|
|
20957
|
+
// ⚠️ 顺序是判据:先打断朗读,再开麦(用户一说话就把桌宠的声音掐掉)
|
|
20958
|
+
try { onBeforeRecord(); } catch { /* 打断失败不能挡住录音 */ }
|
|
20939
20959
|
onState({ state: 'listening' });
|
|
20940
20960
|
let result;
|
|
20941
20961
|
try {
|
|
@@ -21021,6 +21041,40 @@ window.__ModuleLoader__.load({
|
|
|
21021
21041
|
let text = '';
|
|
21022
21042
|
let visible = false;
|
|
21023
21043
|
let fadeTimer = null;
|
|
21044
|
+
let stylesInjected = false;
|
|
21045
|
+
|
|
21046
|
+
/**
|
|
21047
|
+
* 三态与“说”的波形(P1):
|
|
21048
|
+
* listen / think / speak / idle —— 只改 `data-state`,由一小段**无颜色**的 CSS 表现:
|
|
21049
|
+
* · listen:正文前的实心点;think:省略号;speak:正文下一排四根跳动竖条。
|
|
21050
|
+
* 用伪元素而不是新增 DOM 子节点,是因为气泡正文一直用 `textContent` 整体写入
|
|
21051
|
+
* (设 textContent 会把子节点一起清掉);伪元素不会被它清掉,也不会引入第二种“文字容器”。
|
|
21052
|
+
*/
|
|
21053
|
+
const WAVE_CSS = [
|
|
21054
|
+
'.we-pet-bubble[data-state="listen"]::before{content:"●";margin-right:4px;opacity:.55;}',
|
|
21055
|
+
'.we-pet-bubble[data-state="think"]::before{content:"…";margin-right:4px;opacity:.6;}',
|
|
21056
|
+
'.we-pet-bubble[data-state="speak"]::after{content:"";display:block;width:34px;height:10px;margin-top:6px;opacity:.85;',
|
|
21057
|
+
'background:',
|
|
21058
|
+
'linear-gradient(currentColor,currentColor) 0 100%/3px 45% no-repeat,',
|
|
21059
|
+
'linear-gradient(currentColor,currentColor) 8px 100%/3px 90% no-repeat,',
|
|
21060
|
+
'linear-gradient(currentColor,currentColor) 16px 100%/3px 60% no-repeat,',
|
|
21061
|
+
'linear-gradient(currentColor,currentColor) 24px 100%/3px 100% no-repeat;',
|
|
21062
|
+
'transform-origin:0 100%;animation:we-pet-bubble-wave .8s ease-in-out infinite alternate;}',
|
|
21063
|
+
'@keyframes we-pet-bubble-wave{from{transform:scaleY(.55);opacity:.55;}to{transform:scaleY(1);opacity:.95;}}',
|
|
21064
|
+
].join('');
|
|
21065
|
+
|
|
21066
|
+
/** 只注入一次;没有 head 的环境(判据的极简 DOM)静默跳过。 */
|
|
21067
|
+
function ensureStyles() {
|
|
21068
|
+
if (stylesInjected) return;
|
|
21069
|
+
stylesInjected = true;
|
|
21070
|
+
try {
|
|
21071
|
+
if (!doc || !doc.head || typeof doc.createElement !== 'function') return;
|
|
21072
|
+
const style = doc.createElement('style');
|
|
21073
|
+
style.setAttribute('data-folia-pet-bubble', '1');
|
|
21074
|
+
style.textContent = WAVE_CSS;
|
|
21075
|
+
if (typeof doc.head.appendChild === 'function') doc.head.appendChild(style);
|
|
21076
|
+
} catch { /* 气泡是装饰层,样式失败不能影响显示 */ }
|
|
21077
|
+
}
|
|
21024
21078
|
|
|
21025
21079
|
/** 锚点 → 气泡位置:水平居中于桌宠,垂直贴在头顶上方。 */
|
|
21026
21080
|
function place() {
|
|
@@ -21115,9 +21169,10 @@ window.__ModuleLoader__.load({
|
|
|
21115
21169
|
doHide();
|
|
21116
21170
|
}
|
|
21117
21171
|
|
|
21118
|
-
/** 状态:听 / 想 /
|
|
21172
|
+
/** 状态:听 / 想 / 说(客户端据此换桌宠动作、气泡配色与波形)。 */
|
|
21119
21173
|
function setState(kind) {
|
|
21120
|
-
if (!
|
|
21174
|
+
if (!ensure()) return;
|
|
21175
|
+
ensureStyles();
|
|
21121
21176
|
el.dataset = el.dataset || {};
|
|
21122
21177
|
el.dataset.state = String(kind || '');
|
|
21123
21178
|
}
|
|
@@ -21143,14 +21198,323 @@ window.__ModuleLoader__.load({
|
|
|
21143
21198
|
};
|
|
21144
21199
|
}
|
|
21145
21200
|
|
|
21146
|
-
// ── 内联模块:src/pet-
|
|
21201
|
+
// ── 内联模块:src/pet-tts.js —— 桌宠朗读客户端:petTtsSplit 切句 / 排队播放 / 预取下一句 / stop 清队列 / 句字幕回调(构建期注入;勿手改本段)──
|
|
21147
21202
|
/**
|
|
21148
|
-
* pet-
|
|
21203
|
+
* pet-tts.js(客户端)— 桌宠朗读:**按句合成 / 排队播放 / 字幕 / barge-in**。
|
|
21204
|
+
*
|
|
21205
|
+
* 为什么不把整段文字一次合成:
|
|
21206
|
+
* · 第一句能先出声(模型刚说完第一句就开始念,不等整段);
|
|
21207
|
+
* · 一句失败只影响一句,不会“整段静音”;
|
|
21208
|
+
* · stop 时清队列即可立刻闭嘴,不需要等一个长请求。
|
|
21149
21209
|
*
|
|
21150
|
-
*
|
|
21151
|
-
*
|
|
21210
|
+
* 依赖全部注入(apiFetch / Audio / URL / 回调),所以 Node 里能用假播放器跑判据;
|
|
21211
|
+
* 浏览器侧由 `src/pet-chat.js` 用真实 `Audio` 与 `URL.createObjectURL` 构造。
|
|
21212
|
+
*
|
|
21213
|
+
* 与宿主的分工:
|
|
21214
|
+
* · 宿主负责“SAPI → Edge 系统音色 → 明确错误”的兜底链,返回 `audio/wav`;
|
|
21215
|
+
* · 客户端只负责切句、排队、播、停、把当前句交给气泡显示。
|
|
21216
|
+
*/
|
|
21217
|
+
|
|
21218
|
+
/** 单句上限:超过就在标点/字数处切开(与宿主路由的 240 字上限配合)。 */
|
|
21219
|
+
const PET_TTS_MAX_SENTENCE = 48;
|
|
21220
|
+
/** 一次最多几句:再长也只念前 8 句(防止任务提醒念一整篇)。 */
|
|
21221
|
+
const PET_TTS_MAX_PIECES = 8;
|
|
21222
|
+
/** 与宿主 `TTS_MAX_CHARS` 对齐的总上限。 */
|
|
21223
|
+
const PET_TTS_MAX_CHARS = 240;
|
|
21224
|
+
|
|
21225
|
+
/**
|
|
21226
|
+
* 纯函数:把一段文字切成“适合一句一合成”的片段。
|
|
21227
|
+
* 优先在句末标点切;长句在逗号处或硬上限处切。
|
|
21228
|
+
*/
|
|
21229
|
+
function petTtsSplit(text) {
|
|
21230
|
+
const raw = String(text == null ? '' : text).replace(/\s+/g, ' ').trim().slice(0, PET_TTS_MAX_CHARS);
|
|
21231
|
+
if (!raw) return [];
|
|
21232
|
+
const pieces = [];
|
|
21233
|
+
let buffer = '';
|
|
21234
|
+
const flush = () => {
|
|
21235
|
+
const piece = buffer.trim();
|
|
21236
|
+
buffer = '';
|
|
21237
|
+
if (piece) pieces.push(piece);
|
|
21238
|
+
};
|
|
21239
|
+
for (const ch of raw) {
|
|
21240
|
+
buffer += ch;
|
|
21241
|
+
const ends = /[。!?!?;;\n]/.test(ch);
|
|
21242
|
+
const commaCut = /[,,、]/.test(ch) && buffer.length >= PET_TTS_MAX_SENTENCE * 0.7;
|
|
21243
|
+
const hardCut = buffer.length >= PET_TTS_MAX_SENTENCE;
|
|
21244
|
+
if (ends || commaCut || hardCut) flush();
|
|
21245
|
+
if (pieces.length >= PET_TTS_MAX_PIECES) break;
|
|
21246
|
+
}
|
|
21247
|
+
flush();
|
|
21248
|
+
return pieces.slice(0, PET_TTS_MAX_PIECES);
|
|
21249
|
+
}
|
|
21250
|
+
|
|
21251
|
+
/**
|
|
21252
|
+
* 纯函数:流式场景下“已经说完的句子”与“还没说完的尾巴”。
|
|
21253
|
+
* SSE 每来一小段就调用一次,把完整句立刻入队(第一句更早出声)。
|
|
21254
|
+
*/
|
|
21255
|
+
function petTtsSentences(text) {
|
|
21256
|
+
const raw = String(text == null ? '' : text);
|
|
21257
|
+
const sentences = [];
|
|
21258
|
+
let start = 0;
|
|
21259
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
21260
|
+
if (/[。!?!?;;\n]/.test(raw[i])) {
|
|
21261
|
+
const piece = raw.slice(start, i + 1).trim();
|
|
21262
|
+
if (piece) sentences.push(piece);
|
|
21263
|
+
start = i + 1;
|
|
21264
|
+
}
|
|
21265
|
+
}
|
|
21266
|
+
let rest = raw.slice(start);
|
|
21267
|
+
// 没有标点的长句也要在安全长度切开,避免一直等到整段结束
|
|
21268
|
+
if (rest.length >= PET_TTS_MAX_SENTENCE) {
|
|
21269
|
+
const cut = rest.lastIndexOf(',', PET_TTS_MAX_SENTENCE);
|
|
21270
|
+
const at = cut > 8 ? cut + 1 : PET_TTS_MAX_SENTENCE;
|
|
21271
|
+
sentences.push(rest.slice(0, at).trim());
|
|
21272
|
+
rest = rest.slice(at);
|
|
21273
|
+
}
|
|
21274
|
+
return { sentences, rest };
|
|
21275
|
+
}
|
|
21276
|
+
|
|
21277
|
+
/**
|
|
21278
|
+
* @param {{
|
|
21279
|
+
* apiFetch: Function,
|
|
21280
|
+
* apiPostJson?: Function,
|
|
21281
|
+
* Audio?: Function,
|
|
21282
|
+
* URL?: object,
|
|
21283
|
+
* getVoice?: () => {name?: string, muted?: boolean, rate?: number},
|
|
21284
|
+
* onSentence?: (text: string) => void,
|
|
21285
|
+
* onState?: (state: 'speak'|'idle') => void,
|
|
21286
|
+
* onError?: (error: {code: string, hint?: string, status?: number}) => void,
|
|
21287
|
+
* onIdle?: () => void,
|
|
21288
|
+
* log?: (line: string) => void,
|
|
21289
|
+
* }} deps
|
|
21290
|
+
*/
|
|
21291
|
+
function petTtsCreate(deps) {
|
|
21292
|
+
const options = deps || {};
|
|
21293
|
+
const apiFetch = options.apiFetch;
|
|
21294
|
+
const apiPostJson = options.apiPostJson;
|
|
21295
|
+
const AudioCtor = typeof options.Audio === 'function' ? options.Audio : null;
|
|
21296
|
+
const UrlApi = options.URL || null;
|
|
21297
|
+
const getVoice = typeof options.getVoice === 'function' ? options.getVoice : () => ({});
|
|
21298
|
+
const onSentence = typeof options.onSentence === 'function' ? options.onSentence : () => {};
|
|
21299
|
+
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
21300
|
+
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
21301
|
+
const onIdle = typeof options.onIdle === 'function' ? options.onIdle : () => {};
|
|
21302
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
21303
|
+
|
|
21304
|
+
let generation = 0;
|
|
21305
|
+
let queue = [];
|
|
21306
|
+
let busy = false;
|
|
21307
|
+
let playing = null;
|
|
21308
|
+
let prefetch = null;
|
|
21309
|
+
let disposed = false;
|
|
21310
|
+
|
|
21311
|
+
function revoke(url) {
|
|
21312
|
+
if (!url || !UrlApi || typeof UrlApi.revokeObjectURL !== 'function') return;
|
|
21313
|
+
try { UrlApi.revokeObjectURL(url); } catch { /* ignore */ }
|
|
21314
|
+
}
|
|
21315
|
+
|
|
21316
|
+
/** 取一句的 WAV:成功 `{url,size}`,失败 `{error}`,被 stop `{stopped:true}`。 */
|
|
21317
|
+
async function fetchSpeech(item, gen) {
|
|
21318
|
+
if (typeof apiFetch !== 'function') {
|
|
21319
|
+
return { error: { code: 'tts-unavailable', hint: '这个版本没有接朗读接口' } };
|
|
21320
|
+
}
|
|
21321
|
+
const query = '/pet-chat/tts?text=' + encodeURIComponent(item.text)
|
|
21322
|
+
+ '&voice=' + encodeURIComponent(item.voice || '')
|
|
21323
|
+
+ '&rate=' + encodeURIComponent(String(item.rate));
|
|
21324
|
+
let res;
|
|
21325
|
+
let blob;
|
|
21326
|
+
try {
|
|
21327
|
+
// parse:false:**二进制体**不能交给默认的 json() 解析(流会被吃掉);
|
|
21328
|
+
// 这里的 blob() 必须和它在同一个调用窗里(verify-api-client ①b 的判据)。
|
|
21329
|
+
res = await apiFetch(query, { parse: false, cache: 'no-store' });
|
|
21330
|
+
if (gen !== generation) return { stopped: true };
|
|
21331
|
+
if (!res || !res.ok || !res.response) {
|
|
21332
|
+
let hint = '';
|
|
21333
|
+
try {
|
|
21334
|
+
if (res && res.response && typeof res.response.json === 'function') {
|
|
21335
|
+
const doc = await res.response.json();
|
|
21336
|
+
hint = String((doc && doc.hint) || '');
|
|
21337
|
+
}
|
|
21338
|
+
} catch { /* 非 JSON 错误体 */ }
|
|
21339
|
+
return { error: { code: 'tts-failed', status: (res && res.status) || 0, hint: hint || '语音合成失败' } };
|
|
21340
|
+
}
|
|
21341
|
+
blob = await res.response.blob();
|
|
21342
|
+
} catch (error) {
|
|
21343
|
+
if (!res) return { error: { code: 'tts-network', hint: '连不上宿主,语音没出来' } };
|
|
21344
|
+
return { error: { code: 'tts-read-failed', hint: '读不到语音数据' } };
|
|
21345
|
+
}
|
|
21346
|
+
if (!blob || !blob.size) return { error: { code: 'tts-empty', hint: '没合成出声音' } };
|
|
21347
|
+
let url = '';
|
|
21348
|
+
if (UrlApi && typeof UrlApi.createObjectURL === 'function') {
|
|
21349
|
+
try { url = UrlApi.createObjectURL(blob); } catch { url = ''; }
|
|
21350
|
+
}
|
|
21351
|
+
if (!url) return { error: { code: 'tts-audio-unavailable', hint: '这个环境不能播放音频' } };
|
|
21352
|
+
return { url, size: blob.size };
|
|
21353
|
+
}
|
|
21354
|
+
|
|
21355
|
+
/** 播一句;stop 时由 `entry.finish` 立即结束 Promise。 */
|
|
21356
|
+
function playSpeech(item, prepared, gen) {
|
|
21357
|
+
return new Promise((resolve) => {
|
|
21358
|
+
let audio;
|
|
21359
|
+
try {
|
|
21360
|
+
audio = new AudioCtor(prepared.url);
|
|
21361
|
+
} catch (error) {
|
|
21362
|
+
resolve({ code: 'tts-audio', hint: '播放器创建失败' });
|
|
21363
|
+
return;
|
|
21364
|
+
}
|
|
21365
|
+
const entry = { audio, url: prepared.url, finish: null };
|
|
21366
|
+
let settled = false;
|
|
21367
|
+
const finish = (error) => {
|
|
21368
|
+
if (settled) return;
|
|
21369
|
+
settled = true;
|
|
21370
|
+
if (playing === entry) playing = null;
|
|
21371
|
+
revoke(prepared.url);
|
|
21372
|
+
resolve(error || null);
|
|
21373
|
+
};
|
|
21374
|
+
entry.finish = finish;
|
|
21375
|
+
playing = entry;
|
|
21376
|
+
onState('speak');
|
|
21377
|
+
onSentence(item.text);
|
|
21378
|
+
audio.onended = () => finish(null);
|
|
21379
|
+
audio.onerror = () => finish({ code: 'tts-play-failed', hint: '这条语音播放失败' });
|
|
21380
|
+
try {
|
|
21381
|
+
const ret = audio.play();
|
|
21382
|
+
if (ret && typeof ret.then === 'function') {
|
|
21383
|
+
ret.catch(() => finish({ code: 'tts-blocked', hint: '系统拦了自动播放,点一下桌宠再试' }));
|
|
21384
|
+
}
|
|
21385
|
+
} catch (error) {
|
|
21386
|
+
finish({ code: 'tts-blocked', hint: '系统拦了自动播放,点一下桌宠再试' });
|
|
21387
|
+
}
|
|
21388
|
+
if (gen !== generation) finish(null);
|
|
21389
|
+
});
|
|
21390
|
+
}
|
|
21391
|
+
|
|
21392
|
+
function startPrefetch(gen) {
|
|
21393
|
+
if (prefetch || !queue.length) return;
|
|
21394
|
+
const item = queue[0];
|
|
21395
|
+
if (item.gen !== gen) return;
|
|
21396
|
+
prefetch = { item, gen, promise: fetchSpeech(item, gen) };
|
|
21397
|
+
}
|
|
21398
|
+
|
|
21399
|
+
async function pump(gen) {
|
|
21400
|
+
if (busy || disposed) return;
|
|
21401
|
+
busy = true;
|
|
21402
|
+
try {
|
|
21403
|
+
while (queue.length) {
|
|
21404
|
+
const item = queue[0];
|
|
21405
|
+
// stop 之后的新一批有自己的 pump;旧 pump 不许动它
|
|
21406
|
+
if (item.gen !== gen) break;
|
|
21407
|
+
let prepared;
|
|
21408
|
+
if (prefetch && prefetch.item === item && prefetch.gen === gen) {
|
|
21409
|
+
prepared = await prefetch.promise;
|
|
21410
|
+
prefetch = null;
|
|
21411
|
+
} else {
|
|
21412
|
+
prepared = await fetchSpeech(item, gen);
|
|
21413
|
+
}
|
|
21414
|
+
if (item.gen !== generation) { queue.shift(); if (prepared && prepared.url) revoke(prepared.url); break; }
|
|
21415
|
+
if (!prepared || prepared.error) {
|
|
21416
|
+
queue.length = 0;
|
|
21417
|
+
onState('idle');
|
|
21418
|
+
onError((prepared && prepared.error) || { code: 'tts-failed', hint: '语音合成失败' });
|
|
21419
|
+
break;
|
|
21420
|
+
}
|
|
21421
|
+
queue.shift();
|
|
21422
|
+
startPrefetch(gen);
|
|
21423
|
+
const error = await playSpeech(item, prepared, gen);
|
|
21424
|
+
if (item.gen !== generation) break;
|
|
21425
|
+
if (error) {
|
|
21426
|
+
queue.length = 0;
|
|
21427
|
+
onState('idle');
|
|
21428
|
+
onError(error);
|
|
21429
|
+
break;
|
|
21430
|
+
}
|
|
21431
|
+
}
|
|
21432
|
+
} finally {
|
|
21433
|
+
busy = false;
|
|
21434
|
+
if (disposed) {
|
|
21435
|
+
// 已销毁:不再启动下一批,也不再回调界面
|
|
21436
|
+
} else if (queue.length && queue[0].gen === generation) {
|
|
21437
|
+
// stop 之后又来了新的一批:旧 pump 收尾时把接力棒交出去
|
|
21438
|
+
void pump(queue[0].gen);
|
|
21439
|
+
} else if (gen === generation && !queue.length && !playing) {
|
|
21440
|
+
onState('idle');
|
|
21441
|
+
onIdle();
|
|
21442
|
+
}
|
|
21443
|
+
}
|
|
21444
|
+
}
|
|
21445
|
+
|
|
21446
|
+
/** 停止:清队列 + 停当前音频 + 通知宿主作废在途合成(幂等)。 */
|
|
21447
|
+
function stop() {
|
|
21448
|
+
generation += 1;
|
|
21449
|
+
queue = [];
|
|
21450
|
+
prefetch = null;
|
|
21451
|
+
if (playing) {
|
|
21452
|
+
const entry = playing;
|
|
21453
|
+
playing = null;
|
|
21454
|
+
try { entry.audio.pause(); } catch { /* ignore */ }
|
|
21455
|
+
if (typeof entry.finish === 'function') entry.finish(null);
|
|
21456
|
+
revoke(entry.url);
|
|
21457
|
+
}
|
|
21458
|
+
onState('idle');
|
|
21459
|
+
if (typeof apiPostJson === 'function') {
|
|
21460
|
+
try {
|
|
21461
|
+
const ret = apiPostJson('/pet-chat/tts/stop', {});
|
|
21462
|
+
if (ret && typeof ret.catch === 'function') ret.catch(() => {});
|
|
21463
|
+
} catch { /* 停不下来也不能抛给界面 */ }
|
|
21464
|
+
}
|
|
21465
|
+
return true;
|
|
21466
|
+
}
|
|
21467
|
+
|
|
21468
|
+
/**
|
|
21469
|
+
* 说一段话(会按句切开排队)。
|
|
21470
|
+
* @returns {boolean} 是否入队(静音 / 空文本 / 环境不支持时 false)
|
|
21471
|
+
*/
|
|
21472
|
+
function speak(text, speech) {
|
|
21473
|
+
if (disposed) return false;
|
|
21474
|
+
const cfg = getVoice() || {};
|
|
21475
|
+
if (cfg.muted === true) { onState('idle'); return false; }
|
|
21476
|
+
const pieces = petTtsSplit(text);
|
|
21477
|
+
if (!pieces.length) return false;
|
|
21478
|
+
if (!AudioCtor) {
|
|
21479
|
+
onError({ code: 'tts-no-audio', hint: '这个环境不能播放声音' });
|
|
21480
|
+
return false;
|
|
21481
|
+
}
|
|
21482
|
+
const speechOpts = speech || {};
|
|
21483
|
+
const voice = String(speechOpts.voice || cfg.name || '');
|
|
21484
|
+
const rawRate = speechOpts.rate !== undefined ? speechOpts.rate : cfg.rate;
|
|
21485
|
+
const rate = Number.isFinite(Number(rawRate)) ? Number(rawRate) : 0;
|
|
21486
|
+
const gen = generation;
|
|
21487
|
+
for (const piece of pieces) queue.push({ text: piece, voice, rate, gen });
|
|
21488
|
+
log('[pet-tts] queue ' + pieces.length + ' sentence(s) voice=' + (voice || '(auto)'));
|
|
21489
|
+
void pump(gen);
|
|
21490
|
+
return true;
|
|
21491
|
+
}
|
|
21492
|
+
|
|
21493
|
+
function isSpeaking() {
|
|
21494
|
+
return Boolean(playing) || queue.length > 0 || busy;
|
|
21495
|
+
}
|
|
21496
|
+
|
|
21497
|
+
function state() {
|
|
21498
|
+
return { busy, playing: Boolean(playing), queued: queue.length, generation };
|
|
21499
|
+
}
|
|
21500
|
+
|
|
21501
|
+
function dispose() {
|
|
21502
|
+
if (disposed) return;
|
|
21503
|
+
stop();
|
|
21504
|
+
disposed = true;
|
|
21505
|
+
}
|
|
21506
|
+
|
|
21507
|
+
return { speak, stop, isSpeaking, state, dispose };
|
|
21508
|
+
}
|
|
21509
|
+
|
|
21510
|
+
/* 供判据从产物/源码里取纯函数;浏览器侧由 pet-chat.js 构造实例。 */
|
|
21511
|
+
|
|
21512
|
+
// ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
|
|
21513
|
+
/**
|
|
21514
|
+
* pet-chat.js — 桌宠语音助手(P1:语音输入 + 朗读 + 头顶气泡 + 主动搭话)。
|
|
21152
21515
|
*
|
|
21153
|
-
* 交互:点桌宠 = 唤醒 →
|
|
21516
|
+
* 交互:点桌宠 = 唤醒 → 录音(说完自动停)→ 转写 → SSE 回答 → 按句朗读
|
|
21517
|
+
* (气泡逐句字幕 + “说”态波形);说话/点击/打字都先打断当前朗读。
|
|
21154
21518
|
* 没有聊天窗口:无输入框、无历史列表、无开关按钮。
|
|
21155
21519
|
*/
|
|
21156
21520
|
const PET_CHAT_PRESET_LINES = {
|
|
@@ -21232,8 +21596,7 @@ window.__ModuleLoader__.load({
|
|
|
21232
21596
|
* 然后轮询 /pet-chat/asr 把下载进度显示在气泡里。
|
|
21233
21597
|
* 这样用户装完插件直接说话就行,不需要去 DSH 设置里找「语音输入」开关。
|
|
21234
21598
|
*/
|
|
21235
|
-
async function ensureAsrReady() {
|
|
21236
|
-
petBubble.setState('think');
|
|
21599
|
+
async function ensureAsrReady() { petBubble.setState('think');
|
|
21237
21600
|
try {
|
|
21238
21601
|
await apiPostJson('/pet-chat/asr', {}, { parse: 'always' });
|
|
21239
21602
|
} catch { /* 触发失败也要继续轮询看状态 */ }
|
|
@@ -21265,14 +21628,72 @@ window.__ModuleLoader__.load({
|
|
|
21265
21628
|
petBubble.hide(3000);
|
|
21266
21629
|
}
|
|
21267
21630
|
|
|
21631
|
+
/**
|
|
21632
|
+
* 朗读配置(P1):`/pet-chat/state` 的 voice 字段。
|
|
21633
|
+
*
|
|
21634
|
+
* 懒加载:挂载时与每次唤醒时各刷一次(设置面板改完立刻生效,不用重启)。
|
|
21635
|
+
* 读不到就保持“不静音”,宁可多念一句,也不要让用户以为朗读坏了。
|
|
21636
|
+
*/
|
|
21637
|
+
let petChatVoice = { name: '', muted: false, rate: 0 };
|
|
21638
|
+
async function petChatRefreshVoice() {
|
|
21639
|
+
try {
|
|
21640
|
+
const resp = await apiJson('/pet-chat/state', { parse: 'always' });
|
|
21641
|
+
const doc = (resp && resp.data) || {};
|
|
21642
|
+
if (doc.voice && typeof doc.voice === 'object') {
|
|
21643
|
+
petChatVoice = {
|
|
21644
|
+
name: String(doc.voice.name || ''),
|
|
21645
|
+
muted: doc.voice.muted === true,
|
|
21646
|
+
rate: Number.isFinite(Number(doc.voice.rate)) ? Number(doc.voice.rate) : 0,
|
|
21647
|
+
};
|
|
21648
|
+
}
|
|
21649
|
+
} catch { /* 读不到就用默认(不静音) */ }
|
|
21650
|
+
return petChatVoice;
|
|
21651
|
+
}
|
|
21652
|
+
|
|
21653
|
+
/**
|
|
21654
|
+
* 朗读实例(P1):宿主负责合成兜底,这里负责切句、排队、播、停、字幕同步。
|
|
21655
|
+
* 回调全部接到气泡:说 → `speak` 态 + 当前句;停/念完 → `idle` + 3 秒后淡出。
|
|
21656
|
+
*/
|
|
21657
|
+
const petTts = petTtsCreate({
|
|
21658
|
+
// ⚠️ 包一层再传:`api-client.js` 的内联位置在 `pet-chat.js` **之后**,
|
|
21659
|
+
// 直接 `apiFetch` / `apiPostJson` 会在模块求值期触发 TDZ
|
|
21660
|
+
// (真机/冒烟统一症状:Cannot access 'apiPostJson' before initialization)。
|
|
21661
|
+
apiFetch: (path, opts) => apiFetch(path, opts),
|
|
21662
|
+
apiPostJson: (path, payload, opts) => apiPostJson(path, payload, opts),
|
|
21663
|
+
Audio: typeof Audio === 'function' ? Audio : null,
|
|
21664
|
+
URL: typeof URL === 'function' ? URL : null,
|
|
21665
|
+
getVoice: () => petChatVoice,
|
|
21666
|
+
onSentence: (text) => {
|
|
21667
|
+
petBubble.setState('speak');
|
|
21668
|
+
petBubble.show(text);
|
|
21669
|
+
},
|
|
21670
|
+
onState: (kind) => { petBubble.setState(kind); },
|
|
21671
|
+
onIdle: () => { petBubble.hide(3000); },
|
|
21672
|
+
onError: (error) => {
|
|
21673
|
+
// 失败只进气泡提示行(不弹窗);不静默 —— 用户至少知道为什么没声音
|
|
21674
|
+
const hint = (error && error.hint) || '语音没出来';
|
|
21675
|
+
petBubble.setState('idle');
|
|
21676
|
+
petBubble.show(hint);
|
|
21677
|
+
petBubble.hide(4000);
|
|
21678
|
+
},
|
|
21679
|
+
});
|
|
21680
|
+
|
|
21681
|
+
/** 对外/对内的“说一句”:按句入队,返回是否真的入队。 */
|
|
21682
|
+
function petSpeak(text, speech) { return petTts.speak(text, speech); }
|
|
21683
|
+
/** 立刻停:清队列 + 停当前音频 + 通知宿主作废在途合成(barge-in 用)。 */
|
|
21684
|
+
function petSpeakStop() { return petTts.stop(); }
|
|
21685
|
+
|
|
21268
21686
|
/** 语音输入(v0.1):前端不碰麦克风 —— 宿主用 ffmpeg 录,这里只发请求、收文本。 */
|
|
21269
21687
|
const petVoiceIn = petVoiceInputCreate({
|
|
21688
|
+
// barge-in:**一开录就先停朗读**(判据 verify-voice-tts 断言这个顺序)
|
|
21689
|
+
onBeforeRecord: () => { petSpeakStop(); },
|
|
21270
21690
|
postRecord: async () => {
|
|
21271
21691
|
const res = await apiPostJson('/pet-chat/record', { language: 'zh' }, { parse: 'always' });
|
|
21272
21692
|
return (res && res.data) || {};
|
|
21273
21693
|
},
|
|
21274
21694
|
postChat: async (text, onState) => {
|
|
21275
|
-
|
|
21695
|
+
// “想”态:模型还在回,先不给“说”的波形
|
|
21696
|
+
petBubble.setState('think');
|
|
21276
21697
|
// ⚠️ apiFetch 的返回值里**已经带上了原始 Response**(字段 `response`)。
|
|
21277
21698
|
// 上一版误写成 `res.body.getReader()`:res 是 { ok, status, data, response },
|
|
21278
21699
|
// res.body 恒为 undefined ⇒ 抛 TypeError ⇒ 读流代码一行都跑不到
|
|
@@ -21305,6 +21726,18 @@ window.__ModuleLoader__.load({
|
|
|
21305
21726
|
let rawReply = '';
|
|
21306
21727
|
let replyStarted = false;
|
|
21307
21728
|
let replyDone = false;
|
|
21729
|
+
/**
|
|
21730
|
+
* 朗读的流式切句(P1):
|
|
21731
|
+
* SSE 每来一小段就交给 `petTtsSentences`;**句末标点一到就入队**,
|
|
21732
|
+
* 不等 done —— 这是“录音停止后尽快开始播报”的关键(合成与模型生成重叠)。
|
|
21733
|
+
*/
|
|
21734
|
+
let speakBuffer = '';
|
|
21735
|
+
let queuedSpeech = 0;
|
|
21736
|
+
const enqueueSpeech = (piece) => {
|
|
21737
|
+
const line = String(piece || '').trim();
|
|
21738
|
+
if (!line) return;
|
|
21739
|
+
if (petSpeak(line)) queuedSpeech += 1;
|
|
21740
|
+
};
|
|
21308
21741
|
const reader = stream.body.getReader();
|
|
21309
21742
|
const decoder = new TextDecoder();
|
|
21310
21743
|
let buffer = '';
|
|
@@ -21319,7 +21752,7 @@ window.__ModuleLoader__.load({
|
|
|
21319
21752
|
buffer = buffer.slice(cut + 2);
|
|
21320
21753
|
const line = frame.split('\n').find((item) => item.startsWith('data:'));
|
|
21321
21754
|
if (!line) continue;
|
|
21322
|
-
let payload
|
|
21755
|
+
let payload;
|
|
21323
21756
|
try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
|
|
21324
21757
|
// 防兜底:模型偶尔仍会输出 {"reply":"…","emotion":"…"} 信封,
|
|
21325
21758
|
// 这里只把 reply 的正文喂给气泡(不显示大括号/字段名/emotion)。
|
|
@@ -21338,13 +21771,25 @@ window.__ModuleLoader__.load({
|
|
|
21338
21771
|
if (piece && !replyDone) {
|
|
21339
21772
|
const cut = piece.indexOf('","emotion"');
|
|
21340
21773
|
if (cut >= 0) { piece = piece.slice(0, cut); replyDone = true; }
|
|
21341
|
-
if (piece)
|
|
21774
|
+
if (piece) {
|
|
21775
|
+
// 朗读没开始时先照旧把文字逐字填进气泡;一开始播,气泡字幕就交给
|
|
21776
|
+
// petTts 的 onSentence(逐句显示),避免两路同时写同一个气泡。
|
|
21777
|
+
if (queuedSpeech === 0) petBubble.append(piece);
|
|
21778
|
+
speakBuffer += piece;
|
|
21779
|
+
const split = petTtsSentences(speakBuffer);
|
|
21780
|
+
for (const sentence of split.sentences) enqueueSpeech(sentence);
|
|
21781
|
+
speakBuffer = split.rest;
|
|
21782
|
+
}
|
|
21342
21783
|
}
|
|
21343
21784
|
}
|
|
21344
21785
|
}
|
|
21345
21786
|
}
|
|
21787
|
+
// 最后一段没有句末标点也要念(比如“我也在”)
|
|
21788
|
+
enqueueSpeech(speakBuffer);
|
|
21346
21789
|
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
21347
|
-
|
|
21790
|
+
// 没有任何一句进入朗读(静音 / 合成不可用)⇒ 沿用旧行为:整段文字 3 秒后淡出。
|
|
21791
|
+
// 有朗读时由 petTts 的 onIdle 在念完后淡出(按句字幕不会被提前清掉)。
|
|
21792
|
+
if (!queuedSpeech) petBubble.hide(3000);
|
|
21348
21793
|
},
|
|
21349
21794
|
// P4:用户自己的话**不进**气泡(那是回声);只显示 assistant 的 SSE delta
|
|
21350
21795
|
onText: () => {},
|
|
@@ -21393,6 +21838,8 @@ window.__ModuleLoader__.load({
|
|
|
21393
21838
|
const text = String(input.value || '').trim();
|
|
21394
21839
|
if (!text) return;
|
|
21395
21840
|
box.remove();
|
|
21841
|
+
// 新的一轮 = 先掐掉上一轮还在念的(与录音入口同一条 barge-in 纪律)
|
|
21842
|
+
petSpeakStop();
|
|
21396
21843
|
// 打字说的文本**不上气泡**(P4 同理:气泡只显示助手的回答)。
|
|
21397
21844
|
// 这里只把状态切成"思考中",等 SSE 的 delta 逐字填进来。
|
|
21398
21845
|
petBubble.setState('think');
|
|
@@ -21407,18 +21854,22 @@ window.__ModuleLoader__.load({
|
|
|
21407
21854
|
input.focus();
|
|
21408
21855
|
}
|
|
21409
21856
|
|
|
21410
|
-
/**
|
|
21411
|
-
*
|
|
21857
|
+
/**
|
|
21858
|
+
* 说一句:气泡显示 + 朗读(P1)。
|
|
21859
|
+
* 静音/合成不可用时退回“只显示 3 秒”,不抛错、不弹窗。
|
|
21412
21860
|
*/
|
|
21413
21861
|
function petChatSay(text) {
|
|
21414
21862
|
const line = String(text || '').trim();
|
|
21415
21863
|
if (!line) return;
|
|
21416
21864
|
petBubble.show(line);
|
|
21417
|
-
petBubble.hide(3000);
|
|
21865
|
+
if (!petSpeak(line)) petBubble.hide(3000);
|
|
21418
21866
|
}
|
|
21419
21867
|
|
|
21420
|
-
/** 点桌宠:气泡可见 ⇒
|
|
21868
|
+
/** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音与朗读);否则唤醒并开始听。 */
|
|
21421
21869
|
function petChatWake() {
|
|
21870
|
+
// **任何一次唤醒都是 barge-in**:先把正在念的停掉,再决定是收起还是开麦。
|
|
21871
|
+
petSpeakStop();
|
|
21872
|
+
void petChatRefreshVoice();
|
|
21422
21873
|
if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
|
|
21423
21874
|
petBubble.setState('listen');
|
|
21424
21875
|
// 先看语音模型是否就绪;没就绪就**立刻**开始下载并在气泡里显示进度,
|
|
@@ -21436,9 +21887,36 @@ window.__ModuleLoader__.load({
|
|
|
21436
21887
|
});
|
|
21437
21888
|
}
|
|
21438
21889
|
|
|
21890
|
+
/**
|
|
21891
|
+
* 工作联动反向通道(P1):宿主 `/pet-chat/speak` → SSE `/pet-chat/events` → 这里念。
|
|
21892
|
+
* 待办/提醒/其它插件可以直接 `POST /folia/pet-chat/speak`,也可以在同一渲染进程里
|
|
21893
|
+
* `window.__dshFoliaPet.speak(text)` / 派发 `we-pet-speak` 事件。
|
|
21894
|
+
* EventSource 自带重连;这里不弹任何提示。
|
|
21895
|
+
*/
|
|
21896
|
+
let petChatEventSource = null;
|
|
21897
|
+
function petChatEventsStart() {
|
|
21898
|
+
if (petChatEventSource || typeof EventSource !== 'function') return;
|
|
21899
|
+
try {
|
|
21900
|
+
const source = new EventSource(apiUrl('/pet-chat/events'));
|
|
21901
|
+
source.onmessage = (event) => {
|
|
21902
|
+
let doc;
|
|
21903
|
+
try { doc = JSON.parse((event && event.data) || ''); } catch { doc = null; }
|
|
21904
|
+
if (!doc || doc.type !== 'speak' || !doc.text) return;
|
|
21905
|
+
petSpeak(String(doc.text), { voice: doc.voice, rate: doc.rate });
|
|
21906
|
+
};
|
|
21907
|
+
source.onerror = () => { /* EventSource 自动重连;失败不打扰用户 */ };
|
|
21908
|
+
petChatEventSource = source;
|
|
21909
|
+
} catch { /* 老环境没有 EventSource:仍在渲染进程内的调用走 window.__dshFoliaPet */ }
|
|
21910
|
+
}
|
|
21911
|
+
function petChatEventsStop() {
|
|
21912
|
+
if (!petChatEventSource) return;
|
|
21913
|
+
try { petChatEventSource.close(); } catch { /* ignore */ }
|
|
21914
|
+
petChatEventSource = null;
|
|
21915
|
+
}
|
|
21916
|
+
|
|
21439
21917
|
/**
|
|
21440
21918
|
* 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点桌宠 / 快捷键。
|
|
21441
|
-
* 返回 cleanup ——
|
|
21919
|
+
* 返回 cleanup —— 卸载时摘监听、断开反向通道、销毁气泡。
|
|
21442
21920
|
*/
|
|
21443
21921
|
function mountPetChat() {
|
|
21444
21922
|
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return () => {};
|
|
@@ -21456,13 +21934,37 @@ window.__ModuleLoader__.load({
|
|
|
21456
21934
|
// 打字入口只从**右键菜单「对话」**进:pet-layer 的菜单项派发 `we-pet-talk`。
|
|
21457
21935
|
// 不再劫持 contextmenu —— 那会让右键弹不出桌宠原生菜单(试演动作/缩放…)。
|
|
21458
21936
|
const onTalkEvent = () => { petChatOpenTyping(); };
|
|
21937
|
+
|
|
21938
|
+
/** 工作联动:同一渲染进程里的待办/提醒可以直接派发这个事件。 */
|
|
21939
|
+
const onSpeakEvent = (event) => {
|
|
21940
|
+
const detail = (event && event.detail) || {};
|
|
21941
|
+
const text = detail && detail.text;
|
|
21942
|
+
if (text) petSpeak(String(text), { voice: detail.voice, rate: detail.rate });
|
|
21943
|
+
};
|
|
21944
|
+
|
|
21459
21945
|
window.addEventListener('we-pet-talk', onTalkEvent);
|
|
21946
|
+
window.addEventListener('we-pet-speak', onSpeakEvent);
|
|
21460
21947
|
document.addEventListener('click', onDocumentClick, true);
|
|
21461
21948
|
document.addEventListener('keydown', onKeyDown, true);
|
|
21949
|
+
void petChatRefreshVoice();
|
|
21950
|
+
petChatEventsStart();
|
|
21951
|
+
// 对外通道:`speak(text)` 供待办/提醒直接调用(不打开任何窗口)
|
|
21952
|
+
try {
|
|
21953
|
+
window.__dshFoliaPet = {
|
|
21954
|
+
speak: (text, speech) => petSpeak(text, speech || {}),
|
|
21955
|
+
stop: () => petSpeakStop(),
|
|
21956
|
+
chat: (text) => petVoiceIn.postChat(String(text || '')),
|
|
21957
|
+
isSpeaking: () => petTts.isSpeaking(),
|
|
21958
|
+
};
|
|
21959
|
+
} catch { /* 被别的插件占用就只保留事件通道 */ }
|
|
21462
21960
|
return () => {
|
|
21463
21961
|
window.removeEventListener('we-pet-talk', onTalkEvent);
|
|
21962
|
+
window.removeEventListener('we-pet-speak', onSpeakEvent);
|
|
21464
21963
|
document.removeEventListener('click', onDocumentClick, true);
|
|
21465
21964
|
document.removeEventListener('keydown', onKeyDown, true);
|
|
21965
|
+
petChatEventsStop();
|
|
21966
|
+
petSpeakStop();
|
|
21967
|
+
try { if (window.__dshFoliaPet) delete window.__dshFoliaPet; } catch { /* ignore */ }
|
|
21466
21968
|
petBubble.dispose();
|
|
21467
21969
|
};
|
|
21468
21970
|
}
|
|
@@ -24226,13 +24728,18 @@ window.__ModuleLoader__.load({
|
|
|
24226
24728
|
}
|
|
24227
24729
|
|
|
24228
24730
|
/**
|
|
24229
|
-
* 挂载自愈**执行体**:对 `dlHealTargets()`
|
|
24731
|
+
* 挂载自愈**执行体**:对 `dlHealTargets()` 挑出来的条目各补打收尾请求。
|
|
24230
24732
|
*
|
|
24231
|
-
*
|
|
24733
|
+
* 约定(回调都由页签提供,本函数不认识组件、也不认识 React):
|
|
24232
24734
|
* · `path` / `body(it)` 打哪个宿主接口、带什么体(三个模块各一条,都是幂等的);
|
|
24233
|
-
* · `onTry(it)`
|
|
24234
|
-
* · `
|
|
24235
|
-
* · `
|
|
24735
|
+
* · `onTry(it, attempt, total)` 每次发出前(用来写「正在补收尾… 第 a/t 次」与卡片 healing);
|
|
24736
|
+
* · `onRetry(it, code, attempt, total)` 退避重试前(可选;默认没有额外动作);
|
|
24737
|
+
* · `onOk(it)` 宿主明确回 2xx(页签据此 `cards.healOk()` + 重拉清单);
|
|
24738
|
+
* · `onFail(it, code)` **全部 attempts 都失败**(页签据此 `cards.healFail()` 把原因写在卡片上)。
|
|
24739
|
+
*
|
|
24740
|
+
* pre.46:一次 → 带退避多次(调用方传 `attempts: 3, backoff: [3000, 8000]`)。
|
|
24741
|
+
* 默认仍是 1 次,保持既有调用点/判据的语义;`dlHealOnce` 仍按 `<kind>:<id>` 每次会话只领一次,
|
|
24742
|
+
* 所以“3 次”是**同一次挂载内**的退避重试,切页签不会无限重打。
|
|
24236
24743
|
*
|
|
24237
24744
|
* 绝不抛:任何一个模块/一张卡片失败都不该让别的卡片或整页挂掉。
|
|
24238
24745
|
*
|
|
@@ -24245,21 +24752,41 @@ window.__ModuleLoader__.load({
|
|
|
24245
24752
|
const targets = (() => {
|
|
24246
24753
|
try { return dlHealTargets(o.jobs, kind, o.items, o.doneOf); } catch { return []; }
|
|
24247
24754
|
})();
|
|
24755
|
+
const attempts = Math.max(1, Math.min(5, Number(o.attempts) || 1));
|
|
24756
|
+
const backoff = Array.isArray(o.backoff) ? o.backoff : [3000, 8000];
|
|
24757
|
+
const post = typeof o.post === "function" ? o.post : apiPostJson;
|
|
24758
|
+
const sleep = typeof o.sleep === "function"
|
|
24759
|
+
? o.sleep
|
|
24760
|
+
: (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });
|
|
24248
24761
|
for (const it of targets) {
|
|
24249
24762
|
if (!dlHealOnce(kind + ":" + it.id)) continue;
|
|
24250
24763
|
tried.push(it);
|
|
24251
|
-
try { if (typeof o.onTry === "function") o.onTry(it); } catch { /* 提示失败不影响补装 */ }
|
|
24252
24764
|
/** 空串 = 成功;非空 = 宿主给的错误码(或兜底码)。 */
|
|
24253
|
-
let code;
|
|
24254
|
-
|
|
24255
|
-
|
|
24256
|
-
|
|
24257
|
-
|
|
24258
|
-
|
|
24259
|
-
|
|
24260
|
-
|
|
24261
|
-
|
|
24262
|
-
|
|
24765
|
+
let code = "";
|
|
24766
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
24767
|
+
if (attempt > 1) {
|
|
24768
|
+
const wait = Math.max(0, Number(backoff[attempt - 2]) || 0);
|
|
24769
|
+
try {
|
|
24770
|
+
if (typeof o.onRetry === "function") o.onRetry(it, code, attempt, attempts);
|
|
24771
|
+
} catch { /* 重试提示失败不影响补装 */ }
|
|
24772
|
+
if (wait > 0) {
|
|
24773
|
+
// eslint-disable-next-line no-await-in-loop -- 退避本来就是按 attempt 串行等待
|
|
24774
|
+
try { await sleep(wait); } catch { /* 定时器失败就立刻重试 */ }
|
|
24775
|
+
}
|
|
24776
|
+
}
|
|
24777
|
+
try { if (typeof o.onTry === "function") o.onTry(it, attempt, attempts); } catch { /* 提示失败不影响补装 */ }
|
|
24778
|
+
code = "";
|
|
24779
|
+
try {
|
|
24780
|
+
const resp = await post(String(o.path || ""), typeof o.body === "function" ? o.body(it) : (o.body || {}), { parse: "always" });
|
|
24781
|
+
const data = (resp && resp.data) || null;
|
|
24782
|
+
// 宿主回 `{ ok:false, error }` 时把**它的**错误码带出去(比 `http-500` 有信息量)。
|
|
24783
|
+
if (resp && resp.ok && data && data.ok === false) code = String(data.error || "failed");
|
|
24784
|
+
else if (!(resp && resp.ok)) code = String((data && data.error) || ("http-" + ((resp && resp.status) || 0)));
|
|
24785
|
+
else code = "";
|
|
24786
|
+
} catch (e) {
|
|
24787
|
+
code = /timeout|超时/i.test(String((e && e.message) || "")) ? "submit-timeout" : "network";
|
|
24788
|
+
}
|
|
24789
|
+
if (!code) break;
|
|
24263
24790
|
}
|
|
24264
24791
|
try {
|
|
24265
24792
|
if (code) { if (typeof o.onFail === "function") o.onFail(it, code); }
|
|
@@ -24337,7 +24864,7 @@ window.__ModuleLoader__.load({
|
|
|
24337
24864
|
*/
|
|
24338
24865
|
const DL_PHASES = {
|
|
24339
24866
|
IDLE: "idle", SUBMITTING: "submitting", QUEUED: "queued",
|
|
24340
|
-
RUNNING: "running", INSTALLING: "installing", DONE: "done", FAILED: "failed",
|
|
24867
|
+
RUNNING: "running", INSTALLING: "installing", HEALING: "healing", DONE: "done", FAILED: "failed",
|
|
24341
24868
|
};
|
|
24342
24869
|
|
|
24343
24870
|
/** 提交请求的宽容窗口:超过它还没返回 ⇒ 按「提交超时」失败并给「重试」,不让卡片永远停在提交中。
|
|
@@ -24588,6 +25115,21 @@ window.__ModuleLoader__.load({
|
|
|
24588
25115
|
// 而"我们刚试过、宿主明确回了错"比"队列说 done"更具体,所以它优先。
|
|
24589
25116
|
// 它不盖正常路径:`begin()`(用户点下去)会清掉这条失败,`markOk()` 让卡片直接变 done。
|
|
24590
25117
|
if (o.err && o.err.code) return fail(o.err.code);
|
|
25118
|
+
// ②c pre.46:**正在补收尾**(挂载自愈的 3 次退避重试期间)。
|
|
25119
|
+
//
|
|
25120
|
+
// 必须排在 ③ 之前:否则卡片会先显示「解压/落位中…」,用户只能干等;
|
|
25121
|
+
// 而自愈其实已经在打幂等的 `/boot/download` / `/skins/install`。
|
|
25122
|
+
// 失败后 `healFail` 会清掉这一格并写 `err` ⇒ 落在 ②b 的红字 +「重试」。
|
|
25123
|
+
if (o.heal && String(o.heal.id || "") === String(o.id || "")) {
|
|
25124
|
+
const attempt = Math.max(1, Number(o.heal.attempt) || 1);
|
|
25125
|
+
const total = Math.max(1, Number(o.heal.total) || 3);
|
|
25126
|
+
return make(
|
|
25127
|
+
DL_PHASES.HEALING,
|
|
25128
|
+
weT("正在补收尾…"),
|
|
25129
|
+
weT("第 {a}/{t} 次 · 下载已完成,正在补落地", { a: attempt, t: total }),
|
|
25130
|
+
true, false, "",
|
|
25131
|
+
);
|
|
25132
|
+
}
|
|
24591
25133
|
// ③ 包下完了、还没落地:宿主正在解压 / 规范化清单 / 写目录。
|
|
24592
25134
|
//
|
|
24593
25135
|
// ⚠️ 4.23.6:这一格**必须有上界**(老实现无条件映射成 installing:disabled、retry=false、
|
|
@@ -25315,6 +25857,8 @@ window.__ModuleLoader__.load({
|
|
|
25315
25857
|
const [sub, setSub] = React.useState(null);
|
|
25316
25858
|
const [errs, setErrs] = React.useState({});
|
|
25317
25859
|
const [okIds, setOkIds] = React.useState({});
|
|
25860
|
+
/** pre.46:正在挂载自愈的卡片 `id → { attempt, total, at }`(卡片显示「正在补收尾…」)。 */
|
|
25861
|
+
const [heals, setHeals] = React.useState({});
|
|
25318
25862
|
const [eta, setEta] = React.useState({});
|
|
25319
25863
|
const [nowMs, setNowMs] = React.useState(() => Date.now());
|
|
25320
25864
|
const samplesRef = React.useRef(new Map());
|
|
@@ -25463,6 +26007,53 @@ window.__ModuleLoader__.load({
|
|
|
25463
26007
|
* 而不是静默回到「安装」——那正是"点了没反应"的另一种样子。
|
|
25464
26008
|
*/
|
|
25465
26009
|
markOk: (id) => { setOkIds((m) => (m[key(id)] ? m : { ...m, [key(id)]: true })); },
|
|
26010
|
+
/**
|
|
26011
|
+
* pre.46:挂载自愈进行中 —— 卡片显示「正在补收尾…」而不是「解压/落位中…」。
|
|
26012
|
+
* 每次重试都更新 attempt/total,用户能看到“第 2/3 次”。
|
|
26013
|
+
*/
|
|
26014
|
+
heal: (id, attempt, total) => {
|
|
26015
|
+
const k = key(id);
|
|
26016
|
+
setHeals((m) => ({ ...m, [k]: { attempt: Math.max(1, Number(attempt) || 1), total: Math.max(1, Number(total) || 3), at: Date.now() } }));
|
|
26017
|
+
// 新一轮补收尾 ⇒ 清掉上一轮的失败红字(失败会由 healFail 重新写)
|
|
26018
|
+
setErrs((m) => {
|
|
26019
|
+
if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
|
|
26020
|
+
const n = { ...m };
|
|
26021
|
+
delete n[k];
|
|
26022
|
+
return n;
|
|
26023
|
+
});
|
|
26024
|
+
},
|
|
26025
|
+
healEnd: (id) => {
|
|
26026
|
+
const k = key(id);
|
|
26027
|
+
setHeals((m) => {
|
|
26028
|
+
if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
|
|
26029
|
+
const n = { ...m };
|
|
26030
|
+
delete n[k];
|
|
26031
|
+
return n;
|
|
26032
|
+
});
|
|
26033
|
+
},
|
|
26034
|
+
/** 补收尾成功:清 healing + 标记已装(皮肤页签据此立刻变 done)。 */
|
|
26035
|
+
healOk: (id) => {
|
|
26036
|
+
const k = key(id);
|
|
26037
|
+
setHeals((m) => {
|
|
26038
|
+
if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
|
|
26039
|
+
const n = { ...m };
|
|
26040
|
+
delete n[k];
|
|
26041
|
+
return n;
|
|
26042
|
+
});
|
|
26043
|
+
setOkIds((m) => (m[k] ? m : { ...m, [k]: true }));
|
|
26044
|
+
},
|
|
26045
|
+
/** 3 次都失败:清 healing + 写失败原因(卡片红字 +「重试」)。 */
|
|
26046
|
+
healFail: (id, code) => {
|
|
26047
|
+
const k = key(id);
|
|
26048
|
+
setHeals((m) => {
|
|
26049
|
+
if (!Object.prototype.hasOwnProperty.call(m, k)) return m;
|
|
26050
|
+
const n = { ...m };
|
|
26051
|
+
delete n[k];
|
|
26052
|
+
return n;
|
|
26053
|
+
});
|
|
26054
|
+
setErrs((m) => ({ ...m, [k]: { code: String(code == null ? "failed" : code) } }));
|
|
26055
|
+
},
|
|
26056
|
+
healOf: (id) => heals[key(id)] || null,
|
|
25466
26057
|
// 卸载成功后必须把它忘掉:否则卡片会一直按"已安装"渲染(站点已删、徽标还在)。
|
|
25467
26058
|
clearOk: (id) => {
|
|
25468
26059
|
const k = key(id);
|
|
@@ -25486,7 +26077,8 @@ window.__ModuleLoader__.load({
|
|
|
25486
26077
|
const since = stallOf(x.id, x.job, x.done);
|
|
25487
26078
|
const st = dlCardState({
|
|
25488
26079
|
id: x.id, job: x.job, done: x.done, labels: x.labels,
|
|
25489
|
-
sub: api.subOf(x.id), err: api.errOf(x.id),
|
|
26080
|
+
sub: api.subOf(x.id), err: api.errOf(x.id), heal: api.healOf(x.id),
|
|
26081
|
+
etaSec: api.etaOf(x.job), nowMs,
|
|
25490
26082
|
installStallMs: stallMs, installingSince: since,
|
|
25491
26083
|
});
|
|
25492
26084
|
// 已经判过超时 ⇒ 标记 expired:秒表停转(不空转),卡片保持 failed +「重试」。
|