dsh-message-actions 0.0.0-stage → 0.2.1

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 ADDED
@@ -0,0 +1,4293 @@
1
+ // dsh-message-actions — 浏览器端(客户端 UI)。
2
+ //
3
+ // 本文件由 build.mjs 处理:
4
+ // - 共享纯函数占位符会被内联为 shared.cjs 的 IIFE(见下方 const shared 声明);
5
+ // - 构建时间戳占位符会被替换为 ISO 时间(见下方 const BUILD 声明)。
6
+ //
7
+ // 官方图标组件(@deepseek-ai/dsh-client-ui-primitives)为可选依赖:
8
+ // 加载成功时与官方「复制」等按钮保持同一套图标;失败时回退到内置图标。
9
+
10
+ window.__ModuleLoader__.load({
11
+ id: "dsh-message-actions",
12
+ factory: (require) => {
13
+ const React = require("react");
14
+
15
+ let ReactDOMClient = null;
16
+ try {
17
+ ReactDOMClient = require("react-dom/client");
18
+ } catch {
19
+ ReactDOMClient = null;
20
+ }
21
+
22
+ let PRIMITIVES = null;
23
+ try {
24
+ PRIMITIVES = require("@deepseek-ai/dsh-client-ui-primitives");
25
+ } catch {
26
+ PRIMITIVES = null;
27
+ }
28
+
29
+ // 占位符写成合法表达式,保证 src/client.js 可被 lint/typecheck 直接解析;
30
+ // build.mjs 会把 `null` 整体替换为 shared.cjs 的 IIFE。
31
+ const shared = (function () {
32
+ const module = { exports: {} };
33
+ const exports = module.exports;
34
+ 'use strict';
35
+
36
+ /**
37
+ * dsh-message-actions — 共享纯函数(宿主与客户端共用)。
38
+ *
39
+ * 本模块不依赖任何 DSH / 第三方运行时,也不产生副作用,因此可被
40
+ * `test/check.mjs` 离线加载,也可被构建脚本内联进客户端 bundle。
41
+ *
42
+ * 命名与实现均为本项目自行设计,不复制任何第三方代码。
43
+ */
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // 常量
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /** 墓碑事件的 producer 标识,用于在会话日志里识别本插件写入的删除/撤回标记。 */
50
+ const PRODUCER = 'dsh-message-actions';
51
+
52
+ /** 墓碑正文占位文本。 */
53
+ const TOMBSTONE_TEXT = { recall: '[已撤回]', delete: '[已删除]', deleteFrom: '[已删除]' };
54
+
55
+ /**
56
+ * 宿主 HTTP 错误码与文案(zh / en)。
57
+ * 错误码稳定;文案仅用于日志与客户端 toast 兜底展示。
58
+ */
59
+ const ERROR_LABELS = {
60
+ zh: {
61
+ INVALID_REQUEST: '无效请求',
62
+ FORBIDDEN: '请求被拒绝',
63
+ PAYLOAD_TOO_LARGE: '请求体过大',
64
+ AGENT_BUSY: '正在生成回复,请稍后再试',
65
+ SESSION_NOT_LIVE: '会话不可用',
66
+ TARGET_NOT_FOUND: '目标消息不存在或已被删除',
67
+ NOT_DELETABLE: '该消息不可删除',
68
+ NOT_A_USER_MESSAGE: '仅用户消息可撤回',
69
+ SPAN_NOT_CONTIGUOUS: '目标回答与工具结果不连续,无法整体删除',
70
+ INVALID_AMOUNT: '金额格式不合法',
71
+ READ_ONLY: '状态文件只读,未保存',
72
+ WRITE_FAILED: '写入状态文件失败',
73
+ INTERNAL: '内部错误'
74
+ },
75
+ en: {
76
+ INVALID_REQUEST: 'Invalid request',
77
+ FORBIDDEN: 'Forbidden',
78
+ PAYLOAD_TOO_LARGE: 'Payload too large',
79
+ AGENT_BUSY: 'A reply is being generated; try again later',
80
+ SESSION_NOT_LIVE: 'Session is not live',
81
+ TARGET_NOT_FOUND: 'Target message not found or already deleted',
82
+ NOT_DELETABLE: 'This message cannot be deleted',
83
+ NOT_A_USER_MESSAGE: 'Only user messages can be recalled',
84
+ SPAN_NOT_CONTIGUOUS: 'Answer and tool results are not contiguous',
85
+ INVALID_AMOUNT: 'Invalid amount',
86
+ READ_ONLY: 'State file is read-only; nothing saved',
87
+ WRITE_FAILED: 'Could not write the state file',
88
+ INTERNAL: 'Internal error'
89
+ }
90
+ };
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // 文本提取
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /**
97
+ * 折叠 OpenAI 风格 content(字符串或 block 数组)为纯文本。
98
+ * 只取用户可见的 text 块:reasoning(思维链)不属于回答正文,不能混进分享/导出。
99
+ */
100
+ function contentText(content) {
101
+ if (typeof content === 'string') return content;
102
+ if (!Array.isArray(content)) return '';
103
+ const parts = [];
104
+ for (const block of content) {
105
+ if (block == null) continue;
106
+ if (typeof block === 'string') {
107
+ parts.push(block);
108
+ continue;
109
+ }
110
+ if (block.type === 'text' && typeof block.text === 'string') {
111
+ parts.push(block.text);
112
+ } else if (block.type === 'image') {
113
+ parts.push('[图片]');
114
+ } else if (block.type === 'file') {
115
+ parts.push('[文件]');
116
+ }
117
+ }
118
+ return parts.join('');
119
+ }
120
+
121
+ /** 取一个事件的纯文本正文(按事件类型分发)。 */
122
+ function textOf(event) {
123
+ if (!event || typeof event !== 'object') return '';
124
+ const data = event.data;
125
+ if (!data || typeof data !== 'object') return '';
126
+ switch (event.type) {
127
+ case 'user/message':
128
+ return contentText(data.content);
129
+ case 'assistant/message':
130
+ return contentText(data.message && data.message.content);
131
+ case 'tool/result':
132
+ return contentText(data.message && data.message.content);
133
+ case 'system/message':
134
+ return contentText(data.message && data.message.content);
135
+ case 'developer/message':
136
+ return contentText(data.message && data.message.content);
137
+ default:
138
+ return '';
139
+ }
140
+ }
141
+
142
+ /** 事件对应的角色(供 /messages 摘要与客户端槽位对齐)。 */
143
+ function messageRoleOf(event) {
144
+ if (!event || typeof event !== 'object') return 'other';
145
+ switch (event.type) {
146
+ case 'user/message': return 'user';
147
+ case 'assistant/message': return 'assistant';
148
+ case 'tool/result': return 'tool';
149
+ case 'system/message': return 'system';
150
+ case 'developer/message': return 'developer';
151
+ default: return 'other';
152
+ }
153
+ }
154
+
155
+ /** 取事件的稳定消息 id(供客户端与辅助/答行槽位对齐)。 */
156
+ function messageIdOf(event) {
157
+ if (!event || typeof event !== 'object' || !event.data) return undefined;
158
+ const data = event.data;
159
+ if (typeof data.id === 'string') return data.id;
160
+ if (data.message && typeof data.message.id === 'string') return data.message.id;
161
+ return undefined;
162
+ }
163
+
164
+ /** 取事件的用量摘要(答行统计 tokens 来源);只回传 outputTokens。 */
165
+ function usageSummaryOf(event) {
166
+ if (!event || typeof event !== 'object' || !event.data) return undefined;
167
+ const usage = event.data.usage;
168
+ if (!usage || typeof usage !== 'object') return undefined;
169
+ return usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : undefined;
170
+ }
171
+
172
+ /**
173
+ * 取工具事件的 callId。
174
+ * 宿主工具行 DOM 的 `data-chat-node-key` = `9:tool-call<callId>`,
175
+ * callId 来自 `tool/call.data.callId` / `tool/result.data.message.source.callId`。
176
+ */
177
+ function toolCallIdOf(event) {
178
+ if (!event || typeof event !== 'object' || !event.data) return undefined;
179
+ const data = event.data;
180
+ if (event.type === 'tool/result') {
181
+ const source = data.message && data.message.source;
182
+ if (source && typeof source.callId === 'string' && source.callId !== '') return source.callId;
183
+ }
184
+ if (event.type === 'tool/call' && typeof data.callId === 'string' && data.callId !== '') {
185
+ return data.callId;
186
+ }
187
+ return undefined;
188
+ }
189
+
190
+ /** 宿主工具节点 key 前缀(`conversationContextKey("tool-call", id)` = `9:tool-call<id>`)。 */
191
+ const TOOL_NODE_KEY_PREFIX = '9:tool-call';
192
+
193
+ /**
194
+ * 从宿主 DOM 的 `data-chat-node-key` 解析工具 callId。
195
+ * 这不是序号 / 坐标猜测:前缀与 key 构造规则来自宿主
196
+ * `conversationContextKey(kind, id) = ${kind.length}:${kind}${id}`,
197
+ * 而 id 就是服务端 `tool/call` 事件的 callId。
198
+ * @param {string} nodeKey
199
+ * @returns {string|null}
200
+ */
201
+ function toolCallIdFromNodeKey(nodeKey) {
202
+ if (typeof nodeKey !== 'string' || !nodeKey.startsWith(TOOL_NODE_KEY_PREFIX)) return null;
203
+ const id = nodeKey.slice(TOOL_NODE_KEY_PREFIX.length);
204
+ return id.length > 0 ? id : null;
205
+ }
206
+
207
+ /**
208
+ * 从 DOM 上现存的工具节点 key 中,挑出应被隐藏的那些。
209
+ * 宿主切换会话 / 刷新会重建 DOM,新节点不带任何本地隐藏标记,
210
+ * 因此客户端每次重建后都要按墓碑里的 callId 重新判定一次。
211
+ * @param {string[]} nodeKeys 现存的 `data-chat-node-key`
212
+ * @param {string[]} callIds 墓碑覆盖的 callId(来自 /messages 的 goneTools)
213
+ * @returns {string[]} 需要隐藏的 nodeKey
214
+ */
215
+ function toolNodeKeysToHide(nodeKeys, callIds) {
216
+ if (!Array.isArray(nodeKeys) || !Array.isArray(callIds) || callIds.length === 0) return [];
217
+ const gone = new Set();
218
+ for (const callId of callIds) {
219
+ if (typeof callId === 'string' && callId !== '') gone.add(callId);
220
+ }
221
+ if (gone.size === 0) return [];
222
+ const out = [];
223
+ for (const key of nodeKeys) {
224
+ const callId = toolCallIdFromNodeKey(key);
225
+ if (callId !== null && gone.has(callId)) out.push(key);
226
+ }
227
+ return out;
228
+ }
229
+
230
+ /** 在 /messages 摘要 rows 中找到 callId 对应的 tool/result 行(表面顺序第一条)。 */
231
+ function findToolRowByCallId(rows, callId) {
232
+ if (!Array.isArray(rows) || typeof callId !== 'string' || callId === '') return null;
233
+ for (const row of rows) {
234
+ if (row && row.type === 'tool/result' && row.callId === callId) return row;
235
+ }
236
+ return null;
237
+ }
238
+
239
+ /**
240
+ * 汇总所有墓碑声明的 removed seq。
241
+ * 墓碑随事件日志一起持久化(带 surfaceOp),因此即使宿主重建表面时
242
+ * 没有重放 surfaceOp,或客户端拿到旧快照,这里仍能还原「哪些节点已被删」。
243
+ * @param events 按 seq 索引的事件数组
244
+ * @returns {Set<number>}
245
+ */
246
+ function tombstonedSeqsOf(events) {
247
+ const hidden = new Set();
248
+ if (!Array.isArray(events)) return hidden;
249
+ for (const event of events) {
250
+ if (!isTombstone(event)) continue;
251
+ const removed = event.data && event.data.source && event.data.source.removed;
252
+ if (!Array.isArray(removed)) continue;
253
+ for (const seq of removed) {
254
+ if (Number.isSafeInteger(seq) && seq >= 0) hidden.add(seq);
255
+ }
256
+ }
257
+ return hidden;
258
+ }
259
+
260
+ /**
261
+ * 从 events + 表面节点得到「仍可见」的节点列表。
262
+ * 不信任宿主表面重放结果:被墓碑覆盖的 seq 一律剔除。
263
+ * @param events
264
+ * @param nodes
265
+ * @returns {number[]}
266
+ */
267
+ function liveNodesOf(events, nodes) {
268
+ if (!Array.isArray(nodes)) return [];
269
+ const hidden = tombstonedSeqsOf(events);
270
+ if (hidden.size === 0) return nodes.slice();
271
+ return nodes.filter((seq) => !hidden.has(seq));
272
+ }
273
+
274
+ /**
275
+ * 已删除的工具行 callId 列表(供客户端在每次 DOM 重建后重新隐藏)。
276
+ * 工具行 DOM key = `9:tool-call<callId>`,因此只需 callId。
277
+ * @param events
278
+ * @returns {string[]}
279
+ */
280
+ function goneToolsOf(events) {
281
+ const hidden = tombstonedSeqsOf(events);
282
+ const out = [];
283
+ const seen = new Set();
284
+ for (const seq of hidden) {
285
+ const event = events[seq];
286
+ if (!event) continue;
287
+ if (event.type !== 'tool/result' && event.type !== 'tool/call') continue;
288
+ const callId = toolCallIdOf(event);
289
+ if (typeof callId !== 'string' || callId === '' || seen.has(callId)) continue;
290
+ seen.add(callId);
291
+ out.push(callId);
292
+ }
293
+ return out;
294
+ }
295
+
296
+ /** 判断键盘事件目标是否为可编辑控件(输入框内 Enter 必须交给控件自己处理)。 */
297
+ function isEditableTarget(target) {
298
+ if (!target || typeof target !== 'object') return false;
299
+ if (target.isContentEditable === true) return true;
300
+ const tag = typeof target.tagName === 'string' ? target.tagName.toUpperCase() : '';
301
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
302
+ }
303
+
304
+ /** 判断键盘事件目标是否落在按钮上(按钮上的 Enter 由原生 click 处理)。 */
305
+ function isButtonTarget(target) {
306
+ if (!target || typeof target !== 'object') return false;
307
+ if (typeof target.closest === 'function') {
308
+ try {
309
+ if (target.closest('button')) return true;
310
+ } catch {
311
+ /* 非 DOM 环境,回退到 tagName */
312
+ }
313
+ }
314
+ const tag = typeof target.tagName === 'string' ? target.tagName.toUpperCase() : '';
315
+ return tag === 'BUTTON';
316
+ }
317
+
318
+ /**
319
+ * 浮层键盘行为判定(纯函数,供客户端与离线测试共用)。
320
+ *
321
+ * - 浮层未打开:一律 none(不拦截宿主快捷键)。
322
+ * - Esc:dismiss。
323
+ * - Enter:焦点在输入框 / 可编辑区域 / 按钮上、或主操作不可用 / 正在执行时返回 none;
324
+ * 否则返回 primary。disabled 时客户端选择「什么都不做」,与点击禁用按钮一致。
325
+ * - 其它键:none。
326
+ *
327
+ * @param params {{ key?: string, target?: object, overlayOpen?: boolean, primaryEnabled?: boolean, busy?: boolean }}
328
+ * @returns {'none'|'dismiss'|'primary'}
329
+ */
330
+ function resolveKeyAction(params) {
331
+ const opts = params || {};
332
+ if (opts.overlayOpen !== true) return 'none';
333
+ if (opts.key === 'Escape' || opts.key === 'Esc') return 'dismiss';
334
+ if (opts.key !== 'Enter') return 'none';
335
+ // 焦点落在按钮上时交给原生 click:否则「取消」按钮上按 Enter 会同时触发主操作。
336
+ if (isEditableTarget(opts.target) || isButtonTarget(opts.target)) return 'none';
337
+ if (opts.busy === true) return 'none';
338
+ if (opts.primaryEnabled === false) return 'none';
339
+ return 'primary';
340
+ }
341
+
342
+ /** 去掉空白后的字符数(用于「答行统计」的“字数”)。 */
343
+ function wordCount(text) {
344
+ return String(text == null ? '' : text).replace(/\s/g, '').length;
345
+ }
346
+
347
+ /**
348
+ * 生成单行预览文本(供分享/导出多选列表使用)。
349
+ * 折叠换行与连续空白后截断,超出部分以 `…` 结尾;不改变原始文本,导出仍用全文。
350
+ * @param {string} text
351
+ * @param {number} limit 最大字符数(<=0 视为空)
352
+ * @returns {string}
353
+ */
354
+ function previewText(text, limit) {
355
+ const raw = String(text == null ? '' : text).replace(/\r\n?/g, '\n');
356
+ const flat = raw.replace(/[ \t\f\v]+/g, ' ').replace(/\s*\n\s*/g, ' ').trim();
357
+ if (!Number.isFinite(limit) || limit <= 0) return '';
358
+ if (flat.length <= limit) return flat;
359
+ return flat.slice(0, limit).trimEnd() + '…';
360
+ }
361
+
362
+ /**
363
+ * 紧凑的 token 计数:`169` / `1.2k` / `39.1k` / `120k`。
364
+ * @param {number} n
365
+ * @returns {string}
366
+ */
367
+ function formatTokens(n) {
368
+ if (!Number.isFinite(n) || n < 0) return '';
369
+ if (n < 1000) return String(Math.round(n));
370
+ const k = n / 1000;
371
+ return (k >= 100 ? String(Math.round(k)) : k.toFixed(1).replace(/\.0$/, '')) + 'k';
372
+ }
373
+
374
+ // ---------------------------------------------------------------------------
375
+ // 事件与表面结构
376
+ // ---------------------------------------------------------------------------
377
+
378
+ /** 判断某事件是否为本插件写入的墓碑。 */
379
+ function isTombstone(event) {
380
+ return !!event &&
381
+ event.type === 'user/message' &&
382
+ !!event.data &&
383
+ !!event.data.source &&
384
+ event.data.source.producer === PRODUCER;
385
+ }
386
+
387
+ /**
388
+ * 扫描日志,建立「轮次 -> { startSeq, endSeq }」索引。
389
+ * turn/start、turn/end 是 log-only 事件,不在 surface.nodes 里,
390
+ * 但它们的 seq 可用来界定该轮表面的上下界。
391
+ */
392
+ function buildTurnIndex(events) {
393
+ const starts = new Map();
394
+ events.forEach((evt, seq) => {
395
+ if (evt && evt.type === 'turn/start') {
396
+ const turn = evt.data && evt.data.turn;
397
+ if (typeof turn === 'number' && !starts.has(turn)) starts.set(turn, seq);
398
+ }
399
+ });
400
+ const index = [];
401
+ events.forEach((evt, seq) => {
402
+ if (evt && evt.type === 'turn/end') {
403
+ const turn = evt.data && evt.data.turn;
404
+ if (typeof turn === 'number' && starts.has(turn)) {
405
+ index.push({ turn, startSeq: starts.get(turn), endSeq: seq });
406
+ }
407
+ }
408
+ });
409
+ index.sort((a, b) => a.startSeq - b.startSeq);
410
+ return index;
411
+ }
412
+
413
+ /** 返回包含给定 seq 的轮次号;孤立(无 turn/start)返回 null。 */
414
+ function turnOf(turnIndex, seq) {
415
+ for (const info of turnIndex) {
416
+ if (seq > info.startSeq && seq < info.endSeq) return info.turn;
417
+ }
418
+ return null;
419
+ }
420
+
421
+ /**
422
+ * 把轮次区间展开成 seq → turn 的 Map,避免逐条消息线性扫描 turnIndex。
423
+ * 结果必须与 turnOf(turnIndex, seq) 一致(见离线测试)。
424
+ * @param turnIndex buildTurnIndex 的返回值
425
+ * @returns {Map<number, number>}
426
+ */
427
+ function buildTurnSeqMap(turnIndex) {
428
+ const map = new Map();
429
+ if (!Array.isArray(turnIndex)) return map;
430
+ for (const info of turnIndex) {
431
+ // 与 turnOf 的「按 startSeq 顺序取第一个命中」语义保持一致:
432
+ // 轮次区间若有重叠 / 嵌套,先出现的轮次优先,后出现的不得覆盖。
433
+ for (let seq = info.startSeq + 1; seq < info.endSeq; seq += 1) {
434
+ if (!map.has(seq)) map.set(seq, info.turn);
435
+ }
436
+ }
437
+ return map;
438
+ }
439
+
440
+ /** 一次构建轮次索引与 seq 映射,供 /messages 复用。 */
441
+ function createTurnLookup(events) {
442
+ const index = buildTurnIndex(events);
443
+ return { index, seqTurn: buildTurnSeqMap(index) };
444
+ }
445
+
446
+ /** 从 lookup(或现建)取某 seq 所属轮次。 */
447
+ function turnOfLookup(lookup, seq) {
448
+ if (lookup && lookup.seqTurn instanceof Map) {
449
+ const turn = lookup.seqTurn.get(seq);
450
+ return Number.isSafeInteger(turn) ? turn : null;
451
+ }
452
+ if (lookup && Array.isArray(lookup.index)) return turnOf(lookup.index, seq);
453
+ return null;
454
+ }
455
+
456
+ /** 返回同一 (turn, step) 的全部表面节点 seq(按出现顺序)。 */
457
+ function stepNodesOf(events, nodes, turn, step) {
458
+ const out = [];
459
+ for (const seq of nodes) {
460
+ const data = events[seq] && events[seq].data;
461
+ if (data && data.turn === turn && data.step === step) out.push(seq);
462
+ }
463
+ return out;
464
+ }
465
+
466
+ // ---------------------------------------------------------------------------
467
+ // 删除/撤回区间规划(核心纯函数)
468
+ // ---------------------------------------------------------------------------
469
+
470
+ /**
471
+ * 由目标 seq + action 规划要遮蔽的区间。
472
+ *
473
+ * @param events 完整日志事件数组(events[seq] = event)
474
+ * @param nodes 当前 surface.nodes(模型可见有序 seq 数组)
475
+ * @param params { action: "recall"|"delete"|"deleteFrom", seq: number }
476
+ * @returns
477
+ * 成功:{ ok:true, startSeq, endSeq, removed, kinds, via, turn, refillText }
478
+ * 失败:{ ok:false, code }
479
+ */
480
+ function planAction(events, nodes, params) {
481
+ const action = params && params.action;
482
+ const targetSeq = params && params.seq;
483
+ if ((action !== 'recall' && action !== 'delete' && action !== 'deleteFrom') ||
484
+ !Number.isSafeInteger(targetSeq) || targetSeq < 0) {
485
+ return { ok: false, code: 'INVALID_REQUEST' };
486
+ }
487
+
488
+ // 已写墓碑的节点不再可操作:宿主重建表面时可能仍把旧节点留在 nodes 里,
489
+ // 这里统一按「墓碑 → 可见集合」判定,避免对同一段内容重复撤回 / 重复删除。
490
+ const liveNodes = liveNodesOf(events, nodes);
491
+ const idx = liveNodes.indexOf(targetSeq);
492
+ if (idx === -1) return { ok: false, code: 'TARGET_NOT_FOUND' };
493
+ const evt = events[targetSeq];
494
+ if (!evt) return { ok: false, code: 'TARGET_NOT_FOUND' };
495
+
496
+ // 系统提示(节点 0)与 system/message 一律拒绝。
497
+ if (targetSeq === 0 || evt.type === 'system/message') {
498
+ return { ok: false, code: 'NOT_DELETABLE' };
499
+ }
500
+
501
+ // 撤回仅允许 user/message 且非系统/开发者来源。
502
+ if (action === 'recall') {
503
+ if (evt.type !== 'user/message') return { ok: false, code: 'NOT_A_USER_MESSAGE' };
504
+ const kind = evt.data && evt.data.source && evt.data.source.kind;
505
+ if (kind === 'system' || kind === 'developer') return { ok: false, code: 'NOT_DELETABLE' };
506
+ }
507
+
508
+ const turnIndex = buildTurnIndex(events);
509
+
510
+ // 删至末尾:从目标节点到 surface 末尾全部遮蔽。
511
+ if (action === 'deleteFrom') {
512
+ const endSeq = liveNodes[liveNodes.length - 1];
513
+ return buildPlan(events, liveNodes, targetSeq, endSeq, evt.type, 'deleteFrom',
514
+ turnOf(turnIndex, targetSeq));
515
+ }
516
+
517
+ // 问行:整轮;孤立提问只删自身。
518
+ if (evt.type === 'user/message') {
519
+ const turn = turnOf(turnIndex, targetSeq);
520
+ const plan = turn === null
521
+ ? buildPlan(events, liveNodes, targetSeq, targetSeq, evt.type, action, null)
522
+ : (() => {
523
+ const span = turnSpan(events, liveNodes, turnIndex, turn);
524
+ return buildPlan(events, liveNodes, span.startSeq, span.endSeq, evt.type, action, turn);
525
+ })();
526
+ // 撤回回填必须用被点的那条提问文本:轮次区间起点可能是运行时注入消息,
527
+ // 不能取 startSeq 的正文,否则会把注入上下文回填到输入框。
528
+ if (plan.ok && action === 'recall') plan.refillText = textOf(evt);
529
+ return plan;
530
+ }
531
+
532
+ // 答行 / 工具行:同 (turn, step) 的整 step。
533
+ if (evt.type === 'assistant/message' || evt.type === 'tool/result') {
534
+ const data = evt.data || {};
535
+ const { turn, step } = data;
536
+ if (!Number.isSafeInteger(turn) || !Number.isSafeInteger(step)) {
537
+ return { ok: false, code: 'NOT_DELETABLE' };
538
+ }
539
+ const stepNodes = stepNodesOf(events, liveNodes, turn, step);
540
+ if (stepNodes.length === 0) return { ok: false, code: 'TARGET_NOT_FOUND' };
541
+ const start = stepNodes[0];
542
+ const end = stepNodes[stepNodes.length - 1];
543
+ const startIdx = liveNodes.indexOf(start);
544
+ const endIdx = liveNodes.indexOf(end);
545
+ for (let i = startIdx; i <= endIdx; i++) {
546
+ if (!stepNodes.includes(liveNodes[i])) return { ok: false, code: 'SPAN_NOT_CONTIGUOUS' };
547
+ }
548
+ return buildPlan(events, liveNodes, start, end, evt.type, action, turn);
549
+ }
550
+
551
+ return { ok: false, code: 'NOT_DELETABLE' };
552
+ }
553
+
554
+ /** 计算某个轮次在 surface 中覆盖的 [startSeq, endSeq](含边界)。 */
555
+ function turnSpan(events, nodes, turnIndex, turn) {
556
+ const info = turnIndex.find((item) => item.turn === turn);
557
+ if (!info) return { startSeq: null, endSeq: null };
558
+ const inTurn = nodes.filter((seq) => seq > info.startSeq && seq < info.endSeq);
559
+ if (inTurn.length === 0) return { startSeq: null, endSeq: null };
560
+ return { startSeq: inTurn[0], endSeq: inTurn[inTurn.length - 1] };
561
+ }
562
+
563
+ /** 由区间组装一个可落地的删除计划。 */
564
+ function buildPlan(events, nodes, startSeq, endSeq, targetType, action, turn) {
565
+ const startIdx = nodes.indexOf(startSeq);
566
+ const endIdx = nodes.indexOf(endSeq);
567
+ if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {
568
+ return { ok: false, code: 'TARGET_NOT_FOUND' };
569
+ }
570
+ const removed = nodes.slice(startIdx, endIdx + 1);
571
+ const kinds = removed.map((seq) => (events[seq] ? events[seq].type : 'unknown'));
572
+ const via = targetType === 'user/message' ? 'user' :
573
+ targetType === 'assistant/message' ? 'assistant' :
574
+ targetType === 'tool/result' ? 'tool' : 'unknown';
575
+ const target = events[startSeq] || {};
576
+ const step = target.data && Number.isSafeInteger(target.data.step) ? target.data.step : undefined;
577
+ return {
578
+ ok: true,
579
+ startSeq,
580
+ endSeq,
581
+ removed,
582
+ kinds,
583
+ via,
584
+ turn,
585
+ step,
586
+ refillText: action === 'recall' ? textOf(events[startSeq]) : null
587
+ };
588
+ }
589
+
590
+ // ---------------------------------------------------------------------------
591
+ // 分享 / 导出:活表面分组
592
+ // ---------------------------------------------------------------------------
593
+
594
+ /**
595
+ * 从活表面分离出「轮次」列表(排除墓碑与系统提示),供分享/导出使用。
596
+ * @returns [{ turn, question, answer }],按轮次升序。
597
+ */
598
+ function roundsOf(events, nodes, lookup) {
599
+ const turns = lookup || createTurnLookup(events);
600
+ const rounds = new Map();
601
+ const ensure = (turn) => {
602
+ if (!rounds.has(turn)) rounds.set(turn, { turn, question: '', answer: '' });
603
+ return rounds.get(turn);
604
+ };
605
+ // 不依赖宿主表面是否重放了 surfaceOp:被墓碑覆盖的节点一律不导出。
606
+ for (const seq of liveNodesOf(events, nodes)) {
607
+ const evt = events[seq];
608
+ if (!evt || isTombstone(evt)) continue;
609
+ if (evt.type === 'user/message') {
610
+ const turn = turnOfLookup(turns, seq);
611
+ if (turn === null) continue; // 无轮次归属的游离消息不进导出
612
+ // 运行时上下文 / 技能目录 / 时间上下文也是 user/message,但不算用户提问。
613
+ const kind = evt.data && evt.data.source && evt.data.source.kind;
614
+ if (kind !== undefined && kind !== 'user') continue;
615
+ const r = ensure(turn);
616
+ const text = textOf(evt);
617
+ // 一轮只取第一条真实提问:runtime context / system-reminder 等注入消息不混入导出。
618
+ if (text && !r.question) r.question = text;
619
+ } else if (evt.type === 'assistant/message') {
620
+ const data = evt.data || {};
621
+ const turn = Number.isSafeInteger(data.turn) ? data.turn : turnOfLookup(turns, seq);
622
+ if (turn === null) continue;
623
+ const r = ensure(turn);
624
+ const text = textOf(evt);
625
+ // 一轮只保留最后一条回答,避免把中间步骤 / 重试内容拼进导出。
626
+ if (text) r.answer = text;
627
+ }
628
+ }
629
+ return [...rounds.values()].sort((a, b) => a.turn - b.turn);
630
+ }
631
+
632
+ /**
633
+ * 计算「已消失轮次」:日志里有 turn/start 但当前 surface 中已无任何活节点的轮次。
634
+ * 用于导航刻度隐藏(turnOutline 只看 turn/start,忽略 surfaceOp,必须靠客户端补齐)。
635
+ * @returns 升序的轮次号数组。
636
+ */
637
+ function goneTurnsOf(events, nodes, lookup) {
638
+ const turns = lookup || createTurnLookup(events);
639
+ const turnIndex = turns.index;
640
+ if (turnIndex.length === 0) return [];
641
+ const live = new Set();
642
+ for (const seq of liveNodesOf(events, nodes)) {
643
+ const evt = events[seq];
644
+ if (!evt || isTombstone(evt)) continue;
645
+ const data = evt.data || {};
646
+ const turn = Number.isSafeInteger(data.turn) ? data.turn : turnOfLookup(turns, seq);
647
+ if (Number.isSafeInteger(turn)) live.add(turn);
648
+ }
649
+ return turnIndex.filter((info) => !live.has(info.turn)).map((info) => info.turn);
650
+ }
651
+
652
+ /**
653
+ * `/messages` 摘要快照:只返回预览、字数、用量与 callId,不返回正文。
654
+ * 分享图 / 导出需要全文时,走 `full=1&turns=a,b` 的按需接口(见 index.mjs)。
655
+ *
656
+ * 增量:传入 `since`(上次快照的 version)时,rows 只回 seq > since 的行,
657
+ * rounds 只回本次有新增行的轮次,并额外回 `removedSeqs`(since 之后墓碑
658
+ * 覆盖的 seq),供客户端合并并剔除已删行;不带 since 仍是全量快照。
659
+ * goneTurns / goneTools 始终全量返回,删除同步不受增量影响。
660
+ *
661
+ * @param events 按 seq 索引的事件数组
662
+ * @param nodes 当前 surface.nodes
663
+ * @param lookup createTurnLookup 的返回值(可缺省)
664
+ * @param options { filter?: Set<number>, since?: number, previewLimit?: number }
665
+ * @returns {{ version: number, nodeCount: number, rows: Array, rounds: Array, goneTurns: number[], goneTools: string[], removedSeqs: number[] }}
666
+ */
667
+ function messagesSummaryOf(events, nodes, lookup, options) {
668
+ const opts = options || {};
669
+ const turns = lookup || createTurnLookup(events);
670
+ const filter = opts.filter instanceof Set ? opts.filter : null;
671
+ // 游标 v.s. seqs 列表:seqs 是「包含列表」,且长会话里已持有的 seq 数量会无限增长;
672
+ // 游标只传一个整数,天然表达「只要新的」。
673
+ const since = Number.isSafeInteger(opts.since) && opts.since >= 0 ? opts.since : null;
674
+ const previewLimit = Number.isFinite(opts.previewLimit) && opts.previewLimit > 0
675
+ ? Math.floor(opts.previewLimit)
676
+ : 200;
677
+ const rows = [];
678
+ const rounds = new Map();
679
+ const touched = since === null ? null : new Set();
680
+ const ensure = (turn) => {
681
+ if (!rounds.has(turn)) rounds.set(turn, { turn, questionPreview: '', answerPreview: '' });
682
+ return rounds.get(turn);
683
+ };
684
+ const liveNodes = liveNodesOf(events, nodes);
685
+ for (const seq of liveNodes) {
686
+ const event = events[seq];
687
+ if (!event || isTombstone(event)) continue;
688
+ const data = event.data || {};
689
+ const explicitTurn = data.turn;
690
+ const turn = Number.isSafeInteger(explicitTurn) ? explicitTurn : turnOfLookup(turns, seq);
691
+ // 只有真实提问与助手回答进入预览:system / developer 消息、运行时注入的
692
+ // 上下文(user/message + 非 user 来源)与工具结果都不回传正文。
693
+ const isUserQuestion = event.type === 'user/message' &&
694
+ (data.source === undefined || data.source === null || data.source.kind === undefined || data.source.kind === 'user');
695
+ const isText = isUserQuestion || event.type === 'assistant/message';
696
+ const text = isText ? textOf(event) : '';
697
+ const summary = {
698
+ seq,
699
+ type: event.type,
700
+ id: messageIdOf(event),
701
+ turn,
702
+ step: data.step,
703
+ role: messageRoleOf(event),
704
+ sourceKind: (data.source && data.source.kind) || 'user',
705
+ preview: isText ? previewText(text, previewLimit) : '',
706
+ words: isText ? wordCount(text) : 0,
707
+ usage: usageSummaryOf(event),
708
+ callId: toolCallIdOf(event)
709
+ };
710
+ const beyondCursor = since === null || seq > since;
711
+ if (beyondCursor && (!filter || filter.has(seq))) rows.push(summary);
712
+
713
+ if (isUserQuestion) {
714
+ if (turn === null) continue;
715
+ const round = ensure(turn);
716
+ if (summary.preview && !round.questionPreview) round.questionPreview = summary.preview;
717
+ } else if (event.type === 'assistant/message') {
718
+ if (turn === null) continue;
719
+ const round = ensure(turn);
720
+ if (summary.preview) round.answerPreview = summary.preview;
721
+ }
722
+ if (touched && beyondCursor && turn !== null) touched.add(turn);
723
+ }
724
+ const lastSeq = liveNodes.length > 0 ? liveNodes[liveNodes.length - 1] : 0;
725
+ // 增量响应附带 since 之后墓碑覆盖的 seq;全量响应不需要(rows 已不含它们)。
726
+ const removedSeqs = [];
727
+ if (since !== null && Array.isArray(events)) {
728
+ const seen = new Set();
729
+ for (let seq = since + 1; seq < events.length; seq += 1) {
730
+ const event = events[seq];
731
+ if (!isTombstone(event)) continue;
732
+ const removed = event.data && event.data.source && event.data.source.removed;
733
+ if (!Array.isArray(removed)) continue;
734
+ for (const target of removed) {
735
+ if (!Number.isSafeInteger(target) || target < 0 || seen.has(target)) continue;
736
+ seen.add(target);
737
+ removedSeqs.push(target);
738
+ }
739
+ }
740
+ }
741
+ const sortedRounds = [...rounds.values()].sort((a, b) => a.turn - b.turn);
742
+ return {
743
+ version: Number.isSafeInteger(lastSeq) ? lastSeq : 0,
744
+ nodeCount: liveNodes.length,
745
+ rows,
746
+ rounds: touched === null ? sortedRounds : sortedRounds.filter((round) => touched.has(round.turn)),
747
+ goneTurns: goneTurnsOf(events, nodes, turns),
748
+ // 客户端在每次 DOM 重建(切换会话 / 刷新)后据此重新隐藏工具行,
749
+ // 不能只在删除成功当下隐藏一次。
750
+ goneTools: goneToolsOf(events),
751
+ removedSeqs
752
+ };
753
+ }
754
+
755
+ /**
756
+ * 合并增量摘要到已持有的快照:按 seq 合并行、按 turn 合并轮次,
757
+ * 剔除增量确认删除的 seq 以及整轮消失的轮次。
758
+ * goneTurns / goneTools 以服务端最新结果为准(服务端始终全量返回)。
759
+ */
760
+ function mergeMessageSummary(base, patch) {
761
+ const rows = new Map();
762
+ for (const row of (base && base.rows) || []) rows.set(row.seq, row);
763
+ for (const row of (patch && patch.rows) || []) rows.set(row.seq, row);
764
+ for (const seq of (patch && patch.removedSeqs) || []) rows.delete(seq);
765
+
766
+ const goneTurns = Array.isArray(patch && patch.goneTurns) ? patch.goneTurns : [];
767
+ for (const turn of goneTurns) {
768
+ for (const [seq, row] of rows) {
769
+ if (row.turn === turn) rows.delete(seq);
770
+ }
771
+ }
772
+
773
+ const rounds = new Map();
774
+ for (const round of (base && base.rounds) || []) rounds.set(round.turn, round);
775
+ for (const round of (patch && patch.rounds) || []) rounds.set(round.turn, round);
776
+ for (const turn of goneTurns) rounds.delete(turn);
777
+
778
+ return {
779
+ version: patch && Number.isSafeInteger(patch.version) ? patch.version : (base ? base.version : 0),
780
+ nodeCount: patch && Number.isSafeInteger(patch.nodeCount) ? patch.nodeCount : (base ? base.nodeCount : 0),
781
+ rows: [...rows.values()].sort((a, b) => a.seq - b.seq),
782
+ rounds: [...rounds.values()].sort((a, b) => a.turn - b.turn),
783
+ goneTurns,
784
+ goneTools: Array.isArray(patch && patch.goneTools) ? patch.goneTools : []
785
+ };
786
+ }
787
+
788
+ /** 生成本轮导出的 Markdown 文本(不含被删内容)。 */
789
+ function markdownOf(rounds, meta) {
790
+ const m = meta || {};
791
+ const lines = [];
792
+ if (m.title) lines.push(`# ${m.title}`);
793
+ lines.push(`> ${m.sessionId || ''}${m.exportedAt ? ' / ' + m.exportedAt : ''}`);
794
+ const qLabel = m.questionLabel || '问';
795
+ const aLabel = m.answerLabel || '答';
796
+ for (const round of rounds) {
797
+ lines.push('');
798
+ lines.push(`## ${qLabel} ${round.turn}`);
799
+ const question = (round.question || '').trim();
800
+ if (question) {
801
+ lines.push('');
802
+ lines.push(question);
803
+ }
804
+ lines.push('');
805
+ lines.push(`### ${aLabel}`);
806
+ const answer = (round.answer || '').trim();
807
+ lines.push('');
808
+ lines.push(answer || '');
809
+ }
810
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim() + '\n';
811
+ }
812
+
813
+ /** 导出文件名:dsh-{sessionId}-{YYYYMMDD-HHmm}.md */
814
+ function exportFilename(sessionId, date) {
815
+ const d = date instanceof Date ? date : new Date();
816
+ const pad = (n) => String(n).padStart(2, '0');
817
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`;
818
+ const safeId = String(sessionId == null ? '' : sessionId).replace(/[^\w.-]/g, '_').slice(0, 64);
819
+ return `dsh-${safeId}-${stamp}.md`;
820
+ }
821
+
822
+ // ---------------------------------------------------------------------------
823
+ // 导航刻度
824
+ // ---------------------------------------------------------------------------
825
+
826
+ /**
827
+ * 从导航刻度 aria-label(中/英)解析轮号:取最后一个整数。
828
+ * 例:'第 3 问' -> 3,'Turn 12' -> 12,'第 10 问,共 5 轮' -> 5。
829
+ */
830
+ function railTurnOf(label) {
831
+ if (typeof label !== 'string') return null;
832
+ const nums = label.match(/\d+/g);
833
+ if (!nums || nums.length === 0) return null;
834
+ const value = parseInt(nums[nums.length - 1], 10);
835
+ return Number.isFinite(value) ? value : null;
836
+ }
837
+
838
+ /**
839
+ * 导航刻度的轮号解析:`data-index` 语义未验证,只在它与 aria-label 结果
840
+ * 一致时才采用;不一致或缺失时完全回退到原有 railTurnOf,避免改变现状。
841
+ * @param dataIndex 元素 data-index 属性(可能是 0-based,未验证)
842
+ * @param label aria-label 文本
843
+ */
844
+ function railTurnOfAttributes(dataIndex, label) {
845
+ const byLabel = railTurnOf(label);
846
+ const raw = typeof dataIndex === 'number'
847
+ ? String(dataIndex)
848
+ : (typeof dataIndex === 'string' ? dataIndex.trim() : '');
849
+ const byIndex = /^\d+$/.test(raw) ? parseInt(raw, 10) : null;
850
+ if (byIndex !== null && Number.isFinite(byIndex) && byIndex >= 1) {
851
+ if (byLabel === null) return byIndex;
852
+ // aria-label 可能同时含「第 N 问」与「共 M 轮」:与首个整数或旧解析结果
853
+ // 任一一致即可信;都不一致说明 data-index 语义不同(如 0-based),回退旧逻辑。
854
+ const nums = typeof label === 'string' ? label.match(/\d+/g) : null;
855
+ const first = nums && nums.length > 0 ? parseInt(nums[0], 10) : null;
856
+ if (byIndex === byLabel || byIndex === first) return byIndex;
857
+ }
858
+ return byLabel;
859
+ }
860
+
861
+ /**
862
+ * 计算虚拟轨道上每个可见刻度的向上压缩偏移。
863
+ * @param items [{ turn, hidden }] 按轨道顺序
864
+ * @returns [{ turn, hidden, offset }],offset 为「排在它前面被隐藏的数量 * 10」像素。
865
+ */
866
+ function collapseRail(items) {
867
+ let hiddenBefore = 0;
868
+ return (items || []).map((item) => {
869
+ if (item.hidden) {
870
+ hiddenBefore += 1;
871
+ return { turn: item.turn, hidden: true, offset: 0 };
872
+ }
873
+ return { turn: item.turn, hidden: false, offset: hiddenBefore * 10 };
874
+ });
875
+ }
876
+
877
+ // ---------------------------------------------------------------------------
878
+ // HTTP 围栏与状态码
879
+ // ---------------------------------------------------------------------------
880
+
881
+ /** 写请求体上限(字节)。 */
882
+ const MAX_BODY_BYTES = 1024 * 1024;
883
+
884
+ /** 判断 Host 头是否为回环地址(localhost / 127.0.0.0/8 / ::1)。 */
885
+ function isLoopbackHost(hostHeader) {
886
+ if (typeof hostHeader !== 'string' || hostHeader.trim().length === 0) return false;
887
+ const raw = hostHeader.trim();
888
+ let host;
889
+ if (raw.startsWith('[')) {
890
+ // 带方括号的 IPv6(可含端口):[::1] 或 [::1]:8080
891
+ const close = raw.indexOf(']');
892
+ if (close === -1) return false;
893
+ host = raw.slice(1, close);
894
+ } else if (raw.startsWith(':')) {
895
+ // 裸 IPv6(如 ::1)
896
+ host = raw;
897
+ } else {
898
+ // 主机名或 IPv4,剥端口
899
+ const colon = raw.indexOf(':');
900
+ host = colon === -1 ? raw : raw.slice(0, colon);
901
+ }
902
+ host = host.toLowerCase();
903
+ return host === 'localhost' || host === '::1' || /^127\.\d+\.\d+\.\d+$/.test(host);
904
+ }
905
+
906
+ /**
907
+ * 入站请求三重围栏(纯函数,便于离线测试):
908
+ * 1. 仅回环 Host(挡住 DNS rebinding / 局域网来源);
909
+ * 2. Sec-Fetch-Site 只接受 `same-origin` / `none`(用户直达)或缺失(非浏览器客户端);
910
+ * 显式拒绝 `cross-site` 与 `same-site`(同站不同端口 / 子域的本机页面);
911
+ * 3. 携带 Origin 时必须与服务同源(expectedOrigin 由宿主实时计算);
912
+ * `expectedOrigin` 未知时一律拒绝带 Origin 的请求(失败即关闭)。
913
+ */
914
+ function isTrustedRequest(info) {
915
+ const { host, secFetchSite, origin, expectedOrigin } = info || {};
916
+ if (!isLoopbackHost(host)) return false;
917
+ if (secFetchSite !== undefined && secFetchSite !== 'same-origin' && secFetchSite !== 'none') {
918
+ return false;
919
+ }
920
+ if (origin === undefined) return true;
921
+ return expectedOrigin !== undefined && origin === expectedOrigin;
922
+ }
923
+
924
+ /** 错误码 -> HTTP 状态码映射。 */
925
+ function statusCodeOf(code) {
926
+ switch (code) {
927
+ case 'INVALID_REQUEST':
928
+ case 'INVALID_AMOUNT': return 400;
929
+ case 'FORBIDDEN': return 403;
930
+ case 'PAYLOAD_TOO_LARGE': return 413;
931
+ case 'AGENT_BUSY': return 423;
932
+ case 'SESSION_NOT_LIVE':
933
+ case 'TARGET_NOT_FOUND':
934
+ case 'NOT_DELETABLE':
935
+ case 'NOT_A_USER_MESSAGE':
936
+ case 'SPAN_NOT_CONTIGUOUS': return 409;
937
+ case 'INTERNAL': return 500;
938
+ default: return 500;
939
+ }
940
+ }
941
+
942
+ /**
943
+ * 判断异常是否为「智能体正忙」。
944
+ * 优先使用结构化字段(err.code / err.status / err.statusCode),
945
+ * 文案匹配只作为没有结构化字段时的兜底:
946
+ * 宿主 @deepseek-ai/dsh-agent-loop 抛出的忙错误目前是普通 Error(无 code),
947
+ * 因此兜底文案必须保留;但只要带了结构化字段,就以字段判定为准。
948
+ */
949
+ const BUSY_CODES = new Set(['AGENT_BUSY', 'ALREADY_ACTIVE', 'EBUSY', 'BUSY']);
950
+
951
+ function isBusyError(err) {
952
+ if (!err || typeof err !== 'object') return false;
953
+ const code = typeof err.code === 'string' ? err.code.trim().toUpperCase() : '';
954
+ const statusRaw = err.status != null ? err.status : err.statusCode;
955
+ const status = typeof statusRaw === 'number' && Number.isFinite(statusRaw) ? statusRaw : null;
956
+ if (code !== '' && BUSY_CODES.has(code)) return true;
957
+ if (status === 423) return true;
958
+ if (code !== '' || status !== null) return false;
959
+ const message = err instanceof Error ? err.message : String(err);
960
+ return message.includes('already has active work');
961
+ }
962
+
963
+ /** 依据 Content-Length 判断是否超限(离线可测的 413 判据)。 */
964
+ function bodyTooLarge(contentLength, limit = MAX_BODY_BYTES) {
965
+ const length = Number(contentLength);
966
+ return Number.isFinite(length) && length > limit;
967
+ }
968
+
969
+ // ---------------------------------------------------------------------------
970
+ // 费用统计:北京时间、峰谷定价、token 计价
971
+ // ---------------------------------------------------------------------------
972
+
973
+ /** 北京时间固定 UTC+8(无夏令时),不依赖宿主 / 浏览器本地时区。 */
974
+ const BJ_OFFSET_MS = 8 * 60 * 60 * 1000;
975
+
976
+ /** 该日期起(含)周末全天谷价;之前周末仍按工作日时段判定。 */
977
+ const WEEKEND_VALLEY_SINCE = '2026-08-23';
978
+
979
+ /** 谷价 = 高峰价的一半(官方固定规则,非可调)。 */
980
+ const VALLEY_FACTOR = 0.5;
981
+
982
+ /**
983
+ * 官方 2026 价目(单位 ¥/百万 token,取高峰价)。
984
+ * 官方调价时只改这里与测试期望值;最后核对日期 2026-11-01。
985
+ */
986
+ const PRICE_CHECKED_AT = '2026-11-01';
987
+ const PRICE_TABLE = {
988
+ 'deepseek-flash': { cacheHit: 0.04, cacheMiss: 2.0, output: 8.0, reasoning: 0 },
989
+ 'deepseek-v4-pro': { cacheHit: 0.30, cacheMiss: 9.0, output: 27.0, reasoning: 0 },
990
+ default: { cacheHit: 0.04, cacheMiss: 2.0, output: 8.0, reasoning: 0 }
991
+ };
992
+
993
+ /** 需要缓冲的计价事件类型(turn/start 单独处理,不占缓冲配额)。 */
994
+ const TURN_EVENT_TYPES = new Set(['request/header', 'assistant/attempt', 'assistant/message', 'turn/end']);
995
+
996
+ /** 单个 Turn 缓冲最多保留的计价事件条数;超出即放弃该轮(宁缺不错算)。 */
997
+ const MAX_TURN_EVENTS = 2000;
998
+
999
+ /** 金额校正允许的最大值(元)。 */
1000
+ const MAX_CORRECTION_YUAN = 1e7;
1001
+
1002
+ /** 日累计保留天数(北京时间自然日)。 */
1003
+ const DAILY_KEEP_DAYS = 90;
1004
+
1005
+ /** 把毫秒时间换算成北京时间的年月日与星期。 */
1006
+ function beijingParts(ms) {
1007
+ const t = Number.isFinite(ms) ? ms : Date.now();
1008
+ const d = new Date(t + BJ_OFFSET_MS);
1009
+ const year = d.getUTCFullYear();
1010
+ const month = d.getUTCMonth() + 1;
1011
+ const day = d.getUTCDate();
1012
+ const minutes = d.getUTCHours() * 60 + d.getUTCMinutes();
1013
+ const pad = (n) => String(n).padStart(2, '0');
1014
+ return {
1015
+ year,
1016
+ month,
1017
+ day,
1018
+ weekday: d.getUTCDay(),
1019
+ minutes,
1020
+ dateKey: `${year}-${pad(month)}-${pad(day)}`
1021
+ };
1022
+ }
1023
+
1024
+ /** 北京时间的自然日键 `YYYY-MM-DD`。 */
1025
+ function beijingDateKey(ms) {
1026
+ return beijingParts(ms).dateKey;
1027
+ }
1028
+
1029
+ /** 由北京时间年月日 + 当日分钟数还原 epoch ms(日/月溢出由 Date.UTC 处理)。 */
1030
+ function beijingMsOf(year, month, day, minutes) {
1031
+ return Date.UTC(year, month - 1, day, 0, 0, 0, 0) + minutes * 60000 - BJ_OFFSET_MS;
1032
+ }
1033
+
1034
+ /** 是否为「周末全天谷价」生效后的周末(含阈值当天)。 */
1035
+ function isValleyDay(parts) {
1036
+ const weekend = parts.weekday === 0 || parts.weekday === 6;
1037
+ return weekend && parts.dateKey >= WEEKEND_VALLEY_SINCE;
1038
+ }
1039
+
1040
+ /** 高峰窗口:09:00–12:00、14:00–18:00(北京时间)。 */
1041
+ function inPeakWindow(minutes) {
1042
+ return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080);
1043
+ }
1044
+
1045
+ /** 下一个工作日的 09:00(跳过谷价周末)。 */
1046
+ function nextWeekdayPeak(parts) {
1047
+ for (let i = 1; i <= 8; i += 1) {
1048
+ const at = beijingMsOf(parts.year, parts.month, parts.day + i, 540);
1049
+ if (!isValleyDay(beijingParts(at))) return at;
1050
+ }
1051
+ return beijingMsOf(parts.year, parts.month, parts.day + 1, 540);
1052
+ }
1053
+
1054
+ /**
1055
+ * 判定某时刻的峰 / 谷状态与下一次切换时刻。
1056
+ * @param {number} ms epoch ms(缺省取当前)
1057
+ * @returns {{ period: "peak"|"offpeak", nextChangeAt: number }}
1058
+ */
1059
+ function periodInfo(ms) {
1060
+ const t = Number.isFinite(ms) ? ms : Date.now();
1061
+ const parts = beijingParts(t);
1062
+ if (!isValleyDay(parts) && inPeakWindow(parts.minutes)) {
1063
+ const end = parts.minutes < 720 ? 720 : 1080;
1064
+ return { period: 'peak', nextChangeAt: beijingMsOf(parts.year, parts.month, parts.day, end) };
1065
+ }
1066
+ if (!isValleyDay(parts)) {
1067
+ if (parts.minutes < 540) {
1068
+ return { period: 'offpeak', nextChangeAt: beijingMsOf(parts.year, parts.month, parts.day, 540) };
1069
+ }
1070
+ if (parts.minutes < 840) {
1071
+ return { period: 'offpeak', nextChangeAt: beijingMsOf(parts.year, parts.month, parts.day, 840) };
1072
+ }
1073
+ }
1074
+ return { period: 'offpeak', nextChangeAt: nextWeekdayPeak(parts) };
1075
+ }
1076
+
1077
+ /** 峰谷切换文案:`12:00 转谷价` / `明日 9:00 起高峰` / `周一 9:00 起高峰`。 */
1078
+ function periodChangeText(nowMs, nextChangeAt, lang) {
1079
+ const isEn = lang === 'en';
1080
+ const now = beijingParts(nowMs);
1081
+ const next = beijingParts(nextChangeAt);
1082
+ const zhWeekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
1083
+ const enWeekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
1084
+ const pad = (n) => String(n).padStart(2, '0');
1085
+ const time = `${Math.floor(next.minutes / 60)}:${pad(next.minutes % 60)}`;
1086
+ let dayPrefix = '';
1087
+ if (next.dateKey !== now.dateKey) {
1088
+ const tomorrowKey = beijingParts(nowMs + 24 * 3600 * 1000).dateKey;
1089
+ if (next.dateKey === tomorrowKey) {
1090
+ dayPrefix = isEn ? 'Tomorrow ' : '明日 ';
1091
+ } else {
1092
+ dayPrefix = (isEn ? enWeekdays : zhWeekdays)[next.weekday] + ' ';
1093
+ }
1094
+ }
1095
+ const action = periodInfo(nowMs).period === 'peak'
1096
+ ? (isEn ? 'off-peak at ' : '转谷价')
1097
+ : (isEn ? 'peak at ' : '起高峰');
1098
+ return isEn ? `${action}${dayPrefix}${time}` : `${dayPrefix}${time} ${action}`;
1099
+ }
1100
+
1101
+ /** 按模型名取价目;未知 / 旧模型名回落到 default(与 deepseek-flash 同价)。 */
1102
+ function priceFor(model, table) {
1103
+ const prices = table && typeof table === 'object' ? table : PRICE_TABLE;
1104
+ const key = String(model == null ? '' : model).trim().toLowerCase();
1105
+ if (Object.prototype.hasOwnProperty.call(prices, key)) return prices[key];
1106
+ return prices.default || PRICE_TABLE.default;
1107
+ }
1108
+
1109
+ /** 计数型 token 值:非负安全整数才认。 */
1110
+ function tokenCount(value) {
1111
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
1112
+ }
1113
+
1114
+ /**
1115
+ * 单次金额:逐项用浮点元计算,最后一次性取整到微元(1e-6 元)。
1116
+ * reasoning 价一律 0(官方输出价已覆盖思考 token)。
1117
+ * @param usage 原始 usage(inputTokens / cacheReadTokens / outputTokens / reasoningTokens)
1118
+ * @param model 模型名
1119
+ * @param period "peak" | "offpeak"
1120
+ * @param table 价目表(缺省 PRICE_TABLE)
1121
+ * @returns {number} costMicros
1122
+ */
1123
+ function turnCost(usage, model, period, table) {
1124
+ const u = usage && typeof usage === 'object' ? usage : {};
1125
+ const p = priceFor(model, table);
1126
+ const factor = period === 'peak' ? 1 : VALLEY_FACTOR;
1127
+ const yuan =
1128
+ tokenCount(u.inputTokens) * p.cacheMiss / 1e6 +
1129
+ tokenCount(u.cacheReadTokens) * p.cacheHit / 1e6 +
1130
+ tokenCount(u.outputTokens) * p.output / 1e6 +
1131
+ tokenCount(u.reasoningTokens) * p.reasoning / 1e6;
1132
+ return Math.round(yuan * factor * 1e6);
1133
+ }
1134
+
1135
+ /** 多个 (route, usage) 分组分别计价后求和(不同模型不会用错单价)。 */
1136
+ function turnCostOfGroups(groups, period, table) {
1137
+ let micros = 0;
1138
+ for (const group of groups || []) {
1139
+ if (!group) continue;
1140
+ micros += turnCost(group.usage || group.tokens, group.model, period, table);
1141
+ }
1142
+ return micros;
1143
+ }
1144
+
1145
+ /**
1146
+ * 取 assistant 流最后一帧 usage(stream 为官方 compact records 数组)。
1147
+ * 兼容 `{type:"chunk",chunk:{type:"usage",usage}}` 与直接 usage 记录。
1148
+ */
1149
+ function streamUsageOf(stream) {
1150
+ if (Array.isArray(stream)) {
1151
+ for (let i = stream.length - 1; i >= 0; i -= 1) {
1152
+ const record = stream[i];
1153
+ if (!record || typeof record !== 'object') continue;
1154
+ if (record.type === 'chunk' && record.chunk && record.chunk.type === 'usage') {
1155
+ return record.chunk.usage;
1156
+ }
1157
+ if (record.type === 'usage' && record.usage) return record.usage;
1158
+ }
1159
+ return undefined;
1160
+ }
1161
+ if (stream && typeof stream === 'object' && stream.usage && typeof stream.usage === 'object') {
1162
+ return stream.usage;
1163
+ }
1164
+ return undefined;
1165
+ }
1166
+
1167
+ /** 消息路由:`message.source` 的 provider / model。 */
1168
+ function routeOfMessage(message) {
1169
+ if (!message || typeof message !== 'object') return undefined;
1170
+ const source = message.source;
1171
+ if (!source || typeof source !== 'object') return undefined;
1172
+ if (typeof source.provider !== 'string' || source.provider.length === 0) return undefined;
1173
+ if (typeof source.model !== 'string' || source.model.length === 0) return undefined;
1174
+ return { provider: source.provider, model: source.model };
1175
+ }
1176
+
1177
+ /** 归一化原始 usage:inputTokens / outputTokens 必须是计数,可选分项缺省按 0。 */
1178
+ function normalizeCostUsage(usage) {
1179
+ if (!usage || typeof usage !== 'object') return undefined;
1180
+ if (!Number.isSafeInteger(usage.inputTokens) || usage.inputTokens < 0) return undefined;
1181
+ if (!Number.isSafeInteger(usage.outputTokens) || usage.outputTokens < 0) return undefined;
1182
+ const cacheReadTokens = tokenCount(usage.cacheReadTokens);
1183
+ const cacheWriteTokens = tokenCount(usage.cacheWriteTokens);
1184
+ const reasoningTokens = tokenCount(usage.reasoningTokens);
1185
+ return {
1186
+ inputTokens: usage.inputTokens,
1187
+ cacheReadTokens,
1188
+ cacheWriteTokens,
1189
+ outputTokens: usage.outputTokens,
1190
+ reasoningTokens,
1191
+ totalTokens: tokenCount(usage.totalTokens) || usage.inputTokens + cacheReadTokens + cacheWriteTokens + usage.outputTokens
1192
+ };
1193
+ }
1194
+
1195
+ /** 从一个 step 的 message / attempt 取原始 usage(message 优先)。 */
1196
+ function stepUsageOf(messageEvent, attemptEvent) {
1197
+ const messageData = messageEvent && messageEvent.data;
1198
+ if (messageData && messageData.usage) {
1199
+ const normalized = normalizeCostUsage(messageData.usage);
1200
+ if (normalized) return normalized;
1201
+ }
1202
+ if (messageData) {
1203
+ const fromStream = normalizeCostUsage(streamUsageOf(messageData.stream));
1204
+ if (fromStream) return fromStream;
1205
+ }
1206
+ const attemptData = attemptEvent && attemptEvent.data;
1207
+ if (attemptData) {
1208
+ const normalized = normalizeCostUsage(streamUsageOf(attemptData.stream));
1209
+ if (normalized) return normalized;
1210
+ }
1211
+ return undefined;
1212
+ }
1213
+
1214
+ /** 路由列表里的第一条合法 route。 */
1215
+ function routeOfUsage(usage) {
1216
+ if (!usage || typeof usage !== 'object' || !Array.isArray(usage.routes)) return undefined;
1217
+ for (const route of usage.routes) {
1218
+ if (!route) continue;
1219
+ if (typeof route.provider !== 'string' || route.provider.length === 0) continue;
1220
+ if (typeof route.model !== 'string' || route.model.length === 0) continue;
1221
+ return { provider: route.provider, model: route.model };
1222
+ }
1223
+ return undefined;
1224
+ }
1225
+
1226
+ /**
1227
+ * provider → 计费口径:
1228
+ * - `deepseek-account` → account(账户余额可观测)
1229
+ * - 其他 DeepSeek 官方路由(如 deepseek-official)→ api-key
1230
+ * - 非 DeepSeek 的 provider(本地模型、第三方网关)→ local(不消耗 DeepSeek 余额)
1231
+ */
1232
+ function routingOfProvider(provider) {
1233
+ if (typeof provider !== 'string' || provider.length === 0) return null;
1234
+ const key = provider.trim().toLowerCase();
1235
+ if (!key) return null;
1236
+ if (key === 'deepseek-account') return 'account';
1237
+ if (key.startsWith('deepseek')) return 'api-key';
1238
+ return 'local';
1239
+ }
1240
+
1241
+ /**
1242
+ * 费用卡片样式枚举。数组顺序即设置页选项顺序:单行样式排在第一位。
1243
+ * 内部存储值沿用 `compact` / `default`,与旧版本配置兼容。
1244
+ */
1245
+ const COST_LAYOUTS = ['compact', 'default'];
1246
+ const DEFAULT_COST_LAYOUT = 'compact';
1247
+
1248
+ /**
1249
+ * 把已保存 / 未配置的样式值归一为枚举值。
1250
+ * 旧配置里的 `default` 保持不变(映射到「多行样式」),未知值回退到当前默认值。
1251
+ * @param value 配置中的 costLayout
1252
+ * @returns {'compact' | 'default'}
1253
+ */
1254
+ function normalizeCostLayout(value) {
1255
+ return value === 'default' ? 'default' : DEFAULT_COST_LAYOUT;
1256
+ }
1257
+
1258
+ /**
1259
+ * 费用相关开关的运行时视图:每次调用都重新读取 Config,默认值保持「开启」。
1260
+ * @param config 宿主 Config(可能被配置通道原地更新)
1261
+ * @returns {{ enabled: boolean, perTurn: boolean }}
1262
+ */
1263
+ function costSwitches(config) {
1264
+ const cfg = config || {};
1265
+ return {
1266
+ enabled: cfg.usageStats !== false,
1267
+ perTurn: cfg.costPerTurn !== false
1268
+ };
1269
+ }
1270
+
1271
+ /**
1272
+ * 聚合一轮(turn/start…turn/end)内各 step 的 usage。
1273
+ * 每个 step 只取最后一个有效 assistant 结果(message 优先,其次 attempt),
1274
+ * 重试产生的多个 attempt 不重复累加;不同 route 的 step 分别成组,由调用方分价求和。
1275
+ *
1276
+ * @param events 本轮缓冲事件(可含 turn/start、turn/end)
1277
+ * @param options { fallbackRoute } 本轮回退路由(最近一次 request/header)
1278
+ * @returns undefined 或 { at, endedAt, turn, provider, models, tokens, groups }
1279
+ */
1280
+ function deriveTurnUsage(events, options) {
1281
+ if (!Array.isArray(events) || events.length === 0) return undefined;
1282
+ const fallbackRoute = options && options.fallbackRoute;
1283
+ let at;
1284
+ let endedAt;
1285
+ let turn;
1286
+ let headerRoute;
1287
+ const steps = new Map();
1288
+ const timeOf = (event) => {
1289
+ if (Number.isFinite(event.time)) return event.time;
1290
+ if (event.data && Number.isFinite(event.data.at)) return event.data.at;
1291
+ return undefined;
1292
+ };
1293
+
1294
+ for (const event of events) {
1295
+ if (!event || typeof event !== 'object') continue;
1296
+ const data = event.data || {};
1297
+ if (event.type === 'turn/start') {
1298
+ if (turn === undefined && Number.isSafeInteger(data.turn)) turn = data.turn;
1299
+ if (at === undefined) at = timeOf(event);
1300
+ continue;
1301
+ }
1302
+ if (event.type === 'turn/end') {
1303
+ if (endedAt === undefined) endedAt = timeOf(event);
1304
+ continue;
1305
+ }
1306
+ if (event.type === 'request/header') {
1307
+ const config = data.header && data.header.config;
1308
+ if (config && typeof config.provider === 'string' && typeof config.model === 'string') {
1309
+ headerRoute = { provider: config.provider, model: config.model };
1310
+ }
1311
+ continue;
1312
+ }
1313
+ if (event.type !== 'assistant/attempt' && event.type !== 'assistant/message') continue;
1314
+ const step = Number.isSafeInteger(data.step) ? data.step : 0;
1315
+ let entry = steps.get(step);
1316
+ if (!entry) {
1317
+ entry = { message: undefined, attempt: undefined, headerRoute };
1318
+ steps.set(step, entry);
1319
+ }
1320
+ if (event.type === 'assistant/message') entry.message = event;
1321
+ else entry.attempt = event;
1322
+ }
1323
+
1324
+ const groups = [];
1325
+ const models = [];
1326
+ const totals = {
1327
+ inputTokens: 0,
1328
+ cacheReadTokens: 0,
1329
+ cacheWriteTokens: 0,
1330
+ outputTokens: 0,
1331
+ reasoningTokens: 0,
1332
+ totalTokens: 0
1333
+ };
1334
+ let provider;
1335
+ for (const entry of steps.values()) {
1336
+ const usage = stepUsageOf(entry.message, entry.attempt);
1337
+ if (!usage) continue;
1338
+ const messageRoute = entry.message ? routeOfMessage(entry.message.data && entry.message.data.message) : undefined;
1339
+ const route = messageRoute ||
1340
+ routeOfUsage(entry.message && entry.message.data && entry.message.data.usage) ||
1341
+ routeOfUsage(entry.attempt && entry.attempt.data && entry.attempt.data.usage) ||
1342
+ entry.headerRoute ||
1343
+ headerRoute ||
1344
+ fallbackRoute;
1345
+ const model = route && route.model ? route.model : undefined;
1346
+ groups.push({ provider: route ? route.provider : undefined, model, usage });
1347
+ if (!provider && route && route.provider) provider = route.provider;
1348
+ if (model && models.indexOf(model) === -1) models.push(model);
1349
+ for (const key of Object.keys(totals)) totals[key] += usage[key] || 0;
1350
+ }
1351
+ if (groups.length === 0) return undefined;
1352
+
1353
+ return {
1354
+ at,
1355
+ endedAt,
1356
+ turn,
1357
+ provider: provider || undefined,
1358
+ models,
1359
+ tokens: totals,
1360
+ groups
1361
+ };
1362
+ }
1363
+
1364
+ /** 新建一轮缓冲。 */
1365
+ function createTurnBuffer(turn, at) {
1366
+ return { turn, at: Number.isFinite(at) ? at : Date.now(), events: [], overflow: false };
1367
+ }
1368
+
1369
+ /**
1370
+ * 向缓冲追加一条计价事件。
1371
+ * @returns true 表示已收下;false 表示类型不需要 / 已溢出(overflow 置位)
1372
+ */
1373
+ function appendTurnEvent(buffer, event) {
1374
+ if (!buffer || !event) return false;
1375
+ if (buffer.overflow) return false;
1376
+ if (!TURN_EVENT_TYPES.has(event.type)) return false;
1377
+ if (buffer.events.length >= MAX_TURN_EVENTS) {
1378
+ buffer.overflow = true;
1379
+ return false;
1380
+ }
1381
+ buffer.events.push(event);
1382
+ return true;
1383
+ }
1384
+
1385
+ // ---------------------------------------------------------------------------
1386
+ // 费用统计:余额观测(账户口径)与金额校正
1387
+ // ---------------------------------------------------------------------------
1388
+
1389
+ /** 间隔超过 25 小时视为应用长时间未运行,不补记差额。 */
1390
+ const MAX_OBSERVE_GAP_MS = 25 * 60 * 60 * 1000;
1391
+
1392
+ /** 校正后余额(允许为负)。 */
1393
+ function correctedBalanceCents(account) {
1394
+ const a = account || {};
1395
+ const baseline = Number.isFinite(a.baselineCents) ? a.baselineCents : null;
1396
+ if (baseline === null) return null;
1397
+ return baseline -
1398
+ (Number.isFinite(a.observedSpendCents) ? a.observedSpendCents : 0) +
1399
+ (Number.isFinite(a.creditCents) ? a.creditCents : 0) -
1400
+ (Number.isFinite(a.debitCents) ? a.debitCents : 0);
1401
+ }
1402
+
1403
+ /**
1404
+ * 一次余额观测的记账(纯函数,返回新状态与本次记账原因)。
1405
+ *
1406
+ * - 下降 → 累计「已观测消费」,按北京时间日期计入「日用」;
1407
+ * - 上升 → 累计「待核对余额调整」,绝不冲减消费;
1408
+ * - 跨日 / 间隔超 25h / 路由切换 → 只更新 lastBalance,跳过本次差额;
1409
+ * - 非 account 路由 → 完全不记账。
1410
+ *
1411
+ * @param state 持久化状态(不修改入参)
1412
+ * @param params { cents, routing, at }
1413
+ * @returns {{ state, reason }}
1414
+ */
1415
+ function observeBalance(state, params) {
1416
+ const s = state || {};
1417
+ const cents = params && Number.isFinite(params.cents) ? Math.round(params.cents) : null;
1418
+ const routing = params && params.routing;
1419
+ const at = params && Number.isFinite(params.at) ? params.at : Date.now();
1420
+ const out = {
1421
+ baselineBalanceCents: Number.isFinite(s.baselineBalanceCents) ? s.baselineBalanceCents : null,
1422
+ lastBalanceCents: Number.isFinite(s.lastBalanceCents) ? s.lastBalanceCents : null,
1423
+ lastBalanceAt: Number.isFinite(s.lastBalanceAt) ? s.lastBalanceAt : 0,
1424
+ lastRouting: typeof s.lastRouting === 'string' ? s.lastRouting : null,
1425
+ observedSpendTotalCents: Number.isFinite(s.observedSpendTotalCents) ? s.observedSpendTotalCents : 0,
1426
+ dailySpendCents: Object.assign({}, s.dailySpendCents || {}),
1427
+ pendingAdjustmentCents: Number.isFinite(s.pendingAdjustmentCents) ? s.pendingAdjustmentCents : 0,
1428
+ pendingAdjustmentAt: Number.isFinite(s.pendingAdjustmentAt) ? s.pendingAdjustmentAt : 0
1429
+ };
1430
+ if (cents === null) return { state: out, reason: 'invalid' };
1431
+ if (routing !== 'account') return { state: out, reason: 'not-account' };
1432
+
1433
+ if (out.baselineBalanceCents === null) {
1434
+ out.baselineBalanceCents = cents;
1435
+ out.lastBalanceCents = cents;
1436
+ out.lastBalanceAt = at;
1437
+ out.lastRouting = routing;
1438
+ return { state: out, reason: 'baseline' };
1439
+ }
1440
+ if (out.lastBalanceCents === null || out.lastBalanceAt === 0) {
1441
+ out.lastBalanceCents = cents;
1442
+ out.lastBalanceAt = at;
1443
+ out.lastRouting = routing;
1444
+ return { state: out, reason: 'first' };
1445
+ }
1446
+ if (out.lastRouting !== routing) {
1447
+ out.lastBalanceCents = cents;
1448
+ out.lastBalanceAt = at;
1449
+ out.lastRouting = routing;
1450
+ return { state: out, reason: 'routing-switch' };
1451
+ }
1452
+ if (beijingDateKey(out.lastBalanceAt) !== beijingDateKey(at)) {
1453
+ out.lastBalanceCents = cents;
1454
+ out.lastBalanceAt = at;
1455
+ return { state: out, reason: 'cross-day' };
1456
+ }
1457
+ if (at - out.lastBalanceAt > MAX_OBSERVE_GAP_MS) {
1458
+ out.lastBalanceCents = cents;
1459
+ out.lastBalanceAt = at;
1460
+ return { state: out, reason: 'too-long' };
1461
+ }
1462
+
1463
+ const diff = out.lastBalanceCents - cents;
1464
+ let reason = 'none';
1465
+ if (diff > 0) {
1466
+ out.observedSpendTotalCents += diff;
1467
+ const key = beijingDateKey(at);
1468
+ out.dailySpendCents[key] = (out.dailySpendCents[key] || 0) + diff;
1469
+ reason = 'spend';
1470
+ } else if (diff < 0) {
1471
+ out.pendingAdjustmentCents += -diff;
1472
+ out.pendingAdjustmentAt = at;
1473
+ reason = 'adjust';
1474
+ }
1475
+ out.lastBalanceCents = cents;
1476
+ out.lastBalanceAt = at;
1477
+ return { state: out, reason };
1478
+ }
1479
+
1480
+ /** 元(数字或字符串)转分;非法返回 null。 */
1481
+ function yuanToCents(value) {
1482
+ if (typeof value === 'number') {
1483
+ if (!Number.isFinite(value)) return null;
1484
+ return Math.round(value * 100);
1485
+ }
1486
+ if (typeof value !== 'string') return null;
1487
+ const raw = value.trim().replace(/,/g, '');
1488
+ if (!/^-?\d+(\.\d+)?$/.test(raw)) return null;
1489
+ const negative = raw.startsWith('-');
1490
+ const body = negative ? raw.slice(1) : raw;
1491
+ const split = body.split('.');
1492
+ const whole = split[0];
1493
+ const frac = split[1] || '';
1494
+ let cents = Number(whole) * 100 + Number((frac + '00').slice(0, 2));
1495
+ if (frac.length > 2 && Number(frac.charAt(2)) >= 5) cents += 1;
1496
+ return negative ? -cents : cents;
1497
+ }
1498
+
1499
+ /**
1500
+ * 校正金额校验:有限数字(或数字字符串)、≥ 0、最多两位小数、≤ 1e7。
1501
+ * @returns {{ ok: true, cents } | { ok: false, code: "INVALID_AMOUNT" }}
1502
+ */
1503
+ function validateCorrectionAmount(value) {
1504
+ let num;
1505
+ if (typeof value === 'number') {
1506
+ num = value;
1507
+ } else if (typeof value === 'string' && value.trim().length > 0) {
1508
+ const raw = value.trim().replace(/,/g, '');
1509
+ if (!/^\d+(\.\d{0,2})?$/.test(raw)) return { ok: false, code: 'INVALID_AMOUNT' };
1510
+ num = Number(raw);
1511
+ } else {
1512
+ return { ok: false, code: 'INVALID_AMOUNT' };
1513
+ }
1514
+ if (!Number.isFinite(num)) return { ok: false, code: 'INVALID_AMOUNT' };
1515
+ if (num < 0 || num > MAX_CORRECTION_YUAN) return { ok: false, code: 'INVALID_AMOUNT' };
1516
+ const cents = Math.round(num * 100);
1517
+ if (Math.abs(cents / 100 - num) > 1e-9) {
1518
+ return { ok: false, code: 'INVALID_AMOUNT' };
1519
+ }
1520
+ return { ok: true, cents };
1521
+ }
1522
+
1523
+ /** 删除早于「北京今天 − keepDays 天」的日累计键(返回新对象)。 */
1524
+ function pruneDailySpend(daily, nowMs, keepDays) {
1525
+ const days = Number.isFinite(keepDays) ? keepDays : DAILY_KEEP_DAYS;
1526
+ const cutoff = beijingDateKey((Number.isFinite(nowMs) ? nowMs : Date.now()) - days * 24 * 3600 * 1000);
1527
+ const out = {};
1528
+ for (const [key, value] of Object.entries(daily || {})) {
1529
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) continue;
1530
+ if (key < cutoff) continue;
1531
+ if (!Number.isFinite(value)) continue;
1532
+ out[key] = value;
1533
+ }
1534
+ return out;
1535
+ }
1536
+
1537
+ // ---------------------------------------------------------------------------
1538
+ // 费用统计:展示格式与动画辅助(客户端与离线测试共用)
1539
+ // ---------------------------------------------------------------------------
1540
+
1541
+ /** 分 -> `16.84`(千分位、两位小数、允许负号);非有限值返回 `—`。 */
1542
+ function formatCents(cents) {
1543
+ if (!Number.isFinite(cents)) return '—';
1544
+ const rounded = Math.round(cents);
1545
+ const negative = rounded < 0;
1546
+ const abs = Math.abs(rounded);
1547
+ const yuan = String(Math.floor(abs / 100)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
1548
+ const fen = String(abs % 100).padStart(2, '0');
1549
+ return (negative ? '-' : '') + yuan + '.' + fen;
1550
+ }
1551
+
1552
+ /** 分 -> `¥16.84`。 */
1553
+ function formatYuanCents(cents) {
1554
+ const text = formatCents(cents);
1555
+ return text === '—' ? text : '¥' + text;
1556
+ }
1557
+
1558
+ /**
1559
+ * 微元 -> 单次金额展示:
1560
+ * 0 → `¥0.00`;0 < x < ¥0.01 → `<¥0.01`;其余按分四舍五入。
1561
+ */
1562
+ function formatCostMicros(micros) {
1563
+ if (!Number.isFinite(micros)) return '—';
1564
+ if (micros <= 0) return '¥0.00';
1565
+ if (micros < 10000) return '<¥0.01';
1566
+ return formatYuanCents(Math.round(micros / 10000));
1567
+ }
1568
+
1569
+ /** 自动关闭时刻:秒数 0 / 非法返回 null(不自动关闭);上限 600 秒。 */
1570
+ function autoCloseAt(firstSeenAt, seconds) {
1571
+ const s = typeof seconds === 'string' ? Number(seconds) : seconds;
1572
+ if (!Number.isFinite(firstSeenAt) || !Number.isFinite(s) || s <= 0) return null;
1573
+ return firstSeenAt + Math.min(600, s) * 1000;
1574
+ }
1575
+
1576
+ /** 数字滚动动画缓动:easeOutCubic,端点 0 → 0、1 → 1。 */
1577
+ function easeOutCubic(t) {
1578
+ const x = t <= 0 ? 0 : t >= 1 ? 1 : t;
1579
+ return 1 - Math.pow(1 - x, 3);
1580
+ }
1581
+
1582
+ // ---------------------------------------------------------------------------
1583
+ // 工具函数
1584
+ // ---------------------------------------------------------------------------
1585
+
1586
+ /**
1587
+ * 可取消的延迟执行器(DOM 观察器节流 / rAF 合并)。
1588
+ * 定时/取消函数可注入,便于离线测试「卸载后不再执行」。
1589
+ *
1590
+ * @param run 到点执行的回调
1591
+ * @param options { delay?: number, schedule?: (fn) => handle, cancel?: (handle) => void }
1592
+ * @returns {{ request: () => boolean, dispose: () => void, disposed: boolean }}
1593
+ */
1594
+ function createScheduler(run, options) {
1595
+ const o = options || {};
1596
+ const schedule = typeof o.schedule === 'function'
1597
+ ? o.schedule
1598
+ : (fn) => setTimeout(fn, Number.isFinite(o.delay) ? o.delay : 0);
1599
+ const cancel = typeof o.cancel === 'function'
1600
+ ? o.cancel
1601
+ : (handle) => clearTimeout(handle);
1602
+ let handle = null;
1603
+ let disposed = false;
1604
+
1605
+ return {
1606
+ request() {
1607
+ if (disposed || handle !== null) return false;
1608
+ handle = schedule(() => {
1609
+ handle = null;
1610
+ if (!disposed) run();
1611
+ });
1612
+ return true;
1613
+ },
1614
+ dispose() {
1615
+ disposed = true;
1616
+ if (handle !== null) {
1617
+ try { cancel(handle); } catch { /* 已触发 */ }
1618
+ handle = null;
1619
+ }
1620
+ },
1621
+ get disposed() {
1622
+ return disposed;
1623
+ }
1624
+ };
1625
+ }
1626
+
1627
+ /**
1628
+ * 请求代际栅栏:用于丢弃「后发先至」的旧快照。
1629
+ * 每次 begin() 递增代号,只有最新代号的结果才允许写回。
1630
+ * @returns {{ begin: () => number, isLatest: (token: number) => boolean }}
1631
+ */
1632
+ function createRequestGate() {
1633
+ let seq = 0;
1634
+ return {
1635
+ begin() {
1636
+ seq += 1;
1637
+ return seq;
1638
+ },
1639
+ isLatest(token) {
1640
+ return token === seq;
1641
+ }
1642
+ };
1643
+ }
1644
+
1645
+ /** HTML 转义(用于浮层内注入标题/正文)。 */
1646
+ function escapeHtml(value) {
1647
+ return String(value == null ? '' : value)
1648
+ .replaceAll('&', '&amp;')
1649
+ .replaceAll('<', '&lt;')
1650
+ .replaceAll('>', '&gt;')
1651
+ .replaceAll('"', '&quot;')
1652
+ .replaceAll("'", '&#39;');
1653
+ }
1654
+
1655
+ // ---------------------------------------------------------------------------
1656
+ // 图标(内置兜底:24 网格 / 1.5px 线宽 / round cap 的通用线性图标)
1657
+ //
1658
+ // 线宽 1.5 与官方图标(16 网格 / 1px 线宽)在 15px 尺寸下的视觉粗细一致,
1659
+ // 因此官方组件缺失时混用也不会出现粗细差异。
1660
+ // 运行时优先使用 DSH 官方图标组件(见 client.js 的 OFFICIAL_ICON_NAMES)。
1661
+ // ---------------------------------------------------------------------------
1662
+
1663
+ const ICONS = {
1664
+ recall: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/></svg>',
1665
+ share: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12v7a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-7"/><path d="M12 16V3"/><path d="m8 7 4-4 4 4"/></svg>',
1666
+ export: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 14v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5"/><path d="M12 3v11"/><path d="m8 10 4 4 4-4"/></svg>',
1667
+ delete: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v5M14 11v5"/></svg>',
1668
+ deleteFrom: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M12 10v6"/><path d="m9 13 3 3 3-3"/></svg>',
1669
+ check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L19 7"/></svg>'
1670
+ };
1671
+
1672
+ // ---------------------------------------------------------------------------
1673
+ // 客户端注入样式表
1674
+ // ---------------------------------------------------------------------------
1675
+
1676
+ /**
1677
+ * 客户端注入的行内样式。仅依赖 CSS 变量(DSH 主题提供),不硬编码品牌色。
1678
+ */
1679
+ const CSS = `
1680
+ .dma-row-actions{display:inline-flex;align-items:center;gap:2px;vertical-align:middle}
1681
+ .dma-tool-actions{display:inline-flex;align-items:center;gap:2px;margin-inline-start:6px;vertical-align:middle}
1682
+ .dma-btn{display:inline-flex;align-items:center;justify-content:center;width:calc(28px + var(--dsh-content-font-delta,0px));height:calc(28px + var(--dsh-content-font-delta,0px));padding:0;border:0;border-radius:var(--dsw-radius-sm,6px);background:transparent;color:var(--dsw-alias-label-tertiary,#8a919e);cursor:pointer;line-height:1;transition:background 80ms ease,color 80ms ease}
1683
+ .dma-btn svg{display:block;width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px))}
1684
+ .dma-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.06));color:var(--dsw-alias-label-secondary,#5b6472)}
1685
+ .dma-btn:disabled{opacity:.35;cursor:not-allowed}
1686
+ .dma-btn.dma-danger:hover{background:var(--dsw-alias-interactive-bg-hover-danger,rgba(229,72,77,.12));color:var(--dsw-alias-state-error-primary,#e5484d)}
1687
+ .dma-stats{order:1;display:inline-flex;align-items:center;font-size:11px;line-height:1;color:var(--dsw-alias-label-tertiary,#8a919e);white-space:nowrap;user-select:text;margin-inline:2px}
1688
+ [data-dma-hidden="1"]{display:none!important}
1689
+ [data-dma-rail="1"]{display:none!important}
1690
+ .dma-overlay{position:fixed;inset:0;z-index:2147483000;background:var(--dsw-alias-bg-mask-1,rgba(0,0,0,.45));display:flex;align-items:center;justify-content:center}
1691
+ .dma-panel{width:min(680px,calc(100vw - 48px));max-height:80vh;display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1,#ffffff);border:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1));border-radius:var(--dsw-radius-panel,12px);box-shadow:var(--dsw-elevation-panel,0 18px 48px rgba(0,0,0,.18));overflow:hidden;color:var(--dsw-alias-label-primary,#1f2329)}
1692
+ .dma-panel-head{padding:16px 20px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1));font-size:16px;font-weight:600}
1693
+ .dma-panel-body{overflow:auto;padding:12px 16px}
1694
+ .dma-round{display:flex;gap:12px;align-items:flex-start;padding:10px 8px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));border-radius:8px}
1695
+ .dma-round:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04))}
1696
+ .dma-round-box{flex:0 0 auto;width:20px;height:20px;border-radius:50%;border:1.5px solid var(--dsw-alias-border-l3,#c9ced6);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;padding:0;background:transparent;color:transparent;margin-top:2px}
1697
+ .dma-round-box[aria-checked="true"]{border-color:var(--dsw-alias-state-business-primary,#4c8dff);background:var(--dsw-alias-state-business-primary,#4c8dff);color:#fff}
1698
+ .dma-round-box svg{width:13px;height:13px}
1699
+ .dma-round-main{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:4px}
1700
+ .dma-round-line{display:flex;align-items:center;gap:8px;min-width:0;font-size:13px}
1701
+ .dma-round-tag{flex:0 0 auto;font-size:11px;line-height:18px;padding:0 6px;border-radius:9px;background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-secondary,#5b6472)}
1702
+ .dma-round-q{font-weight:600}
1703
+ .dma-round-q .dma-round-tag{background:var(--dsw-alias-button-primary-dimmed,rgba(76,141,255,.14));color:var(--dsw-alias-state-business-primary,#4c8dff)}
1704
+ .dma-round-tag-a{color:var(--dsw-alias-label-tertiary,#8a919e)}
1705
+ .dma-round-a{color:var(--dsw-alias-label-secondary,#5b6472)}
1706
+ .dma-round-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1707
+ .dma-panel-foot{display:flex;align-items:center;justify-content:space-between;padding:12px 20px;border-top:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1))}
1708
+ .dma-panel-foot .dma-btn{width:auto;height:32px;padding:0 14px;border:.5px solid var(--dsw-alias-border-l3,#c9ced6);border-radius:8px;color:var(--dsw-alias-label-secondary,#5b6472)}
1709
+ .dma-panel-foot .dma-primary{background:var(--dsw-alias-button-primary-fill,#4c8dff);color:var(--dsw-alias-label-primary-inverted,#fff);border-color:transparent}
1710
+ .dma-panel-foot .dma-primary.dma-danger{background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}
1711
+ .dma-panel-foot .dma-primary:disabled{background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-dimmed,#a0a6b0)}
1712
+ .dma-panel-foot .dma-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
1713
+ .dma-toast{position:fixed;left:50%;bottom:32px;transform:translateX(-50%);z-index:2147483100;padding:8px 16px;border-radius:999px;background:var(--dsw-alias-toast-bg,rgba(32,35,42,.96));box-shadow:0 6px 20px rgba(0,0,0,.22);font-size:12px;line-height:1.6;color:var(--dsw-alias-toast-label,#fff);pointer-events:none}
1714
+ `;
1715
+
1716
+ // ---------------------------------------------------------------------------
1717
+ // 导出
1718
+ // ---------------------------------------------------------------------------
1719
+
1720
+ module.exports = {
1721
+ PRODUCER,
1722
+ TOMBSTONE_TEXT,
1723
+ ERROR_LABELS,
1724
+ contentText,
1725
+ textOf,
1726
+ messageRoleOf,
1727
+ messageIdOf,
1728
+ usageSummaryOf,
1729
+ toolCallIdOf,
1730
+ toolCallIdFromNodeKey,
1731
+ toolNodeKeysToHide,
1732
+ findToolRowByCallId,
1733
+ tombstonedSeqsOf,
1734
+ liveNodesOf,
1735
+ goneToolsOf,
1736
+ resolveKeyAction,
1737
+ isEditableTarget,
1738
+ TOOL_NODE_KEY_PREFIX,
1739
+ wordCount,
1740
+ previewText,
1741
+ formatTokens,
1742
+ isTombstone,
1743
+ buildTurnIndex,
1744
+ buildTurnSeqMap,
1745
+ createTurnLookup,
1746
+ turnOf,
1747
+ turnOfLookup,
1748
+ stepNodesOf,
1749
+ planAction,
1750
+ turnSpan,
1751
+ buildPlan,
1752
+ roundsOf,
1753
+ goneTurnsOf,
1754
+ messagesSummaryOf,
1755
+ mergeMessageSummary,
1756
+ markdownOf,
1757
+ exportFilename,
1758
+ railTurnOf,
1759
+ railTurnOfAttributes,
1760
+ collapseRail,
1761
+ createScheduler,
1762
+ createRequestGate,
1763
+ escapeHtml,
1764
+ MAX_BODY_BYTES,
1765
+ isLoopbackHost,
1766
+ isTrustedRequest,
1767
+ statusCodeOf,
1768
+ isBusyError,
1769
+ bodyTooLarge,
1770
+ BJ_OFFSET_MS,
1771
+ WEEKEND_VALLEY_SINCE,
1772
+ VALLEY_FACTOR,
1773
+ PRICE_CHECKED_AT,
1774
+ PRICE_TABLE,
1775
+ MAX_TURN_EVENTS,
1776
+ MAX_CORRECTION_YUAN,
1777
+ DAILY_KEEP_DAYS,
1778
+ MAX_OBSERVE_GAP_MS,
1779
+ beijingParts,
1780
+ beijingDateKey,
1781
+ beijingMsOf,
1782
+ isValleyDay,
1783
+ inPeakWindow,
1784
+ periodInfo,
1785
+ periodChangeText,
1786
+ priceFor,
1787
+ turnCost,
1788
+ turnCostOfGroups,
1789
+ streamUsageOf,
1790
+ routeOfMessage,
1791
+ routeOfUsage,
1792
+ routingOfProvider,
1793
+ costSwitches,
1794
+ COST_LAYOUTS,
1795
+ DEFAULT_COST_LAYOUT,
1796
+ normalizeCostLayout,
1797
+ normalizeCostUsage,
1798
+ stepUsageOf,
1799
+ deriveTurnUsage,
1800
+ createTurnBuffer,
1801
+ appendTurnEvent,
1802
+ correctedBalanceCents,
1803
+ observeBalance,
1804
+ yuanToCents,
1805
+ validateCorrectionAmount,
1806
+ pruneDailySpend,
1807
+ formatCents,
1808
+ formatYuanCents,
1809
+ formatCostMicros,
1810
+ autoCloseAt,
1811
+ easeOutCubic,
1812
+ ICONS,
1813
+ CSS
1814
+ };
1815
+ return module.exports;
1816
+ })();
1817
+ const BUILD = "2026-11-03T09:14:46.153Z";
1818
+ // 构建时由 build.mjs 用 package.json 的 version 替换,避免设置页显示旧版本。
1819
+ const VERSION = "0.2.1";
1820
+
1821
+ if (typeof console !== "undefined" && typeof console.info === "function") {
1822
+ console.info("[dsh-message-actions] build", BUILD);
1823
+ }
1824
+
1825
+ const {
1826
+ ICONS,
1827
+ CSS,
1828
+ ERROR_LABELS,
1829
+ escapeHtml,
1830
+ markdownOf,
1831
+ exportFilename,
1832
+ toolCallIdFromNodeKey,
1833
+ toolNodeKeysToHide,
1834
+ findToolRowByCallId,
1835
+ resolveKeyAction,
1836
+ mergeMessageSummary,
1837
+ formatTokens,
1838
+ railTurnOfAttributes,
1839
+ createScheduler,
1840
+ createRequestGate,
1841
+ formatCents,
1842
+ formatYuanCents,
1843
+ formatCostMicros,
1844
+ periodInfo,
1845
+ periodChangeText,
1846
+ autoCloseAt,
1847
+ easeOutCubic,
1848
+ validateCorrectionAmount,
1849
+ yuanToCents,
1850
+ COST_LAYOUTS,
1851
+ DEFAULT_COST_LAYOUT,
1852
+ normalizeCostLayout
1853
+ } = shared;
1854
+
1855
+ const NS = "dsh-message-actions";
1856
+
1857
+ // -------------------------------------------------------------------------
1858
+ // 本地化字典(客户端 UI 文案)
1859
+ // -------------------------------------------------------------------------
1860
+
1861
+ // 文案单一来源:src/i18n.cjs(构建时内联为 IIFE,同时生成 locale/*.json)。
1862
+ const I18N = (function () {
1863
+ const module = { exports: {} };
1864
+ const exports = module.exports;
1865
+ // dsh-message-actions 本地化单一来源
1866
+ //
1867
+ // client.js 通过 I18N 占位符内联本文件的 IIFE;
1868
+ // build.mjs 同时据 meta 生成 locale/zh.json 与 locale/en.json。
1869
+ // 新增文案只需改这一处,避免客户端字典与 locale 文件漂移。
1870
+
1871
+ 'use strict';
1872
+
1873
+ const meta = {
1874
+ zh: {
1875
+ title: '消息费用',
1876
+ description: '撤回、删除、删至末尾;多选分享与导出对话;回答统计;DeepSeek 账户余额、日用与单次费用统计。'
1877
+ },
1878
+ en: {
1879
+ title: 'Messages & Cost',
1880
+ description: 'Recall, delete, and delete-to-end messages; multi-select share and export; per-answer statistics; DeepSeek balance, daily spend, and per-turn cost.'
1881
+ }
1882
+ };
1883
+
1884
+ const zh = {
1885
+ nav: '消息费用',
1886
+ 'btn.recall': '撤回',
1887
+ 'btn.share': '分享',
1888
+ 'btn.export': '导出',
1889
+ 'btn.delete': '删除',
1890
+ 'btn.deleteFrom': '删至末尾',
1891
+ 'btn.deleteTool': '删除该工具行',
1892
+ 'confirm.title': '确认操作',
1893
+ 'confirm.recall': '撤回该提问及其整轮回答?原文将回填到输入框。',
1894
+ 'confirm.delete': '删除该提问及其整轮回答?删除后不可恢复。',
1895
+ 'confirm.deleteFrom': '删除从该提问到对话末尾的全部内容?删除后不可恢复。',
1896
+ 'confirm.step': '删除该回答及其工具结果?删除后不可恢复。',
1897
+ 'confirm.tool': '删除该工具行?同一步的其它工具结果会一并删除,删除后不可恢复。',
1898
+ 'confirm.ok': '确认',
1899
+ 'confirm.cancel': '取消',
1900
+ 'pick.title.share': '选择对话',
1901
+ 'pick.title.export': '导出对话',
1902
+ 'pick.all': '全选',
1903
+ 'pick.cancel': '取消',
1904
+ 'pick.share': '生成图片',
1905
+ 'pick.export': '导出',
1906
+ 'pick.turn': '问',
1907
+ 'pick.answer': '答',
1908
+ 'pick.session': '会话',
1909
+ 'export.title': '导出对话',
1910
+ 'toast.empty': '没有可导出的内容',
1911
+ 'toast.busy': '正在生成回复,请稍后再试',
1912
+ 'toast.failed': '操作失败',
1913
+ 'toast.copied': '已复制到剪贴板',
1914
+ 'toast.tooMuch': '内容过多,无法生成图片',
1915
+ 'stats.unit': '字',
1916
+ 'stats.title': '回答 {tokens} tokens · {words} 字',
1917
+ 'settings.recall': '撤回',
1918
+ 'settings.recallDesc': '把自己发错的消息撤回(整轮),原文回填输入框',
1919
+ 'settings.share': '分享',
1920
+ 'settings.shareDesc': '选择对话并生成分享图片',
1921
+ 'settings.export': '导出',
1922
+ 'settings.exportDesc': '在问行提供入口,选择对话后导出 Markdown',
1923
+ 'settings.delete': '删除',
1924
+ 'settings.deleteDesc': '在问行删除整轮对话;在工具行删除该步工具结果',
1925
+ 'settings.deleteFrom': '删至末尾',
1926
+ 'settings.deleteFromDesc': '从该条起截断到会话末尾',
1927
+ 'settings.confirm': '操作确认',
1928
+ 'settings.confirmDesc': '撤回/删除前弹出确认框;关闭后直接执行',
1929
+ 'settings.stats': '回答统计',
1930
+ 'settings.statsDesc': '答行显示本次回答的 tokens 与字数',
1931
+ 'settings.soon': '即将推出',
1932
+ 'settings.saveFailed': '无法保存设置',
1933
+ 'cost.tab.actions': '消息操作',
1934
+ 'cost.tab.billing': '费用统计',
1935
+ 'cost.balance': '余额',
1936
+ 'cost.daily': '日用',
1937
+ 'cost.perTurn': '单次',
1938
+ 'cost.peak': '高峰价',
1939
+ 'cost.valley': '谷价',
1940
+ 'cost.title': '费用统计卡片',
1941
+ 'cost.refresh': '刷新余额',
1942
+ 'cost.refreshing': '正在刷新余额',
1943
+ 'cost.pending': '待核对',
1944
+ 'cost.pendingTitle': '余额有增加,请到 设置 → 消息费用 → 费用统计 → 余额校正 核对',
1945
+ 'cost.signedOut': '未登录',
1946
+ 'cost.apiKey': 'API key',
1947
+ 'cost.unavailable': '不可用',
1948
+ 'cost.local': '本地模型 · 无需计费',
1949
+ 'cost.stale': '沿用中',
1950
+ 'cost.staleTitle': '最近更新 {time}',
1951
+ 'cost.railTitle': '余额 {balance}',
1952
+ 'cost.hide': '隐藏单次',
1953
+ 'cost.settings.usageStats': '费用统计',
1954
+ 'cost.settings.usageStatsDesc': '侧边栏显示余额 / 日用 / 单次',
1955
+ 'cost.settings.perTurn': '单次消耗',
1956
+ 'cost.settings.perTurnDesc': '每轮对话结束后显示本轮换算金额',
1957
+ 'cost.settings.autoClose': '自动关闭',
1958
+ 'cost.settings.autoCloseDesc': '本轮金额显示多少秒后整组隐藏(0 = 不自动关闭)',
1959
+ 'cost.settings.peakValley': '峰谷定价行',
1960
+ 'cost.settings.peakValleyDesc': '在卡片中显示当前高峰 / 谷价与下一跳时间',
1961
+ 'cost.settings.layout': '计费样式',
1962
+ 'cost.settings.layoutDesc': '单行样式去背景、所有数字排成一行;多行样式带背景卡片与峰谷文字行',
1963
+ 'cost.layout.default': '多行样式',
1964
+ 'cost.layout.compact': '单行样式',
1965
+ 'cost.correction.title': '余额校正(DeepSeek 账户口径)',
1966
+ 'cost.correction.credit': '实际累计到账',
1967
+ 'cost.correction.debit': '非调用扣减',
1968
+ 'cost.correction.preview': '校正后余额(推导)',
1969
+ 'cost.correction.pending': '待核对调整',
1970
+ 'cost.correction.save': '保存校正',
1971
+ 'cost.correction.saving': '保存中…',
1972
+ 'cost.correction.invalid': '金额不合法:最多两位小数、≥ 0、≤ 10000000',
1973
+ 'cost.correction.failed': '保存失败,请稍后再试',
1974
+ 'cost.correction.negative': '与账户实际余额差异较大,请复核校正值',
1975
+ 'cost.correction.yuan': '¥',
1976
+ 'cost.note': '「单次」按官方价目换算,「日用」按账户额度实际下降观测;两者口径不同,不要求逐轮对齐。'
1977
+ };
1978
+
1979
+ const en = {
1980
+ nav: 'Messages & Cost',
1981
+ 'btn.recall': 'Recall',
1982
+ 'btn.share': 'Share',
1983
+ 'btn.export': 'Export',
1984
+ 'btn.delete': 'Delete',
1985
+ 'btn.deleteFrom': 'Delete to end',
1986
+ 'btn.deleteTool': 'Delete tool',
1987
+ 'confirm.title': 'Confirm action',
1988
+ 'confirm.recall': 'Recall this question and its whole reply? The text will be restored to the composer.',
1989
+ 'confirm.delete': 'Delete this question and its whole reply? This cannot be undone.',
1990
+ 'confirm.deleteFrom': 'Delete everything from this question to the end? This cannot be undone.',
1991
+ 'confirm.step': 'Delete this answer and its tool results? This cannot be undone.',
1992
+ 'confirm.tool': 'Delete this tool row? Other tool results in the same step are removed too. This cannot be undone.',
1993
+ 'confirm.ok': 'Confirm',
1994
+ 'confirm.cancel': 'Cancel',
1995
+ 'pick.title.share': 'Choose conversations',
1996
+ 'pick.title.export': 'Export conversations',
1997
+ 'pick.all': 'Select all',
1998
+ 'pick.cancel': 'Cancel',
1999
+ 'pick.share': 'Share image',
2000
+ 'pick.export': 'Export',
2001
+ 'pick.turn': 'Q',
2002
+ 'pick.answer': 'A',
2003
+ 'pick.session': 'Session',
2004
+ 'export.title': 'Exported conversations',
2005
+ 'toast.empty': 'Nothing to export',
2006
+ 'toast.busy': 'A reply is being generated; try again later',
2007
+ 'toast.failed': 'Operation failed',
2008
+ 'toast.copied': 'Copied to clipboard',
2009
+ 'toast.tooMuch': 'Too much content to render as an image',
2010
+ 'stats.unit': 'chars',
2011
+ 'stats.title': '{tokens} tokens · {words} chars',
2012
+ 'settings.recall': 'Recall',
2013
+ 'settings.recallDesc': 'Recall a message you sent (whole turn); the text returns to the composer',
2014
+ 'settings.share': 'Share',
2015
+ 'settings.shareDesc': 'Choose conversations and generate a share image',
2016
+ 'settings.export': 'Export',
2017
+ 'settings.exportDesc': 'Offer an entry on question rows; export selected conversations as Markdown',
2018
+ 'settings.delete': 'Delete',
2019
+ 'settings.deleteDesc': 'Delete a whole exchange from the question row; delete a step’s tool results from the tool row',
2020
+ 'settings.deleteFrom': 'Delete to end',
2021
+ 'settings.deleteFromDesc': 'Truncate the session from this message onward',
2022
+ 'settings.confirm': 'Confirm actions',
2023
+ 'settings.confirmDesc': 'Ask before recall/delete; when off, actions run immediately',
2024
+ 'settings.stats': 'Reply statistics',
2025
+ 'settings.statsDesc': 'Show tokens and character count on reply rows',
2026
+ 'settings.soon': 'Coming soon',
2027
+ 'settings.saveFailed': 'Could not save the setting',
2028
+ 'cost.tab.actions': 'Message Actions',
2029
+ 'cost.tab.billing': 'Cost Statistics',
2030
+ 'cost.balance': 'Bal',
2031
+ 'cost.daily': 'Today',
2032
+ 'cost.perTurn': 'Turn',
2033
+ 'cost.peak': 'Peak',
2034
+ 'cost.valley': 'Off-peak',
2035
+ 'cost.title': 'Cost statistics card',
2036
+ 'cost.refresh': 'Refresh balance',
2037
+ 'cost.refreshing': 'Refreshing balance',
2038
+ 'cost.pending': 'Check',
2039
+ 'cost.pendingTitle': 'Balance increased. Review it in Settings → Messages & Cost → Cost Statistics → Balance correction.',
2040
+ 'cost.signedOut': 'Signed out',
2041
+ 'cost.apiKey': 'API key',
2042
+ 'cost.unavailable': 'Unavailable',
2043
+ 'cost.local': 'Local · no billing',
2044
+ 'cost.stale': 'Cached',
2045
+ 'cost.staleTitle': 'Last updated {time}',
2046
+ 'cost.railTitle': 'Balance {balance}',
2047
+ 'cost.hide': 'Hide turn',
2048
+ 'cost.settings.usageStats': 'Cost statistics',
2049
+ 'cost.settings.usageStatsDesc': 'Show balance / today / last turn in the sidebar',
2050
+ 'cost.settings.perTurn': 'Per-turn',
2051
+ 'cost.settings.perTurnDesc': 'Show the converted cost of each finished turn',
2052
+ 'cost.settings.autoClose': 'Auto-hide',
2053
+ 'cost.settings.autoCloseDesc': 'Seconds before the last-turn group hides (0 = never)',
2054
+ 'cost.settings.peakValley': 'Peak/off-peak',
2055
+ 'cost.settings.peakValleyDesc': 'Show current pricing period and the next switch',
2056
+ 'cost.settings.layout': 'Style',
2057
+ 'cost.settings.layoutDesc': 'Single-line drops the background and keeps all numbers on one row; multi-line keeps the card and the pricing-period line',
2058
+ 'cost.layout.default': 'Multi-line',
2059
+ 'cost.layout.compact': 'Single-line',
2060
+ 'cost.correction.title': 'Balance correction',
2061
+ 'cost.correction.credit': 'Total credited',
2062
+ 'cost.correction.debit': 'Other deductions',
2063
+ 'cost.correction.preview': 'Corrected balance',
2064
+ 'cost.correction.pending': 'Pending adj.',
2065
+ 'cost.correction.save': 'Save',
2066
+ 'cost.correction.saving': 'Saving…',
2067
+ 'cost.correction.invalid': 'Invalid amount: at most two decimals, ≥ 0, ≤ 10000000',
2068
+ 'cost.correction.failed': 'Could not save; try again later',
2069
+ 'cost.correction.negative': 'Far from the actual balance; please review the correction values',
2070
+ 'cost.correction.yuan': '¥',
2071
+ 'cost.note': 'Per-turn uses official list prices; today is observed from the actual account balance drop. They use different bases and need not match turn by turn.'
2072
+ };
2073
+
2074
+ module.exports = { meta, zh, en };
2075
+
2076
+ return module.exports;
2077
+ })();
2078
+
2079
+ const zh = I18N.zh;
2080
+ const en = I18N.en;
2081
+
2082
+ const DICTS = { zh, en };
2083
+
2084
+ // 语言来源:优先宿主 locale 服务快照(active 为 "zh" / "en"),
2085
+ // 其次 <html lang>,最后浏览器语言。不能缓存:插件加载可能早于宿主同步 <html lang>。
2086
+ let localeService = null;
2087
+
2088
+ function normalizeLang(value) {
2089
+ const raw = String(value == null ? "" : value).toLowerCase();
2090
+ if (raw.startsWith("zh")) return "zh";
2091
+ if (raw.startsWith("en")) return "en";
2092
+ return null;
2093
+ }
2094
+
2095
+ function detectLang() {
2096
+ if (localeService && typeof localeService.getLocale === "function") {
2097
+ const snapshot = localeService.getLocale();
2098
+ const active = normalizeLang(snapshot && snapshot.active);
2099
+ if (active) return active;
2100
+ }
2101
+ const docLang = typeof document !== "undefined" ? document.documentElement.lang : "";
2102
+ const nav = typeof navigator !== "undefined" ? navigator.language : "";
2103
+ return normalizeLang(docLang) || normalizeLang(nav) || "zh";
2104
+ }
2105
+
2106
+ function t(key, params) {
2107
+ const dict = DICTS[detectLang()] || DICTS.zh;
2108
+ let text = dict[key] != null ? dict[key] : key;
2109
+ if (params) {
2110
+ for (const [k, v] of Object.entries(params)) {
2111
+ text = text.split("{" + k + "}").join(String(v));
2112
+ }
2113
+ }
2114
+ return text;
2115
+ }
2116
+
2117
+ // -------------------------------------------------------------------------
2118
+ // 图标:优先官方组件,缺失时回退内置 SVG
2119
+ // -------------------------------------------------------------------------
2120
+
2121
+ // 官方图标组件名(@deepseek-ai/dsh-client-ui-primitives)。
2122
+ // 除「撤回」外全部使用官方图标;官方缺失时回退内置 SVG。
2123
+ const OFFICIAL_ICON_NAMES = {
2124
+ recall: null,
2125
+ share: "IconShareOutlineRegular",
2126
+ export: "IconDownloadOutlineRegular",
2127
+ delete: "IconTrashOutlineRegular",
2128
+ deleteFrom: "IconArchiveOffOutlineRegular",
2129
+ check: "IconCheckOutlineRegular"
2130
+ };
2131
+
2132
+ function officialIconElement(kind, size) {
2133
+ if (!PRIMITIVES || typeof PRIMITIVES !== "object") return null;
2134
+ const name = OFFICIAL_ICON_NAMES[kind];
2135
+ const component = name ? PRIMITIVES[name] : null;
2136
+ if (typeof component !== "function") return null;
2137
+ return React.createElement(component, { size: size });
2138
+ }
2139
+
2140
+ /** 把图标画进命令式创建的按钮;返回 false 表示应使用内置 SVG。 */
2141
+ function paintButtonIcon(btn, kind) {
2142
+ const element = officialIconElement(kind, 15);
2143
+ if (!element) return false;
2144
+ if (!ReactDOMClient || typeof ReactDOMClient.createRoot !== "function") return false;
2145
+ try {
2146
+ const root = ReactDOMClient.createRoot(btn);
2147
+ root.render(element);
2148
+ btn.__dmaIconRoot = root;
2149
+ return true;
2150
+ } catch {
2151
+ return false;
2152
+ }
2153
+ }
2154
+
2155
+ function unmountButtonIcon(btn) {
2156
+ const root = btn.__dmaIconRoot;
2157
+ if (!root) return;
2158
+ btn.__dmaIconRoot = null;
2159
+ try {
2160
+ root.unmount();
2161
+ } catch {
2162
+ /* ignore */
2163
+ }
2164
+ }
2165
+
2166
+ /** 移除一个问行按钮容器前,先卸载 React 图标根,避免残留。 */
2167
+ function disposeActionsRow(row) {
2168
+ if (!row) return;
2169
+ row.querySelectorAll(".dma-btn").forEach(unmountButtonIcon);
2170
+ row.remove();
2171
+ }
2172
+
2173
+ // -------------------------------------------------------------------------
2174
+ // 最小可观测 store(供 slot 的 hooks 机制使用:subscribe + getSnapshot)
2175
+ // -------------------------------------------------------------------------
2176
+
2177
+ function createStore(initial) {
2178
+ let state = initial;
2179
+ const listeners = new Set();
2180
+ const api = {
2181
+ getSnapshot() {
2182
+ return state;
2183
+ },
2184
+ subscribe(listener) {
2185
+ listeners.add(listener);
2186
+ return () => {
2187
+ listeners.delete(listener);
2188
+ };
2189
+ },
2190
+ set(next) {
2191
+ if (next !== state) {
2192
+ state = next;
2193
+ for (const listener of [...listeners]) listener();
2194
+ }
2195
+ }
2196
+ };
2197
+ return api;
2198
+ }
2199
+
2200
+ // -------------------------------------------------------------------------
2201
+ // HTTP 工具(同源请求宿主 webServer 路由)
2202
+ // -------------------------------------------------------------------------
2203
+
2204
+ function baseOrigin() {
2205
+ if (typeof location !== "undefined" && location.origin) return location.origin;
2206
+ if (typeof document !== "undefined" && document.baseURI) {
2207
+ try {
2208
+ return new URL(document.baseURI).origin;
2209
+ } catch {
2210
+ /* ignore */
2211
+ }
2212
+ }
2213
+ return "";
2214
+ }
2215
+
2216
+ function apiUrl(path, query) {
2217
+ const url = baseOrigin() + path;
2218
+ return query ? url + "?" + query : url;
2219
+ }
2220
+
2221
+ /** 请求超时:宿主卡住时不至于让轮询 / 按钮永久挂起。 */
2222
+ const REQUEST_TIMEOUT_MS = 15000;
2223
+
2224
+ async function fetchWithTimeout(url, init) {
2225
+ if (typeof AbortController !== "function") return fetch(url, init);
2226
+ const controller = new AbortController();
2227
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
2228
+ try {
2229
+ return await fetch(url, Object.assign({}, init, { signal: controller.signal }));
2230
+ } finally {
2231
+ clearTimeout(timer);
2232
+ }
2233
+ }
2234
+
2235
+ async function postJson(path, body) {
2236
+ const res = await fetchWithTimeout(apiUrl(path), {
2237
+ method: "POST",
2238
+ headers: { "content-type": "application/json" },
2239
+ body: JSON.stringify(body)
2240
+ });
2241
+ let data = null;
2242
+ try {
2243
+ data = await res.json();
2244
+ } catch {
2245
+ data = null;
2246
+ }
2247
+ return { status: res.status, data };
2248
+ }
2249
+
2250
+ async function getJson(path, query) {
2251
+ const res = await fetchWithTimeout(apiUrl(path, query), { cache: "no-store" });
2252
+ let data = null;
2253
+ try {
2254
+ data = await res.json();
2255
+ } catch {
2256
+ data = null;
2257
+ }
2258
+ return { status: res.status, data };
2259
+ }
2260
+
2261
+ // -------------------------------------------------------------------------
2262
+ // 费用统计:共享状态 + 轮询
2263
+ // -------------------------------------------------------------------------
2264
+
2265
+ const COST_POLL_MS = 5000;
2266
+
2267
+ const costStore = createStore({ status: "idle", value: null, fetchedAt: 0, error: "" });
2268
+ let costForm = null;
2269
+ let costPollTimer = null;
2270
+ let costPolling = false;
2271
+ let costVisibilityBound = false;
2272
+
2273
+ function patchCostState(patch) {
2274
+ costStore.set(Object.assign({}, costStore.getSnapshot(), patch));
2275
+ }
2276
+
2277
+ /** 总开关(默认 true)。设置快照未就绪时按开启处理,避免首屏空白。 */
2278
+ function costEnabledNow() {
2279
+ if (!costForm || typeof costForm.getSnapshot !== "function") return true;
2280
+ const snap = costForm.getSnapshot();
2281
+ if (!snap || snap.status !== "ready" || typeof snap.value !== "object" || !snap.value) return true;
2282
+ return snap.value.usageStats !== false;
2283
+ }
2284
+
2285
+ async function fetchCostState(force) {
2286
+ try {
2287
+ const { status, data } = await getJson(
2288
+ "/dsh-message-actions/cost/state",
2289
+ force ? "refresh=1" : undefined
2290
+ );
2291
+ if (status === 200 && data && data.ok && data.value) {
2292
+ patchCostState({ status: "ready", value: data.value, fetchedAt: Date.now(), error: "" });
2293
+ return data.value;
2294
+ }
2295
+ patchCostState({ status: "error", error: "request" });
2296
+ } catch {
2297
+ patchCostState({ status: "error", error: "network" });
2298
+ }
2299
+ return null;
2300
+ }
2301
+
2302
+ function onCostVisibility() {
2303
+ if (typeof document !== "undefined" && !document.hidden && costEnabledNow()) {
2304
+ fetchCostState(false).catch(() => {});
2305
+ }
2306
+ }
2307
+
2308
+ function startCostPolling(form) {
2309
+ costForm = form;
2310
+ if (costPolling) return;
2311
+ costPolling = true;
2312
+ const tick = () => {
2313
+ if (typeof document !== "undefined" && document.hidden) return;
2314
+ if (!costEnabledNow()) return;
2315
+ fetchCostState(false).catch(() => {});
2316
+ };
2317
+ tick();
2318
+ costPollTimer = setInterval(tick, COST_POLL_MS);
2319
+ if (typeof document !== "undefined" && !costVisibilityBound) {
2320
+ costVisibilityBound = true;
2321
+ document.addEventListener("visibilitychange", onCostVisibility);
2322
+ }
2323
+ }
2324
+
2325
+ function stopCostPolling() {
2326
+ costPolling = false;
2327
+ if (costPollTimer !== null) {
2328
+ clearInterval(costPollTimer);
2329
+ costPollTimer = null;
2330
+ }
2331
+ if (typeof document !== "undefined" && costVisibilityBound) {
2332
+ costVisibilityBound = false;
2333
+ document.removeEventListener("visibilitychange", onCostVisibility);
2334
+ }
2335
+ }
2336
+
2337
+ // -------------------------------------------------------------------------
2338
+ // Toast
2339
+ // -------------------------------------------------------------------------
2340
+
2341
+ function showToast(text) {
2342
+ if (typeof document === "undefined") return;
2343
+ document.querySelectorAll("[data-dma-toast]").forEach((n) => n.remove());
2344
+ const node = document.createElement("div");
2345
+ node.className = "dma-toast";
2346
+ node.setAttribute("data-dma-toast", "1");
2347
+ node.textContent = text;
2348
+ document.body.appendChild(node);
2349
+ setTimeout(() => node.remove(), 3200);
2350
+ }
2351
+
2352
+ // -------------------------------------------------------------------------
2353
+ // 会话控制器(按 sessionId 分桶,避免跨会话串状态)
2354
+ // -------------------------------------------------------------------------
2355
+
2356
+ const controllers = new Map();
2357
+
2358
+ function sessionFor(ctx, sessionId) {
2359
+ let controller = controllers.get(sessionId);
2360
+ if (controller === undefined) {
2361
+ controller = new SessionController(ctx, sessionId);
2362
+ controllers.set(sessionId, controller);
2363
+ }
2364
+ return controller;
2365
+ }
2366
+
2367
+ /**
2368
+ * 回收已从 DOM 消失的会话控制器:快照里含完整正文,长期累积会占用内存。
2369
+ * 只删除当前页面找不到对应容器且没有在途请求的控制器,避免误删正在切换的会话。
2370
+ */
2371
+ function evictStaleControllers() {
2372
+ if (typeof document === "undefined" || controllers.size === 0) return;
2373
+ const alive = new Set();
2374
+ for (const el of document.querySelectorAll("[data-conversation-session]")) {
2375
+ const id = el.getAttribute("data-conversation-session");
2376
+ if (id) alive.add(id);
2377
+ }
2378
+ for (const [id, controller] of controllers) {
2379
+ if (alive.has(id) || controller.messagesPromise) continue;
2380
+ controllers.delete(id);
2381
+ }
2382
+ }
2383
+
2384
+ class SessionController {
2385
+ constructor(ctx, sessionId) {
2386
+ this.ctx = ctx;
2387
+ this.sessionId = sessionId;
2388
+ this.form = ctx.configForms.get("dsh-message-actions");
2389
+ this.messages = null; // { rows, rounds, goneTurns }
2390
+ this.messagesPromise = null;
2391
+ this.fetchedAt = 0; // 上次成功拉取快照的时间,用于 TTL 失效(避免永久缓存旧对话)
2392
+ this.hiddenTurns = new Set(); // 乐观隐藏的轮次(本地,用于导航与导出过滤)
2393
+ this.requestGate = createRequestGate(); // 丢弃后发先至的旧快照
2394
+ this.data = createStore({ messages: null, hidden: [] });
2395
+ this.overlay = createStore({ view: null });
2396
+ }
2397
+
2398
+ config() {
2399
+ const snap = this.form && this.form.getSnapshot ? this.form.getSnapshot() : null;
2400
+ return snap && typeof snap.value === "object" && snap.value !== null
2401
+ ? snap.value
2402
+ : {};
2403
+ }
2404
+
2405
+ refreshData() {
2406
+ this.data.set({ messages: this.messages, hidden: [...this.hiddenTurns] });
2407
+ }
2408
+
2409
+ addHiddenTurn(turn) {
2410
+ if (!Number.isFinite(turn)) return;
2411
+ this.hiddenTurns.add(turn);
2412
+ this.refreshData();
2413
+ }
2414
+
2415
+ /**
2416
+ * 拉取会话快照(rows / rounds / goneTurns)。
2417
+ * 快照必须随新轮次失效:早期实现把 promise 永久缓存,导致弹窗只看到 1 轮。
2418
+ * 普通刷新只带游标取增量;force(弹窗 / 操作前)仍取全量,覆盖任何变更。
2419
+ * @param {boolean} force true 时忽略 TTL 与在途请求,强制重新拉取
2420
+ */
2421
+ async fetchMessages(force) {
2422
+ const TTL = 3000;
2423
+ if (!force && this.messages && Date.now() - this.fetchedAt < TTL) return this.messages;
2424
+ if (this.messagesPromise && !force) return this.messagesPromise;
2425
+ // force 会绕过在途请求;用代际栅栏保证只有最新请求能写回快照。
2426
+ const token = this.requestGate.begin();
2427
+ const base = this.messages;
2428
+ const since = !force && base && Number.isSafeInteger(base.version) && base.version > 0
2429
+ ? base.version
2430
+ : null;
2431
+ const messagesUrl = (cursor) =>
2432
+ "sessionId=" + encodeURIComponent(this.sessionId) +
2433
+ (cursor === null ? "" : "&since=" + cursor);
2434
+ const promise = (async () => {
2435
+ try {
2436
+ let cursor = since;
2437
+ let { data } = await getJson("/dsh-message-actions/messages", messagesUrl(cursor));
2438
+ if (
2439
+ cursor !== null &&
2440
+ !(data && data.ok && data.value && Number.isSafeInteger(data.value.version) && data.value.version >= cursor)
2441
+ ) {
2442
+ // 游标回退(宿主重建会话 / 版本跳变):增量不可信,改为全量重取一次。
2443
+ cursor = null;
2444
+ ({ data } = await getJson("/dsh-message-actions/messages", messagesUrl(cursor)));
2445
+ }
2446
+ if (data && data.ok && data.value && this.requestGate.isLatest(token)) {
2447
+ this.messages = cursor === null
2448
+ ? data.value
2449
+ : mergeMessageSummary(base, data.value);
2450
+ this.fetchedAt = Date.now();
2451
+ this.refreshData();
2452
+ // 切换会话 / 刷新后重新挂载的 DOM 没有 data-dma-hidden,
2453
+ // 拿到最新快照后立刻按 goneTurns / goneTools 重放隐藏。
2454
+ syncRail();
2455
+ }
2456
+ return this.messages;
2457
+ } finally {
2458
+ if (this.messagesPromise === promise) this.messagesPromise = null;
2459
+ }
2460
+ })();
2461
+ this.messagesPromise = promise;
2462
+ return promise;
2463
+ }
2464
+
2465
+ /**
2466
+ * 按需拉取指定轮次的完整正文(分享图 / 导出使用)。
2467
+ * 摘要轮询不带正文,避免每 3 秒传整份对话;这里只拉用户实际选中的轮次。
2468
+ * @param {number[]} turns
2469
+ * @returns {Promise<Array<{ turn, question, answer }> | null>} 失败返回 null
2470
+ */
2471
+ async fetchRoundText(turns) {
2472
+ const list = (turns || []).filter(Number.isSafeInteger);
2473
+ if (list.length === 0) return [];
2474
+ const query =
2475
+ "sessionId=" + encodeURIComponent(this.sessionId) +
2476
+ "&full=1&turns=" + list.join(",");
2477
+ try {
2478
+ const { status, data } = await getJson("/dsh-message-actions/messages", query);
2479
+ if (status === 200 && data && data.ok && data.value && Array.isArray(data.value.rounds)) {
2480
+ return data.value.rounds;
2481
+ }
2482
+ } catch {
2483
+ /* 网络失败由调用方统一提示 */
2484
+ }
2485
+ return null;
2486
+ }
2487
+
2488
+ /** 按 turn 找到真实提问的 seq(问行按钮据此定位)。 */
2489
+ userSeqForTurn(rows, turn) {
2490
+ let fallback = null;
2491
+ for (const row of rows || []) {
2492
+ if (row.turn !== turn || row.type !== "user/message") continue;
2493
+ // 优先真实提问;运行时注入(runtime-context 等)只作为兜底。
2494
+ if (row.sourceKind === undefined || row.sourceKind === "user") return row.seq;
2495
+ if (fallback === null) fallback = row.seq;
2496
+ }
2497
+ return fallback;
2498
+ }
2499
+
2500
+ // —— 浮层控制 ——
2501
+
2502
+ openConfirm(action, opts) {
2503
+ this.overlay.set({ view: { kind: "confirm", action, ...(opts || {}) } });
2504
+ }
2505
+
2506
+ async openPick(mode, turn) {
2507
+ // 弹窗必须看到最新全部轮次,不能复用早期只有 1 轮的快照。
2508
+ await this.fetchMessages(true).catch(() => {});
2509
+ this.overlay.set({ view: { kind: "pick", mode, turn } });
2510
+ }
2511
+
2512
+ dismiss() {
2513
+ this.overlay.set({ view: null });
2514
+ }
2515
+
2516
+ requestAction(action, opts) {
2517
+ const config = this.config();
2518
+ if (config.confirm !== false) {
2519
+ this.openConfirm(action, opts);
2520
+ return;
2521
+ }
2522
+ this.doAction(action, opts);
2523
+ }
2524
+
2525
+ confirmAction(action, opts) {
2526
+ this.dismiss();
2527
+ this.doAction(action, opts);
2528
+ }
2529
+
2530
+ async doAction(action, opts) {
2531
+ const body = { sessionId: this.sessionId, action };
2532
+ if (opts && opts.seq != null) body.seq = opts.seq;
2533
+ else if (opts && opts.messageId != null) body.messageId = opts.messageId;
2534
+
2535
+ let data;
2536
+ try {
2537
+ ({ data } = await postJson("/dsh-message-actions", body));
2538
+ } catch {
2539
+ // 网络中断 / 宿主 15s 超时:必须给用户可理解的反馈,且不留下未捕获 rejection。
2540
+ showToast(t("toast.failed"));
2541
+ return false;
2542
+ }
2543
+ if (!data || !data.ok) {
2544
+ const code = data && data.error && data.error.code;
2545
+ const labels = ERROR_LABELS[detectLang()] || ERROR_LABELS.zh;
2546
+ if (code === "AGENT_BUSY") showToast(t("toast.busy"));
2547
+ else showToast((code && labels[code]) || t("toast.failed"));
2548
+ return false;
2549
+ }
2550
+
2551
+ const value = data.value || {};
2552
+ const removedTurn = value.turn;
2553
+ if (value.via === "user" && Number.isFinite(removedTurn)) {
2554
+ this.addHiddenTurn(removedTurn);
2555
+ } else if (value.via === "tool" && opts && opts.nodeKey) {
2556
+ // 工具行删除只遮蔽该工具节点,不影响同轮其它内容。
2557
+ applyHiddenTool(this.sessionId, opts.nodeKey);
2558
+ }
2559
+ if (action === "recall" && value.refillText) {
2560
+ refillComposer(this.sessionId, value.refillText);
2561
+ }
2562
+ // 刷新消息快照(拿到最新 goneTurns),再重放导航隐藏。
2563
+ await this.fetchMessages(true).catch(() => {});
2564
+ syncRail();
2565
+ return true;
2566
+ }
2567
+ }
2568
+
2569
+ // -------------------------------------------------------------------------
2570
+ // DOM 工具
2571
+ // -------------------------------------------------------------------------
2572
+
2573
+ function sessionElement(sessionId) {
2574
+ if (typeof document === "undefined") return null;
2575
+ for (const el of document.querySelectorAll("[data-conversation-session]")) {
2576
+ if (el.getAttribute("data-conversation-session") === sessionId) return el;
2577
+ }
2578
+ return null;
2579
+ }
2580
+
2581
+ function isRunning(sessionId) {
2582
+ const el = sessionElement(sessionId);
2583
+ return !!(el && el.querySelector("[data-chat-running]"));
2584
+ }
2585
+
2586
+ function refillComposer(sessionId, text) {
2587
+ if (!text) return;
2588
+ const sessionEl = sessionElement(sessionId);
2589
+ if (!sessionEl) {
2590
+ showToast(t("toast.failed"));
2591
+ return;
2592
+ }
2593
+ const editable = sessionEl.querySelector(
2594
+ "[data-conversation-region='composer'] [contenteditable='true']"
2595
+ );
2596
+ if (!editable) {
2597
+ // 找不到输入框时退回剪贴板;给用户明确反馈,避免“复制成功却提示失败”。
2598
+ try {
2599
+ if (navigator.clipboard) {
2600
+ Promise.resolve(navigator.clipboard.writeText(text)).then(
2601
+ () => showToast(t("toast.copied")),
2602
+ () => showToast(t("toast.failed"))
2603
+ );
2604
+ return;
2605
+ }
2606
+ } catch {
2607
+ /* ignore */
2608
+ }
2609
+ showToast(t("toast.failed"));
2610
+ return;
2611
+ }
2612
+ editable.focus();
2613
+ try {
2614
+ const range = document.createRange();
2615
+ range.selectNodeContents(editable);
2616
+ range.collapse(false);
2617
+ const sel = window.getSelection();
2618
+ sel.removeAllRanges();
2619
+ sel.addRange(range);
2620
+ document.execCommand("insertText", false, text);
2621
+ } catch {
2622
+ try {
2623
+ document.execCommand("insertText", false, text);
2624
+ } catch {
2625
+ showToast(t("toast.failed"));
2626
+ }
2627
+ }
2628
+ }
2629
+
2630
+ // -------------------------------------------------------------------------
2631
+ // 问行按钮 DOM 注入
2632
+ // -------------------------------------------------------------------------
2633
+
2634
+ const BUTTON_DEFS = [
2635
+ { key: "recall", cfg: "recall", danger: false },
2636
+ { key: "share", cfg: "share", danger: false },
2637
+ { key: "export", cfg: "export", danger: false },
2638
+ { key: "delete", cfg: "delete", danger: true },
2639
+ { key: "deleteFrom", cfg: "deleteFrom", danger: true }
2640
+ ];
2641
+
2642
+ function injectQuestionButtons(ctx) {
2643
+ if (typeof document === "undefined") return;
2644
+ for (const clock of document.querySelectorAll('[data-clock="start"]')) {
2645
+ const sessionEl = clock.closest("[data-conversation-session]");
2646
+ if (!sessionEl) continue;
2647
+ const sessionId = sessionEl.getAttribute("data-conversation-session");
2648
+ const row = clock.closest("[data-chat-turn]");
2649
+ const turnText = row ? row.getAttribute("data-chat-turn") : null;
2650
+ const turn = turnText == null ? null : Number(turnText);
2651
+
2652
+ const controller = sessionFor(ctx, sessionId);
2653
+ const config = controller.config();
2654
+ const running = isRunning(sessionId);
2655
+ const lang = detectLang();
2656
+
2657
+ // 签名含语言:语言切换后按钮的 aria-label / title 需要重建。
2658
+ const signature = BUTTON_DEFS.map((def) =>
2659
+ config[def.cfg] === false ? "0" : "1"
2660
+ ).join("") + (running ? "R" : "I") + (lang === "zh" ? "Z" : "E");
2661
+
2662
+ const existing = clock.querySelector("[data-dma-actions]");
2663
+ if (existing && existing.getAttribute("data-dma-sig") === signature) continue;
2664
+ disposeActionsRow(existing);
2665
+
2666
+ const wrap = document.createElement("span");
2667
+ wrap.className = "dma-row-actions";
2668
+ wrap.setAttribute("data-dma-actions", "1");
2669
+ wrap.setAttribute("data-dma-sig", signature);
2670
+
2671
+ for (const def of BUTTON_DEFS) {
2672
+ if (config[def.cfg] === false) continue;
2673
+ const btn = document.createElement("button");
2674
+ btn.type = "button";
2675
+ btn.className = "dma-btn" + (def.danger ? " dma-danger" : "");
2676
+ btn.setAttribute("data-dma-action", def.key);
2677
+ btn.setAttribute("aria-label", t("btn." + def.key));
2678
+ btn.title = t("btn." + def.key);
2679
+ if (!paintButtonIcon(btn, def.key)) btn.innerHTML = ICONS[def.key] || "";
2680
+ if (running) btn.disabled = true;
2681
+ btn.addEventListener("click", (event) => {
2682
+ event.preventDefault();
2683
+ event.stopPropagation();
2684
+ handleQuestionAction(ctx, controller, def.key, turn);
2685
+ });
2686
+ wrap.appendChild(btn);
2687
+ }
2688
+
2689
+ clock.appendChild(wrap);
2690
+ }
2691
+ }
2692
+
2693
+ async function handleQuestionAction(ctx, controller, actionKey, turn) {
2694
+ if (actionKey === "share") {
2695
+ controller.openPick("share", turn);
2696
+ return;
2697
+ }
2698
+ if (actionKey === "export") {
2699
+ controller.openPick("export", turn);
2700
+ return;
2701
+ }
2702
+ if (turn == null) return;
2703
+ await controller.fetchMessages(true).catch(() => {});
2704
+ const rows = controller.messages && controller.messages.rows;
2705
+ const seq = controller.userSeqForTurn(rows, turn);
2706
+ if (seq == null) {
2707
+ showToast(t("toast.failed"));
2708
+ return;
2709
+ }
2710
+ controller.requestAction(actionKey, { seq, turn });
2711
+ }
2712
+
2713
+ // -------------------------------------------------------------------------
2714
+ // 工具行按钮 DOM 注入
2715
+ // -------------------------------------------------------------------------
2716
+
2717
+ /**
2718
+ * 工具行定位依据(宿主 `@deepseek-ai/dsh-client-ui-chat`):
2719
+ * - `data-chat-flow-kind="tool-call"`:toolDefinition 的 kind;
2720
+ * - `data-chat-node-key`:conversationContextKey("tool-call", id) = `9:tool-call<id>`;
2721
+ * - id 来自服务端 `tool/call.data.callId` / `tool/result.data.message.source.callId`。
2722
+ * 因此可以稳定映射到服务端 tool/result 的 seq,不依赖子节点序号或点击坐标。
2723
+ */
2724
+ function injectToolButtons(ctx) {
2725
+ if (typeof document === "undefined") return;
2726
+ const rows = document.querySelectorAll(
2727
+ "[data-chat-flow-kind='tool-call'][data-chat-node-key]"
2728
+ );
2729
+ for (const row of rows) {
2730
+ const nodeKey = row.getAttribute("data-chat-node-key");
2731
+ const callId = toolCallIdFromNodeKey(nodeKey);
2732
+ if (!callId) continue;
2733
+ const sessionEl = row.closest("[data-conversation-session]");
2734
+ const sessionId = sessionEl ? sessionEl.getAttribute("data-conversation-session") : null;
2735
+ if (!sessionId) continue;
2736
+ if (row.closest("[data-dma-hidden='1']") || row.hasAttribute("hidden")) continue;
2737
+
2738
+ const controller = sessionFor(ctx, sessionId);
2739
+ const config = controller.config();
2740
+ const existing = row.querySelector("[data-dma-tool-actions]");
2741
+ if (config.delete === false) {
2742
+ if (existing) disposeActionsRow(existing);
2743
+ continue;
2744
+ }
2745
+
2746
+ const running = isRunning(sessionId);
2747
+ const lang = detectLang();
2748
+ const signature = (running ? "R" : "I") + (lang === "zh" ? "Z" : "E");
2749
+ if (existing && existing.getAttribute("data-dma-sig") === signature) continue;
2750
+ if (existing) disposeActionsRow(existing);
2751
+
2752
+ const wrap = document.createElement("span");
2753
+ wrap.className = "dma-tool-actions";
2754
+ wrap.setAttribute("data-dma-tool-actions", "1");
2755
+ wrap.setAttribute("data-dma-sig", signature);
2756
+
2757
+ const btn = document.createElement("button");
2758
+ btn.type = "button";
2759
+ btn.className = "dma-btn dma-danger";
2760
+ btn.setAttribute("data-dma-action", "deleteTool");
2761
+ btn.setAttribute("aria-label", t("btn.deleteTool"));
2762
+ btn.title = t("btn.deleteTool");
2763
+ if (!paintButtonIcon(btn, "delete")) btn.innerHTML = ICONS.delete || "";
2764
+ if (running) btn.disabled = true;
2765
+ btn.addEventListener("click", (event) => {
2766
+ event.preventDefault();
2767
+ event.stopPropagation();
2768
+ handleToolAction(ctx, controller, nodeKey);
2769
+ });
2770
+ wrap.appendChild(btn);
2771
+ row.appendChild(wrap);
2772
+ }
2773
+ }
2774
+
2775
+ async function handleToolAction(ctx, controller, nodeKey) {
2776
+ const callId = toolCallIdFromNodeKey(nodeKey);
2777
+ if (!callId) {
2778
+ showToast(t("toast.failed"));
2779
+ return;
2780
+ }
2781
+ // 摘要快照必须含最新 tool/result 行,否则拿不到稳定的服务端 seq。
2782
+ await controller.fetchMessages(true).catch(() => {});
2783
+ const rows = controller.messages && controller.messages.rows;
2784
+ const row = findToolRowByCallId(rows, callId);
2785
+ if (!row) {
2786
+ showToast(t("toast.failed"));
2787
+ return;
2788
+ }
2789
+ controller.requestAction("delete", {
2790
+ seq: row.seq,
2791
+ turn: row.turn,
2792
+ step: row.step,
2793
+ target: "tool",
2794
+ nodeKey
2795
+ });
2796
+ }
2797
+
2798
+ // -------------------------------------------------------------------------
2799
+ // 导航刻度隐藏与压缩
2800
+ // -------------------------------------------------------------------------
2801
+
2802
+ function findRail(root) {
2803
+ if (!root) return null;
2804
+ if (root.tagName === "NAV" && root.querySelector("button[data-index]")) return root;
2805
+ const inner = root.querySelector("nav");
2806
+ return inner ? findRail(inner) : null;
2807
+ }
2808
+
2809
+ function railButtons(rail) {
2810
+ return rail ? [...rail.querySelectorAll("button[data-index]")] : [];
2811
+ }
2812
+
2813
+ /** 删除成功后立刻隐藏该轮的行(乐观更新),避免等宿主刷新才消失。 */
2814
+ function applyHiddenRows(sessionId, goneTurns) {
2815
+ const sessionEl = sessionElement(sessionId);
2816
+ if (!sessionEl || goneTurns.size === 0) return;
2817
+ for (const row of sessionEl.querySelectorAll("[data-chat-turn]")) {
2818
+ const turn = Number(row.getAttribute("data-chat-turn"));
2819
+ if (!goneTurns.has(turn) || row.getAttribute("data-dma-hidden") === "1") continue;
2820
+ // 只用自有属性隐藏(CSS display:none),不写官方 hidden 属性,
2821
+ // 避免反复写属性触发导航观察器自激。
2822
+ row.setAttribute("data-dma-hidden", "1");
2823
+ }
2824
+ }
2825
+
2826
+ /** 工具行删除成功后,只隐藏该工具节点(按宿主稳定的 data-chat-node-key)。 */
2827
+ function applyHiddenTool(sessionId, nodeKey) {
2828
+ const sessionEl = sessionElement(sessionId);
2829
+ if (!sessionEl || typeof nodeKey !== "string" || nodeKey === "") return;
2830
+ for (const row of sessionEl.querySelectorAll("[data-chat-flow-kind='tool-call'][data-chat-node-key]")) {
2831
+ if (row.getAttribute("data-chat-node-key") !== nodeKey) continue;
2832
+ row.setAttribute("data-dma-hidden", "1");
2833
+ }
2834
+ }
2835
+
2836
+ /**
2837
+ * 按「已删除工具行 callId」重新隐藏。
2838
+ * 删除成功当下隐藏一次是不够的:切换会话 / 刷新页面会让宿主重建 DOM,
2839
+ * 新节点不带 data-dma-hidden,于是被删内容又出现。这里每次同步都重放。
2840
+ */
2841
+ function applyHiddenTools(sessionId, callIds) {
2842
+ const sessionEl = sessionElement(sessionId);
2843
+ if (!sessionEl || !callIds || callIds.length === 0) return;
2844
+ const rows = [...sessionEl.querySelectorAll("[data-chat-flow-kind='tool-call'][data-chat-node-key]")];
2845
+ if (rows.length === 0) return;
2846
+ const keys = rows.map((row) => row.getAttribute("data-chat-node-key"));
2847
+ const hide = new Set(toolNodeKeysToHide(keys, callIds));
2848
+ if (hide.size === 0) return;
2849
+ for (let i = 0; i < rows.length; i += 1) {
2850
+ if (!hide.has(keys[i])) continue;
2851
+ if (rows[i].getAttribute("data-dma-hidden") === "1") continue;
2852
+ rows[i].setAttribute("data-dma-hidden", "1");
2853
+ }
2854
+ }
2855
+
2856
+ function visibleRowsExist(sessionId, turn) {
2857
+ const sessionEl = sessionElement(sessionId);
2858
+ if (!sessionEl) return false;
2859
+ for (const row of sessionEl.querySelectorAll('[data-chat-turn="' + turn + '"]')) {
2860
+ if (row.hasAttribute("data-dma-hidden") || row.hasAttribute("hidden")) continue;
2861
+ if (row.closest("[data-dma-hidden='1']") || row.closest("[hidden]")) continue;
2862
+ if (row.hasAttribute("data-chat-group-key")) continue;
2863
+ if (row.getAttribute("data-chat-flow-kind") === "turn-process") continue;
2864
+ if (row.textContent.trim() === "") continue;
2865
+ return true;
2866
+ }
2867
+ return false;
2868
+ }
2869
+
2870
+ let railSyncing = false;
2871
+
2872
+ function syncRail() {
2873
+ if (typeof document === "undefined" || railSyncing) return;
2874
+ railSyncing = true;
2875
+ try {
2876
+ for (const sessionNode of document.querySelectorAll("[data-conversation-session]")) {
2877
+ const sessionId = sessionNode.getAttribute("data-conversation-session");
2878
+
2879
+ const goneTurns = new Set();
2880
+ const goneTools = [];
2881
+ const controller = controllers.get(sessionId);
2882
+ if (controller) {
2883
+ for (const turn of controller.hiddenTurns) goneTurns.add(turn);
2884
+ const hostGone = controller.messages && controller.messages.goneTurns;
2885
+ if (Array.isArray(hostGone)) for (const turn of hostGone) goneTurns.add(turn);
2886
+ const hostGoneTools = controller.messages && controller.messages.goneTools;
2887
+ if (Array.isArray(hostGoneTools)) goneTools.push(...hostGoneTools);
2888
+ }
2889
+ applyHiddenRows(sessionId, goneTurns);
2890
+ applyHiddenTools(sessionId, goneTools);
2891
+
2892
+ const rail = findRail(sessionNode);
2893
+ if (!rail) continue;
2894
+
2895
+ const items = [];
2896
+ for (const btn of railButtons(rail)) {
2897
+ // data-index 语义未验证:与 aria-label 解析一致时才采用,否则回退旧逻辑。
2898
+ const turn = railTurnOfAttributes(
2899
+ btn.getAttribute("data-index"),
2900
+ btn.getAttribute("aria-label")
2901
+ );
2902
+ const gone = turn != null && goneTurns.has(turn);
2903
+ const hidden = gone && (!visibleRowsExist(sessionId, turn));
2904
+ items.push({ btn, hidden });
2905
+ }
2906
+
2907
+ applyRailCollapse(items);
2908
+ }
2909
+ } finally {
2910
+ railSyncing = false;
2911
+ }
2912
+ }
2913
+
2914
+ /**
2915
+ * 只在目标状态与 DOM 现状不同的时候写入。
2916
+ * 之前每次同步都无条件 setAttribute/style,而导航观察器监听 attributes,
2917
+ * 会形成「写入 → 观察 → 再写入」的微任务死循环,导致整个页面无响应。
2918
+ */
2919
+ function applyRailCollapse(items) {
2920
+ let hiddenBefore = 0;
2921
+ for (const item of items) {
2922
+ const btn = item.btn;
2923
+ const tooltip = btn.querySelector('[role="tooltip"]');
2924
+ if (item.hidden) {
2925
+ hiddenBefore += 1;
2926
+ if (btn.getAttribute("data-dma-rail") !== "1") btn.setAttribute("data-dma-rail", "1");
2927
+ if (btn.style.marginTop !== "") btn.style.marginTop = "";
2928
+ if (tooltip && tooltip.style.transform !== "") tooltip.style.transform = "";
2929
+ } else {
2930
+ if (btn.hasAttribute("data-dma-rail")) btn.removeAttribute("data-dma-rail");
2931
+ const offset = hiddenBefore * 10;
2932
+ const margin = offset === 0 ? "" : "-" + offset + "px";
2933
+ if (btn.style.marginTop !== margin) btn.style.marginTop = margin;
2934
+ const transform = offset === 0 ? "" : "translateY(-" + offset + "px)";
2935
+ if (tooltip && tooltip.style.transform !== transform) tooltip.style.transform = transform;
2936
+ }
2937
+ }
2938
+ }
2939
+
2940
+ // -------------------------------------------------------------------------
2941
+ // 分享 / 导出
2942
+ // -------------------------------------------------------------------------
2943
+
2944
+ function roundsOfData(data) {
2945
+ if (!data || !data.messages) return [];
2946
+ const hidden = new Set(data.hidden || []);
2947
+ return (data.messages.rounds || []).filter((r) => !hidden.has(r.turn));
2948
+ }
2949
+
2950
+ function downloadBlob(content, filename, type) {
2951
+ const blob = new Blob([content], { type });
2952
+ const url = URL.createObjectURL(blob);
2953
+ const a = document.createElement("a");
2954
+ a.href = url;
2955
+ a.download = filename;
2956
+ document.body.appendChild(a);
2957
+ a.click();
2958
+ a.remove();
2959
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
2960
+ }
2961
+
2962
+ function formatNow() {
2963
+ const d = new Date();
2964
+ const pad = (n) => String(n).padStart(2, "0");
2965
+ return (
2966
+ d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()) +
2967
+ " " + pad(d.getHours()) + ":" + pad(d.getMinutes())
2968
+ );
2969
+ }
2970
+
2971
+ /**
2972
+ * 摘要快照里的 round 只有预览;分享图 / 导出必须先按需拉全文。
2973
+ * 只请求用户实际选中的轮次(`full=1&turns=`),失败返回 null,绝不用预览生成产物。
2974
+ * @returns {Promise<Array<{ turn, question, answer }> | null>}
2975
+ */
2976
+ async function resolveFullRounds(controller, selected) {
2977
+ const turns = (selected || [])
2978
+ .map((round) => round && round.turn)
2979
+ .filter(Number.isSafeInteger);
2980
+ if (turns.length === 0) return [];
2981
+ const rounds = await controller.fetchRoundText(turns);
2982
+ if (!Array.isArray(rounds)) return null;
2983
+ const byTurn = new Map(rounds.map((round) => [round.turn, round]));
2984
+ // 保持用户在列表里的选择顺序,按轮次升序输出。
2985
+ return turns
2986
+ .map((turn) => byTurn.get(turn))
2987
+ .filter(Boolean)
2988
+ .sort((a, b) => a.turn - b.turn);
2989
+ }
2990
+
2991
+ async function doExport(controller, selected) {
2992
+ const full = await resolveFullRounds(controller, selected);
2993
+ if (full === null) {
2994
+ showToast(t("toast.failed"));
2995
+ return false;
2996
+ }
2997
+ const content = markdownOf(full, {
2998
+ title: t("export.title"),
2999
+ sessionId: controller.sessionId,
3000
+ exportedAt: formatNow(),
3001
+ questionLabel: t("pick.turn"),
3002
+ answerLabel: t("pick.answer")
3003
+ });
3004
+ if (!content.trim()) {
3005
+ showToast(t("toast.empty"));
3006
+ return false;
3007
+ }
3008
+ downloadBlob(content, exportFilename(controller.sessionId, new Date()), "text/markdown;charset=utf-8");
3009
+ return true;
3010
+ }
3011
+
3012
+ const SHARE_FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei','PingFang SC',sans-serif";
3013
+
3014
+ /** 把纯文本渲染成分享图可用的 HTML(保留代码围栏,折叠其余为 pre-wrap)。 */
3015
+ function shareTextHtml(text) {
3016
+ const parts = String(text == null ? "" : text).split(/```(?:[^\n]*)\n?([\s\S]*?)```/g);
3017
+ let out = "";
3018
+ for (let index = 0; index < parts.length; index += 1) {
3019
+ if (index % 2 === 0) {
3020
+ out += '<span style="white-space:pre-wrap;word-break:break-word">' + escapeHtml(parts[index]) + "</span>";
3021
+ } else {
3022
+ out += '<pre style="white-space:pre-wrap;word-break:break-word;margin:8px 0;padding:10px 12px;border-radius:8px;background:#f4f5f7;color:#24292f;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:13px;line-height:1.55">' + escapeHtml(parts[index]) + "</pre>";
3023
+ }
3024
+ }
3025
+ return out;
3026
+ }
3027
+
3028
+ /** 与旧版一致的浅色分享图:问行右对齐气泡,答行正文。 */
3029
+ function buildShareHtml(controller, selected) {
3030
+ const blocks = selected.map((round) => {
3031
+ const question = (round.question || "").trim();
3032
+ const answer = (round.answer || "").trim();
3033
+ let out = '<div style="margin:0 0 28px">';
3034
+ if (question) {
3035
+ out +=
3036
+ '<div style="display:flex;justify-content:flex-end">' +
3037
+ '<div style="max-width:76%;padding:10px 14px;border-radius:12px;background:#f1f3f6;color:#1a1a1a;font-size:14px;line-height:1.7">' +
3038
+ '<span style="display:inline-block;margin-right:8px;color:#8a8f98;font-size:11px">' +
3039
+ escapeHtml(t("pick.turn")) +
3040
+ "</span>" +
3041
+ shareTextHtml(question) +
3042
+ "</div></div>";
3043
+ }
3044
+ if (answer) {
3045
+ out +=
3046
+ '<div style="margin-top:12px;color:#2b2f36;font-size:14px;line-height:1.7">' +
3047
+ '<span style="display:inline-block;margin-right:8px;color:#8a8f98;font-size:11px">' +
3048
+ escapeHtml(t("pick.answer")) +
3049
+ "</span>" +
3050
+ shareTextHtml(answer) +
3051
+ "</div>";
3052
+ }
3053
+ return out + "</div>";
3054
+ }).join("");
3055
+ return (
3056
+ '<article xmlns="http://www.w3.org/1999/xhtml" style="box-sizing:border-box;width:720px;padding:46px 44px;background:#ffffff;color:#1a1a1a;font-family:' +
3057
+ SHARE_FONT +
3058
+ ";font-size:14px;line-height:1.7\">" +
3059
+ blocks +
3060
+ "</article>"
3061
+ );
3062
+ }
3063
+
3064
+ /**
3065
+ * 生成并下载分享图。
3066
+ * @returns {Promise<boolean>} true = 已成功触发下载;false = 失败(已提示)
3067
+ */
3068
+ async function generateSharePng(controller, selected) {
3069
+ const full = await resolveFullRounds(controller, selected);
3070
+ if (full === null) {
3071
+ showToast(t("toast.failed"));
3072
+ return false;
3073
+ }
3074
+ const html = buildShareHtml(controller, full);
3075
+ const holder = document.createElement("div");
3076
+ holder.style.cssText = "position:fixed;left:-10000px;top:0;width:0;height:0;overflow:hidden;pointer-events:none";
3077
+ holder.innerHTML = html;
3078
+ document.body.appendChild(holder);
3079
+ const height = Math.max(1, Math.ceil(holder.firstElementChild.getBoundingClientRect().height));
3080
+ holder.remove();
3081
+
3082
+ const MAX_HEIGHT = 12000;
3083
+ if (height > MAX_HEIGHT) {
3084
+ showToast(t("toast.tooMuch"));
3085
+ return false;
3086
+ }
3087
+
3088
+ const svg =
3089
+ '<svg xmlns="http://www.w3.org/2000/svg" width="720" height="' + height + '" viewBox="0 0 720 ' + height + '">' +
3090
+ '<foreignObject x="0" y="0" width="100%" height="100%">' + html + "</foreignObject></svg>";
3091
+ const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
3092
+ const img = new Image();
3093
+ // 成功路径原本在 img.onload 里异步完成;用 Promise 包起来,
3094
+ // 调用方才能据返回值决定是否关闭浮层(失败时保留已选轮次)。
3095
+ return new Promise((resolve) => {
3096
+ img.onload = () => {
3097
+ // 目标 2x;但按面积上限回落,避免长会话触发部分 WebView 的 canvas 面积限制。
3098
+ const MAX_CANVAS_PIXELS = 16 * 1000 * 1000;
3099
+ const scale = Math.max(1, Math.min(2, Math.sqrt(MAX_CANVAS_PIXELS / (720 * height))));
3100
+ const canvas = document.createElement("canvas");
3101
+ canvas.width = Math.ceil(720 * scale);
3102
+ canvas.height = Math.ceil(height * scale);
3103
+ const ctx = canvas.getContext("2d");
3104
+ if (!ctx) {
3105
+ showToast(t("toast.failed"));
3106
+ resolve(false);
3107
+ return;
3108
+ }
3109
+ ctx.fillStyle = "#ffffff";
3110
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
3111
+ ctx.scale(scale, scale);
3112
+ ctx.drawImage(img, 0, 0, 720, height);
3113
+ canvas.toBlob((png) => {
3114
+ if (!png) {
3115
+ showToast(t("toast.failed"));
3116
+ resolve(false);
3117
+ return;
3118
+ }
3119
+ const pngUrl = URL.createObjectURL(png);
3120
+ const a = document.createElement("a");
3121
+ a.href = pngUrl;
3122
+ a.download = exportFilename(controller.sessionId, new Date()).replace(/\.md$/, ".png");
3123
+ document.body.appendChild(a);
3124
+ a.click();
3125
+ a.remove();
3126
+ // 留足下载启动时间,避免慢磁盘/大图时提前释放。
3127
+ setTimeout(() => URL.revokeObjectURL(pngUrl), 10000);
3128
+ resolve(true);
3129
+ }, "image/png");
3130
+ };
3131
+ img.onerror = () => {
3132
+ showToast(t("toast.failed"));
3133
+ resolve(false);
3134
+ };
3135
+ img.src = url;
3136
+ });
3137
+ }
3138
+
3139
+ // -------------------------------------------------------------------------
3140
+ // React 组件
3141
+ // -------------------------------------------------------------------------
3142
+
3143
+ const e = React.createElement;
3144
+
3145
+ function Icon({ kind, size }) {
3146
+ const official = officialIconElement(kind, size || 13);
3147
+ if (official) return e("span", { className: "dma-ico" }, official);
3148
+ return e("span", {
3149
+ className: "dma-ico",
3150
+ dangerouslySetInnerHTML: { __html: ICONS[kind] || "" }
3151
+ });
3152
+ }
3153
+
3154
+ // 答行统计(assistant-actions 槽位)
3155
+ function AssistantActions({ messageId, t: tt, useData, form, refresh }) {
3156
+ const messages = useData((view) => view.messages);
3157
+ const snap = React.useSyncExternalStore(
3158
+ (listener) => (form && form.subscribe ? form.subscribe(listener) : () => {}),
3159
+ () => (form && form.getSnapshot ? form.getSnapshot() : null)
3160
+ );
3161
+ const config = snap && snap.status === "ready" && typeof snap.value === "object"
3162
+ ? snap.value
3163
+ : null;
3164
+ const rows = (messages && messages.rows) || [];
3165
+ const row = rows.find((item) => item.id === messageId && item.type === "assistant/message");
3166
+
3167
+ // 快照可能还没包含这条新回答:按 TTL 补拉一次,让统计随对话更新。
3168
+ React.useEffect(() => {
3169
+ if (!row && refresh) refresh();
3170
+ }, [row && row.id, refresh]);
3171
+
3172
+ let tokens = row && row.usage && Number.isFinite(row.usage.outputTokens)
3173
+ ? row.usage.outputTokens
3174
+ : null;
3175
+ // 与旧版对齐:中间步骤没有 usage 时,用同一轮最后一条带用量的回答兜底。
3176
+ if (tokens == null && row && Number.isSafeInteger(row.turn)) {
3177
+ const sameTurn = rows.filter((item) =>
3178
+ item.turn === row.turn &&
3179
+ item.type === "assistant/message" &&
3180
+ item.usage &&
3181
+ Number.isFinite(item.usage.outputTokens)
3182
+ );
3183
+ if (sameTurn.length > 0) tokens = sameTurn[sameTurn.length - 1].usage.outputTokens;
3184
+ }
3185
+ // 摘要快照只带 words,不带正文;字数由服务端一次算好,客户端不再重复统计。
3186
+ const words = row && Number.isFinite(row.words) ? row.words : 0;
3187
+
3188
+ if (config && config.stats === false) return null;
3189
+ if (!row || words === 0) return null;
3190
+
3191
+ const label = [
3192
+ tokens == null ? null : formatTokens(tokens) + " tok",
3193
+ words + " " + tt("stats.unit")
3194
+ ].filter(Boolean).join(" \u00b7 ");
3195
+
3196
+ return e("span", {
3197
+ className: "dma-stats",
3198
+ title: tt("stats.title", { tokens: tokens == null ? "?" : tokens, words })
3199
+ }, label);
3200
+ }
3201
+
3202
+ /**
3203
+ * 浮层键盘支持:仅在浮层打开期间挂监听,关闭 / 卸载时由 effect 清理。
3204
+ * 捕获阶段处理并阻止冒泡:确认框是模态的,同一个 Enter 不应再触发宿主的
3205
+ * 其它快捷键;焦点在输入框时不拦截(交给控件自己处理)。
3206
+ */
3207
+ function useOverlayKeys(options) {
3208
+ const { active, primaryEnabled, busy, onDismiss, onPrimary } = options;
3209
+ const handlers = React.useRef({ onDismiss, onPrimary });
3210
+ handlers.current = { onDismiss, onPrimary };
3211
+ React.useEffect(() => {
3212
+ if (!active) return undefined;
3213
+ function onKey(event) {
3214
+ const action = resolveKeyAction({
3215
+ key: event.key,
3216
+ target: event.target,
3217
+ overlayOpen: true,
3218
+ primaryEnabled,
3219
+ busy
3220
+ });
3221
+ if (action === "none") return;
3222
+ event.preventDefault();
3223
+ event.stopPropagation();
3224
+ if (action === "dismiss") handlers.current.onDismiss();
3225
+ else if (action === "primary") handlers.current.onPrimary();
3226
+ }
3227
+ window.addEventListener("keydown", onKey, true);
3228
+ return () => window.removeEventListener("keydown", onKey, true);
3229
+ }, [active, primaryEnabled, busy]);
3230
+ }
3231
+
3232
+ // 确认弹窗(Enter = 确认,Esc = 取消)
3233
+ function ConfirmOverlay({ t: tt, view, onDismiss, confirmAction }) {
3234
+ const firing = React.useRef(false);
3235
+ // 工具行删除与答行 step 删除共用服务端 step 分支,但文案必须能区分入口。
3236
+ const message = view.target === "tool"
3237
+ ? tt("confirm.tool")
3238
+ : (view.step ? tt("confirm.step") : tt("confirm." + String(view.action)));
3239
+ const danger = view.action !== "recall";
3240
+ function primary() {
3241
+ // 与点击「确认」完全同一个处理函数,避免键盘与鼠标行为分叉。
3242
+ if (firing.current) return;
3243
+ firing.current = true;
3244
+ confirmAction(view.action, {
3245
+ seq: view.seq,
3246
+ messageId: view.messageId,
3247
+ nodeKey: view.nodeKey,
3248
+ target: view.target
3249
+ });
3250
+ }
3251
+ useOverlayKeys({ active: true, primaryEnabled: true, busy: false, onDismiss, onPrimary: primary });
3252
+ return e("div", {
3253
+ className: "dma-overlay",
3254
+ onClick: (ev) => {
3255
+ if (ev.target === ev.currentTarget) onDismiss();
3256
+ }
3257
+ },
3258
+ e("div", { className: "dma-panel dma-confirm" },
3259
+ e("div", { className: "dma-panel-head" }, tt("confirm.title")),
3260
+ e("div", { className: "dma-panel-body" }, message),
3261
+ e("div", { className: "dma-panel-foot" },
3262
+ e("button", { type: "button", className: "dma-btn", onClick: () => onDismiss() }, tt("confirm.cancel")),
3263
+ e("button", {
3264
+ type: "button",
3265
+ autoFocus: true,
3266
+ className: "dma-btn dma-primary" + (danger ? " dma-danger" : ""),
3267
+ onClick: primary
3268
+ }, tt("confirm.ok"))
3269
+ )
3270
+ ));
3271
+ }
3272
+
3273
+ // 确认弹窗 + 分享/导出浮层控制器(input.overlay 槽位)
3274
+ function OverlayController(props) {
3275
+ const { t: tt, useOverlay, useData, confirmAction, dismiss, runShare, runExport } = props;
3276
+ const view = useOverlay((v) => v.view);
3277
+ const data = useData((v) => v);
3278
+
3279
+ if (!view) return null;
3280
+
3281
+ if (view.kind === "confirm") {
3282
+ return e(ConfirmOverlay, {
3283
+ t: tt,
3284
+ view,
3285
+ onDismiss: dismiss,
3286
+ confirmAction
3287
+ });
3288
+ }
3289
+
3290
+ if (view.kind === "pick") {
3291
+ return e(PickOverlay, {
3292
+ t: tt,
3293
+ mode: view.mode,
3294
+ seedTurn: view.turn,
3295
+ rounds: roundsOfData(data),
3296
+ onDismiss: () => dismiss(),
3297
+ runShare,
3298
+ runExport
3299
+ });
3300
+ }
3301
+
3302
+ return null;
3303
+ }
3304
+
3305
+ // 分享/导出多选列表
3306
+ function PickOverlay({ t, mode, seedTurn, rounds, onDismiss, runShare, runExport }) {
3307
+ // 与旧版一致:默认选中触发按钮所在的那一轮;没有轮次信息时选第一轮。
3308
+ const [selected, setSelected] = React.useState(() => {
3309
+ if (Number.isSafeInteger(seedTurn) && rounds.some((r) => r.turn === seedTurn)) {
3310
+ return new Set([seedTurn]);
3311
+ }
3312
+ return rounds.length > 0 ? new Set([rounds[0].turn]) : new Set();
3313
+ });
3314
+ const all = rounds.length > 0 && selected.size === rounds.length;
3315
+
3316
+ function toggle(turn) {
3317
+ setSelected((prev) => {
3318
+ const next = new Set(prev);
3319
+ if (next.has(turn)) next.delete(turn);
3320
+ else next.add(turn);
3321
+ return next;
3322
+ });
3323
+ }
3324
+
3325
+ function selectAll() {
3326
+ setSelected(new Set(rounds.map((r) => r.turn)));
3327
+ }
3328
+
3329
+ const chosen = rounds.filter((r) => selected.has(r.turn));
3330
+ const primaryLabel = mode === "share" ? t("pick.share") : t("pick.export");
3331
+ const primaryDisabled = chosen.length === 0;
3332
+ const [busy, setBusy] = React.useState(false);
3333
+
3334
+ function primary() {
3335
+ // 与点击主按钮同一个处理函数;busy 期间忽略重复 Enter,避免重复生成 / 重复下载。
3336
+ if (primaryDisabled || busy) return;
3337
+ setBusy(true);
3338
+ const task = mode === "share" ? runShare(chosen) : runExport(chosen);
3339
+ Promise.resolve(task)
3340
+ .then((done) => {
3341
+ if (done) {
3342
+ onDismiss();
3343
+ return;
3344
+ }
3345
+ // 失败:保留浮层与已选轮次,复位 busy 以便重试;提示由生成函数给出。
3346
+ setBusy(false);
3347
+ })
3348
+ .catch(() => {
3349
+ showToast(t("toast.failed"));
3350
+ setBusy(false);
3351
+ });
3352
+ }
3353
+
3354
+ useOverlayKeys({
3355
+ active: true,
3356
+ primaryEnabled: !primaryDisabled,
3357
+ busy,
3358
+ onDismiss,
3359
+ onPrimary: primary
3360
+ });
3361
+
3362
+ return e("div", { className: "dma-overlay", onClick: (ev) => { if (ev.target === ev.currentTarget) onDismiss(); } },
3363
+ e("div", { className: "dma-panel" },
3364
+ e("div", { className: "dma-panel-head" },
3365
+ mode === "share" ? t("pick.title.share") : t("pick.title.export")),
3366
+ e("div", { className: "dma-panel-body" },
3367
+ rounds.length === 0
3368
+ ? e("p", { className: "dma-empty" }, t("toast.empty"))
3369
+ : rounds.map((round) =>
3370
+ e("div", { className: "dma-round", key: round.turn },
3371
+ e("button", {
3372
+ type: "button",
3373
+ className: "dma-round-box",
3374
+ role: "checkbox",
3375
+ "aria-checked": selected.has(round.turn),
3376
+ onClick: () => toggle(round.turn)
3377
+ }, selected.has(round.turn) ? e(Icon, { kind: "check" }) : null),
3378
+ e("div", { className: "dma-round-main" },
3379
+ e("div", { className: "dma-round-line dma-round-q" },
3380
+ e("span", { className: "dma-round-tag" }, t("pick.turn") + " " + round.turn),
3381
+ e("span", { className: "dma-round-text" },
3382
+ round.questionPreview || "…")),
3383
+ e("div", { className: "dma-round-line dma-round-a" },
3384
+ e("span", { className: "dma-round-tag dma-round-tag-a" }, t("pick.answer")),
3385
+ e("span", { className: "dma-round-text" },
3386
+ round.answerPreview || "…"))
3387
+ )
3388
+ )
3389
+ )
3390
+ ),
3391
+ e("div", { className: "dma-panel-foot" },
3392
+ e("button", { type: "button", className: "dma-btn", onClick: selectAll }, t("pick.all")),
3393
+ e("div", {},
3394
+ e("button", { type: "button", className: "dma-btn", onClick: () => onDismiss() }, t("pick.cancel")),
3395
+ e("button", {
3396
+ type: "button",
3397
+ autoFocus: true,
3398
+ className: "dma-btn dma-primary",
3399
+ disabled: primaryDisabled || busy,
3400
+ onClick: primary
3401
+ }, primaryLabel)
3402
+ )
3403
+ )
3404
+ )
3405
+ );
3406
+ }
3407
+
3408
+ // 设置页(settings.section 槽位)
3409
+ const SETTING_FIELDS = [
3410
+ ["recall", "settings.recall", "settings.recallDesc"],
3411
+ ["share", "settings.share", "settings.shareDesc"],
3412
+ ["export", "settings.export", "settings.exportDesc"],
3413
+ ["delete", "settings.delete", "settings.deleteDesc"],
3414
+ ["deleteFrom", "settings.deleteFrom", "settings.deleteFromDesc"],
3415
+ ["confirm", "settings.confirm", "settings.confirmDesc"],
3416
+ ["stats", "settings.stats", "settings.statsDesc"]
3417
+ ];
3418
+
3419
+ function SettingRow({ t: tt, labelKey, descKey, on, disabled, onToggle }) {
3420
+ return e("div", { className: "dma-setting-row" },
3421
+ e("div", { className: "dma-setting-text" },
3422
+ e("div", { className: "dma-setting-label" }, tt(labelKey)),
3423
+ e("div", { className: "dma-setting-desc" }, tt(descKey))
3424
+ ),
3425
+ e("button", {
3426
+ type: "button",
3427
+ role: "switch",
3428
+ className: "dma-switch",
3429
+ "aria-checked": on ? "true" : "false",
3430
+ "aria-label": tt(labelKey),
3431
+ disabled: !!disabled,
3432
+ onClick: onToggle
3433
+ }, e("span", { className: "dma-switch-thumb" }))
3434
+ );
3435
+ }
3436
+
3437
+ function NumberRow({ t: tt, labelKey, descKey, value, disabled, onCommit }) {
3438
+ const fallback = Number.isFinite(value) ? Math.round(value) : 0;
3439
+ const [text, setText] = React.useState(String(fallback));
3440
+ React.useEffect(() => {
3441
+ setText(String(fallback));
3442
+ }, [fallback]);
3443
+ const commit = () => {
3444
+ const raw = String(text).trim();
3445
+ if (raw === "") {
3446
+ setText("0");
3447
+ onCommit(0);
3448
+ return;
3449
+ }
3450
+ const num = Number(raw);
3451
+ if (!Number.isFinite(num)) {
3452
+ setText(String(fallback));
3453
+ return;
3454
+ }
3455
+ const clamped = Math.min(600, Math.max(0, Math.round(num)));
3456
+ setText(String(clamped));
3457
+ if (clamped !== fallback) onCommit(clamped);
3458
+ };
3459
+ return e("div", { className: "dma-setting-row" },
3460
+ e("div", { className: "dma-setting-text" },
3461
+ e("div", { className: "dma-setting-label" }, tt(labelKey)),
3462
+ e("div", { className: "dma-setting-desc" }, tt(descKey))
3463
+ ),
3464
+ e("input", {
3465
+ type: "number",
3466
+ className: "dma-number",
3467
+ min: 0,
3468
+ max: 600,
3469
+ step: 1,
3470
+ value: text,
3471
+ disabled: !!disabled,
3472
+ "aria-label": tt(labelKey),
3473
+ onChange: (ev) => setText(ev.target.value),
3474
+ onBlur: commit,
3475
+ onKeyDown: (ev) => {
3476
+ if (ev.key === "Enter") ev.currentTarget.blur();
3477
+ }
3478
+ })
3479
+ );
3480
+ }
3481
+
3482
+ function LayoutRow({ t: tt, value, disabled, onPick }) {
3483
+ const current = normalizeCostLayout(value);
3484
+ return e("div", { className: "dma-setting-row" },
3485
+ e("div", { className: "dma-setting-text" },
3486
+ e("div", { className: "dma-setting-label" }, tt("cost.settings.layout")),
3487
+ e("div", { className: "dma-setting-desc" }, tt("cost.settings.layoutDesc"))
3488
+ ),
3489
+ e("div", { className: "dma-seg", role: "group", "aria-label": tt("cost.settings.layout") },
3490
+ COST_LAYOUTS.map((id) => e("button", {
3491
+ key: id,
3492
+ type: "button",
3493
+ className: "dma-seg-btn",
3494
+ "aria-pressed": current === id ? "true" : "false",
3495
+ disabled,
3496
+ onClick: () => onPick(id)
3497
+ }, tt("cost.layout." + id)))
3498
+ )
3499
+ );
3500
+ }
3501
+
3502
+ function BillingTab({ t: tt, form, value, save }) {
3503
+ const enabled = value ? value.usageStats !== false : true;
3504
+ const onToggle = (key, on) => () => save(key, !on);
3505
+ return e("div", { className: "dma-billing" },
3506
+ e(SettingRow, {
3507
+ t: tt,
3508
+ labelKey: "cost.settings.usageStats",
3509
+ descKey: "cost.settings.usageStatsDesc",
3510
+ on: enabled,
3511
+ onToggle: onToggle("usageStats", enabled)
3512
+ }),
3513
+ e(LayoutRow, {
3514
+ t: tt,
3515
+ value: value && typeof value.costLayout === "string" ? value.costLayout : DEFAULT_COST_LAYOUT,
3516
+ disabled: !enabled,
3517
+ onPick: (id) => save("costLayout", id)
3518
+ }),
3519
+ e(SettingRow, {
3520
+ t: tt,
3521
+ labelKey: "cost.settings.perTurn",
3522
+ descKey: "cost.settings.perTurnDesc",
3523
+ on: value ? value.costPerTurn !== false : true,
3524
+ disabled: !enabled,
3525
+ onToggle: enabled ? onToggle("costPerTurn", value ? value.costPerTurn !== false : true) : null
3526
+ }),
3527
+ e(NumberRow, {
3528
+ t: tt,
3529
+ labelKey: "cost.settings.autoClose",
3530
+ descKey: "cost.settings.autoCloseDesc",
3531
+ value: value && Number.isFinite(value.costPerTurnAutoClose) ? value.costPerTurnAutoClose : 0,
3532
+ disabled: !enabled,
3533
+ onCommit: (seconds) => save("costPerTurnAutoClose", seconds)
3534
+ }),
3535
+ e(SettingRow, {
3536
+ t: tt,
3537
+ labelKey: "cost.settings.peakValley",
3538
+ descKey: "cost.settings.peakValleyDesc",
3539
+ on: value ? value.costPeakValley !== false : true,
3540
+ disabled: !enabled,
3541
+ onToggle: enabled ? onToggle("costPeakValley", value ? value.costPeakValley !== false : true) : null
3542
+ }),
3543
+ e(CorrectionForm, { t: tt })
3544
+ );
3545
+ }
3546
+
3547
+ function centsToInput(cents) {
3548
+ return Number.isFinite(cents) ? formatCents(cents) : "0.00";
3549
+ }
3550
+
3551
+ function CorrectionForm({ t: tt }) {
3552
+ const snap = React.useSyncExternalStore(
3553
+ costStore.subscribe,
3554
+ costStore.getSnapshot,
3555
+ costStore.getSnapshot
3556
+ );
3557
+ const value = snap && snap.status === "ready" ? snap.value : null;
3558
+ const [credit, setCredit] = React.useState("0.00");
3559
+ const [debit, setDebit] = React.useState("0.00");
3560
+ const [busy, setBusy] = React.useState(false);
3561
+ const [error, setError] = React.useState("");
3562
+ const initialized = React.useRef(false);
3563
+
3564
+ React.useEffect(() => {
3565
+ if (!value || initialized.current) return;
3566
+ initialized.current = true;
3567
+ setCredit(centsToInput(value.account.creditCents));
3568
+ setDebit(centsToInput(value.account.debitCents));
3569
+ }, [value]);
3570
+
3571
+ const creditCheck = validateCorrectionAmount(credit === "" ? 0 : credit);
3572
+ const debitCheck = validateCorrectionAmount(debit === "" ? 0 : debit);
3573
+ const invalid = !creditCheck.ok || !debitCheck.ok;
3574
+
3575
+ const account = value ? value.account : null;
3576
+ const baseline = account && Number.isFinite(account.baselineCents) ? account.baselineCents : null;
3577
+ const observed = account && Number.isFinite(account.observedSpendCents) ? account.observedSpendCents : 0;
3578
+ const previewCents = baseline === null
3579
+ ? null
3580
+ : baseline - observed + (creditCheck.ok ? creditCheck.cents : 0) - (debitCheck.ok ? debitCheck.cents : 0);
3581
+
3582
+ async function submit() {
3583
+ if (invalid || busy) return;
3584
+ setBusy(true);
3585
+ setError("");
3586
+ let res;
3587
+ try {
3588
+ res = await postJson("/dsh-message-actions/cost/correction", {
3589
+ creditYuan: credit,
3590
+ debitYuan: debit
3591
+ });
3592
+ } catch {
3593
+ // 网络中断 / 宿主超时:给出可理解的反馈,不留未捕获 rejection。
3594
+ setError(tt("cost.correction.failed"));
3595
+ setBusy(false);
3596
+ return;
3597
+ }
3598
+ if (res.status === 200 && res.data && res.data.ok && res.data.value) {
3599
+ patchCostState({ status: "ready", value: res.data.value, fetchedAt: Date.now(), error: "" });
3600
+ setCredit(centsToInput(res.data.value.account.creditCents));
3601
+ setDebit(centsToInput(res.data.value.account.debitCents));
3602
+ } else {
3603
+ const code = res.data && res.data.error ? res.data.error.code : undefined;
3604
+ setError(tt(code === "INVALID_AMOUNT" ? "cost.correction.invalid" : "cost.correction.failed"));
3605
+ }
3606
+ setBusy(false);
3607
+ }
3608
+
3609
+ return e("div", { className: "dma-correction" },
3610
+ e("div", { className: "dma-correction-title" }, tt("cost.correction.title")),
3611
+ e("div", { className: "dma-correction-row" },
3612
+ e("label", { className: "dma-correction-label" }, tt("cost.correction.credit")),
3613
+ e("span", { className: "dma-correction-input" },
3614
+ e("span", { className: "dma-correction-yuan" }, tt("cost.correction.yuan")),
3615
+ e("input", {
3616
+ type: "text",
3617
+ inputMode: "decimal",
3618
+ value: credit,
3619
+ disabled: busy,
3620
+ "aria-invalid": invalid ? "true" : "false",
3621
+ onChange: (ev) => setCredit(ev.target.value)
3622
+ })
3623
+ )
3624
+ ),
3625
+ e("div", { className: "dma-correction-row" },
3626
+ e("label", { className: "dma-correction-label" }, tt("cost.correction.debit")),
3627
+ e("span", { className: "dma-correction-input" },
3628
+ e("span", { className: "dma-correction-yuan" }, tt("cost.correction.yuan")),
3629
+ e("input", {
3630
+ type: "text",
3631
+ inputMode: "decimal",
3632
+ value: debit,
3633
+ disabled: busy,
3634
+ "aria-invalid": invalid ? "true" : "false",
3635
+ onChange: (ev) => setDebit(ev.target.value)
3636
+ })
3637
+ )
3638
+ ),
3639
+ e("div", { className: "dma-correction-row dma-correction-preview" },
3640
+ e("label", { className: "dma-correction-label" }, tt("cost.correction.preview")),
3641
+ e("span", {
3642
+ className: "dma-correction-value" + (previewCents !== null && previewCents < 0 ? " dma-correction-negative" : "")
3643
+ }, previewCents === null ? "—" : formatYuanCents(previewCents))
3644
+ ),
3645
+ e("div", { className: "dma-correction-row" },
3646
+ e("label", { className: "dma-correction-label" }, tt("cost.correction.pending")),
3647
+ e("span", { className: "dma-correction-value" },
3648
+ formatYuanCents(value && Number.isFinite(value.pendingAdjustmentCents) ? value.pendingAdjustmentCents : 0))
3649
+ ),
3650
+ invalid ? e("div", { className: "dma-setting-error" }, tt("cost.correction.invalid")) : null,
3651
+ previewCents !== null && previewCents < 0
3652
+ ? e("div", { className: "dma-correction-warn" }, tt("cost.correction.negative"))
3653
+ : null,
3654
+ error ? e("div", { className: "dma-setting-error" }, error) : null,
3655
+ e("p", { className: "dma-cost-note" }, tt("cost.note")),
3656
+ e("div", { className: "dma-correction-actions" },
3657
+ e("button", {
3658
+ type: "button",
3659
+ className: "dma-correction-save",
3660
+ disabled: invalid || busy,
3661
+ onClick: submit
3662
+ }, tt(busy ? "cost.correction.saving" : "cost.correction.save"))
3663
+ )
3664
+ );
3665
+ }
3666
+
3667
+ let settingsTab = "actions";
3668
+
3669
+ function SettingsSection({ t: tt, form }) {
3670
+ const snap = React.useSyncExternalStore(
3671
+ (listener) => (form && form.subscribe ? form.subscribe(listener) : () => {}),
3672
+ () => (form && form.getSnapshot ? form.getSnapshot() : { status: "loading" })
3673
+ );
3674
+ const [tab, setTab] = React.useState(settingsTab);
3675
+ const [error, setError] = React.useState("");
3676
+ const billingFetched = React.useRef(false);
3677
+ const value = snap && snap.status === "ready" && typeof snap.value === "object"
3678
+ ? snap.value
3679
+ : null;
3680
+
3681
+ React.useEffect(() => {
3682
+ if (tab !== "billing" || billingFetched.current) return;
3683
+ billingFetched.current = true;
3684
+ fetchCostState(false).catch(() => {});
3685
+ }, [tab]);
3686
+
3687
+ function save(key, next) {
3688
+ if (!form || !form.set) return;
3689
+ try {
3690
+ const result = form.set(key, next);
3691
+ if (result && typeof result.then === "function") {
3692
+ result.then((ok) => setError(ok === false ? tt("settings.saveFailed") : ""),
3693
+ () => setError(tt("settings.saveFailed")));
3694
+ } else if (result === false) {
3695
+ setError(tt("settings.saveFailed"));
3696
+ } else {
3697
+ setError("");
3698
+ }
3699
+ } catch {
3700
+ setError(tt("settings.saveFailed"));
3701
+ }
3702
+ }
3703
+
3704
+ function switchTab(next) {
3705
+ settingsTab = next;
3706
+ setTab(next);
3707
+ }
3708
+
3709
+ const tabButton = (id, labelKey) => e("button", {
3710
+ type: "button",
3711
+ role: "tab",
3712
+ "aria-selected": tab === id ? "true" : "false",
3713
+ className: "dma-tab" + (tab === id ? " dma-tab-active" : ""),
3714
+ onClick: () => switchTab(id)
3715
+ }, tt(labelKey));
3716
+
3717
+ return e("div", { className: "dma-settings" },
3718
+ e("div", { className: "dma-tabs", role: "tablist" },
3719
+ tabButton("actions", "cost.tab.actions"),
3720
+ tabButton("billing", "cost.tab.billing")
3721
+ ),
3722
+ tab === "actions"
3723
+ ? e("div", { className: "dma-settings-panel" },
3724
+ SETTING_FIELDS.map(([key, labelKey, descKey]) => {
3725
+ const on = value ? value[key] === true : false;
3726
+ return e(SettingRow, {
3727
+ key,
3728
+ t: tt,
3729
+ labelKey,
3730
+ descKey,
3731
+ on,
3732
+ onToggle: () => save(key, !on)
3733
+ });
3734
+ }),
3735
+ // 第一个标签页底部:只读版本号,不抢设置项视觉焦点。
3736
+ e("div", { className: "dma-settings-version" }, "v" + VERSION)
3737
+ )
3738
+ : e(BillingTab, { t: tt, form, value, save }),
3739
+ error ? e("div", { className: "dma-setting-error" }, error) : null
3740
+ );
3741
+ }
3742
+
3743
+ // -------------------------------------------------------------------------
3744
+ // 侧边栏费用卡片
3745
+ // -------------------------------------------------------------------------
3746
+
3747
+ const COIN_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="7.5"/><path d="M9.5 12h5M12 9.5v5"/></svg>';
3748
+ const PEAK_SVG = '<svg viewBox="0 0 12 12" aria-hidden="true"><circle cx="6" cy="6" r="5.6" fill="#f97316"/><path d="M6 3.1 8.9 7.3H3.1z" fill="#fff"/></svg>';
3749
+ const VALLEY_SVG = '<svg viewBox="0 0 12 12" aria-hidden="true"><circle cx="6" cy="6" r="5.6" fill="#3b82f6"/><path d="M6 8.9 3.1 4.7h5.8z" fill="#fff"/></svg>';
3750
+ const LOCAL_SVG = '<svg viewBox="0 0 12 12" aria-hidden="true"><circle cx="6" cy="6" r="5.6" fill="#9aa3af"/><circle cx="6" cy="6" r="2.2" fill="#fff"/></svg>';
3751
+
3752
+ function useRollingNumber(value) {
3753
+ const [shown, setShown] = React.useState(value);
3754
+ const fromRef = React.useRef(value);
3755
+ React.useEffect(() => {
3756
+ const from = fromRef.current;
3757
+ fromRef.current = value;
3758
+ if (!Number.isFinite(from) || !Number.isFinite(value) || from === value
3759
+ || typeof requestAnimationFrame !== "function") {
3760
+ setShown(value);
3761
+ return undefined;
3762
+ }
3763
+ const clock = () => (typeof performance !== "undefined" && performance.now ? performance.now() : Date.now());
3764
+ const startedAt = clock();
3765
+ let raf = 0;
3766
+ const step = () => {
3767
+ const p = Math.min(1, (clock() - startedAt) / 350);
3768
+ setShown(from + (value - from) * easeOutCubic(p));
3769
+ if (p < 1) raf = requestAnimationFrame(step);
3770
+ };
3771
+ raf = requestAnimationFrame(step);
3772
+ return () => cancelAnimationFrame(raf);
3773
+ }, [value]);
3774
+ return shown;
3775
+ }
3776
+
3777
+ function CostCard({ t: tt, wide, form }) {
3778
+ const costSnap = React.useSyncExternalStore(
3779
+ costStore.subscribe,
3780
+ costStore.getSnapshot,
3781
+ costStore.getSnapshot
3782
+ );
3783
+ const formSnap = React.useSyncExternalStore(
3784
+ (listener) => (form && form.subscribe ? form.subscribe(listener) : () => {}),
3785
+ () => (form && form.getSnapshot ? form.getSnapshot() : { status: "loading" }),
3786
+ () => ({ status: "loading" })
3787
+ );
3788
+ const cfg = formSnap && formSnap.status === "ready" && typeof formSnap.value === "object"
3789
+ ? formSnap.value
3790
+ : {};
3791
+ const enabled = cfg.usageStats !== false;
3792
+ const showPeak = cfg.costPeakValley !== false;
3793
+ const showTurn = cfg.costPerTurn !== false;
3794
+ const compact = normalizeCostLayout(cfg.costLayout) === "compact";
3795
+
3796
+ const value = costSnap && costSnap.status === "ready" ? costSnap.value : null;
3797
+ const balance = value ? value.balance : null;
3798
+ const status = value ? value.status : "stale";
3799
+ const lastTurn = value && value.lastTurn ? value.lastTurn : null;
3800
+
3801
+ const balanceCents = balance && balance.updatedAt > 0 && Number.isFinite(balance.totalCents)
3802
+ ? balance.totalCents
3803
+ : null;
3804
+ const dailyCents = balanceCents !== null && value && Number.isFinite(value.dailyCents)
3805
+ ? value.dailyCents
3806
+ : null;
3807
+ const turnMicros = showTurn && lastTurn && Number.isFinite(lastTurn.costMicros)
3808
+ ? lastTurn.costMicros
3809
+ : null;
3810
+
3811
+ const [manualBusy, setManualBusy] = React.useState(false);
3812
+ const [closedAt, setClosedAt] = React.useState(null);
3813
+ const seenRef = React.useRef({ at: null, firstAt: 0 });
3814
+
3815
+ const balanceShown = useRollingNumber(balanceCents);
3816
+ const dailyShown = useRollingNumber(dailyCents);
3817
+ const turnShown = useRollingNumber(turnMicros);
3818
+
3819
+ const turnAt = lastTurn ? lastTurn.at : null;
3820
+ React.useEffect(() => {
3821
+ setClosedAt(null);
3822
+ }, [turnAt]);
3823
+ React.useEffect(() => {
3824
+ if (turnAt === null) return undefined;
3825
+ if (seenRef.current.at !== turnAt || seenRef.current.closeSeconds !== cfg.costPerTurnAutoClose) {
3826
+ seenRef.current.at = turnAt;
3827
+ seenRef.current.closeSeconds = cfg.costPerTurnAutoClose;
3828
+ seenRef.current.firstAt = Date.now();
3829
+ }
3830
+ const closeAt = autoCloseAt(seenRef.current.firstAt, cfg.costPerTurnAutoClose);
3831
+ if (closeAt === null) return undefined;
3832
+ const delay = Math.max(0, closeAt - Date.now());
3833
+ const timer = setTimeout(() => setClosedAt(turnAt), delay);
3834
+ return () => clearTimeout(timer);
3835
+ }, [turnAt, cfg.costPerTurnAutoClose]);
3836
+
3837
+ if (!enabled) return null;
3838
+
3839
+ async function refresh() {
3840
+ setManualBusy(true);
3841
+ await fetchCostState(true);
3842
+ setManualBusy(false);
3843
+ }
3844
+
3845
+ const refreshing = manualBusy || (balance && balance.refreshing === true);
3846
+ const turnHidden = lastTurn !== null && closedAt === turnAt;
3847
+
3848
+ if (!wide) {
3849
+ const title = balanceCents !== null
3850
+ ? tt("cost.railTitle", { balance: formatYuanCents(balanceCents) })
3851
+ : tt("cost.balance");
3852
+ return e("div", { className: "dma-cost-item" },
3853
+ e("button", {
3854
+ type: "button",
3855
+ className: "dma-cost-rail" + (refreshing ? " dma-cost-busy" : ""),
3856
+ title,
3857
+ "aria-label": tt("cost.refresh"),
3858
+ onClick: refresh
3859
+ }, e("span", { className: "dma-ico", dangerouslySetInnerHTML: { __html: COIN_SVG } }))
3860
+ );
3861
+ }
3862
+
3863
+ if (status === "local") {
3864
+ return e("div", { className: "dma-cost-item" },
3865
+ e("div", {
3866
+ className: "dma-cost-card dma-cost-local" + (compact ? " dma-cost-plain" : ""),
3867
+ "aria-label": tt("cost.local")
3868
+ },
3869
+ e("span", {
3870
+ className: "dma-cost-period-icon",
3871
+ "aria-hidden": "true",
3872
+ dangerouslySetInnerHTML: { __html: LOCAL_SVG }
3873
+ }),
3874
+ e("span", { className: "dma-cost-local-text" }, tt("cost.local"))
3875
+ )
3876
+ );
3877
+ }
3878
+
3879
+ let balanceText = "—";
3880
+ if (status === "signed-out") balanceText = tt("cost.signedOut");
3881
+ else if (status === "api-key") balanceText = tt("cost.apiKey");
3882
+ else if (status === "unavailable") balanceText = tt("cost.unavailable");
3883
+ else if (Number.isFinite(balanceShown)) balanceText = formatYuanCents(Math.round(balanceShown));
3884
+
3885
+ const dailyText = Number.isFinite(dailyShown) && status !== "signed-out" && status !== "api-key" && status !== "unavailable"
3886
+ ? formatYuanCents(Math.round(dailyShown))
3887
+ : "—";
3888
+ const amountsHidden = status === "signed-out" || status === "api-key" || status === "unavailable";
3889
+ const turnText = turnHidden || amountsHidden || !Number.isFinite(turnShown)
3890
+ ? "—"
3891
+ : formatCostMicros(Math.round(turnShown));
3892
+
3893
+ const stale = status === "stale" && balanceCents !== null;
3894
+ const pending = value && Number.isFinite(value.pendingAdjustmentCents) && value.pendingAdjustmentCents > 0;
3895
+ const staleTitle = balance && balance.updatedAt > 0
3896
+ ? tt("cost.staleTitle", { time: new Date(balance.updatedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) })
3897
+ : "";
3898
+
3899
+ const period = periodInfo(Date.now());
3900
+ const changeText = periodChangeText(Date.now(), period.nextChangeAt, detectLang());
3901
+ const periodLabel = period.period === "peak" ? tt("cost.peak") : tt("cost.valley");
3902
+ const periodIcon = e("span", {
3903
+ className: "dma-cost-period-icon",
3904
+ title: periodLabel + " · " + changeText,
3905
+ dangerouslySetInnerHTML: { __html: period.period === "peak" ? PEAK_SVG : VALLEY_SVG }
3906
+ });
3907
+
3908
+ if (compact) {
3909
+ return e("div", { className: "dma-cost-item" },
3910
+ e("div", { className: "dma-cost-card dma-cost-plain" },
3911
+ e("button", {
3912
+ type: "button",
3913
+ className: "dma-cost-plain-row",
3914
+ onClick: refresh,
3915
+ title: stale ? staleTitle : tt("cost.refresh"),
3916
+ "aria-label": tt("cost.refresh"),
3917
+ "aria-busy": refreshing ? "true" : "false"
3918
+ },
3919
+ showPeak ? periodIcon : null,
3920
+ e("span", { className: "dma-cost-col" },
3921
+ e("span", { className: "dma-cost-label" }, tt("cost.balance")),
3922
+ e("span", { className: "dma-cost-value" }, balanceText)
3923
+ ),
3924
+ e("span", { className: "dma-cost-col" },
3925
+ e("span", { className: "dma-cost-label" }, tt("cost.daily")),
3926
+ e("span", { className: "dma-cost-value" }, dailyText)
3927
+ ),
3928
+ showTurn && !turnHidden
3929
+ ? e("span", { className: "dma-cost-col" },
3930
+ e("span", { className: "dma-cost-label", title: tt("cost.settings.perTurnDesc") }, tt("cost.perTurn")),
3931
+ e("span", { className: "dma-cost-value" }, turnText)
3932
+ )
3933
+ : null,
3934
+ pending ? e("span", { className: "dma-cost-badge", title: tt("cost.pendingTitle") }, tt("cost.pending")) : null
3935
+ )
3936
+ )
3937
+ );
3938
+ }
3939
+
3940
+ return e("div", { className: "dma-cost-item" },
3941
+ e("div", { className: "dma-cost-card", "aria-label": tt("cost.title") },
3942
+ e("div", { className: "dma-cost-cols" },
3943
+ e("button", {
3944
+ type: "button",
3945
+ className: "dma-cost-col dma-cost-balance" + (refreshing ? " dma-cost-busy" : ""),
3946
+ onClick: refresh,
3947
+ title: stale ? staleTitle : tt("cost.refresh"),
3948
+ "aria-label": tt("cost.refresh"),
3949
+ "aria-busy": refreshing ? "true" : "false"
3950
+ },
3951
+ e("span", { className: "dma-cost-label" },
3952
+ tt("cost.balance"),
3953
+ pending ? e("span", { className: "dma-cost-badge", title: tt("cost.pendingTitle") }, tt("cost.pending")) : null,
3954
+ refreshing ? e("span", { className: "dma-cost-spinner" }) : null,
3955
+ stale ? e("span", { className: "dma-cost-stale", title: staleTitle }) : null
3956
+ ),
3957
+ e("span", { className: "dma-cost-value" }, balanceText)
3958
+ ),
3959
+ e("div", { className: "dma-cost-col" },
3960
+ e("span", { className: "dma-cost-label" }, tt("cost.daily")),
3961
+ e("span", { className: "dma-cost-value" }, dailyText)
3962
+ ),
3963
+ showTurn && !turnHidden
3964
+ ? e("div", { className: "dma-cost-col" },
3965
+ e("span", { className: "dma-cost-label", title: tt("cost.settings.perTurnDesc") }, tt("cost.perTurn")),
3966
+ e("span", { className: "dma-cost-value" }, turnText),
3967
+ lastTurn
3968
+ ? e("button", {
3969
+ type: "button",
3970
+ className: "dma-cost-hide",
3971
+ title: tt("cost.hide"),
3972
+ "aria-label": tt("cost.hide"),
3973
+ onClick: () => setClosedAt(turnAt)
3974
+ }, "×")
3975
+ : null
3976
+ )
3977
+ : null
3978
+ ),
3979
+ showPeak
3980
+ ? e("div", {
3981
+ className: "dma-cost-period " + (period.period === "peak" ? "dma-cost-peak" : "dma-cost-valley"),
3982
+ "aria-live": "polite"
3983
+ },
3984
+ periodIcon,
3985
+ e("span", { className: "dma-cost-period-text" }, periodLabel + " · " + changeText)
3986
+ )
3987
+ : null
3988
+ )
3989
+ );
3990
+ }
3991
+
3992
+ // -------------------------------------------------------------------------
3993
+ // CSS 注入
3994
+ // -------------------------------------------------------------------------
3995
+
3996
+ const EXTRA_CSS = `
3997
+ .dma-settings{max-width:680px;display:flex;flex-direction:column;gap:2px}
3998
+ .dma-settings-panel{display:flex;flex-direction:column;gap:2px}
3999
+ .dma-settings-version{margin-top:14px;padding-top:10px;font-size:11px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a919e);text-align:right;user-select:text}
4000
+ .dma-setting-row{display:flex;align-items:flex-start;justify-content:space-between;gap:20px;padding:14px 4px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08))}
4001
+ .dma-setting-text{min-width:0}
4002
+ .dma-setting-label{font-size:14px;line-height:1.5;color:var(--dsw-alias-label-primary,#1f2329)}
4003
+ .dma-setting-desc{margin-top:3px;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a919e)}
4004
+ .dma-switch{flex:none;position:relative;width:36px;height:20px;margin-top:2px;border:0;border-radius:999px;padding:0;background:var(--dsw-alias-border-l3,#c9ced6);cursor:pointer;transition:background 120ms ease}
4005
+ .dma-switch[aria-checked="true"]{background:var(--dsw-alias-state-business-primary,#4c8dff)}
4006
+ .dma-switch:disabled{opacity:.45;cursor:default}
4007
+ .dma-switch-thumb{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-switch-thumb,#fff);box-shadow:0 1px 2px rgba(0,0,0,.18);transition:transform 120ms ease}
4008
+ .dma-switch[aria-checked="true"] .dma-switch-thumb{transform:translateX(16px)}
4009
+ .dma-setting-error{margin-top:10px;font-size:12px;color:var(--dsw-alias-state-error-primary,#e5484d)}
4010
+ .dma-ico{display:inline-flex}
4011
+ .dma-empty{color:var(--dsw-alias-label-tertiary,#8a919e);font-size:13px;margin:12px 0}
4012
+ .dma-tabs{display:inline-flex;gap:4px;align-self:flex-start;margin:2px 0 10px;padding:3px;border-radius:9px;background:var(--dsw-alias-bg-layer-2,#f2f3f5)}
4013
+ .dma-tab{border:0;border-radius:7px;padding:5px 14px;background:transparent;color:var(--dsw-alias-label-secondary,#5b6472);font-size:13px;line-height:1.4;cursor:pointer}
4014
+ .dma-tab[aria-selected="true"]{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-weight:600;box-shadow:0 1px 3px rgba(0,0,0,.08)}
4015
+ .dma-tab:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4016
+ .dma-number{flex:none;width:88px;margin-top:4px;padding:5px 8px;border:.5px solid var(--dsw-alias-border-l3,#c9ced6);border-radius:7px;background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-size:13px;font-variant-numeric:tabular-nums;text-align:right}
4017
+ .dma-number:disabled{opacity:.5}
4018
+ .dma-seg{flex:none;display:inline-flex;gap:2px;margin-top:2px;padding:2px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,#f2f3f5)}
4019
+ .dma-seg-btn{border:0;border-radius:6px;padding:4px 10px;background:transparent;color:var(--dsw-alias-label-secondary,#5b6472);font-size:12px;line-height:1.4;cursor:pointer}
4020
+ .dma-seg-btn[aria-pressed="true"]{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#1f2329);font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.08)}
4021
+ .dma-seg-btn:disabled{opacity:.45;cursor:default}
4022
+ .dma-correction{margin-top:14px;padding-top:14px;border-top:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08))}
4023
+ .dma-correction-title{margin-bottom:8px;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,#1f2329)}
4024
+ .dma-correction-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:7px 0;font-size:13px}
4025
+ .dma-correction-label{color:var(--dsw-alias-label-secondary,#5b6472)}
4026
+ .dma-correction-input{display:inline-flex;align-items:center;gap:4px;padding:4px 8px;border:.5px solid var(--dsw-alias-border-l3,#c9ced6);border-radius:7px;background:var(--dsw-alias-bg-layer-1,#fff)}
4027
+ .dma-correction-input input{width:110px;border:0;outline:0;background:transparent;color:var(--dsw-alias-label-primary,#1f2329);font:inherit;font-variant-numeric:tabular-nums;text-align:right}
4028
+ .dma-correction-input input[aria-invalid="true"]{color:var(--dsw-alias-state-error-primary,#e5484d)}
4029
+ .dma-correction-yuan{color:var(--dsw-alias-label-tertiary,#8a919e)}
4030
+ .dma-correction-value{color:var(--dsw-alias-label-primary,#1f2329);font-variant-numeric:tabular-nums}
4031
+ .dma-correction-negative{color:var(--dsw-alias-state-error-primary,#e5484d);font-weight:600}
4032
+ .dma-correction-warn{margin-top:4px;font-size:12px;color:var(--dsw-alias-state-error-primary,#e5484d)}
4033
+ .dma-cost-note{margin:10px 0 0;font-size:11px;line-height:1.6;color:var(--dsw-alias-label-tertiary,#8a919e)}
4034
+ .dma-correction-actions{display:flex;justify-content:flex-end;margin-top:10px}
4035
+ .dma-correction-save{height:32px;padding:0 16px;border:0;border-radius:8px;background:var(--dsw-alias-button-primary-fill,#4c8dff);color:#fff;font-size:13px;cursor:pointer}
4036
+ .dma-correction-save:disabled{background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-dimmed,#a0a6b0);cursor:default}
4037
+ .dma-cost-item{flex:1 1 auto;min-width:0}
4038
+ .dma-cost-card{display:flex;flex-direction:column;gap:3px;min-width:0;padding:5px 8px;border:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));border-radius:8px;background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-primary,#1f2329)}
4039
+ .dma-cost-cols{display:flex;align-items:baseline;justify-content:space-between;gap:6px;min-width:0}
4040
+ .dma-cost-col{display:flex;align-items:baseline;gap:3px;min-width:0;flex:0 1 auto;text-align:left}
4041
+ .dma-cost-balance{display:flex;align-items:baseline;gap:3px;min-width:0;border:0;border-radius:5px;padding:0 2px;background:transparent;color:inherit;font:inherit;cursor:pointer}
4042
+ .dma-cost-balance:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05))}
4043
+ .dma-cost-balance:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4044
+ .dma-cost-label{display:flex;align-items:center;gap:2px;overflow:hidden;font-size:11px;line-height:1.2;white-space:nowrap;color:var(--dsw-alias-label-tertiary,#8a919e)}
4045
+ .dma-cost-value{overflow:hidden;font-size:14px;font-weight:600;line-height:1.25;white-space:nowrap;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
4046
+ .dma-cost-badge{flex:none;padding:0 4px;border-radius:7px;background:rgba(245,154,46,.16);color:#b56a00;font-size:10.5px;font-weight:500;line-height:15px}
4047
+ .dma-cost-spinner{flex:none;width:9px;height:9px;border:1.5px solid rgba(0,0,0,.15);border-top-color:var(--dsw-alias-state-business-primary,#4c8dff);border-radius:50%;animation:dma-spin .8s linear infinite}
4048
+ .dma-cost-stale{flex:none;width:4px;height:4px;border-radius:50%;background:var(--dsw-alias-label-dimmed,#a0a6b0)}
4049
+ .dma-cost-hide{margin-left:1px;border:0;padding:0 1px;background:transparent;color:var(--dsw-alias-label-tertiary,#8a919e);font-size:11px;line-height:1;cursor:pointer}
4050
+ .dma-cost-period{display:flex;align-items:center;justify-content:center;gap:5px;padding-top:4px;border-top:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));font-size:10.5px;line-height:1.35}
4051
+ .dma-cost-period-icon{flex:none;display:inline-flex;align-items:center;justify-content:center;width:14px;height:14px}
4052
+ .dma-cost-period-icon svg{display:block;width:14px;height:14px}
4053
+ .dma-cost-peak .dma-cost-period-text{color:#c2610b}
4054
+ .dma-cost-valley .dma-cost-period-text{color:#2563b8}
4055
+ .dma-cost-period-text{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
4056
+ .dma-cost-plain{padding:2px 2px;border:0;border-radius:0;background:transparent;gap:0}
4057
+ .dma-cost-plain-row{display:flex;align-items:center;justify-content:flex-start;gap:9px;width:100%;min-width:0;border:0;padding:0;background:transparent;color:inherit;font:inherit;cursor:pointer;text-align:left}
4058
+ .dma-cost-plain-row:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4059
+ .dma-cost-plain .dma-cost-col{flex:0 1 auto;overflow:hidden}
4060
+ .dma-cost-plain .dma-cost-value{font-size:13.5px}
4061
+ .dma-cost-plain .dma-cost-badge{margin-left:auto}
4062
+ .dma-cost-local{flex-direction:row;align-items:center;justify-content:center;gap:5px;padding:6px 8px}
4063
+ .dma-cost-local.dma-cost-plain{justify-content:flex-start;gap:6px;padding:2px 2px}
4064
+ .dma-cost-local-text{overflow:hidden;font-size:12px;line-height:1.3;white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-secondary,#5b6472)}
4065
+ .dma-cost-rail{display:flex;align-items:center;justify-content:center;width:100%;min-width:0;height:30px;border:0;border-radius:7px;background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-secondary,#5b6472);cursor:pointer}
4066
+ .dma-cost-rail:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05))}
4067
+ .dma-cost-rail:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4068
+ .dma-cost-rail svg{width:16px;height:16px}
4069
+ @keyframes dma-spin{to{transform:rotate(360deg)}}
4070
+ `;
4071
+
4072
+ function injectCss() {
4073
+ if (typeof document === "undefined") return;
4074
+ if (document.querySelector('style[data-plugin-css="' + NS + '"]')) return;
4075
+ const tag = document.createElement("style");
4076
+ tag.dataset.plugin = NS;
4077
+ tag.dataset.pluginCss = NS;
4078
+ tag.textContent = CSS + "\n" + EXTRA_CSS;
4079
+ document.head.appendChild(tag);
4080
+ }
4081
+
4082
+ // -------------------------------------------------------------------------
4083
+ // DOM 观察
4084
+ // -------------------------------------------------------------------------
4085
+
4086
+ function startDomObserver(ctx) {
4087
+ if (typeof document === "undefined" || !document.body) return () => {};
4088
+ const run = () => {
4089
+ injectQuestionButtons(ctx);
4090
+ injectToolButtons(ctx);
4091
+ evictStaleControllers();
4092
+ syncRail();
4093
+ // 对话在流式输出时结构频繁变化:按 TTL 补拉快照,让答行统计与轮次列表跟上。
4094
+ for (const el of document.querySelectorAll("[data-conversation-session]")) {
4095
+ const sessionId = el.getAttribute("data-conversation-session");
4096
+ if (sessionId) sessionFor(ctx, sessionId).fetchMessages(false).catch(() => {});
4097
+ }
4098
+ };
4099
+ const scheduler = createScheduler(run, { delay: 120 });
4100
+ const observer = new MutationObserver(() => scheduler.request());
4101
+ observer.observe(document.body, { childList: true, subtree: true });
4102
+ run();
4103
+ return () => {
4104
+ observer.disconnect();
4105
+ scheduler.dispose();
4106
+ };
4107
+ }
4108
+
4109
+ function startRailObserver() {
4110
+ if (typeof document === "undefined" || !document.body) return () => {};
4111
+ let running = false;
4112
+ let observer = null;
4113
+ const run = () => {
4114
+ if (running) return;
4115
+ running = true;
4116
+ try {
4117
+ syncRail();
4118
+ } finally {
4119
+ // 丢弃本次同步自己写出的变更记录,避免「写入 → 观察 → 再写入」自激。
4120
+ if (observer) observer.takeRecords();
4121
+ running = false;
4122
+ }
4123
+ };
4124
+ const schedule = typeof requestAnimationFrame === "function"
4125
+ ? (fn) => requestAnimationFrame(fn)
4126
+ : (fn) => setTimeout(fn, 60);
4127
+ const cancel = typeof cancelAnimationFrame === "function"
4128
+ ? (handle) => cancelAnimationFrame(handle)
4129
+ : (handle) => clearTimeout(handle);
4130
+ const scheduler = createScheduler(run, { schedule, cancel });
4131
+ observer = new MutationObserver(() => scheduler.request());
4132
+ // 只关心官方刻度自身的重建与标签变化;不监听本插件写入的属性(data-dma-*)。
4133
+ observer.observe(document.body, {
4134
+ childList: true,
4135
+ subtree: true,
4136
+ attributes: true,
4137
+ attributeFilter: ["aria-label", "data-index"]
4138
+ });
4139
+ return () => {
4140
+ if (observer) observer.disconnect();
4141
+ observer = null;
4142
+ scheduler.dispose();
4143
+ };
4144
+ }
4145
+
4146
+ // -------------------------------------------------------------------------
4147
+ // 插件主体
4148
+ // -------------------------------------------------------------------------
4149
+
4150
+ /**
4151
+ * 设置开关或界面语言变化后,立即重绘会话内的按钮与刻度。
4152
+ * 只靠 DOM 观察器时,改设置不会改动会话 DOM,界面要等面板关闭才更新。
4153
+ */
4154
+ function watchLiveUpdates(ctx, form) {
4155
+ const run = () => {
4156
+ injectQuestionButtons(ctx);
4157
+ injectToolButtons(ctx);
4158
+ syncRail();
4159
+ };
4160
+ const schedule = typeof requestAnimationFrame === "function"
4161
+ ? (fn) => requestAnimationFrame(fn)
4162
+ : (fn) => setTimeout(fn, 60);
4163
+ const cancel = typeof cancelAnimationFrame === "function"
4164
+ ? (handle) => cancelAnimationFrame(handle)
4165
+ : (handle) => clearTimeout(handle);
4166
+ const scheduler = createScheduler(run, { schedule, cancel });
4167
+ const queue = () => scheduler.request();
4168
+
4169
+ const stops = [scheduler.dispose];
4170
+ if (form && typeof form.subscribe === "function") {
4171
+ const off = form.subscribe(queue);
4172
+ if (typeof off === "function") stops.push(off);
4173
+ }
4174
+ if (typeof ctx.on === "function") {
4175
+ const onLocale = () => {
4176
+ localeService = ctx.locale || localeService;
4177
+ queue();
4178
+ };
4179
+ ctx.on("locale/change", onLocale);
4180
+ stops.push(() => {
4181
+ if (typeof ctx.off === "function") ctx.off("locale/change", onLocale);
4182
+ });
4183
+ }
4184
+
4185
+ return () => {
4186
+ for (const stop of stops) {
4187
+ try {
4188
+ stop();
4189
+ } catch {
4190
+ /* ignore */
4191
+ }
4192
+ }
4193
+ };
4194
+ }
4195
+
4196
+ const inject = ["slots", "locale", "configForms"];
4197
+
4198
+ function apply(ctx) {
4199
+ injectCss();
4200
+ localeService = ctx.locale || null;
4201
+
4202
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), "dsh-message-actions: locale");
4203
+
4204
+ const settingsForm = ctx.configForms.get("dsh-message-actions");
4205
+
4206
+ // 答行统计
4207
+ ctx.slots.inject("conversation.chat.assistant-actions", () =>
4208
+ ctx.slots.register({
4209
+ name: "conversation.chat.assistant-actions",
4210
+ id: "dsh-message-actions-stats",
4211
+ order: 30,
4212
+ locale: NS,
4213
+ inject: (sessionId) => {
4214
+ const controller = sessionFor(ctx, sessionId);
4215
+ return {
4216
+ hooks: { data: controller.data },
4217
+ form: controller.form,
4218
+ refresh: () => controller.fetchMessages(false).catch(() => {})
4219
+ };
4220
+ }
4221
+ }, AssistantActions)
4222
+ );
4223
+
4224
+ // 确认弹窗 + 分享/导出浮层
4225
+ ctx.slots.inject("conversation.input.overlay", () =>
4226
+ ctx.slots.register({
4227
+ name: "conversation.input.overlay",
4228
+ id: "dsh-message-actions-overlay",
4229
+ order: 20,
4230
+ locale: NS,
4231
+ inject: (sessionId) => {
4232
+ const controller = sessionFor(ctx, sessionId);
4233
+ return {
4234
+ hooks: { overlay: controller.overlay, data: controller.data },
4235
+ confirmAction: (action, opts) => controller.confirmAction(action, opts),
4236
+ dismiss: () => controller.dismiss(),
4237
+ // 摘要不含正文:先按需拉全文。只有成功才关闭浮层,
4238
+ // 失败时由浮层保留已选轮次并复位 busy(提示在生成函数内给出)。
4239
+ runShare: (rounds) => generateSharePng(controller, rounds),
4240
+ runExport: (rounds) => doExport(controller, rounds)
4241
+ };
4242
+ }
4243
+ }, OverlayController)
4244
+ );
4245
+
4246
+ // 设置页
4247
+ ctx.slots.inject("settings.section", () =>
4248
+ ctx.slots.register({
4249
+ name: "settings.section",
4250
+ id: "dsh-message-actions",
4251
+ order: 100,
4252
+ label: () => t("nav"),
4253
+ locale: NS,
4254
+ inject: () => ({ form: settingsForm })
4255
+ }, SettingsSection)
4256
+ );
4257
+
4258
+ // 侧边栏底部费用卡片
4259
+ ctx.slots.inject("sidebar.footer.action", () =>
4260
+ ctx.slots.register({
4261
+ name: "sidebar.footer.action",
4262
+ id: "dsh-message-actions-cost",
4263
+ order: 20,
4264
+ locale: NS,
4265
+ inject: () => ({ form: settingsForm })
4266
+ }, CostCard)
4267
+ );
4268
+
4269
+ // 费用状态轮询(5s;usageStats 关闭 / 页面隐藏时暂停)
4270
+ startCostPolling(settingsForm);
4271
+
4272
+ // DOM 观察:问行按钮注入 + 导航刻度隐藏/压缩
4273
+ const stopDom = startDomObserver(ctx);
4274
+ const stopRail = startRailObserver();
4275
+ const stopLive = watchLiveUpdates(ctx, settingsForm);
4276
+ ctx.effect(() => () => {
4277
+ stopDom();
4278
+ stopRail();
4279
+ stopLive();
4280
+ stopCostPolling();
4281
+ if (typeof document !== "undefined") {
4282
+ document.querySelectorAll("[data-dma-actions]").forEach((node) => disposeActionsRow(node));
4283
+ // 工具行按钮是命令式创建的,卸载时要一并移除(含可能的 React 图标根)。
4284
+ document.querySelectorAll("[data-dma-tool-actions]").forEach((node) => disposeActionsRow(node));
4285
+ document.querySelectorAll("[data-dma-toast]").forEach((node) => node.remove());
4286
+ document.querySelectorAll('style[data-plugin-css="' + NS + '"]').forEach((node) => node.remove());
4287
+ }
4288
+ }, "dsh-message-actions: dom observers");
4289
+ }
4290
+
4291
+ return { inject, apply };
4292
+ }
4293
+ });