dsh-message-actions 0.2.1 → 0.2.3

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 CHANGED
@@ -19,6 +19,15 @@ window.__ModuleLoader__.load({
19
19
  ReactDOMClient = null;
20
20
  }
21
21
 
22
+ // createPortal 来自 react-dom(不是 react-dom/client)。单独探测:
23
+ // 拿不到时浮层退回宿主槽位渲染,不影响按钮与弹窗功能。
24
+ let ReactDOM = null;
25
+ try {
26
+ ReactDOM = require("react-dom");
27
+ } catch {
28
+ ReactDOM = null;
29
+ }
30
+
22
31
  let PRIMITIVES = null;
23
32
  try {
24
33
  PRIMITIVES = require("@deepseek-ai/dsh-client-ui-primitives");
@@ -70,6 +79,9 @@ const ERROR_LABELS = {
70
79
  INVALID_AMOUNT: '金额格式不合法',
71
80
  READ_ONLY: '状态文件只读,未保存',
72
81
  WRITE_FAILED: '写入状态文件失败',
82
+ ATTACHMENT_NOT_FOUND: '附件不存在或已失效',
83
+ ATTACHMENT_UNAVAILABLE: '附件服务不可用',
84
+ ATTACHMENT_READ_FAILED: '附件读取失败',
73
85
  INTERNAL: '内部错误'
74
86
  },
75
87
  en: {
@@ -85,6 +97,9 @@ const ERROR_LABELS = {
85
97
  INVALID_AMOUNT: 'Invalid amount',
86
98
  READ_ONLY: 'State file is read-only; nothing saved',
87
99
  WRITE_FAILED: 'Could not write the state file',
100
+ ATTACHMENT_NOT_FOUND: 'Attachment not found or no longer available',
101
+ ATTACHMENT_UNAVAILABLE: 'Attachment service is unavailable',
102
+ ATTACHMENT_READ_FAILED: 'Could not read the attachment',
88
103
  INTERNAL: 'Internal error'
89
104
  }
90
105
  };
@@ -97,7 +112,8 @@ const ERROR_LABELS = {
97
112
  * 折叠 OpenAI 风格 content(字符串或 block 数组)为纯文本。
98
113
  * 只取用户可见的 text 块:reasoning(思维链)不属于回答正文,不能混进分享/导出。
99
114
  */
100
- function contentText(content) {
115
+ function contentText(content, options) {
116
+ const placeholders = !options || options.attachments !== false;
101
117
  if (typeof content === 'string') return content;
102
118
  if (!Array.isArray(content)) return '';
103
119
  const parts = [];
@@ -110,14 +126,56 @@ function contentText(content) {
110
126
  if (block.type === 'text' && typeof block.text === 'string') {
111
127
  parts.push(block.text);
112
128
  } else if (block.type === 'image') {
113
- parts.push('[图片]');
129
+ if (placeholders) parts.push('[图片]');
114
130
  } else if (block.type === 'file') {
115
- parts.push('[文件]');
131
+ if (placeholders) parts.push('[文件]');
116
132
  }
117
133
  }
118
134
  return parts.join('');
119
135
  }
120
136
 
137
+ /**
138
+ * 撤回回填用的正文:只拼接文本块,不插入 `[图片]` / `[文件]` 占位符。
139
+ * 附件由客户端另行恢复(见 `attachmentsOfEvent`);只有附件恢复不可用时,
140
+ * 占位符才有意义,因此这里不留占位符,避免与真实附件重复。
141
+ */
142
+ function refillTextOf(event) {
143
+ if (!event || event.type !== 'user/message') return '';
144
+ const content = event.data && event.data.content;
145
+ return contentText(content, { attachments: false });
146
+ }
147
+
148
+ /**
149
+ * 提取用户消息里的附件描述(图片与文件),供客户端按 id 取回字节后恢复。
150
+ * 只读取 durable `attachment` 引用,不展开内容;同一 id 只保留一次。
151
+ * @returns {{ kind: 'image'|'file', attachmentId: string, name: string, mediaType: string, bytes?: number, width?: number, height?: number }[]}
152
+ */
153
+ function attachmentsOfEvent(event) {
154
+ const content = event && event.type === 'user/message' && event.data && event.data.content;
155
+ if (!Array.isArray(content)) return [];
156
+ const list = [];
157
+ const seen = new Set();
158
+ for (const block of content) {
159
+ if (!block || block.type !== 'image' && block.type !== 'file') continue;
160
+ const ref = block.attachment;
161
+ if (!ref || typeof ref.attachmentId !== 'string' || ref.attachmentId.length === 0) continue;
162
+ if (seen.has(ref.attachmentId)) continue;
163
+ seen.add(ref.attachmentId);
164
+ list.push({
165
+ kind: block.type,
166
+ attachmentId: ref.attachmentId,
167
+ name: typeof ref.name === 'string' && ref.name.length > 0
168
+ ? ref.name
169
+ : (block.type === 'image' ? 'image' : 'file'),
170
+ mediaType: typeof ref.mediaType === 'string' ? ref.mediaType : '',
171
+ bytes: Number.isSafeInteger(ref.bytes) ? ref.bytes : undefined,
172
+ width: Number.isSafeInteger(ref.width) ? ref.width : undefined,
173
+ height: Number.isSafeInteger(ref.height) ? ref.height : undefined
174
+ });
175
+ }
176
+ return list;
177
+ }
178
+
121
179
  /** 取一个事件的纯文本正文(按事件类型分发)。 */
122
180
  function textOf(event) {
123
181
  if (!event || typeof event !== 'object') return '';
@@ -525,7 +583,11 @@ function planAction(events, nodes, params) {
525
583
  })();
526
584
  // 撤回回填必须用被点的那条提问文本:轮次区间起点可能是运行时注入消息,
527
585
  // 不能取 startSeq 的正文,否则会把注入上下文回填到输入框。
528
- if (plan.ok && action === 'recall') plan.refillText = textOf(evt);
586
+ // 附件单独返回,客户端恢复成真实图片 / 文件;正文不再插入占位符。
587
+ if (plan.ok && action === 'recall') {
588
+ plan.refillText = refillTextOf(evt);
589
+ plan.attachments = attachmentsOfEvent(evt);
590
+ }
529
591
  return plan;
530
592
  }
531
593
 
@@ -583,7 +645,7 @@ function buildPlan(events, nodes, startSeq, endSeq, targetType, action, turn) {
583
645
  via,
584
646
  turn,
585
647
  step,
586
- refillText: action === 'recall' ? textOf(events[startSeq]) : null
648
+ refillText: action === 'recall' ? refillTextOf(events[startSeq]) : null
587
649
  };
588
650
  }
589
651
 
@@ -649,6 +711,25 @@ function goneTurnsOf(events, nodes, lookup) {
649
711
  return turnIndex.filter((info) => !live.has(info.turn)).map((info) => info.turn);
650
712
  }
651
713
 
714
+ /**
715
+ * 单条回答的估算成本:只针对该条 `assistant/message` 自己的 usage,
716
+ * 不复用同一轮其它步骤的数据,避免同轮多步骤重复计价。
717
+ * 本地 / 非 DeepSeek 路由返回 `{ micros: 0, billable: false }`;
718
+ * 无 usage 或无法判定路由时返回 undefined(界面不显示金额)。
719
+ * @returns {{ micros: number, billable: boolean } | undefined}
720
+ */
721
+ function replyCostOf(event) {
722
+ if (!event || event.type !== 'assistant/message') return undefined;
723
+ const usage = stepUsageOf(event);
724
+ if (!usage) return undefined;
725
+ const data = event.data || {};
726
+ const route = routeOfUsage(data.usage) || routeOfMessage(data.message);
727
+ if (!route) return undefined;
728
+ if (!isBillableRoute(route.provider, route.model)) return { micros: 0, billable: false };
729
+ const at = Number.isFinite(event.time) ? event.time : Date.now();
730
+ return { micros: turnCost(usage, route.model, periodInfo(at).period), billable: true };
731
+ }
732
+
652
733
  /**
653
734
  * `/messages` 摘要快照:只返回预览、字数、用量与 callId,不返回正文。
654
735
  * 分享图 / 导出需要全文时,走 `full=1&turns=a,b` 的按需接口(见 index.mjs)。
@@ -694,6 +775,7 @@ function messagesSummaryOf(events, nodes, lookup, options) {
694
775
  (data.source === undefined || data.source === null || data.source.kind === undefined || data.source.kind === 'user');
695
776
  const isText = isUserQuestion || event.type === 'assistant/message';
696
777
  const text = isText ? textOf(event) : '';
778
+ const replyCost = event.type === 'assistant/message' ? replyCostOf(event) : undefined;
697
779
  const summary = {
698
780
  seq,
699
781
  type: event.type,
@@ -705,6 +787,8 @@ function messagesSummaryOf(events, nodes, lookup, options) {
705
787
  preview: isText ? previewText(text, previewLimit) : '',
706
788
  words: isText ? wordCount(text) : 0,
707
789
  usage: usageSummaryOf(event),
790
+ costMicros: replyCost ? replyCost.micros : null,
791
+ billable: replyCost ? replyCost.billable : null,
708
792
  callId: toolCallIdOf(event)
709
793
  };
710
794
  const beyondCursor = since === null || seq > since;
@@ -1238,6 +1322,29 @@ function routingOfProvider(provider) {
1238
1322
  return 'local';
1239
1323
  }
1240
1324
 
1325
+ /** 模型名是否为 DeepSeek 官方模型(无 provider 时用于兜底判定)。 */
1326
+ function isDeepseekModel(model) {
1327
+ return typeof model === 'string' && /^deepseek/i.test(model.trim());
1328
+ }
1329
+
1330
+ /**
1331
+ * 该次用量是否计入 DeepSeek 费用(统计表「估算成本」/「预算使用」/「日用」)。
1332
+ *
1333
+ * - provider 已知:`deepseek-account` / `deepseek-*` 计费,其余(本地模型、第三方网关)不计费;
1334
+ * - provider 缺失:只有模型名明确是 `deepseek-*` 才计费,未知来源一律不计费(不臆测)。
1335
+ *
1336
+ * 本地 / 未知来源的 token 仍照常统计,只是成本记 0。
1337
+ * @param provider 路由 provider(如 `deepseek-account` / `ninfer-27b`)
1338
+ * @param model 模型名(如 `deepseek-flash`)
1339
+ * @returns {boolean}
1340
+ */
1341
+ function isBillableRoute(provider, model) {
1342
+ const routing = routingOfProvider(provider);
1343
+ if (routing === 'local') return false;
1344
+ if (routing === 'account' || routing === 'api-key') return true;
1345
+ return isDeepseekModel(model);
1346
+ }
1347
+
1241
1348
  /**
1242
1349
  * 费用卡片样式枚举。数组顺序即设置页选项顺序:单行样式排在第一位。
1243
1350
  * 内部存储值沿用 `compact` / `default`,与旧版本配置兼容。
@@ -1268,6 +1375,81 @@ function costSwitches(config) {
1268
1375
  };
1269
1376
  }
1270
1377
 
1378
+ /** 可选音色(Web Audio 现场合成,无音频文件)。 */
1379
+ const SOUND_TONES = ['double', 'bell', 'soft'];
1380
+ const DEFAULT_SOUND_TONE = 'double';
1381
+
1382
+ /** 音色归一化:未知值回落到默认双音('off' 由 completionSoundTone 单独处理)。 */
1383
+ function normalizeSoundTone(value) {
1384
+ return typeof value === 'string' && SOUND_TONES.indexOf(value) >= 0 ? value : DEFAULT_SOUND_TONE;
1385
+ }
1386
+
1387
+ /**
1388
+ * 运行时音色。0.2.2 起不再有独立开关:
1389
+ * - `soundTone === 'off'` 即关闭;
1390
+ * - 旧配置只有 `sound: false`(没有音色)时,映射为「关闭」,保持旧行为;
1391
+ * - 旧配置 `sound: false` + 已有音色,同样显示「关闭」(旧开关优先)。
1392
+ */
1393
+ function completionSoundTone(config) {
1394
+ const cfg = config || {};
1395
+ if (cfg.sound === false) return 'off';
1396
+ if (cfg.soundTone === 'off') return 'off';
1397
+ return normalizeSoundTone(cfg.soundTone);
1398
+ }
1399
+
1400
+ /** 完成提示音是否开启:等价于音色不为「关闭」。 */
1401
+ function completionSoundEnabled(config) {
1402
+ return completionSoundTone(config) !== 'off';
1403
+ }
1404
+
1405
+ /**
1406
+ * 设置页音色选项:3 个音色 + 「关闭」。
1407
+ * 选中「关闭」即关闭完成提示音;选中任一音色即开启并试听。
1408
+ * 供客户端渲染与离线断言共用。
1409
+ */
1410
+ function soundToneOptions() {
1411
+ return SOUND_TONES.concat(['off']);
1412
+ }
1413
+
1414
+ // 音量:0–100 整数,默认 50(= 现有增益基准),步进 5 由滑杆约束。
1415
+ const DEFAULT_SOUND_VOLUME = 50;
1416
+
1417
+ /** 音量归一化:非法值回默认 50,其余夹到 0–100 的整数。 */
1418
+ function clampSoundVolume(value) {
1419
+ const num = typeof value === 'number' ? value : Number(value);
1420
+ if (!Number.isFinite(num)) return DEFAULT_SOUND_VOLUME;
1421
+ return Math.min(100, Math.max(0, Math.round(num)));
1422
+ }
1423
+
1424
+ /**
1425
+ * 音量倍数:50 为基准 1.0,0 为 0(静音),100 为 2.0。
1426
+ * 播放端用 `TONE_SPECS[音色].gain * soundGainScale(音量)`,避免 0 音量仍发声。
1427
+ */
1428
+ function soundGainScale(volume) {
1429
+ return clampSoundVolume(volume) / 50;
1430
+ }
1431
+
1432
+ /**
1433
+ * 判断这一轮是否该播放完成提示音。
1434
+ * - 开关必须开启、本轮已结算(`settled !== false`)且拿到有效结算时间;
1435
+ * - `previousAt` 相同说明还是上一轮(重渲染 / 重复拉取),不重复响;
1436
+ * - `lastPlayedAt` 记录已响过的轮次,迟到回调不补响;
1437
+ * - 宿主仍忙(`busy === true`)时不响。
1438
+ * @param {{enabled?:boolean, busy?:boolean, settled?:boolean, previousAt?:number|null, at?:number|null, lastPlayedAt?:number|null}} options
1439
+ * @returns {boolean}
1440
+ */
1441
+ function shouldPlayCompletionSound(options) {
1442
+ const opt = options || {};
1443
+ if (opt.enabled !== true) return false;
1444
+ if (opt.busy === true) return false;
1445
+ if (opt.settled === false) return false;
1446
+ const at = opt.at;
1447
+ if (!Number.isFinite(at) || at <= 0) return false;
1448
+ if (Number.isFinite(opt.previousAt) && opt.previousAt === at) return false;
1449
+ if (Number.isFinite(opt.lastPlayedAt) && opt.lastPlayedAt === at) return false;
1450
+ return true;
1451
+ }
1452
+
1271
1453
  /**
1272
1454
  * 聚合一轮(turn/start…turn/end)内各 step 的 usage。
1273
1455
  * 每个 step 只取最后一个有效 assistant 结果(message 优先,其次 attempt),
@@ -1383,31 +1565,61 @@ function appendTurnEvent(buffer, event) {
1383
1565
  }
1384
1566
 
1385
1567
  // ---------------------------------------------------------------------------
1386
- // 费用统计:余额观测(账户口径)与金额校正
1568
+ // 费用统计:余额观测(账户口径)
1387
1569
  // ---------------------------------------------------------------------------
1388
1570
 
1389
1571
  /** 间隔超过 25 小时视为应用长时间未运行,不补记差额。 */
1390
1572
  const MAX_OBSERVE_GAP_MS = 25 * 60 * 60 * 1000;
1391
1573
 
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);
1574
+ /**
1575
+ * 轮次结算累加当日用量(纯函数)。
1576
+ *
1577
+ * 口径:**以结算累加为主**——每轮 `turn/end` 落地时立即把估算金额(分)
1578
+ * 记入当日桶,并与「自上次余额观测以来已结算的金额」一起累计;
1579
+ * 余额观测随后只对差额做校正(见 observeBalance),避免重复计入。
1580
+ *
1581
+ * 幂等:同一 `key`(会话 + 轮次 + 结束时刻)只累加一次,重复推送不会二次计数。
1582
+ * 跨零点:按结算时刻(endedAt)的北京日期入桶。
1583
+ *
1584
+ * @param state 持久化状态(不修改入参)
1585
+ * @param params { micros, at, key }
1586
+ * @returns {{ state, applied, cents }}
1587
+ */
1588
+ function settleSpend(state, params) {
1589
+ const s = state || {};
1590
+ const p = params || {};
1591
+ const micros = Number.isFinite(p.micros) ? p.micros : 0;
1592
+ const cents = micros > 0 ? Math.round(micros / 10000) : 0;
1593
+ const out = {
1594
+ dailySpendCents: Object.assign({}, s.dailySpendCents || {}),
1595
+ settledSpendTotalCents: Number.isFinite(s.settledSpendTotalCents) ? s.settledSpendTotalCents : 0,
1596
+ settledSinceObserveCents: Number.isFinite(s.settledSinceObserveCents) ? s.settledSinceObserveCents : 0,
1597
+ lastSettledKey: typeof s.lastSettledKey === 'string' ? s.lastSettledKey : ''
1598
+ };
1599
+ const key = typeof p.key === 'string' ? p.key : '';
1600
+ if (cents === 0) return { state: out, applied: false, cents: 0 };
1601
+ if (key !== '' && key === out.lastSettledKey) return { state: out, applied: false, cents: 0 };
1602
+ const at = Number.isFinite(p.at) ? p.at : Date.now();
1603
+ const day = beijingDateKey(at);
1604
+ out.dailySpendCents[day] = (out.dailySpendCents[day] || 0) + cents;
1605
+ out.settledSpendTotalCents += cents;
1606
+ out.settledSinceObserveCents += cents;
1607
+ if (key !== '') out.lastSettledKey = key;
1608
+ return { state: out, applied: true, cents };
1401
1609
  }
1402
1610
 
1403
1611
  /**
1404
1612
  * 一次余额观测的记账(纯函数,返回新状态与本次记账原因)。
1405
1613
  *
1406
1614
  * - 下降 → 累计「已观测消费」,按北京时间日期计入「日用」;
1407
- * - 上升 → 累计「待核对余额调整」,绝不冲减消费;
1615
+ * - 上升 → 只更新 lastBalance,不冲减消费(不再维护手工校正字段);
1408
1616
  * - 跨日 / 间隔超 25h / 路由切换 → 只更新 lastBalance,跳过本次差额;
1409
1617
  * - 非 account 路由 → 完全不记账。
1410
1618
  *
1619
+ * 与轮次结算共用同一份「日用」:本轮已结算的金额先由 settleSpend 记入,
1620
+ * 观测到差额时只把 **超出已结算部分** 补进当日桶(`diff - settledSinceObserveCents`),
1621
+ * 不重复计入;估算高于实际(差额为负)时不做减法,保持「日用」为花费上限提示。
1622
+ *
1411
1623
  * @param state 持久化状态(不修改入参)
1412
1624
  * @param params { cents, routing, at }
1413
1625
  * @returns {{ state, reason }}
@@ -1424,8 +1636,9 @@ function observeBalance(state, params) {
1424
1636
  lastRouting: typeof s.lastRouting === 'string' ? s.lastRouting : null,
1425
1637
  observedSpendTotalCents: Number.isFinite(s.observedSpendTotalCents) ? s.observedSpendTotalCents : 0,
1426
1638
  dailySpendCents: Object.assign({}, s.dailySpendCents || {}),
1427
- pendingAdjustmentCents: Number.isFinite(s.pendingAdjustmentCents) ? s.pendingAdjustmentCents : 0,
1428
- pendingAdjustmentAt: Number.isFinite(s.pendingAdjustmentAt) ? s.pendingAdjustmentAt : 0
1639
+ settledSpendTotalCents: Number.isFinite(s.settledSpendTotalCents) ? s.settledSpendTotalCents : 0,
1640
+ settledSinceObserveCents: Number.isFinite(s.settledSinceObserveCents) ? s.settledSinceObserveCents : 0,
1641
+ lastSettledKey: typeof s.lastSettledKey === 'string' ? s.lastSettledKey : ''
1429
1642
  };
1430
1643
  if (cents === null) return { state: out, reason: 'invalid' };
1431
1644
  if (routing !== 'account') return { state: out, reason: 'not-account' };
@@ -1435,28 +1648,34 @@ function observeBalance(state, params) {
1435
1648
  out.lastBalanceCents = cents;
1436
1649
  out.lastBalanceAt = at;
1437
1650
  out.lastRouting = routing;
1651
+ out.settledSinceObserveCents = 0;
1438
1652
  return { state: out, reason: 'baseline' };
1439
1653
  }
1440
1654
  if (out.lastBalanceCents === null || out.lastBalanceAt === 0) {
1441
1655
  out.lastBalanceCents = cents;
1442
1656
  out.lastBalanceAt = at;
1443
1657
  out.lastRouting = routing;
1658
+ out.settledSinceObserveCents = 0;
1444
1659
  return { state: out, reason: 'first' };
1445
1660
  }
1446
1661
  if (out.lastRouting !== routing) {
1447
1662
  out.lastBalanceCents = cents;
1448
1663
  out.lastBalanceAt = at;
1449
1664
  out.lastRouting = routing;
1665
+ out.settledSinceObserveCents = 0;
1450
1666
  return { state: out, reason: 'routing-switch' };
1451
1667
  }
1452
1668
  if (beijingDateKey(out.lastBalanceAt) !== beijingDateKey(at)) {
1453
1669
  out.lastBalanceCents = cents;
1454
1670
  out.lastBalanceAt = at;
1671
+ // 跨日不补记差额;同时清空待核对结算,避免把昨天的金额算进今天的差值。
1672
+ out.settledSinceObserveCents = 0;
1455
1673
  return { state: out, reason: 'cross-day' };
1456
1674
  }
1457
1675
  if (at - out.lastBalanceAt > MAX_OBSERVE_GAP_MS) {
1458
1676
  out.lastBalanceCents = cents;
1459
1677
  out.lastBalanceAt = at;
1678
+ out.settledSinceObserveCents = 0;
1460
1679
  return { state: out, reason: 'too-long' };
1461
1680
  }
1462
1681
 
@@ -1464,12 +1683,16 @@ function observeBalance(state, params) {
1464
1683
  let reason = 'none';
1465
1684
  if (diff > 0) {
1466
1685
  out.observedSpendTotalCents += diff;
1467
- const key = beijingDateKey(at);
1468
- out.dailySpendCents[key] = (out.dailySpendCents[key] || 0) + diff;
1686
+ // 已结算部分已计入「日用」,这里只补超出部分,避免同一轮被计两次。
1687
+ const extra = diff - out.settledSinceObserveCents;
1688
+ if (extra > 0) {
1689
+ const key = beijingDateKey(at);
1690
+ out.dailySpendCents[key] = (out.dailySpendCents[key] || 0) + extra;
1691
+ }
1692
+ out.settledSinceObserveCents = 0;
1469
1693
  reason = 'spend';
1470
1694
  } else if (diff < 0) {
1471
- out.pendingAdjustmentCents += -diff;
1472
- out.pendingAdjustmentAt = at;
1695
+ // 余额上升(充值 / 退货):只更新基准,不冲减消费,也不做手工校正。
1473
1696
  reason = 'adjust';
1474
1697
  }
1475
1698
  out.lastBalanceCents = cents;
@@ -1478,10 +1701,15 @@ function observeBalance(state, params) {
1478
1701
  }
1479
1702
 
1480
1703
  /** 元(数字或字符串)转分;非法返回 null。 */
1481
- function yuanToCents(value) {
1704
+ function yuanToCents(value, mode) {
1705
+ const truncate = mode === 'truncate';
1482
1706
  if (typeof value === 'number') {
1483
1707
  if (!Number.isFinite(value)) return null;
1484
- return Math.round(value * 100);
1708
+ // 数字先转十进制字符串再按分解析:避免 `5.99 * 100 = 598.999…` 的浮点误差把分差成 1。
1709
+ const asText = String(value);
1710
+ if (/^-?\d+(\.\d+)?$/.test(asText.trim())) return yuanToCents(asText, mode);
1711
+ // 科学计数法等无法逐位解析的极端值,退回浮点换算。
1712
+ return truncate && value >= 0 ? Math.floor(value * 100 + 1e-6) : Math.round(value * 100);
1485
1713
  }
1486
1714
  if (typeof value !== 'string') return null;
1487
1715
  const raw = value.trim().replace(/,/g, '');
@@ -1492,7 +1720,9 @@ function yuanToCents(value) {
1492
1720
  const whole = split[0];
1493
1721
  const frac = split[1] || '';
1494
1722
  let cents = Number(whole) * 100 + Number((frac + '00').slice(0, 2));
1495
- if (frac.length > 2 && Number(frac.charAt(2)) >= 5) cents += 1;
1723
+ // 官方「账号与余额」对正金额截断至分:原始余额字符串可能带三位以上小数,
1724
+ // 这里必须同样截断,否则 5.999… 会进位成 6.00,比官方页面多一分。
1725
+ if (frac.length > 2 && !(truncate && !negative) && Number(frac.charAt(2)) >= 5) cents += 1;
1496
1726
  return negative ? -cents : cents;
1497
1727
  }
1498
1728
 
@@ -1566,6 +1796,17 @@ function formatCostMicros(micros) {
1566
1796
  return formatYuanCents(Math.round(micros / 10000));
1567
1797
  }
1568
1798
 
1799
+ /**
1800
+ * 微元 -> 单条回答金额展示(保留 4 位小数,避免每轮几厘钱被舍成 0):
1801
+ * 0 → `¥0.0000`;0 < x < ¥0.0001 → `<¥0.0001`;其余四舍五入到 4 位。
1802
+ */
1803
+ function formatReplyCost(micros) {
1804
+ if (!Number.isFinite(micros)) return '';
1805
+ if (micros <= 0) return '¥0.0000';
1806
+ if (micros < 100) return '<¥0.0001';
1807
+ return '¥' + (micros / 1000000).toFixed(4);
1808
+ }
1809
+
1569
1810
  /** 自动关闭时刻:秒数 0 / 非法返回 null(不自动关闭);上限 600 秒。 */
1570
1811
  function autoCloseAt(firstSeenAt, seconds) {
1571
1812
  const s = typeof seconds === 'string' ? Number(seconds) : seconds;
@@ -1579,6 +1820,329 @@ function easeOutCubic(t) {
1579
1820
  return 1 - Math.pow(1 - x, 3);
1580
1821
  }
1581
1822
 
1823
+ // ---------------------------------------------------------------------------
1824
+ // 会话统计:从真实会话日志折叠 token / 成本 / 时间线(宿主与测试共用)
1825
+ // ---------------------------------------------------------------------------
1826
+
1827
+ /** 时间线桶数:小时视图 48 个(客户端展示最近 24 个),日视图 30 个。 */
1828
+ const STATS_HOURLY_BUCKETS = 48;
1829
+ const STATS_DAILY_BUCKETS = 30;
1830
+
1831
+ /** 四类 token 的空桶。 */
1832
+ function emptyStatsTokens() {
1833
+ return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
1834
+ }
1835
+
1836
+ /** 四类 token 合计。 */
1837
+ function statsTokenTotal(tokens) {
1838
+ const t = tokens || {};
1839
+ return tokenCount(t.input) + tokenCount(t.cacheRead) + tokenCount(t.cacheWrite) + tokenCount(t.output);
1840
+ }
1841
+
1842
+ /**
1843
+ * 原始 usage → 四类 token 桶。缺 input/output 计数时返回 null(该条不计入)。
1844
+ * 与费用统计共用 `normalizeCostUsage`,保证同一份日志得到同一组数字。
1845
+ */
1846
+ function statsUsageBuckets(usage) {
1847
+ const normalized = normalizeCostUsage(usage);
1848
+ if (!normalized) return null;
1849
+ return {
1850
+ input: normalized.inputTokens,
1851
+ cacheRead: normalized.cacheReadTokens,
1852
+ cacheWrite: normalized.cacheWriteTokens,
1853
+ output: normalized.outputTokens
1854
+ };
1855
+ }
1856
+
1857
+ /**
1858
+ * 单个时间点的估算成本(微元):按该点时刻的峰 / 谷价与当时模型价目计算,
1859
+ * 与费用卡片的「单次」共用 `turnCost`,因此两处口径一致。
1860
+ */
1861
+ function statsPointCostMicros(point) {
1862
+ if (!point) return 0;
1863
+ // 本地 / 未知来源的 token 照常统计,但成本记 0(不套用 DeepSeek 价目)。
1864
+ if (point.billable === false) return 0;
1865
+ const at = Number.isFinite(point.t) ? point.t : Date.now();
1866
+ const period = periodInfo(at).period;
1867
+ const usage = {
1868
+ inputTokens: tokenCount(point.input),
1869
+ cacheReadTokens: tokenCount(point.cacheRead),
1870
+ cacheWriteTokens: tokenCount(point.cacheWrite),
1871
+ outputTokens: tokenCount(point.output),
1872
+ reasoningTokens: 0
1873
+ };
1874
+ return turnCost(usage, point.model, period);
1875
+ }
1876
+
1877
+ /** 取目录的最后一段,作为无标题会话的兜底名称。 */
1878
+ function baseNameOfPath(value) {
1879
+ if (typeof value !== 'string' || value.length === 0) return '';
1880
+ const parts = value.split(/[\\/]/).filter(Boolean);
1881
+ return parts.length === 0 ? '' : parts[parts.length - 1];
1882
+ }
1883
+
1884
+ /**
1885
+ * 折叠一条会话日志:四类 token 汇总、时间线点(含计价时刻的模型)、
1886
+ * 标题 / 首个问题 / 模型与最后活跃时间。与宿主的 `tokenUsage` 投影口径一致:
1887
+ * 每个 assistant/message 的 usage 只取一次。
1888
+ * @param events 会话事件数组(读取日志得到的原始事件)
1889
+ */
1890
+ function foldSessionStats(events) {
1891
+ const list = Array.isArray(events) ? events : [];
1892
+ const tokens = emptyStatsTokens();
1893
+ const points = [];
1894
+ let title = '';
1895
+ let firstPrompt = '';
1896
+ let model = '';
1897
+ let provider = '';
1898
+ let currentModel = '';
1899
+ let lastActiveAt = 0;
1900
+ let turns = 0;
1901
+ let steps = 0;
1902
+ let messages = 0;
1903
+
1904
+ for (const event of list) {
1905
+ if (!event || typeof event.type !== 'string') continue;
1906
+ const time = Number.isFinite(event.time) ? event.time : 0;
1907
+ if (time > lastActiveAt) lastActiveAt = time;
1908
+ const data = event.data || {};
1909
+
1910
+ if (event.type === 'assistant/message') {
1911
+ messages += 1;
1912
+ if (Number.isSafeInteger(data.turn) && data.turn > turns) turns = data.turn;
1913
+ const route = routeOfMessage(data.message) || routeOfUsage(data.usage);
1914
+ if (route) {
1915
+ provider = route.provider;
1916
+ if (route.model) currentModel = route.model;
1917
+ }
1918
+ const buckets = statsUsageBuckets(data.usage);
1919
+ if (buckets) {
1920
+ const pointModel = currentModel || model;
1921
+ const point = {
1922
+ t: time,
1923
+ input: buckets.input,
1924
+ cacheRead: buckets.cacheRead,
1925
+ cacheWrite: buckets.cacheWrite,
1926
+ output: buckets.output,
1927
+ model: pointModel,
1928
+ // 只对 DeepSeek 官方路由计价;本地模型仍统计 token,但成本为 0。
1929
+ billable: isBillableRoute(provider, pointModel)
1930
+ };
1931
+ tokens.input += point.input;
1932
+ tokens.cacheRead += point.cacheRead;
1933
+ tokens.cacheWrite += point.cacheWrite;
1934
+ tokens.output += point.output;
1935
+ points.push(point);
1936
+ }
1937
+ continue;
1938
+ }
1939
+
1940
+ if (event.type === 'step/end') {
1941
+ steps += 1;
1942
+ continue;
1943
+ }
1944
+
1945
+ if (event.type === 'session/title') {
1946
+ if (typeof data.title === 'string' && data.title.trim()) title = data.title.trim();
1947
+ continue;
1948
+ }
1949
+
1950
+ if (event.type === 'request/header') {
1951
+ const config = data.header && data.header.config;
1952
+ if (config && typeof config === 'object') {
1953
+ if (typeof config.model === 'string' && config.model) {
1954
+ model = config.model;
1955
+ currentModel = config.model;
1956
+ }
1957
+ if (typeof config.provider === 'string' && config.provider) provider = config.provider;
1958
+ }
1959
+ continue;
1960
+ }
1961
+
1962
+ if (event.type === 'user/message' && !firstPrompt) {
1963
+ // 会话日志两种历史形状都兼容:data.message.content 或 data.content。
1964
+ const message = data.message && typeof data.message === 'object' ? data.message : data;
1965
+ const text = contentText(message.content).replace(/\s+/g, ' ').trim();
1966
+ if (text) firstPrompt = text.length > 80 ? text.slice(0, 80) + '…' : text;
1967
+ }
1968
+ }
1969
+
1970
+ return { tokens, points, title, firstPrompt, model, provider, lastActiveAt, turns, steps, messages };
1971
+ }
1972
+
1973
+ /** 本地时间的小时起点。 */
1974
+ function statsFloorHour(ts) {
1975
+ const date = new Date(ts);
1976
+ date.setMinutes(0, 0, 0);
1977
+ return date.getTime();
1978
+ }
1979
+
1980
+ /** 本地时间的日起点。 */
1981
+ function statsFloorDay(ts) {
1982
+ const date = new Date(ts);
1983
+ date.setHours(0, 0, 0, 0);
1984
+ return date.getTime();
1985
+ }
1986
+
1987
+ /** 以 `now` 为终点、向过去生成连续桶起点(旧 → 新)。 */
1988
+ function statsBucketStarts(now, count, unit) {
1989
+ const total = Number.isSafeInteger(count) && count > 0 ? count : 1;
1990
+ const starts = [];
1991
+ const cursor = new Date(unit === 'hour' ? statsFloorHour(now) : statsFloorDay(now));
1992
+ for (let index = 0; index < total; index += 1) {
1993
+ starts.push(cursor.getTime());
1994
+ if (unit === 'hour') cursor.setHours(cursor.getHours() - 1);
1995
+ else cursor.setDate(cursor.getDate() - 1);
1996
+ }
1997
+ return starts.reverse();
1998
+ }
1999
+
2000
+ /** 把时间点聚合成桶(含 token 合计与成本合计,微元)。 */
2001
+ function statsAggregate(points, starts, unit) {
2002
+ const list = starts || [];
2003
+ const buckets = list.map((t) => ({
2004
+ t,
2005
+ ...emptyStatsTokens(),
2006
+ tokens: 0,
2007
+ billableTokens: 0,
2008
+ localTokens: 0,
2009
+ costMicros: 0
2010
+ }));
2011
+ const positionOf = new Map();
2012
+ buckets.forEach((bucket, index) => positionOf.set(bucket.t, index));
2013
+ for (const point of points || []) {
2014
+ if (!point || !Number.isFinite(point.t)) continue;
2015
+ const start = unit === 'hour' ? statsFloorHour(point.t) : statsFloorDay(point.t);
2016
+ const position = positionOf.get(start);
2017
+ if (position === undefined) continue;
2018
+ const bucket = buckets[position];
2019
+ bucket.input += tokenCount(point.input);
2020
+ bucket.cacheRead += tokenCount(point.cacheRead);
2021
+ bucket.cacheWrite += tokenCount(point.cacheWrite);
2022
+ bucket.output += tokenCount(point.output);
2023
+ const pointTokens = tokenCount(point.input) + tokenCount(point.cacheRead) +
2024
+ tokenCount(point.cacheWrite) + tokenCount(point.output);
2025
+ bucket.tokens += pointTokens;
2026
+ if (point.billable === false) bucket.localTokens += pointTokens;
2027
+ else bucket.billableTokens += pointTokens;
2028
+ bucket.costMicros += statsPointCostMicros(point);
2029
+ }
2030
+ return buckets;
2031
+ }
2032
+
2033
+ /** 小时 / 日两条时间线(宿主一次性算好,客户端只切换显示)。 */
2034
+ function statsTimeline(points, now) {
2035
+ const at = Number.isFinite(now) ? now : Date.now();
2036
+ return {
2037
+ hourly: statsAggregate(points, statsBucketStarts(at, STATS_HOURLY_BUCKETS, 'hour'), 'hour'),
2038
+ daily: statsAggregate(points, statsBucketStarts(at, STATS_DAILY_BUCKETS, 'day'), 'day')
2039
+ };
2040
+ }
2041
+
2042
+ /** 会话行(供表格与汇总;纯函数便于离线断言)。 */
2043
+ function statsSessionRow(header, fold, options) {
2044
+ const h = header && typeof header === 'object' ? header : {};
2045
+ const f = fold && typeof fold === 'object' ? fold : {};
2046
+ const opt = options || {};
2047
+ const source = f.tokens && typeof f.tokens === 'object' ? f.tokens : emptyStatsTokens();
2048
+ const tokens = {
2049
+ input: tokenCount(source.input),
2050
+ cacheRead: tokenCount(source.cacheRead),
2051
+ cacheWrite: tokenCount(source.cacheWrite),
2052
+ output: tokenCount(source.output)
2053
+ };
2054
+ const total = statsTokenTotal(tokens);
2055
+ let costMicros = 0;
2056
+ let billableTokens = 0;
2057
+ let localTokens = 0;
2058
+ for (const point of Array.isArray(f.points) ? f.points : []) {
2059
+ if (!point) continue;
2060
+ const pointTokens = tokenCount(point.input) + tokenCount(point.cacheRead) +
2061
+ tokenCount(point.cacheWrite) + tokenCount(point.output);
2062
+ if (point.billable === false) localTokens += pointTokens;
2063
+ else billableTokens += pointTokens;
2064
+ costMicros += statsPointCostMicros(point);
2065
+ }
2066
+ const id = typeof h.id === 'string' ? h.id : '';
2067
+ return {
2068
+ id,
2069
+ title: f.title || f.firstPrompt || baseNameOfPath(h.cwd) || id,
2070
+ cwd: typeof h.cwd === 'string' ? h.cwd : '',
2071
+ createdAt: Number.isFinite(h.createdAt) ? h.createdAt : 0,
2072
+ lastActiveAt: Number.isFinite(f.lastActiveAt) ? f.lastActiveAt : 0,
2073
+ model: f.model || '',
2074
+ provider: f.provider || '',
2075
+ turns: Number.isSafeInteger(f.turns) ? f.turns : 0,
2076
+ steps: Number.isSafeInteger(f.steps) ? f.steps : 0,
2077
+ messages: Number.isSafeInteger(f.messages) ? f.messages : 0,
2078
+ tokens: { ...tokens, total },
2079
+ billableTokens,
2080
+ localTokens,
2081
+ /** 该会话是否有任何 DeepSeek 计费用量(用于会话表「本地 · 不计费」展示)。 */
2082
+ billable: billableTokens > 0,
2083
+ costMicros,
2084
+ running: opt.running === true,
2085
+ live: opt.live === true,
2086
+ subagent: h.origin === 'subagent'
2087
+ };
2088
+ }
2089
+
2090
+ /** 汇总多行:四类 token、成本、会话数、运行中数量与轮 / step / 消息数。 */
2091
+ function statsSummary(rows) {
2092
+ const list = Array.isArray(rows) ? rows : [];
2093
+ const tokens = emptyStatsTokens();
2094
+ let costMicros = 0;
2095
+ let billableTokens = 0;
2096
+ let localTokens = 0;
2097
+ let running = 0;
2098
+ let turns = 0;
2099
+ let steps = 0;
2100
+ let messages = 0;
2101
+ for (const row of list) {
2102
+ if (!row) continue;
2103
+ const source = row.tokens || {};
2104
+ tokens.input += tokenCount(source.input);
2105
+ tokens.cacheRead += tokenCount(source.cacheRead);
2106
+ tokens.cacheWrite += tokenCount(source.cacheWrite);
2107
+ tokens.output += tokenCount(source.output);
2108
+ costMicros += Number.isFinite(row.costMicros) ? Math.max(0, Math.round(row.costMicros)) : 0;
2109
+ billableTokens += Number.isFinite(row.billableTokens) ? Math.max(0, row.billableTokens) : 0;
2110
+ localTokens += Number.isFinite(row.localTokens) ? Math.max(0, row.localTokens) : 0;
2111
+ turns += Number.isSafeInteger(row.turns) ? row.turns : 0;
2112
+ steps += Number.isSafeInteger(row.steps) ? row.steps : 0;
2113
+ messages += Number.isSafeInteger(row.messages) ? row.messages : 0;
2114
+ if (row.running === true) running += 1;
2115
+ }
2116
+ return {
2117
+ tokens: { ...tokens, total: statsTokenTotal(tokens) },
2118
+ billableTokens,
2119
+ localTokens,
2120
+ costMicros,
2121
+ sessions: list.length,
2122
+ running,
2123
+ turns,
2124
+ steps,
2125
+ messages
2126
+ };
2127
+ }
2128
+
2129
+ /**
2130
+ * 预算视图:金额为分(人民币,与费用卡片币种一致)。
2131
+ * budgetCents 为 0 视为未设预算(enabled=false,比例不显示)。
2132
+ */
2133
+ function statsBudget(spentMicros, budgetCents) {
2134
+ const amountCents = Number.isFinite(budgetCents) && budgetCents > 0 ? Math.round(budgetCents) : 0;
2135
+ const spentCents = Number.isFinite(spentMicros) ? Math.max(0, Math.round(spentMicros / 10000)) : 0;
2136
+ const enabled = amountCents > 0;
2137
+ return {
2138
+ amountCents,
2139
+ spentCents,
2140
+ remainingCents: enabled ? Math.max(0, amountCents - spentCents) : 0,
2141
+ ratio: enabled ? spentCents / amountCents : 0,
2142
+ enabled
2143
+ };
2144
+ }
2145
+
1582
2146
  // ---------------------------------------------------------------------------
1583
2147
  // 工具函数
1584
2148
  // ---------------------------------------------------------------------------
@@ -1687,10 +2251,12 @@ const CSS = `
1687
2251
  .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
2252
  [data-dma-hidden="1"]{display:none!important}
1689
2253
  [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}
2254
+ .dma-overlay{position:fixed;inset:0;z-index:2147483000;background:var(--dsw-alias-bg-mask-1,rgba(0,0,0,.45));display:grid;place-items:center;padding:16px;overflow:auto}
2255
+ .dma-panel{width:min(680px,calc(100vw - 48px));max-height:calc(100vh - 32px);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)}
2256
+ .dma-confirm{width:min(420px,calc(100vw - 48px))}
2257
+ @media (max-width:480px){.dma-confirm{width:calc(100vw - 32px)}.dma-panel-foot{gap:8px}.dma-panel-foot .dma-btn{padding:0 12px}}
2258
+ .dma-panel-head{flex:none;padding:16px 20px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1));font-size:16px;font-weight:600}
2259
+ .dma-panel-body{flex:1 1 auto;min-height:0;overflow:auto;padding:12px 16px}
1694
2260
  .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
2261
  .dma-round:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04))}
1696
2262
  .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}
@@ -1704,7 +2270,7 @@ const CSS = `
1704
2270
  .dma-round-tag-a{color:var(--dsw-alias-label-tertiary,#8a919e)}
1705
2271
  .dma-round-a{color:var(--dsw-alias-label-secondary,#5b6472)}
1706
2272
  .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))}
2273
+ .dma-panel-foot{flex:none;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
2274
  .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
2275
  .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
2276
  .dma-panel-foot .dma-primary.dma-danger{background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}
@@ -1722,6 +2288,8 @@ module.exports = {
1722
2288
  TOMBSTONE_TEXT,
1723
2289
  ERROR_LABELS,
1724
2290
  contentText,
2291
+ refillTextOf,
2292
+ attachmentsOfEvent,
1725
2293
  textOf,
1726
2294
  messageRoleOf,
1727
2295
  messageIdOf,
@@ -1790,7 +2358,19 @@ module.exports = {
1790
2358
  routeOfMessage,
1791
2359
  routeOfUsage,
1792
2360
  routingOfProvider,
2361
+ isDeepseekModel,
2362
+ isBillableRoute,
1793
2363
  costSwitches,
2364
+ completionSoundEnabled,
2365
+ SOUND_TONES,
2366
+ DEFAULT_SOUND_TONE,
2367
+ normalizeSoundTone,
2368
+ completionSoundTone,
2369
+ soundToneOptions,
2370
+ DEFAULT_SOUND_VOLUME,
2371
+ clampSoundVolume,
2372
+ soundGainScale,
2373
+ shouldPlayCompletionSound,
1794
2374
  COST_LAYOUTS,
1795
2375
  DEFAULT_COST_LAYOUT,
1796
2376
  normalizeCostLayout,
@@ -1799,24 +2379,40 @@ module.exports = {
1799
2379
  deriveTurnUsage,
1800
2380
  createTurnBuffer,
1801
2381
  appendTurnEvent,
1802
- correctedBalanceCents,
1803
2382
  observeBalance,
2383
+ settleSpend,
1804
2384
  yuanToCents,
1805
2385
  validateCorrectionAmount,
1806
2386
  pruneDailySpend,
1807
2387
  formatCents,
1808
2388
  formatYuanCents,
1809
2389
  formatCostMicros,
2390
+ formatReplyCost,
1810
2391
  autoCloseAt,
1811
2392
  easeOutCubic,
2393
+ STATS_HOURLY_BUCKETS,
2394
+ STATS_DAILY_BUCKETS,
2395
+ emptyStatsTokens,
2396
+ statsTokenTotal,
2397
+ statsUsageBuckets,
2398
+ statsPointCostMicros,
2399
+ foldSessionStats,
2400
+ statsFloorHour,
2401
+ statsFloorDay,
2402
+ statsBucketStarts,
2403
+ statsAggregate,
2404
+ statsTimeline,
2405
+ statsSessionRow,
2406
+ statsSummary,
2407
+ statsBudget,
1812
2408
  ICONS,
1813
2409
  CSS
1814
2410
  };
1815
2411
  return module.exports;
1816
2412
  })();
1817
- const BUILD = "2026-11-03T09:14:46.153Z";
2413
+ const BUILD = "2026-11-07T10:32:59.412Z";
1818
2414
  // 构建时由 build.mjs 用 package.json 的 version 替换,避免设置页显示旧版本。
1819
- const VERSION = "0.2.1";
2415
+ const VERSION = "0.2.3";
1820
2416
 
1821
2417
  if (typeof console !== "undefined" && typeof console.info === "function") {
1822
2418
  console.info("[dsh-message-actions] build", BUILD);
@@ -1834,6 +2430,14 @@ return module.exports;
1834
2430
  findToolRowByCallId,
1835
2431
  resolveKeyAction,
1836
2432
  mergeMessageSummary,
2433
+ completionSoundEnabled,
2434
+ normalizeSoundTone,
2435
+ completionSoundTone,
2436
+ soundToneOptions,
2437
+ DEFAULT_SOUND_VOLUME,
2438
+ clampSoundVolume,
2439
+ soundGainScale,
2440
+ shouldPlayCompletionSound,
1837
2441
  formatTokens,
1838
2442
  railTurnOfAttributes,
1839
2443
  createScheduler,
@@ -1841,6 +2445,7 @@ return module.exports;
1841
2445
  formatCents,
1842
2446
  formatYuanCents,
1843
2447
  formatCostMicros,
2448
+ formatReplyCost,
1844
2449
  periodInfo,
1845
2450
  periodChangeText,
1846
2451
  autoCloseAt,
@@ -1872,12 +2477,12 @@ const exports = module.exports;
1872
2477
 
1873
2478
  const meta = {
1874
2479
  zh: {
1875
- title: '消息费用',
1876
- description: '撤回、删除、删至末尾;多选分享与导出对话;回答统计;DeepSeek 账户余额、日用与单次费用统计。'
2480
+ title: 'dsh-message-actions',
2481
+ description: '对话完成声音提示;每条回答的 token、字数与费用;单次花费、统计表、预算与余额;撤回、删除、删至末尾;多选分享与导出对话。'
1877
2482
  },
1878
2483
  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.'
2484
+ title: 'dsh-message-actions',
2485
+ description: 'Completion sound; per-reply tokens, words, and cost; per-turn spend, stats panel, budget, and balance; recall, delete, and delete-to-end; multi-select share and export.'
1881
2486
  }
1882
2487
  };
1883
2488
 
@@ -1928,11 +2533,20 @@ const zh = {
1928
2533
  'settings.confirmDesc': '撤回/删除前弹出确认框;关闭后直接执行',
1929
2534
  'settings.stats': '回答统计',
1930
2535
  'settings.statsDesc': '答行显示本次回答的 tokens 与字数',
2536
+ 'settings.soundTone': '提示音音色',
2537
+ 'settings.soundToneDesc': '选中即开启并试听;选「关闭」即关闭完成提示音',
2538
+ 'settings.soundTone.double': '默认双音',
2539
+ 'settings.soundTone.bell': '短铃',
2540
+ 'settings.soundTone.soft': '轻提示',
2541
+ 'settings.soundTone.off': '关闭',
2542
+ 'settings.soundVolume': '音量',
2543
+ 'settings.soundVolumeDesc': '作用于全部音色:0% 静音,50% 为标准音量,100% 为两倍',
1931
2544
  'settings.soon': '即将推出',
1932
2545
  'settings.saveFailed': '无法保存设置',
1933
2546
  'cost.tab.actions': '消息操作',
1934
2547
  'cost.tab.billing': '费用统计',
1935
2548
  'cost.balance': '余额',
2549
+ 'cost.bonusHint': '含赠金 {bonus}',
1936
2550
  'cost.daily': '日用',
1937
2551
  'cost.perTurn': '单次',
1938
2552
  'cost.peak': '高峰价',
@@ -1940,8 +2554,6 @@ const zh = {
1940
2554
  'cost.title': '费用统计卡片',
1941
2555
  'cost.refresh': '刷新余额',
1942
2556
  'cost.refreshing': '正在刷新余额',
1943
- 'cost.pending': '待核对',
1944
- 'cost.pendingTitle': '余额有增加,请到 设置 → 消息费用 → 费用统计 → 余额校正 核对',
1945
2557
  'cost.signedOut': '未登录',
1946
2558
  'cost.apiKey': 'API key',
1947
2559
  'cost.unavailable': '不可用',
@@ -1962,18 +2574,79 @@ const zh = {
1962
2574
  'cost.settings.layoutDesc': '单行样式去背景、所有数字排成一行;多行样式带背景卡片与峰谷文字行',
1963
2575
  'cost.layout.default': '多行样式',
1964
2576
  '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': '「单次」按官方价目换算,「日用」按账户额度实际下降观测;两者口径不同,不要求逐轮对齐。'
2577
+ 'cost.balanceNote': '余额直接读取 DeepSeek 账户的可用总余额(充值余额 + 赠金钱包,逐钱包按官方规则截断至分;赠金已并入主数字,悬停提示给出拆分)。「日用」按同一总额的实际下降观测,「单次」按官方价目换算,两者口径不同,不要求逐轮对齐。',
2578
+ 'cost.settings.statsTable': '统计表',
2579
+ 'cost.settings.statsTableDesc': '查看 Token 用量、消耗时间线与各会话成本',
2580
+ 'cost.settings.statsTableButton': '打开统计表',
2581
+ 'stats.entry': '统计表',
2582
+ 'stats.entryTitle': '统计表',
2583
+ 'stats.panelTitle': '统计表',
2584
+ 'stats.intro': '数据来自本机真实会话日志;估算成本与费用卡片使用同一价目与峰谷规则。仅 DeepSeek 官方模型计费,本地模型只统计 token。',
2585
+ 'stats.refresh': '刷新',
2586
+ 'stats.close': '关闭',
2587
+ 'stats.loading': '正在读取会话日志…',
2588
+ 'stats.error': '读取失败',
2589
+ 'stats.stale': '沿用上次数据',
2590
+ 'stats.unavailable': '宿主没有提供会话查询服务,暂时无法统计',
2591
+ 'stats.totalTokens': '总 Token 消耗',
2592
+ 'stats.sessions': '会话数量',
2593
+ 'stats.estCost': '估算成本',
2594
+ 'stats.budget': '预算使用',
2595
+ 'stats.cacheShare': '缓存命中',
2596
+ 'stats.runningNow': '运行中',
2597
+ 'stats.priceHint': '仅 DeepSeek 计费 · 官方价目',
2598
+ 'stats.budgetOff': '未设预算',
2599
+ 'stats.budgetLeft': '剩余',
2600
+ 'stats.overBudget': '已超预算',
2601
+ 'stats.of': ' / ',
2602
+ 'stats.timeline': 'Token 消耗时间线',
2603
+ 'stats.range24': '近 24 小时',
2604
+ 'stats.range30': '近 30 天',
2605
+ 'stats.input': '输入',
2606
+ 'stats.cacheRead': '缓存命中',
2607
+ 'stats.cacheWrite': '缓存写入',
2608
+ 'stats.output': '输出',
2609
+ 'stats.peak': '峰值',
2610
+ 'stats.total': '合计',
2611
+ 'stats.sessionsSection': '各会话用量',
2612
+ 'stats.colSession': '会话',
2613
+ 'stats.colTokens': 'Tokens',
2614
+ 'stats.colCost': '成本',
2615
+ 'stats.colUpdated': '更新时间',
2616
+ 'stats.empty': '还没有可统计的会话',
2617
+ 'stats.truncated': '仅显示用量最多的 100 个会话',
2618
+ 'stats.ledger': '对照:费用卡片 日用 {daily} · 累计观测 {observed}',
2619
+ 'stats.budgetEdit': '预算',
2620
+ 'stats.budgetUnit': '元',
2621
+ 'stats.budgetSave': '保存',
2622
+ 'stats.budgetSaving': '保存中…',
2623
+ 'stats.budgetHint': '按全部会话估算成本;填 0 隐藏占比',
2624
+ 'stats.budgetNote': '预算只用于计算「预算使用」占比与剩余额度,用来提示本期花了多少;不参与计费,也不影响余额与单次换算。默认 ¥5,填 0 只显示估算成本。',
2625
+ 'stats.budgetUsed': '已用',
2626
+ 'stats.budgetCancel': '取消',
2627
+ 'stats.moneyBudget': '预算',
2628
+ 'stats.moneyBalanceSub': '账户总余额(含赠金)',
2629
+ 'stats.moneyDailySub': '今日累计',
2630
+ 'stats.moneyTurnSub': '最近一轮',
2631
+ 'stats.moneyEdit': '修改预算',
2632
+ 'stats.budgetOffSub': '仅提示花费,不计费',
2633
+ 'stats.budgetInvalid': '预算金额不合法:最多两位小数、≥ 0',
2634
+ 'stats.budgetFailed': '保存失败,请稍后再试',
2635
+ 'stats.localCost': '本地',
2636
+ 'stats.replyCostTitle': '本条回答估算 {cost};同一轮的合计见侧边栏「单次」',
2637
+ 'stats.localTag': '本地 · 不计费',
2638
+ 'stats.billingLegend': '计费口径',
2639
+ 'stats.billingDeepseek': 'DeepSeek 计费',
2640
+ 'stats.billingLocal': '本地 · 不计费',
2641
+ 'stats.billingNote': '仅 DeepSeek 官方模型计费;本地模型只统计 token,不计入估算成本、预算使用与日用。',
2642
+ 'stats.running': '运行中',
2643
+ 'stats.subagent': '子会话',
2644
+ 'stats.noModel': '未知模型',
2645
+ 'stats.live': '实时',
2646
+ 'stats.now': '刚刚',
2647
+ 'stats.minutesAgo': '{n} 分钟前',
2648
+ 'stats.hoursAgo': '{n} 小时前',
2649
+ 'stats.daysAgo': '{n} 天前'
1977
2650
  };
1978
2651
 
1979
2652
  const en = {
@@ -2023,11 +2696,20 @@ const en = {
2023
2696
  'settings.confirmDesc': 'Ask before recall/delete; when off, actions run immediately',
2024
2697
  'settings.stats': 'Reply statistics',
2025
2698
  'settings.statsDesc': 'Show tokens and character count on reply rows',
2699
+ 'settings.soundTone': 'Sound tone',
2700
+ 'settings.soundToneDesc': 'Picking a tone turns it on and previews it; "Off" turns the completion sound off',
2701
+ 'settings.soundTone.double': 'Default double',
2702
+ 'settings.soundTone.bell': 'Bell',
2703
+ 'settings.soundTone.soft': 'Soft',
2704
+ 'settings.soundTone.off': 'Off',
2705
+ 'settings.soundVolume': 'Volume',
2706
+ 'settings.soundVolumeDesc': 'Applies to all tones: 0% mutes, 50% is normal, 100% is double',
2026
2707
  'settings.soon': 'Coming soon',
2027
2708
  'settings.saveFailed': 'Could not save the setting',
2028
2709
  'cost.tab.actions': 'Message Actions',
2029
2710
  'cost.tab.billing': 'Cost Statistics',
2030
2711
  'cost.balance': 'Bal',
2712
+ 'cost.bonusHint': 'incl. bonus {bonus}',
2031
2713
  'cost.daily': 'Today',
2032
2714
  'cost.perTurn': 'Turn',
2033
2715
  'cost.peak': 'Peak',
@@ -2035,8 +2717,6 @@ const en = {
2035
2717
  'cost.title': 'Cost statistics card',
2036
2718
  'cost.refresh': 'Refresh balance',
2037
2719
  'cost.refreshing': 'Refreshing balance',
2038
- 'cost.pending': 'Check',
2039
- 'cost.pendingTitle': 'Balance increased. Review it in Settings → Messages & Cost → Cost Statistics → Balance correction.',
2040
2720
  'cost.signedOut': 'Signed out',
2041
2721
  'cost.apiKey': 'API key',
2042
2722
  'cost.unavailable': 'Unavailable',
@@ -2057,18 +2737,79 @@ const en = {
2057
2737
  '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
2738
  'cost.layout.default': 'Multi-line',
2059
2739
  '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.'
2740
+ 'cost.balanceNote': 'Balance is the DeepSeek account total available balance (recharge wallets + bonus wallets, each truncated to the cent like the official page; bonus is merged into the main figure and broken out on hover). "Today" observes drops in that same total; "Turn" is converted from official list prices — different bases, so they need not match turn by turn.',
2741
+ 'cost.settings.statsTable': 'Stats table',
2742
+ 'cost.settings.statsTableDesc': 'Token usage, usage timeline and per-session cost',
2743
+ 'cost.settings.statsTableButton': 'Open stats table',
2744
+ 'stats.entry': 'Statistics',
2745
+ 'stats.entryTitle': 'Statistics',
2746
+ 'stats.panelTitle': 'Statistics',
2747
+ 'stats.intro': 'Built from real local session logs; estimates share the same prices and peak/off-peak rules as the cost card. Only official DeepSeek models are billed; local models count tokens only.',
2748
+ 'stats.refresh': 'Refresh',
2749
+ 'stats.close': 'Close',
2750
+ 'stats.loading': 'Reading session logs…',
2751
+ 'stats.error': 'Could not load',
2752
+ 'stats.stale': 'Showing stale data',
2753
+ 'stats.unavailable': 'The host does not expose a session query service',
2754
+ 'stats.totalTokens': 'Total tokens',
2755
+ 'stats.sessions': 'Sessions',
2756
+ 'stats.estCost': 'Estimated cost',
2757
+ 'stats.budget': 'Budget used',
2758
+ 'stats.cacheShare': 'Cache hit',
2759
+ 'stats.runningNow': 'Running',
2760
+ 'stats.priceHint': 'DeepSeek only · list prices',
2761
+ 'stats.budgetOff': 'No budget',
2762
+ 'stats.budgetLeft': 'Remaining',
2763
+ 'stats.overBudget': 'Over budget',
2764
+ 'stats.of': ' of ',
2765
+ 'stats.timeline': 'Token usage timeline',
2766
+ 'stats.range24': 'Last 24 hours',
2767
+ 'stats.range30': 'Last 30 days',
2768
+ 'stats.input': 'Input',
2769
+ 'stats.cacheRead': 'Cache hit',
2770
+ 'stats.cacheWrite': 'Cache write',
2771
+ 'stats.output': 'Output',
2772
+ 'stats.peak': 'Peak',
2773
+ 'stats.total': 'Total',
2774
+ 'stats.sessionsSection': 'Usage by session',
2775
+ 'stats.colSession': 'Session',
2776
+ 'stats.colTokens': 'Tokens',
2777
+ 'stats.colCost': 'Cost',
2778
+ 'stats.colUpdated': 'Updated',
2779
+ 'stats.empty': 'No sessions to summarize yet',
2780
+ 'stats.truncated': 'Showing the 100 sessions with the most usage',
2781
+ 'stats.ledger': 'Cross-check: card today {daily} · observed total {observed}',
2782
+ 'stats.budgetEdit': 'Budget',
2783
+ 'stats.budgetUnit': 'CNY',
2784
+ 'stats.budgetSave': 'Save',
2785
+ 'stats.budgetSaving': 'Saving…',
2786
+ 'stats.budgetHint': 'All sessions; 0 hides the ratio',
2787
+ 'stats.budgetNote': 'The budget only computes the "budget used" ratio and remaining allowance as a spending hint. It never bills you and does not affect the balance or per-turn figures. Default ¥5; 0 shows only the estimated cost.',
2788
+ 'stats.budgetUsed': 'used',
2789
+ 'stats.budgetCancel': 'Cancel',
2790
+ 'stats.moneyBudget': 'Budget',
2791
+ 'stats.moneyBalanceSub': 'Total balance (incl. bonus)',
2792
+ 'stats.moneyDailySub': 'Since midnight',
2793
+ 'stats.moneyTurnSub': 'Latest turn',
2794
+ 'stats.moneyEdit': 'Edit budget',
2795
+ 'stats.budgetOffSub': 'Hint only, never billed',
2796
+ 'stats.budgetInvalid': 'Invalid budget: at most two decimals, ≥ 0',
2797
+ 'stats.budgetFailed': 'Could not save; try again later',
2798
+ 'stats.localCost': 'Local',
2799
+ 'stats.replyCostTitle': 'Estimated cost of this reply: {cost}; the turn total is shown as Last turn in the sidebar.',
2800
+ 'stats.localTag': 'Local · unbilled',
2801
+ 'stats.billingLegend': 'Billing scope',
2802
+ 'stats.billingDeepseek': 'DeepSeek billed',
2803
+ 'stats.billingLocal': 'Local · unbilled',
2804
+ 'stats.billingNote': 'Only official DeepSeek models are billed; local models count tokens but are excluded from estimated cost, budget usage and daily spend.',
2805
+ 'stats.running': 'Running',
2806
+ 'stats.subagent': 'Subagent',
2807
+ 'stats.noModel': 'Unknown model',
2808
+ 'stats.live': 'Live',
2809
+ 'stats.now': 'just now',
2810
+ 'stats.minutesAgo': '{n} min ago',
2811
+ 'stats.hoursAgo': '{n} h ago',
2812
+ 'stats.daysAgo': '{n} d ago'
2072
2813
  };
2073
2814
 
2074
2815
  module.exports = { meta, zh, en };
@@ -2282,6 +3023,167 @@ return module.exports;
2282
3023
  return snap.value.usageStats !== false;
2283
3024
  }
2284
3025
 
3026
+ let lastTurnAtApplied = null;
3027
+ let lastPlayedTurnAt = null;
3028
+ let audioCtx = null;
3029
+ let audioUnlockBound = false;
3030
+
3031
+ /** 提示音开关(默认 true);设置快照未就绪时按开启处理。 */
3032
+ function soundEnabledNow() {
3033
+ if (!costForm || typeof costForm.getSnapshot !== "function") return true;
3034
+ const snap = costForm.getSnapshot();
3035
+ if (!snap || snap.status !== "ready" || typeof snap.value !== "object" || !snap.value) return true;
3036
+ return completionSoundEnabled(snap.value);
3037
+ }
3038
+
3039
+ /** 当前音色(关闭时返回 'off');设置快照未就绪时按默认双音。 */
3040
+ function soundToneNow() {
3041
+ if (!costForm || typeof costForm.getSnapshot !== "function") return "double";
3042
+ const snap = costForm.getSnapshot();
3043
+ if (!snap || snap.status !== "ready" || typeof snap.value !== "object" || !snap.value) return "double";
3044
+ return completionSoundTone(snap.value);
3045
+ }
3046
+
3047
+ /** 当前音量(0–100,默认 50);设置快照未就绪时按默认值。 */
3048
+ function soundVolumeNow() {
3049
+ if (!costForm || typeof costForm.getSnapshot !== "function") return DEFAULT_SOUND_VOLUME;
3050
+ const snap = costForm.getSnapshot();
3051
+ if (!snap || snap.status !== "ready" || typeof snap.value !== "object" || !snap.value) {
3052
+ return DEFAULT_SOUND_VOLUME;
3053
+ }
3054
+ return clampSoundVolume(snap.value.soundVolume);
3055
+ }
3056
+
3057
+ /**
3058
+ * 创建 / 唤醒 AudioContext。浏览器要求一次用户手势后才能发声:
3059
+ * 模块加载时注册一次全局首次点击/按键监听,提前解锁,避免任务完成时才 resume 而错过。
3060
+ */
3061
+ function ensureAudio() {
3062
+ try {
3063
+ const Ctor = typeof window !== "undefined" ? window.AudioContext || window.webkitAudioContext : null;
3064
+ if (!Ctor) return null;
3065
+ if (!audioCtx) audioCtx = new Ctor();
3066
+ if (audioCtx.state !== "running" && typeof audioCtx.resume === "function") {
3067
+ audioCtx.resume().catch(() => {});
3068
+ }
3069
+ return audioCtx;
3070
+ } catch {
3071
+ return null;
3072
+ }
3073
+ }
3074
+
3075
+ function unlockAudio() {
3076
+ ensureAudio();
3077
+ }
3078
+
3079
+ function installAudioUnlock() {
3080
+ if (audioUnlockBound) return;
3081
+ if (typeof window === "undefined" || typeof window.addEventListener !== "function") return;
3082
+ audioUnlockBound = true;
3083
+ window.addEventListener("pointerdown", unlockAudio, { passive: true, capture: true });
3084
+ window.addEventListener("keydown", unlockAudio, { passive: true, capture: true });
3085
+ }
3086
+
3087
+ // 插件加载即挂载首次交互解锁:用户点任何按钮/发消息后再播放就不会被策略拦截。
3088
+ installAudioUnlock();
3089
+
3090
+ /**
3091
+ * 音色参数:按「双音 / 短铃 / 轻提示」给出频率与包络。
3092
+ * `gain` 是音量 50% 时的基准(0.12–0.18),实际峰值 = gain × soundGainScale(音量)。
3093
+ */
3094
+ const TONE_SPECS = {
3095
+ double: { gain: 0.18, notes: [{ freq: 880, at: 0, dur: 0.16, type: "sine" }, { freq: 660, at: 0.15, dur: 0.2, type: "sine" }] },
3096
+ bell: { gain: 0.16, notes: [{ freq: 1046, at: 0, dur: 0.1, type: "triangle" }, { freq: 784, at: 0.11, dur: 0.16, type: "triangle" }] },
3097
+ soft: { gain: 0.12, notes: [{ freq: 523, at: 0, dur: 0.24, type: "sine" }] }
3098
+ };
3099
+
3100
+ function emitTone(ctx, tone, volume) {
3101
+ const spec = TONE_SPECS[normalizeSoundTone(tone)];
3102
+ if (!spec) return false;
3103
+ const scale = soundGainScale(volume);
3104
+ // 0% 音量直接不发声,避免出现「静音档仍在响」。
3105
+ if (!(scale > 0)) return false;
3106
+ const now = ctx.currentTime;
3107
+ const body = Math.max(...spec.notes.map((note) => note.at + note.dur));
3108
+ const peak = Math.max(0.0001, spec.gain * scale);
3109
+ const gain = ctx.createGain();
3110
+ gain.gain.setValueAtTime(0.0001, now);
3111
+ gain.gain.exponentialRampToValueAtTime(peak, now + 0.03);
3112
+ gain.gain.exponentialRampToValueAtTime(0.0001, now + body);
3113
+ gain.connect(ctx.destination);
3114
+ for (const note of spec.notes) {
3115
+ const osc = ctx.createOscillator();
3116
+ osc.type = note.type;
3117
+ osc.frequency.setValueAtTime(note.freq, now + note.at);
3118
+ osc.connect(gain);
3119
+ osc.start(now + note.at);
3120
+ osc.stop(now + note.at + note.dur);
3121
+ }
3122
+ return true;
3123
+ }
3124
+
3125
+ /**
3126
+ * 播放完成提示音。挂起时 resume 后静默重试一次(不弹 toast):
3127
+ * 用户已交互过就一定能听到;仍被策略拦截则安静放弃。
3128
+ * @param tone 指定音色(试听用);省略时读设置快照。
3129
+ * @param volume 指定音量(试听用);省略时读设置快照。
3130
+ */
3131
+ function playCompletionSound(tone, volume) {
3132
+ const id = typeof tone === "string" ? tone : soundToneNow();
3133
+ if (id === "off") return false;
3134
+ const vol = Number.isFinite(volume) ? clampSoundVolume(volume) : soundVolumeNow();
3135
+ if (!(soundGainScale(vol) > 0)) return false;
3136
+ const ctx = ensureAudio();
3137
+ if (!ctx) return false;
3138
+ if (ctx.state !== "running") {
3139
+ const retry = () => {
3140
+ try {
3141
+ if (ctx.state === "running") emitTone(ctx, id, vol);
3142
+ } catch {
3143
+ /* 静默放弃 */
3144
+ }
3145
+ };
3146
+ if (typeof ctx.resume === "function") ctx.resume().then(retry).catch(() => {});
3147
+ return false;
3148
+ }
3149
+ try {
3150
+ return emitTone(ctx, id, vol);
3151
+ } catch {
3152
+ return false;
3153
+ }
3154
+ }
3155
+
3156
+ function perTurnNow() {
3157
+ if (!costForm || typeof costForm.getSnapshot !== "function") return true;
3158
+ const snap = costForm.getSnapshot();
3159
+ if (!snap || snap.status !== "ready" || typeof snap.value !== "object" || !snap.value) return true;
3160
+ return snap.value.costPerTurn !== false;
3161
+ }
3162
+
3163
+ /** 单次费用写明的那一刻判定提示音:同一状态更新里出数字、响一次。 */
3164
+ function maybeCompletionSound(value) {
3165
+ const turn = value && value.lastTurn ? value.lastTurn : null;
3166
+ const at = turn && Number.isFinite(turn.at) ? turn.at : null;
3167
+ if (at === null) return;
3168
+ const previousAt = lastTurnAtApplied;
3169
+ lastTurnAtApplied = at;
3170
+ if (previousAt === null) return; // 首次快照只记基线,刷新页面不补响
3171
+ if (!shouldPlayCompletionSound({
3172
+ enabled: costEnabledNow() && soundEnabledNow(),
3173
+ settled: true,
3174
+ previousAt,
3175
+ at,
3176
+ lastPlayedAt: lastPlayedTurnAt
3177
+ })) return;
3178
+ lastPlayedTurnAt = at;
3179
+ playCompletionSound();
3180
+ }
3181
+
3182
+ function applyCostState(value) {
3183
+ patchCostState({ status: "ready", value, fetchedAt: Date.now(), error: "" });
3184
+ maybeCompletionSound(value);
3185
+ }
3186
+
2285
3187
  async function fetchCostState(force) {
2286
3188
  try {
2287
3189
  const { status, data } = await getJson(
@@ -2289,7 +3191,7 @@ return module.exports;
2289
3191
  force ? "refresh=1" : undefined
2290
3192
  );
2291
3193
  if (status === 200 && data && data.ok && data.value) {
2292
- patchCostState({ status: "ready", value: data.value, fetchedAt: Date.now(), error: "" });
3194
+ applyCostState(data.value);
2293
3195
  return data.value;
2294
3196
  }
2295
3197
  patchCostState({ status: "error", error: "request" });
@@ -2305,6 +3207,39 @@ return module.exports;
2305
3207
  }
2306
3208
  }
2307
3209
 
3210
+ // 结算推送:带 wait=<已知 lastTurn.at> 的长轮询,宿主结算后立即返回。
3211
+ let costWaitTimer = null;
3212
+ let costWaitActive = false;
3213
+
3214
+ function costWaitStep() {
3215
+ costWaitTimer = null;
3216
+ if (!costPolling || !costWaitActive) return;
3217
+ if (typeof document !== "undefined" && document.hidden) {
3218
+ costWaitTimer = setTimeout(costWaitStep, 1500);
3219
+ return;
3220
+ }
3221
+ if (!costEnabledNow() || !perTurnNow()) {
3222
+ costWaitTimer = setTimeout(costWaitStep, 1500);
3223
+ return;
3224
+ }
3225
+ const wait = lastTurnAtApplied === null ? 0 : lastTurnAtApplied;
3226
+ getJson("/dsh-message-actions/cost/state", "wait=" + wait)
3227
+ .then(({ status, data }) => {
3228
+ if (!costPolling || !costWaitActive) return;
3229
+ if (status === 200 && data && data.ok && data.value) applyCostState(data.value);
3230
+ costWaitTimer = setTimeout(costWaitStep, 0);
3231
+ })
3232
+ .catch(() => {
3233
+ costWaitTimer = setTimeout(costWaitStep, 2000);
3234
+ });
3235
+ }
3236
+
3237
+ function startCostWaitLoop() {
3238
+ if (costWaitActive) return;
3239
+ costWaitActive = true;
3240
+ costWaitStep();
3241
+ }
3242
+
2308
3243
  function startCostPolling(form) {
2309
3244
  costForm = form;
2310
3245
  if (costPolling) return;
@@ -2316,6 +3251,7 @@ return module.exports;
2316
3251
  };
2317
3252
  tick();
2318
3253
  costPollTimer = setInterval(tick, COST_POLL_MS);
3254
+ startCostWaitLoop();
2319
3255
  if (typeof document !== "undefined" && !costVisibilityBound) {
2320
3256
  costVisibilityBound = true;
2321
3257
  document.addEventListener("visibilitychange", onCostVisibility);
@@ -2324,6 +3260,11 @@ return module.exports;
2324
3260
 
2325
3261
  function stopCostPolling() {
2326
3262
  costPolling = false;
3263
+ costWaitActive = false;
3264
+ if (costWaitTimer !== null) {
3265
+ clearTimeout(costWaitTimer);
3266
+ costWaitTimer = null;
3267
+ }
2327
3268
  if (costPollTimer !== null) {
2328
3269
  clearInterval(costPollTimer);
2329
3270
  costPollTimer = null;
@@ -2556,8 +3497,10 @@ return module.exports;
2556
3497
  // 工具行删除只遮蔽该工具节点,不影响同轮其它内容。
2557
3498
  applyHiddenTool(this.sessionId, opts.nodeKey);
2558
3499
  }
2559
- if (action === "recall" && value.refillText) {
2560
- refillComposer(this.sessionId, value.refillText);
3500
+ if (action === "recall") {
3501
+ if (value.refillText) refillComposer(this.sessionId, value.refillText);
3502
+ // 图片 / 文件:按附件 id 取回字节,交给官方输入框的 drop 通道恢复成真实附件。
3503
+ restoreRecallAttachments(this.sessionId, value.attachments).catch(() => {});
2561
3504
  }
2562
3505
  // 刷新消息快照(拿到最新 goneTurns),再重放导航隐藏。
2563
3506
  await this.fetchMessages(true).catch(() => {});
@@ -2627,6 +3570,49 @@ return module.exports;
2627
3570
  }
2628
3571
  }
2629
3572
 
3573
+ // 附件回读路由:撤回后按 id 取回字节(image 为宿主归一化后的图片)。
3574
+ const ATTACHMENT_PATH = "/dsh-message-actions/attachment";
3575
+
3576
+ /**
3577
+ * 撤回后恢复图片 / 文件附件。
3578
+ * 取回字节 -> 构造 File -> 在 document 上派发 drop 事件,
3579
+ * 交给官方输入框的 `onAddFiles`(createDrafts + addFiles)恢复成真实附件。
3580
+ * 无附件、环境不支持 DataTransfer 或全部取回失败时静默跳过。
3581
+ */
3582
+ async function restoreRecallAttachments(sessionId, attachments) {
3583
+ if (!Array.isArray(attachments) || attachments.length === 0) return;
3584
+ if (typeof document === "undefined" || typeof DataTransfer !== "function") return;
3585
+ const files = [];
3586
+ for (const meta of attachments) {
3587
+ if (!meta || typeof meta.attachmentId !== "string") continue;
3588
+ try {
3589
+ const query =
3590
+ "sessionId=" + encodeURIComponent(sessionId) +
3591
+ "&attachmentId=" + encodeURIComponent(meta.attachmentId);
3592
+ const res = await fetchWithTimeout(apiUrl(ATTACHMENT_PATH, query), { cache: "no-store" });
3593
+ if (!res.ok) continue;
3594
+ const blob = await res.blob();
3595
+ const name = typeof meta.name === "string" && meta.name.length > 0
3596
+ ? meta.name
3597
+ : (meta.kind === "image" ? "image.png" : "attachment");
3598
+ files.push(new File([blob], name, { type: meta.mediaType || blob.type || "" }));
3599
+ } catch {
3600
+ /* 单个附件失败不影响其它附件 */
3601
+ }
3602
+ }
3603
+ if (files.length === 0) return;
3604
+ const transfer = new DataTransfer();
3605
+ for (const file of files) transfer.items.add(file);
3606
+ let event;
3607
+ try {
3608
+ event = new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: transfer });
3609
+ } catch {
3610
+ event = new Event("drop", { bubbles: true, cancelable: true });
3611
+ Object.defineProperty(event, "dataTransfer", { value: transfer });
3612
+ }
3613
+ document.dispatchEvent(event);
3614
+ }
3615
+
2630
3616
  // -------------------------------------------------------------------------
2631
3617
  // 问行按钮 DOM 注入
2632
3618
  // -------------------------------------------------------------------------
@@ -3188,14 +4174,22 @@ return module.exports;
3188
4174
  if (config && config.stats === false) return null;
3189
4175
  if (!row || words === 0) return null;
3190
4176
 
4177
+ // 单条回答金额:只认该条自己的 usage(服务端已算好 costMicros),
4178
+ // 中间步骤没有 usage 时不拿同轮其它回答的金额兜底,避免重复计价。
4179
+ const replyCost = row && Number.isFinite(row.costMicros)
4180
+ ? (row.billable === false ? tt("stats.localCost") : formatReplyCost(row.costMicros))
4181
+ : null;
4182
+
3191
4183
  const label = [
3192
4184
  tokens == null ? null : formatTokens(tokens) + " tok",
3193
- words + " " + tt("stats.unit")
4185
+ words + " " + tt("stats.unit"),
4186
+ replyCost
3194
4187
  ].filter(Boolean).join(" \u00b7 ");
3195
4188
 
3196
4189
  return e("span", {
3197
4190
  className: "dma-stats",
3198
- title: tt("stats.title", { tokens: tokens == null ? "?" : tokens, words })
4191
+ title: tt("stats.title", { tokens: tokens == null ? "?" : tokens, words }) +
4192
+ (replyCost ? " \u00b7 " + tt("stats.replyCostTitle", { cost: replyCost }) : "")
3199
4193
  }, label);
3200
4194
  }
3201
4195
 
@@ -3270,7 +4264,26 @@ return module.exports;
3270
4264
  ));
3271
4265
  }
3272
4266
 
3273
- // 确认弹窗 + 分享/导出浮层控制器(input.overlay 槽位)
4267
+ /**
4268
+ * 确认框与分享/导出面板的唯一挂载路径。
4269
+ * 新版宿主会给输入区容器加 `will-change: transform`,使 `position:fixed`
4270
+ * 的包含块变成输入区而不是视口;portal 到 document.body 可彻底脱离该容器,
4271
+ * 同时不受其 `overflow:hidden` 裁剪。
4272
+ * 拿不到 createPortal / body 时原样返回,退回槽位渲染,保证旧宿主可用。
4273
+ */
4274
+ function mountOverlay(node) {
4275
+ if (node && ReactDOM && typeof ReactDOM.createPortal === "function" &&
4276
+ typeof document !== "undefined" && document.body) {
4277
+ try {
4278
+ return ReactDOM.createPortal(node, document.body);
4279
+ } catch {
4280
+ // 探测失败按旧路径渲染,弹窗不会消失。
4281
+ }
4282
+ }
4283
+ return node;
4284
+ }
4285
+
4286
+ // 确认弹窗 + 分享/导出浮层控制器(input.overlay 槽位只作为渲染触发点)
3274
4287
  function OverlayController(props) {
3275
4288
  const { t: tt, useOverlay, useData, confirmAction, dismiss, runShare, runExport } = props;
3276
4289
  const view = useOverlay((v) => v.view);
@@ -3278,17 +4291,16 @@ return module.exports;
3278
4291
 
3279
4292
  if (!view) return null;
3280
4293
 
4294
+ let panel = null;
3281
4295
  if (view.kind === "confirm") {
3282
- return e(ConfirmOverlay, {
4296
+ panel = e(ConfirmOverlay, {
3283
4297
  t: tt,
3284
4298
  view,
3285
4299
  onDismiss: dismiss,
3286
4300
  confirmAction
3287
4301
  });
3288
- }
3289
-
3290
- if (view.kind === "pick") {
3291
- return e(PickOverlay, {
4302
+ } else if (view.kind === "pick") {
4303
+ panel = e(PickOverlay, {
3292
4304
  t: tt,
3293
4305
  mode: view.mode,
3294
4306
  seedTurn: view.turn,
@@ -3299,7 +4311,7 @@ return module.exports;
3299
4311
  });
3300
4312
  }
3301
4313
 
3302
- return null;
4314
+ return panel ? mountOverlay(panel) : null;
3303
4315
  }
3304
4316
 
3305
4317
  // 分享/导出多选列表
@@ -3405,7 +4417,595 @@ return module.exports;
3405
4417
  );
3406
4418
  }
3407
4419
 
4420
+ // -------------------------------------------------------------------------
4421
+ // 会话统计浮层:body 级挂载,会话页与设置页都能打开
4422
+ // -------------------------------------------------------------------------
4423
+
4424
+ const STATS_ROUTE = "/dsh-message-actions/stats";
4425
+ const STATS_BUDGET_ROUTE = "/dsh-message-actions/stats/budget";
4426
+ const STATS_POLL_MS = 10000;
4427
+
4428
+ const STATS_ICON = '<svg viewBox="0 0 16 16" fill="none" aria-hidden="true">' +
4429
+ '<path d="M3 13V9M6.7 13V6M10.4 13V8.5M14 13V3" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>';
4430
+ const REFRESH_ICON = '<svg viewBox="0 0 16 16" fill="none" aria-hidden="true">' +
4431
+ '<path d="M13 8a5 5 0 1 1-1.6-3.7M13 2.6V5.4h-2.8" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>';
4432
+
4433
+ let statsHost = null;
4434
+ let statsOpener = null;
4435
+ const statsStore = createStore({ open: false, seq: 0 });
4436
+
4437
+ function openStatsPanel(opener) {
4438
+ if (typeof document === "undefined" || !document.body) return;
4439
+ if (!ReactDOMClient || typeof ReactDOMClient.createRoot !== "function") return;
4440
+ statsOpener = opener || (document.activeElement instanceof HTMLElement ? document.activeElement : null);
4441
+ if (!statsHost) {
4442
+ statsHost = document.createElement("div");
4443
+ statsHost.className = "dma-stats-root";
4444
+ document.body.appendChild(statsHost);
4445
+ ReactDOMClient.createRoot(statsHost).render(e(StatsOverlay));
4446
+ }
4447
+ const snapshot = statsStore.getSnapshot();
4448
+ statsStore.set({ open: true, seq: snapshot.seq + 1 });
4449
+ }
4450
+
4451
+ function closeStatsPanel() {
4452
+ const snapshot = statsStore.getSnapshot();
4453
+ if (!snapshot.open) return;
4454
+ statsStore.set({ open: false, seq: snapshot.seq + 1 });
4455
+ const opener = statsOpener;
4456
+ statsOpener = null;
4457
+ if (opener && typeof opener.focus === "function" && opener.isConnected) {
4458
+ try {
4459
+ opener.focus({ preventScroll: true });
4460
+ } catch {
4461
+ /* ignore */
4462
+ }
4463
+ }
4464
+ }
4465
+
4466
+ function StatsOverlay() {
4467
+ const snapshot = React.useSyncExternalStore(statsStore.subscribe, statsStore.getSnapshot, statsStore.getSnapshot);
4468
+ if (!snapshot.open) return null;
4469
+ return e(StatsPanel, { key: snapshot.seq, onClose: closeStatsPanel });
4470
+ }
4471
+
4472
+ function statsPct(value) {
4473
+ const n = Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0;
4474
+ return (Math.round(n * 10) / 10) + "%";
4475
+ }
4476
+
4477
+ /** 比例文本不封顶(超预算时仍显示真实百分比)。 */
4478
+ function statsRatioText(value) {
4479
+ const n = Number.isFinite(value) ? Math.max(0, value) : 0;
4480
+ return (Math.round(n * 10) / 10) + "%";
4481
+ }
4482
+
4483
+ function statsShare(part, total) {
4484
+ if (!Number.isFinite(part) || !Number.isFinite(total) || total <= 0) return 0;
4485
+ return (part / total) * 100;
4486
+ }
4487
+
4488
+ function statsClock(ts) {
4489
+ const date = new Date(ts);
4490
+ const pad = (n) => (n < 10 ? "0" + n : String(n));
4491
+ return pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + " " + pad(date.getHours()) + ":" + pad(date.getMinutes());
4492
+ }
4493
+
4494
+ function statsRelative(ts, tt) {
4495
+ if (!Number.isFinite(ts) || ts <= 0) return "—";
4496
+ const diff = Math.max(0, Date.now() - ts);
4497
+ if (diff < 60 * 1000) return tt("stats.now");
4498
+ if (diff < 60 * 60 * 1000) return tt("stats.minutesAgo", { n: Math.floor(diff / 60000) });
4499
+ if (diff < 24 * 60 * 60 * 1000) return tt("stats.hoursAgo", { n: Math.floor(diff / 3600000) });
4500
+ return tt("stats.daysAgo", { n: Math.floor(diff / 86400000) });
4501
+ }
4502
+
4503
+ function StatsLegend({ t: tt }) {
4504
+ const rows = [
4505
+ ["input", "dma-stats-seg-input"],
4506
+ ["cacheRead", "dma-stats-seg-cacheRead"],
4507
+ ["cacheWrite", "dma-stats-seg-cacheWrite"],
4508
+ ["output", "dma-stats-seg-output"]
4509
+ ];
4510
+ return e("div", { className: "dma-stats-legend" },
4511
+ rows.map(([key, cls]) => e("span", { key },
4512
+ e("i", { className: "dma-stats-swatch " + cls }),
4513
+ tt("stats." + key))
4514
+ )
4515
+ );
4516
+ }
4517
+
4518
+ function StatsStack({ bucket, max, className }) {
4519
+ const total = Number.isFinite(bucket.tokens) ? bucket.tokens : 0;
4520
+ const height = max > 0 ? statsShare(total, max) : 0;
4521
+ // 计费口径细条:DeepSeek 计费(深蓝)/ 本地 · 不计费(中性灰)。
4522
+ // 四色分类已占用蓝色系,因此不重上分类色,而是另加一条独立细条与独立图例。
4523
+ const billableTokens = Number.isFinite(bucket.billableTokens) ? bucket.billableTokens : total;
4524
+ const localTokens = Number.isFinite(bucket.localTokens) ? bucket.localTokens : 0;
4525
+ const segments = [
4526
+ ["input", "dma-stats-seg-input"],
4527
+ ["cacheRead", "dma-stats-seg-cacheRead"],
4528
+ ["cacheWrite", "dma-stats-seg-cacheWrite"],
4529
+ ["output", "dma-stats-seg-output"]
4530
+ ];
4531
+ return e("div", { className: "dma-stats-col" },
4532
+ e("div", {
4533
+ className: "dma-stats-stack" + (className ? " " + className : ""),
4534
+ style: { height: statsPct(height) }
4535
+ },
4536
+ segments.map(([key, cls]) => {
4537
+ const part = Number.isFinite(bucket[key]) ? bucket[key] : 0;
4538
+ if (part <= 0 || total <= 0) return null;
4539
+ return e("i", {
4540
+ key,
4541
+ className: "dma-stats-seg " + cls,
4542
+ style: { height: statsPct(statsShare(part, total)) }
4543
+ });
4544
+ })
4545
+ ),
4546
+ total > 0
4547
+ ? e("div", { className: "dma-stats-billing-bar" },
4548
+ billableTokens > 0
4549
+ ? e("i", { className: "dma-stats-billing-deepseek", style: { width: statsPct(statsShare(billableTokens, total)) } })
4550
+ : null,
4551
+ localTokens > 0
4552
+ ? e("i", { className: "dma-stats-billing-local", style: { width: statsPct(statsShare(localTokens, total)) } })
4553
+ : null
4554
+ )
4555
+ : null
4556
+ );
4557
+ }
4558
+
4559
+ function StatsTimeline({ t: tt, series, range, onRange }) {
4560
+ const buckets = range === "hour" ? (series.hourly || []).slice(-24) : (series.daily || []);
4561
+ let max = 0;
4562
+ let billableTotal = 0;
4563
+ let localTotal = 0;
4564
+ for (const bucket of buckets) {
4565
+ if (bucket.tokens > max) max = bucket.tokens;
4566
+ billableTotal += Number.isFinite(bucket.billableTokens) ? bucket.billableTokens : bucket.tokens;
4567
+ localTotal += Number.isFinite(bucket.localTokens) ? bucket.localTokens : 0;
4568
+ }
4569
+ const first = buckets.length > 0 ? buckets[0].t : 0;
4570
+ const last = buckets.length > 0 ? buckets[buckets.length - 1].t : 0;
4571
+ return e("div", { className: "dma-stats-section" },
4572
+ e("div", { className: "dma-stats-section-head" },
4573
+ e("h4", { className: "dma-stats-section-title" }, tt("stats.timeline")),
4574
+ e("div", { className: "dma-stats-range", role: "group", "aria-label": tt("stats.timeline") },
4575
+ e("button", {
4576
+ type: "button",
4577
+ "aria-pressed": range === "hour" ? "true" : "false",
4578
+ onClick: () => onRange("hour")
4579
+ }, tt("stats.range24")),
4580
+ e("button", {
4581
+ type: "button",
4582
+ "aria-pressed": range === "day" ? "true" : "false",
4583
+ onClick: () => onRange("day")
4584
+ }, tt("stats.range30"))
4585
+ )
4586
+ ),
4587
+ e("div", { className: "dma-stats-chart-card" },
4588
+ e("div", { className: "dma-stats-chart-meta" },
4589
+ e("span", {}, statsClock(first) + " → " + statsClock(last)),
4590
+ e("span", {}, tt("stats.peak") + " " + formatTokens(max))
4591
+ ),
4592
+ e("div", {
4593
+ className: "dma-stats-chart",
4594
+ role: "img",
4595
+ "aria-label": tt("stats.timeline") + ": " + tt("stats.total") + " " + formatTokens(
4596
+ buckets.reduce((sum, bucket) => sum + (Number.isFinite(bucket.tokens) ? bucket.tokens : 0), 0)
4597
+ )
4598
+ },
4599
+ buckets.map((bucket, index) => e("div", {
4600
+ key: bucket.t,
4601
+ title: statsClock(bucket.t) + " · " + formatTokens(bucket.tokens) + " · " + formatCostMicros(bucket.costMicros)
4602
+ + (Number.isFinite(bucket.localTokens) && bucket.localTokens > 0
4603
+ ? " · " + tt("stats.billingLocal") + " " + formatTokens(bucket.localTokens)
4604
+ : "")
4605
+ }, e(StatsStack, { bucket, max })))
4606
+ ),
4607
+ e("div", { className: "dma-stats-axis" },
4608
+ [0, Math.floor(buckets.length / 3), Math.floor((buckets.length * 2) / 3), Math.max(0, buckets.length - 1)]
4609
+ .map((position, index) => e("span", { key: index },
4610
+ buckets[position] ? statsClock(buckets[position].t).slice(0, 5) : ""))
4611
+ ),
4612
+ e("div", { className: "dma-stats-legend-row" },
4613
+ e(StatsLegend, { t: tt }),
4614
+ e("div", { className: "dma-stats-legend dma-stats-legend-billing" },
4615
+ e("span", {},
4616
+ e("i", { className: "dma-stats-swatch dma-stats-billing-deepseek" }),
4617
+ tt("stats.billingDeepseek") + " " + formatTokens(billableTotal)),
4618
+ e("span", {},
4619
+ e("i", { className: "dma-stats-swatch dma-stats-billing-local" }),
4620
+ tt("stats.billingLocal") + " " + formatTokens(localTotal))
4621
+ )
4622
+ )
4623
+ )
4624
+ );
4625
+ }
4626
+
4627
+ function StatsSessionRows({ t: tt, rows, truncated, total }) {
4628
+ return e("div", { className: "dma-stats-section" },
4629
+ e("div", { className: "dma-stats-section-head" },
4630
+ e("h4", { className: "dma-stats-section-title" }, tt("stats.sessionsSection")),
4631
+ e("span", { className: "dma-stats-note" }, truncated ? tt("stats.truncated") : total + " / " + total)
4632
+ ),
4633
+ e("div", { className: "dma-stats-rows" },
4634
+ e("div", { className: "dma-stats-row dma-stats-row-head", "aria-hidden": "true" },
4635
+ e("span", {}, tt("stats.colSession")),
4636
+ e("span", { className: "dma-stats-cell-right" }, tt("stats.colTokens")),
4637
+ e("span", { className: "dma-stats-cell-right" }, tt("stats.colCost")),
4638
+ e("span", { className: "dma-stats-cell-right" }, tt("stats.colUpdated"))
4639
+ ),
4640
+ rows.length === 0
4641
+ ? e("div", { className: "dma-stats-empty" }, tt("stats.empty"))
4642
+ : rows.map((row) => {
4643
+ // 只有本地用量时成本显示「本地」而不是 ¥0.00,避免误读为「花了 0 元」。
4644
+ const localOnly = Number.isFinite(row.localTokens) && row.localTokens > 0 &&
4645
+ !(Number.isFinite(row.billableTokens) && row.billableTokens > 0);
4646
+ return e("div", { key: row.id, className: "dma-stats-row" },
4647
+ e("div", { className: "dma-stats-cell" },
4648
+ e("div", { className: "dma-stats-row-title" },
4649
+ e("b", { title: row.title }, row.title),
4650
+ localOnly ? e("span", { className: "dma-stats-pill dma-stats-pill-local" }, tt("stats.localTag")) : null,
4651
+ row.running ? e("span", { className: "dma-stats-pill dma-stats-pill-running" }, tt("stats.running")) : null,
4652
+ row.subagent ? e("span", { className: "dma-stats-pill" }, tt("stats.subagent")) : null
4653
+ ),
4654
+ e("div", { className: "dma-stats-meta" },
4655
+ (row.model || tt("stats.noModel")) + " · " + row.turns + " turns · " + row.messages + " msgs"),
4656
+ e("div", { className: "dma-stats-mini" },
4657
+ e("i", { className: "dma-stats-seg-input", style: { width: statsPct(statsShare(row.tokens.input, row.tokens.total || 1)) } }),
4658
+ e("i", { className: "dma-stats-seg-cacheRead", style: { width: statsPct(statsShare(row.tokens.cacheRead, row.tokens.total || 1)) } }),
4659
+ e("i", { className: "dma-stats-seg-cacheWrite", style: { width: statsPct(statsShare(row.tokens.cacheWrite, row.tokens.total || 1)) } }),
4660
+ e("i", { className: "dma-stats-seg-output", style: { width: statsPct(statsShare(row.tokens.output, row.tokens.total || 1)) } })
4661
+ )
4662
+ ),
4663
+ e("span", { className: "dma-stats-cell dma-stats-cell-right" }, formatTokens(row.tokens.total)),
4664
+ e("span", {
4665
+ className: "dma-stats-cell dma-stats-cell-right",
4666
+ title: localOnly ? tt("stats.billingNote") : undefined
4667
+ }, localOnly ? tt("stats.localCost") : formatCostMicros(row.costMicros)),
4668
+ e("span", { className: "dma-stats-cell dma-stats-cell-right dma-stats-meta" },
4669
+ statsRelative(row.lastActiveAt, tt))
4670
+ );
4671
+ })
4672
+ )
4673
+ );
4674
+ }
4675
+
4676
+ function StatsPanel({ onClose }) {
4677
+ const tt = t;
4678
+ const [state, setState] = React.useState({ status: "loading", data: null, error: "" });
4679
+ const [range, setRange] = React.useState("hour");
4680
+ const [budgetText, setBudgetText] = React.useState("");
4681
+ const [budgetEditing, setBudgetEditing] = React.useState(false);
4682
+ const [budgetBusy, setBudgetBusy] = React.useState(false);
4683
+ const [budgetError, setBudgetError] = React.useState("");
4684
+ const alive = React.useRef(true);
4685
+ const budgetInit = React.useRef(false);
4686
+
4687
+ const load = React.useCallback(async () => {
4688
+ try {
4689
+ const res = await getJson(STATS_ROUTE);
4690
+ if (!alive.current) return;
4691
+ if (res.status === 200 && res.data && res.data.ok) {
4692
+ setState({ status: "ready", data: res.data.value, error: "" });
4693
+ return;
4694
+ }
4695
+ const message = res.data && res.data.error && res.data.error.message
4696
+ ? String(res.data.error.message)
4697
+ : tt("stats.error");
4698
+ setState((prev) => ({ status: prev.data ? "stale" : "error", data: prev.data, error: message }));
4699
+ } catch (err) {
4700
+ if (!alive.current) return;
4701
+ setState((prev) => ({
4702
+ status: prev.data ? "stale" : "error",
4703
+ data: prev.data,
4704
+ error: err instanceof Error ? err.message : tt("stats.error")
4705
+ }));
4706
+ }
4707
+ }, [tt]);
4708
+
4709
+ React.useEffect(() => {
4710
+ alive.current = true;
4711
+ load();
4712
+ const timer = setInterval(() => {
4713
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
4714
+ load();
4715
+ }, STATS_POLL_MS);
4716
+ const onVisibility = () => {
4717
+ if (typeof document !== "undefined" && document.visibilityState === "visible") load();
4718
+ };
4719
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", onVisibility);
4720
+ return () => {
4721
+ alive.current = false;
4722
+ clearInterval(timer);
4723
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", onVisibility);
4724
+ };
4725
+ }, [load]);
4726
+
4727
+ React.useEffect(() => {
4728
+ const data = state.data;
4729
+ if (budgetInit.current || !data || !data.budget) return;
4730
+ budgetInit.current = true;
4731
+ setBudgetText(formatCents(data.budget.amountCents));
4732
+ }, [state.data]);
4733
+
4734
+ useOverlayKeys({ active: true, primaryEnabled: false, busy: budgetBusy, onDismiss: onClose, onPrimary: () => {} });
4735
+
4736
+ const data = state.data;
4737
+ const loading = state.status === "loading";
4738
+ const totals = data ? data.totals : null;
4739
+ const budget = data ? data.budget : null;
4740
+ const ledger = data ? data.ledger : null;
4741
+ const ratio = budget && budget.enabled ? budget.ratio * 100 : 0;
4742
+ const over = budget && budget.enabled && budget.remainingCents === 0 && budget.spentCents > 0;
4743
+ const cacheShare = totals && totals.tokens.total > 0
4744
+ ? statsShare(totals.tokens.cacheRead, totals.tokens.total)
4745
+ : 0;
4746
+ const kpi = [
4747
+ {
4748
+ label: tt("stats.totalTokens"),
4749
+ value: totals ? formatTokens(totals.tokens.total) : "—",
4750
+ sub: totals ? tt("stats.cacheShare") + " " + statsPct(cacheShare) : ""
4751
+ },
4752
+ {
4753
+ label: tt("stats.sessions"),
4754
+ value: totals ? String(totals.sessions) : "—",
4755
+ sub: totals ? tt("stats.runningNow") + " " + totals.running : ""
4756
+ },
4757
+ {
4758
+ label: tt("stats.estCost"),
4759
+ value: totals ? formatCostMicros(totals.costMicros) : "—",
4760
+ sub: tt("stats.priceHint")
4761
+ }
4762
+ ];
4763
+ const statsCard = (item) => e("div", { key: item.label, className: "dma-stats-card" },
4764
+ e("span", { className: "dma-stats-card-label" }, item.label),
4765
+ e("span", { className: "dma-stats-card-value", title: item.value }, item.value),
4766
+ e("span", { className: "dma-stats-card-sub" }, item.sub)
4767
+ );
4768
+
4769
+ async function saveBudget() {
4770
+ if (budgetBusy) return;
4771
+ const check = validateCorrectionAmount(budgetText);
4772
+ if (!check.ok) {
4773
+ setBudgetError(tt("stats.budgetInvalid"));
4774
+ return;
4775
+ }
4776
+ setBudgetBusy(true);
4777
+ setBudgetError("");
4778
+ try {
4779
+ const res = await postJson(STATS_BUDGET_ROUTE, { budgetYuan: String(budgetText).trim() });
4780
+ if (res.status === 200 && res.data && res.data.ok) {
4781
+ setBudgetText(formatCents(res.data.value.budgetCents));
4782
+ if (alive.current) setBudgetEditing(false);
4783
+ await load();
4784
+ } else {
4785
+ setBudgetError(tt("stats.budgetFailed"));
4786
+ }
4787
+ } catch {
4788
+ setBudgetError(tt("stats.budgetFailed"));
4789
+ } finally {
4790
+ if (alive.current) setBudgetBusy(false);
4791
+ }
4792
+ }
4793
+
4794
+ /** 取消就地编辑:丢掉未保存的输入,恢复为当前预算金额。 */
4795
+ function cancelBudget() {
4796
+ setBudgetEditing(false);
4797
+ setBudgetError("");
4798
+ if (data && data.budget) setBudgetText(formatCents(data.budget.amountCents));
4799
+ }
4800
+
4801
+ const openBudgetEdit = () => {
4802
+ setBudgetError("");
4803
+ setBudgetEditing(true);
4804
+ };
4805
+
4806
+ const budgetProgress = budget && budget.enabled
4807
+ ? e("div", { className: "dma-stats-progress", role: "progressbar", "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.min(100, Math.round(ratio)) },
4808
+ e("i", { style: { width: statsPct(ratio) } }))
4809
+ : null;
4810
+
4811
+ // 第一行第三张:预算卡(金额 + 剩余/已用 + 进度条);「修改预算」小按钮与金额同一行,
4812
+ // 点金额仍可直接编辑(隐藏路径保留)。
4813
+ const budgetCardNode = e("div", { className: "dma-stats-card dma-stats-money-card" },
4814
+ e("span", { className: "dma-stats-card-label" }, tt("stats.moneyBudget")),
4815
+ budgetEditing
4816
+ ? e("div", { className: "dma-stats-money-edit-row" },
4817
+ e("span", { className: "dma-stats-money-input" },
4818
+ "¥",
4819
+ e("input", {
4820
+ id: "dma-stats-budget-input",
4821
+ type: "text",
4822
+ inputMode: "decimal",
4823
+ value: budgetText,
4824
+ disabled: budgetBusy,
4825
+ autoFocus: true,
4826
+ "aria-label": tt("stats.budgetEdit"),
4827
+ onChange: (ev) => {
4828
+ setBudgetText(ev.target.value);
4829
+ if (budgetError) setBudgetError("");
4830
+ },
4831
+ onKeyDown: (ev) => {
4832
+ if (ev.key === "Enter") saveBudget();
4833
+ else if (ev.key === "Escape") {
4834
+ ev.stopPropagation();
4835
+ cancelBudget();
4836
+ }
4837
+ }
4838
+ }),
4839
+ tt("stats.budgetUnit")
4840
+ ),
4841
+ e("button", {
4842
+ type: "button",
4843
+ className: "dma-stats-money-mini",
4844
+ disabled: budgetBusy,
4845
+ onClick: saveBudget
4846
+ }, budgetBusy ? tt("stats.budgetSaving") : tt("stats.budgetSave")),
4847
+ e("button", {
4848
+ type: "button",
4849
+ className: "dma-stats-money-cancel",
4850
+ disabled: budgetBusy,
4851
+ onClick: cancelBudget
4852
+ }, tt("stats.budgetCancel"))
4853
+ )
4854
+ : e("div", { className: "dma-stats-money-value-row" },
4855
+ e("button", {
4856
+ type: "button",
4857
+ className: "dma-stats-card-value dma-stats-money-edit",
4858
+ title: tt("stats.moneyEdit"),
4859
+ "aria-label": tt("stats.moneyEdit"),
4860
+ onClick: openBudgetEdit
4861
+ }, budget ? formatYuanCents(budget.amountCents) : "—"),
4862
+ e("button", {
4863
+ type: "button",
4864
+ className: "dma-stats-money-mini",
4865
+ title: tt("stats.moneyEdit"),
4866
+ "aria-label": tt("stats.moneyEdit"),
4867
+ onClick: openBudgetEdit
4868
+ }, tt("stats.moneyEdit"))
4869
+ ),
4870
+ e("span", { className: "dma-stats-card-sub" },
4871
+ budget && budget.enabled
4872
+ ? (over
4873
+ ? tt("stats.overBudget")
4874
+ : tt("stats.budgetLeft") + " " + formatYuanCents(budget.remainingCents) + " · "
4875
+ + tt("stats.budgetUsed") + " " + statsPct(ratio))
4876
+ : tt("stats.budgetOffSub")),
4877
+ budgetEditing
4878
+ ? e("span", { className: "dma-stats-money-hint" }, budgetError || tt("stats.budgetHint"))
4879
+ : null,
4880
+ budgetProgress
4881
+ );
4882
+
4883
+ // 第一行第四张:预算使用(比例 + 剩余 / 额度 + 进度条)。
4884
+ const budgetUsageCardNode = e("div", { className: "dma-stats-card" },
4885
+ e("span", { className: "dma-stats-card-label" }, tt("stats.budget")),
4886
+ e("span", { className: "dma-stats-card-value", title: budget && budget.enabled ? statsRatioText(ratio) : tt("stats.budgetOff") },
4887
+ budget && budget.enabled ? statsRatioText(ratio) : tt("stats.budgetOff")),
4888
+ e("span", { className: "dma-stats-card-sub" },
4889
+ budget && budget.enabled
4890
+ ? (over
4891
+ ? tt("stats.overBudget") + " · " + formatYuanCents(budget.amountCents)
4892
+ : tt("stats.budgetLeft") + " " + formatYuanCents(budget.remainingCents) + tt("stats.of") + formatYuanCents(budget.amountCents))
4893
+ : tt("stats.budgetOffSub")),
4894
+ budgetProgress
4895
+ );
4896
+
4897
+ return e("div", {
4898
+ className: "dma-overlay",
4899
+ onClick: (ev) => {
4900
+ if (ev.target === ev.currentTarget) onClose();
4901
+ }
4902
+ },
4903
+ e("div", {
4904
+ className: "dma-panel dma-stats-panel",
4905
+ role: "dialog",
4906
+ "aria-modal": "true",
4907
+ "aria-label": tt("stats.panelTitle")
4908
+ },
4909
+ e("div", { className: "dma-panel-head dma-stats-head" },
4910
+ e("span", { className: "dma-stats-title" }, tt("stats.panelTitle")),
4911
+ e("span", { className: "dma-stats-live" },
4912
+ e("i", { className: "dma-stats-dot" }),
4913
+ state.status === "ready" ? tt("stats.live") : state.status === "stale" ? tt("stats.stale") : tt("stats.loading")),
4914
+ e("button", {
4915
+ type: "button",
4916
+ className: "dma-stats-icon",
4917
+ title: tt("stats.refresh"),
4918
+ "aria-label": tt("stats.refresh"),
4919
+ disabled: loading || budgetBusy,
4920
+ onClick: () => load()
4921
+ }, e("span", { className: "dma-stats-ico", dangerouslySetInnerHTML: { __html: REFRESH_ICON } })),
4922
+ e("button", {
4923
+ type: "button",
4924
+ autoFocus: true,
4925
+ className: "dma-stats-icon",
4926
+ title: tt("stats.close"),
4927
+ "aria-label": tt("stats.close"),
4928
+ onClick: onClose
4929
+ }, "×")
4930
+ ),
4931
+ e("div", { className: "dma-panel-body dma-stats-body" },
4932
+ e("p", { className: "dma-stats-intro" }, tt("stats.intro")),
4933
+ state.status === "error"
4934
+ ? e("p", { className: "dma-stats-error" }, tt("stats.error") + ":" + state.error)
4935
+ : null,
4936
+ state.status === "stale"
4937
+ ? e("p", { className: "dma-stats-error" }, tt("stats.stale") + ":" + state.error)
4938
+ : null,
4939
+ !loading && data && data.available === false
4940
+ ? e("p", { className: "dma-stats-error" }, tt("stats.unavailable"))
4941
+ : null,
4942
+ loading
4943
+ ? e("p", { className: "dma-stats-empty" }, tt("stats.loading"))
4944
+ : e("div", { className: "dma-stats-kpis" },
4945
+ kpi.slice(0, 2).map(statsCard),
4946
+ // 第一行:总 Token → 会话数量 → 预算 → 预算使用。
4947
+ budgetCardNode,
4948
+ budgetUsageCardNode
4949
+ ),
4950
+ !loading && data
4951
+ ? e("div", { className: "dma-stats-kpis dma-stats-money" },
4952
+ // 第二行:余额 → 日用 → 单次 → 估算成本。
4953
+ ledger
4954
+ ? e("div", { className: "dma-stats-card" },
4955
+ e("span", { className: "dma-stats-card-label" }, tt("cost.balance")),
4956
+ e("span", { className: "dma-stats-card-value" },
4957
+ Number.isFinite(ledger.balanceCents) ? formatYuanCents(ledger.balanceCents) : "—"),
4958
+ e("span", { className: "dma-stats-card-sub" }, tt("stats.moneyBalanceSub"))
4959
+ )
4960
+ : null,
4961
+ ledger
4962
+ ? e("div", { className: "dma-stats-card" },
4963
+ e("span", { className: "dma-stats-card-label" }, tt("cost.daily")),
4964
+ e("span", { className: "dma-stats-card-value" }, formatYuanCents(ledger.dailyCents || 0)),
4965
+ e("span", { className: "dma-stats-card-sub" }, tt("stats.moneyDailySub"))
4966
+ )
4967
+ : null,
4968
+ ledger
4969
+ ? e("div", { className: "dma-stats-card" },
4970
+ e("span", { className: "dma-stats-card-label" }, tt("cost.perTurn")),
4971
+ e("span", { className: "dma-stats-card-value" },
4972
+ Number.isFinite(ledger.lastTurnMicros) ? formatCostMicros(ledger.lastTurnMicros) : "—"),
4973
+ e("span", { className: "dma-stats-card-sub" }, tt("stats.moneyTurnSub"))
4974
+ )
4975
+ : null,
4976
+ statsCard(kpi[2])
4977
+ )
4978
+ : null,
4979
+ !loading && data
4980
+ ? e("p", { className: "dma-stats-note" }, tt("stats.budgetNote"))
4981
+ : null,
4982
+ !loading && data
4983
+ ? e("p", { className: "dma-stats-note" }, tt("stats.billingNote"))
4984
+ : null,
4985
+ !loading && data
4986
+ ? e(StatsTimeline, { t: tt, series: data.series, range, onRange: setRange })
4987
+ : null,
4988
+ !loading && data
4989
+ ? e(StatsSessionRows, {
4990
+ t: tt,
4991
+ rows: data.sessions || [],
4992
+ truncated: data.truncated === true,
4993
+ total: data.sessionsTotal || 0
4994
+ })
4995
+ : null,
4996
+ !loading && data && data.ledger
4997
+ ? e("p", { className: "dma-stats-note" }, tt("stats.ledger", {
4998
+ daily: formatYuanCents(data.ledger.dailyCents || 0),
4999
+ observed: formatYuanCents(data.ledger.observedSpendCents || 0)
5000
+ }))
5001
+ : null
5002
+ )
5003
+ )
5004
+ );
5005
+ }
5006
+
3408
5007
  // 设置页(settings.section 槽位)
5008
+ // 「完成提示音」不再有独立开关行:音色选「关闭」即关闭(见 SoundToneRow)。
3409
5009
  const SETTING_FIELDS = [
3410
5010
  ["recall", "settings.recall", "settings.recallDesc"],
3411
5011
  ["share", "settings.share", "settings.shareDesc"],
@@ -3499,6 +5099,112 @@ return module.exports;
3499
5099
  );
3500
5100
  }
3501
5101
 
5102
+ function SoundToneRow({ t: tt, value, onPick }) {
5103
+ const current = completionSoundTone(value || {});
5104
+ return e("div", { className: "dma-setting-row" },
5105
+ e("div", { className: "dma-setting-text" },
5106
+ e("div", { className: "dma-setting-label" }, tt("settings.soundTone")),
5107
+ e("div", { className: "dma-setting-desc" }, tt("settings.soundToneDesc"))
5108
+ ),
5109
+ e("div", { className: "dma-seg", role: "group", "aria-label": tt("settings.soundTone") },
5110
+ soundToneOptions().map((id) => e("button", {
5111
+ key: id,
5112
+ type: "button",
5113
+ className: "dma-seg-btn",
5114
+ "aria-pressed": current === id ? "true" : "false",
5115
+ onClick: () => onPick(id)
5116
+ }, tt("settings.soundTone." + id)))
5117
+ )
5118
+ );
5119
+ }
5120
+
5121
+ function VolumeRow({ t: tt, value, disabled, onCommit }) {
5122
+ const committed = clampSoundVolume(value);
5123
+ const [draft, setDraft] = React.useState(committed);
5124
+ const draftRef = React.useRef(committed);
5125
+ const committedRef = React.useRef(committed);
5126
+ const dragging = React.useRef(false);
5127
+ const timer = React.useRef(null);
5128
+ const inputRef = React.useRef(null);
5129
+ const commitRef = React.useRef(() => {});
5130
+
5131
+ // 外部配置变化时才回写本地值;拖动中或防抖未落盘时不覆盖,保证数字跟手。
5132
+ React.useEffect(() => {
5133
+ committedRef.current = committed;
5134
+ if (!dragging.current && !timer.current) {
5135
+ draftRef.current = committed;
5136
+ setDraft(committed);
5137
+ }
5138
+ }, [committed]);
5139
+
5140
+ React.useEffect(() => () => {
5141
+ if (timer.current) clearTimeout(timer.current);
5142
+ }, []);
5143
+
5144
+ // 拖动过程只更新本地显示,不写宿主配置、不重拉设置快照。
5145
+ const update = (raw) => {
5146
+ const next = clampSoundVolume(raw);
5147
+ draftRef.current = next;
5148
+ setDraft(next);
5149
+ };
5150
+
5151
+ // 松手 / 键盘抬起 / 失焦合并成一次提交:120ms 防抖后写入并试听一次。
5152
+ const commit = () => {
5153
+ dragging.current = false;
5154
+ if (timer.current) clearTimeout(timer.current);
5155
+ timer.current = setTimeout(() => {
5156
+ timer.current = null;
5157
+ const next = draftRef.current;
5158
+ if (next === committedRef.current) return;
5159
+ committedRef.current = next;
5160
+ onCommit(next);
5161
+ }, 120);
5162
+ };
5163
+ commitRef.current = commit;
5164
+
5165
+ // 原生 change 在拖动结束时才触发(React 的 onChange 实际是 input 事件),
5166
+ // 兜住指针在滑杆外松开、或浏览器不做隐式指针捕获的情况。
5167
+ React.useEffect(() => {
5168
+ const el = inputRef.current;
5169
+ if (!el || typeof el.addEventListener !== "function") return undefined;
5170
+ const onChangeEnd = () => commitRef.current();
5171
+ el.addEventListener("change", onChangeEnd);
5172
+ return () => el.removeEventListener("change", onChangeEnd);
5173
+ }, []);
5174
+
5175
+ return e("div", { className: "dma-setting-row" },
5176
+ e("div", { className: "dma-setting-text" },
5177
+ e("div", { className: "dma-setting-label" }, tt("settings.soundVolume")),
5178
+ e("div", { className: "dma-setting-desc" }, tt("settings.soundVolumeDesc"))
5179
+ ),
5180
+ e("div", { className: "dma-volume" },
5181
+ e("input", {
5182
+ ref: inputRef,
5183
+ type: "range",
5184
+ className: "dma-volume-range",
5185
+ min: 0,
5186
+ max: 100,
5187
+ step: 5,
5188
+ value: draft,
5189
+ disabled: !!disabled,
5190
+ "aria-label": tt("settings.soundVolume"),
5191
+ onChange: (ev) => {
5192
+ dragging.current = true;
5193
+ update(ev.target.value);
5194
+ },
5195
+ onPointerDown: () => {
5196
+ dragging.current = true;
5197
+ },
5198
+ onPointerUp: commit,
5199
+ onPointerCancel: commit,
5200
+ onKeyUp: commit,
5201
+ onBlur: commit
5202
+ }),
5203
+ e("span", { className: "dma-volume-value" }, draft + "%")
5204
+ )
5205
+ );
5206
+ }
5207
+
3502
5208
  function BillingTab({ t: tt, form, value, save }) {
3503
5209
  const enabled = value ? value.usageStats !== false : true;
3504
5210
  const onToggle = (key, on) => () => save(key, !on);
@@ -3540,127 +5246,18 @@ return module.exports;
3540
5246
  disabled: !enabled,
3541
5247
  onToggle: enabled ? onToggle("costPeakValley", value ? value.costPeakValley !== false : true) : null
3542
5248
  }),
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" },
5249
+ e("div", { className: "dma-setting-row" },
5250
+ e("div", { className: "dma-setting-text" },
5251
+ e("div", { className: "dma-setting-label" }, tt("cost.settings.statsTable")),
5252
+ e("div", { className: "dma-setting-desc" }, tt("cost.settings.statsTableDesc"))
5253
+ ),
3657
5254
  e("button", {
3658
5255
  type: "button",
3659
- className: "dma-correction-save",
3660
- disabled: invalid || busy,
3661
- onClick: submit
3662
- }, tt(busy ? "cost.correction.saving" : "cost.correction.save"))
3663
- )
5256
+ className: "dma-setting-primary dma-setting-btn",
5257
+ onClick: (ev) => openStatsPanel(ev.currentTarget)
5258
+ }, tt("cost.settings.statsTableButton"))
5259
+ ),
5260
+ e("p", { className: "dma-cost-note" }, tt("cost.balanceNote"))
3664
5261
  );
3665
5262
  }
3666
5263
 
@@ -3721,8 +5318,8 @@ return module.exports;
3721
5318
  ),
3722
5319
  tab === "actions"
3723
5320
  ? e("div", { className: "dma-settings-panel" },
3724
- SETTING_FIELDS.map(([key, labelKey, descKey]) => {
3725
- const on = value ? value[key] === true : false;
5321
+ SETTING_FIELDS.map(([key, labelKey, descKey, defaultOn]) => {
5322
+ const on = value ? (defaultOn ? value[key] !== false : value[key] === true) : defaultOn === true;
3726
5323
  return e(SettingRow, {
3727
5324
  key,
3728
5325
  t: tt,
@@ -3732,6 +5329,28 @@ return module.exports;
3732
5329
  onToggle: () => save(key, !on)
3733
5330
  });
3734
5331
  }),
5332
+ // 音色 + 音量:没有独立开关行,「关闭」音色即关闭完成提示音。
5333
+ e(SoundToneRow, {
5334
+ key: "soundTone",
5335
+ t: tt,
5336
+ value: value || {},
5337
+ onPick: (id) => {
5338
+ save("soundTone", id);
5339
+ if (id === "off") return; // 选「关闭」即关闭,不再试听
5340
+ // 旧配置可能还留着 sound=false:选任一音色时同步打开。
5341
+ if (value && value.sound === false) save("sound", true);
5342
+ playCompletionSound(id);
5343
+ }
5344
+ }),
5345
+ e(VolumeRow, {
5346
+ key: "soundVolume",
5347
+ t: tt,
5348
+ value: value ? value.soundVolume : DEFAULT_SOUND_VOLUME,
5349
+ onCommit: (volume) => {
5350
+ save("soundVolume", volume);
5351
+ playCompletionSound(undefined, volume);
5352
+ }
5353
+ }),
3735
5354
  // 第一个标签页底部:只读版本号,不抢设置项视觉焦点。
3736
5355
  e("div", { className: "dma-settings-version" }, "v" + VERSION)
3737
5356
  )
@@ -3798,9 +5417,17 @@ return module.exports;
3798
5417
  const status = value ? value.status : "stale";
3799
5418
  const lastTurn = value && value.lastTurn ? value.lastTurn : null;
3800
5419
 
3801
- const balanceCents = balance && balance.updatedAt > 0 && Number.isFinite(balance.totalCents)
3802
- ? balance.totalCents
5420
+ // 余额口径:主数字 = 充值余额 + 赠金钱包(与「日用」观测的总额同基准),
5421
+ // 全部按分计,不做元级四舍五入;赠金拆分只在悬停提示,不再单独占行。
5422
+ const rechargeCents = balance && Number.isFinite(balance.rechargeCents) ? balance.rechargeCents : null;
5423
+ const bonusCents = balance && Number.isFinite(balance.bonusCents) ? balance.bonusCents : null;
5424
+ const totalCents = balance && Number.isFinite(balance.totalCents) ? balance.totalCents : null;
5425
+ const balanceCents = balance && balance.updatedAt > 0
5426
+ ? (totalCents !== null ? totalCents : rechargeCents)
3803
5427
  : null;
5428
+ const bonusTitle = bonusCents !== null && bonusCents > 0
5429
+ ? " · " + tt("cost.bonusHint", { bonus: formatYuanCents(bonusCents) })
5430
+ : "";
3804
5431
  const dailyCents = balanceCents !== null && value && Number.isFinite(value.dailyCents)
3805
5432
  ? value.dailyCents
3806
5433
  : null;
@@ -3847,7 +5474,7 @@ return module.exports;
3847
5474
 
3848
5475
  if (!wide) {
3849
5476
  const title = balanceCents !== null
3850
- ? tt("cost.railTitle", { balance: formatYuanCents(balanceCents) })
5477
+ ? tt("cost.railTitle", { balance: formatYuanCents(balanceCents) }) + bonusTitle
3851
5478
  : tt("cost.balance");
3852
5479
  return e("div", { className: "dma-cost-item" },
3853
5480
  e("button", {
@@ -3891,7 +5518,6 @@ return module.exports;
3891
5518
  : formatCostMicros(Math.round(turnShown));
3892
5519
 
3893
5520
  const stale = status === "stale" && balanceCents !== null;
3894
- const pending = value && Number.isFinite(value.pendingAdjustmentCents) && value.pendingAdjustmentCents > 0;
3895
5521
  const staleTitle = balance && balance.updatedAt > 0
3896
5522
  ? tt("cost.staleTitle", { time: new Date(balance.updatedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) })
3897
5523
  : "";
@@ -3908,30 +5534,38 @@ return module.exports;
3908
5534
  if (compact) {
3909
5535
  return e("div", { className: "dma-cost-item" },
3910
5536
  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)
5537
+ e("div", { className: "dma-cost-plain-wrap" },
5538
+ e("button", {
5539
+ type: "button",
5540
+ className: "dma-cost-plain-row",
5541
+ onClick: refresh,
5542
+ title: (stale ? staleTitle : tt("cost.refresh")) + bonusTitle,
5543
+ "aria-label": tt("cost.refresh"),
5544
+ "aria-busy": refreshing ? "true" : "false"
5545
+ },
5546
+ showPeak ? periodIcon : null,
5547
+ e("span", { className: "dma-cost-col" },
5548
+ e("span", { className: "dma-cost-label" }, tt("cost.balance")),
5549
+ e("span", { className: "dma-cost-value" }, balanceText)
5550
+ ),
5551
+ e("span", { className: "dma-cost-col" },
5552
+ e("span", { className: "dma-cost-label" }, tt("cost.daily")),
5553
+ e("span", { className: "dma-cost-value" }, dailyText)
5554
+ ),
5555
+ showTurn && !turnHidden
5556
+ ? e("span", { className: "dma-cost-col" },
5557
+ e("span", { className: "dma-cost-label", title: tt("cost.settings.perTurnDesc") }, tt("cost.perTurn")),
5558
+ e("span", { className: "dma-cost-value" }, turnText)
5559
+ )
5560
+ : null
3927
5561
  ),
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
5562
+ e("button", {
5563
+ type: "button",
5564
+ className: "dma-stats-entry",
5565
+ title: tt("stats.entryTitle"),
5566
+ "aria-label": tt("stats.entryTitle"),
5567
+ onClick: (ev) => openStatsPanel(ev.currentTarget)
5568
+ }, e("span", { className: "dma-ico", dangerouslySetInnerHTML: { __html: STATS_ICON } }))
3935
5569
  )
3936
5570
  )
3937
5571
  );
@@ -3944,13 +5578,12 @@ return module.exports;
3944
5578
  type: "button",
3945
5579
  className: "dma-cost-col dma-cost-balance" + (refreshing ? " dma-cost-busy" : ""),
3946
5580
  onClick: refresh,
3947
- title: stale ? staleTitle : tt("cost.refresh"),
5581
+ title: (stale ? staleTitle : tt("cost.refresh")) + bonusTitle,
3948
5582
  "aria-label": tt("cost.refresh"),
3949
5583
  "aria-busy": refreshing ? "true" : "false"
3950
5584
  },
3951
5585
  e("span", { className: "dma-cost-label" },
3952
5586
  tt("cost.balance"),
3953
- pending ? e("span", { className: "dma-cost-badge", title: tt("cost.pendingTitle") }, tt("cost.pending")) : null,
3954
5587
  refreshing ? e("span", { className: "dma-cost-spinner" }) : null,
3955
5588
  stale ? e("span", { className: "dma-cost-stale", title: staleTitle }) : null
3956
5589
  ),
@@ -3974,7 +5607,14 @@ return module.exports;
3974
5607
  }, "×")
3975
5608
  : null
3976
5609
  )
3977
- : null
5610
+ : null,
5611
+ e("button", {
5612
+ type: "button",
5613
+ className: "dma-stats-entry",
5614
+ title: tt("stats.entryTitle"),
5615
+ "aria-label": tt("stats.entryTitle"),
5616
+ onClick: (ev) => openStatsPanel(ev.currentTarget)
5617
+ }, e("span", { className: "dma-ico", dangerouslySetInnerHTML: { __html: STATS_ICON } }))
3978
5618
  ),
3979
5619
  showPeak
3980
5620
  ? e("div", {
@@ -3996,17 +5636,17 @@ return module.exports;
3996
5636
  const EXTRA_CSS = `
3997
5637
  .dma-settings{max-width:680px;display:flex;flex-direction:column;gap:2px}
3998
5638
  .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))}
5639
+ .dma-settings-version{margin-top:10px;padding-top:8px;font-size:11px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a919e);text-align:right;user-select:text}
5640
+ .dma-setting-row{display:flex;align-items:flex-start;justify-content:space-between;gap:20px;padding:10px 4px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08))}
4001
5641
  .dma-setting-text{min-width:0}
4002
5642
  .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)}
5643
+ .dma-setting-desc{margin-top:2px;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a919e)}
4004
5644
  .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
5645
  .dma-switch[aria-checked="true"]{background:var(--dsw-alias-state-business-primary,#4c8dff)}
4006
5646
  .dma-switch:disabled{opacity:.45;cursor:default}
4007
5647
  .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
5648
  .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)}
5649
+ .dma-setting-error{margin-top:8px;font-size:12px;color:var(--dsw-alias-state-error-primary,#e5484d)}
4010
5650
  .dma-ico{display:inline-flex}
4011
5651
  .dma-empty{color:var(--dsw-alias-label-tertiary,#8a919e);font-size:13px;margin:12px 0}
4012
5652
  .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)}
@@ -4019,21 +5659,13 @@ return module.exports;
4019
5659
  .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
5660
  .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
5661
  .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)}
5662
+ .dma-volume{flex:none;display:inline-flex;align-items:center;gap:8px;margin-top:2px}
5663
+ .dma-volume-range{width:132px;accent-color:var(--dsw-alias-state-business-primary,#4c8dff)}
5664
+ .dma-volume-range:disabled{opacity:.45}
5665
+ .dma-volume-value{min-width:38px;font-size:12px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary,#5b6472);text-align:right}
4033
5666
  .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}
5667
+ .dma-setting-primary{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}
5668
+ .dma-setting-primary:disabled{background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-dimmed,#a0a6b0);cursor:default}
4037
5669
  .dma-cost-item{flex:1 1 auto;min-width:0}
4038
5670
  .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
5671
  .dma-cost-cols{display:flex;align-items:baseline;justify-content:space-between;gap:6px;min-width:0}
@@ -4043,7 +5675,6 @@ return module.exports;
4043
5675
  .dma-cost-balance:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4044
5676
  .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
5677
  .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
5678
  .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
5679
  .dma-cost-stale{flex:none;width:4px;height:4px;border-radius:50%;background:var(--dsw-alias-label-dimmed,#a0a6b0)}
4049
5680
  .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}
@@ -4058,7 +5689,6 @@ return module.exports;
4058
5689
  .dma-cost-plain-row:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4059
5690
  .dma-cost-plain .dma-cost-col{flex:0 1 auto;overflow:hidden}
4060
5691
  .dma-cost-plain .dma-cost-value{font-size:13.5px}
4061
- .dma-cost-plain .dma-cost-badge{margin-left:auto}
4062
5692
  .dma-cost-local{flex-direction:row;align-items:center;justify-content:center;gap:5px;padding:6px 8px}
4063
5693
  .dma-cost-local.dma-cost-plain{justify-content:flex-start;gap:6px;padding:2px 2px}
4064
5694
  .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)}
@@ -4066,6 +5696,101 @@ return module.exports;
4066
5696
  .dma-cost-rail:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05))}
4067
5697
  .dma-cost-rail:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
4068
5698
  .dma-cost-rail svg{width:16px;height:16px}
5699
+ .dma-cost-plain-wrap{display:flex;align-items:center;gap:2px;width:100%;min-width:0}
5700
+ .dma-cost-plain-wrap .dma-cost-plain-row{flex:1 1 auto;min-width:0}
5701
+ .dma-cost-cols>.dma-stats-entry{align-self:center}
5702
+ .dma-stats-entry{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-tertiary,#8a919e);cursor:pointer;transition:background 120ms ease,color 120ms ease}
5703
+ .dma-stats-entry:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05));color:var(--dsw-alias-label-primary,#1f2329)}
5704
+ .dma-stats-entry:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
5705
+ .dma-stats-entry svg{display:block;width:15px;height:15px}
5706
+ .dma-stats-panel{width:min(920px,calc(100vw - 48px));max-height:86vh}
5707
+ .dma-stats-head{display:flex;align-items:center;gap:6px}
5708
+ .dma-stats-title{margin-right:auto;font-size:16px;font-weight:600;color:var(--dsw-alias-label-primary,#1f2329)}
5709
+ .dma-stats-live{display:inline-flex;align-items:center;gap:5px;font-size:11px;color:var(--dsw-alias-label-tertiary,#8a919e)}
5710
+ .dma-stats-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-state-success-primary,#22a06b)}
5711
+ .dma-stats-icon{flex:none;display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary,#5b6472);font-size:16px;line-height:1;cursor:pointer}
5712
+ .dma-stats-icon:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.05))}
5713
+ .dma-stats-icon:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
5714
+ .dma-stats-icon:disabled{opacity:.45;cursor:default}
5715
+ .dma-stats-ico svg{display:block;width:16px;height:16px}
5716
+ .dma-stats-body{display:flex;flex-direction:column;gap:14px;padding:14px 18px}
5717
+ .dma-stats-intro{margin:0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-tertiary,#8a919e)}
5718
+ .dma-stats-kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px}
5719
+ .dma-stats-card{display:flex;flex-direction:column;gap:4px;min-width:0;padding:10px 12px;border:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));border-radius:9px;background:var(--dsw-alias-bg-layer-2,#f2f3f5)}
5720
+ .dma-stats-card-label{font-size:11px;line-height:1.4;color:var(--dsw-alias-label-tertiary,#8a919e)}
5721
+ .dma-stats-card-value{overflow:hidden;font-size:20px;font-weight:600;line-height:1.25;white-space:nowrap;text-overflow:ellipsis;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary,#1f2329)}
5722
+ .dma-stats-card-sub{overflow:hidden;font-size:11px;line-height:1.45;white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-tertiary,#8a919e)}
5723
+ .dma-stats-progress{height:5px;margin-top:2px;border-radius:3px;background:var(--dsw-alias-bg-layer-1,#fff);overflow:hidden}
5724
+ .dma-stats-progress i{display:block;height:100%;border-radius:3px;background:var(--dsw-alias-state-business-primary,#4c8dff);transition:width 240ms ease}
5725
+ .dma-stats-section{display:flex;flex-direction:column;gap:8px;min-width:0}
5726
+ .dma-stats-section-head{display:flex;align-items:center;justify-content:space-between;gap:10px}
5727
+ .dma-stats-section-title{margin:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,#1f2329)}
5728
+ .dma-stats-note{font-size:11px;line-height:1.5;color:var(--dsw-alias-label-tertiary,#8a919e)}
5729
+ .dma-stats-range{display:inline-flex;gap:2px;padding:2px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,#f2f3f5)}
5730
+ .dma-stats-range button{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}
5731
+ .dma-stats-range button[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)}
5732
+ .dma-stats-range button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
5733
+ .dma-stats-chart-card{display:flex;flex-direction:column;gap:8px;padding:10px 12px;border:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));border-radius:9px;background:var(--dsw-alias-bg-layer-2,#f2f3f5)}
5734
+ .dma-stats-chart-meta{display:flex;justify-content:space-between;gap:10px;font-size:11px;color:var(--dsw-alias-label-tertiary,#8a919e)}
5735
+ .dma-stats-chart{display:flex;align-items:flex-end;gap:2px;height:150px;min-width:0}
5736
+ .dma-stats-chart>div{flex:1 1 0;display:flex;align-items:flex-end;justify-content:center;min-width:0;height:100%}
5737
+ .dma-stats-col{position:relative;flex:1 1 0;display:flex;align-items:flex-end;justify-content:center;min-width:0;height:100%}
5738
+ .dma-stats-billing-bar{position:absolute;left:50%;bottom:0;transform:translateX(-50%);display:flex;width:100%;max-width:26px;height:3px;border-radius:2px;overflow:hidden;background:var(--dsw-alias-bg-layer-1,#fff)}
5739
+ .dma-stats-billing-bar i{display:block;height:100%}
5740
+ .dma-stats-billing-deepseek{background:#2f6bd8}
5741
+ .dma-stats-billing-local{background:#a8aeb8}
5742
+ .dma-stats-stack{display:flex;flex-direction:column-reverse;width:100%;max-width:26px;border-radius:3px 3px 0 0;overflow:hidden}
5743
+ .dma-stats-seg{display:block;width:100%}
5744
+ .dma-stats-seg-input{background:var(--dsw-alias-brand-primary,#4c8dff)}
5745
+ .dma-stats-seg-cacheRead{background:var(--dsw-alias-brand-primary,#4c8dff);opacity:.5}
5746
+ .dma-stats-seg-cacheWrite{background:var(--dsw-alias-brand-primary,#4c8dff);opacity:.26}
5747
+ .dma-stats-seg-output{background:var(--dsw-alias-state-success-primary,#22a06b)}
5748
+ .dma-stats-axis{display:grid;grid-template-columns:repeat(4,1fr);gap:2px;font-size:10px;color:var(--dsw-alias-label-tertiary,#8a919e)}
5749
+ .dma-stats-axis span{overflow:hidden;white-space:nowrap;text-align:center}
5750
+ .dma-stats-legend{display:flex;flex-wrap:wrap;gap:12px;font-size:11px;color:var(--dsw-alias-label-tertiary,#8a919e)}
5751
+ .dma-stats-legend span{display:inline-flex;align-items:center;gap:4px}
5752
+ .dma-stats-legend-row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:6px 12px;min-width:0}
5753
+ .dma-stats-legend-billing{flex:none;margin-left:auto}
5754
+ .dma-stats-swatch{display:inline-block;width:9px;height:9px;border-radius:2px}
5755
+ .dma-stats-rows{display:flex;flex-direction:column;border:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));border-radius:9px;overflow:hidden}
5756
+ .dma-stats-row{display:grid;grid-template-columns:minmax(0,1fr) 96px 84px 84px;gap:8px;align-items:center;padding:8px 12px;font-size:12px;border-top:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08))}
5757
+ .dma-stats-row:first-child{border-top:0}
5758
+ .dma-stats-row-head{font-size:11px;font-weight:600;color:var(--dsw-alias-label-tertiary,#8a919e);background:var(--dsw-alias-bg-layer-2,#f2f3f5)}
5759
+ .dma-stats-cell{min-width:0;overflow:hidden}
5760
+ .dma-stats-cell-right{text-align:right;font-variant-numeric:tabular-nums}
5761
+ .dma-stats-row-title{display:flex;align-items:center;gap:5px;min-width:0}
5762
+ .dma-stats-row-title b{overflow:hidden;font-weight:600;white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-primary,#1f2329)}
5763
+ .dma-stats-pill{flex:none;padding:0 5px;border-radius:7px;background:rgba(76,141,255,.14);color:#2f6bd8;font-size:10px;font-weight:500;line-height:15px}
5764
+ .dma-stats-pill-running{background:rgba(34,160,107,.15);color:#137a4e}
5765
+ .dma-stats-pill-local{background:rgba(0,0,0,.06);color:#6b7280}
5766
+ .dma-stats-meta{overflow:hidden;font-size:10.5px;line-height:1.45;white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-tertiary,#8a919e)}
5767
+ .dma-stats-mini{display:flex;height:4px;margin-top:4px;border-radius:2px;overflow:hidden;background:var(--dsw-alias-bg-layer-1,#fff)}
5768
+ .dma-stats-mini i{display:block;height:100%}
5769
+ .dma-stats-mini .dma-stats-seg-cacheRead{opacity:.5}
5770
+ .dma-stats-mini .dma-stats-seg-output{background:var(--dsw-alias-state-success-primary,#22a06b)}
5771
+ .dma-stats-empty{margin:6px 0;font-size:12px;color:var(--dsw-alias-label-tertiary,#8a919e)}
5772
+ .dma-stats-money-edit{padding:0;border:0;background:transparent;font:inherit;font-size:20px;font-weight:600;line-height:1.25;text-align:left;color:inherit;border-radius:4px;cursor:pointer;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
5773
+ .dma-stats-money-edit:hover{color:var(--dsw-alias-state-business-primary,#4c8dff)}
5774
+ .dma-stats-money-edit:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
5775
+ .dma-stats-money-edit-row{display:flex;flex-wrap:nowrap;align-items:center;gap:7px;min-width:0;min-height:24px}
5776
+ .dma-stats-money-edit-row>*{flex:none;min-width:0}
5777
+ .dma-stats-money-card{container-type:inline-size}
5778
+ .dma-stats-money-input{display:inline-flex;flex:0 1 92px;align-items:center;gap:3px;box-sizing:border-box;width:92px;min-width:64px;padding:2px 6px;border:.5px solid var(--dsw-alias-border-l3,#c9ced6);border-radius:6px;background:var(--dsw-alias-bg-layer-1,#fff);font-size:13px;color:var(--dsw-alias-label-tertiary,#8a919e);overflow:hidden}
5779
+ .dma-stats-money-input input{flex:1 1 auto;width:0;min-width:0;border:0;outline:0;background:transparent;color:var(--dsw-alias-label-primary,#1f2329);font:inherit;font-size:13px;font-variant-numeric:tabular-nums;text-align:right}
5780
+ .dma-stats-money-mini{flex:none;height:25px;padding:0 9px;border:0;border-radius:6px;background:var(--dsw-alias-button-primary-fill,#4c8dff);color:#fff;font-size:11.5px;font-weight:500;line-height:1;cursor:pointer;white-space:nowrap}
5781
+ .dma-stats-money-mini:hover{filter:brightness(.95)}
5782
+ .dma-stats-money-mini:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
5783
+ .dma-stats-money-mini:disabled{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-dimmed,#a0a6b0);cursor:default;filter:none}
5784
+ .dma-stats-money-cancel{flex:none;height:25px;padding:0 7px;border:.5px solid var(--dsw-alias-border-l3,#c9ced6);border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#5b6472);font-size:11px;cursor:pointer;white-space:nowrap}
5785
+ .dma-stats-money-cancel:hover{color:var(--dsw-alias-label-primary,#1f2329);border-color:var(--dsw-alias-border-l2,rgba(0,0,0,.16))}
5786
+ .dma-stats-money-cancel:disabled{opacity:.45;cursor:default}
5787
+ @container (max-width:181px){.dma-stats-money-edit-row{gap:4px}.dma-stats-money-mini{padding:0 5px}.dma-stats-money-cancel{padding:0 4px}}
5788
+ .dma-stats-money-hint{overflow:hidden;font-size:10px;line-height:1.3;white-space:nowrap;text-overflow:ellipsis;color:var(--dsw-alias-label-tertiary,#8a919e)}
5789
+ .dma-stats-money-value-row{display:flex;align-items:center;gap:8px;min-width:0;min-height:24px}
5790
+ .dma-stats-money-value-row .dma-stats-money-edit{flex:1 1 auto;min-width:0}
5791
+ .dma-stats-money-value-row .dma-stats-money-mini{flex:none;white-space:nowrap}
5792
+ .dma-stats-error{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-state-error-primary,#e5484d)}
5793
+ .dma-setting-btn{flex:none;margin-top:2px;align-self:flex-start}
4069
5794
  @keyframes dma-spin{to{transform:rotate(360deg)}}
4070
5795
  `;
4071
5796