@fish-under-sea/magpie-dragonapi 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +140 -2
- package/index.mjs +452 -0
- package/lib/catalog-source.mjs +87 -0
- package/lib/catalog.mjs +200 -0
- package/lib/pricing.mjs +256 -0
- package/lib/service.mjs +498 -0
- package/lib/site.mjs +301 -0
- package/lib/status-source.mjs +44 -0
- package/lib/store.mjs +86 -0
- package/lib/usage.mjs +202 -0
- package/package.json +65 -4
- package/page/boot.js +112 -0
- package/page/icon.svg +12 -0
- package/page/index.html +32 -0
- package/serve.mjs +110 -0
- package/ui/app.js +1722 -0
- package/ui/index.html +259 -0
- package/ui/style.css +968 -0
package/ui/app.js
ADDED
|
@@ -0,0 +1,1722 @@
|
|
|
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
|
+
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
// ── DOM 小工具 ─────────────────────────────────────────────
|
|
17
|
+
|
|
18
|
+
const $ = (sel, root = document) => root.querySelector(sel);
|
|
19
|
+
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 轻量建元素:只做本文件需要的那几种属性,避免到处写 setAttribute。
|
|
23
|
+
* 数据一律走 textContent(不接受 html 字符串),防止站点返回的文本变成标记。
|
|
24
|
+
*/
|
|
25
|
+
function h(tag, props, ...kids) {
|
|
26
|
+
const node = document.createElement(tag);
|
|
27
|
+
if (props && typeof props === 'object' && !(props instanceof Node) && !Array.isArray(props)) {
|
|
28
|
+
for (const [key, val] of Object.entries(props)) {
|
|
29
|
+
if (val === null || val === undefined || val === false) continue;
|
|
30
|
+
if (key === 'class') node.className = val;
|
|
31
|
+
else if (key === 'text') node.textContent = String(val);
|
|
32
|
+
else if (key === 'dataset') Object.assign(node.dataset, val);
|
|
33
|
+
else if (key === 'value') node.value = val;
|
|
34
|
+
else if (key === 'checked') node.checked = Boolean(val);
|
|
35
|
+
else if (key === 'disabled') node.disabled = Boolean(val);
|
|
36
|
+
else if (key.startsWith('on') && typeof val === 'function') {
|
|
37
|
+
node.addEventListener(key.slice(2).toLowerCase(), val);
|
|
38
|
+
} else node.setAttribute(key, val === true ? '' : String(val));
|
|
39
|
+
}
|
|
40
|
+
} else if (props !== null && props !== undefined && props !== false) {
|
|
41
|
+
kids.unshift(props);
|
|
42
|
+
}
|
|
43
|
+
append(node, ...kids);
|
|
44
|
+
return node;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function append(parent, ...kids) {
|
|
48
|
+
for (const kid of kids) {
|
|
49
|
+
if (kid === null || kid === undefined || kid === false || kid === true) continue;
|
|
50
|
+
if (Array.isArray(kid)) { append(parent, ...kid); continue; }
|
|
51
|
+
parent.append(kid instanceof Node ? kid : document.createTextNode(String(kid)));
|
|
52
|
+
}
|
|
53
|
+
return parent;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 通用表格:headers 为字符串或 {label, cls},rows 为单元格描述或现成的 <tr>。 */
|
|
57
|
+
function tableEl(headers, rows, { empty = '没有数据', tableClass = 'data-table' } = {}) {
|
|
58
|
+
if (!rows || rows.length === 0) return h('div', { class: 'empty', text: empty });
|
|
59
|
+
const thead = h('thead', null, h('tr', null, headers.map((hd) => {
|
|
60
|
+
const spec = typeof hd === 'string' ? { label: hd } : hd;
|
|
61
|
+
return h('th', { scope: 'col', class: spec.cls || null }, spec.label);
|
|
62
|
+
})));
|
|
63
|
+
const tbody = h('tbody');
|
|
64
|
+
for (const row of rows) {
|
|
65
|
+
if (row instanceof Node) { tbody.append(row); continue; }
|
|
66
|
+
const tr = h('tr');
|
|
67
|
+
for (const cell of row) {
|
|
68
|
+
if (cell instanceof Node) { tr.append(cell); continue; }
|
|
69
|
+
const spec = cell || {};
|
|
70
|
+
// 有些单元格要跨列(价格未知 / auto 分组),直接给现成的 <td>
|
|
71
|
+
if (spec.node instanceof Node) { tr.append(spec.node); continue; }
|
|
72
|
+
tr.append(h('td', { class: spec.cls || null, title: spec.title || null }, spec.text ?? ''));
|
|
73
|
+
}
|
|
74
|
+
tbody.append(tr);
|
|
75
|
+
}
|
|
76
|
+
const wrap = h('div', { class: 'table-wrap' }, h('table', { class: tableClass }, thead, tbody));
|
|
77
|
+
// 窄屏时表格会横向溢出,但滚动条在触屏上不可见——不加提示的话,用户
|
|
78
|
+
// 会以为输入价/输出价/说明那几列不存在。
|
|
79
|
+
//
|
|
80
|
+
// 提示必须放在表格**上方**:放下面的话,195 行的表格得滚到底才看见,
|
|
81
|
+
// 等于没提示。也不能放进滚动容器里(::after),那会跟着内容一起滚。
|
|
82
|
+
const hint = h('p', { class: 'scroll-hint', 'data-overflow': '0', text: '← 左右滑动看完整列 →' });
|
|
83
|
+
markOverflow(wrap, hint);
|
|
84
|
+
return h('div', null, hint, wrap);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* markOverflow 在表格渲染后判断是否真的溢出,只有溢出才显示提示。
|
|
89
|
+
*
|
|
90
|
+
* 判两次:插入 DOM 后立刻判一次(多数情况下布局已经算好了),再在下一帧
|
|
91
|
+
* 复核一次(字体加载完、图片撑开等会让宽度变化)。只靠 rAF 的话,无头截图
|
|
92
|
+
* 或虚拟时间预算下可能还没跑到,提示就不出现。
|
|
93
|
+
*/
|
|
94
|
+
function markOverflow(wrap, hint) {
|
|
95
|
+
const check = () => {
|
|
96
|
+
if (!wrap.isConnected) return;
|
|
97
|
+
// +2 是给亚像素留的余量,避免「差 1px」也提示
|
|
98
|
+
hint.dataset.overflow = wrap.scrollWidth > wrap.clientWidth + 2 ? '1' : '0';
|
|
99
|
+
};
|
|
100
|
+
check();
|
|
101
|
+
if (typeof requestAnimationFrame === 'function') requestAnimationFrame(check);
|
|
102
|
+
else setTimeout(check, 0);
|
|
103
|
+
// 窗口变宽变窄都要重判,否则转屏后提示会留在屏幕上
|
|
104
|
+
window.addEventListener('resize', check, { passive: true });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function regionLoading(node, text) {
|
|
108
|
+
node.replaceChildren(h('p', { class: 'loading', text }));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function regionError(node, message, retry) {
|
|
112
|
+
node.replaceChildren(h('div', { class: 'region-error' },
|
|
113
|
+
h('p', { class: 'region-error-text', text: message }),
|
|
114
|
+
retry ? h('button', { class: 'btn ghost', type: 'button', onclick: retry }, '重试') : null,
|
|
115
|
+
));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ── 主题:URL 上的 ?theme / ?tokens ────────────────────────
|
|
119
|
+
|
|
120
|
+
/** 兜底色板:tokens 缺失或损坏时页面也得能看,不能白底白字。 */
|
|
121
|
+
const FALLBACK = {
|
|
122
|
+
dark: { bg: '#14161b', fg: '#e7e9ee', muted: '#9aa1ae', accent: '#5b8def' },
|
|
123
|
+
light: { bg: '#f7f8fa', fg: '#1b1f27', muted: '#5f6672', accent: '#3b5bdb' },
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
function initTheme() {
|
|
127
|
+
const params = new URLSearchParams(location.search);
|
|
128
|
+
const asked = params.get('theme');
|
|
129
|
+
const mode = asked === 'dark' || asked === 'light'
|
|
130
|
+
? asked
|
|
131
|
+
: (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
|
132
|
+
|
|
133
|
+
const root = document.documentElement;
|
|
134
|
+
root.dataset.theme = mode;
|
|
135
|
+
// 先铺兜底色,再让 magpie 注入的 token 覆盖;顺序反了会出现「只注入了 bg」的花屏。
|
|
136
|
+
for (const [key, value] of Object.entries(FALLBACK[mode])) root.style.setProperty('--' + key, value);
|
|
137
|
+
|
|
138
|
+
const raw = params.get('tokens');
|
|
139
|
+
if (raw) {
|
|
140
|
+
try {
|
|
141
|
+
const tokens = JSON.parse(raw);
|
|
142
|
+
if (tokens && typeof tokens === 'object') {
|
|
143
|
+
for (const [key, value] of Object.entries(tokens)) {
|
|
144
|
+
if (typeof value !== 'string' || !value.trim()) continue;
|
|
145
|
+
root.style.setProperty('--' + String(key).replace(/^--/, ''), value.trim());
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
// tokens 是宿主拼出来的,坏了不该连累整页;保留兜底色即可。
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const meta = document.querySelector('meta[name="color-scheme"]');
|
|
154
|
+
if (meta) meta.setAttribute('content', mode === 'light' ? 'light dark' : 'dark light');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ── 请求层 ────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
class ApiError extends Error {
|
|
160
|
+
constructor(message, status, payload) {
|
|
161
|
+
super(message);
|
|
162
|
+
this.name = 'ApiError';
|
|
163
|
+
this.status = status;
|
|
164
|
+
this.payload = payload;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function request(path, { method = 'GET', body } = {}) {
|
|
169
|
+
let res;
|
|
170
|
+
try {
|
|
171
|
+
res = await fetch(path, {
|
|
172
|
+
method,
|
|
173
|
+
credentials: 'omit', // opaque origin:带凭据必被拒
|
|
174
|
+
cache: 'no-store', // 服务端已经自己缓存目录,浏览器别再叠一层
|
|
175
|
+
headers: body ? { 'content-type': 'application/json' } : undefined,
|
|
176
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
177
|
+
});
|
|
178
|
+
} catch (err) {
|
|
179
|
+
// 网络层失败(服务没起来 / 端口变了)统一成一句人话
|
|
180
|
+
throw new ApiError('连不上本地服务,插件可能已经退出,或端口被改了。', 0, null);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const text = await res.text();
|
|
184
|
+
let data = null;
|
|
185
|
+
if (text) {
|
|
186
|
+
try { data = JSON.parse(text); } catch { data = null; }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (!res.ok || (data && typeof data === 'object' && data.ok === false)) {
|
|
190
|
+
const reason = (data && (data.error || data.message)) || `请求失败(HTTP ${res.status})`;
|
|
191
|
+
throw new ApiError(reason, res.status, data);
|
|
192
|
+
}
|
|
193
|
+
if (data === null) {
|
|
194
|
+
throw new ApiError('服务返回的不是 JSON,这个端口上可能跑着别的服务。', res.status, null);
|
|
195
|
+
}
|
|
196
|
+
return data;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 把异常翻译成能直接给用户看的中文,别把 stack 抖到界面上。 */
|
|
200
|
+
function describeError(err) {
|
|
201
|
+
if (err instanceof ApiError) {
|
|
202
|
+
if (err.status === 401) return `PAT 无效或已过期:${err.message}`;
|
|
203
|
+
if (err.status === 403) return `权限不足:${err.message}`;
|
|
204
|
+
if (err.status === 404) return `接口不存在,页面与插件版本可能不一致:${err.message}`;
|
|
205
|
+
if (err.status === 429) return `请求太频繁,稍等一下再试:${err.message}`;
|
|
206
|
+
return err.message;
|
|
207
|
+
}
|
|
208
|
+
return (err && err.message) || '未知错误';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const api = {
|
|
212
|
+
ping: () => request('/api/ping'),
|
|
213
|
+
state: () => request('/api/state'),
|
|
214
|
+
savePat: (pat) => request('/api/pat', { method: 'POST', body: { pat } }),
|
|
215
|
+
clearPat: () => request('/api/pat', { method: 'DELETE' }),
|
|
216
|
+
catalog: (force) => request('/api/catalog' + (force ? '?refresh=1' : '')),
|
|
217
|
+
model: (group, name) => request(`/api/model?group=${encodeURIComponent(group)}&model=${encodeURIComponent(name)}`),
|
|
218
|
+
usage: (range) => request(`/api/usage?range=${encodeURIComponent(range)}`),
|
|
219
|
+
logs: (account) => request(`/api/logs?limit=200&account=${encodeURIComponent(account)}`),
|
|
220
|
+
keys: () => request('/api/keys'),
|
|
221
|
+
createKey: (body) => request('/api/keys', { method: 'POST', body }),
|
|
222
|
+
deleteKey: (id) => request(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE' }),
|
|
223
|
+
revealKey: (id) => request(`/api/keys/${encodeURIComponent(id)}/reveal`, { method: 'POST' }),
|
|
224
|
+
bindInfo: () => request('/api/bind-info'),
|
|
225
|
+
health: () => request('/api/health'),
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
// ── 提示条:所有失败都必须在界面上说话 ────────────────────
|
|
229
|
+
|
|
230
|
+
const banners = new Map();
|
|
231
|
+
|
|
232
|
+
function banner(tone, text, { key = 'b-' + Math.random().toString(36).slice(2), timeout = 0 } = {}) {
|
|
233
|
+
const host = $('#banners');
|
|
234
|
+
if (!host) return key;
|
|
235
|
+
|
|
236
|
+
let entry = banners.get(key);
|
|
237
|
+
if (!entry) {
|
|
238
|
+
const icon = h('span', { class: 'banner-icon', 'aria-hidden': 'true' });
|
|
239
|
+
const textEl = h('div', { class: 'banner-text' });
|
|
240
|
+
const el = h('div', { class: 'banner' }, icon, textEl,
|
|
241
|
+
h('button', {
|
|
242
|
+
class: 'banner-close', type: 'button', 'aria-label': '关闭这条提示',
|
|
243
|
+
onclick: () => clearBanner(key),
|
|
244
|
+
}, '×'));
|
|
245
|
+
entry = { el, icon, textEl, timer: 0 };
|
|
246
|
+
banners.set(key, entry);
|
|
247
|
+
host.append(el);
|
|
248
|
+
// 提示条不该越堆越长,最多留 6 条
|
|
249
|
+
while (host.children.length > 6) {
|
|
250
|
+
const first = host.firstElementChild;
|
|
251
|
+
const deadKey = [...banners.entries()].find(([, v]) => v.el === first);
|
|
252
|
+
if (deadKey) { if (deadKey[1].timer) clearTimeout(deadKey[1].timer); banners.delete(deadKey[0]); }
|
|
253
|
+
first.remove();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
entry.el.dataset.tone = tone;
|
|
258
|
+
entry.el.setAttribute('role', tone === 'error' ? 'alert' : 'status');
|
|
259
|
+
entry.icon.textContent = tone === 'error' ? '!' : tone === 'warn' ? '!' : tone === 'ok' ? '✓' : 'i';
|
|
260
|
+
entry.textEl.textContent = text;
|
|
261
|
+
|
|
262
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
263
|
+
if (timeout > 0) entry.timer = setTimeout(() => clearBanner(key), timeout);
|
|
264
|
+
return key;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function clearBanner(key) {
|
|
268
|
+
const entry = banners.get(key);
|
|
269
|
+
if (!entry) return;
|
|
270
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
271
|
+
entry.el.remove();
|
|
272
|
+
banners.delete(key);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ── 格式化 ────────────────────────────────────────────────
|
|
276
|
+
|
|
277
|
+
const RANGE_LABEL = { day: '日', week: '周', month: '月' };
|
|
278
|
+
const KIND_LABEL = { chat: '对话', image: '生图', video: '视频', audio: '音频', embedding: '向量' };
|
|
279
|
+
const SOURCE_LABEL = { live: '实时', cache: '缓存', snapshot: '快照' };
|
|
280
|
+
|
|
281
|
+
const dtf = new Intl.DateTimeFormat('zh-CN', {
|
|
282
|
+
month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false,
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
function fmtAt(ms) {
|
|
286
|
+
return Number.isFinite(ms) && ms > 0 ? dtf.format(new Date(ms)) : '—';
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function fmtInt(n) {
|
|
290
|
+
return Number.isFinite(n) ? n.toLocaleString('zh-CN') : '—';
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function fmtRatio(r) {
|
|
294
|
+
return Number.isFinite(r) ? `${r}×` : '—';
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** 把服务端给的原始 quota 折成站点币种;金额本身仍优先用服务端格式化好的字符串。 */
|
|
298
|
+
function moneyRaw(raw) {
|
|
299
|
+
if (!Number.isFinite(raw)) return '—';
|
|
300
|
+
const cur = cache.state && cache.state.currency;
|
|
301
|
+
if (!cur || cur.display === false) return fmtInt(raw);
|
|
302
|
+
const per = Number(cur.per) > 0 ? Number(cur.per) : 500000;
|
|
303
|
+
const rate = Number(cur.rate) > 0 ? Number(cur.rate) : 1;
|
|
304
|
+
const value = (raw / per) * rate;
|
|
305
|
+
const digits = Math.abs(value) >= 1 ? 2 : 4;
|
|
306
|
+
const shown = value.toFixed(digits).replace(/0+$/, '').replace(/\.$/, '');
|
|
307
|
+
return `${cur.symbol || '$'}${shown || '0'}`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** 币种金额 → 原始 quota,建钥匙填额度时用;与服务端 moneyRaw 的折算方向相反。 */
|
|
311
|
+
function rawFromMoney(amount) {
|
|
312
|
+
const cur = cache.state && cache.state.currency;
|
|
313
|
+
const per = cur && Number(cur.per) > 0 ? Number(cur.per) : 500000;
|
|
314
|
+
const rate = cur && Number(cur.rate) > 0 ? Number(cur.rate) : 1;
|
|
315
|
+
return Math.round((amount * per) / rate);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ── 全局状态(只放内存) ──────────────────────────────────
|
|
319
|
+
|
|
320
|
+
const cache = {
|
|
321
|
+
ping: null,
|
|
322
|
+
state: null,
|
|
323
|
+
stateError: '',
|
|
324
|
+
catalog: null,
|
|
325
|
+
keys: null,
|
|
326
|
+
bind: null,
|
|
327
|
+
health: null,
|
|
328
|
+
usage: {}, // range -> response
|
|
329
|
+
logs: {}, // account key -> rows[]
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
const loading = { state: false, catalog: false, keys: false, bind: false, health: false, usage: false, logs: false };
|
|
333
|
+
|
|
334
|
+
const filters = { group: '', kind: '', q: '', range: 'day', account: '' };
|
|
335
|
+
|
|
336
|
+
let activeTab = 'catalog';
|
|
337
|
+
|
|
338
|
+
// 页面内存里的临时物:完整钥匙只在这里出现一次
|
|
339
|
+
let lastSecret = null; // { key, bind }
|
|
340
|
+
const revealed = new Map(); // key id -> secret
|
|
341
|
+
let confirmDeleteId = null; // 正在二次确认删除的钥匙 id
|
|
342
|
+
|
|
343
|
+
// ── 顶部栏 ────────────────────────────────────────────────
|
|
344
|
+
|
|
345
|
+
function renderHeader() {
|
|
346
|
+
const dot = $('#conn-dot');
|
|
347
|
+
const text = $('#conn-text');
|
|
348
|
+
const pill = $('#conn-pill');
|
|
349
|
+
const st = cache.state;
|
|
350
|
+
|
|
351
|
+
if (!dot || !text || !pill) return;
|
|
352
|
+
|
|
353
|
+
let tone = 'busy';
|
|
354
|
+
let label = '连接中…';
|
|
355
|
+
let title = '';
|
|
356
|
+
|
|
357
|
+
if (cache.stateError) {
|
|
358
|
+
tone = 'bad';
|
|
359
|
+
label = '本地服务无响应';
|
|
360
|
+
title = cache.stateError;
|
|
361
|
+
} else if (st) {
|
|
362
|
+
const health = st.health || {};
|
|
363
|
+
if (health.ok) {
|
|
364
|
+
tone = 'ok';
|
|
365
|
+
label = health.source === 'live' ? '已连接' : `已连接 · ${SOURCE_LABEL[health.source] || health.source || '缓存'}`;
|
|
366
|
+
title = `${health.ms != null ? health.ms + ' ms' : '耗时未知'} · ${fmtAt(health.at)}`;
|
|
367
|
+
} else {
|
|
368
|
+
tone = 'warn';
|
|
369
|
+
label = '站点不可达';
|
|
370
|
+
title = '本地服务正常,但上游 DragonAPI 没有响应;目录可能来自缓存。';
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
dot.dataset.state = tone;
|
|
375
|
+
text.textContent = label;
|
|
376
|
+
pill.title = title || '本地服务与站点连接状态';
|
|
377
|
+
|
|
378
|
+
const currency = st && st.currency;
|
|
379
|
+
const curPill = $('#currency-pill');
|
|
380
|
+
if (curPill) {
|
|
381
|
+
curPill.textContent = currency
|
|
382
|
+
? `${currency.symbol || ''} ${currency.code || ''}`.trim() || '—'
|
|
383
|
+
: '—';
|
|
384
|
+
curPill.title = currency
|
|
385
|
+
? `站点币种 ${currency.code || ''}${currency.per ? ` · 1 单位 = ${currency.per} quota` : ''}`
|
|
386
|
+
: '站点币种';
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const site = st && st.site;
|
|
390
|
+
const link = $('#site-link');
|
|
391
|
+
if (link && site) {
|
|
392
|
+
link.href = site;
|
|
393
|
+
link.textContent = site.replace(/^https?:\/\//, '').replace(/\/$/, '');
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (st && cache.ping && cache.ping.version) {
|
|
397
|
+
pill.title = `${pill.title} · 插件 v${cache.ping.version}`;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function populateAccountSelect() {
|
|
402
|
+
const sel = $('#flow-account');
|
|
403
|
+
if (!sel) return;
|
|
404
|
+
const accounts = (cache.state && cache.state.accounts) || [];
|
|
405
|
+
const current = filters.account;
|
|
406
|
+
|
|
407
|
+
// 注意:replaceChildren 只吃 Node / string,数组必须展开,否则直接抛 TypeError
|
|
408
|
+
sel.replaceChildren(
|
|
409
|
+
h('option', { value: '', text: '全部账号' }),
|
|
410
|
+
...accounts.map((a) => h('option', { value: a.key, text: a.label || a.masked || a.key })),
|
|
411
|
+
);
|
|
412
|
+
|
|
413
|
+
if (current && accounts.some((a) => a.key === current)) sel.value = current;
|
|
414
|
+
else { sel.value = ''; filters.account = ''; }
|
|
415
|
+
sel.disabled = accounts.length === 0;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// ── 标签页切换 ────────────────────────────────────────────
|
|
419
|
+
|
|
420
|
+
function activateTab(name, { focus = false, force = false } = {}) {
|
|
421
|
+
const tab = $(`.tab[data-tab="${name}"]`);
|
|
422
|
+
if (!tab) return;
|
|
423
|
+
activeTab = name;
|
|
424
|
+
|
|
425
|
+
for (const btn of $$('.tab')) {
|
|
426
|
+
const on = btn === tab;
|
|
427
|
+
btn.setAttribute('aria-selected', String(on));
|
|
428
|
+
btn.tabIndex = on ? 0 : -1;
|
|
429
|
+
}
|
|
430
|
+
for (const panel of $$('.panel')) {
|
|
431
|
+
panel.hidden = panel.dataset.panel !== name;
|
|
432
|
+
}
|
|
433
|
+
if (focus) tab.focus();
|
|
434
|
+
|
|
435
|
+
// 离开密钥页就丢掉「只显示一次」的完整钥匙,避免它一直留在屏幕上
|
|
436
|
+
if (name !== 'keys' && lastSecret) {
|
|
437
|
+
lastSecret = null;
|
|
438
|
+
renderSecret();
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
ensureTab(name, force);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function ensureTab(name, force = false) {
|
|
445
|
+
if (name === 'catalog') return loadCatalog(force);
|
|
446
|
+
if (name === 'wallet') return loadWallet(force);
|
|
447
|
+
// 密钥页有两块独立内容:钥匙列表(要 PAT)与绑定说明(不需要)。
|
|
448
|
+
// 绑定说明必须一起拉,否则「怎么绑进 magpie」会永远停在加载中——
|
|
449
|
+
// 它只有 loadBind 里才会被填,而 loadBind 之前只在刷新按钮里被调到。
|
|
450
|
+
if (name === 'keys') return Promise.all([loadKeys(force), loadBind(force)]);
|
|
451
|
+
if (name === 'pat') return loadPat(force);
|
|
452
|
+
return Promise.resolve();
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function bindTabs() {
|
|
456
|
+
const tabs = $$('.tab');
|
|
457
|
+
tabs.forEach((tab, index) => {
|
|
458
|
+
tab.addEventListener('click', () => activateTab(tab.dataset.tab));
|
|
459
|
+
tab.addEventListener('keydown', (ev) => {
|
|
460
|
+
let next = -1;
|
|
461
|
+
if (ev.key === 'ArrowRight') next = (index + 1) % tabs.length;
|
|
462
|
+
else if (ev.key === 'ArrowLeft') next = (index - 1 + tabs.length) % tabs.length;
|
|
463
|
+
else if (ev.key === 'Home') next = 0;
|
|
464
|
+
else if (ev.key === 'End') next = tabs.length - 1;
|
|
465
|
+
else return;
|
|
466
|
+
ev.preventDefault();
|
|
467
|
+
activateTab(tabs[next].dataset.tab, { focus: true });
|
|
468
|
+
});
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// ── 1. 模型广场(纯展示) ─────────────────────────────────
|
|
473
|
+
|
|
474
|
+
async function loadCatalog(force = false) {
|
|
475
|
+
if (cache.catalog && !force) { renderCatalog(); return cache.catalog; }
|
|
476
|
+
if (loading.catalog) return cache.catalog;
|
|
477
|
+
|
|
478
|
+
loading.catalog = true;
|
|
479
|
+
regionLoading($('#catalog-body'), '正在读取模型目录');
|
|
480
|
+
|
|
481
|
+
try {
|
|
482
|
+
const data = await api.catalog(force);
|
|
483
|
+
cache.catalog = data;
|
|
484
|
+
clearBanner('catalog');
|
|
485
|
+
renderCatalog();
|
|
486
|
+
return data;
|
|
487
|
+
} catch (err) {
|
|
488
|
+
const msg = describeError(err);
|
|
489
|
+
banner('error', `读取模型目录失败:${msg}`, { key: 'catalog' });
|
|
490
|
+
regionError($('#catalog-body'), `模型目录没读到:${msg}`, () => loadCatalog(true));
|
|
491
|
+
$('#catalog-meta').replaceChildren();
|
|
492
|
+
return null;
|
|
493
|
+
} finally {
|
|
494
|
+
loading.catalog = false;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function catalogCounts(data) {
|
|
499
|
+
if (data && data.counts) return data.counts;
|
|
500
|
+
if (cache.state && cache.state.counts) return cache.state.counts;
|
|
501
|
+
const models = (data && data.models) || [];
|
|
502
|
+
return {
|
|
503
|
+
models: new Set(models.map((m) => m.name)).size,
|
|
504
|
+
rows: models.length,
|
|
505
|
+
groups: ((data && data.groups) || []).length,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function renderCatalog() {
|
|
510
|
+
const data = cache.catalog;
|
|
511
|
+
const body = $('#catalog-body');
|
|
512
|
+
const meta = $('#catalog-meta');
|
|
513
|
+
if (!data || !body) return;
|
|
514
|
+
|
|
515
|
+
const models = data.models || [];
|
|
516
|
+
const groups = data.groups || [];
|
|
517
|
+
const groupMap = new Map(groups.map((g) => [g.id, g]));
|
|
518
|
+
|
|
519
|
+
renderGroupChips(groups, models);
|
|
520
|
+
|
|
521
|
+
const counts = catalogCounts(data);
|
|
522
|
+
const query = filters.q.trim().toLowerCase();
|
|
523
|
+
const rows = models.filter((m) => {
|
|
524
|
+
if (filters.group && m.group !== filters.group) return false;
|
|
525
|
+
if (filters.kind && m.kind !== filters.kind) return false;
|
|
526
|
+
if (!query) return true;
|
|
527
|
+
const hay = [m.name, m.id, m.group, m.vendor, m.description, m.tags].filter(Boolean).join(' ').toLowerCase();
|
|
528
|
+
return hay.includes(query);
|
|
529
|
+
});
|
|
530
|
+
|
|
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
|
+
);
|
|
541
|
+
|
|
542
|
+
if (!rows.length) {
|
|
543
|
+
body.replaceChildren(h('div', { class: 'empty', text: '没有符合条件的模型。放宽分组或搜索词再试。' }));
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const tableRows = rows.map((m) => catalogRow(m, groupMap));
|
|
548
|
+
body.replaceChildren(tableEl(
|
|
549
|
+
['模型名', '分组', '倍率', '输入价', '输出价', '缓存价', '端点', '说明'],
|
|
550
|
+
tableRows,
|
|
551
|
+
));
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function renderGroupChips(groups, models) {
|
|
555
|
+
const host = $('#group-chips');
|
|
556
|
+
if (!host) return;
|
|
557
|
+
|
|
558
|
+
const counts = new Map();
|
|
559
|
+
for (const m of models) counts.set(m.group, (counts.get(m.group) || 0) + 1);
|
|
560
|
+
|
|
561
|
+
const chips = [
|
|
562
|
+
h('button', {
|
|
563
|
+
class: 'chip', type: 'button',
|
|
564
|
+
'aria-pressed': String(filters.group === ''),
|
|
565
|
+
onclick: () => { filters.group = ''; renderCatalog(); },
|
|
566
|
+
}, '全部', h('span', { class: 'chip-count', text: String(models.length) })),
|
|
567
|
+
];
|
|
568
|
+
|
|
569
|
+
for (const g of groups) {
|
|
570
|
+
chips.push(h('button', {
|
|
571
|
+
class: 'chip', type: 'button',
|
|
572
|
+
'aria-pressed': String(filters.group === g.id),
|
|
573
|
+
title: [
|
|
574
|
+
g.auto ? 'auto 分组:费率取决于实际命中的通道' : (g.ratio != null ? `分组倍率 ${g.ratio}×` : ''),
|
|
575
|
+
g.note || '',
|
|
576
|
+
].filter(Boolean).join(' · '),
|
|
577
|
+
onclick: () => {
|
|
578
|
+
filters.group = filters.group === g.id ? '' : g.id;
|
|
579
|
+
renderCatalog();
|
|
580
|
+
},
|
|
581
|
+
}, g.id, h('span', { class: 'chip-count', text: String(counts.get(g.id) || g.models || 0) })));
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
host.replaceChildren(...chips);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function catalogRow(m, groupMap) {
|
|
588
|
+
const info = groupMap.get(m.group);
|
|
589
|
+
const isAuto = m.group === 'auto' || (info && info.auto === true);
|
|
590
|
+
const pricing = m.pricing || {};
|
|
591
|
+
const priceKind = pricing.kind || 'unknown';
|
|
592
|
+
const ratio = m.groupRatio != null ? m.groupRatio : (info ? info.ratio : null);
|
|
593
|
+
|
|
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
|
+
];
|
|
612
|
+
|
|
613
|
+
// 价格三列:auto 与 unknown 都用一格跨三列,避免三格重复同一句提示。
|
|
614
|
+
if (isAuto) {
|
|
615
|
+
cells.push({ node: h('td', {
|
|
616
|
+
colspan: 3, class: 'muted price-merged',
|
|
617
|
+
title: 'auto 分组没有固定倍率,实际费率取决于命中的通道',
|
|
618
|
+
}, '以实际命中通道为准') });
|
|
619
|
+
} else if (priceKind === 'unknown') {
|
|
620
|
+
cells.push({ node: h('td', {
|
|
621
|
+
colspan: 3, class: 'unknown price-merged',
|
|
622
|
+
title: pricing.note || '站点没有给出可解析的价格',
|
|
623
|
+
}, '价格未知') });
|
|
624
|
+
} 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
|
+
}
|
|
631
|
+
|
|
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
|
+
});
|
|
638
|
+
|
|
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
|
+
});
|
|
646
|
+
|
|
647
|
+
return cells;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function bindCatalogControls() {
|
|
651
|
+
const search = $('#catalog-search');
|
|
652
|
+
const kind = $('#catalog-kind');
|
|
653
|
+
const reset = $('#catalog-reset');
|
|
654
|
+
|
|
655
|
+
search.addEventListener('input', () => {
|
|
656
|
+
filters.q = search.value;
|
|
657
|
+
if (cache.catalog) renderCatalog();
|
|
658
|
+
});
|
|
659
|
+
kind.addEventListener('change', () => {
|
|
660
|
+
filters.kind = kind.value;
|
|
661
|
+
if (cache.catalog) renderCatalog();
|
|
662
|
+
});
|
|
663
|
+
reset.addEventListener('click', () => {
|
|
664
|
+
filters.group = '';
|
|
665
|
+
filters.kind = '';
|
|
666
|
+
filters.q = '';
|
|
667
|
+
search.value = '';
|
|
668
|
+
kind.value = '';
|
|
669
|
+
if (cache.catalog) renderCatalog();
|
|
670
|
+
search.focus();
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// ── 2. 余额与用量 ─────────────────────────────────────────
|
|
675
|
+
|
|
676
|
+
async function loadWallet(force = false) {
|
|
677
|
+
await loadState(force);
|
|
678
|
+
renderAccounts();
|
|
679
|
+
await Promise.all([loadUsage(force), loadFlow(force)]);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
function renderAccounts() {
|
|
683
|
+
const box = $('#account-body');
|
|
684
|
+
const sub = $('#account-sub');
|
|
685
|
+
if (!box) return;
|
|
686
|
+
|
|
687
|
+
if (cache.stateError) {
|
|
688
|
+
regionError(box, `账户信息没读到:${cache.stateError}`, () => loadState(true).then(renderAccounts));
|
|
689
|
+
if (sub) sub.textContent = '';
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
const st = cache.state;
|
|
693
|
+
if (!st) { regionLoading(box, '正在读取账户'); if (sub) sub.textContent = ''; return; }
|
|
694
|
+
|
|
695
|
+
const accounts = st.accounts || [];
|
|
696
|
+
if (sub) sub.textContent = accounts.length ? `${accounts.length} 个账号` : '';
|
|
697
|
+
if (!accounts.length) {
|
|
698
|
+
box.replaceChildren(h('div', { class: 'empty', text: '还没有绑定任何账号。在 magpie 里添加 DragonAPI 账号后,钥匙与余额会出现在这里。' }));
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
box.replaceChildren(...accounts.map((a) => h('div', { class: 'acct' },
|
|
703
|
+
h('div', { class: 'acct-top' },
|
|
704
|
+
h('span', { class: 'acct-label', text: a.label || a.tokenName || '未命名账号' }),
|
|
705
|
+
a.group ? h('span', { class: 'tag', text: a.group }) : null,
|
|
706
|
+
h('span', { class: 'acct-mask', text: a.masked || '' }),
|
|
707
|
+
),
|
|
708
|
+
h('div', { class: 'acct-figs' },
|
|
709
|
+
fig('余额', a.balance ?? '—', 'big pos', Number.isFinite(a.balanceRaw) ? `${fmtInt(a.balanceRaw)} quota` : ''),
|
|
710
|
+
fig('已用', a.used ?? '—', '', Number.isFinite(a.usedRaw) ? `${fmtInt(a.usedRaw)} quota` : ''),
|
|
711
|
+
fig('模型数', Number.isFinite(a.models) ? fmtInt(a.models) : '—'),
|
|
712
|
+
fig('绑定于', fmtAt(a.boundAt)),
|
|
713
|
+
),
|
|
714
|
+
)));
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function fig(k, v, cls = '', title = '') {
|
|
718
|
+
return h('div', { class: 'fig' },
|
|
719
|
+
h('span', { class: 'fig-k', text: k }),
|
|
720
|
+
h('span', { class: `fig-v ${cls}`.trim(), title: title || null, text: v }),
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
async function loadUsage(force = false) {
|
|
725
|
+
const range = filters.range;
|
|
726
|
+
if (cache.usage[range] && !force) { renderUsage(); return cache.usage[range]; }
|
|
727
|
+
if (loading.usage) return cache.usage[range] || null;
|
|
728
|
+
|
|
729
|
+
loading.usage = true;
|
|
730
|
+
regionLoading($('#usage-body'), `正在读取${RANGE_LABEL[range]}用量`);
|
|
731
|
+
|
|
732
|
+
try {
|
|
733
|
+
const data = await api.usage(range);
|
|
734
|
+
cache.usage[range] = data;
|
|
735
|
+
clearBanner('usage');
|
|
736
|
+
renderUsage();
|
|
737
|
+
renderFlow();
|
|
738
|
+
return data;
|
|
739
|
+
} catch (err) {
|
|
740
|
+
const msg = describeError(err);
|
|
741
|
+
banner('error', `读取${RANGE_LABEL[range]}用量失败:${msg}`, { key: 'usage' });
|
|
742
|
+
regionError($('#usage-body'), `用量没读到:${msg}`, () => loadUsage(true));
|
|
743
|
+
return null;
|
|
744
|
+
} finally {
|
|
745
|
+
loading.usage = false;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function renderUsage() {
|
|
750
|
+
const box = $('#usage-body');
|
|
751
|
+
if (!box) return;
|
|
752
|
+
const data = cache.usage[filters.range];
|
|
753
|
+
|
|
754
|
+
if (!data) {
|
|
755
|
+
regionLoading(box, '正在读取用量');
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
const byModel = data.byModel || [];
|
|
760
|
+
const rows = byModel.map((m) => [
|
|
761
|
+
{ text: m.model || '—', cls: 'mono' },
|
|
762
|
+
{ text: fmtInt(m.calls), cls: 'num' },
|
|
763
|
+
{ text: fmtInt(m.tokens), cls: 'num' },
|
|
764
|
+
{ text: m.cost || '—', cls: 'num', title: Number.isFinite(m.costRaw) ? `${fmtInt(m.costRaw)} quota` : null },
|
|
765
|
+
]);
|
|
766
|
+
|
|
767
|
+
box.replaceChildren(
|
|
768
|
+
h('div', { class: 'summary-row' },
|
|
769
|
+
h('div', { class: 'summary-box' },
|
|
770
|
+
h('span', { class: 'fig-k', text: '花费 spent' }),
|
|
771
|
+
h('div', { class: 'fig-v', text: data.spent || '—' })),
|
|
772
|
+
h('div', { class: 'summary-box' },
|
|
773
|
+
h('span', { class: 'fig-k', text: 'tokens' }),
|
|
774
|
+
h('div', { class: 'fig-v', text: fmtInt(data.tokens) })),
|
|
775
|
+
),
|
|
776
|
+
h('p', { class: 'range-note', text: `区间 ${fmtAt(data.start)} → ${fmtAt(data.end)}` }),
|
|
777
|
+
tableEl([{ label: '模型' }, { label: '调用', cls: 'num' }, { label: 'tokens', cls: 'num' }, { label: '费用', cls: 'num' }],
|
|
778
|
+
rows, { empty: '这个区间还没有按模型的用量。' }),
|
|
779
|
+
);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
async function loadFlow(force = false) {
|
|
783
|
+
const account = filters.account;
|
|
784
|
+
if (!account) { renderFlow(); return null; } // 全部账号直接用 usage.rows
|
|
785
|
+
if (cache.logs[account] && !force) { renderFlow(); return cache.logs[account]; }
|
|
786
|
+
if (loading.logs) return cache.logs[account] || null;
|
|
787
|
+
|
|
788
|
+
loading.logs = true;
|
|
789
|
+
renderFlow();
|
|
790
|
+
try {
|
|
791
|
+
const data = await api.logs(account);
|
|
792
|
+
// 契约写的是「同 rows 的扁平列表」,可能直接是数组,也可能包在 rows 里
|
|
793
|
+
const rows = Array.isArray(data) ? data : (data.rows || data.logs || []);
|
|
794
|
+
cache.logs[account] = rows;
|
|
795
|
+
clearBanner('logs');
|
|
796
|
+
renderFlow();
|
|
797
|
+
return rows;
|
|
798
|
+
} catch (err) {
|
|
799
|
+
const msg = describeError(err);
|
|
800
|
+
banner('error', `读取账号流水失败:${msg}`, { key: 'logs' });
|
|
801
|
+
regionError($('#flow-body'), `流水没读到:${msg}`, () => loadFlow(true));
|
|
802
|
+
return null;
|
|
803
|
+
} finally {
|
|
804
|
+
loading.logs = false;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function renderFlow() {
|
|
809
|
+
const box = $('#flow-body');
|
|
810
|
+
const count = $('#flow-count');
|
|
811
|
+
if (!box) return;
|
|
812
|
+
|
|
813
|
+
const account = filters.account;
|
|
814
|
+
const source = account ? cache.logs[account] : (cache.usage[filters.range] && cache.usage[filters.range].rows);
|
|
815
|
+
|
|
816
|
+
if (source === undefined) {
|
|
817
|
+
regionLoading(box, account ? '正在读取该账号的流水' : '正在读取用量流水');
|
|
818
|
+
if (count) count.textContent = '';
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const rows = (source || []).slice(0, 200);
|
|
823
|
+
if (count) {
|
|
824
|
+
count.textContent = account
|
|
825
|
+
? `${fmtInt(rows.length)} 行 · 仅该账号`
|
|
826
|
+
: `${fmtInt(rows.length)} 行 · 多账号合并`;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
const tableRows = rows.map((r) => [
|
|
830
|
+
{ text: r.atText || fmtAt(r.at), cls: 'mono' },
|
|
831
|
+
{ text: r.model || '—', cls: 'mono' },
|
|
832
|
+
{ text: r.group || '—', cls: 'mono' },
|
|
833
|
+
{ text: r.tokenName || '—', cls: 'mono' },
|
|
834
|
+
{ text: fmtInt(r.input), cls: 'num' },
|
|
835
|
+
{ text: fmtInt(r.output), cls: 'num' },
|
|
836
|
+
{ text: fmtInt(r.cache), cls: 'num' },
|
|
837
|
+
{ text: r.cost || '—', cls: 'num', title: Number.isFinite(r.costRaw) ? `${fmtInt(r.costRaw)} quota` : null },
|
|
838
|
+
{
|
|
839
|
+
text: r.detail || (r.kind ? r.kind : '—'),
|
|
840
|
+
cls: 'col-desc',
|
|
841
|
+
title: [
|
|
842
|
+
r.detail || '',
|
|
843
|
+
r.kind ? `类型 ${r.kind}` : '',
|
|
844
|
+
Number.isFinite(r.tps) ? `TPS ${r.tps}` : '',
|
|
845
|
+
Number.isFinite(r.ttft) ? `TTFT ${r.ttft}s` : '',
|
|
846
|
+
Number.isFinite(r.dur) ? `耗时 ${r.dur}s` : '',
|
|
847
|
+
r.isStream ? '流式' : '',
|
|
848
|
+
].filter(Boolean).join('\n'),
|
|
849
|
+
},
|
|
850
|
+
]);
|
|
851
|
+
|
|
852
|
+
box.replaceChildren(tableEl(
|
|
853
|
+
['时间', '模型', '分组', '令牌名', { label: '输入', cls: 'num' }, { label: '输出', cls: 'num' },
|
|
854
|
+
{ label: '缓存', cls: 'num' }, { label: '费用', cls: 'num' }, '详情'],
|
|
855
|
+
tableRows,
|
|
856
|
+
{ empty: account ? '这个账号还没有用量记录。' : '这个区间还没有用量记录。' },
|
|
857
|
+
));
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
function bindWalletControls() {
|
|
861
|
+
for (const btn of $$('.segmented [data-range]')) {
|
|
862
|
+
btn.addEventListener('click', () => {
|
|
863
|
+
const range = btn.dataset.range;
|
|
864
|
+
if (filters.range === range) return;
|
|
865
|
+
filters.range = range;
|
|
866
|
+
for (const other of $$('.segmented [data-range]')) {
|
|
867
|
+
other.setAttribute('aria-pressed', String(other === btn));
|
|
868
|
+
}
|
|
869
|
+
loadUsage(false).then(renderFlow);
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const account = $('#flow-account');
|
|
874
|
+
account.addEventListener('change', () => {
|
|
875
|
+
filters.account = account.value;
|
|
876
|
+
if (!filters.account) { renderFlow(); return; }
|
|
877
|
+
loadFlow(false);
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// ── 3. 密钥 ───────────────────────────────────────────────
|
|
882
|
+
|
|
883
|
+
async function loadKeys(force = false) {
|
|
884
|
+
if (cache.keys && !force) { renderKeys(); return cache.keys; }
|
|
885
|
+
if (loading.keys) return cache.keys;
|
|
886
|
+
|
|
887
|
+
loading.keys = true;
|
|
888
|
+
regionLoading($('#keys-body'), '正在读取钥匙列表');
|
|
889
|
+
|
|
890
|
+
try {
|
|
891
|
+
const data = await api.keys();
|
|
892
|
+
cache.keys = data;
|
|
893
|
+
clearBanner('keys');
|
|
894
|
+
renderKeys();
|
|
895
|
+
return data;
|
|
896
|
+
} catch (err) {
|
|
897
|
+
const msg = describeError(err);
|
|
898
|
+
banner('error', `读取钥匙列表失败:${msg}`, { key: 'keys' });
|
|
899
|
+
regionError($('#keys-body'), `钥匙列表没读到:${msg}`, () => loadKeys(true));
|
|
900
|
+
renderKeyGroupOptions();
|
|
901
|
+
return null;
|
|
902
|
+
} finally {
|
|
903
|
+
loading.keys = false;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function keyGroups() {
|
|
908
|
+
const data = cache.keys;
|
|
909
|
+
if (data && Array.isArray(data.groups) && data.groups.length) {
|
|
910
|
+
return data.groups.map((g) => (typeof g === 'string' ? { id: g } : g));
|
|
911
|
+
}
|
|
912
|
+
const st = cache.state;
|
|
913
|
+
if (st && Array.isArray(st.groups) && st.groups.length) {
|
|
914
|
+
return st.groups.map((g) => ({ id: g.id, ratio: g.ratio, auto: g.auto, note: g.note }));
|
|
915
|
+
}
|
|
916
|
+
return [];
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function renderKeyGroupOptions() {
|
|
920
|
+
const sel = $('#key-group');
|
|
921
|
+
const submit = $('#key-submit');
|
|
922
|
+
if (!sel) return;
|
|
923
|
+
|
|
924
|
+
const groups = keyGroups();
|
|
925
|
+
const previous = sel.value;
|
|
926
|
+
sel.replaceChildren(...groups.map((g) => h('option', {
|
|
927
|
+
value: g.id,
|
|
928
|
+
text: g.auto
|
|
929
|
+
? `${g.id}(auto · 按命中通道计费)`
|
|
930
|
+
: (g.ratio != null ? `${g.id} · ${g.ratio}×` : g.id),
|
|
931
|
+
})));
|
|
932
|
+
if (previous && groups.some((g) => g.id === previous)) sel.value = previous;
|
|
933
|
+
|
|
934
|
+
sel.disabled = groups.length === 0;
|
|
935
|
+
if (submit) submit.disabled = groups.length === 0;
|
|
936
|
+
|
|
937
|
+
if (!groups.length) {
|
|
938
|
+
const hasPat = Boolean(cache.state && cache.state.pat && cache.state.pat.set);
|
|
939
|
+
banner('warn', hasPat
|
|
940
|
+
? '服务端没有返回可建钥匙的分组,可能是 PAT 缺少 api_key:read 权限。'
|
|
941
|
+
: '还没有 PAT,读不到可建钥匙的分组。先到「访问令牌」页设置 PAT。', { key: 'key-groups' });
|
|
942
|
+
} else {
|
|
943
|
+
clearBanner('key-groups');
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
function renderKeys() {
|
|
948
|
+
const box = $('#keys-body');
|
|
949
|
+
const count = $('#keys-count');
|
|
950
|
+
if (!box) return;
|
|
951
|
+
|
|
952
|
+
renderKeyGroupOptions();
|
|
953
|
+
if (count) {
|
|
954
|
+
const n = cache.keys && Array.isArray(cache.keys.keys) ? cache.keys.keys.length : 0;
|
|
955
|
+
count.textContent = n ? `${n} 把` : '';
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
if (!cache.keys) {
|
|
959
|
+
if (!loading.keys) regionLoading(box, '正在读取钥匙列表');
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
const keys = cache.keys.keys || [];
|
|
964
|
+
if (!keys.length) {
|
|
965
|
+
box.replaceChildren(h('div', { class: 'empty', text: '还没有钥匙。用左边的表单按分组建一把,建完记得立刻复制 sk-。' }));
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
const thead = h('thead', null, h('tr', null,
|
|
970
|
+
['名称', '分组', '打码', '创建时间', { label: '已用', cls: 'num' }, '状态', '绑定', '操作']
|
|
971
|
+
.map((hd) => {
|
|
972
|
+
const spec = typeof hd === 'string' ? { label: hd } : hd;
|
|
973
|
+
return h('th', { scope: 'col', class: spec.cls || null }, spec.label);
|
|
974
|
+
})));
|
|
975
|
+
|
|
976
|
+
const tbody = h('tbody');
|
|
977
|
+
for (const k of keys) {
|
|
978
|
+
const status = keyStatus(k);
|
|
979
|
+
tbody.append(h('tr', null,
|
|
980
|
+
h('td', { class: 'col-name' }, k.name || '未命名'),
|
|
981
|
+
h('td', null, k.group ? h('span', { class: 'tag', text: k.group }) : '—'),
|
|
982
|
+
h('td', { class: 'mono' }, k.masked || '—'),
|
|
983
|
+
h('td', { class: 'mono' }, fmtAt(k.createdAt)),
|
|
984
|
+
h('td', {
|
|
985
|
+
class: 'num',
|
|
986
|
+
title: Number.isFinite(k.used) ? `${fmtInt(k.used)} quota` : null,
|
|
987
|
+
}, moneyRaw(k.used)),
|
|
988
|
+
h('td', null, h('span', { class: status.cls, text: status.label })),
|
|
989
|
+
h('td', null, k.bound
|
|
990
|
+
? h('span', { class: 'tag ok', text: '已绑定' })
|
|
991
|
+
: h('span', { class: 'tag', text: '未绑定' })),
|
|
992
|
+
h('td', null, keyActions(k)),
|
|
993
|
+
));
|
|
994
|
+
|
|
995
|
+
if (revealed.has(k.id)) {
|
|
996
|
+
tbody.append(h('tr', null, h('td', { colspan: 8 }, h('div', { class: 'reveal-box' },
|
|
997
|
+
h('span', { class: 'reveal-label', text: '完整钥匙' }),
|
|
998
|
+
h('code', { class: 'reveal-value', text: revealed.get(k.id) }),
|
|
999
|
+
copyButton(revealed.get(k.id), '复制'),
|
|
1000
|
+
h('button', {
|
|
1001
|
+
class: 'btn tiny ghost', type: 'button',
|
|
1002
|
+
onclick: () => { revealed.delete(k.id); renderKeys(); },
|
|
1003
|
+
}, '收起'),
|
|
1004
|
+
))));
|
|
1005
|
+
}
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// 密钥表也走同一套滚动容器 + 提示,别让它在窄屏上悄悄裁掉「状态」「操作」列。
|
|
1009
|
+
const wrap = h('div', { class: 'table-wrap' }, h('table', { class: 'data-table' }, thead, tbody));
|
|
1010
|
+
const hint = h('p', { class: 'scroll-hint', 'data-overflow': '0', text: '← 左右滑动看完整列 →' });
|
|
1011
|
+
markOverflow(wrap, hint);
|
|
1012
|
+
box.replaceChildren(hint, wrap);
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function keyStatus(k) {
|
|
1016
|
+
if (Number.isFinite(k.expiredAt) && k.expiredAt > 0 && k.expiredAt < Date.now()) {
|
|
1017
|
+
return { label: '已过期', cls: 'tag bad' };
|
|
1018
|
+
}
|
|
1019
|
+
if (k.status === 1) return { label: '启用', cls: 'tag ok' };
|
|
1020
|
+
if (k.status === 2) return { label: '已禁用', cls: 'tag warn' };
|
|
1021
|
+
if (k.status === 3) return { label: '已过期', cls: 'tag bad' };
|
|
1022
|
+
if (k.status === 4) return { label: '已耗尽', cls: 'tag bad' };
|
|
1023
|
+
return { label: k.status == null ? '未知' : `状态 ${k.status}`, cls: 'tag' };
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
function keyActions(k) {
|
|
1027
|
+
if (confirmDeleteId === k.id) {
|
|
1028
|
+
return h('span', { class: 'row-actions' },
|
|
1029
|
+
h('button', {
|
|
1030
|
+
class: 'btn tiny danger', type: 'button',
|
|
1031
|
+
onclick: () => deleteKey(k),
|
|
1032
|
+
}, '确认删除'),
|
|
1033
|
+
h('button', {
|
|
1034
|
+
class: 'btn tiny ghost', type: 'button',
|
|
1035
|
+
onclick: () => { confirmDeleteId = null; renderKeys(); },
|
|
1036
|
+
}, '取消'),
|
|
1037
|
+
);
|
|
1038
|
+
}
|
|
1039
|
+
return h('span', { class: 'row-actions' },
|
|
1040
|
+
h('button', {
|
|
1041
|
+
class: 'btn tiny ghost', type: 'button',
|
|
1042
|
+
title: '需要 PAT 的 api_key:reveal 权限',
|
|
1043
|
+
onclick: (ev) => revealKey(k, ev.currentTarget),
|
|
1044
|
+
}, '查看完整钥匙'),
|
|
1045
|
+
h('button', {
|
|
1046
|
+
class: 'btn tiny danger', type: 'button',
|
|
1047
|
+
onclick: () => { confirmDeleteId = k.id; renderKeys(); },
|
|
1048
|
+
}, '删除'),
|
|
1049
|
+
);
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
async function revealKey(k, btn) {
|
|
1053
|
+
btn.disabled = true;
|
|
1054
|
+
btn.textContent = '读取中…';
|
|
1055
|
+
try {
|
|
1056
|
+
const data = await api.revealKey(k.id);
|
|
1057
|
+
if (!data.secret) throw new ApiError('服务端没有返回 secret。', 200, data);
|
|
1058
|
+
revealed.set(k.id, data.secret);
|
|
1059
|
+
clearBanner('reveal-' + k.id);
|
|
1060
|
+
renderKeys();
|
|
1061
|
+
} catch (err) {
|
|
1062
|
+
const msg = describeError(err);
|
|
1063
|
+
banner('error', `查看完整钥匙失败:${msg}`, { key: 'reveal-' + k.id });
|
|
1064
|
+
btn.disabled = false;
|
|
1065
|
+
btn.textContent = '查看完整钥匙';
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
async function deleteKey(k) {
|
|
1070
|
+
confirmDeleteId = null;
|
|
1071
|
+
try {
|
|
1072
|
+
await api.deleteKey(k.id);
|
|
1073
|
+
revealed.delete(k.id);
|
|
1074
|
+
cache.keys = null;
|
|
1075
|
+
clearBanner('keys');
|
|
1076
|
+
banner('ok', `已删除钥匙「${k.name || k.masked || k.id}」。`, { key: 'keys-ok', timeout: 6000 });
|
|
1077
|
+
await loadKeys(true);
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
banner('error', `删除钥匙失败:${describeError(err)}`, { key: 'keys' });
|
|
1080
|
+
renderKeys();
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
function renderSecret() {
|
|
1085
|
+
const slot = $('#secret-slot');
|
|
1086
|
+
if (!slot) return;
|
|
1087
|
+
|
|
1088
|
+
if (!lastSecret) { slot.replaceChildren(); return; }
|
|
1089
|
+
|
|
1090
|
+
const { key = {}, bind } = lastSecret;
|
|
1091
|
+
const secret = key.secret || '';
|
|
1092
|
+
const how = Array.isArray(bind && bind.how)
|
|
1093
|
+
? bind.how
|
|
1094
|
+
: (bind && bind.how ? [bind.how] : ((cache.bind && cache.bind.how) || []));
|
|
1095
|
+
|
|
1096
|
+
const valueNode = h('div', { class: 'secret-value', id: 'secret-value', text: secret || '(服务端没有返回 secret)' });
|
|
1097
|
+
|
|
1098
|
+
slot.replaceChildren(h('div', { class: 'secret-card' },
|
|
1099
|
+
h('h2', { text: '新钥匙已创建' }),
|
|
1100
|
+
h('p', { class: 'secret-warn', text: '这把钥匙只显示这一次,关掉或离开本页就再也看不到,请立刻复制。' }),
|
|
1101
|
+
h('div', { class: 'secret-line' },
|
|
1102
|
+
valueNode,
|
|
1103
|
+
copyButton(secret, '复制'),
|
|
1104
|
+
h('button', {
|
|
1105
|
+
class: 'btn ghost', type: 'button',
|
|
1106
|
+
onclick: () => { lastSecret = null; renderSecret(); },
|
|
1107
|
+
}, '我已保存,关闭'),
|
|
1108
|
+
),
|
|
1109
|
+
h('p', { class: 'hint', text: `名称 ${key.name || '—'} · 分组 ${key.group || '—'} · id ${key.id ?? '—'}` }),
|
|
1110
|
+
how.length ? h('div', null,
|
|
1111
|
+
h('p', { class: 'hint', text: '怎么绑进 magpie:' }),
|
|
1112
|
+
h('ol', { class: 'bind-steps' }, how.map((step) => h('li', { text: String(step) }))),
|
|
1113
|
+
) : null,
|
|
1114
|
+
));
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function bindKeyForm() {
|
|
1118
|
+
const form = $('#key-form');
|
|
1119
|
+
const unlimited = $('#key-unlimited');
|
|
1120
|
+
const quota = $('#key-quota');
|
|
1121
|
+
const group = $('#key-group');
|
|
1122
|
+
const name = $('#key-name');
|
|
1123
|
+
|
|
1124
|
+
unlimited.addEventListener('change', () => {
|
|
1125
|
+
quota.disabled = unlimited.checked;
|
|
1126
|
+
if (unlimited.checked) quota.value = '';
|
|
1127
|
+
});
|
|
1128
|
+
|
|
1129
|
+
// 换分组时给个默认名,省一次手打;用户改过就不覆盖
|
|
1130
|
+
group.addEventListener('change', () => {
|
|
1131
|
+
if (!name.value.trim() || name.dataset.auto === '1') {
|
|
1132
|
+
name.value = group.value ? `Magpie-${group.value}` : '';
|
|
1133
|
+
name.dataset.auto = '1';
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
1136
|
+
name.addEventListener('input', () => { name.dataset.auto = '0'; });
|
|
1137
|
+
|
|
1138
|
+
form.addEventListener('submit', onCreateKey);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
async function onCreateKey(ev) {
|
|
1142
|
+
ev.preventDefault();
|
|
1143
|
+
const submit = $('#key-submit');
|
|
1144
|
+
const group = $('#key-group').value;
|
|
1145
|
+
const name = $('#key-name').value.trim();
|
|
1146
|
+
const unlimited = $('#key-unlimited').checked;
|
|
1147
|
+
const amount = Number($('#key-quota').value);
|
|
1148
|
+
|
|
1149
|
+
if (!group) {
|
|
1150
|
+
banner('warn', '先选一个分组;分组决定这把钥匙能用到哪些模型。', { key: 'key-form' });
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
if (!name) {
|
|
1154
|
+
banner('warn', '给钥匙起个名字,之后在控制台里才认得出来。', { key: 'key-form' });
|
|
1155
|
+
$('#key-name').focus();
|
|
1156
|
+
return;
|
|
1157
|
+
}
|
|
1158
|
+
if (!unlimited && (!Number.isFinite(amount) || amount <= 0)) {
|
|
1159
|
+
banner('warn', '额度要填一个大于 0 的数,或者勾上「无限额度」。', { key: 'key-form' });
|
|
1160
|
+
$('#key-quota').focus();
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// 契约的请求体只写了 name / group / unlimited / expiredAt;
|
|
1165
|
+
// 有限额度按契约里 keys[].remain 的语义补 remain(原始 quota),
|
|
1166
|
+
// 换算沿用 state.currency 的 per / rate,与金额显示同源。
|
|
1167
|
+
const body = { name, group, unlimited, expiredAt: 0 };
|
|
1168
|
+
if (!unlimited) body.remain = rawFromMoney(amount);
|
|
1169
|
+
|
|
1170
|
+
submit.disabled = true;
|
|
1171
|
+
submit.textContent = '创建中…';
|
|
1172
|
+
try {
|
|
1173
|
+
const data = await api.createKey(body);
|
|
1174
|
+
lastSecret = { key: data.key || {}, bind: data.bind || null };
|
|
1175
|
+
renderSecret();
|
|
1176
|
+
clearBanner('key-form');
|
|
1177
|
+
banner('ok', '钥匙已创建。完整钥匙只显示一次,请立刻复制。', { key: 'key-create', timeout: 9000 });
|
|
1178
|
+
$('#key-name').value = '';
|
|
1179
|
+
$('#key-name').dataset.auto = '0';
|
|
1180
|
+
$('#key-quota').value = '';
|
|
1181
|
+
cache.keys = null;
|
|
1182
|
+
await loadKeys(true);
|
|
1183
|
+
const slot = $('#secret-slot');
|
|
1184
|
+
if (slot && slot.firstElementChild) slot.firstElementChild.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
|
1185
|
+
} catch (err) {
|
|
1186
|
+
const msg = describeError(err);
|
|
1187
|
+
banner('error', `创建钥匙失败:${msg}`, { key: 'key-form' });
|
|
1188
|
+
} finally {
|
|
1189
|
+
submit.disabled = false;
|
|
1190
|
+
submit.textContent = '创建钥匙';
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
async function loadBind(force = false) {
|
|
1195
|
+
if (cache.bind && !force) { renderBind(); return cache.bind; }
|
|
1196
|
+
if (loading.bind) return cache.bind;
|
|
1197
|
+
loading.bind = true;
|
|
1198
|
+
try {
|
|
1199
|
+
cache.bind = await api.bindInfo();
|
|
1200
|
+
clearBanner('bind');
|
|
1201
|
+
renderBind();
|
|
1202
|
+
return cache.bind;
|
|
1203
|
+
} catch (err) {
|
|
1204
|
+
const msg = describeError(err);
|
|
1205
|
+
banner('error', `读取绑定说明失败:${msg}`, { key: 'bind' });
|
|
1206
|
+
regionError($('#bind-info-body'), `绑定说明没读到:${msg}`, () => loadBind(true));
|
|
1207
|
+
return null;
|
|
1208
|
+
} finally {
|
|
1209
|
+
loading.bind = false;
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
function renderBind() {
|
|
1214
|
+
const box = $('#bind-info-body');
|
|
1215
|
+
if (!box) return;
|
|
1216
|
+
const data = cache.bind;
|
|
1217
|
+
if (!data) { regionLoading(box, '正在读取绑定说明'); return; }
|
|
1218
|
+
|
|
1219
|
+
const how = Array.isArray(data.how) ? data.how : (data.how ? [data.how] : []);
|
|
1220
|
+
box.replaceChildren(
|
|
1221
|
+
how.length
|
|
1222
|
+
? h('ol', { class: 'bind-steps' }, how.map((step) => h('li', { text: String(step) })))
|
|
1223
|
+
: h('p', { class: 'muted', text: '服务端没有给出绑定步骤。' }),
|
|
1224
|
+
data.auto && data.auto.label
|
|
1225
|
+
? h('p', { class: 'hint', text: `自动方式:${data.auto.label}(method: ${data.auto.method || '—'})` })
|
|
1226
|
+
: null,
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
// ── 4. 访问令牌(PAT) ────────────────────────────────────
|
|
1231
|
+
|
|
1232
|
+
async function loadPat(force = false) {
|
|
1233
|
+
await loadState(force);
|
|
1234
|
+
renderPat();
|
|
1235
|
+
await Promise.all([loadHealth(force), loadPing(force)]);
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function renderPat() {
|
|
1239
|
+
const box = $('#pat-state');
|
|
1240
|
+
const badge = $('#pat-badge');
|
|
1241
|
+
if (!box) return;
|
|
1242
|
+
|
|
1243
|
+
if (cache.stateError) {
|
|
1244
|
+
regionError(box, `PAT 状态没读到:${cache.stateError}`, () => loadState(true).then(renderPat));
|
|
1245
|
+
if (badge) badge.textContent = '';
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
const st = cache.state;
|
|
1249
|
+
if (!st) { regionLoading(box, '正在读取 PAT 状态'); if (badge) badge.textContent = ''; return; }
|
|
1250
|
+
|
|
1251
|
+
const pat = st.pat || {};
|
|
1252
|
+
if (badge) badge.textContent = pat.set ? '已设置' : '未设置';
|
|
1253
|
+
|
|
1254
|
+
if (!pat.set) {
|
|
1255
|
+
box.replaceChildren(
|
|
1256
|
+
h('p', { class: 'muted', text: '还没有设置 PAT。设置后才能读账户、建钥匙、看钱包。' }),
|
|
1257
|
+
h('p', { class: 'hint', text: 'PAT 以 nap_ 开头,在控制台「安全 → 访问令牌」创建。' }),
|
|
1258
|
+
);
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
const scopes = Array.isArray(pat.scopes) ? pat.scopes : [];
|
|
1263
|
+
box.replaceChildren(
|
|
1264
|
+
h('div', { class: 'kv' }, h('span', { class: 'k', text: 'hint' }), h('span', { class: 'v', text: pat.hint || '—' })),
|
|
1265
|
+
h('div', { class: 'kv' },
|
|
1266
|
+
h('span', { class: 'k', text: 'scopes' }),
|
|
1267
|
+
scopes.length
|
|
1268
|
+
? h('span', { class: 'scope-list' }, scopes.map((s) => h('span', { class: 'tag', text: s })))
|
|
1269
|
+
: h('span', { class: 'v muted', text: '服务端没有返回 scopes' }),
|
|
1270
|
+
),
|
|
1271
|
+
);
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
async function loadPing(force = false) {
|
|
1275
|
+
if (cache.ping && !force) return cache.ping;
|
|
1276
|
+
try {
|
|
1277
|
+
cache.ping = await api.ping();
|
|
1278
|
+
renderHeader();
|
|
1279
|
+
renderHealth();
|
|
1280
|
+
return cache.ping;
|
|
1281
|
+
} catch (err) {
|
|
1282
|
+
// ping 失败通常意味着服务没起来;state 那条会给出更完整的提示,这里只记一次
|
|
1283
|
+
banner('error', `本地服务探测失败:${describeError(err)}`, { key: 'ping' });
|
|
1284
|
+
renderHeader();
|
|
1285
|
+
return null;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
async function loadHealth(force = false) {
|
|
1290
|
+
if (cache.health && !force) { renderHealth(); return cache.health; }
|
|
1291
|
+
if (loading.health) return cache.health;
|
|
1292
|
+
loading.health = true;
|
|
1293
|
+
try {
|
|
1294
|
+
cache.health = await api.health();
|
|
1295
|
+
clearBanner('health');
|
|
1296
|
+
renderHealth();
|
|
1297
|
+
return cache.health;
|
|
1298
|
+
} catch (err) {
|
|
1299
|
+
banner('error', `读取健康记录失败:${describeError(err)}`, { key: 'health' });
|
|
1300
|
+
regionError($('#diag-body'), `健康记录没读到:${describeError(err)}`, () => loadHealth(true));
|
|
1301
|
+
return null;
|
|
1302
|
+
} finally {
|
|
1303
|
+
loading.health = false;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
function renderHealth() {
|
|
1308
|
+
const box = $('#diag-body');
|
|
1309
|
+
if (!box) return;
|
|
1310
|
+
|
|
1311
|
+
const health = cache.health;
|
|
1312
|
+
const ping = cache.ping;
|
|
1313
|
+
|
|
1314
|
+
if (!health && !ping) { regionLoading(box, '正在读取诊断信息'); return; }
|
|
1315
|
+
|
|
1316
|
+
const head = h('dl', { class: 'kv-grid' },
|
|
1317
|
+
h('dt', { text: '插件版本' }), h('dd', { text: ping && ping.version ? `v${ping.version}` : '—' }),
|
|
1318
|
+
h('dt', { text: '本地端口' }), h('dd', { text: ping && ping.port != null ? String(ping.port) : '—' }),
|
|
1319
|
+
h('dt', { text: '站点' }), h('dd', { text: (cache.state && cache.state.site) || '—' }),
|
|
1320
|
+
h('dt', { text: '目录版本' }), h('dd', { text: (cache.state && cache.state.catalogAt) ? fmtAt(cache.state.catalogAt) : '—' }),
|
|
1321
|
+
);
|
|
1322
|
+
|
|
1323
|
+
const recent = (health && health.recent) || [];
|
|
1324
|
+
const rows = recent.map((r) => [
|
|
1325
|
+
{ text: fmtAt(r.at), cls: 'mono' },
|
|
1326
|
+
{ text: r.ok ? '正常' : '失败', cls: r.ok ? 'tag ok' : 'tag bad' },
|
|
1327
|
+
{ text: SOURCE_LABEL[r.source] || r.source || '—', cls: 'mono' },
|
|
1328
|
+
{ text: Number.isFinite(r.count) ? fmtInt(r.count) : '—', cls: 'num' },
|
|
1329
|
+
{ text: Number.isFinite(r.ms) ? `${r.ms} ms` : '—', cls: 'num' },
|
|
1330
|
+
]);
|
|
1331
|
+
|
|
1332
|
+
box.replaceChildren(
|
|
1333
|
+
head,
|
|
1334
|
+
h('p', { class: 'hint', text: '最近的目录拉取记录:' }),
|
|
1335
|
+
tableEl(['时间', '结果', '来源', '条目数', { label: '耗时', cls: 'num' }], rows, { empty: '还没有健康记录。' }),
|
|
1336
|
+
);
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
async function onSavePat(ev) {
|
|
1340
|
+
ev.preventDefault();
|
|
1341
|
+
const input = $('#pat-input');
|
|
1342
|
+
const btn = $('#pat-save');
|
|
1343
|
+
const pat = input.value.trim();
|
|
1344
|
+
|
|
1345
|
+
if (!pat) { banner('warn', '先粘贴一个 PAT 再保存。', { key: 'pat-form' }); input.focus(); return; }
|
|
1346
|
+
if (!pat.startsWith('nap_')) {
|
|
1347
|
+
banner('warn', 'PAT 一般以 nap_ 开头,确认一下有没有粘错(sk- 是钥匙,不是 PAT)。', { key: 'pat-form' });
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
btn.disabled = true;
|
|
1352
|
+
btn.textContent = '保存中…';
|
|
1353
|
+
try {
|
|
1354
|
+
const data = await api.savePat(pat);
|
|
1355
|
+
if (cache.state) cache.state.pat = data.pat || { set: true };
|
|
1356
|
+
input.value = '';
|
|
1357
|
+
clearBanner('pat-form');
|
|
1358
|
+
banner('ok', data.user && data.user.name
|
|
1359
|
+
? `PAT 已保存,已连接到账户 ${data.user.name}。`
|
|
1360
|
+
: 'PAT 已保存。', { key: 'pat-ok', timeout: 7000 });
|
|
1361
|
+
renderPat();
|
|
1362
|
+
// PAT 换了,钥匙/余额/用量都可能变,别拿旧缓存骗人
|
|
1363
|
+
cache.keys = null;
|
|
1364
|
+
cache.health = null;
|
|
1365
|
+
cache.stateError = '';
|
|
1366
|
+
if (activeTab === 'keys') loadKeys(true);
|
|
1367
|
+
return data;
|
|
1368
|
+
} catch (err) {
|
|
1369
|
+
banner('error', `保存 PAT 失败:${describeError(err)}`, { key: 'pat-form' });
|
|
1370
|
+
return null;
|
|
1371
|
+
} finally {
|
|
1372
|
+
btn.disabled = false;
|
|
1373
|
+
btn.textContent = '保存';
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
async function onClearPat(btn) {
|
|
1378
|
+
if (btn.dataset.armed !== '1') {
|
|
1379
|
+
btn.dataset.armed = '1';
|
|
1380
|
+
btn.textContent = '确认清除?';
|
|
1381
|
+
setTimeout(() => {
|
|
1382
|
+
if (btn.dataset.armed === '1') { btn.dataset.armed = '0'; btn.textContent = '清除 PAT'; }
|
|
1383
|
+
}, 4000);
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
btn.dataset.armed = '0';
|
|
1387
|
+
btn.textContent = '清除中…';
|
|
1388
|
+
btn.disabled = true;
|
|
1389
|
+
try {
|
|
1390
|
+
const data = await api.clearPat();
|
|
1391
|
+
if (cache.state) cache.state.pat = data.pat || { set: false };
|
|
1392
|
+
cache.keys = null;
|
|
1393
|
+
cache.health = null;
|
|
1394
|
+
clearBanner('pat-form');
|
|
1395
|
+
banner('ok', 'PAT 已清除,页面不再持有任何凭据。', { key: 'pat-ok', timeout: 6000 });
|
|
1396
|
+
renderPat();
|
|
1397
|
+
if (activeTab === 'keys') loadKeys(true);
|
|
1398
|
+
} catch (err) {
|
|
1399
|
+
banner('error', `清除 PAT 失败:${describeError(err)}`, { key: 'pat-form' });
|
|
1400
|
+
} finally {
|
|
1401
|
+
btn.disabled = false;
|
|
1402
|
+
btn.textContent = '清除 PAT';
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
function bindPatControls() {
|
|
1407
|
+
$('#pat-form').addEventListener('submit', onSavePat);
|
|
1408
|
+
$('#pat-clear').addEventListener('click', (ev) => onClearPat(ev.currentTarget));
|
|
1409
|
+
$('#pat-shortcut').addEventListener('click', () => {
|
|
1410
|
+
activateTab('pat', { focus: true });
|
|
1411
|
+
setTimeout(() => $('#pat-input').focus(), 0);
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// ── 复制:clipboard 失败就退回「选中文本」 ────────────────
|
|
1416
|
+
|
|
1417
|
+
function copyButton(text, label) {
|
|
1418
|
+
const btn = h('button', {
|
|
1419
|
+
class: 'btn', type: 'button',
|
|
1420
|
+
onclick: () => copyText(text, btn, label),
|
|
1421
|
+
}, label);
|
|
1422
|
+
return btn;
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
async function copyText(text, btn, label = '复制') {
|
|
1426
|
+
if (!text) { banner('warn', '没有可复制的内容。', { key: 'copy' }); return; }
|
|
1427
|
+
|
|
1428
|
+
// 首选异步剪贴板;opaque origin / 权限拒绝时它会抛,必须能退回
|
|
1429
|
+
try {
|
|
1430
|
+
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
|
1431
|
+
await navigator.clipboard.writeText(text);
|
|
1432
|
+
flashButton(btn, label, '已复制');
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
} catch {
|
|
1436
|
+
// 继续走下面的兜底
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
// 兜底一:临时 textarea + execCommand(老浏览器 / 无权限时还能用)
|
|
1440
|
+
try {
|
|
1441
|
+
const ta = document.createElement('textarea');
|
|
1442
|
+
ta.value = text;
|
|
1443
|
+
ta.setAttribute('readonly', '');
|
|
1444
|
+
ta.style.position = 'fixed';
|
|
1445
|
+
ta.style.top = '-1000px';
|
|
1446
|
+
ta.style.opacity = '0';
|
|
1447
|
+
document.body.append(ta);
|
|
1448
|
+
ta.select();
|
|
1449
|
+
const ok = document.execCommand && document.execCommand('copy');
|
|
1450
|
+
ta.remove();
|
|
1451
|
+
if (ok) { flashButton(btn, label, '已复制'); return; }
|
|
1452
|
+
} catch {
|
|
1453
|
+
// 再退一步
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
// 兜底二:选中文本,让用户自己按 Ctrl+C;至少不会静默失败
|
|
1457
|
+
const target = btn.closest('.secret-line, .reveal-box, .secret-card');
|
|
1458
|
+
const node = target && (target.querySelector('.secret-value, .reveal-value') || target);
|
|
1459
|
+
if (node) {
|
|
1460
|
+
const range = document.createRange();
|
|
1461
|
+
range.selectNodeContents(node);
|
|
1462
|
+
const sel = window.getSelection();
|
|
1463
|
+
sel.removeAllRanges();
|
|
1464
|
+
sel.addRange(range);
|
|
1465
|
+
flashButton(btn, label, '已选中,按 Ctrl+C');
|
|
1466
|
+
banner('warn', '浏览器不允许直接写剪贴板,文本已选中,按 Ctrl+C 复制。', { key: 'copy', timeout: 6000 });
|
|
1467
|
+
} else {
|
|
1468
|
+
flashButton(btn, label, '复制失败');
|
|
1469
|
+
banner('warn', '复制失败,请手动选中钥匙文本。', { key: 'copy', timeout: 6000 });
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
function flashButton(btn, original, temporary) {
|
|
1474
|
+
if (!btn) return;
|
|
1475
|
+
btn.textContent = temporary;
|
|
1476
|
+
btn.disabled = true;
|
|
1477
|
+
setTimeout(() => { btn.textContent = original; btn.disabled = false; }, 1600);
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// ── 单模型详情(抽屉) ────────────────────────────────────
|
|
1481
|
+
|
|
1482
|
+
let drawerLastFocus = null;
|
|
1483
|
+
|
|
1484
|
+
function openModelDrawer(model) {
|
|
1485
|
+
const drawer = $('#drawer');
|
|
1486
|
+
if (!drawer) return;
|
|
1487
|
+
drawerLastFocus = document.activeElement;
|
|
1488
|
+
|
|
1489
|
+
$('#drawer-title').textContent = model.name || model.id || '模型详情';
|
|
1490
|
+
$('#drawer-sub').textContent = [model.group, model.kind].filter(Boolean).join(' · ');
|
|
1491
|
+
const body = $('#drawer-body');
|
|
1492
|
+
regionLoading(body, '正在读取计费详情');
|
|
1493
|
+
drawer.hidden = false;
|
|
1494
|
+
$('#drawer-close').focus();
|
|
1495
|
+
|
|
1496
|
+
loadModelDetail(model, body);
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
async function loadModelDetail(model, body) {
|
|
1500
|
+
try {
|
|
1501
|
+
const data = await api.model(model.group || '', model.name || model.id || '');
|
|
1502
|
+
body.replaceChildren(...modelDetailNodes(model, data));
|
|
1503
|
+
clearBanner('model');
|
|
1504
|
+
} catch (err) {
|
|
1505
|
+
const msg = describeError(err);
|
|
1506
|
+
banner('error', `读取模型详情失败:${msg}`, { key: 'model' });
|
|
1507
|
+
body.replaceChildren(h('div', { class: 'region-error' },
|
|
1508
|
+
h('p', { class: 'region-error-text', text: `模型详情没读到:${msg}` }),
|
|
1509
|
+
h('p', { class: 'hint', text: '模型广场本身仍然可用,这里只是单模型的分档与表达式。' }),
|
|
1510
|
+
));
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
function modelDetailNodes(model, data) {
|
|
1515
|
+
const nodes = [];
|
|
1516
|
+
const pricing = model.pricing || {};
|
|
1517
|
+
const billing = data.billing || null;
|
|
1518
|
+
|
|
1519
|
+
nodes.push(h('dl', { class: 'kv-grid' },
|
|
1520
|
+
h('dt', { text: '模型名' }), h('dd', { text: model.name || '—' }),
|
|
1521
|
+
h('dt', { text: '分组' }), h('dd', { text: model.group || '—' }),
|
|
1522
|
+
h('dt', { text: '厂商' }), h('dd', { text: model.vendor || '—' }),
|
|
1523
|
+
h('dt', { text: '类型' }), h('dd', { text: KIND_LABEL[model.kind] || model.kind || '—' }),
|
|
1524
|
+
h('dt', { text: '上下文' }), h('dd', { text: Number.isFinite(model.context) ? fmtInt(model.context) : '—' }),
|
|
1525
|
+
h('dt', { text: '端点' }), h('dd', { text: (model.endpoints || []).join(' · ') || '—' }),
|
|
1526
|
+
h('dt', { text: '分组倍率' }), h('dd', { text: model.groupRatio != null ? fmtRatio(model.groupRatio) : '—' }),
|
|
1527
|
+
h('dt', { text: '价格' }), h('dd', {
|
|
1528
|
+
text: pricing.kind === 'unknown'
|
|
1529
|
+
? '价格未知'
|
|
1530
|
+
: [pricing.input, pricing.output, pricing.cache].filter(Boolean).join(' · ') || '—',
|
|
1531
|
+
}),
|
|
1532
|
+
));
|
|
1533
|
+
|
|
1534
|
+
if (pricing.note) nodes.push(h('p', { class: 'hint', text: `站点说明:${pricing.note}` }));
|
|
1535
|
+
if (model.description) nodes.push(h('p', { class: 'hint', text: model.description }));
|
|
1536
|
+
|
|
1537
|
+
if (!billing) {
|
|
1538
|
+
nodes.push(h('p', { class: 'muted', text: '服务端没有给出更细的计费信息。' }));
|
|
1539
|
+
return nodes;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
nodes.push(h('h3', { class: 'drawer-h3', text: '计费模式' }));
|
|
1543
|
+
nodes.push(h('p', { class: 'hint', text: `mode: ${billing.mode || '—'}` }));
|
|
1544
|
+
|
|
1545
|
+
if (billing.expr) {
|
|
1546
|
+
nodes.push(h('pre', { class: 'expr', text: String(billing.expr) }));
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
const tiers = Array.isArray(billing.tiers) ? billing.tiers : [];
|
|
1550
|
+
if (tiers.length) {
|
|
1551
|
+
nodes.push(h('h3', { class: 'drawer-h3', text: '分档' }));
|
|
1552
|
+
nodes.push(tableEl(['档位', { label: '输入', cls: 'num' }, { label: '输出', cls: 'num' }],
|
|
1553
|
+
tiers.map((t) => [
|
|
1554
|
+
{ text: t.name || '—', cls: 'mono' },
|
|
1555
|
+
{ text: t.input != null ? String(t.input) : '—', cls: 'num' },
|
|
1556
|
+
{ text: t.output != null ? String(t.output) : '—', cls: 'num' },
|
|
1557
|
+
])));
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
const usages = Array.isArray(billing.usages) ? billing.usages : [];
|
|
1561
|
+
if (usages.length) {
|
|
1562
|
+
nodes.push(h('h3', { class: 'drawer-h3', text: '按用量计费' }));
|
|
1563
|
+
nodes.push(tableEl(['字段', '单位', { label: '单价', cls: 'num' }],
|
|
1564
|
+
usages.map((u) => [
|
|
1565
|
+
{ text: u.field || '—', cls: 'mono' },
|
|
1566
|
+
{ text: u.unit || '—', cls: 'mono' },
|
|
1567
|
+
{ text: u.price != null ? String(u.price) : '—', cls: 'num' },
|
|
1568
|
+
])));
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
if (billing.schema) {
|
|
1572
|
+
nodes.push(h('h3', { class: 'drawer-h3', text: '用量 schema' }));
|
|
1573
|
+
nodes.push(h('pre', { class: 'expr', text: safeJson(billing.schema) }));
|
|
1574
|
+
}
|
|
1575
|
+
if (billing.examples) {
|
|
1576
|
+
nodes.push(h('h3', { class: 'drawer-h3', text: '示例' }));
|
|
1577
|
+
nodes.push(h('pre', { class: 'expr', text: safeJson(billing.examples) }));
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
return nodes;
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
function safeJson(value) {
|
|
1584
|
+
try { return JSON.stringify(value, null, 2); } catch { return String(value); }
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
function closeDrawer() {
|
|
1588
|
+
const drawer = $('#drawer');
|
|
1589
|
+
if (!drawer || drawer.hidden) return;
|
|
1590
|
+
drawer.hidden = true;
|
|
1591
|
+
if (drawerLastFocus && typeof drawerLastFocus.focus === 'function') drawerLastFocus.focus();
|
|
1592
|
+
drawerLastFocus = null;
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
function bindDrawer() {
|
|
1596
|
+
const drawer = $('#drawer');
|
|
1597
|
+
if (!drawer) return;
|
|
1598
|
+
|
|
1599
|
+
drawer.addEventListener('click', (ev) => {
|
|
1600
|
+
if (ev.target.closest('[data-drawer-close]')) closeDrawer();
|
|
1601
|
+
});
|
|
1602
|
+
|
|
1603
|
+
document.addEventListener('keydown', (ev) => {
|
|
1604
|
+
if (drawer.hidden) return;
|
|
1605
|
+
if (ev.key === 'Escape') { ev.preventDefault(); closeDrawer(); return; }
|
|
1606
|
+
if (ev.key !== 'Tab') return;
|
|
1607
|
+
// 焦点别跑出抽屉:简单的手工 trap,够用且不引依赖
|
|
1608
|
+
const focusables = $$('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', drawer)
|
|
1609
|
+
.filter((el) => !el.disabled && el.offsetParent !== null);
|
|
1610
|
+
if (!focusables.length) return;
|
|
1611
|
+
const first = focusables[0];
|
|
1612
|
+
const last = focusables[focusables.length - 1];
|
|
1613
|
+
if (ev.shiftKey && document.activeElement === first) { ev.preventDefault(); last.focus(); }
|
|
1614
|
+
else if (!ev.shiftKey && document.activeElement === last) { ev.preventDefault(); first.focus(); }
|
|
1615
|
+
});
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
// ── 数据加载编排 ──────────────────────────────────────────
|
|
1619
|
+
|
|
1620
|
+
async function loadState(force = false) {
|
|
1621
|
+
if (cache.state && !force) { renderHeader(); return cache.state; }
|
|
1622
|
+
if (loading.state) return cache.state;
|
|
1623
|
+
|
|
1624
|
+
loading.state = true;
|
|
1625
|
+
try {
|
|
1626
|
+
const data = await api.state();
|
|
1627
|
+
cache.state = data;
|
|
1628
|
+
cache.stateError = '';
|
|
1629
|
+
clearBanner('state');
|
|
1630
|
+
renderHeader();
|
|
1631
|
+
populateAccountSelect();
|
|
1632
|
+
renderKeyGroupOptions();
|
|
1633
|
+
if (activeTab === 'wallet') renderAccounts();
|
|
1634
|
+
if (activeTab === 'pat') renderPat();
|
|
1635
|
+
return data;
|
|
1636
|
+
} catch (err) {
|
|
1637
|
+
const msg = describeError(err);
|
|
1638
|
+
cache.stateError = msg;
|
|
1639
|
+
banner('error', `读取站点状态失败:${msg}`, { key: 'state' });
|
|
1640
|
+
renderHeader();
|
|
1641
|
+
if (activeTab === 'wallet') renderAccounts();
|
|
1642
|
+
if (activeTab === 'pat') renderPat();
|
|
1643
|
+
return null;
|
|
1644
|
+
} finally {
|
|
1645
|
+
loading.state = false;
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
function clearCache() {
|
|
1650
|
+
cache.state = null;
|
|
1651
|
+
cache.stateError = '';
|
|
1652
|
+
cache.ping = null;
|
|
1653
|
+
cache.catalog = null;
|
|
1654
|
+
cache.keys = null;
|
|
1655
|
+
cache.bind = null;
|
|
1656
|
+
cache.health = null;
|
|
1657
|
+
cache.usage = {};
|
|
1658
|
+
cache.logs = {};
|
|
1659
|
+
confirmDeleteId = null;
|
|
1660
|
+
revealed.clear();
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
async function refreshAll() {
|
|
1664
|
+
const btn = $('#refresh-btn');
|
|
1665
|
+
if (!btn) return;
|
|
1666
|
+
const original = btn.textContent;
|
|
1667
|
+
btn.disabled = true;
|
|
1668
|
+
btn.textContent = '刷新中…';
|
|
1669
|
+
|
|
1670
|
+
clearCache();
|
|
1671
|
+
try {
|
|
1672
|
+
await Promise.allSettled([loadPing(true), loadState(true), loadHealth(true), loadBind(true)]);
|
|
1673
|
+
await ensureTab(activeTab, true);
|
|
1674
|
+
banner('ok', '已重新拉取最新数据。', { key: 'refresh', timeout: 4000 });
|
|
1675
|
+
} finally {
|
|
1676
|
+
btn.disabled = false;
|
|
1677
|
+
btn.textContent = original;
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// ── 启动 ──────────────────────────────────────────────────
|
|
1682
|
+
|
|
1683
|
+
function bindGlobal() {
|
|
1684
|
+
$('#refresh-btn').addEventListener('click', refreshAll);
|
|
1685
|
+
|
|
1686
|
+
const search = $('#catalog-search');
|
|
1687
|
+
// 搜索框里按 Esc 清空,符合输入框的常规预期
|
|
1688
|
+
search.addEventListener('keydown', (ev) => {
|
|
1689
|
+
if (ev.key === 'Escape' && search.value) {
|
|
1690
|
+
ev.preventDefault();
|
|
1691
|
+
search.value = '';
|
|
1692
|
+
filters.q = '';
|
|
1693
|
+
if (cache.catalog) renderCatalog();
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
async function boot() {
|
|
1699
|
+
initTheme();
|
|
1700
|
+
bindGlobal();
|
|
1701
|
+
bindTabs();
|
|
1702
|
+
bindCatalogControls();
|
|
1703
|
+
bindWalletControls();
|
|
1704
|
+
bindKeyForm();
|
|
1705
|
+
bindPatControls();
|
|
1706
|
+
bindDrawer();
|
|
1707
|
+
|
|
1708
|
+
const params = new URLSearchParams(location.search);
|
|
1709
|
+
const wanted = params.get('tab');
|
|
1710
|
+
const valid = ['catalog', 'wallet', 'keys', 'pat'];
|
|
1711
|
+
const start = valid.includes(wanted) ? wanted : 'catalog';
|
|
1712
|
+
|
|
1713
|
+
activateTab(start, { focus: false });
|
|
1714
|
+
|
|
1715
|
+
// 首屏并行拉:状态与目录互不依赖,谁先回来谁先画
|
|
1716
|
+
await Promise.allSettled([loadPing(false), loadState(false), ensureTab(start, false)]);
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
boot().catch((err) => {
|
|
1720
|
+
// 兜底:boot 里任何没接住的异常都不能变成白屏
|
|
1721
|
+
banner('error', `页面初始化失败:${describeError(err)}。可以点右上角「刷新」重试。`, { key: 'boot' });
|
|
1722
|
+
});
|