@fish-under-sea/magpie-dragonapi 0.2.1 → 1.0.0

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/ui/app.js CHANGED
@@ -1,18 +1,14 @@
1
- /* DragonAPI in Magpie · 本地控制台前端
2
- *
3
- * 为什么不用框架:页面由插件自起的本地 HTTP 服务直接托管,没有构建步骤,
4
- * 四个标签页不值得引入几百 KB 的运行时。
5
- *
6
- * 为什么状态全在内存:页面文档的 origin 是 opaque(从 magpie 沙箱 iframe
7
- * location.replace 过来),碰 localStorage / sessionStorage / indexedDB / cookie
8
- * 都会抛异常;需要留下来的东西只能交给服务端 API。
9
- *
10
- * 为什么所有 fetch 都 credentials: "omit":opaque origin 下带凭据的跨源请求
11
- * 会被直接拒,服务端也用 Access-Control-Allow-Origin: * 兜住,不需要 cookie。
12
- */
13
1
 
14
2
  'use strict';
15
3
 
4
+ // 聚合与排序逻辑独立成纯模块,可单测(见 tests/model-agg.test.mjs)。
5
+ import { aggregateRows, focusGroupOf, orderDefault } from './model-agg.js';
6
+ // 演示数据层:网址带 ?demo 时接管全部 GET 读接口,只在内存里,刷新即还原。
7
+ import { createDemoApi } from './demo.js';
8
+
9
+ const DEMO_PARAMS = new URLSearchParams(location.search);
10
+ const DEMO_API = DEMO_PARAMS.has('demo') && DEMO_PARAMS.get('demo') !== '0' ? createDemoApi() : null;
11
+
16
12
  // ── DOM 小工具 ─────────────────────────────────────────────
17
13
 
18
14
  const $ = (sel, root = document) => root.querySelector(sel);
@@ -105,10 +101,12 @@ function markOverflow(wrap, hint) {
105
101
  }
106
102
 
107
103
  function regionLoading(node, text) {
104
+ if (!node) return;
108
105
  node.replaceChildren(h('p', { class: 'loading', text }));
109
106
  }
110
107
 
111
108
  function regionError(node, message, retry) {
109
+ if (!node) return;
112
110
  node.replaceChildren(h('div', { class: 'region-error' },
113
111
  h('p', { class: 'region-error-text', text: message }),
114
112
  retry ? h('button', { class: 'btn ghost', type: 'button', onclick: retry }, '重试') : null,
@@ -198,6 +196,9 @@ class ApiError extends Error {
198
196
  }
199
197
 
200
198
  async function request(path, { method = 'GET', body } = {}) {
199
+ // 演示模式只拦读接口;写接口(POST/DELETE)一律走真实实现,
200
+ // 这样「演示模式」永远不可能改到真实账号。
201
+ if (DEMO_API && method === 'GET') return DEMO_API(path);
201
202
  let res;
202
203
  try {
203
204
  res = await fetch(apiUrl(path), {
@@ -206,8 +207,7 @@ async function request(path, { method = 'GET', body } = {}) {
206
207
  cache: 'no-store', // 服务端已经自己缓存目录,浏览器别再叠一层
207
208
  headers: body ? { 'content-type': 'application/json' } : undefined,
208
209
  body: body ? JSON.stringify(body) : undefined,
209
- // 必须自己设上限:保存 PAT 要串行探三个站点端点,站点半死不活时
210
- // 没有信号就会一直转圈,用户看到的是「点了没反应」。
210
+ // 保存 PAT 并行验证;页面仍独立设等待上限,避免本地服务挂住。
211
211
  signal: AbortSignal.timeout(45000),
212
212
  });
213
213
  } catch (err) {
@@ -254,9 +254,14 @@ const api = {
254
254
  catalog: (force) => request('/api/catalog' + (force ? '?refresh=1' : '')),
255
255
  model: (group, name) => request(`/api/model?group=${encodeURIComponent(group)}&model=${encodeURIComponent(name)}`),
256
256
  usage: (range) => request(`/api/usage?range=${encodeURIComponent(range)}`),
257
- logs: (account) => request(`/api/logs?limit=200&account=${encodeURIComponent(account)}`),
257
+ logStats: (range) => request(`/api/logs/stats?range=${encodeURIComponent(range)}`),
258
+ dashboard: (days, granularity) => request(`/api/dashboard?days=${days}&granularity=${encodeURIComponent(granularity)}`),
258
259
  keys: () => request('/api/keys'),
260
+ aff: () => request('/api/aff'),
261
+ subscriptions: () => request('/api/subscriptions'),
262
+ transferAff: () => request('/api/aff/transfer', { method: 'POST' }),
259
263
  createKey: (body) => request('/api/keys', { method: 'POST', body }),
264
+ updateKey: (id, body) => request(`/api/keys/${encodeURIComponent(id)}`, { method: 'PUT', body }),
260
265
  deleteKey: (id) => request(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE' }),
261
266
  revealKey: (id) => request(`/api/keys/${encodeURIComponent(id)}/reveal`, { method: 'POST' }),
262
267
  bindInfo: () => request('/api/bind-info'),
@@ -387,14 +392,21 @@ const cache = {
387
392
  catalog: null,
388
393
  keys: null,
389
394
  bind: null,
395
+ aff: null,
396
+ subscriptions: null,
397
+ usageErrors: {},
390
398
  health: null,
391
399
  usage: {}, // range -> response
392
- logs: {}, // account key -> rows[]
400
+ logStats: {}, // range -> { available, quota, rpm, tpm }
401
+ dashboard: {}, // `${days}:${granularity}` -> /api/dashboard
393
402
  };
394
403
 
395
- const loading = { state: false, catalog: false, keys: false, bind: false, health: false, usage: false, logs: false };
404
+ const loading = { state: false, catalog: false, keys: false, bind: false, health: false, usage: false, aff: false, subscriptions: false };
405
+ // PAT 切换/清除后,旧请求即使较晚返回也不能重新填回上个账户的数据。
406
+ let dataEpoch = 0;
407
+ const usagePending = new Map();
396
408
 
397
- const filters = { category: '', group: '', vendor: '', kind: '', q: '', unit: 'M', sort: 'latest', view: 'grid', range: 'day', account: '' };
409
+ const filters = { category: '', group: '', vendor: '', kind: '', q: '', unit: 'M', sort: 'latest', view: 'grid', range: 'day' };
398
410
 
399
411
  let activeTab = 'catalog';
400
412
 
@@ -417,7 +429,12 @@ function renderHeader() {
417
429
  let label = '连接中…';
418
430
  let title = '';
419
431
 
420
- if (cache.stateError) {
432
+ if (DEMO_API) {
433
+ // 演示模式没有真实站点连接可探,别拿「站点不可达」吓人。
434
+ tone = 'ok';
435
+ label = '演示数据';
436
+ title = '演示模式:数据只在本页内存,去掉网址里的 ?demo 回到真实数据。';
437
+ } else if (cache.stateError) {
421
438
  tone = 'bad';
422
439
  label = '本地服务无响应';
423
440
  title = cache.stateError;
@@ -438,17 +455,6 @@ function renderHeader() {
438
455
  text.textContent = label;
439
456
  pill.title = title || '本地服务与站点连接状态';
440
457
 
441
- const currency = st && st.currency;
442
- const curPill = $('#currency-pill');
443
- if (curPill) {
444
- curPill.textContent = currency
445
- ? `${currency.symbol || ''} ${currency.code || ''}`.trim() || '—'
446
- : '—';
447
- curPill.title = currency
448
- ? `站点币种 ${currency.code || ''}${currency.per ? ` · 1 单位 = ${currency.per} quota` : ''}`
449
- : '站点币种';
450
- }
451
-
452
458
  const site = st && st.site;
453
459
  const link = $('#site-link');
454
460
  if (link && site) {
@@ -461,22 +467,6 @@ function renderHeader() {
461
467
  }
462
468
  }
463
469
 
464
- function populateAccountSelect() {
465
- const sel = $('#flow-account');
466
- if (!sel) return;
467
- const accounts = (cache.state && cache.state.accounts) || [];
468
- const current = filters.account;
469
-
470
- // 注意:replaceChildren 只吃 Node / string,数组必须展开,否则直接抛 TypeError
471
- sel.replaceChildren(
472
- h('option', { value: '', text: '全部账号' }),
473
- ...accounts.map((a) => h('option', { value: a.key, text: a.label || a.masked || a.key })),
474
- );
475
-
476
- if (current && accounts.some((a) => a.key === current)) sel.value = current;
477
- else { sel.value = ''; filters.account = ''; }
478
- sel.disabled = accounts.length === 0;
479
- }
480
470
 
481
471
  // ── 标签页切换 ────────────────────────────────────────────
482
472
 
@@ -495,8 +485,8 @@ function activateTab(name, { focus = false, force = false } = {}) {
495
485
  }
496
486
  if (focus) tab.focus();
497
487
 
498
- // 离开密钥页就丢掉「只显示一次」的完整钥匙,避免它一直留在屏幕上
499
- if (name !== 'keys' && lastSecret) {
488
+ // 离开账户页就丢掉「只显示一次」的完整钥匙,避免它一直留在屏幕上
489
+ if (name !== 'wallet' && lastSecret) {
500
490
  lastSecret = null;
501
491
  renderSecret();
502
492
  }
@@ -506,11 +496,18 @@ function activateTab(name, { focus = false, force = false } = {}) {
506
496
 
507
497
  function ensureTab(name, force = false) {
508
498
  if (name === 'catalog') return loadCatalog(force);
509
- if (name === 'wallet') return loadWallet(force);
510
- // 密钥页有两块独立内容:钥匙列表(要 PAT)与绑定说明(不需要)。
511
- // 绑定说明必须一起拉,否则「怎么绑进 magpie」会永远停在加载中——
512
- // 它只有 loadBind 里才会被填,而 loadBind 之前只在刷新按钮里被调到。
513
- if (name === 'keys') return Promise.all([loadKeys(force), loadBind(force)]);
499
+ // 账户页现在同时承载余额、用量、推荐计划与密钥,四块一起拉。
500
+ // 「怎么绑进 magpie」只有 loadBind 里才会被填,漏了它会永远停在加载中。
501
+ if (name === 'wallet') {
502
+ return Promise.all([
503
+ loadWallet(force),
504
+ loadKeys(force),
505
+ loadBind(force),
506
+ ]);
507
+ }
508
+ // 使用日志复用 /api/usage 的行,只在前端筛选,所以不用另开接口
509
+ if (name === 'logs') return loadLogs(force);
510
+ if (name === 'dashboard') return loadDashboard(force);
514
511
  if (name === 'pat') return loadPat(force);
515
512
  return Promise.resolve();
516
513
  }
@@ -653,12 +650,12 @@ const CATEGORY_META = {
653
650
  // 「可灵 / 即梦」这类词的分组会被国模抢走。
654
651
  const CATEGORY_TESTS = [
655
652
  ['image', /image|img|生图|绘图|draw|flux|midjourney|dall|stable|sdxl/i],
656
- ['video', /video|视频|veo|sora|runway|pika|hailuo|可灵|kling|万相|seedance|muse/i],
653
+ ['video', /video|视频|veo|sora|runway|pika|hailuo|\bh3\b|可灵|kling|万相|seedance|muse/i],
657
654
  ['claude', /claude|anthropic|kiro/i],
658
655
  ['gpt', /gpt|openai|codex|davinci|o[134]\b/i],
659
656
  ['gemini', /gemini|google|bard/i],
660
657
  ['grok', /grok|xai/i],
661
- ['guomo', /国模|deepseek|qwen|通义|千问|glm|智谱|moonshot|kimi|月之暗面|豆包|doubao|hunyuan|混元|文心|ernie|百度|baidu|讯飞|spark|minimax|海螺|阶跃|ling|jimeng|即梦|小米|mimo|零一|yi-/i],
658
+ ['guomo', /国模|deepseek|qwen|通义|千问|glm|智谱|moonshot|kimi|月之暗面|豆包|doubao|hunyuan|混元|\bhy\d|文心|ernie|百度|baidu|讯飞|spark|minimax|海螺|阶跃|ling|jimeng|即梦|小米|mimo|零一|yi-/i],
662
659
  ];
663
660
  /** 分组显示名:站点的「视频」按你说的改名成 video。 */
664
661
  const GROUP_ALIAS = { 视频: 'video' };
@@ -685,14 +682,31 @@ function iconImg(file, size = 14) {
685
682
  return img;
686
683
  }
687
684
 
688
- /** fmtTok 把一个「每百万 token」的数值按当前单位(M/K)印出来。 */
685
+ /**
686
+ * 价格单位:/1M(每百万 token)与 /272K(每 272K token)。
687
+ *
688
+ * 272K 不是随手挑的数:站点给 GPT 类模型的分档线就是 272000
689
+ * (`len <= 272000 ? short_context : long_context`)。卡片上表只展示
690
+ * 「≤272K」那一档——也就是默认首档——所以 /272K 对分档模型和普通模型
691
+ * 是同一种线性折算:每 272K 价 = 每百万价 × 0.272。272K 以上那一档
692
+ * 只在详情抽屉的分档表里出现,不混进卡片。
693
+ */
694
+ const UNIT_SCALE = { M: 1, '272K': 272000 / 1e6 };
695
+ const UNIT_TEXT = { M: '1M', '272K': '272K' };
696
+ const unitScale = (unit) => UNIT_SCALE[unit] || 1;
697
+ const unitText = (unit) => UNIT_TEXT[unit] || '1M';
698
+ /** 小数位:/1M 沿用站点的 2/4 位;/272K 数值小一档,相应多两位。 */
699
+ function unitDigits(v, unit) {
700
+ if (unit === '272K') return v >= 0.01 ? 4 : 6;
701
+ return v >= 0.01 ? 2 : 4;
702
+ }
703
+
704
+ /** fmtTok 把一个「每百万 token」的数值按当前单位印出来。 */
689
705
  function fmtTok(num, unit) {
690
706
  if (!Number.isFinite(num)) return '—';
691
- const v = unit === 'K' ? num / 1000 : num;
692
- // 位数跟站点原来的写法一致:/M 时 ≥0.01 两位、更小四位;/K 再补两位。
693
- const digits = unit === 'K' ? (v >= 0.01 ? 4 : 6) : (v >= 0.01 ? 2 : 4);
707
+ const v = num * unitScale(unit);
694
708
  const cur = cache.state && cache.state.currency;
695
- return `${(cur && cur.symbol) || '$'}${v.toFixed(digits)}/${unit}`;
709
+ return `${(cur && cur.symbol) || '$'}${v.toFixed(unitDigits(v, unit))}/${unitText(unit)}`;
696
710
  }
697
711
 
698
712
  /** 卡片的三个价格格:有数值就按单位换算,没有就退回服务端给的字符串。 */
@@ -707,26 +721,6 @@ function priceCellsOf(pricing, unit) {
707
721
  ];
708
722
  }
709
723
 
710
- /** versionRank 取模型名里的版本号(gpt-6.1-sol → [6,1],deepseek-v4 → [4])。 */
711
- function versionRank(name) {
712
- const m = String(name || '').match(/\d+(?:[.-]\d+)*/);
713
- return m ? m[0].split(/[.-]/).map(Number) : null;
714
- }
715
-
716
- /** byLatestVersion 新版本在前;没有版本号的排到最后,同版本按名称。 */
717
- function byLatestVersion(a, b) {
718
- const x = versionRank(a.name);
719
- const y = versionRank(b.name);
720
- if (x && y) {
721
- const n = Math.max(x.length, y.length);
722
- for (let i = 0; i < n; i++) {
723
- const d = (y[i] || 0) - (x[i] || 0);
724
- if (d) return d;
725
- }
726
- } else if (x) return -1;
727
- else if (y) return 1;
728
- return String(a.name).localeCompare(String(b.name), 'zh');
729
- }
730
724
 
731
725
  /** billingLabel 计费方式的一句话标签(卡片与列表行共用同一套判据)。 */
732
726
  function billingLabel(pricing, isAuto, priceKind) {
@@ -741,23 +735,47 @@ function billingLabel(pricing, isAuto, priceKind) {
741
735
  /** fmtTokValue 只给数值(不带单位),列表里单位单独占一行。 */
742
736
  function fmtTokValue(num, unit) {
743
737
  if (!Number.isFinite(num)) return '—';
744
- const v = unit === 'K' ? num / 1000 : num;
745
- const digits = unit === 'K' ? (v >= 0.01 ? 4 : 6) : (v >= 0.01 ? 2 : 4);
738
+ const v = num * unitScale(unit);
746
739
  const cur = cache.state && cache.state.currency;
747
- return `${(cur && cur.symbol) || '$'}${v.toFixed(digits)}`;
740
+ return `${(cur && cur.symbol) || '$'}${v.toFixed(unitDigits(v, unit))}`;
741
+ }
742
+
743
+ /**
744
+ * fmtRange 跨分组的价格区间:`$0.12–0.32/1M`。
745
+ *
746
+ * 只写一次符号、只写一次单位 —— `$0.12/1M–$0.32/1M` 又长又难看,一列里塞不下。
747
+ * 两端用同一个精度,避免出现 `$0.0032–0.12/1M` 这种一头 4 位一头 2 位的怪东西。
748
+ */
749
+ function fmtRange(span, unit) {
750
+ return fmtRangeBare(span, unit) + '/' + unitText(unit);
748
751
  }
749
752
 
750
- /** 端点 id → 看得懂的名字(站点给的是 openai / openai-response / anthropic 这类内部名)。 */
753
+ /** fmtRangeBare 只要 `$0.12–0.32`,单位由调用方另起一行印。 */
754
+ function fmtRangeBare(span, unit) {
755
+ const cur = cache.state && cache.state.currency;
756
+ const sym = (cur && cur.symbol) || '$';
757
+ const scale = unitScale(unit);
758
+ const lo = span.min * scale;
759
+ const hi = span.max * scale;
760
+ const digits = unitDigits(hi, unit);
761
+ return `${sym}${lo.toFixed(digits)}–${hi.toFixed(digits)}`;
762
+ }
763
+
764
+ /** 端点 id → 看得懂的名字。
765
+ *
766
+ * 站点给的是内部名(openai / openai-response / anthropic)。只写「Chat」
767
+ * 会让人以为只支持一种协议,其实一个模型常常同时挂在几种兼容层上,
768
+ * 所以按 NearToken 的说法写全:OpenAI 兼容 / OpenAI Responses / Anthropic 兼容… */
751
769
  const ENDPOINT_LABEL = {
752
- openai: 'Chat',
753
- 'openai-response': 'Response',
754
- anthropic: 'Anthropic',
755
- gemini: 'Gemini',
756
- 'image-generation': '图片',
770
+ openai: 'OpenAI 兼容',
771
+ 'openai-response': 'OpenAI Responses',
772
+ anthropic: 'Anthropic 兼容',
773
+ gemini: 'Gemini 兼容',
774
+ 'image-generation': '生图',
757
775
  '视频任务': '视频',
758
- 'jina-rerank': 'Rerank',
759
- rerank: 'Rerank',
760
- embedding: '嵌入',
776
+ 'jina-rerank': '重排',
777
+ rerank: '重排',
778
+ embedding: '向量',
761
779
  audio: '语音',
762
780
  tts: '语音合成',
763
781
  asr: '语音识别',
@@ -812,14 +830,25 @@ function renderCatalog() {
812
830
  return hay.includes(query);
813
831
  });
814
832
 
815
- // 一行 = 一个「分组 × 模型」。跨分组聚合成一张卡留到下一个 PR。
816
- const rows = matched;
833
+ // 一行 = 一个「分组 × 模型」,但一张卡 = 一个模型。
834
+ // 聚合在这里做(而不是服务端):筛选与排序都基于行,展示才需要合并。
835
+ // 价格按「每百万 token」存,/272K 视图只在展示时乘 0.272——同一条价格
836
+ // 只是换个单位,不影响聚合与排序的取值。
837
+ const rows = aggregateRows(matched);
817
838
 
818
839
  if (meta) {
819
- // replaceChildren 吃 null 会把它印成字符串「null」——先过滤掉空项再加。
840
+ // 聚合后「当前显示」与「全站」可能相等(没筛选时)。同一个数说两遍是噪音,
841
+ // 这时直接给一行完整的口径;筛选过才需要把「筛出几个 / 全站几个」并置。
842
+ const filtered = rows.length !== counts.models;
843
+ const scope = `${fmtInt(counts.models)} 个模型 / ${fmtInt(counts.rows)} 行 / ${fmtInt(counts.groups)} 个分组`;
820
844
  meta.replaceChildren(...[
845
+
821
846
  h('b', { text: fmtInt(rows.length) }),
822
- h('span', { text: ` 个模型 · 全站 ${fmtInt(counts.models)} 个 / ${fmtInt(counts.rows)} 行 / ${fmtInt(counts.groups)} 个分组` }),
847
+ h('span', {
848
+ text: filtered
849
+ ? ` 个模型 · 全站 ${scope}`
850
+ : ` 个模型 · ${fmtInt(counts.rows)} 行 / ${fmtInt(counts.groups)} 个分组`,
851
+ }),
823
852
  filters.category ? h('span', { text: ` · 分类 ${categoryTitle(filters.category)}` }) : null,
824
853
  filters.vendor ? h('span', { text: ` · 厂商 ${filters.vendor}` }) : null,
825
854
  h('span', { class: 'spacer' }),
@@ -836,9 +865,15 @@ function renderCatalog() {
836
865
  return;
837
866
  }
838
867
 
839
- // 排序:默认保留站点顺序(宿主列表与页面一致),另外给价格与名称两种。
840
- // 排序:默认「最新版本」——按模型名里的版本号从新到旧。
841
- const priceKey = (m) => (Number.isFinite(m.pricing?.inputNum) ? m.pricing.inputNum : Infinity);
868
+ // 排序。默认那档叫「默认排序」,不是「最新版本」:站点没有发布时间字段,
869
+ // 拿版本号大小冒充「最新」会让 gpt-6.1 压住 claude-fable-5-2 这类跨厂商
870
+ // 插队。默认排序的规则是「厂商 → 模型等级 → 版本号从新到旧」,见 model-agg.js。
871
+ // 价格按「最便宜的那个分组」排:聚合后一张卡代表多个价,用最低价才符合直觉。
872
+ const priceKey = (a) => {
873
+ const n = a?.cheapest?.pricing?.inputNum;
874
+ return Number.isFinite(n) ? n : Infinity;
875
+ };
876
+ const catOfAgg = (agg) => groupCat.get(agg.cheapest?.id) || 'other';
842
877
  if (filters.sort === 'price-asc') {
843
878
  rows.sort((a, b) => priceKey(a) - priceKey(b) || String(a.name).localeCompare(String(b.name)));
844
879
  } else if (filters.sort === 'price-desc') {
@@ -846,7 +881,10 @@ function renderCatalog() {
846
881
  } else if (filters.sort === 'name') {
847
882
  rows.sort((a, b) => String(a.name).localeCompare(String(b.name), 'zh'));
848
883
  } else {
849
- rows.sort(byLatestVersion);
884
+ // 默认排序不是比较器能表达的:它要「分等级道、轮流取版本」,
885
+ // 所以是重排整个数组(见 model-agg.js 的 orderDefault)。
886
+ const ordered = orderDefault(rows, { catOf: catOfAgg, catOrder: CATEGORY_ORDER });
887
+ rows.splice(0, rows.length, ...ordered);
850
888
  }
851
889
 
852
890
  body.className = 'model-grid' + (filters.view === 'list' ? ' as-list' : '');
@@ -864,39 +902,53 @@ function listHead() {
864
902
  }
865
903
 
866
904
  /** modelRow 列表模式的一行;点整行打开详情。 */
867
- function modelRow(m, groupMap) {
868
- const info = groupMap.get(m.group);
869
- const pricing = m.pricing || {};
870
- const kind = m.kind || 'chat';
871
- const priceKind = pricing.kind || 'unknown';
872
- const isAuto = m.group === 'auto' || (info && info.auto === true);
873
- const billing = billingLabel(pricing, isAuto, priceKind);
874
- const ends = Array.isArray(m.endpoints) ? m.endpoints : [];
905
+ /** modelRow 列表模式的一行(一个模型一行);点整行打开详情。 */
906
+ function modelRow(agg, groupMap) {
907
+ const focus = agg.cheapest || { pricing: {} };
908
+ const pricing = focus.pricing || {};
909
+ const kind = agg.kind || 'chat';
910
+ const priceKind = agg.priceKind || pricing.kind || 'unknown';
911
+ const isAuto = Boolean(focus.auto);
912
+ const billing = billingOfAgg(agg);
913
+ const ends = Array.isArray(agg.endpoints) ? agg.endpoints : [];
875
914
  const unit = filters.unit;
876
- const open = () => openModelDrawer(m);
915
+ const open = () => openModelDrawer(agg);
916
+
917
+ // 列宽固定,区间比单值长,这里用不带单位的紧凑写法($0.12–0.32),单位单独一行。
918
+ const bareRange = (span) => fmtRangeBare(span, unit);
919
+ const pair = (span, fallback) => {
920
+ if (span && !span.same) return [h('span', { class: 'ml-p-v', text: bareRange(span) })];
921
+ const n = span ? span.min : null;
922
+ return [h('span', { class: 'ml-p-v', text: Number.isFinite(n) ? fmtTokValue(n, unit) : (fallback || '—') })];
923
+ };
877
924
 
878
- const priceCell = priceKind === 'percall' || priceKind === 'unknown' || isAuto
925
+ const priceCell = priceKind === 'percall' || priceKind === 'unknown' || priceKind === 'mixed' || isAuto
879
926
  ? h('span', { class: 'ml-cell ml-price' },
880
927
  h('span', { class: 'ml-p-line' }, h('span', { class: 'ml-p-v', text: pricing.input || '—' })))
881
928
  : h('span', { class: 'ml-cell ml-price' },
882
929
  h('span', { class: 'ml-p-line' },
883
- h('span', { class: 'ml-p-k', text: '输入' }), h('span', { class: 'ml-p-v', text: fmtTokValue(pricing.inputNum, unit) }),
884
- h('span', { class: 'ml-p-k', text: '输出' }), h('span', { class: 'ml-p-v', text: fmtTokValue(pricing.outputNum, unit) })),
885
- h('span', { class: 'ml-p-unit', text: `${(cache.state && cache.state.currency && cache.state.currency.symbol) || '$'} / 1${unit}` }));
930
+ h('span', { class: 'ml-p-k', text: '入' }), ...pair(agg.prices?.input, pricing.input),
931
+ h('span', { class: 'ml-p-k', text: '出' }), ...pair(agg.prices?.output, pricing.output)),
932
+ h('span', { class: 'ml-p-unit', text: `${(cache.state && cache.state.currency && cache.state.currency.symbol) || '$'} / ${unitText(unit)}` }));
933
+
934
+ const cacheSpan = agg.prices?.cache;
935
+ const cacheText = cacheSpan && !cacheSpan.same
936
+ ? fmtRangeBare(cacheSpan, unit)
937
+ : (cacheSpan ? fmtTokValue(cacheSpan.min, unit) : pricing.cache);
886
938
 
887
939
  return h('div', {
888
940
  class: 'ml-row',
889
941
  role: 'button',
890
942
  tabindex: '0',
891
- title: `打开 ${m.name} 的详情`,
943
+ title: `打开 ${agg.name} 的详情(${agg.groupCount} 个分组)`,
892
944
  onclick: open,
893
945
  onkeydown: (ev) => {
894
946
  if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); open(); }
895
947
  },
896
948
  },
897
949
  h('span', { class: 'ml-cell ml-model' },
898
- vendorBadge(m.vendor, { size: 13 }),
899
- h('span', { class: 'ml-name', text: m.name }),
950
+ vendorBadge(agg.vendor, { size: 13 }),
951
+ h('span', { class: 'ml-name', text: agg.name }),
900
952
  kind !== 'chat' ? h('span', { class: 'ml-kind', text: KIND_LABEL[kind] || kind }) : null),
901
953
 
902
954
  h('span', { class: `ml-cell ml-type ${billing.cls}`, text: billing.label }),
@@ -904,20 +956,17 @@ function modelRow(m, groupMap) {
904
956
  priceCell,
905
957
 
906
958
  h('span', { class: 'ml-cell ml-cache' },
907
- h('span', {
908
- class: 'ml-c-v',
909
- text: Number.isFinite(pricing.cacheNum) ? fmtTokValue(pricing.cacheNum, unit) : (pricing.cache || '—'),
910
- }),
911
- Number.isFinite(pricing.cacheNum) ? h('span', { class: 'ml-c-unit', text: `/ 1${unit}` }) : null),
959
+ h('span', { class: 'ml-c-v', text: cacheText || '—' }),
960
+ cacheText ? h('span', { class: 'ml-c-unit', text: `/ ${unitText(unit)}` }) : null),
912
961
 
913
962
  h('span', { class: 'ml-cell ml-vendor' },
914
- vendorBadge(m.vendor, { size: 13 }),
915
- h('span', { text: m.vendor || '—' })),
963
+ vendorBadge(agg.vendor, { size: 13 }),
964
+ h('span', { text: agg.vendor || '—' })),
916
965
 
917
966
  h('span', { class: 'ml-cell ml-ends' },
918
967
  ends.length ? endpointEls(ends, 3) : h('span', { class: 'ml-dash' })),
919
968
 
920
- h('span', { class: 'ml-cell ml-groups' }, groupChipsEl(m)));
969
+ h('span', { class: 'ml-cell ml-groups' }, groupChipsEl(agg)));
921
970
  }
922
971
 
923
972
  /** 顶部横幅:选中分组时给分组信息,只选了分类时给分类信息,都没选就收起。 */
@@ -1065,33 +1114,75 @@ function libraryGroupChips(list, modelsByGroup, countOf) {
1065
1114
  * 「全部」视图下这里列的是它所在的全部(最多两个 + +N,title 里给全量);
1066
1115
  * 选了具体分组时 groups 只有一个,看起来和以前一样。
1067
1116
  */
1068
- function groupChipsEl(m) {
1069
- const list = Array.isArray(m.groups) && m.groups.length
1070
- ? m.groups
1071
- : [{ group: m.group, groupRatio: m.groupRatio, groupAuto: m.groupAuto }];
1072
- const shown = list.slice(0, 2);
1073
- const more = list.length - shown.length;
1117
+ /**
1118
+ * 分组标签:把这张模型卡涉及的分组**全部**列出来。
1119
+ *
1120
+ * 站点把同一个模型在十几个分组里各卖一份,价差能到 20 倍(0.06× 到 1.2×),
1121
+ * 所以「有哪些分组」本身就是关键信息,不能折叠成「+3」让人再点一次。
1122
+ * 分组少就一行排开,多就换行——排版交给 CSS 的 flex-wrap,不在 JS 里截断。
1123
+ */
1124
+ function groupChipsEl(agg) {
1125
+ // 每个分组各占一个 chip,即使两个分组的倍率与价格完全一致也不并成
1126
+ // `gpt-pro/promax`——分组名是用户要认的渠道,拼串会让人以为那是一个名字。
1127
+ // 分组多的模型自然排到第二行,这个双行排布是刻意的。
1128
+ const list = Array.isArray(agg.groups) ? agg.groups : [];
1074
1129
  const title = list
1075
- .map((g) => `${GROUP_ALIAS[g.group] || g.group}${Number(g.groupRatio) > 0 ? ' ' + fmtRatio(g.groupRatio) : ''}`)
1130
+ .map((g) => `${g.id}${Number(g.ratio) > 0 ? ' ' + fmtRatio(g.ratio) : ''}`)
1076
1131
  .join('\n');
1077
1132
  return h('span', { class: 'mc-groups', title },
1078
- shown.map((g) => h('span', { class: 'mc-gb' },
1079
- Number(g.groupRatio) > 0 ? ratioTag(g.groupRatio) : null,
1080
- h('span', { class: 'mc-group', text: GROUP_ALIAS[g.group] || g.group || '—' }))),
1081
- more > 0 ? h('span', { class: 'mc-more', text: `+${more}` }) : null);
1133
+ list.map((g) => h('span', { class: 'mc-gb' },
1134
+ Number(g.ratio) > 0 ? ratioTag(g.ratio) : null,
1135
+ h('span', { class: 'mc-group', text: GROUP_ALIAS[g.id] || g.id || '—' }))));
1082
1136
  }
1083
1137
 
1084
- function modelCard(m, groupMap) {
1085
- const info = groupMap.get(m.group);
1086
- const isAuto = m.group === 'auto' || (info && info.auto === true);
1087
- const pricing = m.pricing || {};
1088
- const priceKind = pricing.kind || 'unknown';
1089
- const kind = m.kind || 'chat';
1090
- const endpoints = Array.isArray(m.endpoints) ? m.endpoints : [];
1138
+ /**
1139
+ * 聚合后的计费方式:分组之间不一致时如实标「多种计费」,
1140
+ * 不挑一个顺眼的来代表全部。
1141
+ */
1142
+ function billingOfAgg(agg) {
1143
+ if (agg.priceKind === 'mixed') return { cls: 'mixed', label: '多种计费' };
1144
+ const g = agg.cheapest;
1145
+ return billingLabel(g?.pricing || {}, Boolean(g?.auto), agg.priceKind);
1146
+ }
1147
+
1148
+ /**
1149
+ * 三个价格格:跨分组是区间就印区间($0.12–$0.32/M),相同就印单值。
1150
+ *
1151
+ * 只印最低价会让人以为这就是这个模型的价——而它其实只属于最便宜的那个分组。
1152
+ */
1153
+ function priceCellsOfAgg(agg, unit) {
1154
+ const cell = (label, span, fallback) => {
1155
+ if (span && !span.same) {
1156
+ const text = fmtRange(span, unit);
1157
+ return h('div', null,
1158
+ h('span', { text: label }),
1159
+ h('b', { class: 'with-range', title: text, text }));
1160
+ }
1161
+ const num = span ? span.min : null;
1162
+ return h('div', null,
1163
+ h('span', { text: label }),
1164
+ h('b', { text: Number.isFinite(num) ? fmtTok(num, unit) : (fallback || '—') }));
1165
+ };
1166
+ const p = (agg.cheapest && agg.cheapest.pricing) || {};
1167
+ return [
1168
+ cell('输入', agg.prices?.input, p.input),
1169
+ cell('输出', agg.prices?.output, p.output),
1170
+ cell('缓存读取', agg.prices?.cache, p.cache),
1171
+ ];
1172
+ }
1173
+
1174
+ function modelCard(agg, groupMap) {
1175
+ const focus = agg.cheapest || { pricing: {} };
1176
+ const pricing = focus.pricing || {};
1177
+ const priceKind = agg.priceKind || pricing.kind || 'unknown';
1178
+ const isAuto = Boolean(focus.auto);
1179
+ const kind = agg.kind || 'chat';
1180
+ const endpoints = Array.isArray(agg.endpoints) ? agg.endpoints : [];
1091
1181
 
1092
1182
  // 计费方式的说法要跟价格表一致:按次/按秒只给一列,别硬凑出「输出价 —」。
1093
- const billing = billingLabel(pricing, isAuto, priceKind);
1183
+ const billing = billingOfAgg(agg);
1094
1184
 
1185
+ const flat = priceKind === 'percall' || priceKind === 'unknown' || priceKind === 'auto' || isAuto;
1095
1186
  let priceCells;
1096
1187
  if (isAuto) {
1097
1188
  priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { class: 'muted', text: '—' }))];
@@ -1099,31 +1190,34 @@ function modelCard(m, groupMap) {
1099
1190
  priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { class: 'unknown', text: '价格未知' }))];
1100
1191
  } else if (priceKind === 'percall') {
1101
1192
  priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { text: pricing.input || '—' }))];
1193
+ } else if (priceKind === 'mixed') {
1194
+ priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { class: 'unknown', text: '见详情' }))];
1102
1195
  } else {
1103
- priceCells = priceCellsOf(pricing, filters.unit);
1196
+ priceCells = priceCellsOfAgg(agg, filters.unit);
1104
1197
  }
1105
1198
 
1106
- const desc = m.description || autoDescription(m);
1199
+ const desc = agg.description || autoDescription(agg, pricing);
1107
1200
  const titleBits = [
1108
- m.description ? desc : desc + '(站点没有给说明,这段是按目录信息拼的)',
1109
- m.tags ? `标签:${m.tags}` : '',
1201
+ agg.description ? desc : desc + '(站点没有给说明,这段是按目录信息拼的)',
1202
+ agg.tags ? `标签:${agg.tags}` : '',
1110
1203
  pricing.note || '',
1111
- m.context ? `上下文 ${fmtInt(m.context)}` : '',
1112
- `模型 id:${m.id || ''}`,
1204
+ agg.context ? `上下文 ${fmtInt(agg.context)}` : '',
1205
+ `模型 id:${focus.row?.id || agg.id || ''}`,
1206
+ agg.groupCount > 1 ? `共 ${agg.groupCount} 个分组:` + agg.groups.map((g) => g.id).join('、') : '',
1113
1207
  ].filter(Boolean).join('\n');
1114
1208
 
1115
- const open = () => openModelDrawer(m);
1209
+ const open = () => openModelDrawer(agg);
1116
1210
 
1117
1211
  return h('article', { class: `mc mc-${kind}`, title: titleBits },
1118
1212
  h('div', { class: 'mc-head' },
1119
- h('span', { class: 'mc-vicon' }, vendorBadge(m.vendor, { size: 18 })),
1213
+ h('span', { class: 'mc-vicon' }, vendorBadge(agg.vendor, { size: 18 })),
1120
1214
  h('div', { class: 'grow' },
1121
1215
  h('button', {
1122
1216
  class: 'mc-name', type: 'button',
1123
- title: '查看这个模型的计费表达式与分档',
1217
+ title: '查看这个模型的计费表达式与各分组定价',
1124
1218
  onclick: open,
1125
- }, m.name || m.id || '未命名'),
1126
- m.vendor ? h('div', { class: 'mc-vendor', text: m.vendor }) : null),
1219
+ }, agg.name || agg.id || '未命名'),
1220
+ agg.vendor ? h('div', { class: 'mc-vendor', text: agg.vendor }) : null),
1127
1221
  // 绝大多数是对话模型,每张卡都挂一个「对话」只会变成噪音;只在生图/视频这类上标。
1128
1222
  kind !== 'chat' ? h('span', { class: 'mc-kind', text: KIND_LABEL[kind] || kind }) : null),
1129
1223
 
@@ -1131,20 +1225,21 @@ function modelCard(m, groupMap) {
1131
1225
 
1132
1226
  h('div', { class: `mc-billing ${billing.cls}`, text: billing.label }),
1133
1227
 
1134
- h('div', { class: priceKind === 'percall' || priceKind === 'unknown' || isAuto ? 'mc-prices one' : 'mc-prices' }, priceCells),
1228
+ h('div', { class: flat ? 'mc-prices one' : 'mc-prices' }, priceCells),
1135
1229
 
1136
- h('div', { class: 'mc-line' },
1230
+ h('div', { class: 'mc-line mc-line-groups' },
1137
1231
  h('span', { class: 'k', text: '分组' }),
1138
- groupChipsEl(m)),
1232
+ groupChipsEl(agg)),
1139
1233
 
1234
+ // 端点与「详情」同一行:卡片最后一行本来就只剩这两个短元素,
1235
+ // 各占一行纯属浪费高度。详情靠右,仍然在视觉上收尾这张卡。
1140
1236
  h('div', { class: 'mc-line mc-line-ends' },
1141
1237
  h('span', { class: 'k', text: '端点' }),
1142
1238
  endpoints.length
1143
1239
  ? h('span', { class: 'mc-ends' }, ...endpointEls(endpoints, 4))
1144
- : h('span', { class: 'muted', text: '—' })),
1145
-
1146
- h('div', { class: 'mc-foot' },
1147
- h('button', { class: 'link mc-detail', type: 'button', onclick: open }, '详情', h('span', { class: 'mc-detail-arrow', text: '›' }))));
1240
+ : h('span', { class: 'muted', text: '—' }),
1241
+ h('button', { class: 'link mc-detail', type: 'button', onclick: open },
1242
+ '详情', h('span', { class: 'mc-detail-arrow', text: '›' }))));
1148
1243
  }
1149
1244
 
1150
1245
  /**
@@ -1153,15 +1248,16 @@ function modelCard(m, groupMap) {
1153
1248
  * 只陈述目录里确实存在的字段(厂商 / 类型 / 端点 / 计价),不编用途与能力;
1154
1249
  * 卡片的 tooltip 里会注明这句是按目录拼的,不冒充站点原文。
1155
1250
  */
1156
- function autoDescription(m) {
1251
+ function autoDescription(m, pricing) {
1157
1252
  const vendor = m.vendor || '站点';
1158
1253
  const kind = KIND_LABEL[m.kind] || '模型';
1159
- const ends = (Array.isArray(m.endpoints) ? m.endpoints : []).slice(0, 2);
1160
- const p = m.pricing || {};
1254
+ const ends = (Array.isArray(m.endpoints) ? m.endpoints : []).slice(0, 2).map(endLabel);
1255
+ const p = pricing || m.pricing || {};
1161
1256
  const billing = p.kind === 'tiered' ? '分档计费'
1162
1257
  : p.kind === 'percall' ? '按次/按秒计费'
1163
- : p.kind === 'ratio' ? '按倍率计费'
1164
- : '';
1258
+ : p.kind === 'flat' ? '按量计费'
1259
+ : p.kind === 'ratio' ? '按倍率计费'
1260
+ : '';
1165
1261
  const price = p.input && p.input !== '价格未知'
1166
1262
  ? (p.kind === 'percall' ? `,单价 ${p.input}` : `,输入 ${p.input}`)
1167
1263
  : '';
@@ -1188,10 +1284,10 @@ function bindCatalogControls() {
1188
1284
  search.focus();
1189
1285
  });
1190
1286
 
1191
- // 价格单位:/1M ↔ /1K
1287
+ // 价格单位:/1M ↔ /272K
1192
1288
  for (const btn of $$('#unit-seg button')) {
1193
1289
  btn.addEventListener('click', () => {
1194
- filters.unit = btn.dataset.unit === 'K' ? 'K' : 'M';
1290
+ filters.unit = btn.dataset.unit === '272K' ? '272K' : 'M';
1195
1291
  for (const other of $$('#unit-seg button')) other.setAttribute('aria-pressed', String(other === btn));
1196
1292
  if (cache.catalog) renderCatalog();
1197
1293
  });
@@ -1258,9 +1354,258 @@ function bindCatalogControls() {
1258
1354
  async function loadWallet(force = false) {
1259
1355
  await loadState(force);
1260
1356
  renderAccounts();
1261
- await Promise.all([loadUsage(force), loadFlow(force)]);
1357
+ await Promise.all([loadUsage(force), loadAff(force), loadSubscriptions(force)]);
1358
+ }
1359
+
1360
+ /**
1361
+ * 推荐计划:邀请码、已邀请人数、累计奖励。
1362
+ *
1363
+ * 站点没开这个端点时不假装「0 人邀请」,而是如实说没有——两者对用户
1364
+ * 意味着完全不同的东西(一个是没开功能,一个是真没人注册)。
1365
+ */
1366
+ async function loadAff(force = false) {
1367
+ const box = $('#aff-body');
1368
+ if (!box) return;
1369
+ if (cache.aff && !force) { renderAff(); return cache.aff }
1370
+ if (loading.aff) return cache.aff
1371
+ const epoch = dataEpoch;
1372
+ loading.aff = true
1373
+ regionLoading(box, '正在读取推荐计划')
1374
+ try {
1375
+ const data = await api.aff()
1376
+ if (epoch !== dataEpoch) return null;
1377
+ cache.aff = data
1378
+ renderAff()
1379
+ return cache.aff
1380
+ } catch (err) {
1381
+ if (epoch !== dataEpoch) return null;
1382
+ const msg = describeError(err)
1383
+ // 没设 PAT 属于正常状态,不甩红条
1384
+ if (err instanceof ApiError && err.status === 400 && /访问令牌/.test(msg)) {
1385
+ cache.aff = { ok: true, aff: null, link: '', note: '设置访问令牌(PAT)后显示邀请与奖励' }
1386
+ renderAff()
1387
+ return cache.aff
1388
+ }
1389
+ cache.aff = { ok: false, error: msg }
1390
+ renderAff()
1391
+ return cache.aff
1392
+ } finally {
1393
+ if (epoch === dataEpoch) loading.aff = false
1394
+ }
1395
+ }
1396
+
1397
+ // ── 只读订阅:原币标价和 quota 额度各用自己的口径 ────────────
1398
+ const BILLING_LABEL = { subscription_first: '优先订阅', wallet_first: '优先钱包', subscription_only: '仅用订阅', wallet_only: '仅用钱包' };
1399
+ const SUB_STATUS = { active: '有效', expired: '已到期', cancelled: '已取消', canceled: '已取消' };
1400
+ const fullDate = (ms) => Number.isFinite(ms) && ms > 0 ? new Date(ms).toLocaleString('zh-CN', { hour12: false }) : '—';
1401
+
1402
+ async function loadSubscriptions(force = false) {
1403
+ if (cache.subscriptions && !force) { renderSubscriptions(); return cache.subscriptions; }
1404
+ if (loading.subscriptions) return null;
1405
+ const epoch = dataEpoch;
1406
+ loading.subscriptions = true;
1407
+ regionLoading($('#subscriptions-body'), '正在读取订阅与套餐');
1408
+ try {
1409
+ const data = await api.subscriptions();
1410
+ if (epoch !== dataEpoch) return null;
1411
+ cache.subscriptions = data;
1412
+ } catch (err) {
1413
+ if (epoch !== dataEpoch) return null;
1414
+ cache.subscriptions = { ok: false, needPat: err.status === 400 && /访问令牌/.test(err.message), error: describeError(err) };
1415
+ } finally {
1416
+ if (epoch === dataEpoch) { loading.subscriptions = false; renderSubscriptions(); }
1417
+ }
1418
+ return cache.subscriptions;
1419
+ }
1420
+
1421
+ function renderSubscriptions() {
1422
+ const box = $('#subscriptions-body');
1423
+ const d = cache.subscriptions;
1424
+ if (!box || !d) return;
1425
+ // 没有 PAT:钱包卡的空态已经带「去设置访问令牌」,这里不再重复一条引导。
1426
+ if (d.needPat) { box.replaceChildren(); return; }
1427
+ if (d.ok === false) { regionError(box, `订阅没读到:${d.error}`, () => loadSubscriptions(true)); return; }
1428
+ // 订阅最多一条:优先当前生效的,其次第一条历史记录。
1429
+ // 套餐列表不再展示——只读、不能买,摆进钱包卡只会把余额挤下去。
1430
+ const list = Array.isArray(d.subscriptions) ? d.subscriptions : [];
1431
+ const current = list.find((s) => s.active) || list[0] || null;
1432
+ const preference = BILLING_LABEL[d.billingPreference] || '站点未返回可识别的扣费偏好';
1433
+ box.replaceChildren(
1434
+ h('div', { class: 'wallet-sub-head' },
1435
+ h('h4', { class: 'subscription-heading', text: '订阅' }),
1436
+ h('span', { class: 'hint', text: `扣费偏好:${preference}(只读)` })),
1437
+ current
1438
+ ? subscriptionCard(current)
1439
+ : h('p', { class: 'empty', text: '当前没有订阅。' }),
1440
+ );
1441
+ }
1442
+
1443
+ function subscriptionCard(s) {
1444
+ const status = s.status === 'active'
1445
+ ? s.active ? '有效' : s.startAt > Date.now() ? '尚未生效' : s.endAt > 0 && s.endAt <= Date.now() ? '已到期' : '未确认有效'
1446
+ : SUB_STATUS[s.status] || s.status || '未知状态';
1447
+ const ratio = Number.isFinite(s.progress) ? s.progress : null;
1448
+ const progress = s.unlimited || ratio === null ? null : h('progress', {
1449
+ class: 'subscription-progress', max: '100', value: String(Math.max(0, Math.min(100, ratio))),
1450
+ title: `已用 ${s.used} / ${s.total} · ${ratio.toFixed(1)}%`,
1451
+ 'aria-label': `${s.title} 使用进度`, 'aria-valuetext': `${ratio.toFixed(1)}% · 已用 ${s.used} / ${s.total}`,
1452
+ });
1453
+ return h('article', { class: 'subscription-item' },
1454
+ h('div', { class: 'subscription-title' }, h('b', { text: s.title }), h('span', { class: 'acct-chip', text: status })),
1455
+ h('dl', { class: 'acct-facts' },
1456
+ h('dt', { text: '到期时间' }), h('dd', { text: fullDate(s.endAt) }),
1457
+ h('dt', { text: '下次重置' }), h('dd', { text: fullDate(s.nextResetAt) }),
1458
+ h('dt', { text: '已用 / 总额度' }), h('dd', { text: `${s.used || '—'} / ${s.unlimited ? '不限量' : s.total || '—'}` }),
1459
+ h('dt', { text: '剩余额度' }), h('dd', { text: s.unlimited ? '不限量' : s.remaining || '—' })),
1460
+ progress,
1461
+ h('p', { class: 'hint', text: s.unlimited ? '不限量 · 不计算额度百分比' : ratio === null ? '额度数据不足,无法计算进度' : `使用进度 ${ratio.toFixed(1)}%${ratio > 100 ? ' · 已超额' : ''}` }),
1462
+ );
1262
1463
  }
1263
1464
 
1465
+ // ── 推荐计划:仿原站钱包页的横条 ────────────────────────────────
1466
+ // 版式照你截图的原站设计:图标 + 标题/说明 + 三统计列(待确认/总收入/邀请)
1467
+ // + 链接胶囊 + 复制图标按钮 + 「转移到余额」蓝色按钮。
1468
+ // 站点 /api/user/aff 的字段名随部署而变(aff_count/aff_quota 是 New API 常见写法,
1469
+ // 「待确认」没有公认键名),所以每列只在真拿到数字时才渲染。
1470
+
1471
+ /** 转入余额需二次确认:第一下改成「确认转入」,5 秒内再点才真的发请求。 */
1472
+ let affTransferArmedUntil = 0;
1473
+
1474
+ function renderAff() {
1475
+ const box = $('#aff-body');
1476
+ if (!box) return;
1477
+ const d = cache.aff || {};
1478
+
1479
+ if (d.ok === false) {
1480
+ box.replaceChildren(h('p', { class: 'rf-note', text: `推荐计划没读到:${d.error || '未知原因'}` }));
1481
+ return;
1482
+ }
1483
+
1484
+ const link = d.link || '';
1485
+ const a = d.aff || {};
1486
+ // 三列:待确认(站点给才显示)/ 总收入 / 邀请。只认真实值,不拿 0 假装同步过。
1487
+ const pending = Number.isFinite(a.pending) ? moneyRaw(a.pending) : null;
1488
+ const total = Number.isFinite(a.historyQuota) ? moneyRaw(a.historyQuota) : null;
1489
+ const invites = Number.isFinite(a.count) ? fmtInt(a.count) : null;
1490
+ const canTransfer = Number.isFinite(a.quota) && a.quota > 0;
1491
+ const armed = Date.now() < affTransferArmedUntil;
1492
+
1493
+ // replaceChildren 收 null 会把它印成字符串「null」——先过滤再加。
1494
+ box.replaceChildren(...[
1495
+ h('div', { class: 'rf-ico', 'aria-hidden': 'true' }, shareIcon()),
1496
+ h('div', { class: 'rf-text' },
1497
+ h('h2', { class: 'rf-title', text: '推荐计划' }),
1498
+ h('p', {
1499
+ class: 'rf-note',
1500
+ text: d.note || '用户通过你的推荐链接注册后,你会获得奖励;累计奖励可随时转入余额。',
1501
+ })),
1502
+ pending ? rfStat('待确认', pending) : null,
1503
+ // 同步时间挪到「总收入」左侧(站点把时间放最右,读起来像脚注)
1504
+ d.at ? h('span', { class: 'rf-sync', text: `· 同步 ${fmtAt(d.at)}` }) : null,
1505
+ total ? rfStat('总收入', total) : null,
1506
+ Number.isFinite(a.quota) ? rfStat('可转奖励', moneyRaw(a.quota)) : null,
1507
+ invites ? rfStat('邀请', invites) : null,
1508
+ h('div', { class: 'rf-actions' },
1509
+ link ? h('div', { class: 'rf-link' }, h('span', { class: 'mono', text: link })) : null,
1510
+ link
1511
+ ? h('button', {
1512
+ class: 'rf-copy', type: 'button', title: '复制推荐链接', 'aria-label': '复制推荐链接',
1513
+ onclick: (ev) => copyText(link, ev.currentTarget, '已复制'),
1514
+ }, copyIcon())
1515
+ : null,
1516
+ canTransfer
1517
+ ? h('button', {
1518
+ class: `btn primary rf-transfer${armed ? ' is-armed' : ''}`,
1519
+ type: 'button',
1520
+ title: '把累计奖励转到余额(站点上的真实资金操作)',
1521
+ onclick: (ev) => transferAffRewards(ev.currentTarget),
1522
+ }, armed ? '确认转入' : '转移到余额')
1523
+ : null),
1524
+ ].filter(Boolean));
1525
+ }
1526
+
1527
+ /** rfStat 一个统计列:小标签在上、数值在下。 */
1528
+ function rfStat(k, v) {
1529
+ return h('div', { class: 'rf-stat' },
1530
+ h('div', { class: 'rf-k', text: k }),
1531
+ h('div', { class: 'rf-v', text: v }));
1532
+ }
1533
+
1534
+ /** transferAffRewards 转账:两段式确认(沙箱里 window.confirm 会被拦成 false)。 */
1535
+ async function transferAffRewards(btn) {
1536
+ if (Date.now() >= affTransferArmedUntil) {
1537
+ affTransferArmedUntil = Date.now() + 5000;
1538
+ renderAff();
1539
+ banner('info', '再点一次「确认转入」,就会把累计奖励转进余额。', { key: 'aff-transfer', timeout: 5000 });
1540
+ return;
1541
+ }
1542
+
1543
+ affTransferArmedUntil = 0;
1544
+ btn.disabled = true;
1545
+ btn.textContent = '转入中…';
1546
+ try {
1547
+ const r = await api.transferAff();
1548
+ banner(r.ok ? 'ok' : 'warn', r.message || (r.ok ? '已转入余额' : '站点没有说明原因'), { key: 'aff-transfer' });
1549
+ await Promise.all([loadAff(true), loadState(true)]);
1550
+ renderAccounts();
1551
+ } catch (err) {
1552
+ banner('error', `转入失败:${describeError(err)}`, { key: 'aff-transfer' });
1553
+ } finally {
1554
+ btn.disabled = false;
1555
+ renderAff();
1556
+ }
1557
+ }
1558
+
1559
+ /** 分享图标:三个节点由连线相接(与原站同一图形语言),放在圆形底上。 */
1560
+ function shareIcon() {
1561
+ const ns = 'http://www.w3.org/2000/svg';
1562
+ const svg = document.createElementNS(ns, 'svg');
1563
+ svg.setAttribute('viewBox', '0 0 24 24');
1564
+ svg.setAttribute('width', '16');
1565
+ svg.setAttribute('height', '16');
1566
+ svg.setAttribute('fill', 'none');
1567
+ svg.setAttribute('stroke', 'currentColor');
1568
+ svg.setAttribute('stroke-width', '1.8');
1569
+ svg.setAttribute('stroke-linecap', 'round');
1570
+ for (const d of ['M8.5 6.2 15.5 9.8', 'M8.5 17.8 15.5 14.2']) {
1571
+ const p = document.createElementNS(ns, 'path');
1572
+ p.setAttribute('d', d);
1573
+ svg.appendChild(p);
1574
+ }
1575
+ for (const [cx, cy] of [[5.5, 5], [5.5, 19], [18, 12]]) {
1576
+ const c = document.createElementNS(ns, 'circle');
1577
+ c.setAttribute('cx', String(cx));
1578
+ c.setAttribute('cy', String(cy));
1579
+ c.setAttribute('r', '2.6');
1580
+ svg.appendChild(c);
1581
+ }
1582
+ return svg;
1583
+ }
1584
+
1585
+ /** 复制图标:两个叠着的圆角矩形,与原站一致。 */
1586
+ function copyIcon() {
1587
+ const ns = 'http://www.w3.org/2000/svg';
1588
+ const svg = document.createElementNS(ns, 'svg');
1589
+ svg.setAttribute('viewBox', '0 0 24 24');
1590
+ svg.setAttribute('width', '13');
1591
+ svg.setAttribute('height', '13');
1592
+ svg.setAttribute('fill', 'none');
1593
+ svg.setAttribute('stroke', 'currentColor');
1594
+ svg.setAttribute('stroke-width', '1.8');
1595
+ svg.setAttribute('stroke-linecap', 'round');
1596
+ svg.setAttribute('stroke-linejoin', 'round');
1597
+ svg.setAttribute('aria-hidden', 'true');
1598
+ for (const d of ['M9 9h10v10H9z', 'M5 15V5h10']) {
1599
+ const p = document.createElementNS(ns, 'path');
1600
+ p.setAttribute('d', d);
1601
+ svg.appendChild(p);
1602
+ }
1603
+ return svg;
1604
+ }
1605
+
1606
+
1607
+
1608
+
1264
1609
  function renderAccounts() {
1265
1610
  const box = $('#account-body');
1266
1611
  const sub = $('#account-sub');
@@ -1274,44 +1619,76 @@ function renderAccounts() {
1274
1619
  const st = cache.state;
1275
1620
  if (!st) { regionLoading(box, '正在读取账户'); if (sub) sub.textContent = ''; return; }
1276
1621
 
1277
- const accounts = st.accounts || [];
1278
- if (sub) sub.textContent = accounts.length ? `${accounts.length} 个账号` : '';
1622
+ const bound = Array.isArray(st.accounts) ? st.accounts : Object.values(st.accounts || {});
1623
+ const user = st.user;
1624
+ const accounts = [
1625
+ ...(user ? [{ ...user, wallet: true, label: user.displayName || user.username, models: undefined }] : []),
1626
+ ...bound,
1627
+ ];
1628
+ if (sub) sub.textContent = [user ? 'PAT 账户钱包' : '', bound.length ? `${bound.length} 把绑定钥匙` : ''].filter(Boolean).join(' · ');
1629
+ // 空态时让说明在卡里居中,而不是顶在上面、下面留一大片空白
1630
+ box.classList.toggle('is-empty', accounts.length === 0);
1279
1631
  if (!accounts.length) {
1280
- box.replaceChildren(h('div', { class: 'empty', text: '还没有绑定任何账号。在 magpie 里添加 DragonAPI 账号后,钥匙与余额会出现在这里。' }));
1632
+ if (st.userError) regionError(box, `PAT 账户没读到:${st.userError}`, () => loadWallet(true));
1633
+ else box.replaceChildren(h('div', { class: 'empty' },
1634
+ h('p', { text: '设置 PAT 后可读取钱包余额、用量与订阅,无需先绑定 sk- 钥匙。绑定钥匙的额度会单独展示。' }),
1635
+ h('button', { class: 'btn ghost', type: 'button', onclick: () => activateTab('pat') }, '去设置访问令牌')));
1281
1636
  return;
1282
1637
  }
1283
1638
 
1284
- box.replaceChildren(...accounts.map((a) => {
1639
+ // 版式照站点控制台的「账户」卡:大字余额 → 已用/用户/分组一行 → 明细 →
1640
+ // 标签行 + 更新时间。**只放我们真有的字段**:站点没有「代金券总额」,
1641
+ // 也没有满血/低价/自有这类标注,就不摆占位符冒充。
1642
+ box.replaceChildren(...[
1643
+ st.userError ? h('p', { class: 'region-error-text', text: `PAT 账户没读到:${st.userError}` }) : null,
1644
+ ...accounts.map((a) => {
1285
1645
  const mask = a.masked || '';
1286
- // 服务端的 label 本身就是「分组 · 打码钥匙」,再单列一次打码就是重复。
1287
- // 只在 label 里没有它时才单独显示。
1288
1646
  const showMask = mask && !String(a.label || '').includes(mask);
1289
- // 余额是「—」不是因为没有余额,而是插件进程还没拿到这把钥匙的明文
1290
- // (冷启动后要等宿主调一次 models/usage 才会填)。说清楚,别让人以为没钱了。
1291
- const noKeyHint = a.balance === '—'
1647
+ const noKeyHint = !a.wallet && a.balance === '—'
1292
1648
  ? '插件还没拿到这把钥匙的明文:在 magpie 里发一次请求、或点右上角「刷新」即可'
1293
1649
  : '';
1294
1650
  const split = splitMoney(a.balance || '—');
1295
- return h('div', { class: 'acct-overview' },
1296
- h('div', { class: 'acct-main' },
1297
- h('div', { class: 'grow' },
1298
- h('div', { class: 'money' },
1299
- split.unit ? h('span', { class: 'unit', text: split.unit }) : null,
1300
- split.value),
1301
- h('p', {
1302
- class: 'money-note',
1303
- text: [
1304
- a.used && a.used !== '—' ? `已用 ${a.used}` : '',
1305
- a.group ? `分组 ${a.group}` : '',
1306
- showMask ? `钥匙 ${mask}` : '',
1307
- Number.isFinite(a.models) && a.models ? `${fmtInt(a.models)} 个模型` : '',
1308
- Number.isFinite(a.boundAt) && a.boundAt ? `绑定于 ${fmtAt(a.boundAt)}` : '',
1309
- ].filter(Boolean).join(' · ') || (a.label || '还没有读到账户'),
1310
- })),
1311
- noKeyHint ? h('span', { class: 'acct-hint', text: noKeyHint }) : null,
1312
- ),
1651
+ const userName = (st.user && (st.user.name || st.user.username)) || '';
1652
+
1653
+ const meta = [
1654
+ a.used && a.used !== '—' ? `已用 ${a.used}` : '',
1655
+ userName ? `用户 ${userName}` : '',
1656
+ a.group ? `分组 ${a.group}` : '',
1657
+ ].filter(Boolean).join(' · ');
1658
+
1659
+ const chips = [
1660
+ a.group ? h('span', { class: 'acct-chip', text: a.group }) : null,
1661
+ showMask ? h('span', { class: 'acct-chip mono', text: mask }) : null,
1662
+ ].filter(Boolean);
1663
+
1664
+ const facts = [
1665
+ Number.isFinite(a.models) ? ['模型数', fmtInt(a.models)] : null,
1666
+ Number.isFinite(a.boundAt) && a.boundAt ? ['绑定于', fmtAt(a.boundAt)] : null,
1667
+ ].filter(Boolean);
1668
+
1669
+ return h('div', { class: 'acct-card' },
1670
+ h('p', { class: 'acct-meta', text: a.wallet ? `账户钱包 · ${a.label || a.username || 'PAT 账户'}` : `钥匙额度 · ${a.label || a.key || '绑定钥匙'}` }),
1671
+ h('div', { class: 'acct-hero' },
1672
+ h('div', { class: 'acct-money' },
1673
+ split.unit ? h('span', { class: 'acct-cur', text: split.unit }) : null,
1674
+ h('b', { class: 'acct-num', text: split.value }))),
1675
+
1676
+ meta ? h('p', { class: 'acct-meta', text: meta }) : null,
1677
+
1678
+ facts.length
1679
+ ? h('dl', { class: 'acct-facts' },
1680
+ facts.flatMap(([k, v]) => [h('dt', { text: k }), h('dd', { class: 'mono', text: v })]))
1681
+ : null,
1682
+
1683
+ (chips.length || a.balanceAt)
1684
+ ? h('div', { class: 'acct-foot' },
1685
+ h('span', { class: 'acct-chips' }, chips),
1686
+ a.balanceAt ? h('span', { class: 'acct-sync', text: `余额截至 ${fmtAt(a.balanceAt)}` }) : null)
1687
+ : null,
1688
+
1689
+ noKeyHint ? h('p', { class: 'acct-hint', text: noKeyHint }) : null,
1313
1690
  );
1314
- }));
1691
+ })].filter(Boolean));
1315
1692
  }
1316
1693
 
1317
1694
  /** splitMoney 把「$12.34」拆成符号与大数字,照 neartoken 账户卡的做法。 */
@@ -1320,14 +1697,6 @@ function splitMoney(text) {
1320
1697
  return { unit: (m && m[1]) || '', value: (m && m[2]) || '—' };
1321
1698
  }
1322
1699
 
1323
- /** totalBalanceText 把各账号余额相加(quota),按站点币种印出来。 */
1324
- function totalBalanceText() {
1325
- const accts = (cache.state && cache.state.accounts) || [];
1326
- if (!accts.length) return '—';
1327
- const raw = accts.reduce((sum, a) => sum + (Number.isFinite(a.balanceRaw) ? a.balanceRaw : 0), 0);
1328
- return moneyRaw(raw);
1329
- }
1330
-
1331
1700
  function fig(k, v, cls = '', title = '') {
1332
1701
  return h('div', { class: 'fig' },
1333
1702
  h('span', { class: 'fig-k', text: k }),
@@ -1338,32 +1707,43 @@ function fig(k, v, cls = '', title = '') {
1338
1707
  async function loadUsage(force = false) {
1339
1708
  const range = filters.range;
1340
1709
  if (cache.usage[range] && !force) { renderUsage(); return cache.usage[range]; }
1341
- if (loading.usage) return cache.usage[range] || null;
1342
-
1343
- loading.usage = true;
1344
- regionLoading($('#usage-body'), `正在读取${RANGE_LABEL[range]}用量`);
1345
-
1346
- try {
1347
- const data = await api.usage(range);
1348
- cache.usage[range] = data;
1349
- clearBanner('usage');
1350
- renderUsage();
1351
- renderFlow();
1352
- return data;
1353
- } catch (err) {
1354
- const msg = describeError(err);
1355
- banner('error', `读取${RANGE_LABEL[range]}用量失败:${msg}`, { key: 'usage' });
1356
- regionError($('#usage-body'), `用量没读到:${msg}`, () => loadUsage(true));
1357
- return null;
1358
- } finally {
1359
- loading.usage = false;
1360
- }
1710
+ if (usagePending.has(range)) return usagePending.get(range);
1711
+ const epoch = dataEpoch;
1712
+ delete cache.usageErrors[range];
1713
+ const usageBox = $('#usage-body');
1714
+ if (usageBox) regionLoading(usageBox, `正在读取${RANGE_LABEL[range]}用量`);
1715
+ const pending = (async () => {
1716
+ try {
1717
+ const data = await api.usage(range);
1718
+ if (epoch !== dataEpoch) return null;
1719
+ cache.usage[range] = data;
1720
+ clearBanner('usage');
1721
+ renderUsage();
1722
+ renderLogs();
1723
+ return data;
1724
+ } catch (err) {
1725
+ if (epoch !== dataEpoch) return null;
1726
+ delete cache.usage[range];
1727
+ cache.usageErrors[range] = describeError(err);
1728
+ renderUsage();
1729
+ renderLogs();
1730
+ return null;
1731
+ } finally {
1732
+ if (epoch === dataEpoch) usagePending.delete(range);
1733
+ }
1734
+ })();
1735
+ usagePending.set(range, pending);
1736
+ return pending;
1361
1737
  }
1362
1738
 
1363
1739
  function renderUsage() {
1364
1740
  const box = $('#usage-body');
1365
1741
  if (!box) return;
1366
1742
  const data = cache.usage[filters.range];
1743
+ if (cache.usageErrors[filters.range]) {
1744
+ regionError(box, `用量没读到:${cache.usageErrors[filters.range]}`, () => loadUsage(true));
1745
+ return;
1746
+ }
1367
1747
 
1368
1748
  if (!data) {
1369
1749
  regionLoading(box, '正在读取用量');
@@ -1371,6 +1751,7 @@ function renderUsage() {
1371
1751
  }
1372
1752
 
1373
1753
  const byModel = data.byModel || [];
1754
+ const calls = byModel.reduce((n, m) => n + (Number(m.calls) || 0), 0);
1374
1755
  const rows = byModel.map((m) => [
1375
1756
  { text: m.model || '—', cls: 'mono' },
1376
1757
  { text: fmtInt(m.calls), cls: 'num' },
@@ -1378,16 +1759,28 @@ function renderUsage() {
1378
1759
  { text: m.cost || '—', cls: 'num', title: Number.isFinite(m.costRaw) ? `${fmtInt(m.costRaw)} quota` : null },
1379
1760
  ]);
1380
1761
 
1762
+ // 有没有真实用量:柱、模型明细、token 数任一有值就算有
1763
+ const hasUsage = (Array.isArray(data.buckets) ? data.buckets : []).some((b) => Number(b.costRaw) > 0)
1764
+ || rows.length > 0 || Number(data.tokens) > 0;
1765
+
1381
1766
  box.replaceChildren(
1382
- // 三个数字一行,照 neartoken 的「数据概览」
1767
+ // 三个数字一行:消耗 / 请求 / Token。余额在钱包卡里,不在这儿重复。
1383
1768
  h('div', { class: 'stats' },
1384
1769
  statBlock('消耗', data.spent || '—'),
1385
- statBlock('当前余额', totalBalanceText()),
1770
+ statBlock('请求', fmtInt(calls)),
1386
1771
  statBlock('Token', fmtInt(data.tokens))),
1387
- usageChart(data),
1388
1772
  h('p', { class: 'range-note', text: `区间 ${fmtAt(data.start)} → ${fmtAt(data.end)}` }),
1389
- tableEl([{ label: '模型' }, { label: '调用', cls: 'num' }, { label: 'tokens', cls: 'num' }, { label: '费用', cls: 'num' }],
1390
- rows, { empty: '这个区间还没有按模型的用量。' }),
1773
+ ...(data.note ? [h('p', { class: 'hint', text: data.note })] : []),
1774
+ // 有数据才画图与明细;没有就只留一处解释。
1775
+ // 以前这里会同时出现三句「没有数据」(虚线框 + 区间 + 空表),
1776
+ // 一屏空白里堆三句废话,反而看不出该怎么让数据出现。
1777
+ ...(hasUsage
1778
+ ? [usageChart(data),
1779
+ tableEl([{ label: '模型' }, { label: '调用', cls: 'num' }, { label: 'tokens', cls: 'num' }, { label: '费用', cls: 'num' }],
1780
+ rows, { empty: '这个区间还没有按模型的用量。' })]
1781
+ : [h('div', { class: 'usage-empty' },
1782
+ h('p', { class: 'usage-empty-title', text: '这个区间还没有消耗。' }),
1783
+ h('p', { class: 'hint', text: '换个区间看看,或在 magpie 里发一次请求后点右上角「刷新」。' }))]),
1391
1784
  );
1392
1785
  }
1393
1786
 
@@ -1419,122 +1812,994 @@ function usageChart(data) {
1419
1812
  }, bars);
1420
1813
  }
1421
1814
 
1422
- async function loadFlow(force = false) {
1423
- const account = filters.account;
1424
- if (!account) { renderFlow(); return null; } // 全部账号直接用 usage.rows
1425
- if (cache.logs[account] && !force) { renderFlow(); return cache.logs[account]; }
1426
- if (loading.logs) return cache.logs[account] || null;
1427
1815
 
1428
- loading.logs = true;
1429
- renderFlow();
1816
+
1817
+ function bindWalletControls() {
1818
+ for (const btn of $$('.segmented [data-range]')) {
1819
+ btn.addEventListener('click', () => {
1820
+ const range = btn.dataset.range;
1821
+ if (filters.range === range) return;
1822
+ filters.range = range;
1823
+ for (const other of $$('.segmented [data-range]')) {
1824
+ other.setAttribute('aria-pressed', String(other === btn));
1825
+ }
1826
+ loadLogs(false);
1827
+ });
1828
+ }
1829
+
1830
+ }
1831
+
1832
+ /** spentText 金额:有币种就按币种印(金额保留两位,$0.00 比 $0 更像钱);
1833
+ * 没有币种就明说是 quota,不印一个像金额的裸数字。 */
1834
+ function spentText(raw) {
1835
+ if (!Number.isFinite(raw)) return '—';
1836
+ const cur = cache.state && cache.state.currency;
1837
+ if (!cur || cur.display === false) return `${fmtInt(raw)} quota`;
1838
+ const per = Number(cur.per) > 0 ? Number(cur.per) : 500000;
1839
+ const rate = Number(cur.rate) > 0 ? Number(cur.rate) : 1;
1840
+ return `${cur.symbol || '$'}${((raw / per) * rate).toFixed(2)}`;
1841
+ }
1842
+
1843
+ // ── 使用日志:对齐 NearToken「通用日志」的详细程度 ────────────────
1844
+ // 版式与信息密度照 NearToken 的 logsCard:
1845
+ // 工具条(区间/模型/分组/类型/展开)→ 更多筛选(令牌名/请求 ID)→
1846
+ // 统计条(用量/请求/Token + 隐私眼睛 + 重置)→
1847
+ // 9 列网格表(时间+类型+令牌 | 分组 | 模型+映射 | 费用 | 请求体 | 流 | Token | 耗时 | 详情)→
1848
+ // 分页条(总计/每页行数/首上页下末)。
1849
+ // 数据仍走 /api/usage 的行,只做前端筛选;不新开接口。
1850
+
1851
+ const LOG_KIND_ORDER = ['消耗', '充值', '退款', '管理', '系统', '错误'];
1852
+
1853
+ /** 日志表列定义:顺序、表头、栅格宽度(「查看」菜单据此显隐)。 */
1854
+ const LOG_COLS = [
1855
+ { id: 'time', label: '时间', w: 'minmax(110px, .95fr)' },
1856
+ { id: 'key', label: '令牌', w: 'minmax(130px, 1.05fr)' },
1857
+ { id: 'model', label: '模型', w: 'minmax(160px, 1.35fr)' },
1858
+ { id: 'flow', label: '流', w: 'minmax(64px, .55fr)' },
1859
+ { id: 'tokens', label: 'Token', w: 'minmax(104px, .85fr)' },
1860
+ { id: 'cost', label: '费用', w: 'minmax(108px, .85fr)' },
1861
+ { id: 'duration', label: '耗时', w: 'minmax(100px, .8fr)' },
1862
+ { id: 'detail', label: '详情', w: 'minmax(160px, 1.3fr)' },
1863
+ ];
1864
+
1865
+ const logFilter = { model: '', group: '', kind: '', tokenName: '', requestId: '', upRequestId: '' };
1866
+ const logView = {
1867
+ page: 1, pageSize: 20, more: false, private: false, colsOpen: false,
1868
+ cols: new Set(['time', 'key', 'model', 'flow', 'tokens', 'cost', 'duration', 'detail']),
1869
+ };
1870
+
1871
+ /** secs 秒数带单位:4.5 → 4.5s。 */
1872
+ function logSecs(v) {
1873
+ const n = Number(v);
1874
+ if (!Number.isFinite(n) || n <= 0) return null;
1875
+ return `${n.toFixed(1)}s`;
1876
+ }
1877
+
1878
+ /** 耗时分档:与 NearToken 同一组可见阈值——<5s 绿、5–15s 橙黄、≥15s 红。 */
1879
+ /**
1880
+ * logTierClass 官方分档:首字按秒(<5 成功 / <10 警告),耗时按 tokens/s
1881
+ * (≥30 成功 / ≥15 警告);输出太少(<100 token)时退回按秒。
1882
+ */
1883
+ function logTierClass(v, tps, output) {
1884
+ const n = Number(v);
1885
+ const out = Number(output);
1886
+ if (tps !== undefined) {
1887
+ if (Number.isFinite(out) && out >= 100 && Number.isFinite(n) && n > 0) {
1888
+ const t = Number(tps);
1889
+ return t >= 30 ? 'lg-dur-fast' : t >= 15 ? 'lg-dur-mid' : 'lg-dur-slow';
1890
+ }
1891
+ if (!Number.isFinite(n) || n <= 0) return 'lg-dur-none';
1892
+ return n < 10 ? 'lg-dur-fast' : n < 30 ? 'lg-dur-mid' : 'lg-dur-slow';
1893
+ }
1894
+ if (!Number.isFinite(n) || n <= 0) return 'lg-dur-none';
1895
+ return n < 5 ? 'lg-dur-fast' : n < 10 ? 'lg-dur-mid' : 'lg-dur-slow';
1896
+ }
1897
+
1898
+ function logRows() {
1899
+ const data = cache.usage[filters.range];
1900
+ if (!data) return null;
1901
+ const all = Array.isArray(data.rows) ? data.rows : [];
1902
+ const q = logFilter.model.trim().toLowerCase();
1903
+ const tn = logFilter.tokenName.trim().toLowerCase();
1904
+ const rid = logFilter.requestId.trim().toLowerCase();
1905
+ const urid = logFilter.upRequestId.trim().toLowerCase();
1906
+ return all.filter((r) => {
1907
+ if (q && !String(r.model || '').toLowerCase().includes(q)) return false;
1908
+ if (logFilter.group && String(r.group || '') !== logFilter.group) return false;
1909
+ if (logFilter.kind && String(r.kind || '') !== logFilter.kind) return false;
1910
+ if (tn && !String(r.tokenName || '').toLowerCase().includes(tn)) return false;
1911
+ if (rid && !String(r.requestId || '').toLowerCase().includes(rid)) return false;
1912
+ if (urid && !String(r.upRequestId || '').toLowerCase().includes(urid)) return false;
1913
+ return true;
1914
+ });
1915
+ }
1916
+
1917
+ async function loadLogs(force = false) {
1918
+ const box = $('#logs-body');
1919
+ if (box && !cache.usage[filters.range]) regionLoading(box, '正在读取日志');
1920
+ // 币种与账号都来自 state:没有它,「用量」只能印成裸数字。
1921
+ await Promise.all([loadState(force), loadUsage(force), loadLogStats(force)]);
1922
+ renderLogs();
1923
+ }
1924
+
1925
+ /** loadLogStats 取站点日志页顶部的 用量 / RPM / TPM(/api/log/self/stat)。 */
1926
+ async function loadLogStats(force = false) {
1927
+ const range = filters.range;
1928
+ if (!force && cache.logStats[range]) return cache.logStats[range];
1430
1929
  try {
1431
- const data = await api.logs(account);
1432
- // 契约写的是「同 rows 的扁平列表」,可能直接是数组,也可能包在 rows 里
1433
- const rows = Array.isArray(data) ? data : (data.rows || data.logs || []);
1434
- cache.logs[account] = rows;
1435
- clearBanner('logs');
1436
- renderFlow();
1437
- return rows;
1930
+ cache.logStats[range] = await api.logStats(range);
1438
1931
  } catch (err) {
1439
- const msg = describeError(err);
1440
- banner('error', `读取账号流水失败:${msg}`, { key: 'logs' });
1441
- regionError($('#flow-body'), `流水没读到:${msg}`, () => loadFlow(true));
1442
- return null;
1443
- } finally {
1444
- loading.logs = false;
1932
+ cache.logStats[range] = { ok: false, available: false, reason: describeError(err) };
1445
1933
  }
1934
+ return cache.logStats[range];
1446
1935
  }
1447
1936
 
1448
- function renderFlow() {
1449
- const box = $('#flow-body');
1450
- const count = $('#flow-count');
1937
+ function renderLogs() {
1938
+ const box = $('#logs-body');
1939
+ const chips = $('#logs-chips');
1940
+ const tools = $('#logs-tools');
1941
+ const pager = $('#logs-pager');
1451
1942
  if (!box) return;
1943
+ if (cache.usageErrors[filters.range]) {
1944
+ regionError(box, `日志没读到:${cache.usageErrors[filters.range]}`, () => loadLogs(true));
1945
+ chips?.replaceChildren();
1946
+ pager?.replaceChildren();
1947
+ return;
1948
+ }
1452
1949
 
1453
- const account = filters.account;
1454
- const source = account ? cache.logs[account] : (cache.usage[filters.range] && cache.usage[filters.range].rows);
1950
+ const rows = logRows();
1951
+ if (rows === null) { regionLoading(box, '正在读取日志'); return; }
1952
+ fillLogFilters((cache.usage[filters.range] && cache.usage[filters.range].rows) || []);
1953
+
1954
+ // 统计条:和站点一致——用量 / RPM / TPM。数据取自 /api/log/self/stat,
1955
+ // 不是本地这 100 行日志(那只能算部分用量)。
1956
+ const stat = cache.logStats[filters.range] || null;
1957
+ if (chips) {
1958
+ chips.replaceChildren(
1959
+ h('span', { class: 'lg-stat' }, h('i', { class: 'lg-stat-bar sky' }),
1960
+ h('span', { class: 'lg-stat-k', text: '用量' }),
1961
+ h('span', { class: 'lg-stat-v', text: stat && stat.available ? statMoney(stat.quota) : '—' })),
1962
+ h('span', { class: 'lg-stat' }, h('i', { class: 'lg-stat-bar rose' }),
1963
+ h('span', { class: 'lg-stat-k', text: 'RPM' }),
1964
+ h('span', { class: 'lg-stat-v', text: stat && stat.available ? Number(stat.rpm || 0).toFixed(2) : '—' })),
1965
+ h('span', { class: 'lg-stat' }, h('i', { class: 'lg-stat-bar slate' }),
1966
+ h('span', { class: 'lg-stat-k', text: 'TPM' }),
1967
+ h('span', { class: 'lg-stat-v', text: stat && stat.available ? fmtWan(stat.tpm || 0) : '—' })),
1968
+ );
1969
+ chips.title = stat && !stat.available && stat.reason ? stat.reason : '';
1970
+ }
1971
+ // 时间范围胶囊:显示真实窗口起止,和站点一样是 start ~ end
1972
+ const win = cache.usage[filters.range];
1973
+ const rangeText = $('#logs-range-text');
1974
+ if (rangeText && win && Number.isFinite(win.start) && Number.isFinite(win.end)) {
1975
+ rangeText.textContent = `${fmtFull(win.start)} ~ ${fmtFull(win.end)}`;
1976
+ }
1455
1977
 
1456
- if (source === undefined) {
1457
- regionLoading(box, account ? '正在读取该账号的流水' : '正在读取用量流水');
1458
- if (count) count.textContent = '';
1459
- return;
1978
+ // 工具条右侧动作:眼睛 / 重置 / 搜索 / 查看(列显隐)
1979
+ if (tools) {
1980
+ tools.replaceChildren(
1981
+ h('button', {
1982
+ class: `btn ghost lg-icon-btn${logView.private ? ' on' : ''}`, type: 'button',
1983
+ title: logView.private ? '显示敏感信息' : '隐藏敏感信息',
1984
+ 'aria-pressed': String(logView.private),
1985
+ onclick: () => { logView.private = !logView.private; renderLogs(); },
1986
+ }, eyeIcon(logView.private)),
1987
+ h('button', { class: 'btn primary', type: 'button', onclick: () => loadLogs(true) }, '搜索'),
1988
+ h('a', {
1989
+ class: 'btn ghost', href: 'https://newapi.dragon3api.com/usage-logs/common',
1990
+ target: '_blank', rel: 'noopener noreferrer', title: '在 DragonAPI 官网查看完整日志',
1991
+ }, '在官网打开'),
1992
+ h('div', { class: 'menu' },
1993
+ h('button', {
1994
+ class: 'btn ghost menu-trigger', type: 'button', id: 'logs-view-btn',
1995
+ 'aria-haspopup': 'listbox', 'aria-expanded': 'false',
1996
+ onclick: (ev) => {
1997
+ ev.stopPropagation();
1998
+ logView.colsOpen = !logView.colsOpen;
1999
+ const pop = $('#logs-view-pop');
2000
+ if (!pop) return;
2001
+ pop.hidden = !logView.colsOpen;
2002
+ ev.currentTarget.setAttribute('aria-expanded', String(logView.colsOpen));
2003
+ },
2004
+ }, '查看', h('span', { class: 'menu-caret', 'aria-hidden': 'true', text: '▾' })),
2005
+ h('div', { class: 'menu-pop', id: 'logs-view-pop', role: 'listbox', 'aria-label': '选择显示列', hidden: !logView.colsOpen },
2006
+ LOG_COLS.map((c) => h('button', {
2007
+ type: 'button', role: 'option', 'data-col': c.id,
2008
+ 'aria-selected': String(logView.cols.has(c.id)),
2009
+ onclick: (ev) => {
2010
+ ev.stopPropagation();
2011
+ if (logView.cols.has(c.id)) { if (logView.cols.size > 1) logView.cols.delete(c.id); }
2012
+ else logView.cols.add(c.id);
2013
+ renderLogs();
2014
+ },
2015
+ }, c.label))),
2016
+ ),
2017
+ );
2018
+ }
2019
+
2020
+ // 分页
2021
+ const totalCount = Number(cache.usage[filters.range]?.total) || rows.length;
2022
+ const pageCount = Math.max(1, Math.ceil(rows.length / logView.pageSize));
2023
+ if (logView.page > pageCount) logView.page = pageCount;
2024
+ if (pager) {
2025
+ const pageBtn = (label, title, disabled, fn) => h('button', {
2026
+ class: 'btn ghost lg-page-btn', type: 'button', title, disabled: disabled || null,
2027
+ onclick: () => { fn(); renderLogs(); },
2028
+ }, label);
2029
+ const sizeSel = h('select', {
2030
+ class: 'logs-select lg-pagesize', 'aria-label': '每页行数',
2031
+ onchange: (ev) => { logView.pageSize = Number(ev.currentTarget.value) || 20; logView.page = 1; renderLogs(); },
2032
+ }, [10, 20, 30, 50, 100].map((v) => h('option', { value: String(v), text: String(v) + ' 行/页', selected: v === logView.pageSize || null })));
2033
+ pager.replaceChildren(
2034
+ h('span', { class: 'lg-total', text: `总计 ${fmtInt(totalCount)}` }),
2035
+ sizeSel,
2036
+ pageBtn('«', '第一页', logView.page <= 1, () => { logView.page = 1 }),
2037
+ pageBtn('‹', '上一页', logView.page <= 1, () => { logView.page -= 1 }),
2038
+ h('span', { class: 'lg-page-pill', text: String(logView.page) }),
2039
+ pageBtn('›', '下一页', logView.page >= pageCount, () => { logView.page += 1 }),
2040
+ pageBtn('»', '最后一页', logView.page >= pageCount, () => { logView.page = pageCount }),
2041
+ );
2042
+ enhanceSelect(sizeSel, 'sel-sm');
2043
+ }
2044
+
2045
+ const slice = rows.slice((logView.page - 1) * logView.pageSize, logView.page * logView.pageSize);
2046
+ const cols = LOG_COLS.filter((c) => logView.cols.has(c.id));
2047
+ const table = h('div', {
2048
+ class: 'lg-table', role: 'table', 'aria-label': '使用日志明细',
2049
+ style: `--lg-cols:${cols.map((c) => c.w).join(' ')}`,
2050
+ },
2051
+ h('div', { class: 'lg-row lg-head', role: 'row' },
2052
+ ...cols.map((c) => h('span', { role: 'columnheader', text: c.label }))),
2053
+ ...slice.map((r) => {
2054
+ const cells = logCells(r);
2055
+ return h('div', { class: 'lg-row', role: 'row' }, cols.map((c) => cells[c.id]));
2056
+ }),
2057
+ );
2058
+
2059
+ box.replaceChildren(
2060
+ slice.length
2061
+ ? table
2062
+ : h('p', { class: 'lg-empty', text: logFilter.model || logFilter.group || logFilter.kind || logFilter.tokenName ? '没有符合筛选的日志。' : '这个区间还没有日志。' }),
2063
+ );
2064
+ }
2065
+
2066
+ // ── 数据看板:照站点 /dashboard/models ────────────────────
2067
+
2068
+ const DASH_COLORS = ['#1664FF', '#1AC6FF', '#FF8A00', '#3CC780', '#7442D4', '#FFC400', '#304D77', '#B48DEB', '#009488', '#FF7DDA'];
2069
+
2070
+ const dashView = {
2071
+ days: 1,
2072
+ granularity: 'hour',
2073
+ usageKind: 'area',
2074
+ callsView: 'trend',
2075
+ hidden: new Set(),
2076
+ };
2077
+
2078
+ const dashIconPaths = {
2079
+ hash: ['M4 9h16', 'M4 15h16', 'M10 3v18', 'M14 3v18'],
2080
+ coins: ['M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18', 'M12 7v10', 'M9.5 9.5h4a1.5 1.5 0 0 1 0 3h-3a1.5 1.5 0 0 0 0 3h4'],
2081
+ layers: ['M12 3 3 8l9 5 9-5-9-5', 'M3 12l9 5 9-5', 'M3 16l9 5 9-5'],
2082
+ download: ['M12 3v12', 'M7 11l5 5 5-5', 'M4 20h16'],
2083
+ upload: ['M12 21V9', 'M7 13l5-5 5 5', 'M4 4h16'],
2084
+ activity: ['M3 12h4l3-7 4 14 3-7h4'],
2085
+ zap: ['M13 2 4 14h6l-1 8 9-12h-6z'],
2086
+ };
2087
+ const dashIcon = (name) => lineIcon(dashIconPaths[name] || dashIconPaths.hash, 16);
2088
+
2089
+ function fmtWan(n) {
2090
+ const v = Number(n) || 0;
2091
+ if (Math.abs(v) >= 1e8) return `${(v / 1e8).toFixed(1).replace(/\.0$/, '')}亿`;
2092
+ if (Math.abs(v) >= 1e4) return `${(v / 1e4).toFixed(1)}万`;
2093
+ return fmtInt(v);
2094
+ }
2095
+
2096
+ function dashCurrency() {
2097
+ const cur = (cache.state && cache.state.currency) || {};
2098
+ const per = Number(cur.per) > 0 ? Number(cur.per) : 1;
2099
+ const rate = cur.display && Number(cur.rate) > 0 ? Number(cur.rate) : 1;
2100
+ return { symbol: cur.symbol || '$', per, rate };
2101
+ }
2102
+
2103
+ function dashMoney(raw, digits = 2) {
2104
+ const { symbol, per, rate } = dashCurrency();
2105
+ return `${symbol}${((Number(raw) || 0) / per * rate).toFixed(digits)}`;
2106
+ }
2107
+
2108
+ function dashMoneyValue(raw) {
2109
+ const { per, rate } = dashCurrency();
2110
+ return (Number(raw) || 0) / per * rate;
2111
+ }
2112
+
2113
+ function dashTimeLabel(at, gran) {
2114
+ const d = new Date(at);
2115
+ const p = (x) => String(x).padStart(2, '0');
2116
+ if (gran === 'hour') return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:00`;
2117
+ return `${p(d.getMonth() + 1)}-${p(d.getDate())}`;
2118
+ }
2119
+
2120
+ function dashTickLabel(at, gran) {
2121
+ const d = new Date(at);
2122
+ const p = (x) => String(x).padStart(2, '0');
2123
+ return gran === 'hour' ? `${p(d.getHours())}:00` : `${p(d.getMonth() + 1)}-${p(d.getDate())}`;
2124
+ }
2125
+
2126
+ function niceStep(max) {
2127
+ const raw = max / 4;
2128
+ const pow = Math.pow(10, Math.floor(Math.log10(raw || 1)));
2129
+ const n = raw / pow;
2130
+ const step = n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10;
2131
+ return step * pow;
2132
+ }
2133
+
2134
+ /** smoothPath 用 Catmull-Rom 转三次贝塞尔,画出站点那种平滑面积线。 */
2135
+ function smoothPath(pts) {
2136
+ if (!pts.length) return '';
2137
+ if (pts.length === 1) return `M${pts[0][0]},${pts[0][1]}`;
2138
+ let d = `M${pts[0][0]},${pts[0][1]}`;
2139
+ for (let i = 0; i < pts.length - 1; i++) {
2140
+ const p0 = pts[i - 1] || pts[i];
2141
+ const p1 = pts[i];
2142
+ const p2 = pts[i + 1];
2143
+ const p3 = pts[i + 2] || p2;
2144
+ const c1x = p1[0] + (p2[0] - p0[0]) / 6;
2145
+ const c1y = p1[1] + (p2[1] - p0[1]) / 6;
2146
+ const c2x = p2[0] - (p3[0] - p1[0]) / 6;
2147
+ const c2y = p2[1] - (p3[1] - p1[1]) / 6;
2148
+ d += ` C${c1x},${c1y} ${c2x},${c2y} ${p2[0]},${p2[1]}`;
1460
2149
  }
2150
+ return d;
2151
+ }
2152
+
2153
+ function svgEl(tag, attrs = {}) {
2154
+ const el = document.createElementNS('http://www.w3.org/2000/svg', tag);
2155
+ for (const [k, v] of Object.entries(attrs)) if (v != null) el.setAttribute(k, String(v));
2156
+ return el;
2157
+ }
2158
+
2159
+ /** dashChart 通用 SVG 图表:网格 + 面积/柱状 + 悬浮提示。 */
2160
+ function dashChart(box, { buckets, series, kind, formatY, formatTip, height = 260 }) {
2161
+ box.replaceChildren();
2162
+ if (!buckets.length) { box.append(h('p', { class: 'empty', text: '这个区间没有数据。' })); return; }
2163
+ const W = 1200, H = height, padL = 52, padR = 18, padT = 16, padB = 30;
2164
+ const plotW = W - padL - padR, plotH = H - padT - padB;
2165
+ let max = 0;
2166
+ for (const s of series) for (const v of s.values) max = Math.max(max, Number(v) || 0);
2167
+ max = max > 0 ? max : 1;
2168
+ const step = niceStep(max);
2169
+ const top = Math.max(step, Math.ceil(max / step) * step);
2170
+ const yOf = (v) => padT + plotH - (Math.min(v, top) / top) * plotH;
2171
+ const xOf = (i) => padL + (buckets.length === 1 ? plotW / 2 : (i / (buckets.length - 1)) * plotW);
2172
+ const svg = svgEl('svg', { viewBox: `0 0 ${W} ${H}`, class: 'dash-svg', role: 'img', 'aria-label': '趋势图' });
2173
+
2174
+ for (let i = 0; i <= 4; i++) {
2175
+ const v = (top * i) / 4;
2176
+ const yy = yOf(v);
2177
+ svg.append(svgEl('line', { x1: padL, x2: W - padR, y1: yy, y2: yy, class: 'dash-grid' }));
2178
+ const t = svgEl('text', { x: padL - 8, y: yy + 3, class: 'dash-axis', 'text-anchor': 'end' });
2179
+ t.textContent = formatY(v);
2180
+ svg.append(t);
2181
+ }
2182
+ const tickEvery = Math.max(1, Math.ceil(buckets.length / 6));
2183
+ buckets.forEach((b, i) => {
2184
+ if (i % tickEvery !== 0 && i !== buckets.length - 1) return;
2185
+ const t = svgEl('text', { x: xOf(i), y: H - 8, class: 'dash-axis', 'text-anchor': 'middle' });
2186
+ t.textContent = dashTickLabel(b.at, dashView.granularity);
2187
+ svg.append(t);
2188
+ });
1461
2189
 
1462
- const rows = (source || []).slice(0, 200);
1463
- if (count) {
1464
- count.textContent = account
1465
- ? `${fmtInt(rows.length)} 行 · 仅该账号`
1466
- : `${fmtInt(rows.length)} 行 · 多账号合并`;
1467
- }
1468
-
1469
- const tableRows = rows.map((r) => [
1470
- { text: r.atText || fmtAt(r.at), cls: 'mono' },
1471
- { text: r.model || '—', cls: 'mono' },
1472
- { text: r.group || '—', cls: 'mono' },
1473
- { text: r.tokenName || '—', cls: 'mono' },
1474
- { text: fmtInt(r.input), cls: 'num' },
1475
- { text: fmtInt(r.output), cls: 'num' },
1476
- { text: fmtInt(r.cache), cls: 'num' },
1477
- { text: r.cost || '—', cls: 'num', title: Number.isFinite(r.costRaw) ? `${fmtInt(r.costRaw)} quota` : null },
1478
- {
1479
- text: r.detail || (r.kind ? r.kind : '—'),
1480
- cls: 'col-desc',
1481
- title: [
1482
- r.detail || '',
1483
- r.kind ? `类型 ${r.kind}` : '',
1484
- Number.isFinite(r.tps) ? `TPS ${r.tps}` : '',
1485
- Number.isFinite(r.ttft) ? `TTFT ${r.ttft}s` : '',
1486
- Number.isFinite(r.dur) ? `耗时 ${r.dur}s` : '',
1487
- r.isStream ? '流式' : '',
1488
- ].filter(Boolean).join('\n'),
2190
+ if (kind === 'bar') {
2191
+ const groupW = plotW / Math.max(1, buckets.length);
2192
+ const barW = Math.max(1, (groupW * 0.68) / Math.max(1, series.length));
2193
+ series.forEach((s, si) => {
2194
+ s.values.forEach((v, i) => {
2195
+ const x = padL + i * groupW + (groupW - barW * series.length) / 2 + si * barW;
2196
+ const y = yOf(Number(v) || 0);
2197
+ svg.append(svgEl('rect', {
2198
+ x, y, width: Math.max(1, barW - 1), height: Math.max(0, padT + plotH - y),
2199
+ rx: 2, fill: s.color, class: 'dash-bar',
2200
+ }));
2201
+ });
2202
+ });
2203
+ } else {
2204
+ series.forEach((s) => {
2205
+ const pts = s.values.map((v, i) => [xOf(i), yOf(Number(v) || 0)]);
2206
+ const line = smoothPath(pts);
2207
+ if (!line) return;
2208
+ const area = `${line} L${xOf(pts.length - 1)},${padT + plotH} L${xOf(0)},${padT + plotH} Z`;
2209
+ svg.append(svgEl('path', { d: area, fill: s.color, class: 'dash-area', opacity: 0.14 }));
2210
+ svg.append(svgEl('path', { d: line, fill: 'none', stroke: s.color, 'stroke-width': 2, 'stroke-linecap': 'round', class: 'dash-line' }));
2211
+ });
2212
+ }
2213
+
2214
+ const hover = svgEl('line', { y1: padT, y2: padT + plotH, class: 'dash-hover-line', opacity: 0 });
2215
+ svg.append(hover);
2216
+ const tip = h('div', { class: 'dash-tip', hidden: true });
2217
+ box.append(svg, tip);
2218
+
2219
+ const move = (ev) => {
2220
+ const rect = svg.getBoundingClientRect();
2221
+ if (!rect.width) return;
2222
+ const ratio = (ev.clientX - rect.left) / rect.width * W;
2223
+ const idx = Math.max(0, Math.min(buckets.length - 1, Math.round((ratio - padL) / plotW * (buckets.length - 1))));
2224
+ const x = xOf(idx);
2225
+ hover.setAttribute('x1', x); hover.setAttribute('x2', x); hover.setAttribute('opacity', '1');
2226
+ const b = buckets[idx];
2227
+ const rows = series.map((s) => h('div', { class: 'dash-tip-row' },
2228
+ h('i', { class: 'dash-tip-dot', style: `background:${s.color}` }),
2229
+ h('span', { class: 'dash-tip-k', text: s.name }),
2230
+ h('b', { class: 'dash-tip-v', text: formatTip(s.values[idx]) })));
2231
+ tip.replaceChildren(h('div', { class: 'dash-tip-time', text: dashTimeLabel(b.at, dashView.granularity) }), ...rows);
2232
+ tip.hidden = false;
2233
+ const left = Math.min(box.clientWidth - 180, Math.max(0, (x / W) * rect.width + 12));
2234
+ tip.style.left = `${left}px`;
2235
+ };
2236
+ svg.addEventListener('mousemove', move);
2237
+ svg.addEventListener('mouseleave', () => { hover.setAttribute('opacity', '0'); tip.hidden = true; });
2238
+ }
2239
+
2240
+ /** renderDashLegend 可点击的图例:点模型名隐藏/显示该系列。 */
2241
+ function renderDashLegend(box, series) {
2242
+ if (!box) return;
2243
+ box.replaceChildren(...series.map((s) => h('button', {
2244
+ class: `dash-legend-item${dashView.hidden.has(s.model) ? ' off' : ''}`,
2245
+ type: 'button', 'aria-pressed': String(!dashView.hidden.has(s.model)),
2246
+ onclick: () => {
2247
+ if (dashView.hidden.has(s.model)) dashView.hidden.delete(s.model);
2248
+ else dashView.hidden.add(s.model);
2249
+ renderDashboard();
1489
2250
  },
1490
- ]);
2251
+ }, h('i', { class: 'dash-legend-dot', style: `background:${s.color}` }), s.model)));
2252
+ }
1491
2253
 
1492
- box.replaceChildren(tableEl(
1493
- ['时间', '模型', '分组', '令牌名', { label: '输入', cls: 'num' }, { label: '输出', cls: 'num' },
1494
- { label: '缓存', cls: 'num' }, { label: '费用', cls: 'num' }, '详情'],
1495
- tableRows,
1496
- { empty: account ? '这个账号还没有用量记录。' : '这个区间还没有用量记录。' },
1497
- ));
2254
+ function renderDashboard() {
2255
+ const cards = $('#dash-cards');
2256
+ if (!cards) return;
2257
+ const key = `${dashView.days}:${dashView.granularity}`;
2258
+ const data = cache.dashboard[key];
2259
+ if (!data) { cards.replaceChildren(h('p', { class: 'loading', text: '正在读取数据看板…' })); return; }
2260
+ if (!data.available) {
2261
+ cards.replaceChildren(h('p', { class: 'hint', text: data.reason || '数据看板暂时不可用。' }));
2262
+ $('#dash-usage-chart')?.replaceChildren();
2263
+ $('#dash-usage-legend')?.replaceChildren();
2264
+ $('#dash-calls-chart')?.replaceChildren();
2265
+ return;
2266
+ }
2267
+ const t = data.totals;
2268
+ const items = [
2269
+ { label: '总数', desc: '统计计数', icon: 'hash', tone: 'info', value: fmtInt(t.count) },
2270
+ { label: '总额度', desc: '统计配额', icon: 'coins', tone: 'success', value: dashMoney(t.quota, 2) },
2271
+ { label: '总 TOKEN 数', desc: '统计 Token 数', icon: 'layers', tone: 'chart-4', value: fmtWan(t.tokens) },
2272
+ { label: '缓存读取', desc: '统计 Token 数', icon: 'download', tone: 'chart-3', value: fmtWan(t.cacheRead) },
2273
+ { label: '缓存写入', desc: '统计 Token 数', icon: 'upload', tone: 'chart-5', value: fmtWan(t.cacheWrite) },
2274
+ ];
2275
+ cards.replaceChildren(...items.map((c) => h('div', { class: `dash-stat tone-${c.tone}` },
2276
+ h('div', { class: 'dash-stat-top' },
2277
+ h('span', { class: 'dash-stat-ico', 'aria-hidden': 'true' }, dashIcon(c.icon)),
2278
+ h('span', { class: 'dash-stat-label', text: c.label })),
2279
+ h('div', { class: 'dash-stat-value', text: c.value }),
2280
+ h('div', { class: 'dash-stat-desc', text: c.desc }))));
2281
+
2282
+ const sub = $('#dash-usage-sub');
2283
+ if (sub) sub.textContent = `总计:${dashMoney(t.quota, 2)}`;
2284
+ const models = data.models.map((m, i) => ({ ...m, color: DASH_COLORS[i % DASH_COLORS.length] }));
2285
+ const visible = models.filter((m) => !dashView.hidden.has(m.model));
2286
+ const usageSeries = visible.map((m) => ({
2287
+ name: m.model, model: m.model, color: m.color,
2288
+ values: data.buckets.map((b) => dashMoneyValue(b.values[m.model] || 0)),
2289
+ }));
2290
+ const usageBox = $('#dash-usage-chart');
2291
+ if (usageBox) {
2292
+ const { symbol } = dashCurrency();
2293
+ dashChart(usageBox, {
2294
+ buckets: data.buckets, series: usageSeries, kind: dashView.usageKind,
2295
+ formatY: (v) => (v >= 1 ? v.toFixed(0) : v.toFixed(2)),
2296
+ formatTip: (v) => `${symbol}${(Number(v) || 0).toFixed(2)}`,
2297
+ });
2298
+ renderDashLegend($('#dash-usage-legend'), models);
2299
+ }
2300
+
2301
+ const callsSub = $('#dash-calls-sub');
2302
+ if (callsSub) callsSub.textContent = `总计:${fmtInt(t.count)}`;
2303
+ const callsBox = $('#dash-calls-chart');
2304
+ if (!callsBox) return;
2305
+ if (dashView.callsView === 'trend') {
2306
+ dashChart(callsBox, {
2307
+ buckets: data.buckets,
2308
+ series: [{ name: '调用次数', color: DASH_COLORS[0], values: data.buckets.map((b) => b.count) }],
2309
+ kind: 'area', formatY: (v) => fmtInt(v), formatTip: (v) => fmtInt(v),
2310
+ });
2311
+ } else if (dashView.callsView === 'proportion') {
2312
+ const total = Math.max(1, t.count);
2313
+ const rows = data.models.map((m, i) => h('div', { class: 'dash-prop-row' },
2314
+ h('span', { class: 'dash-prop-name', title: m.model, text: m.model }),
2315
+ h('span', { class: 'dash-prop-track' },
2316
+ h('i', { class: 'dash-prop-fill', style: `width:${(m.count / total * 100).toFixed(1)}%;background:${DASH_COLORS[i % DASH_COLORS.length]}` })),
2317
+ h('span', { class: 'dash-prop-val', text: `${fmtInt(m.count)}(${(m.count / total * 100).toFixed(1)}%)` })));
2318
+ callsBox.replaceChildren(h('div', { class: 'dash-props' }, ...(rows.length ? rows : [h('p', { class: 'empty', text: '这个区间没有调用。' })])));
2319
+ } else {
2320
+ const head = ['排名', '模型', '调用次数', 'Token', '费用'];
2321
+ const rows = data.models.map((m, i) => [String(i + 1), m.model, fmtInt(m.count), fmtWan(m.tokens), dashMoney(m.quota, 2)]);
2322
+ callsBox.replaceChildren(tableEl(head, rows, { empty: '这个区间没有调用记录', tableClass: 'data-table dash-table' }));
2323
+ }
1498
2324
  }
1499
2325
 
1500
- function bindWalletControls() {
1501
- for (const btn of $$('.segmented [data-range]')) {
1502
- btn.addEventListener('click', () => {
1503
- const range = btn.dataset.range;
1504
- if (filters.range === range) return;
1505
- filters.range = range;
1506
- for (const other of $$('.segmented [data-range]')) {
1507
- other.setAttribute('aria-pressed', String(other === btn));
1508
- }
1509
- loadUsage(false).then(renderFlow);
2326
+ async function loadDashboard(force = false) {
2327
+ const key = `${dashView.days}:${dashView.granularity}`;
2328
+ if (!force && cache.dashboard[key]) { renderDashboard(); return cache.dashboard[key]; }
2329
+ const cards = $('#dash-cards');
2330
+ if (cards) cards.replaceChildren(h('p', { class: 'loading', text: '正在读取数据看板…' }));
2331
+ try {
2332
+ cache.dashboard[key] = await api.dashboard(dashView.days, dashView.granularity);
2333
+ } catch (err) {
2334
+ cache.dashboard[key] = { ok: false, available: false, reason: describeError(err) };
2335
+ }
2336
+ renderDashboard();
2337
+ return cache.dashboard[key];
2338
+ }
2339
+
2340
+ function syncDashControls() {
2341
+ for (const b of $$('#dash-days [data-dash-days]')) b.setAttribute('aria-pressed', String(Number(b.dataset.dashDays) === dashView.days));
2342
+ for (const b of $$('#dash-gran [data-dash-gran]')) b.setAttribute('aria-pressed', String(b.dataset.dashGran === dashView.granularity));
2343
+ for (const b of $$('#dash-usage-kind [data-usage-kind]')) b.setAttribute('aria-pressed', String(b.dataset.usageKind === dashView.usageKind));
2344
+ for (const b of $$('#dash-calls-view [data-calls-view]')) b.setAttribute('aria-pressed', String(b.dataset.callsView === dashView.callsView));
2345
+ }
2346
+
2347
+ function bindDashControls() {
2348
+ for (const b of $$('#dash-days [data-dash-days]')) {
2349
+ b.addEventListener('click', () => { dashView.days = Number(b.dataset.dashDays); syncDashControls(); loadDashboard(true); });
2350
+ }
2351
+ for (const b of $$('#dash-gran [data-dash-gran]')) {
2352
+ b.addEventListener('click', () => { dashView.granularity = b.dataset.dashGran; dashView.hidden.clear(); syncDashControls(); loadDashboard(true); });
2353
+ }
2354
+ for (const b of $$('#dash-usage-kind [data-usage-kind]')) {
2355
+ b.addEventListener('click', () => { dashView.usageKind = b.dataset.usageKind; syncDashControls(); renderDashboard(); });
2356
+ }
2357
+ for (const b of $$('#dash-calls-view [data-calls-view]')) {
2358
+ b.addEventListener('click', () => { dashView.callsView = b.dataset.callsView; syncDashControls(); renderDashboard(); });
2359
+ }
2360
+ syncDashControls();
2361
+ }
2362
+
2363
+ /** vendorOfModel 日志行只有模型名,按系列反推厂商,用来给模型胶囊挂图标。 */
2364
+ function vendorOfModel(model) {
2365
+ const n = String(model || '');
2366
+ const rules = [
2367
+ [/gpt|^o\d|codex|dall-e|sora|text-embedding/i, 'OpenAI'],
2368
+ [/claude/i, 'Anthropic'],
2369
+ [/gemini|imagen|nano-?banana/i, 'Google'],
2370
+ [/deepseek/i, 'DeepSeek'],
2371
+ [/kimi|moonshot/i, 'Moonshot'],
2372
+ [/qwen|qwq|wanx|通义/i, '阿里云'],
2373
+ [/glm/i, '智谱'],
2374
+ [/grok/i, 'xAI'],
2375
+ [/minimax|hailuo/i, 'MiniMax'],
2376
+ [/seedance|doubao/i, '字节跳动'],
2377
+ [/jimeng/i, '即梦'],
2378
+ [/ideogram/i, 'Ideogram'],
2379
+ ];
2380
+ for (const [re, vendor] of rules) if (re.test(n)) return vendor;
2381
+ return '';
2382
+ }
2383
+
2384
+ /** lineIcon 细线图标(钱包 / 订阅),颜色跟随父级 currentColor。 */
2385
+ function lineIcon(paths, size = 12) {
2386
+ const ns = 'http://www.w3.org/2000/svg';
2387
+ const svg = document.createElementNS(ns, 'svg');
2388
+ svg.setAttribute('viewBox', '0 0 24 24');
2389
+ svg.setAttribute('width', String(size));
2390
+ svg.setAttribute('height', String(size));
2391
+ svg.setAttribute('fill', 'none');
2392
+ svg.setAttribute('stroke', 'currentColor');
2393
+ svg.setAttribute('stroke-width', '1.7');
2394
+ svg.setAttribute('stroke-linecap', 'round');
2395
+ svg.setAttribute('stroke-linejoin', 'round');
2396
+ svg.setAttribute('aria-hidden', 'true');
2397
+ for (const d of paths) {
2398
+ const p = document.createElementNS(ns, 'path');
2399
+ p.setAttribute('d', d);
2400
+ svg.appendChild(p);
2401
+ }
2402
+ return svg;
2403
+ }
2404
+
2405
+ /** 钱包 / 订阅两种扣费来源的图标:额度口径不同,不能长一个样。 */
2406
+ const walletGlyph = () => lineIcon([
2407
+ 'M3 7a2 2 0 0 1 2-2h13a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z',
2408
+ 'M3 10h18',
2409
+ 'M16.5 14.5h.01',
2410
+ ]);
2411
+ const subscriptionGlyph = () => lineIcon([
2412
+ 'M3 9a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v1a2 2 0 0 0 0 4v1a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-1a2 2 0 0 0 0-4z',
2413
+ 'M9 7v10',
2414
+ ]);
2415
+
2416
+ /** statMoney 站点金额格式:≥1 保留 4 位,小额 6 位(官网日志页同一套)。 */
2417
+ function statMoney(raw) {
2418
+ const n = Number(raw);
2419
+ if (!Number.isFinite(n)) return '—';
2420
+ const cur = (cache.state && cache.state.currency) || {};
2421
+ const per = Number(cur.per) > 0 ? Number(cur.per) : 1;
2422
+ const base = n / per;
2423
+ const value = cur.display && Number(cur.rate) > 0 ? base * Number(cur.rate) : base;
2424
+ return `${cur.symbol || '$'}${value.toFixed(value >= 1 ? 4 : 6)}`;
2425
+ }
2426
+
2427
+ /** logCostText 一行日志的费用,和统计条同一套格式。 */
2428
+ function logCostText(raw) {
2429
+ return Number.isFinite(Number(raw)) ? statMoney(raw) : '';
2430
+ }
2431
+
2432
+ /** fmtFull 时间戳 → `YYYY-MM-DD HH:mm:ss`(时间范围胶囊用)。 */
2433
+ function fmtFull(ms) {
2434
+ const n = Number(ms);
2435
+ if (!Number.isFinite(n) || n <= 0) return '—';
2436
+ const d = new Date(n);
2437
+ const p = (x) => String(x).padStart(2, '0');
2438
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
2439
+ }
2440
+
2441
+ /** logCells 一行各列的节点(「查看」菜单决定渲染哪几列)。 */
2442
+ function logCells(r) {
2443
+ const dash = (cls = '') => h('span', { class: `lg-dash ${cls}`.trim(), 'aria-hidden': 'true' }, '—');
2444
+ const hasMap = Boolean(r.upModel || r.respModel);
2445
+ const mask = (v) => (logView.private ? '••••' : (v || '—'));
2446
+ const vendor = vendorOfModel(r.model);
2447
+ const costText = logCostText(r.costRaw);
2448
+ const bySubscription = r.billingSource === 'subscription';
2449
+ const paidBy = bySubscription ? '订阅扣费' : r.billingSource === 'wallet' ? '钱包扣费' : '扣费来源未标注';
2450
+ const ratio = Number.isFinite(Number(r.groupRatio)) ? `${Number(r.groupRatio)}×` : '';
2451
+ // 「none」不是思考强度,是没开;摆一个金色 none 反而像有档位
2452
+ const effort = r.effort && !/^(none|无|default)$/i.test(String(r.effort)) ? r.effort : '';
2453
+
2454
+ return {
2455
+ // 时间 + 类型
2456
+ time: h('span', { class: 'lg-cell-stack', role: 'cell' },
2457
+ h('span', { class: 'lg-time-str', text: r.atText || fmtAt(r.at) }),
2458
+ h('span', { class: 'lg-meta-row' },
2459
+ h('span', { class: `lg-tag${r.kind === '消耗' ? ' ok' : ''}`, text: r.kind || '消费' }))),
2460
+
2461
+ // 令牌胶囊 + 分组/倍率(官网把令牌与分组叠在一列)
2462
+ key: h('span', { class: 'lg-cell-stack', role: 'cell' },
2463
+ h('button', {
2464
+ class: 'lg-pill lg-copyable', type: 'button', title: '点击复制令牌名称',
2465
+ onclick: (ev) => copyText(r.tokenName || '', ev.currentTarget),
2466
+ },
2467
+ h('span', { class: 'lg-key', 'aria-hidden': 'true', text: '⚿' }),
2468
+ h('span', { text: mask(r.tokenName || '') })),
2469
+ h('span', { class: 'lg-group-meta' },
2470
+ h('span', { class: 'lg-group-name', title: r.group || '', text: r.group || '—' }),
2471
+ ratio ? h('span', { class: 'lg-group-ratio', text: ratio }) : null)),
2472
+
2473
+ // 模型胶囊(厂商图标)+ 思考强度(金色无包边)+ 映射标记
2474
+ model: h('span', { class: 'lg-cell-stack', role: 'cell' },
2475
+ h('span', { class: 'lg-model-line' },
2476
+ h('span', {
2477
+ class: 'lg-model-pill',
2478
+ title: hasMap
2479
+ ? [`请求模型 ${r.model}`, r.upModel ? `上游 ${r.upModel}` : '', r.respModel ? `响应 ${r.respModel}` : ''].filter(Boolean).join('\n')
2480
+ : r.model,
2481
+ },
2482
+ vendor ? vendorBadge(vendor, { size: 12 }) : null,
2483
+ h('span', { class: 'lg-model', text: r.model || '—' })),
2484
+ effort ? h('span', { class: 'lg-effort', text: effort }) : null,
2485
+ hasMap ? h('span', { class: 'lg-map-mark', title: '查看模型映射', 'aria-hidden': 'true' }, '⇄') : null)),
2486
+
2487
+ // 费用:钱包 / 订阅各用各的图标,徽章照官网(中圆角、muted 底、foreground 字)
2488
+ cost: h('span', { class: 'lg-cell-stack', role: 'cell' },
2489
+ h('span', { class: 'lg-cost-pill', title: paidBy },
2490
+ bySubscription ? subscriptionGlyph() : walletGlyph(),
2491
+ h('span', { text: costText ? mask(costText) : '—' }))),
2492
+
2493
+ // 流:流/非流 + t/s
2494
+ flow: h('span', { class: 'lg-cell-stack', role: 'cell' },
2495
+ h('span', { class: `lg-flow${r.isStream ? '' : ' off'}`, text: r.isStream ? '流' : '非流' }),
2496
+ h('span', { class: 'lg-sub', text: Number.isFinite(r.tps) && r.tps > 0 ? `${fmtInt(r.tps)} t/s` : '—' })),
2497
+
2498
+ // Token:入/出 + 缓存
2499
+ tokens: h('span', { class: 'lg-cell-stack', role: 'cell' },
2500
+ h('span', { class: 'lg-num', text: `${r.input != null ? fmtInt(r.input) : '—'} / ${r.output != null ? fmtInt(r.output) : '—'}` }),
2501
+ h('span', { class: 'lg-sub', text: `缓存 ${fmtInt(Number(r.cache) || 0)}` })),
2502
+
2503
+ // 耗时:首字与耗时各自分档
2504
+ duration: h('span', { class: 'lg-cell-stack lg-time-col', role: 'cell' },
2505
+ h('span', { class: `lg-dur ${logTierClass(r.ttft)}` }, '首字 ', logSecs(r.ttft) ? h('b', { text: logSecs(r.ttft) }) : dash('in')),
2506
+ h('span', { class: `lg-dur ${logTierClass(r.dur, r.tps, r.output)}` }, '耗时 ', logSecs(r.dur) ? h('b', { text: logSecs(r.dur) }) : dash('in'))),
2507
+
2508
+ // 详情:站点给出的计价条件
2509
+ detail: h('span', { class: 'lg-detail', role: 'cell', title: r.detail || '' }, r.detail || dash()),
2510
+ };
2511
+ }
2512
+
2513
+ /** 把筛选下拉的选项按「实际出现过的值」填:不预先假定站点有哪些分组。 */
2514
+ function fillLogFilters(rows) {
2515
+ const groupSel = $('#logs-group');
2516
+ const kindSel = $('#logs-kind');
2517
+ if (groupSel && !groupSel.dataset.filled) {
2518
+ const groups = [...new Set(rows.map((r) => String(r.group || '')).filter(Boolean))].sort();
2519
+ groupSel.replaceChildren(h('option', { value: '', text: '分组' }),
2520
+ ...groups.map((g) => h('option', { value: g, text: g })));
2521
+ groupSel.dataset.filled = '1';
2522
+ }
2523
+ if (groupSel) groupSel.value = logFilter.group;
2524
+ if (kindSel && !kindSel.dataset.filled) {
2525
+ const kinds = [...new Set(rows.map((r) => String(r.kind || '')).filter(Boolean))]
2526
+ .sort((a, b) => {
2527
+ const ia = LOG_KIND_ORDER.indexOf(a);
2528
+ const ib = LOG_KIND_ORDER.indexOf(b);
2529
+ return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib);
2530
+ });
2531
+ kindSel.replaceChildren(h('option', { value: '', text: '所有类型' }),
2532
+ ...kinds.map((k) => h('option', { value: k, text: k })));
2533
+ kindSel.dataset.filled = '1';
2534
+ }
2535
+ if (kindSel) kindSel.value = logFilter.kind;
2536
+ refreshSelect(groupSel);
2537
+ refreshSelect(kindSel);
2538
+ }
2539
+
2540
+ function bindLogControls() {
2541
+ // 时间范围:胶囊按钮打开主题内菜单(今天 / 近 7 天 / 近 30 天)
2542
+ const rangeBtn = $('#logs-range-btn');
2543
+ const rangePop = $('#logs-range-pop');
2544
+ if (rangeBtn && rangePop) {
2545
+ rangeBtn.addEventListener('click', (ev) => {
2546
+ ev.stopPropagation();
2547
+ rangePop.hidden = !rangePop.hidden;
2548
+ rangeBtn.setAttribute('aria-expanded', String(!rangePop.hidden));
2549
+ });
2550
+ for (const opt of $$('#logs-range-pop [data-log-range]')) {
2551
+ opt.addEventListener('click', () => {
2552
+ const range = opt.dataset.logRange;
2553
+ rangePop.hidden = true;
2554
+ rangeBtn.setAttribute('aria-expanded', 'false');
2555
+ if (filters.range === range) return;
2556
+ filters.range = range;
2557
+ syncRangeButtons();
2558
+ logView.page = 1;
2559
+ loadLogs(false);
2560
+ });
2561
+ }
2562
+ document.addEventListener('click', (ev) => {
2563
+ if (rangePop.hidden) return;
2564
+ if (ev.target.closest('#logs-range-pop') || ev.target.closest('#logs-range-btn')) return;
2565
+ rangePop.hidden = true;
2566
+ rangeBtn.setAttribute('aria-expanded', 'false');
2567
+ });
2568
+ document.addEventListener('click', (ev) => {
2569
+ const pop = $('#logs-view-pop');
2570
+ const btn = $('#logs-view-btn');
2571
+ if (!pop || pop.hidden) return;
2572
+ if (ev.target.closest('#logs-view-pop') || ev.target.closest('#logs-view-btn')) return;
2573
+ logView.colsOpen = false;
2574
+ pop.hidden = true;
2575
+ if (btn) btn.setAttribute('aria-expanded', 'false');
2576
+ });
2577
+ }
2578
+
2579
+ const model = $('#logs-model');
2580
+ if (model) {
2581
+ let timer = 0;
2582
+ model.addEventListener('input', () => {
2583
+ clearTimeout(timer);
2584
+ timer = setTimeout(() => { logFilter.model = model.value; logView.page = 1; renderLogs(); }, 120);
2585
+ });
2586
+ }
2587
+
2588
+ const token = $('#logs-token');
2589
+ if (token) {
2590
+ let timer = 0;
2591
+ token.addEventListener('input', () => {
2592
+ clearTimeout(timer);
2593
+ timer = setTimeout(() => { logFilter.tokenName = token.value; logView.page = 1; renderLogs(); }, 120);
1510
2594
  });
1511
2595
  }
1512
2596
 
1513
- const account = $('#flow-account');
1514
- account.addEventListener('change', () => {
1515
- filters.account = account.value;
1516
- if (!filters.account) { renderFlow(); return; }
1517
- loadFlow(false);
2597
+ const request = $('#logs-request');
2598
+ if (request) {
2599
+ let timer = 0;
2600
+ request.addEventListener('input', () => {
2601
+ clearTimeout(timer);
2602
+ timer = setTimeout(() => { logFilter.requestId = request.value; logView.page = 1; renderLogs(); }, 120);
2603
+ });
2604
+ }
2605
+
2606
+ const uprequest = $('#logs-uprequest');
2607
+ if (uprequest) {
2608
+ let timer = 0;
2609
+ uprequest.addEventListener('input', () => {
2610
+ clearTimeout(timer);
2611
+ timer = setTimeout(() => { logFilter.upRequestId = uprequest.value; logView.page = 1; renderLogs(); }, 120);
2612
+ });
2613
+ }
2614
+
2615
+ const group = $('#logs-group');
2616
+ if (group) group.addEventListener('change', () => { logFilter.group = group.value; logView.page = 1; renderLogs(); });
2617
+
2618
+ const kind = $('#logs-kind');
2619
+ if (kind) kind.addEventListener('change', () => { logFilter.kind = kind.value; logView.page = 1; renderLogs(); });
2620
+
2621
+ const more = $('#logs-more');
2622
+ if (more) {
2623
+ more.addEventListener('click', () => {
2624
+ logView.more = !logView.more;
2625
+ more.setAttribute('aria-expanded', String(logView.more));
2626
+ more.classList.toggle('open', logView.more);
2627
+ const row = $('#logs-more-row');
2628
+ if (row) row.hidden = !logView.more;
2629
+ const label = more.firstElementChild;
2630
+ if (label) label.textContent = logView.more ? '收起' : '展开';
2631
+ });
2632
+ }
2633
+ }
2634
+
2635
+ /** eyeIcon 隐私眼睛(睁/闭),与 NearToken 的同一图形。 */
2636
+ function eyeIcon(off) {
2637
+ const ns = 'http://www.w3.org/2000/svg';
2638
+ const svg = document.createElementNS(ns, 'svg');
2639
+ svg.setAttribute('viewBox', '0 0 24 24');
2640
+ svg.setAttribute('width', '14');
2641
+ svg.setAttribute('height', '14');
2642
+ svg.setAttribute('fill', 'none');
2643
+ svg.setAttribute('stroke', 'currentColor');
2644
+ svg.setAttribute('stroke-width', '1.8');
2645
+ svg.setAttribute('stroke-linecap', 'round');
2646
+ svg.setAttribute('aria-hidden', 'true');
2647
+ const paths = off
2648
+ ? ['M3 3l18 18', 'M10.6 10.6a2 2 0 0 0 2.8 2.8', 'M9.9 5.2A9.9 9.9 0 0 1 12 5c5 0 9 4.5 10 7-.4 1-1.4 2.5-2.8 3.8', 'M6.1 6.1C3.9 7.6 2.5 9.7 2 12c1 2.5 5 7 10 7 1.4 0 2.7-.3 3.9-.9']
2649
+ : ['M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z', 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'];
2650
+ for (const d of paths) {
2651
+ const p = document.createElementNS(ns, 'path');
2652
+ p.setAttribute('d', d);
2653
+ svg.appendChild(p);
2654
+ }
2655
+ return svg;
2656
+ }
2657
+
2658
+ /**
2659
+ * syncRangeButtons 让两个页面的时间范围控件与 filters.range 保持一致。
2660
+ */
2661
+ function syncRangeButtons() {
2662
+ for (const btn of $$('.segmented [data-range]')) {
2663
+ btn.setAttribute('aria-pressed', String(btn.dataset.range === filters.range));
2664
+ }
2665
+ for (const opt of $$('#logs-range-pop [data-log-range]')) {
2666
+ opt.setAttribute('aria-selected', String(opt.dataset.logRange === filters.range));
2667
+ }
2668
+ }
2669
+
2670
+ // ── 通用下拉:替掉原生 select 的系统白底弹层 ──────────────────
2671
+ // 原生 <select> 的候选列表由系统画,深色页面里必定是一块白底(截图里的
2672
+ // 「所有分组 / 所有类型」)。这里保留 <select> 作为值与表单校验的载体,
2673
+ // 只把视觉层换成本主题的按钮 + listbox:选中后写回 select.value 并派发
2674
+ // change,原有的筛选与表单逻辑一行都不用改。
2675
+
2676
+ let openSelWrap = null;
2677
+
2678
+ /** closeOpenSelect 同一时间只允许开一个下拉。 */
2679
+ function closeOpenSelect() {
2680
+ if (!openSelWrap) return;
2681
+ const pop = openSelWrap.querySelector('.sel-pop');
2682
+ const trigger = openSelWrap.querySelector('.sel-trigger');
2683
+ if (pop) pop.hidden = true;
2684
+ if (trigger) trigger.setAttribute('aria-expanded', 'false');
2685
+ openSelWrap.classList.remove('open');
2686
+ openSelWrap = null;
2687
+ }
2688
+ document.addEventListener('click', () => closeOpenSelect());
2689
+
2690
+ /**
2691
+ * refreshSelect 在选项或值被程序改动后,重画触发器文案与候选列表。
2692
+ * 旧实现依赖原生 select 自己同步显示,换成自绘之后必须显式调用。
2693
+ */
2694
+ function refreshSelect(sel) {
2695
+ if (!sel || typeof sel.closest !== 'function') return;
2696
+ const wrap = sel.closest('.sel');
2697
+ if (!wrap) return;
2698
+ const text = wrap.querySelector('.sel-text');
2699
+ const pop = wrap.querySelector('.sel-pop');
2700
+ const trigger = wrap.querySelector('.sel-trigger');
2701
+ const selected = [...sel.options].find((o) => o.value === sel.value) || null;
2702
+ if (text) {
2703
+ text.textContent = selected ? selected.textContent : '—';
2704
+ text.classList.toggle('is-placeholder', !sel.value);
2705
+ }
2706
+ if (pop) {
2707
+ pop.replaceChildren(...[...sel.options].map((o) => h('button', {
2708
+ class: 'sel-opt' + (o.value === sel.value ? ' on' : ''), type: 'button', role: 'option',
2709
+ 'aria-selected': String(o.value === sel.value), 'data-value': o.value, tabindex: '-1',
2710
+ }, o.value === '' && sel.dataset.emptyLabel ? sel.dataset.emptyLabel : o.textContent)));
2711
+ }
2712
+ if (trigger) trigger.disabled = Boolean(sel.disabled);
2713
+ }
2714
+
2715
+ /** enhanceSelect 把一个原生 select 换成主题内下拉;可重复调用(幂等)。 */
2716
+ function enhanceSelect(sel, extraClass = '') {
2717
+ if (!sel || sel.dataset.enhanced === '1') return;
2718
+ sel.dataset.enhanced = '1';
2719
+ sel.classList.add('sel-native');
2720
+ sel.setAttribute('tabindex', '-1');
2721
+ const wrap = h('div', { class: `sel ${extraClass}`.trim() });
2722
+ const trigger = h('button', {
2723
+ class: 'sel-trigger', type: 'button', 'aria-haspopup': 'listbox', 'aria-expanded': 'false',
2724
+ }, h('span', { class: 'sel-text' }), h('span', { class: 'sel-caret', 'aria-hidden': 'true' }, '▾'));
2725
+ const pop = h('div', { class: 'sel-pop', role: 'listbox', hidden: true });
2726
+ // 触发器要有自己的可读名字:可见的 label 指向的是原生 select
2727
+ const label = sel.id ? document.querySelector(`label[for="${sel.id}"]`) : null;
2728
+ const labelText = (label && label.textContent.trim()) || sel.getAttribute('aria-label') || '';
2729
+ if (labelText) trigger.setAttribute('aria-label', labelText);
2730
+
2731
+ const parent = sel.parentNode;
2732
+ parent.insertBefore(wrap, sel);
2733
+ wrap.append(sel, trigger, pop);
2734
+
2735
+ const choose = (value) => {
2736
+ sel.value = value;
2737
+ sel.dispatchEvent(new Event('change', { bubbles: true }));
2738
+ refreshSelect(sel);
2739
+ closeOpenSelect();
2740
+ trigger.focus();
2741
+ };
2742
+
2743
+ trigger.addEventListener('click', (ev) => {
2744
+ ev.stopPropagation();
2745
+ if (openSelWrap === wrap) { closeOpenSelect(); return; }
2746
+ closeOpenSelect();
2747
+ pop.hidden = false;
2748
+ trigger.setAttribute('aria-expanded', 'true');
2749
+ wrap.classList.add('open');
2750
+ openSelWrap = wrap;
2751
+ const on = pop.querySelector('.sel-opt.on') || pop.querySelector('.sel-opt');
2752
+ if (on) on.focus();
1518
2753
  });
2754
+
2755
+ pop.addEventListener('click', (ev) => {
2756
+ const opt = ev.target.closest('.sel-opt');
2757
+ if (opt) choose(opt.dataset.value);
2758
+ });
2759
+
2760
+ pop.addEventListener('keydown', (ev) => {
2761
+ const opts = [...pop.querySelectorAll('.sel-opt')];
2762
+ const i = opts.indexOf(document.activeElement);
2763
+ if (ev.key === 'ArrowDown') { ev.preventDefault(); (opts[i + 1] || opts[0])?.focus(); }
2764
+ else if (ev.key === 'ArrowUp') { ev.preventDefault(); (opts[i - 1] || opts[opts.length - 1])?.focus(); }
2765
+ else if (ev.key === 'Home') { ev.preventDefault(); opts[0]?.focus(); }
2766
+ else if (ev.key === 'End') { ev.preventDefault(); opts[opts.length - 1]?.focus(); }
2767
+ else if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); if (i >= 0) choose(opts[i].dataset.value); }
2768
+ else if (ev.key === 'Escape') { ev.preventDefault(); closeOpenSelect(); trigger.focus(); }
2769
+ else if (ev.key === 'Tab') closeOpenSelect();
2770
+ });
2771
+
2772
+ refreshSelect(sel);
2773
+ }
2774
+
2775
+ /** enhanceSelects 把所有「值从服务端来」的原生下拉换成主题内下拉。 */
2776
+ function enhanceSelects() {
2777
+ for (const id of ['logs-group', 'logs-kind', 'keys-filter-group', 'keys-filter-status', 'key-group', 'key-expire']) {
2778
+ enhanceSelect($('#' + id));
2779
+ }
1519
2780
  }
1520
2781
 
2782
+
1521
2783
  // ── 3. 密钥 ───────────────────────────────────────────────
1522
2784
 
1523
2785
  async function loadKeys(force = false) {
1524
2786
  if (cache.keys && !force) { renderKeys(); return cache.keys; }
1525
2787
  if (loading.keys) return cache.keys;
1526
2788
 
2789
+ const epoch = dataEpoch;
1527
2790
  loading.keys = true;
1528
2791
  regionLoading($('#keys-body'), '正在读取钥匙列表');
1529
2792
 
1530
2793
  try {
1531
2794
  const data = await api.keys();
2795
+ if (epoch !== dataEpoch) return null;
1532
2796
  cache.keys = data;
1533
2797
  cache.keysNeedPat = false;
1534
2798
  clearBanner('keys');
1535
2799
  renderKeys();
1536
2800
  return data;
1537
2801
  } catch (err) {
2802
+ if (epoch !== dataEpoch) return null;
1538
2803
  const msg = describeError(err);
1539
2804
  // 「还没设 PAT」是刚装好时的正常状态,不是错误。这里不该甩红条,
1540
2805
  // 该直接告诉他下一步做什么——否则第一次打开就像插件坏了。
@@ -1554,7 +2819,7 @@ async function loadKeys(force = false) {
1554
2819
  renderKeyGroupOptions();
1555
2820
  return null;
1556
2821
  } finally {
1557
- loading.keys = false;
2822
+ if (epoch === dataEpoch) loading.keys = false;
1558
2823
  }
1559
2824
  }
1560
2825
 
@@ -1587,6 +2852,7 @@ function renderKeyGroupOptions() {
1587
2852
 
1588
2853
  sel.disabled = groups.length === 0;
1589
2854
  if (submit) submit.disabled = groups.length === 0;
2855
+ refreshSelect(sel);
1590
2856
 
1591
2857
  if (!groups.length) {
1592
2858
  const hasPat = Boolean(cache.state && cache.state.pat && cache.state.pat.set);
@@ -1598,16 +2864,230 @@ function renderKeyGroupOptions() {
1598
2864
  }
1599
2865
  }
1600
2866
 
2867
+ // ── 新建钥匙弹窗:仿原站「创建 API 密钥」对话框 ──────────────────
2868
+ // 表单本体沿用原 #key-form 的元素与校验逻辑,只是从左列卡片搬进弹窗。
2869
+
2870
+ let keyEditId = null;
2871
+
2872
+ function openKeyModal(editing = null) {
2873
+ const modal = $('#key-modal');
2874
+ if (!modal) return;
2875
+ renderKeyGroupOptions();
2876
+ keyEditId = editing && editing.id ? editing.id : null;
2877
+ const title = $('#key-modal-title');
2878
+ const sub = document.querySelector('#key-modal .modal-sub');
2879
+ if (title) title.textContent = keyEditId ? '更新 API 密钥' : '创建 API 密钥';
2880
+ if (sub) sub.textContent = keyEditId ? '通过提供必要信息更新 API 密钥。' : '通过提供必要信息添加新的 API 密钥。';
2881
+ const name = $('#key-name');
2882
+ const group = $('#key-group');
2883
+ const unlimited = $('#key-unlimited');
2884
+ const quota = $('#key-quota');
2885
+ const expire = $('#key-expire');
2886
+ if (keyEditId) {
2887
+ if (name) { name.value = editing.name || ''; name.dataset.auto = '0'; }
2888
+ if (group) { group.value = editing.group || ''; refreshSelect(group); }
2889
+ if (unlimited) { unlimited.checked = editing.unlimited !== false; }
2890
+ if (quota) { quota.disabled = unlimited ? unlimited.checked : true; quota.value = editing.unlimited ? '' : moneyRaw(editing.remain).replace(/[^0-9.]/g, ''); }
2891
+ if (expire) { expire.value = '0'; refreshSelect(expire); }
2892
+ } else {
2893
+ if (name) { name.value = ''; name.dataset.auto = '0'; }
2894
+ if (unlimited) unlimited.checked = true;
2895
+ if (quota) { quota.value = ''; quota.disabled = true; }
2896
+ if (expire) { expire.value = '0'; refreshSelect(expire); }
2897
+ }
2898
+ const submit = $('#key-submit');
2899
+ if (submit) submit.textContent = keyEditId ? '保存更改' : '保存更改';
2900
+ modal.hidden = false;
2901
+ document.body.classList.add('modal-open');
2902
+ if (name) setTimeout(() => name.focus(), 0);
2903
+ }
2904
+
2905
+ function closeKeyModal() {
2906
+ const modal = $('#key-modal');
2907
+ if (!modal) return;
2908
+ modal.hidden = true;
2909
+ document.body.classList.remove('modal-open');
2910
+ }
2911
+
2912
+ function bindKeyModal() {
2913
+ const open = $('#key-create-open');
2914
+ if (open) open.addEventListener('click', () => openKeyModal());
2915
+ for (const id of ['key-modal-close', 'key-modal-cancel']) {
2916
+ const btn = $('#' + id);
2917
+ if (btn) btn.addEventListener('click', closeKeyModal);
2918
+ }
2919
+ const modal = $('#key-modal');
2920
+ if (modal) {
2921
+ // 点遮罩关(点对话框本体不关)
2922
+ modal.addEventListener('mousedown', (ev) => {
2923
+ if (ev.target === modal) closeKeyModal();
2924
+ });
2925
+ // Esc 关
2926
+ modal.addEventListener('keydown', (ev) => {
2927
+ if (ev.key === 'Escape') closeKeyModal();
2928
+ });
2929
+ }
2930
+ }
2931
+
2932
+ /** 密钥表筛选:名称 + 分组,纯前端过滤。 */
2933
+ const KEY_COLS = [
2934
+ { id: 'name', label: '名称' },
2935
+ { id: 'status', label: '状态' },
2936
+ { id: 'key', label: 'API 密钥' },
2937
+ { id: 'quota', label: '额度 ($)' },
2938
+ { id: 'group', label: '分组' },
2939
+ { id: 'model', label: '模型' },
2940
+ { id: 'ip', label: 'IP 限制' },
2941
+ { id: 'time', label: '时间' },
2942
+ { id: 'expire', label: '过期' },
2943
+ ];
2944
+ const keysView = new Set(['name', 'status', 'key', 'group', 'time', 'expire']);
2945
+
2946
+ const keysFilter = { name: '', key: '', status: '' };
2947
+ const keysSel = new Set();
2948
+
2949
+ function filteredKeys() {
2950
+ const keys = (cache.keys && cache.keys.keys) || [];
2951
+ const q = keysFilter.name.trim().toLowerCase();
2952
+ const kq = keysFilter.key.trim().toLowerCase();
2953
+ return keys.filter((k) => {
2954
+ if (q && !String(k.name || '').toLowerCase().includes(q)) return false;
2955
+ if (kq && !String(k.masked || '').toLowerCase().includes(kq)) return false;
2956
+ if (keysFilter.status && String(k.status) !== keysFilter.status) return false;
2957
+ return true;
2958
+ });
2959
+ }
2960
+
2961
+ /** groupRatioOf 分组倍率(来自 /api/state 的分组表);找不到就给 null。 */
2962
+ function groupRatioOf(name) {
2963
+ const groups = (cache.state && cache.state.groups) || [];
2964
+ const g = groups.find((x) => x.id === name);
2965
+ return g && Number.isFinite(Number(g.ratio)) ? Number(g.ratio) : null;
2966
+ }
2967
+
2968
+ /** ratioTone 官网按倍率给分组上色:1x 绿、1.2x 金、0.35x 橙、低倍率蓝。 */
2969
+ function ratioTone(r) {
2970
+ if (r == null) return '';
2971
+ if (r >= 1.5) return 'rt-gold';
2972
+ if (r >= 1) return 'rt-green';
2973
+ if (r >= 0.3) return 'rt-orange';
2974
+ return 'rt-blue';
2975
+ }
2976
+
2977
+ function ratioLabel(r) {
2978
+ const n = Number(r);
2979
+ if (!Number.isFinite(n)) return '';
2980
+ return `${Number.isInteger(n) ? n : n.toFixed(2).replace(/0+$/, '').replace(/\.$/, '')}x`;
2981
+ }
2982
+
2983
+ /** relTime 官网「时间」列用相对时间(2 小时前 / 4 小时前)。 */
2984
+ function relTime(ms) {
2985
+ const n = Number(ms);
2986
+ if (!Number.isFinite(n) || n <= 0) return '—';
2987
+ const diff = Date.now() - n;
2988
+ if (diff < 60_000) return '刚刚';
2989
+ const min = Math.floor(diff / 60_000);
2990
+ if (min < 60) return `${min} 分钟前`;
2991
+ const h = Math.floor(min / 60);
2992
+ if (h < 24) return `${h} 小时前`;
2993
+ const d = Math.floor(h / 24);
2994
+ if (d < 30) return `${d} 天前`;
2995
+ return fmtAt(n);
2996
+ }
2997
+
2998
+ const KEY_ICON_PENCIL = ['M12 20h9', 'M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z'];
2999
+ const KEY_ICON_TRASH = ['M3 6h18', 'M8 6V4h8v2', 'M19 6l-1 14H6L5 6', 'M10 11v5', 'M14 11v5'];
3000
+
3001
+ function keyIconBtn(title, paths, onclick, danger = false) {
3002
+ return h('button', {
3003
+ class: `keys-act${danger ? ' danger' : ''}`, type: 'button', title, 'aria-label': title,
3004
+ onclick,
3005
+ }, lineIcon(paths, 14));
3006
+ }
3007
+
3008
+ function fillKeyGroupFilter(keys) {
3009
+ const sel = $('#keys-filter-group');
3010
+ if (!sel) return;
3011
+ const groups = [...new Set(keys.map((k) => String(k.group || '')).filter(Boolean))].sort();
3012
+ const keep = keysFilter.group;
3013
+ sel.replaceChildren(
3014
+ h('option', { value: '', text: '所有分组' }),
3015
+ ...groups.map((g) => h('option', { value: g, text: g })),
3016
+ );
3017
+ sel.value = groups.includes(keep) ? keep : '';
3018
+ keysFilter.group = sel.value;
3019
+ refreshSelect(sel);
3020
+ }
3021
+
3022
+ function bindKeysFilter() {
3023
+ const name = $('#keys-filter-name');
3024
+ if (name) {
3025
+ let timer = 0;
3026
+ name.addEventListener('input', () => {
3027
+ clearTimeout(timer);
3028
+ timer = setTimeout(() => { keysFilter.name = name.value; renderKeys(); }, 120);
3029
+ });
3030
+ }
3031
+ const keyInput = $('#keys-filter-key');
3032
+ if (keyInput) {
3033
+ let timer = 0;
3034
+ keyInput.addEventListener('input', () => {
3035
+ clearTimeout(timer);
3036
+ timer = setTimeout(() => { keysFilter.key = keyInput.value; renderKeys(); }, 120);
3037
+ });
3038
+ }
3039
+ const status = $('#keys-filter-status');
3040
+ if (status) status.addEventListener('change', () => { keysFilter.status = status.value; renderKeys(); });
3041
+
3042
+ const viewBtn = $('#keys-view-btn');
3043
+ const viewPop = $('#keys-view-pop');
3044
+ if (viewBtn && viewPop) {
3045
+ viewBtn.addEventListener('click', (ev) => {
3046
+ ev.stopPropagation();
3047
+ viewPop.hidden = !viewPop.hidden;
3048
+ viewBtn.setAttribute('aria-expanded', String(!viewPop.hidden));
3049
+ });
3050
+ document.addEventListener('click', (ev) => {
3051
+ if (viewPop.hidden) return;
3052
+ if (ev.target.closest('#keys-view-pop') || ev.target.closest('#keys-view-btn')) return;
3053
+ viewPop.hidden = true;
3054
+ viewBtn.setAttribute('aria-expanded', 'false');
3055
+ });
3056
+ document.addEventListener('click', (ev) => {
3057
+ if (ev.target.closest('.keys-more')) return;
3058
+ document.querySelectorAll('.keys-more .menu-pop').forEach((p) => { p.hidden = true; });
3059
+ });
3060
+ }
3061
+
3062
+ const addr = $('#keys-api-addr');
3063
+ if (addr) {
3064
+ addr.addEventListener('click', (ev) => {
3065
+ const site = (cache.state && cache.state.site) || 'https://newapi.dragon3api.com';
3066
+ copyText(`${site}/v1`, ev.currentTarget, '已复制');
3067
+ });
3068
+ }
3069
+
3070
+ const clear = $('#keys-filter-clear');
3071
+ if (clear) {
3072
+ clear.addEventListener('click', () => {
3073
+ keysFilter.name = ''; keysFilter.key = ''; keysFilter.status = '';
3074
+ keysSel.clear();
3075
+ if (name) name.value = '';
3076
+ if (keyInput) keyInput.value = '';
3077
+ if (status) { status.value = ''; refreshSelect(status); }
3078
+ renderKeys();
3079
+ });
3080
+ }
3081
+ }
3082
+
1601
3083
  function renderKeys() {
1602
3084
  const box = $('#keys-body');
1603
- const count = $('#keys-count');
1604
3085
  if (!box) return;
1605
3086
 
1606
3087
  renderKeyGroupOptions();
1607
- if (count) {
1608
- const n = cache.keys && Array.isArray(cache.keys.keys) ? cache.keys.keys.length : 0;
1609
- count.textContent = n ? `${n} 把` : '';
1610
- }
3088
+ const all = (cache.keys && cache.keys.keys) || [];
3089
+ const keys = filteredKeys();
3090
+ fillKeyGroupFilter(all);
1611
3091
 
1612
3092
  if (!cache.keys) {
1613
3093
  if (cache.keysNeedPat) {
@@ -1625,40 +3105,48 @@ function renderKeys() {
1625
3105
  return;
1626
3106
  }
1627
3107
 
1628
- const keys = cache.keys.keys || [];
1629
- if (!keys.length) {
1630
- box.replaceChildren(h('div', { class: 'empty', text: '还没有钥匙。用左边的表单按分组建一把,建完记得立刻复制 sk-。' }));
3108
+ if (!all.length) {
3109
+ box.replaceChildren(h('div', { class: 'empty', text: '还没有钥匙。点右上「创建 API 密钥」按分组建一把,建完记得立刻复制 sk-。' }));
1631
3110
  return;
1632
3111
  }
1633
3112
 
3113
+ // 列序照官网;「查看」菜单可切换显示哪些列
3114
+ const visible = KEY_COLS.filter((c) => keysView.has(c.id));
1634
3115
  const thead = h('thead', null, h('tr', null,
1635
- ['名称', '分组', '打码', '创建时间', { label: '已用', cls: 'num' }, '状态', '绑定', '操作']
1636
- .map((hd) => {
1637
- const spec = typeof hd === 'string' ? { label: hd } : hd;
1638
- return h('th', { scope: 'col', class: spec.cls || null }, spec.label);
1639
- })));
3116
+ ...visible.map((c) => h('th', { scope: 'col', text: c.label })),
3117
+ h('th', { scope: 'col', text: '操作' }),
3118
+ ));
1640
3119
 
1641
3120
  const tbody = h('tbody');
1642
3121
  for (const k of keys) {
1643
3122
  const status = keyStatus(k);
1644
- tbody.append(h('tr', null,
1645
- h('td', { class: 'col-name' }, k.name || '未命名'),
1646
- h('td', null, k.group ? h('span', { class: 'tag', text: k.group }) : '—'),
1647
- h('td', { class: 'mono' }, k.masked || '—'),
1648
- h('td', { class: 'mono' }, fmtAt(k.createdAt)),
1649
- h('td', {
1650
- class: 'num',
1651
- title: Number.isFinite(k.used) ? `${fmtInt(k.used)} quota` : null,
1652
- }, moneyRaw(k.used)),
1653
- h('td', null, h('span', { class: status.cls, text: status.label })),
1654
- h('td', null, k.bound
1655
- ? h('span', { class: 'tag ok', text: '已绑定' })
1656
- : h('span', { class: 'tag', text: '未绑定' })),
3123
+ const expireText = Number.isFinite(k.expiredAt) && k.expiredAt > 0 ? fmtAt(k.expiredAt * 1000) : (k.status === 3 ? '已过期' : '永不');
3124
+ const ratio = groupRatioOf(k.group);
3125
+ const cells = {
3126
+ name: h('td', { class: 'keys-name', text: k.name || '未命名' }),
3127
+ status: h('td', null, h('span', { class: `keys-status ${status.cls.includes('ok') ? 'on' : 'off'}`, text: status.label })),
3128
+ key: h('td', null, h('span', { class: 'keys-key' }, k.masked || '—', copyButton(k.masked || '', '⧉'))),
3129
+ quota: h('td', { class: 'keys-quota', title: Number.isFinite(k.used) ? `已用 ${fmtInt(k.used)} quota` : null },
3130
+ k.unlimited ? '无限制' : moneyRaw(k.remain)),
3131
+ group: h('td', null, k.group
3132
+ ? h('span', { class: 'keys-group' },
3133
+ h('span', { class: ratioTone(ratio), text: k.group }),
3134
+ ratio != null ? h('span', { class: 'keys-ratio', text: ratioLabel(ratio) }) : null)
3135
+ : '—'),
3136
+ model: h('td', { class: 'keys-muted', text: '无限制' }),
3137
+ ip: h('td', { class: 'keys-muted', text: '无限制' }),
3138
+ time: h('td', null, h('div', { class: 'keys-time' },
3139
+ h('span', null, '创建时间 ', h('b', { text: relTime(k.createdAt * 1000) })),
3140
+ h('span', null, '最后使用 ', h('b', { text: k.lastUsedAt ? relTime(k.lastUsedAt * 1000) : '—' })))),
3141
+ expire: h('td', { class: 'keys-muted', text: expireText }),
3142
+ };
3143
+ tbody.append(h('tr', { class: keysSel.has(k.id) ? 'is-selected' : null },
3144
+ ...visible.map((c) => cells[c.id]),
1657
3145
  h('td', null, keyActions(k)),
1658
3146
  ));
1659
3147
 
1660
3148
  if (revealed.has(k.id)) {
1661
- tbody.append(h('tr', null, h('td', { colspan: 8 }, h('div', { class: 'reveal-box' },
3149
+ tbody.append(h('tr', null, h('td', { colspan: visible.length + 1 }, h('div', { class: 'reveal-box' },
1662
3150
  h('span', { class: 'reveal-label', text: '完整钥匙' }),
1663
3151
  h('code', { class: 'reveal-value', text: revealed.get(k.id) }),
1664
3152
  copyButton(revealed.get(k.id), '复制'),
@@ -1670,24 +3158,97 @@ function renderKeys() {
1670
3158
  }
1671
3159
  }
1672
3160
 
1673
- // 密钥表也走同一套滚动容器 + 提示,别让它在窄屏上悄悄裁掉「状态」「操作」列。
1674
- const wrap = h('div', { class: 'table-wrap' }, h('table', { class: 'data-table' }, thead, tbody));
1675
- const hint = h('p', { class: 'scroll-hint', 'data-overflow': '0', text: '← 左右滑动看完整列 →' });
1676
- markOverflow(wrap, hint);
1677
- box.replaceChildren(hint, wrap);
3161
+ if (!keys.length) {
3162
+ box.replaceChildren(h('div', { class: 'empty', text: '没有符合筛选的钥匙。' }));
3163
+ return;
3164
+ }
3165
+
3166
+ const wrap = h('div', { class: 'keys-table-wrap' }, h('table', { class: 'keys-table' }, thead, tbody));
3167
+ box.replaceChildren(wrap);
3168
+
3169
+ // 「查看」列菜单:勾选式,至少保留一列
3170
+ const pop = $('#keys-view-pop');
3171
+ if (pop) {
3172
+ pop.replaceChildren(...KEY_COLS.map((c) => h('button', {
3173
+ type: 'button', role: 'option', 'aria-selected': String(keysView.has(c.id)),
3174
+ onclick: (ev) => {
3175
+ ev.stopPropagation();
3176
+ if (keysView.has(c.id)) { if (keysView.size > 1) keysView.delete(c.id); }
3177
+ else keysView.add(c.id);
3178
+ renderKeys();
3179
+ },
3180
+ }, h('span', { class: 'keys-check-mark', text: keysView.has(c.id) ? '✓' : '' }), c.label)));
3181
+ }
1678
3182
  }
1679
3183
 
3184
+
1680
3185
  function keyStatus(k) {
1681
3186
  if (Number.isFinite(k.expiredAt) && k.expiredAt > 0 && k.expiredAt < Date.now()) {
1682
3187
  return { label: '已过期', cls: 'tag bad' };
1683
3188
  }
1684
- if (k.status === 1) return { label: '启用', cls: 'tag ok' };
3189
+ if (k.status === 1) return { label: '已启用', cls: 'tag ok' };
1685
3190
  if (k.status === 2) return { label: '已禁用', cls: 'tag warn' };
1686
3191
  if (k.status === 3) return { label: '已过期', cls: 'tag bad' };
1687
3192
  if (k.status === 4) return { label: '已耗尽', cls: 'tag bad' };
1688
3193
  return { label: k.status == null ? '未知' : `状态 ${k.status}`, cls: 'tag' };
1689
3194
  }
1690
3195
 
3196
+ const KEY_ICON_BAN = ['M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18', 'M5.6 5.6l12.8 12.8'];
3197
+
3198
+ const keySiteUrl = () => (cache.state && cache.state.site) || 'https://newapi.dragon3api.com';
3199
+
3200
+ async function keySecret(k) {
3201
+ const d = await api.revealKey(k.id);
3202
+ if (!d.secret) throw new ApiError('服务端没有返回 secret。', 200, d);
3203
+ return d.secret;
3204
+ }
3205
+
3206
+ async function copyKeySecret(k) {
3207
+ try {
3208
+ const secret = await keySecret(k);
3209
+ await copyText(secret, null);
3210
+ banner('ok', '密钥已复制。', { key: 'keys-ok', timeout: 4000 });
3211
+ } catch (err) {
3212
+ banner('error', `复制密钥失败:${describeError(err)}`, { key: 'reveal-' + k.id });
3213
+ }
3214
+ }
3215
+
3216
+ async function copyKeyConn(k) {
3217
+ try {
3218
+ const secret = await keySecret(k);
3219
+ await copyText(`Base URL: ${keySiteUrl()}/v1\nAPI Key: ${secret}`, null);
3220
+ banner('ok', '连接信息已复制。', { key: 'keys-ok', timeout: 4000 });
3221
+ } catch (err) {
3222
+ banner('error', `复制连接信息失败:${describeError(err)}`, { key: 'reveal-' + k.id });
3223
+ }
3224
+ }
3225
+
3226
+ async function copyCCSwitch(k) {
3227
+ try {
3228
+ const secret = await keySecret(k);
3229
+ const cfg = { name: k.name || 'DragonAPI', baseURL: `${keySiteUrl()}/v1`, apiKey: secret, models: '*' };
3230
+ await copyText(JSON.stringify(cfg, null, 2), null);
3231
+ banner('ok', 'CC Switch 配置已复制。', { key: 'keys-ok', timeout: 4000 });
3232
+ } catch (err) {
3233
+ banner('error', `生成 CC Switch 配置失败:${describeError(err)}`, { key: 'reveal-' + k.id });
3234
+ }
3235
+ }
3236
+
3237
+ function openKeyChat() {
3238
+ window.open(`${keySiteUrl()}/`, '_blank', 'noopener');
3239
+ }
3240
+
3241
+ async function toggleKeyStatus(k) {
3242
+ try {
3243
+ await api.updateKey(k.id, { status: k.status === 1 ? 2 : 1 });
3244
+ banner('ok', k.status === 1 ? '已禁用该密钥。' : '已启用该密钥。', { key: 'keys-ok', timeout: 4000 });
3245
+ cache.keys = null;
3246
+ await loadKeys(true);
3247
+ } catch (err) {
3248
+ banner('error', `操作失败:${describeError(err)}`, { key: 'keys' });
3249
+ }
3250
+ }
3251
+
1691
3252
  function keyActions(k) {
1692
3253
  if (confirmDeleteId === k.id) {
1693
3254
  return h('span', { class: 'row-actions' },
@@ -1701,16 +3262,35 @@ function keyActions(k) {
1701
3262
  }, '取消'),
1702
3263
  );
1703
3264
  }
1704
- return h('span', { class: 'row-actions' },
1705
- h('button', {
1706
- class: 'btn tiny ghost', type: 'button',
1707
- title: '需要 PAT 的 api_key:reveal 权限',
1708
- onclick: (ev) => revealKey(k, ev.currentTarget),
1709
- }, '查看完整钥匙'),
1710
- h('button', {
1711
- class: 'btn tiny danger', type: 'button',
1712
- onclick: () => { confirmDeleteId = k.id; renderKeys(); },
1713
- }, '删除'),
3265
+ const on = k.status === 1;
3266
+ const item = (label, icon, fn, cls = '') => h('button', {
3267
+ type: 'button', role: 'option', class: cls,
3268
+ onclick: (ev) => { ev.stopPropagation(); ev.currentTarget.closest('.menu-pop').hidden = true; fn(); },
3269
+ }, h('span', { class: 'kmi', text: label }), h('span', { class: 'kmi-ico', text: icon }));
3270
+ return h('span', { class: 'keys-actions' },
3271
+ keyIconBtn(on ? '禁用' : '启用', KEY_ICON_BAN, (ev) => { ev.stopPropagation(); toggleKeyStatus(k); }, true),
3272
+ keyIconBtn('编辑', KEY_ICON_PENCIL, (ev) => { ev.stopPropagation(); openKeyModal(k); }),
3273
+ h('div', { class: 'menu keys-more' },
3274
+ h('button', {
3275
+ class: 'keys-act keys-more-btn', type: 'button', title: '更多', 'aria-label': '更多',
3276
+ onclick: (ev) => {
3277
+ ev.stopPropagation();
3278
+ const pop = ev.currentTarget.parentElement.querySelector('.menu-pop');
3279
+ const wasOpen = !pop.hidden;
3280
+ document.querySelectorAll('.keys-more .menu-pop').forEach((p) => { p.hidden = true; });
3281
+ pop.hidden = wasOpen;
3282
+ },
3283
+ }, '⋯'),
3284
+ h('div', { class: 'menu-pop keys-more-pop', hidden: true },
3285
+ item('复制密钥', '⧉', () => copyKeySecret(k)),
3286
+ item('复制连接信息', '🔗', () => copyKeyConn(k)),
3287
+ item('CC Switch', '⇄', () => copyCCSwitch(k)),
3288
+ item('聊天', '›', () => openKeyChat()),
3289
+ h('button', {
3290
+ type: 'button', class: 'keys-more-del',
3291
+ onclick: (ev) => { ev.stopPropagation(); ev.currentTarget.closest('.menu-pop').hidden = true; confirmDeleteId = k.id; renderKeys(); },
3292
+ }, '删除'),
3293
+ )),
1714
3294
  );
1715
3295
  }
1716
3296
 
@@ -1801,6 +3381,9 @@ function bindKeyForm() {
1801
3381
  name.addEventListener('input', () => { name.dataset.auto = '0'; });
1802
3382
 
1803
3383
  form.addEventListener('submit', onCreateKey);
3384
+ // 提交按钮在 form 外(脚部钉住不滚),submit 事件到不了它——直接绑 click
3385
+ const submitBtn = $('#key-submit');
3386
+ if (submitBtn) submitBtn.addEventListener('click', onCreateKey);
1804
3387
  }
1805
3388
 
1806
3389
  async function onCreateKey(ev) {
@@ -1829,12 +3412,23 @@ async function onCreateKey(ev) {
1829
3412
  // 契约的请求体只写了 name / group / unlimited / expiredAt;
1830
3413
  // 有限额度按契约里 keys[].remain 的语义补 remain(原始 quota),
1831
3414
  // 换算沿用 state.currency 的 per / rate,与金额显示同源。
1832
- const body = { name, group, unlimited, expiredAt: 0 };
3415
+ const expireSec = Number($('#key-expire')?.value || 0);
3416
+ const body = { name, group, unlimited, expiredAt: expireSec > 0 ? Math.floor(Date.now() / 1000) + expireSec : 0 };
1833
3417
  if (!unlimited) body.remain = rawFromMoney(amount);
1834
3418
 
1835
3419
  submit.disabled = true;
1836
- submit.textContent = '创建中…';
3420
+ submit.textContent = keyEditId ? '保存中…' : '创建中…';
1837
3421
  try {
3422
+ if (keyEditId) {
3423
+ await api.updateKey(keyEditId, body);
3424
+ clearBanner('key-form');
3425
+ banner('ok', '已更新 API 密钥。', { key: 'keys-ok', timeout: 6000 });
3426
+ closeKeyModal();
3427
+ keyEditId = null;
3428
+ cache.keys = null;
3429
+ await loadKeys(true);
3430
+ return;
3431
+ }
1838
3432
  const data = await api.createKey(body);
1839
3433
  lastSecret = { key: data.key || {}, bind: data.bind || null };
1840
3434
  renderSecret();
@@ -1843,6 +3437,7 @@ async function onCreateKey(ev) {
1843
3437
  $('#key-name').value = '';
1844
3438
  $('#key-name').dataset.auto = '0';
1845
3439
  $('#key-quota').value = '';
3440
+ closeKeyModal();
1846
3441
  cache.keys = null;
1847
3442
  await loadKeys(true);
1848
3443
  const slot = $('#secret-slot');
@@ -1857,40 +3452,23 @@ async function onCreateKey(ev) {
1857
3452
  }
1858
3453
 
1859
3454
  async function loadBind(force = false) {
1860
- if (cache.bind && !force) { renderBind(); return cache.bind; }
3455
+ // 绑定说明的卡片已删除,但「新建钥匙成功」面板仍要用这里的步骤,只缓存不渲染。
3456
+ if (cache.bind && !force) return cache.bind;
1861
3457
  if (loading.bind) return cache.bind;
1862
3458
  loading.bind = true;
1863
3459
  try {
1864
3460
  cache.bind = await api.bindInfo();
1865
3461
  clearBanner('bind');
1866
- renderBind();
1867
3462
  return cache.bind;
1868
3463
  } catch (err) {
1869
3464
  const msg = describeError(err);
1870
3465
  banner('error', `读取绑定说明失败:${msg}`, { key: 'bind' });
1871
- regionError($('#bind-info-body'), `绑定说明没读到:${msg}`, () => loadBind(true));
1872
3466
  return null;
1873
3467
  } finally {
1874
3468
  loading.bind = false;
1875
3469
  }
1876
3470
  }
1877
3471
 
1878
- function renderBind() {
1879
- const box = $('#bind-info-body');
1880
- if (!box) return;
1881
- const data = cache.bind;
1882
- if (!data) { regionLoading(box, '正在读取绑定说明'); return; }
1883
-
1884
- const how = Array.isArray(data.how) ? data.how : (data.how ? [data.how] : []);
1885
- box.replaceChildren(
1886
- how.length
1887
- ? h('ol', { class: 'bind-steps' }, how.map((step) => h('li', { text: String(step) })))
1888
- : h('p', { class: 'muted', text: '服务端没有给出绑定步骤。' }),
1889
- data.auto && data.auto.label
1890
- ? h('p', { class: 'hint', text: `自动方式:${data.auto.label}(method: ${data.auto.method || '—'})` })
1891
- : null,
1892
- );
1893
- }
1894
3472
 
1895
3473
  // ── 4. 访问令牌(PAT) ────────────────────────────────────
1896
3474
 
@@ -2004,11 +3582,20 @@ function renderHealth() {
2004
3582
  );
2005
3583
  }
2006
3584
 
3585
+ function normalizePatInput(value) {
3586
+ return String(value ?? '')
3587
+ .replace(/[\s​-‍⁠'"`“”‘’]/gu, '')
3588
+ .replace(/^(?:(?:authorization:?)|bearer)+/i, '');
3589
+ }
3590
+ function patHintOf(s) {
3591
+ return s.length <= 4 ? '*'.repeat(s.length) : s.length <= 8 ? s.slice(0, 2) + '****' + s.slice(-2) : s.slice(0, 4) + '**********' + s.slice(-4);
3592
+ }
3593
+
2007
3594
  async function onSavePat(ev) {
2008
3595
  ev.preventDefault();
2009
3596
  const input = $('#pat-input');
2010
3597
  const btn = $('#pat-save');
2011
- const pat = input.value.trim();
3598
+ const pat = normalizePatInput(input.value);
2012
3599
 
2013
3600
  if (!pat) { banner('warn', '先粘贴一个 PAT 再保存。', { key: 'pat-form' }); input.focus(); return; }
2014
3601
  // 只挡「明显拿错了凭据」:sk- 是模型钥匙,不是访问令牌。
@@ -2026,7 +3613,7 @@ async function onSavePat(ev) {
2026
3613
 
2027
3614
  btn.disabled = true;
2028
3615
  btn.textContent = '保存中…';
2029
- // 立刻给反馈:保存要串行探三个站点端点,没有这句用户会以为没点上。
3616
+ // PAT 四项只读能力并行探测,页面仍保留独立超时。
2030
3617
  banner('info', '已提交,正在向站点验证这份令牌…', { key: 'pat-form' });
2031
3618
  try {
2032
3619
  const data = await api.savePat(pat);
@@ -2042,14 +3629,25 @@ async function onSavePat(ev) {
2042
3629
  ? `PAT 已保存,已连接到账户 ${data.user.name}。`
2043
3630
  : 'PAT 已保存。', { key: 'pat-ok', timeout: 7000 });
2044
3631
  }
3632
+ clearAccountCache();
3633
+ await loadState(true);
2045
3634
  renderPat();
2046
- // PAT 换了,钥匙/余额/用量都可能变,别拿旧缓存骗人
2047
- cache.keys = null;
2048
- cache.health = null;
2049
- cache.stateError = '';
2050
- if (activeTab === 'keys') loadKeys(true);
3635
+ await ensureTab(activeTab, true);
2051
3636
  return data;
2052
3637
  } catch (err) {
3638
+ // 请求超时不等于服务端没保存;仅核对打码值,不取回或输出完整 PAT。
3639
+ if (err.status === 0) {
3640
+ const state = await api.state().catch(() => null);
3641
+ if (state?.pat?.set && state.pat.hint === patHintOf(pat)) {
3642
+ input.value = '';
3643
+ clearAccountCache();
3644
+ cache.state = state;
3645
+ renderPat();
3646
+ banner('warn', '保存请求未及时返回,但已核对本地服务保存的令牌打码值。', { key: 'pat-form' });
3647
+ await ensureTab(activeTab, true);
3648
+ return state;
3649
+ }
3650
+ }
2053
3651
  // 服务端在 400 里带的 hint 是可操作的下一步(去勾哪个 scope),必须带出来。
2054
3652
  const extra = err && err.payload && err.payload.hint ? ` ${err.payload.hint}` : '';
2055
3653
  banner('error', `保存 PAT 失败:${describeError(err)}${extra}`, { key: 'pat-form' });
@@ -2075,12 +3673,12 @@ async function onClearPat(btn) {
2075
3673
  try {
2076
3674
  const data = await api.clearPat();
2077
3675
  if (cache.state) cache.state.pat = data.pat || { set: false };
2078
- cache.keys = null;
2079
- cache.health = null;
3676
+ clearAccountCache();
2080
3677
  clearBanner('pat-form');
2081
3678
  banner('ok', 'PAT 已清除,页面不再持有任何凭据。', { key: 'pat-ok', timeout: 6000 });
3679
+ await loadState(true);
2082
3680
  renderPat();
2083
- if (activeTab === 'keys') loadKeys(true);
3681
+ await ensureTab(activeTab, true);
2084
3682
  } catch (err) {
2085
3683
  banner('error', `清除 PAT 失败:${describeError(err)}`, { key: 'pat-form' });
2086
3684
  } finally {
@@ -2092,10 +3690,6 @@ async function onClearPat(btn) {
2092
3690
  function bindPatControls() {
2093
3691
  $('#pat-form').addEventListener('submit', onSavePat);
2094
3692
  $('#pat-clear').addEventListener('click', (ev) => onClearPat(ev.currentTarget));
2095
- $('#pat-shortcut').addEventListener('click', () => {
2096
- activateTab('pat', { focus: true });
2097
- setTimeout(() => $('#pat-input').focus(), 0);
2098
- });
2099
3693
  }
2100
3694
 
2101
3695
  // ── 复制:clipboard 失败就退回「选中文本」 ────────────────
@@ -2115,7 +3709,7 @@ async function copyText(text, btn, label = '复制') {
2115
3709
  try {
2116
3710
  if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
2117
3711
  await navigator.clipboard.writeText(text);
2118
- flashButton(btn, label, '已复制');
3712
+ flashButton(btn, '已复制');
2119
3713
  return;
2120
3714
  }
2121
3715
  } catch {
@@ -2148,56 +3742,85 @@ async function copyText(text, btn, label = '复制') {
2148
3742
  const sel = window.getSelection();
2149
3743
  sel.removeAllRanges();
2150
3744
  sel.addRange(range);
2151
- flashButton(btn, label, '已选中,按 Ctrl+C');
3745
+ flashButton(btn, '已选中,按 Ctrl+C');
2152
3746
  banner('warn', '浏览器不允许直接写剪贴板,文本已选中,按 Ctrl+C 复制。', { key: 'copy', timeout: 6000 });
2153
3747
  } else {
2154
- flashButton(btn, label, '复制失败');
3748
+ flashButton(btn, '复制失败');
2155
3749
  banner('warn', '复制失败,请手动选中钥匙文本。', { key: 'copy', timeout: 6000 });
2156
3750
  }
2157
3751
  }
2158
3752
 
2159
- function flashButton(btn, original, temporary) {
3753
+ function flashButton(btn, temporary) {
2160
3754
  if (!btn) return;
3755
+ // 按钮内容可能不是纯文本(令牌胶囊里有图标 + 名字):存 innerHTML,到点原样还原。
3756
+ // 上一版存的是传进来的 label,令牌胶囊被复制后永远变成「复制」,回不来了。
3757
+ if (btn.dataset.flashing === '1') return;
3758
+ btn.dataset.flashing = '1';
3759
+ const saved = btn.innerHTML;
2161
3760
  btn.textContent = temporary;
2162
3761
  btn.disabled = true;
2163
- setTimeout(() => { btn.textContent = original; btn.disabled = false; }, 1600);
3762
+ setTimeout(() => {
3763
+ btn.innerHTML = saved;
3764
+ btn.disabled = false;
3765
+ delete btn.dataset.flashing;
3766
+ }, 1600);
2164
3767
  }
2165
3768
 
2166
3769
  // ── 单模型详情(抽屉) ────────────────────────────────────
2167
3770
 
2168
3771
  let drawerLastFocus = null;
2169
3772
 
2170
- function openModelDrawer(model) {
3773
+ /**
3774
+ * 打开模型详情。
3775
+ *
3776
+ * 入参是聚合后的模型(一个模型一张卡),不是单个分组行。价签、倍率与「当前」
3777
+ * 标记以「聚焦分组」为准:筛选了某个分组就用它,否则用最便宜的那个——这样
3778
+ * 从哪张卡点进来,看到的都是这张卡上那个最显眼的价。
3779
+ */
3780
+ function openModelDrawer(agg) {
2171
3781
  const drawer = $('#drawer');
2172
3782
  if (!drawer) return;
2173
3783
  drawerLastFocus = document.activeElement;
2174
3784
 
2175
- const kind = model.kind || 'chat';
2176
- $('#drawer-title').textContent = model.name || model.id || '模型详情';
3785
+ const focus = focusGroupOf(agg, filters.group);
3786
+ const row = focus?.row || {};
3787
+ const kind = agg.kind || row.kind || 'chat';
3788
+
3789
+ $('#drawer-title').textContent = agg.name || row.name || row.id || '模型详情';
3790
+
3791
+ const ratios = (agg.groups || [])
3792
+ .map((g) => (Number(g.ratio) > 0 ? Number(g.ratio) : null))
3793
+ .filter((r) => r !== null);
3794
+ const ratioRange = ratios.length
3795
+ ? (Math.min(...ratios) === Math.max(...ratios)
3796
+ ? fmtRatio(Math.min(...ratios))
3797
+ : `${fmtRatio(Math.min(...ratios))}–${fmtRatio(Math.max(...ratios))}`)
3798
+ : '';
3799
+
2177
3800
  $('#drawer-sub').replaceChildren(...[
2178
- h('span', { class: 'tag-chip', text: model.group || '未分组' }),
2179
- model.groupRatio != null && Number(model.groupRatio) > 0
2180
- ? h('span', { class: 'tag-chip' }, '倍率 ', h('span', { class: 'ratio', text: fmtRatio(model.groupRatio) }))
2181
- : null,
2182
- model.vendor ? h('span', { class: 'tag-chip' }, vendorBadge(model.vendor, { size: 12 }), ' ', model.vendor) : null,
3801
+ (agg.groupCount || 0) > 1
3802
+ ? h('span', { class: 'tag-chip', text: `${agg.groupCount} 个分组` })
3803
+ : h('span', { class: 'tag-chip', text: row.group || '未分组' }),
3804
+ ratioRange ? h('span', { class: 'tag-chip' }, '倍率 ', h('span', { class: 'ratio', text: ratioRange })) : null,
3805
+ agg.vendor ? h('span', { class: 'tag-chip' }, vendorBadge(agg.vendor, { size: 12 }), ' ', agg.vendor) : null,
2183
3806
  h('span', { class: 'tag-chip', text: KIND_LABEL[kind] || kind }),
2184
3807
  ].filter(Boolean));
2185
3808
 
2186
3809
  const icon = $('#drawer-icon');
2187
- if (icon) icon.replaceChildren(vendorBadge(model.vendor, { size: 30 }));
3810
+ if (icon) icon.replaceChildren(vendorBadge(agg.vendor, { size: 30 }));
2188
3811
 
2189
3812
  const body = $('#drawer-body');
2190
3813
  regionLoading(body, '正在读取计费详情');
2191
3814
  drawer.hidden = false;
2192
3815
  $('#drawer-close').focus();
2193
3816
 
2194
- loadModelDetail(model, body);
3817
+ loadModelDetail(row, body, agg);
2195
3818
  }
2196
3819
 
2197
- async function loadModelDetail(model, body) {
3820
+ async function loadModelDetail(row, body, agg) {
2198
3821
  try {
2199
- const data = await api.model(model.group || '', model.name || model.id || '');
2200
- body.replaceChildren(...modelDetailNodes(model, data));
3822
+ const data = await api.model(row.group || '', agg.name || row.name || row.id || '');
3823
+ body.replaceChildren(...modelDetailNodes(row, data, agg));
2201
3824
  clearBanner('model');
2202
3825
  } catch (err) {
2203
3826
  const msg = describeError(err);
@@ -2229,26 +3852,48 @@ const PARAM_LABEL = { service_tier: '服务档' };
2229
3852
  * 现在的顺序按「先结论、后证据」:
2230
3853
  * 价签 → 概览 → 计费怎么算(中文)→ 每档实际单价 → 按用量单价 → 原始表达式(折叠)
2231
3854
  */
2232
- function modelDetailNodes(model, data) {
3855
+ function modelDetailNodes(model, data, agg = null) {
2233
3856
  const nodes = [];
2234
3857
  const pricing = model.pricing || {};
2235
3858
  const billing = data.billing || null;
2236
3859
  const priceKind = pricing.kind || 'unknown';
2237
3860
  const isAuto = model.group === 'auto' || model.groupAuto === true;
3861
+ const groupCount = agg && agg.groupCount > 1 ? agg.groupCount : null;
2238
3862
 
2239
3863
  // ── 1. 价签:详情页最该先被看到的东西 ──────────────────
2240
3864
  nodes.push(priceTiles(pricing, billing, { isAuto, priceKind }));
2241
3865
 
2242
3866
  // ── 2. 概览 ────────────────────────────────────────────
2243
- nodes.push(h('dl', { class: 'kv-grid' },
2244
- h('dt', { text: '厂商' }), h('dd', { text: model.vendor || '—' }),
2245
- h('dt', { text: '类型' }), h('dd', { text: KIND_LABEL[model.kind] || model.kind || '—' }),
2246
- h('dt', { text: '上下文' }), h('dd', { class: 'mono', text: model.context ? fmtInt(model.context) : '—' }),
2247
- h('dt', { text: '端点' }), h('dd', { class: 'mono', text: (model.endpoints || []).join(' · ') || '—' }),
2248
- h('dt', { text: '分组' }), h('dd', { text: model.group || '—' }),
2249
- h('dt', { text: '分组倍率' }), h('dd', { class: 'mono', text: model.groupRatio != null && Number(model.groupRatio) > 0 ? fmtRatio(model.groupRatio) : '—' }),
2250
- h('dt', { text: '模型 id' }), h('dd', { class: 'mono' }, model.id || '—'),
2251
- ));
3867
+ // 值为空的项直接不印:一排「—」只是噪音,不传递任何信息。
3868
+ const kv = (k, v, mono) => (v ? [h('dt', { text: k }), h('dd', { class: mono ? 'mono' : null, text: v })] : []);
3869
+ const ends = (model.endpoints || []).map(endLabel).join(' · ');
3870
+ // 倍率:多分组时给区间(单值会让人以为整张卡就这一个倍率)
3871
+ const ratios = (agg && Array.isArray(agg.groups) ? agg.groups : [])
3872
+ .map((g) => (Number(g.ratio) > 0 ? Number(g.ratio) : null))
3873
+ .filter((r) => r !== null);
3874
+ const ratioText = ratios.length
3875
+ ? (Math.min(...ratios) === Math.max(...ratios)
3876
+ ? fmtRatio(Math.min(...ratios))
3877
+ : `${fmtRatio(Math.min(...ratios))}–${fmtRatio(Math.max(...ratios))}`)
3878
+ : (model.groupRatio != null && Number(model.groupRatio) > 0 ? fmtRatio(model.groupRatio) : '');
3879
+
3880
+ const kvParts = [
3881
+ kv('厂商', model.vendor || (agg && agg.vendor)),
3882
+ kv('类型', KIND_LABEL[model.kind] || model.kind || (agg && KIND_LABEL[agg.kind])),
3883
+ kv('上下文', model.context ? fmtInt(model.context) : (agg && agg.context ? fmtInt(agg.context) : ''), true),
3884
+ kv('端点', ends, true),
3885
+ kv('分组', groupCount ? `${groupCount} 个(下方横向比较)` : (model.group || '')),
3886
+ kv('分组倍率', ratioText, true),
3887
+ // 站点可能把同一个模型按两种拼写挂着(claude-opus-5-5 / claude-opus-5.5)。
3888
+ // 卡片上合并成一张,但这里要把两个原名都写出来——不能让人以为名字被改过。
3889
+ kv('模型 id', [
3890
+ model.id || (agg && agg.id),
3891
+ agg && Array.isArray(agg.aliases) && agg.aliases.length > 1
3892
+ ? `& ${agg.aliases.slice(1).join(' & ')}`
3893
+ : '',
3894
+ ].filter(Boolean).join(' '), true),
3895
+ ].flat();
3896
+ if (kvParts.length) nodes.push(h('dl', { class: 'kv-grid' }, ...kvParts));
2252
3897
 
2253
3898
  if (model.description) nodes.push(h('p', { class: 'hint', text: model.description }));
2254
3899
 
@@ -2318,18 +3963,23 @@ function modelDetailNodes(model, data) {
2318
3963
  // ── 6. 按分组定价:同一个模型在不同分组里的价格 ──────────
2319
3964
  const siblings = Array.isArray(data.siblings) ? data.siblings : [];
2320
3965
  if (siblings.length > 1) {
3966
+ const td = (cls, child) => h('td', { class: cls || null }, child);
2321
3967
  nodes.push(h('section', { class: 'dtl-section' },
2322
3968
  h('h3', { class: 'dtl-h3', text: '按分组定价' }),
3969
+ // 一句引导:这张表在比什么、价差从哪来。表头只说明了列名。
3970
+ h('p', {
3971
+ class: 'dtl-lead',
3972
+ text: `同一个模型在这些分组里各卖一份,价差来自分组倍率。当前用的是「${GROUP_ALIAS[model.group] || model.group}」,其余分组按倍率从低到高排。`,
3973
+ }),
2323
3974
  tableEl(['分组', '倍率', { label: '输入', cls: 'num' }, { label: '输出', cls: 'num' }, { label: '缓存读取', cls: 'num' }],
2324
- siblings.map((s) => [
2325
- { node: h('span', { class: 'sib-group' + (s.current ? ' is-current' : '') },
3975
+ siblings.map((s) => h('tr', { class: s.current ? 'is-current-row' : null },
3976
+ td(null, h('span', { class: 'sib-group' + (s.current ? ' is-current' : '') },
2326
3977
  h('span', { text: GROUP_ALIAS[s.group] || s.group }),
2327
- s.current ? h('span', { class: 'sib-now', text: '当前' }) : null) },
2328
- { text: Number(s.groupRatio) > 0 ? fmtRatio(s.groupRatio) : (s.auto ? '按通道' : '—'), cls: 'num' },
2329
- { text: s.input || '—', cls: 'num' },
2330
- { text: s.output || '—', cls: 'num' },
2331
- { text: s.cache || '—', cls: 'num' },
2332
- ]),
3978
+ s.current ? h('span', { class: 'sib-now', text: '当前' }) : null)),
3979
+ td('num', Number(s.groupRatio) > 0 ? fmtRatio(s.groupRatio) : (s.auto ? '按通道' : '—')),
3980
+ td('num', s.input || '—'),
3981
+ td('num', s.output || '—'),
3982
+ td('num', s.cache || '—'))),
2333
3983
  { empty: '站点没有给出这个模型的分组价格。' }),
2334
3984
  ));
2335
3985
  }
@@ -2402,9 +4052,15 @@ function billingFacts(billing, { isAuto, priceKind, note } = {}) {
2402
4052
  if (billing && Array.isArray(billing.tiers) && billing.tiers.length) {
2403
4053
  const names = billing.tiers.map((t) => t.name).filter(Boolean);
2404
4054
  const hasTokenPrices = billing.tiers.some((t) => t.prices && Object.keys(t.prices).length);
2405
- facts.push(hasTokenPrices
2406
- ? `共 ${billing.tiers.length} 档:${names.join(' / ')}。下表每一档的单价已经乘上分组倍率 ${fmtRatio(billing.groupRatio)}。`
2407
- : `共 ${billing.tiers.length} 档:${names.join(' / ')}。这些档按用量计费,单价见下表。`);
4055
+ if (hasTokenPrices && billing.tiers.length === 1) {
4056
+ // 单档不是「分档」:这类模型价格是平的,能变的只有 fast / 优先级这类
4057
+ // 整单倍率(见下面「条件乘数」一节)。
4058
+ facts.push(`只有一个档位(${names[0] || '标准'}):单价不随上下文或时段变化。`);
4059
+ } else {
4060
+ facts.push(hasTokenPrices
4061
+ ? `共 ${billing.tiers.length} 档:${names.join(' / ')}。下表每一档的单价已经乘上分组倍率 ${fmtRatio(billing.groupRatio)}。`
4062
+ : `共 ${billing.tiers.length} 档:${names.join(' / ')}。这些档按用量计费,单价见下表。`);
4063
+ }
2408
4064
  }
2409
4065
 
2410
4066
  const usageRows = billing && Array.isArray(billing.usageRows) ? billing.usageRows : [];
@@ -2468,18 +4124,20 @@ async function loadState(force = false) {
2468
4124
  if (loading.state) return cache.state;
2469
4125
 
2470
4126
  loading.state = true;
4127
+ const epoch = dataEpoch;
2471
4128
  try {
2472
4129
  const data = await api.state();
4130
+ if (epoch !== dataEpoch) return null;
2473
4131
  cache.state = data;
2474
4132
  cache.stateError = '';
2475
4133
  clearBanner('state');
2476
4134
  renderHeader();
2477
- populateAccountSelect();
2478
4135
  renderKeyGroupOptions();
2479
4136
  if (activeTab === 'wallet') renderAccounts();
2480
4137
  if (activeTab === 'pat') renderPat();
2481
4138
  return data;
2482
4139
  } catch (err) {
4140
+ if (epoch !== dataEpoch) return null;
2483
4141
  const msg = describeError(err);
2484
4142
  cache.stateError = msg;
2485
4143
  banner('error', `读取站点状态失败:${msg}`, { key: 'state' });
@@ -2488,11 +4146,39 @@ async function loadState(force = false) {
2488
4146
  if (activeTab === 'pat') renderPat();
2489
4147
  return null;
2490
4148
  } finally {
2491
- loading.state = false;
4149
+ if (epoch === dataEpoch) loading.state = false;
4150
+ }
4151
+ }
4152
+
4153
+ function clearAccountCache() {
4154
+ dataEpoch++;
4155
+ usagePending.clear();
4156
+ cache.state = null;
4157
+ cache.stateError = '';
4158
+ cache.keys = null;
4159
+ cache.keysError = '';
4160
+ cache.keysNeedPat = false;
4161
+ cache.aff = null;
4162
+ cache.subscriptions = null;
4163
+ cache.usage = {};
4164
+ cache.usageErrors = {};
4165
+ cache.health = null;
4166
+ for (const name of ['state', 'keys', 'aff', 'subscriptions']) loading[name] = false;
4167
+ lastSecret = null;
4168
+ revealed.clear();
4169
+ affTransferArmedUntil = 0;
4170
+ confirmDeleteId = null;
4171
+ for (const id of ['account-body', 'usage-body', 'aff-body', 'subscriptions-body', 'keys-body', 'logs-body']) {
4172
+ const box = $('#' + id);
4173
+ if (box) regionLoading(box, '正在更新账户数据');
2492
4174
  }
4175
+ $('#logs-chips')?.replaceChildren();
4176
+ $('#logs-pager')?.replaceChildren();
4177
+ renderSecret();
2493
4178
  }
2494
4179
 
2495
4180
  function clearCache() {
4181
+ clearAccountCache();
2496
4182
  cache.state = null;
2497
4183
  cache.stateError = '';
2498
4184
  cache.ping = null;
@@ -2501,7 +4187,6 @@ function clearCache() {
2501
4187
  cache.bind = null;
2502
4188
  cache.health = null;
2503
4189
  cache.usage = {};
2504
- cache.logs = {};
2505
4190
  confirmDeleteId = null;
2506
4191
  revealed.clear();
2507
4192
  }
@@ -2547,14 +4232,22 @@ async function boot() {
2547
4232
  bindTabs();
2548
4233
  bindCatalogControls();
2549
4234
  bindWalletControls();
4235
+ enhanceSelects();
4236
+ bindLogControls();
4237
+ bindDashControls();
2550
4238
  bindKeyForm();
4239
+ bindKeyModal();
4240
+ bindKeysFilter();
2551
4241
  bindPatControls();
2552
4242
  bindDrawer();
2553
4243
 
2554
4244
  const params = new URLSearchParams(location.search);
2555
4245
  const wanted = params.get('tab');
2556
- const valid = ['catalog', 'wallet', 'keys', 'pat'];
2557
- const start = valid.includes(wanted) ? wanted : 'catalog';
4246
+ // 密钥已并入账户页;旧的 ?tab=keys 链接仍要能打开(映射到 wallet),
4247
+ // 不能因为标签被取消就让人书签失效。
4248
+ const valid = ['wallet', 'catalog', 'logs', 'pat'];
4249
+ // 账户页放在首位,也作为默认落地页:打开就能看到余额与钥匙。
4250
+ const start = wanted === 'keys' ? 'wallet' : (valid.includes(wanted) ? wanted : 'wallet');
2558
4251
 
2559
4252
  activateTab(start, { focus: false });
2560
4253