dsh-team-bots 0.2.289 → 0.2.338

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.
Files changed (116) hide show
  1. package/README.md +12 -136
  2. package/docs/README.zh.md +15 -139
  3. package/docs/assets/channel-redesign.png +0 -0
  4. package/docs/assets/global-config-dark.png +0 -0
  5. package/docs/assets/global-config-light.png +0 -0
  6. package/docs/assets/global-config-light.zh.png +0 -0
  7. package/docs/assets/global-config-redesign.png +0 -0
  8. package/docs/assets/secrets-redesign.png +0 -0
  9. package/docs/assets/tasks.png +0 -0
  10. package/docs/assets/tasks.zh.png +0 -0
  11. package/docs/assets/usage-redesign-global.png +0 -0
  12. package/docs/assets/usage.png +0 -0
  13. package/docs/assets/usage.zh.png +0 -0
  14. package/package.json +17 -5
  15. package/scripts/doctor.mjs +4 -4
  16. package/src/api.js +6 -3
  17. package/src/botmsg.js +1 -1
  18. package/src/config.js +18 -8
  19. package/src/db-migrations.js +76 -9
  20. package/src/db.js +28 -2
  21. package/src/http.js +22 -3
  22. package/src/paths.js +32 -1
  23. package/src/pricing.js +2 -2
  24. package/src/runtime.js +1 -1
  25. package/src/secrets.js +4 -4
  26. package/src/service.js +10 -5
  27. package/src/services/approvals.js +109 -24
  28. package/src/services/bot-quota.js +242 -0
  29. package/src/services/bots.js +35 -6
  30. package/src/services/chat.js +15 -9
  31. package/src/services/core.js +33 -5
  32. package/src/services/hygiene.js +8 -4
  33. package/src/services/locale.js +17 -0
  34. package/src/services/memory.js +112 -1
  35. package/src/services/message-images.js +3 -3
  36. package/src/services/notify.js +99 -0
  37. package/src/services/projects.js +119 -10
  38. package/src/services/proposals.js +2 -3
  39. package/src/services/questions.js +75 -32
  40. package/src/services/review-watchdog.js +261 -30
  41. package/src/services/run-finish.js +119 -7
  42. package/src/services/runs.js +42 -13
  43. package/src/services/runtime/lifecycle.js +3 -1
  44. package/src/services/runtime/model-restore.js +5 -5
  45. package/src/services/runtime/prompt.js +106 -45
  46. package/src/services/runtime/session.js +38 -14
  47. package/src/services/runtime/trajectory.js +1 -1
  48. package/src/services/scheduler.js +139 -13
  49. package/src/services/secrets.js +1 -1
  50. package/src/services/system.js +23 -6
  51. package/src/services/task-notify.js +49 -7
  52. package/src/services/task-stage.js +4 -0
  53. package/src/services/tasks.js +121 -12
  54. package/src/services/terminal.js +2 -2
  55. package/src/services/vision-proxy.js +3 -3
  56. package/src/services/wechat.js +228 -7
  57. package/src/services/workspace-groups.js +4 -3
  58. package/src/skill-parse.js +1 -1
  59. package/src/skills.js +1 -1
  60. package/src/tools.js +275 -6
  61. package/src/updater.js +52 -0
  62. package/src/usage-reconcile.js +1 -1
  63. package/src/usage.js +52 -11
  64. package/src/wechat/channel.js +14 -20
  65. package/src/wechat/commands.js +129 -81
  66. package/src/wechat/format.js +247 -0
  67. package/src/wechat/store.js +30 -2
  68. package/ui/app.js +56 -52
  69. package/ui/i18n/en/chat.js +140 -0
  70. package/ui/i18n/en/common.js +189 -0
  71. package/ui/i18n/en/nav.js +90 -0
  72. package/ui/i18n/en/settings.js +354 -0
  73. package/ui/i18n/en/tasks.js +232 -0
  74. package/ui/i18n/en/usage.js +141 -0
  75. package/ui/i18n/en/wechat.js +24 -0
  76. package/ui/i18n/en.js +17 -237
  77. package/ui/i18n/zh/chat.js +140 -0
  78. package/ui/i18n/zh/common.js +189 -0
  79. package/ui/i18n/zh/nav.js +90 -0
  80. package/ui/i18n/zh/settings.js +354 -0
  81. package/ui/i18n/zh/tasks.js +232 -0
  82. package/ui/i18n/zh/usage.js +141 -0
  83. package/ui/i18n/zh/wechat.js +24 -0
  84. package/ui/i18n/zh.js +17 -236
  85. package/ui/modules/api.js +4 -3
  86. package/ui/modules/bot-quota.js +27 -0
  87. package/ui/modules/cards.js +96 -58
  88. package/ui/modules/chat.js +28 -30
  89. package/ui/modules/composer.js +41 -37
  90. package/ui/modules/dom-morph.js +292 -0
  91. package/ui/modules/events-board.js +22 -22
  92. package/ui/modules/events-click.js +100 -68
  93. package/ui/modules/events-misc.js +34 -34
  94. package/ui/modules/events-submit.js +28 -28
  95. package/ui/modules/global-pages.js +127 -116
  96. package/ui/modules/i18n.js +0 -5
  97. package/ui/modules/icons.js +0 -1
  98. package/ui/modules/markdown.js +1 -1
  99. package/ui/modules/modal-forms.js +195 -202
  100. package/ui/modules/modal-layer.js +6 -9
  101. package/ui/modules/page-shell.js +62 -0
  102. package/ui/modules/settings.js +211 -198
  103. package/ui/modules/solo-archive.js +0 -4
  104. package/ui/modules/state.js +57 -50
  105. package/ui/modules/tasks.js +168 -171
  106. package/ui/modules/typing-linger.js +1 -4
  107. package/ui/modules/usage.js +65 -78
  108. package/ui/modules/util.js +92 -25
  109. package/ui/styles/avatars.css +14 -0
  110. package/ui/styles/cards.css +49 -0
  111. package/ui/styles/chat-cards.css +17 -21
  112. package/ui/styles/global-config.css +59 -2
  113. package/ui/styles/modal.css +13 -0
  114. package/ui/styles/usage.css +3 -61
  115. package/CONTRIBUTING.md +0 -20
  116. package/docs/assets/usage-dark.png +0 -0
@@ -1,6 +1,3 @@
1
- // 排队气泡的乐观渲染与终态驻留(DSHBOTS-150)。
2
- // DSHBOTS-159 从 ui/app.js 的 typing-linger 标记块外迁:纯逻辑 + 模块级短命台账,不碰滚动。
3
- // 反向依赖 app.js 的 runStatusLabel(调用期解析:函数声明已提升,无 TDZ)。
4
1
  import { state } from './state.js'
5
2
  import { attr, avatar, botById, duration, esc } from './util.js'
6
3
  import { t } from './i18n.js'
@@ -264,7 +261,7 @@ function pruneTypingLinger(now = Date.now()) {
264
261
  for (const el of document.querySelectorAll(`[data-bubble-key="${key}"]`)) el.remove()
265
262
  }
266
263
  // 淡出段:两次轮询之间也按剩余时间刷新透明度。
267
- for (const el of document.querySelectorAll('[data-linger-until]')) {
264
+ for (const el of document.querySelectorAll('[data-linger-until]') ) {
268
265
  const remaining = Number(el.dataset.lingerUntil) - now
269
266
  el.style.opacity = String(remaining <= TYPING_LINGER_FADE_MS ? Math.max(0, remaining / TYPING_LINGER_FADE_MS) : 1)
270
267
  }
@@ -1,12 +1,10 @@
1
- // usage.js —— 用量域(DSHBOTS-121/56):时间窗快照、用量页与全局视图的用量面板。
2
- // 时间窗状态(usageWindowKey/Cache/Loading/Request)只服务本域,随本文件迁移;
3
- // 切换窗口的入口逻辑 switchUsageWindow 一并迁入(原在 app.js 的 click 委托里)。
4
- import { state, NAV, RUN_STATUS } from './state.js'
1
+ import { state, NAV, RUN_STATUS, labelText } from './state.js'
5
2
  import { icon } from './icons.js'
6
3
  import { CURRENCY_SYMBOL, attr, botById, costValue, esc, formatCost, formatNumber, pageProject, runDot, timeAgo, toast } from './util.js'
7
4
  import { api } from './api.js'
8
5
  import { t } from './i18n.js'
9
6
  import { renderUsageGlobal, renderUsageDomain, renderUsageSolo } from './settings.js'
7
+ import { pageHead, pageSection, refreshAction } from './page-shell.js'
10
8
  import { render } from '../app.js'
11
9
 
12
10
  // 用量时间窗(DSHBOTS-121):今日 / 7 日 / 30 日 / 至今 四档。
@@ -17,10 +15,10 @@ let usageWindowLoading = false
17
15
  let usageWindowRequest = 0
18
16
 
19
17
  const USAGE_WINDOWS = [
20
- { key: 'today', label: '今日' },
21
- { key: '7d', label: '7 日' },
22
- { key: '30d', label: '30 日' },
23
- { key: 'all', label: '至今' },
18
+ { key: 'today', label: 'usage.window.today' },
19
+ { key: '7d', label: 'usage.window.7d' },
20
+ { key: '30d', label: 'usage.window.30d' },
21
+ { key: 'all', label: 'usage.window.all' },
24
22
  ]
25
23
 
26
24
  // 时间窗取数上下文:跟页面口径一致——全局不带项目,单聊带 bot,本群带项目。
@@ -48,25 +46,25 @@ function usageWindowData() {
48
46
  // 当前窗口的一句话口径说明。
49
47
  function usageWindowText(usage) {
50
48
  const window = usage?.window ?? null
51
- if (!window) return `近 ${Number(usage?.days ?? 30) || 30} 天`
52
- if (window.key === 'today') return '今日(产品时区当日 0 点起)'
53
- if (window.key === '7d') return '近 7 天(滚动窗口)'
54
- if (window.key === '30d') return '近 30 天(滚动窗口)'
55
- return '至今(自最早一条明细起,不设下界)'
49
+ if (!window) return t('usage.windowTextFallback', { days: Number(usage?.days ?? 30) || 30 })
50
+ if (window.key === 'today') return t('usage.windowTextToday')
51
+ if (window.key === '7d') return t('usage.windowText7d')
52
+ if (window.key === '30d') return t('usage.windowText30d')
53
+ return t('usage.windowTextAll')
56
54
  }
57
55
 
58
56
  // 按日面板的标题与说明:跟当前时间窗走;没有窗口信息时回落到旧的 14 天口径。
59
57
  function usageDayPanelMeta(usage) {
60
58
  const key = String(usage?.window?.key ?? '')
61
- if (key === 'today') return { title: '今日', note: '产品时区(Asia/Shanghai)当日 0 点起。' }
62
- if (key === '7d') return { title: '近 7 天', note: '按产品时区(Asia/Shanghai)日历日分组。' }
63
- if (key === '30d') return { title: '近 30 天', note: '按产品时区(Asia/Shanghai)日历日分组。' }
64
- if (key === 'all') return { title: '近 30 天', note: '汇总全部历史;日历图只画最近 30 天,更早的调用计入上方汇总。' }
59
+ if (key === 'today') return { title: t('usage.dayTitleToday'), note: t("产品时区(Asia/Shanghai)当日 0 点起。") }
60
+ if (key === '7d') return { title: t('usage.dayTitle7d'), note: t("按产品时区(Asia/Shanghai)日历日分组。") }
61
+ if (key === '30d') return { title: t('usage.dayTitle30d'), note: t("按产品时区(Asia/Shanghai)日历日分组。") }
62
+ if (key === 'all') return { title: t('usage.dayTitle30d'), note: t("汇总全部历史;日历图只画最近 30 天,更早的调用计入上方汇总。") }
65
63
  return { title: '', note: '' }
66
64
  }
67
65
 
68
66
  function usageDayTitle(usage) {
69
- return usageDayPanelMeta(usage).title || '近 14 天'
67
+ return usageDayPanelMeta(usage).title || t('近 14 天')
70
68
  }
71
69
 
72
70
  function usageSnapshot() {
@@ -121,7 +119,7 @@ function usageCostParts(totals, currency) {
121
119
  // 成本文本:符号 + 金额;多币种时主币种在前,其余币种跟在后面(不再用 'CNY x / USD y')。
122
120
  function usageCostText(totals, currency) {
123
121
  const parts = usageCostParts(totals, currency)
124
- if (!parts.code) return '未配置'
122
+ if (!parts.code) return t('usage.costUnconfigured')
125
123
  const main = `${parts.symbol.trim()}${formatAmount(parts.amount)}`
126
124
  if (!parts.others.length) return main
127
125
  return `${main} + ${parts.others.map(other => `${other.code} ${formatAmount(other.amount)}`).join(' + ')}`
@@ -130,14 +128,14 @@ function usageCostText(totals, currency) {
130
128
  // 成本单元格只放主币种金额(保证列宽固定不折行),完整多币种金额进 title。
131
129
  function usageCostPrimaryText(totals, currency) {
132
130
  const parts = usageCostParts(totals, currency)
133
- if (!parts.code) return '未配置'
131
+ if (!parts.code) return t('usage.costUnconfigured')
134
132
  return formatCost(parts.amount, parts.code)
135
133
  }
136
134
 
137
135
  async function exportUsageCsv() {
138
136
  const usage = usageSnapshot()
139
137
  const project = pageProject()
140
- const payload = { days: usage.days ?? 30, window: usageWindowKey }
138
+ const payload = { days: usage.days ?? 30, window: usageWindowKey }
141
139
  // 导出口径跟随当前页面口径(DSHBOTS-56):
142
140
  // global=全局明细(不带任何过滤);domain=本群明细;solo=该 Bot 的项目外明细。
143
141
  const mode = usageMode()
@@ -145,7 +143,7 @@ async function exportUsageCsv() {
145
143
  if (mode === 'solo' && state.soloBotId) payload.soloBotId = state.soloBotId
146
144
  const result = await api('export_usage_csv', payload)
147
145
  const csv = String(result?.csv ?? '')
148
- if (!csv) throw new Error('导出内容为空,请稍后重试。')
146
+ if (!csv) throw new Error(t('usage.exportEmpty'))
149
147
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' })
150
148
  const url = URL.createObjectURL(blob)
151
149
  const link = document.createElement('a')
@@ -155,7 +153,7 @@ async function exportUsageCsv() {
155
153
  link.click()
156
154
  link.remove()
157
155
  setTimeout(() => URL.revokeObjectURL(url), 1000)
158
- toast('CSV 已导出', 'success')
156
+ toast(t('usage.exported'), 'success')
159
157
  }
160
158
 
161
159
  // 用量页三态(DSHBOTS-56):侧栏入口=全局视图(与群聊/单聊上下文零耦合);
@@ -187,7 +185,7 @@ function usageRowCells(item, label, hint, max, currency) {
187
185
  const fill = tokens > 0 ? `<span class="usage-fill${unpriced > 0 ? ' partial' : ''}" style="width:${ratio}%"></span>` : ''
188
186
  const cost = usageCostPrimaryText(item, currency)
189
187
  const costFull = usageCostText(item, currency)
190
- const costTitle = unpriced > 0 ? `${costFull}(含 ${unpriced} 次未计价调用,成本为部分值)` : costFull
188
+ const costTitle = unpriced > 0 ? `${costFull}${t('usage.partialCostSuffix', { count: unpriced })}` : costFull
191
189
  return `<span class="usage-col-name" title="${attr(label + hint)}">${esc(label)}</span>
192
190
  <span class="usage-track">${fill}</span>
193
191
  <span class="usage-col-num">${formatNumber(tokens)}</span>
@@ -202,16 +200,16 @@ function usageBarRow(item, label, max, currency, hint = '') {
202
200
  // 分 bot 行:drillable=true 时可点击查看该 bot 的运行记录。
203
201
  function usageBotRow(item, max, drillable, currency) {
204
202
  const botId = item.botId ?? item.id ?? ''
205
- const name = String(item.name ?? botById(botId)?.name ?? '').trim() || '未知 Bot'
203
+ const name = String(item.name ?? botById(botId)?.name ?? '').trim() || t('usage.unknownBot')
206
204
  const cells = usageRowCells(item, name, '', max, currency)
207
205
  if (!drillable) return `<div class="usage-row">${cells}</div>`
208
206
  const active = state.usageBot === botId
209
- return `<button type="button" class="usage-row usage-row-action${active ? ' active' : ''}" data-action="usage-drill" data-bot-id="${attr(botId)}" aria-pressed="${active}" title="查看该 Bot 在本群的运行记录">${cells}</button>`
207
+ return `<button type="button" class="usage-row usage-row-action${active ? ' active' : ''}" data-action="usage-drill" data-bot-id="${attr(botId)}" aria-pressed="${active}" title="${t('usage.drillTitle')}">${cells}</button>`
210
208
  }
211
209
 
212
210
  // 分项目行:行首只显示项目名/项目 key,不再回落到 prj_ raw id(D-67 P1-6),原始 id 只进 title。
213
211
  function usageProjectRow(item, max, currency) {
214
- const label = String(item.name ?? item.key ?? '').trim() || '未命名项目'
212
+ const label = String(item.name ?? item.key ?? '').trim() || t('未命名项目')
215
213
  const hint = item.projectId ? ` · ${item.projectId}` : ''
216
214
  return usageBarRow(item, label, max, currency, hint)
217
215
  }
@@ -219,28 +217,28 @@ function usageProjectRow(item, max, currency) {
219
217
  // 分布列表面板:表头给出列名与单位,行内只放数值。
220
218
  function usageListPanel(title, rows, nameLabel) {
221
219
  return `<div class="card usage-panel">
222
- <div class="card-head"><h3>${esc(title)}</h3><span class="meta">${rows.length} 个</span></div>
223
- ${rows.length === 0 ? '<div class="faint">暂无调用记录。</div>' : `<div class="usage-list">
220
+ <div class="card-head"><h3>${esc(title)}</h3><span class="meta">${t('usage.count', { count: rows.length })}</span></div>
221
+ ${rows.length === 0 ? `<div class="faint">${t('usage.empty')}</div>` : `<div class="usage-list">
224
222
  <div class="usage-list-head">
225
223
  <span class="usage-col-name">${esc(nameLabel)}</span>
226
- <span class="usage-col-bar">tokens 占比</span>
227
- <span class="usage-col-num">tokens</span>
228
- <span class="usage-col-num">调用</span>
229
- <span class="usage-col-num">成本</span>
224
+ <span class="usage-col-bar">${t('tokens 占比')}</span>
225
+ <span class="usage-col-num">${t('tokens')}</span>
226
+ <span class="usage-col-num">${t('调用')}</span>
227
+ <span class="usage-col-num">${t('成本')}</span>
230
228
  </div>
231
229
  ${rows.join('')}
232
230
  </div>
233
231
  <div class="usage-legend">
234
- <span class="usage-legend-item"><i class="usage-swatch"></i>已计价用量</span>
235
- <span class="usage-legend-item"><i class="usage-swatch star"></i>含未计价调用</span>
236
- <span class="usage-legend-item"><i class="usage-swatch empty"></i>零用量</span>
232
+ <span class="usage-legend-item"><i class="usage-swatch"></i>${t('usage.legendPriced')}</span>
233
+ <span class="usage-legend-item"><i class="usage-swatch star"></i>${t('usage.legendPartial')}</span>
234
+ <span class="usage-legend-item"><i class="usage-swatch empty"></i>${t('usage.legendZero')}</span>
237
235
  </div>`}
238
236
  </div>`
239
237
  }
240
238
 
241
239
  function usageRunRow(run) {
242
240
  return `<div class="run-row">
243
- <div class="run-row-top">${runDot(run.status)}<strong class="mono">${esc(String(run.id ?? '').slice(0, 8))}</strong><span>${esc(RUN_STATUS[run.status] ?? run.status)}</span><span style="margin-left:auto">${esc(timeAgo(run.queued_at))}</span></div>
241
+ <div class="run-row-top">${runDot(run.status)}<strong class="mono">${esc(String(run.id ?? '').slice(0, 8))}</strong><span>${esc(labelText(RUN_STATUS, run.status, 'runStatus.'))}</span><span style="margin-left:auto">${esc(timeAgo(run.queued_at))}</span></div>
244
242
  <div class="run-row-meta"><span>${esc(run.kind || '—')}</span><span>${formatNumber(Number(run.usage_input ?? 0) + Number(run.usage_output ?? 0))} tok</span>${run.usage_cost !== null && run.usage_cost !== undefined ? `<span>${formatCost(run.usage_cost)}</span>` : ''}</div>
245
243
  </div>`
246
244
  }
@@ -248,16 +246,16 @@ function usageRunRow(run) {
248
246
  // 同一模型名可能分属不同 provider(src/usage.js 按 provider+model 分组),用暗色标签区分。
249
247
  function usageModelCell(item) {
250
248
  const provider = String(item.provider ?? '').trim()
251
- const model = String(item.model ?? '').trim() || '未知模型'
249
+ const model = String(item.model ?? '').trim() || t('usage.unknownModel')
252
250
  const tag = provider ? `<span class="usage-tag">${esc(provider)}</span>` : ''
253
251
  return `${tag}<span class="usage-model-name" title="${attr(model)}">${esc(model)}</span>`
254
252
  }
255
253
 
256
254
  function usageModelPanel(byModel, title, headerExtra = '', currency = 'CNY') {
257
255
  return `<div class="card usage-panel">
258
- <div class="card-head"><h3>${esc(title)}</h3>${headerExtra || `<span class="meta">${byModel.length} 个</span>`}</div>
259
- ${byModel.length === 0 ? '<div class="faint">暂无调用记录。</div>' : `<table class="usage-table"><thead><tr><th class="eyebrow mono">模型</th><th class="eyebrow mono num">调用</th><th class="eyebrow mono num">tokens</th><th class="eyebrow mono num">成本</th></tr></thead><tbody>${byModel.map(item => `<tr><td class="usage-model-cell">${usageModelCell(item)}</td><td class="mono num">${formatNumber(item.calls)}</td><td class="mono num">${formatNumber(item.totalTokens)}</td><td class="mono num" title="${attr(usageCostText(item, currency))}">${esc(usageCostPrimaryText(item, currency))}</td></tr>`).join('')}</tbody></table>`}
260
- <div class="usage-note">未配置价格的调用不计入成本合计;价格按每百万 token 配置。</div>
256
+ <div class="card-head"><h3>${esc(title)}</h3>${headerExtra || `<span class="meta">${t('usage.count', { count: byModel.length })}</span>`}</div>
257
+ ${byModel.length === 0 ? `<div class="faint">${t('usage.empty')}</div>` : `<table class="usage-table"><thead><tr><th class="eyebrow mono">${t('模型')}</th><th class="eyebrow mono num">${t('调用')}</th><th class="eyebrow mono num">${t('tokens')}</th><th class="eyebrow mono num">${t('成本')}</th></tr></thead><tbody>${byModel.map(item => `<tr><td class="usage-model-cell">${usageModelCell(item)}</td><td class="mono num">${formatNumber(item.calls)}</td><td class="mono num">${formatNumber(item.totalTokens)}</td><td class="mono num" title="${attr(usageCostText(item, currency))}">${esc(usageCostPrimaryText(item, currency))}</td></tr>`).join('')}</tbody></table>`}
258
+ <div class="usage-note">${t('未配置价格的调用不计入成本合计;价格按每百万 token 配置。')}</div>
261
259
  </div>`
262
260
  }
263
261
 
@@ -274,31 +272,31 @@ function usageMetricCards(totals, scopeLabel, usage) {
274
272
  const perCall = calls > 0 ? totalTokens / calls : 0
275
273
  const costValue = cost.code
276
274
  ? `<span class="unit">${esc(cost.symbol.trim())}</span>${esc(formatAmount(cost.amount))}`
277
- : '未配置'
275
+ : t('usage.costUnconfigured')
278
276
  const costMeta = [
279
- ...cost.others.map(other => `另有 ${other.code} ${formatAmount(other.amount)}`),
280
- usage.priceCount ? `${usage.priceCount} 条价格规则` : '尚未配置模型价格',
277
+ ...cost.others.map(other => t('usage.costOther', { code: other.code, amount: formatAmount(other.amount) })),
278
+ usage.priceCount ? t('usage.priceRules', { count: usage.priceCount }) : t('usage.priceMissing'),
281
279
  ].join(' · ')
282
280
  return `<div class="metric-grid">
283
281
  <div class="card metric">
284
- <span class="metric-label">总 tokens(${esc(scopeLabel)})</span>
282
+ <span class="metric-label">${t('总 tokens(${scope})', { scope: scopeLabel })}</span>
285
283
  <strong>${formatNumber(totalTokens)}</strong>
286
- <small class="mono">入 ${formatNumber(totals.inputTokens)} · 出 ${formatNumber(totals.outputTokens)} · 缓存读 ${formatNumber(totals.cacheReadTokens)}</small>
284
+ <small class="mono">${t('usage.totalTokensMeta', { input: formatNumber(totals.inputTokens), output: formatNumber(totals.outputTokens), cache: formatNumber(totals.cacheReadTokens) })}</small>
287
285
  </div>
288
286
  <div class="card metric">
289
- <span class="metric-label">调用次数(${esc(scopeLabel)})</span>
287
+ <span class="metric-label">${t('调用次数(${scope})', { scope: scopeLabel })}</span>
290
288
  <strong>${formatNumber(calls)}</strong>
291
- <small class="mono">平均每次 ${formatNumber(perCall)} tokens</small>
289
+ <small class="mono">${t('usage.perCall', { value: formatNumber(perCall) })}</small>
292
290
  </div>
293
291
  <div class="card metric">
294
- <span class="metric-label">总成本(${esc(scopeLabel)})</span>
292
+ <span class="metric-label">${t('总成本(${scope})', { scope: scopeLabel })}</span>
295
293
  <strong class="metric-cost">${costValue}</strong>
296
294
  <small class="mono">${esc(costMeta)}</small>
297
295
  </div>
298
296
  <div class="card metric">
299
- <span class="metric-label">日均 tokens(${esc(scopeLabel)})</span>
297
+ <span class="metric-label">${t('日均 tokens(${scope})', { scope: scopeLabel })}</span>
300
298
  <strong>${formatNumber(dailyTokens)}</strong>
301
- <small class="mono">按 ${spanDays} 天汇总窗口折算</small>
299
+ <small class="mono">${t('usage.dailyMeta', { days: spanDays })}</small>
302
300
  </div>
303
301
  </div>`
304
302
  }
@@ -311,44 +309,33 @@ function usageDayPanel(days) {
311
309
  // 日期轴标签密度:柱子越多列越窄,标签按固定步长取,否则「MM/DD」会被列宽截成「10」。
312
310
  const labelStep = days.length > 20 ? 6 : 3
313
311
  return `<div class="card usage-panel">
314
- <div class="card-head"><h3>${esc(usageDayTitle(usage))}</h3>${peak && peak.totalTokens ? `<span class="meta">峰值 ${formatNumber(peak.totalTokens)} · ${esc(String(peak.day).slice(5))}</span>` : ''}</div>
315
- ${days.length === 0 ? '<div class="faint">暂无按日数据。</div>' : `<div class="day-bars">${days.map(day => `<div class="day-bar${day.totalTokens ? '' : ' zero'}" style="height:${Math.max(3, (day.totalTokens ?? 0) / maxDay * 100)}%" title="${esc(day.day)} · ${formatNumber(day.totalTokens)} tokens"></div>`).join('')}</div><div class="day-axis">${days.map((day, index) => `<span title="${esc(day.day)} · ${formatNumber(day.totalTokens)} tokens">${index === 0 || index === days.length - 1 || index % labelStep === 0 ? esc(String(day.day).slice(5).replace('-', '/')) : ''}</span>`).join('')}</div>`}
316
- <div class="usage-note">${esc(meta.note || '日历图只画最近 14 天,更早的调用计入上方汇总。')}</div>
312
+ <div class="card-head"><h3>${esc(usageDayTitle(usage))}</h3>${peak && peak.totalTokens ? `<span class="meta">${t('usage.dayPeak', { value: formatNumber(peak.totalTokens), day: String(peak.day).slice(5) })}</span>` : ''}</div>
313
+ ${days.length === 0 ? `<div class="faint">${t('usage.dayEmpty')}</div>` : `<div class="day-bars">${days.map(day => `<div class="day-bar${day.totalTokens ? '' : ' zero'}" style="height:${Math.max(3, (day.totalTokens ?? 0) / maxDay * 100)}%" title="${esc(day.day)} · ${formatNumber(day.totalTokens)} tokens"></div>`).join('')}</div><div class="day-axis">${days.map((day, index) => `<span title="${esc(day.day)} · ${formatNumber(day.totalTokens)} tokens">${index === 0 || index === days.length - 1 || index % labelStep === 0 ? esc(String(day.day).slice(5).replace('-', '/')) : ''}</span>`).join('')}</div>`}
314
+ <div class="usage-note">${esc(t(meta.note || t("日历图只画最近 14 天,更早的调用计入上方汇总。")))}</div>
317
315
  </div>`
318
316
  }
319
317
 
320
- // 用量页区块:真实标题(H2)+ 一行口径说明。页面不再只剩一个与 H1 重复的灰字 caption。
321
- function usageSection(title, desc, body, headExtra = '') {
322
- return `<section class="usage-section">
323
- <div class="usage-section-head">
324
- <div class="usage-section-title">
325
- <h2 class="usage-h2">${esc(title)}</h2>
326
- <p class="usage-desc">${esc(desc)}</p>
327
- </div>
328
- ${headExtra}
329
- </div>
330
- ${body}
331
- </section>`
318
+ // 用量页区块:序号 + 标题 + 说明 + 12 列槽位网格,与其余三个一级页共用同一分组语言。
319
+ function usageSection(index, id, title, desc, body, headExtra = '') {
320
+ return pageSection({ index, id, title, desc, body, headExtra })
332
321
  }
333
322
 
334
- // 页面头:单一声明统计窗口与本页口径,避免各面板各说一套。
323
+ // 页面头:标题跟随顶栏口径,右侧操作区放四档时间窗切换与 CSV 导出。
335
324
  // 时间窗切换(DSHBOTS-121):今日 / 7 日 / 30 日 / 至今;汇总、分布明细、CSV 导出同窗口。
336
325
  function usagePageHead(usage, scopeText, exportLabel = '') {
337
326
  const windowText = usageWindowText(usage)
338
- return `<div class="section-head usage-page-head">
339
- <div class="usage-head-meta">
327
+ const actions = `
340
328
  <div class="usage-window-row">
341
- <span class="usage-window">汇总窗口</span>
342
- <div class="seg" role="group" aria-label="汇总窗口">
343
- ${USAGE_WINDOWS.map(item => `<button data-action="usage-window" data-window="${item.key}" aria-pressed="${usageWindowKey === item.key}"${usageWindowLoading ? ' disabled' : ''}>${esc(item.label)}</button>`).join('')}
329
+ <span class="usage-window">${t('汇总窗口')}</span>
330
+ <div class="seg" role="group" aria-label="${t('汇总窗口')}">
331
+ ${USAGE_WINDOWS.map(item => `<button data-action="usage-window" data-window="${item.key}" aria-pressed="${usageWindowKey === item.key}"${usageWindowLoading ? ' disabled' : ''}>${t(item.label)}</button>`).join('')}
344
332
  </div>
345
333
  </div>
346
- <span class="usage-head-desc">${esc(scopeText)} · 当前窗口 ${esc(windowText)}${usageWindowLoading ? ' · 载入中…' : ''}</span>
347
- </div>
348
- <div class="btn-row">
349
- <button class="btn" data-action="export-usage-csv">${icon('download')}导出 CSV${exportLabel ? `(${esc(exportLabel)})` : ''}</button>
350
- </div>
351
- </div>`
334
+ <div class="btn-row">
335
+ <button class="btn" data-action="export-usage-csv">${icon('download')}${t('usage.exportCsv')}${exportLabel ? t("(${exportLabel})", { exportLabel: esc(exportLabel) }) : ''}</button>
336
+ ${usageMode() === 'global' ? refreshAction() : ''}
337
+ </div>`
338
+ return pageHead('USAGE', usageViewTitle(), t('usage.headDesc', { scope: scopeText, window: windowText, loading: usageWindowLoading ? t('usage.loading') : '' }), actions)
352
339
  }
353
340
 
354
341
  function renderUsage() {
@@ -1,5 +1,5 @@
1
- // 通用工具函数:转义、格式化、状态徽标与 toast。依赖 state.js 的运行态与枚举。
2
1
  import { state, STATUS, RUN_STATUS, FILE_POLICY, DEFAULT_FILE_POLICY } from './state.js'
2
+ import { t } from './i18n.js'
3
3
 
4
4
  const toastRoot = document.getElementById('toast-root')
5
5
  export function applyUiScale(value) {
@@ -39,11 +39,11 @@ export function actorLabel(raw) {
39
39
  const sep = value.indexOf(':')
40
40
  const type = sep >= 0 ? value.slice(0, sep) : ''
41
41
  const id = sep >= 0 ? value.slice(sep + 1) : value
42
- if (type === 'user' || (!type && (id === 'user' || id === 'owner'))) return state.data?.me?.name || '用户'
42
+ if (type === 'user' || (!type && (id === 'user' || id === 'owner'))) return state.data?.me?.name || t("用户")
43
43
  if (type === 'bot' || (!type && id.startsWith('bot_'))) {
44
44
  const bot = botById(id)
45
- if (bot) return `${bot.name}·${bot.role || '成员'}`
46
- return `已删除 Bot · ${shortRefId(id)}`
45
+ if (bot) return `${bot.name}·${bot.role || t("成员")}`
46
+ return t("已删除 Bot · ${id}", { id: shortRefId(id) })
47
47
  }
48
48
  return value
49
49
  }
@@ -66,7 +66,7 @@ export function formatNumber(value) {
66
66
  // format-tokens:end
67
67
  export const CURRENCY_SYMBOL = { CNY: '¥', RMB: '¥', USD: '$', EUR: '€', JPY: '¥' }
68
68
  export function formatCost(value, currency = 'CNY') {
69
- if (value === null || value === undefined) return '未配置'
69
+ if (value === null || value === undefined) return t("未配置")
70
70
  const code = String(currency || 'CNY').toUpperCase()
71
71
  const symbol = CURRENCY_SYMBOL[code] ?? `${code} `
72
72
  if (value === 0) return `${symbol}0.00`
@@ -77,17 +77,17 @@ export function timeAgo(value) {
77
77
  if (!value) return '—'
78
78
  const ms = Date.now() - new Date(value).getTime()
79
79
  if (!Number.isFinite(ms)) return '—'
80
- if (ms < 45_000) return '刚刚'
81
- if (ms < 3_600_000) return `${Math.floor(ms / 60_000)} 分钟前`
82
- if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)} 小时前`
83
- if (ms < 7 * 86_400_000) return `${Math.floor(ms / 86_400_000)} 天前`
80
+ if (ms < 45_000) return t("刚刚")
81
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)} ${t("分钟前")}`
82
+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)} ${t("小时前")}`
83
+ if (ms < 7 * 86_400_000) return `${Math.floor(ms / 86_400_000)} ${t("天前")}`
84
84
  return new Date(value).toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
85
85
  }
86
86
  export function formatTime(value) {
87
87
  if (!value) return ''
88
88
  return new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
89
89
  }
90
- export function duration(start, end) {
90
+ export function duration(start, end ) {
91
91
  if (!start) return '—'
92
92
  const ms = (end ? new Date(end).getTime() : Date.now()) - new Date(start).getTime()
93
93
  if (!Number.isFinite(ms) || ms < 0) return '—'
@@ -95,19 +95,52 @@ export function duration(start, end) {
95
95
  if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`
96
96
  return `${Math.floor(ms / 60_000)}m ${Math.floor((ms % 60_000) / 1000)}s`
97
97
  }
98
+ // avatar:start —— 头像取字与渲染的唯一出口(DSHBOTS-221 收敛点,散点内联一律改调这里)。
99
+ // initials:英文名取首二字母大写;非英文(CJK 等)取首字——单字居中不换行,修复两字竖排撑破头像块。
98
100
  export function initials(name) {
99
101
  const text = String(name ?? '?').trim()
100
- return /^[A-Za-z]/.test(text) ? text.slice(0, 2).toUpperCase() : text.slice(0, 2)
102
+ return /^[A-Za-z]/.test(text) ? text.slice(0, 2).toUpperCase() : text.slice(0, 1)
103
+ }
104
+ // identicon:GitHub 风格 5x5 镜像对称像素块头像(零依赖,纯 SVG 字符串内联)。
105
+ // seed 先过 FNV-1a 32 位散列,再逐位 xorshift 取随机:左半 3 列 × 5 行每位独立 50% 填充,
106
+ // 右两列沿中轴镜像;同 seed 同图。颜色不进 seed——沿用外层 .avatar 色类的 var(--av)。
107
+ export function identiconSvg(seed) {
108
+ let hash = 0x811c9dc5
109
+ const text = String(seed ?? '')
110
+ for (let i = 0; i < text.length; i++) {
111
+ hash ^= text.charCodeAt(i)
112
+ hash = Math.imul(hash, 0x01000193) >>> 0
113
+ }
114
+ const next = () => {
115
+ hash ^= hash << 13; hash >>>= 0
116
+ hash ^= hash >>> 17
117
+ hash ^= hash << 5; hash >>>= 0
118
+ return hash / 4294967296
119
+ }
120
+ let rects = ''
121
+ for (let row = 0; row < 5; row++) {
122
+ const left = [next() < 0.5, next() < 0.5, next() < 0.5]
123
+ const cells = [left[0], left[1], left[2], left[1], left[0]]
124
+ for (let col = 0; col < 5; col++) {
125
+ if (cells[col]) rects += `<rect x="${col}" y="${row}" width="1" height="1"/>`
126
+ }
127
+ }
128
+ return `<svg class="identicon" viewBox="0 0 5 5" aria-hidden="true">${rects}</svg>`
101
129
  }
130
+ // roll 用的随机种子:字母数字短串,满足服务端 avatarSeedPattern 校验。
131
+ export const avatarSeedRandom = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4)
102
132
  export function avatar(bot, size = '') {
103
- return `<div class="avatar ${attr(bot?.color ?? 'gray')} ${size}">${esc(initials(bot?.name ?? '?'))}</div>`
133
+ const seed = bot?.avatar_seed
134
+ const content = seed ? identiconSvg(seed) : esc(initials(bot?.name ?? '?'))
135
+ return `<div class="avatar ${attr(bot?.color ?? 'gray')} ${size}">${content}</div>`
104
136
  }
137
+ // avatar:end
105
138
  export function statusPill(status, text = STATUS[status] ?? status) {
106
139
  const tone = status === 'done' ? 'green' : status === 'blocked' || status === 'canceled' ? 'red' : status === 'in_review' ? 'violet' : status === 'in_progress' ? 'amber' : ''
107
140
  return `<span class="pill ${tone}">${esc(text)}</span>`
108
141
  }
109
142
  export function runDot(status) {
110
- return `<span class="run-dot ${attr(status ?? '')}" title="${attr(RUN_STATUS[status] ?? '未运行')}"></span>`
143
+ return `<span class="run-dot ${attr(status ?? '')}" title="${attr(RUN_STATUS[status] ?? t("未运行"))}"></span>`
111
144
  }
112
145
 
113
146
  // sandbox-pill:start —— 生效沙箱档位的轻量标签(DSHBOTS-157)。
@@ -122,7 +155,7 @@ const SANDBOX_TONE = {
122
155
  export function sandboxPill(mode) {
123
156
  if (!mode) return ''
124
157
  const tone = SANDBOX_TONE[mode] ?? ''
125
- return `<span class="pill ${tone}" title="${attr(`生效沙箱档位:${mode}`)}">沙箱 ${esc(mode)}</span>`
158
+ return `<span class="pill ${tone}" title="${attr(t("生效沙箱档位:${mode}", { mode: mode }))}">${t("沙箱")} ${esc(mode)}</span>`
126
159
  }
127
160
  // sandbox-pill:end
128
161
  // 成员/总监状态点:红黄绿三色——空闲绿、运行中黄(且仅此态闪烁)、失败红(含限流等待)。
@@ -133,25 +166,25 @@ export function memberRunDot(member) {
133
166
  const waitMin = member?.retry_wait_seconds ? Math.max(1, Math.round(member.retry_wait_seconds / 60)) : null
134
167
  if (status === 'running') {
135
168
  return phase === 'running'
136
- ? { cls: 'running', status: 'running', text: '运行中' }
137
- : { cls: 'idle', status: 'queued', text: '排队中(按空闲计)' }
169
+ ? { cls: 'running', status: 'running', text: t("运行中") }
170
+ : { cls: 'idle', status: 'queued', text: t("排队中(按空闲计)") }
138
171
  }
139
- if (status === 'plan_wait') return { cls: 'plan-wait', status: 'plan_wait', text: `限流等待,约 ${waitMin} 分钟后自动重试` }
140
- if (status === 'failed') return { cls: 'failed', status: 'failed', text: '最近运行失败' }
141
- return { cls: 'idle', status: 'idle', text: '空闲' }
172
+ if (status === 'plan_wait') return { cls: 'plan-wait', status: 'plan_wait', text: t("限流等待,约 ${waitMin} 分钟后自动重试", { waitMin: waitMin }) }
173
+ if (status === 'failed') return { cls: 'failed', status: 'failed', text: t("最近运行失败") }
174
+ return { cls: 'idle', status: 'idle', text: t("空闲") }
142
175
  }
143
176
  export function runDotHtml(dot) {
144
177
  return `<span class="run-dot ${dot.cls}" data-status="${dot.status}" title="${esc(dot.text)}" aria-label="${esc(dot.text)}"></span>`
145
178
  }
146
179
  // 卡片底部的状态短标签(完整说明仍在 run-dot 的 title 里)。
147
- export const MEMBER_STATUS_TEXT = { idle: '空闲', running: '运行中', queued: '排队中', plan_wait: '限流等待', failed: '运行失败' }
180
+ export const MEMBER_STATUS_TEXT = { idle: t("空闲"), running: t("运行中"), queued: t("排队中"), plan_wait: t("限流等待"), failed: t("运行失败") }
148
181
  export function memorySource(source) {
149
182
  const value = String(source ?? '')
150
- if (!value) return '手动写入'
151
- if (value === 'chat-command') return '群聊指令'
152
- if (value.startsWith('run:')) return '运行沉淀'
153
- if (value.startsWith('session:')) return '会话沉淀'
154
- return '自动沉淀'
183
+ if (!value) return t("手动写入")
184
+ if (value === 'chat-command') return t("群聊指令")
185
+ if (value.startsWith('run:')) return t("运行沉淀")
186
+ if (value.startsWith('session:')) return t("会话沉淀")
187
+ return t("自动沉淀")
155
188
  }
156
189
 
157
190
  export function filePolicyOptions(current) {
@@ -172,3 +205,37 @@ export function toast(message, type = '') {
172
205
  }, 3600)
173
206
  }
174
207
 
208
+ // 提案展示辅助(DSHBOTS-223 自 tasks.ts 迁入,tasks.ts 触及 800 行铁律):
209
+ // 灰度范围、评估结论、payload 预览(instructions/skill 内容/兜底 JSON)三段纯格式化。
210
+ export function canaryText(canary) {
211
+ if (!canary) return ''
212
+ if (typeof canary === 'string') return canary
213
+ if (typeof canary === 'object') {
214
+ const parts = Object.entries(canary).map(([key, value]) => {
215
+ const label = key === 'projectIds' ? t("项目") : key
216
+ const values = Array.isArray(value) ? value.join(t("、")) : String(value)
217
+ return `${label} ${values}`
218
+ })
219
+ return parts.join(' · ')
220
+ }
221
+ return String(canary)
222
+ }
223
+
224
+ export function evaluationText(evaluation) {
225
+ if (!evaluation) return ''
226
+ if (typeof evaluation === 'string') return evaluation
227
+ const verdict = { pass: t("通过"), fail: t("不通过"), pending: t("待评估") }[evaluation.verdict] ?? evaluation.verdict ?? ''
228
+ const notes = evaluation.notes ? `${t(":")}${evaluation.notes}` : ''
229
+ const by = evaluation.evaluatedBy ? `${t("(")}${evaluation.evaluatedBy}${t(")")}` : ''
230
+ return `${verdict}${notes}${by}`
231
+ }
232
+
233
+ export function proposalPreview(proposal) {
234
+ const payload = proposal.payload ?? {}
235
+ if (proposal.kind === 'skill') return payload.content || t("技能内容为空")
236
+ if (proposal.kind === 'bot_update') {
237
+ return [payload.role ? `role: ${payload.role}` : '', payload.instructions ? `instructions:\n${payload.instructions}` : '', payload.model ? `model: ${payload.provider}/${payload.model}` : ''].filter(Boolean).join('\n\n') || t("无配置内容")
238
+ }
239
+ return JSON.stringify(payload, null, 2)
240
+ }
241
+
@@ -51,4 +51,18 @@
51
51
  .avatar.gray {
52
52
  --av: var(--c-gray);
53
53
  }
54
+ /* 像素块头像(DSHBOTS-221):identicon SVG 占头像块内 72%,颜色继承 var(--av)。 */
55
+ .avatar .identicon {
56
+ width: 72%;
57
+ height: 72%;
58
+ display: block;
59
+ fill: var(--av, var(--c-gray));
60
+ }
61
+ /* 设置表单里外观颜色一行右侧的 roll / 启用按钮组。 */
62
+ .avatar-roll-row {
63
+ display: flex;
64
+ align-items: center;
65
+ gap: 8px;
66
+ margin-top: 8px;
67
+ }
54
68
 
@@ -120,6 +120,26 @@
120
120
  .bot-status.archived::before {
121
121
  background: var(--line-2);
122
122
  }
123
+ /* Quota exhaustion reads as a state, not a second status chip: quiet text with a warning dot. */
124
+ .quota-badge {
125
+ margin-left: 8px;
126
+ padding: 1px 7px;
127
+ border: 1px solid var(--line-2);
128
+ border-radius: 999px;
129
+ font: 500 var(--fs-caption) var(--sans);
130
+ letter-spacing: 0.08em;
131
+ color: var(--ink-3);
132
+ }
133
+ .quota-badge::before {
134
+ content: "";
135
+ display: inline-block;
136
+ width: 5px;
137
+ height: 5px;
138
+ margin-right: 4px;
139
+ border-radius: 50%;
140
+ background: var(--red, #d64545);
141
+ vertical-align: 1px;
142
+ }
123
143
 
124
144
  .list-card {
125
145
  overflow: hidden;
@@ -279,4 +299,33 @@
279
299
  .proposal-diff[open] > summary .chev {
280
300
  transform: rotate(90deg);
281
301
  }
302
+ /* 待审批提案逐条展开(DSHBOTS-223):summary 复用 .list-row 版式,行分隔线移到 details 上,
303
+ 避免折叠时 summary 与行底线叠出双线。 */
304
+ .proposal-item {
305
+ border-bottom: 1px solid var(--line);
306
+ }
307
+ .proposal-item:last-child {
308
+ border-bottom: 0;
309
+ }
310
+ .proposal-item > summary.list-row {
311
+ cursor: pointer;
312
+ list-style: none;
313
+ border-bottom: 0;
314
+ }
315
+ .proposal-item > summary.list-row::-webkit-details-marker {
316
+ display: none;
317
+ }
318
+ .proposal-item > summary.list-row .chev {
319
+ align-self: center;
320
+ flex: none;
321
+ }
322
+ .proposal-item[open] > summary .chev {
323
+ transform: rotate(90deg);
324
+ }
325
+ .proposal-item-body {
326
+ padding: 0 16px 14px;
327
+ }
328
+ .proposal-item-body .proposal-body {
329
+ margin-top: 10px;
330
+ }
282
331