dsh-colophon 0.2.6 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## 0.3.0(配置页重做 + 每个触发独立引擎 + 用量折线图)
2
+
3
+ - 插件显示名改为 **colophon总结**;对话内入口统一叫 **生成总结**。
4
+ - 配置页每个分组独立成卡片(圆角描边),分组标题 16px + 主题强调色,字段名 14px,提示 12px。
5
+ - 摘要区块从 9 行长列表改为 3 列紧凑开关,勾选态有 ✓ 与强调色描边。
6
+ - 触发时机支持**逐个配置生成方式**:跟随全局 / 本地规则 / API 摘要 / 智能结合;全局引擎为本地规则时自动禁用 API 选项(API 前提不满足时给出提示)。
7
+ - API 摘要设置重排为「服务商与模型」「计费与预算」两级结构;服务商改为中文下拉「DeepSeek 官方」,模型也改为下拉(deepseek-chat / deepseek-reasoner)。
8
+ - 所有选择型配置统一为下拉控件:显示「当前:xxx」并带 ▾ 下拉指示。
9
+ - 价格字段改名并补充说明:**模型输入价格 / 模型输出价格**(元 / 百万 token,用于估算费用)。
10
+ - 用量区改为折线图 + 统计卡:默认展示**本周**(周一为起点)的 token 趋势,可切换 本小时 / 今天 / 本周 / 本月 / 自定义区间;没有 API 调用时显示空态提示。
11
+ - 新增 `GET /api/colophon/usage/series?kind=week|today|month` 与 `?from=&to=` 分桶接口;`triggers.*.engine` 与 `sections` 默认值进入配置模型。
12
+
1
13
  ## 0.2.6(入口按钮更明显)
2
14
 
3
15
  - 输入框上方的入口改成实心感按钮:主题强调色文字与描边、浅色填充、圆角 10px、悬停加深并带投影。
package/client.js CHANGED
@@ -228,6 +228,158 @@ window.__ModuleLoader__.load({
228
228
  }
229
229
 
230
230
  /** Translate a key, interpolating `{name}` placeholders. */
231
+
232
+ Object.assign(DICT.zh, {
233
+ chipReady: '生成总结',
234
+ chipEmpty: '生成总结',
235
+ panelTitle: 'colophon总结',
236
+ settingsLabel: 'colophon总结',
237
+ currentLabel: '当前:',
238
+ subtitle: '把每次对话的最终结论留在本地;重开会话时先看结论,不必重读整段历史。',
239
+ apiDisabledHint: 'API 未启用',
240
+ engineLabel: '摘要引擎',
241
+ engineLocal: '本地规则(0 token)',
242
+ engineApi: 'API 摘要',
243
+ engineInherit: '跟随全局',
244
+ engineSmart: '智能结合',
245
+ engineRulesHint: '完全本地生成,不调用模型,不消耗 token。',
246
+ engineApiHint: '调用模型生成更完整的总结;每次调用受下方预算限制。',
247
+ engineApiBlocked: '摘要引擎为“本地规则”,API 未启用;如需 API,请先在上方切换引擎。',
248
+ triggerEngineLabel: '生成方式',
249
+ onIdleHint: '智能体停止后几秒内写出总结。',
250
+ onSwitchHint: '在另一个会话里开始输入时,先总结上一个会话。',
251
+ closeBatchHint: '退出前为最近的会话集中生成总结。',
252
+ batchLimit: '批量上限',
253
+ batchWarn: '注意:退出前集中调用模型会一次性消耗较多 token,超出预算的会进入待确认队列。',
254
+ apiTitle: 'API 摘要设置',
255
+ apiHint: 'API 摘要为可选项;每次调用前会检查单次费用上限与每日 token 预算。',
256
+ apiNeedEngine: '当前引擎为本地规则,以下 API 设置不会生效。',
257
+ apiModelSub: '服务商与模型',
258
+ apiCostSub: '计费与预算',
259
+ apiProviderLabel: '服务商',
260
+ apiProviderHint: '提供模型服务的平台',
261
+ apiModelLabel: '模型名称',
262
+ apiModelHint: '例如 deepseek-chat',
263
+ providerDeepseek: 'DeepSeek 官方',
264
+ inputPrice: '输入价格',
265
+ inputPriceHint: '模型读取内容的价格,按每百万 token 计费,用于估算费用。',
266
+ outputPrice: '输出价格',
267
+ outputPriceHint: '模型生成内容的价格,按每百万 token 计费,用于估算费用。',
268
+ priceUnit: '元 / 百万 token',
269
+ yuan: '元',
270
+ tokens: 'token',
271
+ perSummaryCap: '单次摘要费用上限',
272
+ perSummaryCapHint: '一次总结最多花多少钱,超过就按下面策略处理。',
273
+ dailyBudget: '每日 token 预算',
274
+ dailyBudgetHint: '每天所有 API 摘要合计不超过这个 token 数。',
275
+ overCap: '超出预算时',
276
+ overCapHint: '达到单次或每日上限后的处理方式。',
277
+ overCapQueue: '排队,等我确认',
278
+ overCapSkip: '直接跳过,改用本地',
279
+ filterTitle: '会话筛选',
280
+ minMessages: '最少消息条数',
281
+ minMessagesHint: '短于这个消息数的会话不生成总结。',
282
+ minTokens: '最少 token 数',
283
+ minTokensHint: '估算 token 少于该值的会话不生成总结。',
284
+ unitMessages: '条',
285
+ unitTokens: 'token',
286
+ queueHint: '下面这些会话因为预算上限没有调用模型,等你确认后才会继续。',
287
+ queueEmpty: '没有等待确认的会话',
288
+ processQueue: '处理队列',
289
+ usageTitle: '用量',
290
+ usageApiHint: '只统计 API 摘要的实际调用',
291
+ usageRulesHint: '本地规则不消耗 token',
292
+ rangeHour: '本小时',
293
+ rangeWeek: '本周',
294
+ rangeToday: '今天',
295
+ rangeMonth: '本月',
296
+ rangeCustom: '自定义',
297
+ usageEmpty: '这段时间还没有 API 摘要调用(本地规则不消耗 token)',
298
+ chartAria: 'token 消耗趋势图',
299
+ chartPeak: '峰值',
300
+ chartLast: '最近',
301
+ save: '保存修改',
302
+ saveHint: '保存后立即生效,无需重启。',
303
+ statusOn: '已启用',
304
+ statusOff: '已暂停',
305
+ engineRulesHint: '完全本地生成,不调用模型,不消耗 token。',
306
+ })
307
+
308
+ Object.assign(DICT.en, {
309
+ chipReady: 'Generate summary',
310
+ chipEmpty: 'Generate summary',
311
+ panelTitle: 'colophon summary',
312
+ settingsLabel: 'colophon summary',
313
+ currentLabel: 'Current: ',
314
+ subtitle: 'Keep each conversation’s final conclusion on disk; see it first when you reopen the session.',
315
+ apiDisabledHint: 'API off',
316
+ engineLabel: 'Summary engine',
317
+ engineLocal: 'Local rules (0 token)',
318
+ engineApi: 'API summary',
319
+ engineInherit: 'Follow global',
320
+ engineSmart: 'Smart mix',
321
+ engineRulesHint: 'Fully local; no model call, no tokens.',
322
+ engineApiHint: 'Calls the model for richer summaries; every call is budget-gated below.',
323
+ engineApiBlocked: 'The engine is “local rules”, so API is off. Switch the engine above to enable it.',
324
+ triggerEngineLabel: 'Generate with',
325
+ onIdleHint: 'Write the summary a few seconds after the agent stops.',
326
+ onSwitchHint: 'When you start typing in another session, summarize the previous one.',
327
+ closeBatchHint: 'On quit, summarize the most recent sessions.',
328
+ batchLimit: 'Batch limit',
329
+ batchWarn: 'Note: batching calls the model right before quit and can spend a lot at once; over-budget ones wait in the queue.',
330
+ apiTitle: 'API summary settings',
331
+ apiHint: 'Optional. Every call checks the per-summary cost cap and the daily token budget.',
332
+ apiNeedEngine: 'The engine is local rules, so these API settings have no effect.',
333
+ apiModelSub: 'Provider and model',
334
+ apiCostSub: 'Cost and budget',
335
+ apiProviderLabel: 'Provider',
336
+ apiProviderHint: 'Where the model is served from',
337
+ apiModelLabel: 'Model name',
338
+ apiModelHint: 'e.g. deepseek-chat',
339
+ providerDeepseek: 'DeepSeek official',
340
+ inputPrice: 'Input price',
341
+ inputPriceHint: 'What the model charges to read a prompt, per million tokens; used to estimate cost.',
342
+ outputPrice: 'Output price',
343
+ outputPriceHint: 'What the model charges to write a reply, per million tokens; used to estimate cost.',
344
+ priceUnit: 'CNY / M tokens',
345
+ yuan: 'CNY',
346
+ tokens: 'tokens',
347
+ perSummaryCap: 'Cost cap per summary',
348
+ perSummaryCapHint: 'The most one summary may cost; beyond it the policy below applies.',
349
+ dailyBudget: 'Daily token budget',
350
+ dailyBudgetHint: 'All API summaries together stay under this many tokens per day.',
351
+ overCap: 'When over budget',
352
+ overCapHint: 'What to do after hitting the per-summary or daily cap.',
353
+ overCapQueue: 'Queue for my confirmation',
354
+ overCapSkip: 'Skip and use local',
355
+ filterTitle: 'Session filter',
356
+ minMessages: 'Minimum messages',
357
+ minMessagesHint: 'Sessions shorter than this never get a summary.',
358
+ minTokens: 'Minimum tokens',
359
+ minTokensHint: 'Sessions estimated below this are skipped.',
360
+ unitMessages: 'msgs',
361
+ unitTokens: 'tokens',
362
+ queueHint: 'These sessions skipped the model because of the budget cap; they wait for your confirmation.',
363
+ queueEmpty: 'Nothing waiting for confirmation',
364
+ processQueue: 'Process queue',
365
+ usageTitle: 'Usage',
366
+ usageApiHint: 'counts real API summary calls only',
367
+ usageRulesHint: 'local rules spend nothing',
368
+ rangeHour: 'Hour',
369
+ rangeWeek: 'This week',
370
+ rangeToday: 'Today',
371
+ rangeMonth: 'This month',
372
+ rangeCustom: 'Custom',
373
+ usageEmpty: 'No API summaries in this window (local rules spend no tokens)',
374
+ chartAria: 'token usage trend',
375
+ chartPeak: 'Peak',
376
+ chartLast: 'Latest',
377
+ save: 'Save changes',
378
+ saveHint: 'Saves and applies immediately; no restart needed.',
379
+ statusOn: 'Enabled',
380
+ statusOff: 'Paused',
381
+ })
382
+
231
383
  function tr(key, params) {
232
384
  const text = (DICT[zh ? 'zh' : 'en'][key] ?? key).replace(/\{(\w+)\}/gu, (_, name) => String(params?.[name] ?? ''))
233
385
  return text
@@ -856,6 +1008,98 @@ window.__ModuleLoader__.load({
856
1008
  count ? onText : on ? onText : offText)
857
1009
  }
858
1010
  /** Digest blocks the user can include, in presentation order. */
1011
+
1012
+ Object.assign(ui, {
1013
+ page: { display: 'flex', flexDirection: 'column', maxWidth: 760, padding: '2px 0 40px', gap: 12, color: 'var(--dsw-alias-label-primary, #e9edf3)' },
1014
+ header: { display: 'flex', flexDirection: 'column', gap: 5, padding: '2px 0 4px' },
1015
+ title: { display: 'flex', alignItems: 'center', gap: 10, fontSize: 20, fontWeight: 700, letterSpacing: '-0.01em' },
1016
+ subtitle: { fontSize: 13, lineHeight: 1.6, color: 'var(--dsw-alias-label-tertiary, #8b93a1)' },
1017
+ meta: { fontSize: 12, color: 'var(--dsw-alias-label-quaternary, #6d7686)' },
1018
+ card: { background: 'var(--dsw-alias-bg-layer-1, rgba(255,255,255,0.028))', border: '1px solid var(--dsw-alias-border-l1, rgba(255,255,255,0.08))', borderRadius: 12, padding: '14px 16px 8px' },
1019
+ cardMuted: { opacity: 0.75 },
1020
+ cardTitle: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 16, fontWeight: 700, color: 'var(--dsw-alias-state-business-primary, #6d97ff)', padding: '2px 0 2px' },
1021
+ cardTitleBar: { width: 3, height: 16, borderRadius: 2, background: 'currentColor' },
1022
+ cardHint: { fontSize: 12, color: 'var(--dsw-alias-label-tertiary, #8b93a1)', padding: '2px 0 2px', lineHeight: 1.5 },
1023
+ cardRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18, padding: '12px 0', borderTop: '1px solid var(--dsw-alias-border-l1, rgba(255,255,255,0.055))' },
1024
+ rowMain: { display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0, flex: '1 1 auto' },
1025
+ rowSide: { display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto' },
1026
+ label: { fontSize: 14, fontWeight: 500, color: 'var(--dsw-alias-label-primary, #e9edf3)' },
1027
+ labelSm: { fontSize: 12, color: 'var(--dsw-alias-label-tertiary, #8b93a1)' },
1028
+ hint: { fontSize: 12, lineHeight: 1.5, color: 'var(--dsw-alias-label-tertiary, #8b93a1)' },
1029
+ input: { height: 32, padding: '0 10px', border: '1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2, rgba(255,255,255,0.05))', color: 'var(--dsw-alias-label-primary, #e9edf3)', fontSize: 13, outline: 'none', width: 120, boxSizing: 'border-box' },
1030
+ inputDisabled: { opacity: 0.55 },
1031
+ chipGrid: { display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0, 1fr))', gap: 8, padding: '12px 0 10px' },
1032
+ secChip: { height: 32, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '0 10px', border: '1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', borderRadius: 8, background: 'transparent', color: 'var(--dsw-alias-label-secondary, #b7bec9)', fontSize: 13, cursor: 'pointer' },
1033
+ secChipOn: { border: '1px solid var(--dsw-alias-state-business-primary, #6d97ff)', color: 'var(--dsw-alias-state-business-primary, #6d97ff)', background: 'color-mix(in srgb, var(--dsw-alias-state-business-primary, #6d97ff) 12%, transparent)' },
1034
+ secChipMark: { width: 12, textAlign: 'center', fontSize: 12 },
1035
+ enginePick: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 },
1036
+ enginePickLabel: { fontSize: 12, color: 'var(--dsw-alias-label-quaternary, #6d7686)' },
1037
+ batchNum: { display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 },
1038
+ subGroup: { marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--dsw-alias-border-l1, rgba(255,255,255,0.055))', fontSize: 13, fontWeight: 650, color: 'var(--dsw-alias-label-secondary, #b7bec9)' },
1039
+ ddWrap: { position: 'relative' },
1040
+ dd: { height: 32, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '0 10px', border: '1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2, rgba(255,255,255,0.05))', color: 'var(--dsw-alias-label-primary, #e9edf3)', fontSize: 13, cursor: 'pointer', minWidth: 168, justifyContent: 'flex-start' },
1041
+ ddDisabled: { opacity: 0.55, cursor: 'not-allowed' },
1042
+ ddCurrent: { fontSize: 12, color: 'var(--dsw-alias-label-quaternary, #6d7686)' },
1043
+ ddValue: { fontSize: 13, fontWeight: 500 },
1044
+ ddChevron: { marginLeft: 'auto', fontSize: 11, color: 'var(--dsw-alias-label-tertiary, #8b93a1)' },
1045
+ ddList: { position: 'absolute', top: 36, right: 0, minWidth: 210, padding: 4, borderRadius: 10, border: '1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', background: 'var(--dsw-alias-bg-layer-2, #1f2329)', boxShadow: '0 12px 32px rgba(0,0,0,0.35)', zIndex: 30 },
1046
+ ddItem: { display: 'flex', alignItems: 'center', gap: 6, width: '100%', height: 32, padding: '0 8px', border: 0, borderRadius: 6, background: 'transparent', color: 'var(--dsw-alias-label-primary, #e9edf3)', fontSize: 13, cursor: 'pointer', textAlign: 'left' },
1047
+ ddItemOn: { background: 'color-mix(in srgb, var(--dsw-alias-state-business-primary, #6d97ff) 16%, transparent)', color: 'var(--dsw-alias-state-business-primary, #6d97ff)' },
1048
+ ddItemCheck: { width: 12, textAlign: 'center', fontSize: 12 },
1049
+ usageHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '8px 0 4px', flexWrap: 'wrap' },
1050
+ tabs: { display: 'inline-flex', gap: 2, padding: 2, borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2, rgba(255,255,255,0.05))' },
1051
+ tab: { height: 28, padding: '0 10px', border: 0, borderRadius: 6, background: 'transparent', color: 'var(--dsw-alias-label-tertiary, #8b93a1)', fontSize: 12, cursor: 'pointer' },
1052
+ tabOn: { background: 'color-mix(in srgb, var(--dsw-alias-state-business-primary, #6d97ff) 16%, transparent)', color: 'var(--dsw-alias-state-business-primary, #6d97ff)', fontWeight: 600 },
1053
+ customRow: { display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0 8px', flexWrap: 'wrap' },
1054
+ chart: { display: 'block', width: '100%', height: 160, marginTop: 6 },
1055
+ chartArea: { fill: 'color-mix(in srgb, var(--dsw-alias-state-business-primary, #6d97ff) 16%, transparent)', stroke: 'none' },
1056
+ chartLine: { fill: 'none', stroke: 'var(--dsw-alias-state-business-primary, #6d97ff)', strokeWidth: 2, strokeLinejoin: 'round', strokeLinecap: 'round' },
1057
+ chartDot: { fill: 'var(--dsw-alias-state-business-primary, #6d97ff)' },
1058
+ chartAxis: { fontSize: 10, fill: 'var(--dsw-alias-label-quaternary, #6d7686)' },
1059
+ chartFoot: { display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--dsw-alias-label-quaternary, #6d7686)', padding: '2px 2px 6px' },
1060
+ chartEmpty: { padding: '20px 0', marginTop: 8, border: '1px dashed var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', borderRadius: 10, fontSize: 13, color: 'var(--dsw-alias-label-quaternary, #6d7686)', textAlign: 'center' },
1061
+ statGrid: { display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 8, padding: '10px 0 6px' },
1062
+ statCard: { background: 'var(--dsw-alias-bg-layer-1, rgba(255,255,255,0.028))', border: '1px solid var(--dsw-alias-border-l1, rgba(255,255,255,0.08))', borderRadius: 10, padding: '10px 12px' },
1063
+ statLabel: { fontSize: 12, color: 'var(--dsw-alias-label-tertiary, #8b93a1)' },
1064
+ statValue: { fontSize: 18, fontWeight: 650, margin: '4px 0 2px' },
1065
+ statFoot: { fontSize: 12, color: 'var(--dsw-alias-label-quaternary, #6d7686)' },
1066
+ queueEmpty: { margin: '8px 0', padding: '12px 0', border: '1px dashed var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', borderRadius: 10, fontSize: 12, color: 'var(--dsw-alias-label-quaternary, #6d7686)', textAlign: 'center' },
1067
+ queueRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '9px 0', borderTop: '1px solid var(--dsw-alias-border-l1, rgba(255,255,255,0.055))', fontSize: 12 },
1068
+ queueTitle: { fontFamily: 'ui-monospace, monospace', fontSize: 11, color: 'var(--dsw-alias-label-secondary, #b7bec9)' },
1069
+ queueReason: { color: 'var(--dsw-alias-state-warn-label, #eed7a6)' },
1070
+ inlineActions: { display: 'flex', justifyContent: 'flex-end', padding: '10px 0 8px' },
1071
+ buttonPrimary: { height: 32, padding: '0 16px', border: 0, borderRadius: 8, background: 'var(--dsw-alias-button-primary-fill, #4f7cff)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer' },
1072
+ buttonSecondary: { height: 30, padding: '0 12px', border: '1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))', borderRadius: 8, background: 'transparent', color: 'var(--dsw-alias-label-primary, #e9edf3)', fontSize: 12, cursor: 'pointer' },
1073
+ buttonDisabled: { opacity: 0.5, cursor: 'not-allowed', boxShadow: 'none' },
1074
+ footer: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginTop: 4, paddingTop: 12, borderTop: '1px solid var(--dsw-alias-border-l1, rgba(255,255,255,0.08))' },
1075
+ footerOk: { fontSize: 12, color: 'var(--dsw-alias-state-success-primary, #7fd7a2)' },
1076
+ footerBad: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #ffb3b3)' },
1077
+ loading: { padding: '24px 0', fontSize: 13, color: 'var(--dsw-alias-label-tertiary, #8b93a1)' },
1078
+ })
1079
+
1080
+ /** Small status pill. */
1081
+ function Pill({ on, onText, offText, count }) {
1082
+ return h('span', {
1083
+ style: {
1084
+ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '1px 8px', borderRadius: 999,
1085
+ fontSize: 12, fontWeight: 500,
1086
+ color: on ? 'var(--dsw-alias-state-success-primary, #7fd7a2)' : 'var(--dsw-alias-label-tertiary, #8b93a1)',
1087
+ background: on ? 'rgba(127,215,162,0.12)' : 'rgba(255,255,255,0.06)',
1088
+ },
1089
+ }, typeof count === 'number' ? count : (on ? (onText ?? tr('statusOn')) : (offText ?? tr('statusOff'))))
1090
+ }
1091
+
1092
+ /** One compact numeric input with an optional unit suffix. */
1093
+ function NumberInput({ value, onChange, step = 1, min, max, unit, disabled }) {
1094
+ return h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 6 } },
1095
+ h('input', {
1096
+ type: 'number', value, step, min, max, disabled,
1097
+ style: { ...ui.input, width: 120, ...(disabled ? ui.inputDisabled : null) },
1098
+ onChange: event => onChange(event.target.value),
1099
+ }),
1100
+ unit ? h('span', { style: ui.labelSm }, unit) : null)
1101
+ }
1102
+
859
1103
  const SECTION_META = [
860
1104
  ['goal', 'secGoal', 'secGoalHint'],
861
1105
  ['conclusion', 'secConclusion', 'secConclusionHint'],
@@ -868,24 +1112,114 @@ window.__ModuleLoader__.load({
868
1112
  ['questions', 'secQuestions', 'secQuestionsHint'],
869
1113
  ]
870
1114
 
871
- /** Settings page: native DSH layout (rows + hairlines) and token colors. */
1115
+ /** One selectable control with an explicit "当前" marker and a chevron. */
1116
+ function Dropdown({ value, options, onChange, disabled }) {
1117
+ const [open, setOpen] = useState(false)
1118
+ const selected = options.find(option => option.value === value) ?? options[0]
1119
+ const style = { ...ui.dd, ...(disabled ? ui.ddDisabled : null) }
1120
+ return h('div', { style: ui.ddWrap },
1121
+ h('button', {
1122
+ type: 'button', style,
1123
+ 'aria-haspopup': 'listbox', 'aria-expanded': open,
1124
+ disabled,
1125
+ onClick: () => setOpen(current => !current),
1126
+ },
1127
+ h('span', { style: ui.ddCurrent }, tr('currentLabel')),
1128
+ h('span', { style: ui.ddValue }, selected?.label ?? ''),
1129
+ h('span', { style: ui.ddChevron, 'aria-hidden': true }, '▾')),
1130
+ open ? h('div', { style: ui.ddList, role: 'listbox' },
1131
+ options.map(option => h('button', {
1132
+ key: option.value,
1133
+ type: 'button',
1134
+ role: 'option',
1135
+ 'aria-selected': option.value === value,
1136
+ style: { ...ui.ddItem, ...(option.value === value ? ui.ddItemOn : null) },
1137
+ onClick: () => { setOpen(false); onChange(option.value) },
1138
+ },
1139
+ h('span', { style: ui.ddItemCheck }, option.value === value ? '✓' : ''),
1140
+ h('span', null, option.label)))) : null)
1141
+ }
1142
+
1143
+ /** Daily token line chart (SVG), zero-token weeks show a hint instead. */
1144
+ function UsageChart({ points, empty }) {
1145
+ const total = Array.isArray(points) ? points.reduce((sum, point) => sum + (Number(point.tokens) || 0), 0) : 0
1146
+ if (!Array.isArray(points) || points.length === 0 || total === 0) return h('div', { style: ui.chartEmpty }, empty)
1147
+ const max = Math.max(1, ...points.map(point => point.tokens))
1148
+ const width = 640
1149
+ const height = 150
1150
+ const padX = 8
1151
+ const padY = 12
1152
+ const stepX = points.length > 1 ? (width - padX * 2) / (points.length - 1) : 0
1153
+ const x = index => padX + stepX * index
1154
+ const y = tokens => height - padY - (tokens / max) * (height - padY * 2)
1155
+ const line = points.map((point, index) => `${index === 0 ? 'M' : 'L'}${x(index).toFixed(1)},${y(point.tokens).toFixed(1)}`).join(' ')
1156
+ const area = `${line} L${x(points.length - 1).toFixed(1)},${height - padY} L${x(0).toFixed(1)},${height - padY} Z`
1157
+ const formatDay = t => {
1158
+ const date = new Date(t)
1159
+ return `${date.getMonth() + 1}/${date.getDate()}`
1160
+ }
1161
+ const last = points[points.length - 1]
1162
+ return h('div', null,
1163
+ h('svg', { viewBox: `0 0 ${width} ${height}`, style: ui.chart, role: 'img', 'aria-label': tr('chartAria') },
1164
+ h('path', { d: area, style: ui.chartArea }),
1165
+ h('path', { d: line, style: ui.chartLine }),
1166
+ points.map((point, index) => h('circle', {
1167
+ key: index, cx: x(index), cy: y(point.tokens), r: 2.5, style: ui.chartDot,
1168
+ title: `${formatDay(point.t)} · ${point.tokens.toLocaleString()} token · ¥${Number(point.costCNY || 0).toFixed(4)}`,
1169
+ })),
1170
+ h('text', { x: padX, y: height - 1, style: ui.chartAxis }, formatDay(points[0].t)),
1171
+ h('text', { x: width - padX, y: height - 1, style: ui.chartAxis, textAnchor: 'end' }, formatDay(last.t))),
1172
+ h('div', { style: ui.chartFoot },
1173
+ h('span', null, `${tr('chartPeak')} ${max.toLocaleString()} token`),
1174
+ h('span', null, `${tr('chartLast')} ${last.tokens.toLocaleString()} token`)))
1175
+ }
1176
+
1177
+ /** Settings page: bordered cards, accent group titles, per-field controls. */
872
1178
  function ColophonSettings() {
873
1179
  const [form, setForm] = useState(null)
874
1180
  const [status, setStatus] = useState(null)
875
- const [custom, setCustom] = useState(null)
1181
+ const [statistics, setStatistics] = useState(null)
1182
+ const [series, setSeries] = useState(null)
1183
+ const [rangeKind, setRangeKind] = useState('week')
876
1184
  const [range, setRange] = useState({ from: '', to: '' })
877
1185
  const [message, setMessage] = useState('')
878
1186
  const [failed, setFailed] = useState('')
879
1187
  const [saving, setSaving] = useState(false)
880
1188
 
1189
+ const withCustomQuery = useCallback(async () => {
1190
+ const params = new URLSearchParams()
1191
+ if (rangeKind === 'custom') {
1192
+ const from = Date.parse(range.from)
1193
+ const to = range.to ? Date.parse(range.to) : Date.now()
1194
+ if (!Number.isFinite(from)) return null
1195
+ params.set('from', String(from))
1196
+ params.set('to', String(Math.min(to, Date.now())))
1197
+ }
1198
+ return callHost(`usage/series${params.toString() ? `?${params}` : ''}`)
1199
+ }, [rangeKind, range])
1200
+
1201
+ const loadSeries = useCallback(async () => {
1202
+ try {
1203
+ if (rangeKind === 'custom') {
1204
+ const data = await withCustomQuery()
1205
+ if (data) setSeries({ bucket: 'day', points: data.points, from: data.from, to: data.to })
1206
+ return
1207
+ }
1208
+ setSeries(await callHost(`usage/series?kind=${rangeKind}`))
1209
+ } catch (cause) {
1210
+ setSeries({ bucket: 'day', points: [] })
1211
+ setFailed(String(cause?.message ?? cause))
1212
+ }
1213
+ }, [rangeKind, withCustomQuery])
1214
+
881
1215
  useEffect(() => {
882
1216
  let alive = true
883
1217
  void (async () => {
884
1218
  try {
885
- const [config, statistics] = await Promise.all([callHost('config'), callHost('status')])
1219
+ const [config, stats] = await Promise.all([callHost('config'), callHost('status')])
886
1220
  if (!alive) return
887
1221
  setForm(config.config)
888
- setStatus(statistics)
1222
+ setStatus(stats)
889
1223
  } catch (cause) {
890
1224
  if (alive) setFailed(String(cause?.message ?? cause))
891
1225
  }
@@ -893,18 +1227,30 @@ window.__ModuleLoader__.load({
893
1227
  return () => { alive = false }
894
1228
  }, [])
895
1229
 
1230
+ useEffect(() => { void loadSeries() }, [loadSeries])
1231
+
1232
+ useEffect(() => {
1233
+ void callHost('usage').then(setStatistics).catch(() => {})
1234
+ }, [series])
1235
+
896
1236
  const update = (section, key, value) => {
897
- setForm(current => {
898
- if (!current) return current
899
- return { ...current, [section]: { ...current[section], [key]: value } }
900
- })
1237
+ setForm(current => (current ? { ...current, [section]: { ...current[section], [key]: value } } : current))
901
1238
  setMessage('')
902
1239
  }
903
1240
  const updateTop = (key, value) => {
904
1241
  setForm(current => (current ? { ...current, [key]: value } : current))
905
1242
  setMessage('')
906
1243
  }
907
-
1244
+ const updateTrigger = (key, patch) => {
1245
+ setForm(current => {
1246
+ if (!current) return current
1247
+ const triggers = { ...current.triggers }
1248
+ const item = typeof triggers[key] === 'boolean' ? { enabled: triggers[key], engine: 'inherit' } : triggers[key]
1249
+ triggers[key] = { ...item, ...patch }
1250
+ return { ...current, triggers }
1251
+ })
1252
+ setMessage('')
1253
+ }
908
1254
  const toggleSection = (id) => {
909
1255
  setForm(current => {
910
1256
  if (!current) return current
@@ -914,199 +1260,218 @@ window.__ModuleLoader__.load({
914
1260
  })
915
1261
  setMessage('')
916
1262
  }
917
-
918
1263
  const save = async () => {
919
1264
  if (!form) return
920
1265
  setSaving(true)
921
1266
  setFailed('')
922
1267
  try {
923
1268
  const patch = {
924
- enabled: form.enabled, engine: form.engine,
1269
+ enabled: form.enabled,
1270
+ engine: form.engine,
925
1271
  sections: form.sections,
926
- api: form.api, triggers: form.triggers, filter: form.filter,
1272
+ api: form.api,
1273
+ triggers: form.triggers,
1274
+ filter: form.filter,
927
1275
  }
928
- const value = await callHost('config', { method: 'POST', body: { patch } })
929
- setForm(value.config)
930
- setStatus(await callHost('status'))
1276
+ const result = await callHost('config', { method: 'POST', body: patch })
1277
+ setForm(result.config)
931
1278
  setMessage(tr('saved'))
1279
+ void callHost('status').then(setStatus).catch(() => {})
932
1280
  } catch (cause) {
933
- setFailed(tr('saveFailed', { message: String(cause?.message ?? cause) }))
1281
+ setFailed(String(cause?.message ?? cause))
934
1282
  } finally {
935
1283
  setSaving(false)
936
1284
  }
937
1285
  }
938
1286
 
939
- const loadCustom = async (from, to) => {
940
- if (!Number.isFinite(from) || !Number.isFinite(to) || from > to) { setCustom(null); return }
941
- try {
942
- const value = await callHost(`usage?from=${from}&to=${to}`)
943
- setCustom(value?.custom ?? null)
944
- } catch { setCustom(null) }
945
- }
1287
+ if (failed) return h('div', { style: ui.page }, h(Callout, { tone: 'error' }, failed))
1288
+ if (!form) return h('div', { style: ui.page }, h('div', { style: ui.loading }, tr('loading')))
946
1289
 
947
- const applyRange = () => {
948
- const from = Date.parse(range.from)
949
- const to = range.to === '' ? Date.now() : Date.parse(range.to)
950
- if (!Number.isFinite(from) || !Number.isFinite(to) || from > to) {
951
- setFailed(tr('rangeInvalid')); setMessage(''); return
952
- }
953
- setFailed(''); setCustom(null); void loadCustom(from, to)
954
- }
1290
+ const apiEnabled = form.engine === 'api'
1291
+ const triggerEngineOptions = [
1292
+ { value: 'inherit', label: tr('engineInherit') },
1293
+ ...(apiEnabled ? [{ value: 'api', label: tr('engineApi') }, { value: 'smart', label: tr('engineSmart') }] : []),
1294
+ { value: 'rules', label: tr('engineLocal') },
1295
+ ]
1296
+ const sectionChips = SECTION_META.map(([id, labelKey]) => {
1297
+ const on = (form.sections ?? []).includes(id)
1298
+ return h('button', {
1299
+ key: id,
1300
+ type: 'button',
1301
+ 'aria-pressed': on,
1302
+ style: on ? { ...ui.secChip, ...ui.secChipOn } : ui.secChip,
1303
+ onClick: () => toggleSection(id),
1304
+ }, h('span', { style: ui.secChipMark }, on ? '✓' : ''), tr(labelKey))
1305
+ })
955
1306
 
956
- const usage = status?.usage ?? {}
957
- const usageCard = (label, slot, key) => h('div', { key, style: ui.statCard },
958
- h('div', { style: ui.statLabel }, label),
959
- h('div', { style: ui.statValue }, money(slot?.costCNY)),
960
- h('div', { style: ui.statMeta }, tr('tokensLabel', { tokens: integer(slot?.tokens) }), ' · ', tr('calls', { count: slot?.calls ?? 0 })))
1307
+ const rangeTabs = [['week', 'rangeWeek'], ['today', 'rangeToday'], ['month', 'rangeMonth'], ['custom', 'rangeCustom']]
961
1308
 
962
- if (!form) {
963
- return h('div', { style: ui.page },
964
- h(CrashBanner),
965
- h('div', { style: ui.hint }, failed || tr('loading')))
1309
+ const triggerRow = (key, titleKey, hintKey, extra) => {
1310
+ const item = typeof form.triggers[key] === 'boolean'
1311
+ ? { enabled: form.triggers[key], engine: 'inherit' }
1312
+ : form.triggers[key]
1313
+ return h('div', { key, style: ui.cardRow },
1314
+ h('div', { style: ui.rowMain },
1315
+ h('div', { style: ui.label }, tr(titleKey)),
1316
+ h('div', { style: ui.hint }, tr(hintKey)),
1317
+ apiEnabled ? h('div', { style: ui.enginePick },
1318
+ h('span', { style: ui.enginePickLabel }, tr('triggerEngineLabel')),
1319
+ h(Dropdown, {
1320
+ value: item.engine ?? 'inherit',
1321
+ options: triggerEngineOptions,
1322
+ onChange: value => updateTrigger(key, { engine: value }),
1323
+ })) : h('div', { style: ui.hint }, tr('engineApiBlocked'))),
1324
+ h('div', { style: ui.rowSide },
1325
+ extra,
1326
+ h(SwitchRow, {
1327
+ label: '', checked: item.enabled !== false, last: true,
1328
+ onChange: () => updateTrigger(key, { enabled: item.enabled === false }),
1329
+ })))
966
1330
  }
967
1331
 
968
- const queueItems = status?.queueItems ?? []
969
- const queueCount = Number(status?.queueCount ?? status?.queue ?? 0) || 0
970
- const enabled = form.enabled === true
971
- const apiOn = form.engine === 'api'
972
- const batchOn = form.triggers.closeBatch === true
973
-
974
1332
  return h('div', { style: ui.page },
975
- h(CrashBanner),
976
1333
  h('div', { style: ui.header },
977
- h('div', { style: ui.headerRow },
978
- h('span', { style: ui.title }, '卷末 Colophon'),
979
- h(StatusPill, { on: enabled, onText: tr('statusOn'), offText: tr('statusOff') })),
980
- h('div', { style: ui.subtitle }, tr('settingsSubtitle')),
981
- h('div', { style: ui.meta },
982
- h('span', null, tr('saveHint')),
983
- status ? h('span', null, tr('dataRoot'), ':', status.dataRoot) : null)),
1334
+ h('div', { style: ui.title }, tr('settingsLabel'), h(Pill, { on: form.enabled })),
1335
+ h('div', { style: ui.subtitle }, tr('subtitle')),
1336
+ h('div', { style: ui.meta }, status?.dataRoot ? `${tr('dataRoot')}:${status.dataRoot}` : '',
1337
+ apiEnabled ? null : h('span', { style: { marginLeft: 10 } }, tr('apiDisabledHint')))),
984
1338
 
985
- h(Group, { title: tr('basicTitle') },
986
- h(SwitchRow, {
987
- label: tr('enabled'), hint: tr('enabledHint'), checked: enabled, last: true,
988
- onChange: value => updateTop('enabled', value),
989
- }),
990
- h(Row, { last: true },
991
- h(LabelBlock, { label: tr('engine'), hint: tr('engineHint') }),
992
- h('div', { style: ui.control },
993
- h(Segmented, {
994
- value: form.engine,
995
- onChange: value => updateTop('engine', value),
996
- options: [
997
- { value: 'rules', label: tr('engineRules'), hint: tr('engineRulesHint') },
998
- { value: 'api', label: tr('engineApi'), hint: tr('engineApiHint') },
999
- ],
1000
- })))),
1339
+ h('section', { style: ui.card },
1340
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('basicTitle')),
1341
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1342
+ h('div', { style: ui.label }, tr('enabled')),
1343
+ h('div', { style: ui.hint }, tr('enabledHint'))),
1344
+ h('div', { style: ui.rowSide }, h(SwitchRow, { label: '', checked: form.enabled, last: true, onChange: () => updateTop('enabled', !form.enabled) }))),
1345
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1346
+ h('div', { style: ui.label }, tr('engineLabel')),
1347
+ h('div', { style: ui.hint }, form.engine === 'api' ? tr('engineApiHint') : tr('engineRulesHint'))),
1348
+ h(Dropdown, {
1349
+ value: form.engine,
1350
+ options: [{ value: 'rules', label: tr('engineLocal') }, { value: 'api', label: tr('engineApi') }],
1351
+ onChange: value => updateTop('engine', value),
1352
+ }))),
1001
1353
 
1002
- h(Group, { title: tr('sectionsTitle'), meta: `${(form.sections ?? []).length}/${SECTION_META.length}` },
1003
- h('div', { style: { paddingBottom: 4 } },
1004
- h('div', null,
1005
- SECTION_META.map(([id, labelKey, hintKey], index) => h(SwitchRow, {
1006
- key: id,
1007
- label: tr(labelKey),
1008
- hint: tr(hintKey),
1009
- checked: (form.sections ?? []).includes(id),
1010
- last: index === SECTION_META.length - 1,
1011
- onChange: () => toggleSection(id),
1012
- }))))),
1354
+ h('section', { style: ui.card },
1355
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('sectionsTitle')),
1356
+ h('div', { style: ui.cardHint }, tr('sectionsHint')),
1357
+ h('div', { style: ui.chipGrid }, sectionChips)),
1013
1358
 
1014
- h(Group, { title: tr('triggers') },
1015
- h(SwitchRow, {
1016
- label: tr('onIdle'), hint: tr('onIdleHint'), checked: form.triggers.onIdle === true,
1017
- onChange: value => update('triggers', 'onIdle', value),
1018
- }),
1019
- h(SwitchRow, {
1020
- label: tr('onSwitch'), hint: tr('onSwitchHint'), checked: form.triggers.onSwitch === true,
1021
- onChange: value => update('triggers', 'onSwitch', value),
1022
- }),
1023
- h(SwitchRow, {
1024
- label: tr('closeBatch'), checked: batchOn, last: !batchOn,
1025
- onChange: value => update('triggers', 'closeBatch', value),
1026
- }),
1027
- batchOn ? h(NumberRow, {
1028
- label: tr('closeBatchMax'), unit: tr('unitSessions'), step: 1,
1029
- value: form.triggers.closeBatchMaxSessions, last: true,
1030
- onChange: value => update('triggers', 'closeBatchMaxSessions', value),
1031
- }) : null,
1032
- batchOn ? h(Callout, { tone: 'warn', label: tr('note') }, tr('closeBatchWarn')) : null),
1359
+ h('section', { style: ui.card },
1360
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('triggers')),
1361
+ triggerRow('onIdle', 'onIdle', 'onIdleHint'),
1362
+ triggerRow('onSwitch', 'onSwitch', 'onSwitchHint'),
1363
+ h('div', { style: ui.cardRow },
1364
+ h('div', { style: ui.rowMain },
1365
+ h('div', { style: ui.label }, tr('closeBatch')),
1366
+ h('div', { style: ui.hint }, tr('closeBatchHint')),
1367
+ form.triggers.closeBatch?.enabled ? h('div', { style: ui.batchNum },
1368
+ h('span', { style: ui.labelSm }, tr('batchLimit')),
1369
+ h(NumberInput, {
1370
+ value: form.triggers.closeBatchMaxSessions ?? 10, min: 1, max: 50,
1371
+ onChange: value => setForm(current => current ? { ...current, triggers: { ...current.triggers, closeBatchMaxSessions: Number(value) || 10 } } : current),
1372
+ })) : null,
1373
+ form.triggers.closeBatch?.enabled ? h(Callout, { tone: 'warn' }, tr('batchWarn')) : null),
1374
+ h('div', { style: ui.rowSide },
1375
+ h(SwitchRow, { label: '', checked: form.triggers.closeBatch?.enabled === true, last: true, onChange: () => updateTrigger('closeBatch', { enabled: !form.triggers.closeBatch?.enabled }) })))),
1033
1376
 
1034
- h(Group, { title: tr('apiSection'), meta: apiOn ? tr('apiOn') : tr('apiOff') },
1035
- h(Callout, null, tr('apiNote')),
1036
- h(TextRow, { label: tr('provider'), hint: 'deepseek-official', value: form.api.provider, width: 200, onChange: value => update('api', 'provider', value) }),
1037
- h(TextRow, { label: tr('model'), hint: 'deepseek-chat', value: form.api.model, width: 200, onChange: value => update('api', 'model', value) }),
1038
- h(NumberRow, { label: tr('priceIn'), hint: tr('unitPrice'), step: 0.1, unit: '元', value: form.api.priceInCNYPerM, onChange: value => update('api', 'priceInCNYPerM', value) }),
1039
- h(NumberRow, { label: tr('priceOut'), hint: tr('unitPrice'), step: 0.1, unit: '元', value: form.api.priceOutCNYPerM, onChange: value => update('api', 'priceOutCNYPerM', value) }),
1040
- h(NumberRow, { label: tr('perSummaryCap'), hint: tr('perSummaryCapHint'), step: 0.01, unit: '元', value: form.api.maxCostPerSummaryCNY, onChange: value => update('api', 'maxCostPerSummaryCNY', value) }),
1041
- h(NumberRow, { label: tr('dailyBudget'), hint: tr('dailyBudgetHint'), step: 1000, unit: 'tokens', value: form.api.dailyTokenBudget, onChange: value => update('api', 'dailyTokenBudget', value) }),
1042
- h(Row, { last: !(apiOn && status && status.apiAvailable === false) },
1043
- h(LabelBlock, { label: tr('overCap'), hint: tr('overCapHint') }),
1044
- h('div', { style: ui.control },
1045
- h(Segmented, {
1046
- value: form.api.overCap,
1047
- onChange: value => update('api', 'overCap', value),
1048
- options: [
1049
- { value: 'queue', label: tr('overCapQueue') },
1050
- { value: 'skip', label: tr('overCapSkip') },
1051
- ],
1052
- }))),
1053
- apiOn && status && status.apiAvailable === false
1054
- ? h(Callout, { tone: 'warn', label: tr('note') }, tr('apiUnavailable'))
1055
- : null),
1377
+ h('section', { style: ui.card, ...(apiEnabled ? null : ui.cardMuted) },
1378
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('apiTitle')),
1379
+ h('div', { style: ui.cardHint }, apiEnabled ? tr('apiHint') : tr('apiNeedEngine')),
1380
+ h('div', { style: ui.subGroup }, tr('apiModelSub')),
1381
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1382
+ h('div', { style: ui.label }, tr('apiProviderLabel')), h('div', { style: ui.hint }, tr('apiProviderHint'))),
1383
+ h(Dropdown, {
1384
+ value: form.api.provider || 'deepseek-official',
1385
+ options: [{ value: 'deepseek-official', label: tr('providerDeepseek') }],
1386
+ onChange: value => update('api', 'provider', value),
1387
+ disabled: !apiEnabled,
1388
+ })),
1389
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1390
+ h('div', { style: ui.label }, tr('apiModelLabel')), h('div', { style: ui.hint }, tr('apiModelHint'))),
1391
+ h(Dropdown, {
1392
+ value: form.api.model || 'deepseek-chat',
1393
+ options: [...new Set([form.api.model || 'deepseek-chat', 'deepseek-chat', 'deepseek-reasoner'])]
1394
+ .map(model => ({ value: model, label: model })),
1395
+ onChange: value => update('api', 'model', value),
1396
+ disabled: !apiEnabled,
1397
+ })),
1398
+ h('div', { style: ui.subGroup }, tr('apiCostSub')),
1399
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1400
+ h('div', { style: ui.label }, tr('inputPrice')), h('div', { style: ui.hint }, tr('inputPriceHint'))),
1401
+ h(NumberInput, { value: form.api.priceInCNYPerM, step: 0.1, unit: tr('priceUnit'), disabled: !apiEnabled, onChange: value => update('api', 'priceInCNYPerM', Number(value)) })),
1402
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1403
+ h('div', { style: ui.label }, tr('outputPrice')), h('div', { style: ui.hint }, tr('outputPriceHint'))),
1404
+ h(NumberInput, { value: form.api.priceOutCNYPerM, step: 0.1, unit: tr('priceUnit'), disabled: !apiEnabled, onChange: value => update('api', 'priceOutCNYPerM', Number(value)) })),
1405
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1406
+ h('div', { style: ui.label }, tr('perSummaryCap')), h('div', { style: ui.hint }, tr('perSummaryCapHint'))),
1407
+ h(NumberInput, { value: form.api.maxCostPerSummaryCNY, step: 0.01, unit: tr('yuan'), disabled: !apiEnabled, onChange: value => update('api', 'maxCostPerSummaryCNY', Number(value)) })),
1408
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1409
+ h('div', { style: ui.label }, tr('dailyBudget')), h('div', { style: ui.hint }, tr('dailyBudgetHint'))),
1410
+ h(NumberInput, { value: form.api.dailyTokenBudget, step: 1000, unit: tr('tokens'), disabled: !apiEnabled, onChange: value => update('api', 'dailyTokenBudget', Number(value)) })),
1411
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1412
+ h('div', { style: ui.label }, tr('overCap')), h('div', { style: ui.hint }, tr('overCapHint'))),
1413
+ h(Dropdown, {
1414
+ value: form.api.overCap,
1415
+ options: [{ value: 'queue', label: tr('overCapQueue') }, { value: 'skip', label: tr('overCapSkip') }],
1416
+ onChange: value => update('api', 'overCap', value),
1417
+ disabled: !apiEnabled,
1418
+ }))),
1056
1419
 
1057
- h(Group, { title: tr('filter') },
1058
- h(NumberRow, { label: tr('minMessages'), hint: tr('minMessagesHint'), unit: tr('unitMessages'), value: form.filter.minMessages, onChange: value => update('filter', 'minMessages', value) }),
1059
- h(NumberRow, { label: tr('minTokens'), hint: tr('minTokensHint'), unit: 'tokens', step: 500, last: true, value: form.filter.minTokens, onChange: value => update('filter', 'minTokens', value) })),
1420
+ h('section', { style: ui.card },
1421
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('filterTitle')),
1422
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1423
+ h('div', { style: ui.label }, tr('minMessages')), h('div', { style: ui.hint }, tr('minMessagesHint'))),
1424
+ h(NumberInput, { value: form.filter.minMessages, step: 1, unit: tr('unitMessages'), onChange: value => update('filter', 'minMessages', Number(value)) })),
1425
+ h('div', { style: ui.cardRow }, h('div', { style: ui.rowMain },
1426
+ h('div', { style: ui.label }, tr('minTokens')), h('div', { style: ui.hint }, tr('minTokensHint'))),
1427
+ h(NumberInput, { value: form.filter.minTokens, step: 100, unit: tr('unitTokens'), onChange: value => update('filter', 'minTokens', Number(value)) }))),
1060
1428
 
1061
- h(Group, { title: tr('queueTitle'), meta: queueCount > 0 ? String(queueCount) : tr('queueEmpty') },
1062
- queueItems.length === 0
1063
- ? h('div', { style: ui.emptyBox }, tr('queueEmpty'))
1064
- : h('div', { style: ui.queueList },
1065
- queueItems.map(item => h('div', { key: item.sessionId, style: ui.queueRow },
1066
- h('span', { style: { fontWeight: 600 } }, String(item.sessionId).slice(0, 14)),
1067
- h('span', { style: ui.hint }, tr('queueReason', { reason: item.reason })),
1068
- h('span', { style: { ...ui.hint, marginLeft: 'auto' } }, new Date(item.at).toLocaleString())))),
1069
- h(Row, { last: true },
1070
- h('div', { style: ui.hint }, tr('queueHint')),
1071
- h('div', { style: ui.control },
1072
- h('button', {
1073
- style: queueCount === 0 ? { ...ui.buttonSecondary, ...ui.buttonDisabled } : ui.buttonSecondary,
1074
- disabled: queueCount === 0,
1075
- onClick: async () => {
1076
- setFailed('')
1077
- try {
1078
- await callHost('queue/run', { method: 'POST', body: {} })
1079
- setStatus(await callHost('status'))
1080
- setMessage(tr('queueRun'))
1081
- } catch (cause) { setFailed(String(cause?.message ?? cause)) }
1082
- },
1083
- }, tr('queueProcess'))))),
1429
+ h('section', { style: ui.card },
1430
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('queueTitle')),
1431
+ h('div', { style: ui.cardHint }, tr('queueHint')),
1432
+ (status?.queueItems ?? []).length === 0
1433
+ ? h('div', { style: ui.queueEmpty }, tr('queueEmpty'))
1434
+ : h('div', null, status.queueItems.map(item => h('div', { key: item.sessionId, style: ui.queueRow },
1435
+ h('span', { style: ui.queueTitle }, item.sessionId),
1436
+ h('span', { style: ui.queueReason }, tr(`reason_${item.reason}`) || item.reason)))),
1437
+ h('div', { style: ui.inlineActions },
1438
+ h('button', {
1439
+ style: { ...ui.buttonSecondary, ...(status?.queueCount > 0 ? null : ui.buttonDisabled) },
1440
+ disabled: !(status?.queueCount > 0),
1441
+ onClick: async () => {
1442
+ try { await callHost('queue/run'); setStatus(await callHost('status')) } catch (cause) { setFailed(String(cause?.message ?? cause)) }
1443
+ },
1444
+ }, tr('processQueue')))),
1084
1445
 
1085
- h(Group, { title: tr('usage'), meta: tr('localZero') },
1446
+ h('section', { style: ui.card },
1447
+ h('div', { style: ui.cardTitle }, h('span', { style: ui.cardTitleBar }), tr('usageTitle')),
1448
+ h('div', { style: ui.usageHead },
1449
+ h('div', { style: ui.tabs },
1450
+ rangeTabs.map(([kind, key]) => h('button', {
1451
+ key, type: 'button',
1452
+ style: rangeKind === kind ? { ...ui.tab, ...ui.tabOn } : ui.tab,
1453
+ onClick: () => setRangeKind(kind),
1454
+ }, tr(key)))),
1455
+ h('span', { style: ui.hint }, form.engine === 'api' ? tr('usageApiHint') : tr('usageRulesHint'))),
1456
+ rangeKind === 'custom' ? h('div', { style: ui.customRow },
1457
+ h('span', { style: ui.labelSm }, tr('from')),
1458
+ h('input', { type: 'datetime-local', style: ui.input, value: range.from, onChange: event => setRange(current => ({ ...current, from: event.target.value })) }),
1459
+ h('span', { style: ui.labelSm }, tr('to')),
1460
+ h('input', { type: 'datetime-local', style: ui.input, value: range.to, onChange: event => setRange(current => ({ ...current, to: event.target.value })) })) : null,
1461
+ h(UsageChart, { points: series?.points ?? [], empty: tr('usageEmpty') }),
1086
1462
  h('div', { style: ui.statGrid },
1087
- usageCard(tr('usageHour'), usage.hour, 'hour'),
1088
- usageCard(tr('usageDay'), usage.day, 'day'),
1089
- usageCard(tr('usageWeek'), usage.week, 'week'),
1090
- usageCard(tr('usageMonth'), usage.month, 'month')),
1091
- custom ? h('div', { style: { ...ui.statGrid, gridTemplateColumns: '1fr' } }, usageCard(tr('usageCustom'), custom, 'custom')) : null,
1092
- h('div', { style: ui.rangeRow },
1093
- h('label', { style: ui.field },
1094
- h('span', null, tr('from')),
1095
- h('input', { style: ui.input, type: 'datetime-local', value: range.from, onChange: event => setRange(current => ({ ...current, from: event.target.value })) })),
1096
- h('label', { style: ui.field },
1097
- h('span', null, tr('to')),
1098
- h('input', { style: ui.input, type: 'datetime-local', value: range.to, onChange: event => setRange(current => ({ ...current, to: event.target.value })) })),
1099
- h('button', { style: ui.buttonSecondary, onClick: () => void applyRange() }, tr('apply')),
1100
- h('span', { style: { ...ui.unit, paddingBottom: 6 } }, tr('customHint'))),
1101
- h('div', { style: { paddingBottom: 6 } }, h('span', { style: ui.unit }, tr('rangeEmptyHint')))),
1463
+ [['hour', 'rangeHour'], ['day', 'rangeToday'], ['week', 'rangeWeek'], ['month', 'rangeMonth']].map(([kind, key]) => {
1464
+ const stat = statistics?.ranges?.[kind] ?? { tokens: 0, costCNY: 0, calls: 0 }
1465
+ return h('div', { key: kind, style: ui.statCard },
1466
+ h('div', { style: ui.statLabel }, tr(key)),
1467
+ h('div', { style: ui.statValue }, `¥${Number(stat.costCNY || 0).toFixed(4)}`),
1468
+ h('div', { style: ui.statFoot }, `${Number(stat.tokens || 0).toLocaleString()} token · ${stat.calls} 次`))
1469
+ }))),
1102
1470
 
1103
1471
  h('div', { style: ui.footer },
1104
- failed
1105
- ? h('span', { style: { ...ui.footerText, color: 'var(--dsw-alias-state-error-primary, #ef675c)' } }, failed)
1106
- : message
1107
- ? h('span', { style: { ...ui.footerText, color: 'var(--dsw-alias-state-success-primary, #6ed889)' } }, message)
1108
- : h('span', { style: ui.footerText }, tr('saveHint')),
1109
- h('button', { style: saving ? { ...ui.buttonPrimary, opacity: 0.7, cursor: 'wait' } : ui.buttonPrimary, disabled: saving, onClick: () => void save() },
1472
+ h('span', { style: message ? ui.footerOk : failed ? ui.footerBad : ui.hint },
1473
+ message || failed || tr('saveHint')),
1474
+ h('button', { style: { ...ui.buttonPrimary, ...(saving ? ui.buttonDisabled : null) }, disabled: saving, onClick: () => void save() },
1110
1475
  saving ? tr('saving') : tr('save'))))
1111
1476
  }
1112
1477
 
package/index.js CHANGED
@@ -37,9 +37,9 @@ export const Config = Schema.object({
37
37
  overCap: Schema.union([Schema.const('queue'), Schema.const('skip')]).default('queue'),
38
38
  }),
39
39
  triggers: Schema.object({
40
- onIdle: Schema.boolean().default(true),
41
- onSwitch: Schema.boolean().default(true),
42
- closeBatch: Schema.boolean().default(false),
40
+ onIdle: Schema.any().default({ enabled: true, engine: 'inherit' }),
41
+ onSwitch: Schema.any().default({ enabled: true, engine: 'inherit' }),
42
+ closeBatch: Schema.any().default({ enabled: false, engine: 'inherit' }),
43
43
  closeBatchMaxSessions: Schema.number().default(10),
44
44
  }),
45
45
  /** Blocks shown in the digest, in the order the settings page lists them. */
package/lib/app.js CHANGED
@@ -11,7 +11,21 @@ import { Collector, SessionTail } from './collect.js'
11
11
  import { buildApiMessages, estimateCost, parseApiDigest } from './api.js'
12
12
  import { DEFAULT_SECTIONS, RULES_VERSION, SECTION_IDS, buildDigest, shouldSummarize } from './digest.js'
13
13
  import { Store } from './store.js'
14
- import { UsageLedger, costCNY } from './usage.js'
14
+ import { UsageLedger, costCNY, rangeOf } from './usage.js'
15
+
16
+ /** Engines a single trigger may use; `inherit` follows the global engine. */
17
+ export const TRIGGER_ENGINES = ['inherit', 'rules', 'api', 'smart']
18
+
19
+ /** Read a trigger setting that may be a legacy boolean or an object. */
20
+ function readTrigger(value, fallbackEnabled) {
21
+ if (typeof value === 'boolean') return { enabled: value, engine: 'inherit' }
22
+ if (value && typeof value === 'object') {
23
+ const engine = TRIGGER_ENGINES.includes(value.engine) ? value.engine : 'inherit'
24
+ return { enabled: value.enabled !== false, engine }
25
+ }
26
+ return { enabled: fallbackEnabled, engine: 'inherit' }
27
+ }
28
+
15
29
  import { estimateTokens } from './text.js'
16
30
 
17
31
  /** Turn-end digest delay. */
@@ -45,14 +59,17 @@ export function normalizeConfig(config) {
45
59
  overCap: source.api?.overCap === 'skip' ? 'skip' : 'queue',
46
60
  },
47
61
  triggers: {
48
- onIdle: source.triggers?.onIdle !== false,
49
- onSwitch: source.triggers?.onSwitch !== false,
50
- closeBatch: source.triggers?.closeBatch === true,
62
+ onIdle: readTrigger(source.triggers?.onIdle, true),
63
+ onSwitch: readTrigger(source.triggers?.onSwitch, true),
64
+ closeBatch: readTrigger(source.triggers?.closeBatch, false),
51
65
  closeBatchMaxSessions: Number(source.triggers?.closeBatchMaxSessions ?? 10),
52
66
  },
67
+ sections: Array.isArray(source.sections) && source.sections.length > 0
68
+ ? [...new Set(source.sections.filter(id => typeof id === 'string' && SECTION_IDS.includes(id)))]
69
+ : [...DEFAULT_SECTIONS],
53
70
  filter: {
54
- minMessages: Number(source.filter?.minMessages ?? 20),
55
- minTokens: Number(source.filter?.minTokens ?? 4_000),
71
+ minMessages: Number(source.filter?.minMessages ?? 2),
72
+ minTokens: Number(source.filter?.minTokens ?? 100),
56
73
  maxAgeDays: Number(source.filter?.maxAgeDays ?? 30),
57
74
  sessionTypes: Array.isArray(source.filter?.sessionTypes) ? source.filter.sessionTypes : ['root'],
58
75
  },
@@ -93,7 +110,15 @@ export function sanitizeSettings(patch) {
93
110
  if (patch.triggers && typeof patch.triggers === 'object') {
94
111
  const triggers = {}
95
112
  for (const key of ['onIdle', 'onSwitch', 'closeBatch']) {
96
- if (typeof patch.triggers[key] === 'boolean') triggers[key] = patch.triggers[key]
113
+ const value = patch.triggers[key]
114
+ if (typeof value === 'boolean') {
115
+ triggers[key] = { enabled: value, engine: 'inherit' }
116
+ } else if (value && typeof value === 'object') {
117
+ const item = {}
118
+ if (typeof value.enabled === 'boolean') item.enabled = value.enabled
119
+ if (TRIGGER_ENGINES.includes(value.engine)) item.engine = value.engine
120
+ if (Object.keys(item).length > 0) triggers[key] = item
121
+ }
97
122
  }
98
123
  const max = number(patch.triggers.closeBatchMaxSessions)
99
124
  if (max !== undefined) triggers.closeBatchMaxSessions = Math.max(1, Math.min(50, Math.round(max)))
@@ -232,7 +257,7 @@ export function install(ctx, rawConfig) {
232
257
  if (type === 'user/message') {
233
258
  const previous = activeSessionId
234
259
  activeSessionId = sessionId
235
- if (previous !== '' && previous !== sessionId && config.triggers.onSwitch) {
260
+ if (previous !== '' && previous !== sessionId && config.triggers.onSwitch.enabled) {
236
261
  const previousLive = ctx.sessions.get?.(previous)
237
262
  void flushSession(previous, previousLive)
238
263
  }
@@ -318,10 +343,25 @@ export function install(ctx, rawConfig) {
318
343
  * @param {string} trigger why the digest is being written.
319
344
  * @returns {Promise<object|null>}
320
345
  */
346
+ /**
347
+ * Which engine a trigger should use, honoring the global API switch.
348
+ * @param {string} trigger trigger name.
349
+ * @returns {'rules'|'api'|'smart'}
350
+ */
351
+ function resolveEngine(trigger) {
352
+ if (config.engine !== 'api') return 'rules'
353
+ const per = config.triggers?.[trigger]?.engine ?? 'inherit'
354
+ if (per === 'rules') return 'rules'
355
+ if (per === 'api') return 'api'
356
+ if (per === 'smart') return 'smart'
357
+ return 'api'
358
+ }
359
+
321
360
  async function writeDigestFor(sessionId, checkpoint, trigger) {
322
361
  if (!shouldSummarize(checkpoint, config.filter).ok) return null
323
- if (config.engine === 'api') {
324
- const digest = await tryApiDigest(sessionId, checkpoint, trigger)
362
+ const engine = resolveEngine(trigger)
363
+ if (engine === 'api' || engine === 'smart') {
364
+ const digest = await tryApiDigest(sessionId, checkpoint, trigger, { smart: engine === 'smart' })
325
365
  if (digest) return digest
326
366
  }
327
367
  const digest = buildDigest(checkpoint, { engine: 'rules', now: Date.now(), sections: config.sections })
@@ -337,7 +377,7 @@ export function install(ctx, rawConfig) {
337
377
  * @param {string} trigger why the summary is wanted.
338
378
  * @returns {Promise<object|null>}
339
379
  */
340
- async function tryApiDigest(sessionId, checkpoint, trigger) {
380
+ async function tryApiDigest(sessionId, checkpoint, trigger, options = {}) {
341
381
  if (!config.enabled) return null
342
382
  const api = config.api
343
383
  if (typeof ctx.llm?.stream !== 'function') {
@@ -347,6 +387,10 @@ export function install(ctx, rawConfig) {
347
387
  }
348
388
  const built = buildApiMessages(checkpoint, config)
349
389
  const estimate = estimateCost(built, config)
390
+ if (options.smart && estimate.costCNY > api.maxCostPerSummaryCNY * 0.6) {
391
+ log(`smart engine kept ${sessionId} local: estimate ¥${estimate.costCNY.toFixed(4)}`)
392
+ return null
393
+ }
350
394
  if (estimate.costCNY > api.maxCostPerSummaryCNY) {
351
395
  if (api.overCap === 'queue') {
352
396
  store.queueJob(sessionId, 'over-cap')
@@ -464,7 +508,7 @@ export function install(ctx, rawConfig) {
464
508
  * Synchronous by design: the `exit` hook cannot await.
465
509
  */
466
510
  function queueCloseBatchSync() {
467
- if (!config.enabled || !config.triggers.closeBatch || config.engine !== 'api') return
511
+ if (!config.enabled || !config.triggers.closeBatch.enabled) return
468
512
  for (const sessionId of collector.ids().slice(0, Math.max(1, config.triggers.closeBatchMaxSessions))) {
469
513
  store.queueJob(sessionId, 'close-batch')
470
514
  }
@@ -664,6 +708,27 @@ export function install(ctx, rawConfig) {
664
708
  return Promise.resolve(json({ ok: true, value: { now, ranges: summaries, custom: custom ?? null } }))
665
709
  },
666
710
  }),
711
+ ctx.connection.fetch.register({
712
+ path: '/api/colophon/usage/series',
713
+ methods: ['GET'],
714
+ requestBody: 'buffered',
715
+ fetch: request => {
716
+ const params = new URL(request.url, 'http://colophon').searchParams
717
+ const now = Date.now()
718
+ const from = Number(params.get('from'))
719
+ const to = Number(params.get('to'))
720
+ const kind = params.get('kind')
721
+ const bucket = params.get('bucket') === 'hour' || kind === 'today' ? 'hour' : 'day'
722
+ const hasCustom = params.get('from') !== null && params.get('to') !== null
723
+ const range = hasCustom && Number.isFinite(from) && Number.isFinite(to) && from <= to
724
+ ? { from, to }
725
+ : ['today', 'week', 'month'].includes(kind)
726
+ ? { from: rangeOf(now, kind).from, to: now }
727
+ : { from: rangeOf(now, 'week').from, to: now }
728
+ const points = ledger.series(bucket, range)
729
+ return Promise.resolve(json({ ok: true, value: { bucket, from: range.from, to: range.to, points } }))
730
+ },
731
+ }),
667
732
  ]
668
733
  disposers.push(...routes)
669
734
 
package/lib/usage.js CHANGED
@@ -120,6 +120,46 @@ export class UsageLedger {
120
120
  * @param {{from: number, to: number}} [custom] custom window.
121
121
  * @returns {Record<string, ReturnType<UsageLedger['aggregate']>>}
122
122
  */
123
+ /**
124
+ * Bucketed series for chart display.
125
+ * @param {'hour'|'day'} bucket bucket size.
126
+ * @param {{from: number, to: number}} range window.
127
+ * @returns {{t: number, tokens: number, costCNY: number, calls: number}[]}
128
+ */
129
+ series(bucket, { from, to }) {
130
+ const step = bucket === 'hour' ? 3_600_000 : 86_400_000
131
+ const startOfBucket = (t) => {
132
+ if (bucket === 'hour') {
133
+ const d = new Date(t)
134
+ d.setMinutes(0, 0, 0)
135
+ return d.getTime()
136
+ }
137
+ const d = new Date(t)
138
+ d.setHours(0, 0, 0, 0)
139
+ return d.getTime()
140
+ }
141
+ const start = startOfBucket(from)
142
+ const end = startOfBucket(to)
143
+ const points = []
144
+ for (let t = start; t <= end; t += step) {
145
+ points.push({ t, tokens: 0, costCNY: 0, calls: 0 })
146
+ }
147
+ const index = new Map(points.map((point, i) => [point.t, i]))
148
+ for (const row of this.rows) {
149
+ const t = Number(row.t) || 0
150
+ if (t < from || t > to) continue
151
+ const i = index.get(startOfBucket(t))
152
+ if (i === undefined) continue
153
+ const usage = row.usage ?? {}
154
+ const tokens = (Number(usage.inputTokens) || 0) + (Number(usage.outputTokens) || 0)
155
+ points[i].tokens += tokens
156
+ points[i].calls += 1
157
+ points[i].costCNY += Number(row.costCNY) || 0
158
+ }
159
+ for (const point of points) point.costCNY = Math.round(point.costCNY * 10000) / 10000
160
+ return points
161
+ }
162
+
123
163
  summary(now = Date.now(), custom) {
124
164
  const result = {}
125
165
  for (const kind of ['hour', 'day', 'week', 'month']) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-colophon",
3
- "version": "0.2.6",
3
+ "version": "0.3.1",
4
4
  "description": "Colophon(卷末)— keep a local, token-free conclusion digest for every conversation, so reopening an old session starts from its final state instead of its full history.",
5
5
  "documentation": "README.md",
6
6
  "license": "MIT",