@fish-under-sea/magpie-dragonapi 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  把 [DragonAPI](https://newapi.dragon3api.com/) 接进 magpie:模型广场、余额、用量,外加一个能按分组建钥匙的本地界面。
4
4
 
5
- > 当前版本 **0.1.2**。只做供应商插件 + 只读看板 + 密钥管理,不做「页面里点充值」。
5
+ > 当前版本 **0.1.4**。只做供应商插件 + 只读看板 + 密钥管理,不做「页面里点充值」。
6
6
 
7
7
  ## 它是什么
8
8
 
@@ -25,7 +25,7 @@
25
25
  | **命令行** | `magpie plugin add @fish-under-sea/magpie-dragonapi` |
26
26
 
27
27
  npm 拉不到时(内网、镜像抽风):到 [Releases](https://github.com/Fish-under-sea/magpie-dragonapi/releases) 下
28
- `fish-under-sea-magpie-dragonapi-0.1.2.tgz`,解包成目录,再 `magpie plugin add <那个目录>` ——
28
+ `fish-under-sea-magpie-dragonapi-0.1.4.tgz`,解包成目录,再 `magpie plugin add <那个目录>` ——
29
29
  `plugin add` 认 `path`,和从文件夹加插件是同一条路。
30
30
 
31
31
  装好后:Settings → Plugins 里出现 **DragonAPI** 行(带一张页面),供应商列表里出现 **DragonAPI**。
@@ -88,7 +88,7 @@ NearToken 那套「页面里点充值、点连接」依赖两个本站没有的
88
88
 
89
89
  | 页 | 内容 |
90
90
  | --- | --- |
91
- | **模型广场** | 122 个模型 / 195 行「分组 × 模型」,按分组、类别、关键词筛选。**纯展示,没有启用/停用开关**——本站做不到 NearToken 那种按分组启停,所以这里不给假开关 |
91
+ | **模型广场** | 左侧分组筛选(14 组,带倍率与数量)、右侧双列卡片网格:每张卡给出名称/厂商/说明/计费方式/输入·输出·缓存价/分组倍率/端点数。**纯展示,没有启用/停用开关**——本站做不到 NearToken 那种按分组启停,所以这里不给假开关,也不伪造健康度数据 |
92
92
  | **余额与用量** | 每个账号的余额与已用;按天/周/月汇总;逐条流水(模型、token、费用、吞吐、首字延迟) |
93
93
  | **密钥** | 列出现有钥匙(打码)、按分组建新钥匙、建完显示一次完整明文并提供复制、删除、查看完整明文 |
94
94
  | **访问令牌** | 填入/清除 PAT,说明需要哪些权限 |
package/index.mjs CHANGED
@@ -119,8 +119,16 @@ export default async function dragonapi(input, options) {
119
119
  void input
120
120
  const ctx = makeContext(input, options)
121
121
 
122
- // 先把站点参数与目录拉起来:冷启动时宿主很快就要模型表。
123
- await Promise.all([ctx.status.get({}), ctx.catalog.get({})])
122
+ // 预热目录与站点参数,但**绝不等它**。
123
+ //
124
+ // 宿主的插件加载有 20 秒上限(实测报错:the plugin's load didn't finish in 20s)。
125
+ // 之前这里 `await Promise.all([...])` 等站点,网络一慢就把整个插件的加载拖死,
126
+ // 表现是插件行直接标「没有加载成功」——而服务其实已经起来了,页面还能开,
127
+ // 只是宿主判定它加载失败。这两件事的因果很容易看错。
128
+ //
129
+ // 预热只是省掉第一次 models() 的等待,失败了也不影响任何功能:
130
+ // models() 自己会取,而且它本来就允许慢。
131
+ void Promise.allSettled([ctx.status.get({}), ctx.catalog.get({})])
124
132
 
125
133
  // 本地服务:页面的真正宿主。起不来也不能让供应商消失,所以失败只记一笔。
126
134
  let service = null
package/lib/service.mjs CHANGED
@@ -30,6 +30,11 @@ import { loadState, saveState, maskKey, tailOf } from './store.mjs'
30
30
 
31
31
  const here = resolve(fileURLToPath(new URL('..', import.meta.url)))
32
32
 
33
+ /** 插件版本,从 package.json 读一次。 */
34
+ const PKG_VERSION = (() => {
35
+ try { return JSON.parse(readFileSync(join(here, 'package.json'), 'utf8')).version || '0.0.0' } catch { return '0.0.0' }
36
+ })()
37
+
33
38
  /** MIME 表只覆盖本插件真正会发的类型。 */
34
39
  const MIME = {
35
40
  '.html': 'text/html; charset=utf-8',
@@ -42,15 +47,30 @@ const MIME = {
42
47
  '.woff2': 'font/woff2',
43
48
  }
44
49
 
45
- /** 一次响应:JSON + CORS + 不缓存(页面是活的,缓存只会让人看到旧数据)。 */
50
+ /**
51
+ * 一次响应:JSON + CORS + 不缓存(页面是活的,缓存只会让人看到旧数据)。
52
+ *
53
+ * 三个 CORS 头都是必需的,少一个页面就「连不上本地服务」:
54
+ *
55
+ * Access-Control-Allow-Origin: * 页面是不透明源(Origin: null)
56
+ * Access-Control-Allow-Private-Network: true 页面在不透明源里请求 127.0.0.1,
57
+ * Chrome 会按 Private Network Access 先发预检;不放行就整个请求被拦,
58
+ * 而且报错长得像「网络不可达」,极难查。
59
+ * Access-Control-Allow-Headers / Methods 预检要过的头与方法
60
+ */
61
+ const CORS = {
62
+ 'access-control-allow-origin': '*',
63
+ 'access-control-allow-private-network': 'true',
64
+ 'access-control-allow-headers': 'content-type',
65
+ 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
66
+ }
67
+
46
68
  function json(res, code, body) {
47
69
  const data = JSON.stringify(body)
48
70
  res.writeHead(code, {
49
71
  'content-type': 'application/json; charset=utf-8',
50
72
  'content-length': Buffer.byteLength(data),
51
- 'access-control-allow-origin': '*',
52
- 'access-control-allow-headers': 'content-type',
53
- 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
73
+ ...CORS,
54
74
  'cache-control': 'no-store',
55
75
  })
56
76
  res.end(data)
@@ -101,7 +121,7 @@ function serveFile(res, root, rel) {
101
121
  res.writeHead(200, {
102
122
  'content-type': MIME[extname(file).toLowerCase()] || 'application/octet-stream',
103
123
  'content-length': body.length,
104
- 'access-control-allow-origin': '*',
124
+ ...CORS,
105
125
  'cache-control': 'no-cache',
106
126
  'x-content-type-options': 'nosniff',
107
127
  'referrer-policy': 'no-referrer',
@@ -151,14 +171,21 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
151
171
  async function handler(req, res) {
152
172
  const url = new URL(req.url || '/', 'http://127.0.0.1')
153
173
  const path = url.pathname
174
+ // 排查用:设 DRAGONAPI_DEBUG=1 时把每条请求打到 stderr。
175
+ // 插件页「连不上」时分不清「请求没到」还是「到了但响应不对」,这一行能分开。
176
+ if (process.env.DRAGONAPI_DEBUG) {
177
+ console.error(`[dragonapi] ${req.method} ${path} origin=${req.headers.origin || '-'} pna=${req.headers['access-control-request-private-network'] || '-'}`)
178
+ }
154
179
 
155
- // 预检:浏览器的 fetch 带自定义头时会先问一次。
180
+ // 预检:浏览器的 fetch 带自定义头、或不透明源访问 loopback 时会先问一次。
156
181
  if (req.method === 'OPTIONS') {
157
182
  res.writeHead(204, {
158
- 'access-control-allow-origin': '*',
159
- 'access-control-allow-headers': 'content-type',
160
- 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
183
+ ...CORS,
184
+ // 允许预检结果缓存,省掉每个请求一次往返。
161
185
  'access-control-max-age': '600',
186
+ // PNA 的预检请求会带 Access-Control-Request-Private-Network,
187
+ // 响应必须有 allow-private-network(CORS 里已含),否则整个请求被拦。
188
+ 'cache-control': 'no-store',
162
189
  })
163
190
  res.end()
164
191
  return
@@ -189,7 +216,9 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
189
216
  // ---- API ----
190
217
  try {
191
218
  if (path === '/api/ping' && req.method === 'GET') {
192
- json(res, 200, { ok: true, version: '0.1.0', port })
219
+ // 版本从 package.json 读,别硬编码:硬编码的版本号会在升级后说谎,
220
+ // 排查时容易把「旧代码还在跑」误判成「新版没修」。
221
+ json(res, 200, { ok: true, version: PKG_VERSION, port })
193
222
  return
194
223
  }
195
224
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fish-under-sea/magpie-dragonapi",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "DragonAPI for magpie: a provider plugin whose models, groups and prices come from the site's public /api/pricing, with balance and per-call usage from an sk- key, plus a local page that lists the market (read-only), shows usage and can mint new keys for a group.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
package/page/boot.js CHANGED
@@ -68,8 +68,12 @@
68
68
  }
69
69
 
70
70
  if (service) {
71
+ // 必须以 `/` 结尾再拼 query。magpie web 给的地址形如
72
+ // `http://host/_magpie/service/<token>`,少了结尾斜杠时,界面里的
73
+ // 相对/目录解析会把 token 当成文件名丢掉,接口就全打到别处。
74
+ const base = service.endsWith('/') ? service : service + '/'
71
75
  armTimeout(port)
72
- location.replace(service + '?' + q.toString())
76
+ location.replace(base + '?' + q.toString())
73
77
  return
74
78
  }
75
79
 
package/ui/app.js CHANGED
@@ -156,6 +156,38 @@ function initTheme() {
156
156
 
157
157
  // ── 请求层 ────────────────────────────────────────────────
158
158
 
159
+ /**
160
+ * API 基址:必须是绝对地址。
161
+ *
162
+ * 页面跑在 magpie 的 `sandbox="allow-scripts"` iframe 里,安全源是**不透明**
163
+ * 的(`self.origin === "null"`,localStorage / cookie 都会抛 SecurityError)。
164
+ * 在这种文档里,`fetch('/api/ping')` 这种相对路径会被 Chrome 直接判
165
+ * `TypeError: Failed to fetch`——绝对地址却正常。实测对比:
166
+ *
167
+ * 相对 path → TypeError: Failed to fetch
168
+ * 绝对 URL → 200
169
+ *
170
+ * 所以这里把「当前文档所在目录」算成基址:
171
+ * - 直接访问服务(http://127.0.0.1:3517/) → http://127.0.0.1:3517/
172
+ * - 经 magpie web 代理(…/_magpie/service/<tok>/)→ 保留那段前缀
173
+ * 不能直接用 location.origin:不透明文档里它可能报出真实源,也可能报 "null",
174
+ * 两种情况都要能工作,所以从 href 里解析并保留 pathname 的目录部分。
175
+ */
176
+ const API_BASE = (() => {
177
+ try {
178
+ const u = new URL(location.href);
179
+ const dir = u.pathname.replace(/[^/]*$/, ''); // 去掉文件名,保留目录
180
+ return u.origin + dir;
181
+ } catch {
182
+ return '/';
183
+ }
184
+ })();
185
+
186
+ /** apiUrl 把接口路径拼成绝对地址。传进来的 path 以 / 开头。 */
187
+ function apiUrl(path) {
188
+ return API_BASE.replace(/\/+$/, '') + path;
189
+ }
190
+
159
191
  class ApiError extends Error {
160
192
  constructor(message, status, payload) {
161
193
  super(message);
@@ -168,7 +200,7 @@ class ApiError extends Error {
168
200
  async function request(path, { method = 'GET', body } = {}) {
169
201
  let res;
170
202
  try {
171
- res = await fetch(path, {
203
+ res = await fetch(apiUrl(path), {
172
204
  method,
173
205
  credentials: 'omit', // opaque origin:带凭据必被拒
174
206
  cache: 'no-store', // 服务端已经自己缓存目录,浏览器别再叠一层
@@ -517,6 +549,7 @@ function renderCatalog() {
517
549
  const groupMap = new Map(groups.map((g) => [g.id, g]));
518
550
 
519
551
  renderGroupChips(groups, models);
552
+ renderKindChips(models);
520
553
 
521
554
  const counts = catalogCounts(data);
522
555
  const query = filters.q.trim().toLowerCase();
@@ -524,31 +557,67 @@ function renderCatalog() {
524
557
  if (filters.group && m.group !== filters.group) return false;
525
558
  if (filters.kind && m.kind !== filters.kind) return false;
526
559
  if (!query) return true;
527
- const hay = [m.name, m.id, m.group, m.vendor, m.description, m.tags].filter(Boolean).join(' ').toLowerCase();
560
+ const hay = [m.name, m.id, m.group, m.vendor, m.description, m.tags, ...(m.endpoints || [])]
561
+ .filter(Boolean).join(' ').toLowerCase();
528
562
  return hay.includes(query);
529
563
  });
530
564
 
531
- meta.replaceChildren(
532
- h('span', { class: 'stat' }, h('b', { text: fmtInt(counts.models) }), '个模型'),
533
- h('span', { class: 'stat' }, h('b', { text: fmtInt(counts.rows) }), '行'),
534
- h('span', { class: 'stat' }, h('b', { text: fmtInt(counts.groups) }), '个分组'),
535
- h('span', { class: 'spacer' }),
536
- h('span', {
537
- class: 'muted',
538
- text: `当前显示 ${fmtInt(rows.length)} 行 · 来源 ${SOURCE_LABEL[data.source] || data.source || '未知'} · 更新于 ${fmtAt(data.at)}`,
539
- }),
540
- );
565
+ if (meta) {
566
+ meta.replaceChildren(
567
+ h('b', { text: fmtInt(rows.length) }),
568
+ h('span', { text: ` 个模型 · 全站 ${fmtInt(counts.models)} 个 / ${fmtInt(counts.rows)} 行 / ${fmtInt(counts.groups)} 个分组` }),
569
+ h('span', { class: 'spacer' }),
570
+ h('span', {
571
+ class: 'muted',
572
+ text: `来源 ${SOURCE_LABEL[data.source] || data.source || '未知'} · 更新于 ${fmtAt(data.at)}`,
573
+ }),
574
+ );
575
+ }
541
576
 
542
577
  if (!rows.length) {
543
578
  body.replaceChildren(h('div', { class: 'empty', text: '没有符合条件的模型。放宽分组或搜索词再试。' }));
544
579
  return;
545
580
  }
546
581
 
547
- const tableRows = rows.map((m) => catalogRow(m, groupMap));
548
- body.replaceChildren(tableEl(
549
- ['模型名', '分组', '倍率', '输入价', '输出价', '缓存价', '端点', '说明'],
550
- tableRows,
551
- ));
582
+ body.replaceChildren(...rows.map((m) => modelCard(m, groupMap)));
583
+ }
584
+
585
+ /** 类型筛选:分组之外的第二维,直接做成 chip,比下拉更省一次点击。 */
586
+ function renderKindChips(models) {
587
+ const host = $('#kind-chips');
588
+ if (!host) return;
589
+
590
+ const counts = new Map();
591
+ for (const m of models) {
592
+ const k = m.kind || 'chat';
593
+ counts.set(k, (counts.get(k) || 0) + 1);
594
+ }
595
+
596
+ const order = ['chat', 'image', 'video', 'audio', 'embedding'];
597
+ const kinds = [...counts.keys()].sort((a, b) => {
598
+ const ia = order.indexOf(a);
599
+ const ib = order.indexOf(b);
600
+ return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib);
601
+ });
602
+
603
+ const chips = [h('button', {
604
+ class: 'market-chip', type: 'button',
605
+ 'aria-pressed': String(filters.kind === ''),
606
+ onclick: () => { filters.kind = ''; renderCatalog(); },
607
+ }, '全部')];
608
+
609
+ for (const k of kinds) {
610
+ chips.push(h('button', {
611
+ class: 'market-chip', type: 'button',
612
+ 'aria-pressed': String(filters.kind === k),
613
+ onclick: () => {
614
+ filters.kind = filters.kind === k ? '' : k;
615
+ renderCatalog();
616
+ },
617
+ }, KIND_LABEL[k] || k, h('span', { class: 'chip-count', text: String(counts.get(k) || 0) })));
618
+ }
619
+
620
+ host.replaceChildren(...chips);
552
621
  }
553
622
 
554
623
  function renderGroupChips(groups, models) {
@@ -560,112 +629,136 @@ function renderGroupChips(groups, models) {
560
629
 
561
630
  const chips = [
562
631
  h('button', {
563
- class: 'chip', type: 'button',
632
+ class: 'market-chip', type: 'button',
564
633
  'aria-pressed': String(filters.group === ''),
565
634
  onclick: () => { filters.group = ''; renderCatalog(); },
566
635
  }, '全部', h('span', { class: 'chip-count', text: String(models.length) })),
567
636
  ];
568
637
 
569
638
  for (const g of groups) {
639
+ const ratio = g.ratio != null && Number(g.ratio) > 0 ? `×${fmtRatio(g.ratio)}` : '';
570
640
  chips.push(h('button', {
571
- class: 'chip', type: 'button',
641
+ class: 'market-chip', type: 'button',
572
642
  'aria-pressed': String(filters.group === g.id),
573
643
  title: [
574
- g.auto ? 'auto 分组:费率取决于实际命中的通道' : (g.ratio != null ? `分组倍率 ${g.ratio}×` : ''),
644
+ g.auto ? '该分组费率取决于实际命中的通道,站点没有给固定倍率' : (ratio ? `分组倍率 ${ratio}` : ''),
575
645
  g.note || '',
576
646
  ].filter(Boolean).join(' · '),
577
647
  onclick: () => {
578
648
  filters.group = filters.group === g.id ? '' : g.id;
579
649
  renderCatalog();
580
650
  },
581
- }, g.id, h('span', { class: 'chip-count', text: String(counts.get(g.id) || g.models || 0) })));
651
+ },
652
+ h('span', { class: 'chip-name', text: g.id }),
653
+ ratio ? h('span', { class: 'ratio', text: ratio }) : null,
654
+ h('span', { class: 'chip-count', text: String(counts.get(g.id) || g.models || 0) })));
582
655
  }
583
656
 
584
657
  host.replaceChildren(...chips);
585
658
  }
586
659
 
587
- function catalogRow(m, groupMap) {
660
+ /**
661
+ * 一张模型卡。
662
+ *
663
+ * 结构照 NearToken 的模型广场:名称/厂商 → 描述 → 计费方式 → 价格 → 分组
664
+ * → 端点 → 详情。等高靠三件事:外层 `.model-grid` 的 `align-items: stretch`、
665
+ * 卡片自身 `display:flex; flex-direction:column`、以及尾部 `margin-top:auto`
666
+ * 把「详情」按到底。任何一项缺失,同一行卡片就会参差。
667
+ *
668
+ * 刻意没照搬的两处:
669
+ * 1. NearToken 的卡片有「已启用/未启用」开关。我们按既定要求做成纯展示,
670
+ * 不给假开关——本站做不到按模型启停。
671
+ * 2. 它有实时健康度(延迟、吞吐、成功率条)。我们没有这些数据,
672
+ * 编一个出来比留白更糟,所以那个位置换成上下文长度与计费档位。
673
+ */
674
+ function modelCard(m, groupMap) {
588
675
  const info = groupMap.get(m.group);
589
676
  const isAuto = m.group === 'auto' || (info && info.auto === true);
590
677
  const pricing = m.pricing || {};
591
678
  const priceKind = pricing.kind || 'unknown';
592
679
  const ratio = m.groupRatio != null ? m.groupRatio : (info ? info.ratio : null);
680
+ const kind = m.kind || 'chat';
681
+ const endpoints = Array.isArray(m.endpoints) ? m.endpoints : [];
593
682
 
594
- const nameCell = h('td', { class: 'col-name' },
595
- h('button', {
596
- class: 'name-btn', type: 'button',
597
- title: '查看这个模型的计费表达式与分档',
598
- onclick: () => openModelDrawer(m),
599
- }, m.name || m.id || '未命名'),
600
- m.vendor ? h('span', { class: 'vendor', text: m.vendor }) : null,
601
- );
602
-
603
- const cells = [
604
- nameCell,
605
- { text: m.group || '—', cls: 'mono' },
606
- {
607
- text: ratio == null ? '—' : fmtRatio(ratio),
608
- cls: 'num',
609
- title: isAuto ? 'auto 分组没有固定倍率,按实际命中通道计费' : (ratio != null ? `分组倍率 ${ratio}×` : '站点没有给出倍率'),
610
- },
611
- ];
683
+ // 计费方式的说法要跟价格表一致:按次/按秒只给一列,别硬凑出「输出价 —」。
684
+ let billing = { cls: 'flat', label: '倍率计费' };
685
+ if (isAuto) billing = { cls: 'auto', label: '以实际命中通道为准' };
686
+ else if (priceKind === 'unknown') billing = { cls: 'unknown', label: '价格未知' };
687
+ else if (priceKind === 'percall') {
688
+ billing = { cls: 'call', label: /\/秒/.test(pricing.input || '') ? '按秒计费' : '按次计费' };
689
+ } else if (priceKind === 'tiered') billing = { cls: 'dyn', label: '分档计费' };
612
690
 
613
- // 价格三列:auto 与 unknown 都用一格跨三列,避免三格重复同一句提示。
691
+ let priceCells;
614
692
  if (isAuto) {
615
- cells.push({ node: h('td', {
616
- colspan: 3, class: 'muted price-merged',
617
- title: 'auto 分组没有固定倍率,实际费率取决于命中的通道',
618
- }, '以实际命中通道为准') });
693
+ priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { class: 'muted', text: '—' }))];
619
694
  } else if (priceKind === 'unknown') {
620
- cells.push({ node: h('td', {
621
- colspan: 3, class: 'unknown price-merged',
622
- title: pricing.note || '站点没有给出可解析的价格',
623
- }, '价格未知') });
695
+ priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { class: 'unknown', text: '价格未知' }))];
696
+ } else if (priceKind === 'percall') {
697
+ priceCells = [h('div', { class: 'wide' }, h('span', { text: '单价' }), h('b', { text: pricing.input || '—' }))];
624
698
  } else {
625
- cells.push(
626
- { text: pricing.input || '—', cls: 'num', title: pricing.note || null },
627
- { text: pricing.output || '—', cls: 'num', title: pricing.note || null },
628
- { text: pricing.cache || '—', cls: 'num', title: pricing.note || null },
629
- );
630
- }
699
+ priceCells = [
700
+ h('div', null, h('span', { text: '输入' }), h('b', { text: pricing.input || '—' })),
701
+ h('div', null, h('span', { text: '输出' }), h('b', { text: pricing.output || '—' })),
702
+ h('div', null, h('span', { text: '缓存读取' }), h('b', { text: pricing.cache || '—' })),
703
+ ];
704
+ }
705
+
706
+ const desc = m.description || '';
707
+ const titleBits = [
708
+ desc,
709
+ m.tags ? `标签:${m.tags}` : '',
710
+ pricing.note || '',
711
+ m.context ? `上下文 ${fmtInt(m.context)}` : '',
712
+ `模型 id:${m.id || ''}`,
713
+ ].filter(Boolean).join('\n');
714
+
715
+ return h('article', { class: `mc mc-${kind}`, title: titleBits },
716
+ h('div', { class: 'mc-head' },
717
+ h('div', { class: 'grow' },
718
+ h('button', {
719
+ class: 'mc-name', type: 'button',
720
+ title: '查看这个模型的计费表达式与分档',
721
+ onclick: () => openModelDrawer(m),
722
+ }, m.name || m.id || '未命名'),
723
+ m.vendor ? h('div', { class: 'mc-vendor', text: m.vendor }) : null),
724
+ h('span', { class: 'mc-kind', text: KIND_LABEL[kind] || kind })),
631
725
 
632
- const endpoints = Array.isArray(m.endpoints) ? m.endpoints : [];
633
- cells.push({
634
- node: h('td', null, endpoints.length
635
- ? h('span', { class: 'ep-list' }, endpoints.map((e) => h('span', { class: 'ep', text: e })))
636
- : h('span', { class: 'muted', text: '—' })),
637
- });
726
+ h('p', { class: desc ? 'mc-desc' : 'mc-desc is-empty', text: desc || '站点没有提供说明' }),
638
727
 
639
- const desc = m.description || m.tags || '';
640
- cells.push({
641
- text: desc || '—',
642
- cls: 'col-desc',
643
- title: [desc, m.tags ? `tags: ${m.tags}` : '', pricing.note || '', m.context ? `上下文 ${fmtInt(m.context)}` : '']
644
- .filter(Boolean).join('\n'),
645
- });
728
+ h('div', { class: `mc-billing ${billing.cls}`, text: billing.label }),
729
+
730
+ h('div', { class: priceKind === 'percall' || priceKind === 'unknown' || isAuto ? 'mc-prices one' : 'mc-prices' }, priceCells),
731
+
732
+ h('div', { class: 'mc-line' },
733
+ h('span', { class: 'k', text: '分组' }),
734
+ h('span', { class: 'mc-group', text: m.group || '—' }),
735
+ ratio != null && Number(ratio) > 0 ? h('span', { class: 'mc-ratio', text: `×${fmtRatio(ratio)}` }) : null),
736
+
737
+ h('div', { class: 'mc-line' },
738
+ h('span', { class: 'k', text: '端点' }),
739
+ endpoints.length
740
+ ? h('span', { class: 'mc-ends' }, endpoints.map((e) => h('span', { class: 'mc-end', text: e })))
741
+ : h('span', { class: 'muted', text: '—' })),
646
742
 
647
- return cells;
743
+ h('div', { class: 'mc-foot' },
744
+ h('button', { class: 'link', type: 'button', onclick: () => openModelDrawer(m) }, '详情')));
648
745
  }
649
746
 
650
747
  function bindCatalogControls() {
651
748
  const search = $('#catalog-search');
652
- const kind = $('#catalog-kind');
653
749
  const reset = $('#catalog-reset');
654
750
 
655
751
  search.addEventListener('input', () => {
656
752
  filters.q = search.value;
657
753
  if (cache.catalog) renderCatalog();
658
754
  });
659
- kind.addEventListener('change', () => {
660
- filters.kind = kind.value;
661
- if (cache.catalog) renderCatalog();
662
- });
755
+
756
+ // 类型筛选现在是 aside 里的 chip(renderKindChips),不再是一个 select。
663
757
  reset.addEventListener('click', () => {
664
758
  filters.group = '';
665
759
  filters.kind = '';
666
760
  filters.q = '';
667
761
  search.value = '';
668
- kind.value = '';
669
762
  if (cache.catalog) renderCatalog();
670
763
  search.focus();
671
764
  });
@@ -890,11 +983,25 @@ async function loadKeys(force = false) {
890
983
  try {
891
984
  const data = await api.keys();
892
985
  cache.keys = data;
986
+ cache.keysNeedPat = false;
893
987
  clearBanner('keys');
894
988
  renderKeys();
895
989
  return data;
896
990
  } catch (err) {
897
991
  const msg = describeError(err);
992
+ // 「还没设 PAT」是刚装好时的正常状态,不是错误。这里不该甩红条,
993
+ // 该直接告诉他下一步做什么——否则第一次打开就像插件坏了。
994
+ const needPat = err instanceof ApiError && err.status === 400 && /访问令牌/.test(msg);
995
+ if (needPat) {
996
+ cache.keysNeedPat = true;
997
+ cache.keysError = '';
998
+ clearBanner('keys');
999
+ renderKeys();
1000
+ renderKeyGroupOptions();
1001
+ return null;
1002
+ }
1003
+ cache.keysNeedPat = false;
1004
+ cache.keysError = msg;
898
1005
  banner('error', `读取钥匙列表失败:${msg}`, { key: 'keys' });
899
1006
  regionError($('#keys-body'), `钥匙列表没读到:${msg}`, () => loadKeys(true));
900
1007
  renderKeyGroupOptions();
@@ -956,6 +1063,17 @@ function renderKeys() {
956
1063
  }
957
1064
 
958
1065
  if (!cache.keys) {
1066
+ if (cache.keysNeedPat) {
1067
+ // 首次打开、还没设 PAT:给一条通往「访问令牌」页的路,而不是报错。
1068
+ box.replaceChildren(h('div', { class: 'empty guide' },
1069
+ h('p', { text: '还没设置访问令牌(PAT),所以读不到钥匙列表,也不能建钥匙。' }),
1070
+ h('p', { class: 'muted', text: 'PAT 只能在浏览器里登录控制台后创建:头像 → 安全 → 访问令牌,勾上 profile:read、api_key:read、api_key:write。' }),
1071
+ h('button', {
1072
+ class: 'btn primary', type: 'button',
1073
+ onclick: () => activateTab('pat', { focus: true }),
1074
+ }, '去设置访问令牌')));
1075
+ return;
1076
+ }
959
1077
  if (!loading.keys) regionLoading(box, '正在读取钥匙列表');
960
1078
  return;
961
1079
  }