@simonyea/holysheep-cli 1.7.52 → 1.7.54

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.
@@ -0,0 +1,873 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>HolySheep WebUI</title>
7
+ <style>
8
+ /* ── Reset & Base ──────────────────────────────────────────────────────── */
9
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
10
+ :root {
11
+ --bg: #f5f6fa; --surface: #fff; --surface2: #eef0f4;
12
+ --text: #1a1a2e; --text2: #666; --border: #dde;
13
+ --primary: #e8a46a; --primary-dim: rgba(232,164,106,0.15);
14
+ --success: #22c55e; --success-dim: rgba(34,197,94,0.12);
15
+ --warning: #f59e0b; --warning-dim: rgba(245,158,11,0.12);
16
+ --error: #ef4444; --error-dim: rgba(239,68,68,0.12);
17
+ --radius: 10px; --shadow: 0 1px 3px rgba(0,0,0,0.06);
18
+ --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
19
+ --mono: "SF Mono", "Cascadia Code", "Fira Code", Consolas, monospace;
20
+ }
21
+ @media (prefers-color-scheme: dark) {
22
+ :root {
23
+ --bg: #0f0f1a; --surface: #1a1a2e; --surface2: #222240;
24
+ --text: #e8e8f0; --text2: #888; --border: #333350;
25
+ --shadow: 0 1px 3px rgba(0,0,0,0.3);
26
+ }
27
+ }
28
+ html { font-size: 15px; }
29
+ body { font-family: var(--font); background: var(--bg); color: var(--text); min-height: 100vh; }
30
+ a { color: var(--primary); text-decoration: none; }
31
+ a:hover { text-decoration: underline; }
32
+ button { font-family: var(--font); cursor: pointer; border: none; border-radius: 6px; padding: 8px 16px; font-size: 0.9rem; transition: all .15s; }
33
+ input[type="text"], input[type="password"] {
34
+ font-family: var(--mono); background: var(--surface2); color: var(--text); border: 1px solid var(--border);
35
+ border-radius: 6px; padding: 8px 12px; font-size: 0.9rem; width: 100%; outline: none;
36
+ }
37
+ input:focus { border-color: var(--primary); box-shadow: 0 0 0 2px var(--primary-dim); }
38
+
39
+ /* ── Layout ────────────────────────────────────────────────────────────── */
40
+ .app { max-width: 960px; margin: 0 auto; padding: 20px; }
41
+ .header { display: flex; align-items: center; justify-content: space-between; padding: 16px 0; margin-bottom: 8px; }
42
+ .header h1 { font-size: 1.4rem; font-weight: 700; }
43
+ .header h1 span { color: var(--primary); }
44
+ .header .ver { color: var(--text2); font-size: 0.8rem; }
45
+
46
+ /* ── Tabs ──────────────────────────────────────────────────────────────── */
47
+ .tabs { display: flex; gap: 4px; border-bottom: 2px solid var(--border); margin-bottom: 20px; }
48
+ .tab { padding: 10px 18px; font-size: 0.9rem; color: var(--text2); background: none; border-radius: 8px 8px 0 0;
49
+ position: relative; transition: color .15s; }
50
+ .tab:hover { color: var(--text); background: var(--surface); }
51
+ .tab.active { color: var(--primary); font-weight: 600; }
52
+ .tab.active::after { content: ''; position: absolute; bottom: -2px; left: 0; right: 0; height: 2px; background: var(--primary); }
53
+
54
+ /* ── Cards ─────────────────────────────────────────────────────────────── */
55
+ .card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 20px; margin-bottom: 16px; box-shadow: var(--shadow); }
56
+ .card h3 { font-size: 1rem; margin-bottom: 12px; display: flex; align-items: center; gap: 8px; }
57
+ .card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; }
58
+ .stat { text-align: center; padding: 12px; }
59
+ .stat .value { font-size: 1.6rem; font-weight: 700; color: var(--primary); }
60
+ .stat .label { font-size: 0.8rem; color: var(--text2); margin-top: 4px; }
61
+
62
+ /* ── Buttons ───────────────────────────────────────────────────────────── */
63
+ .btn-primary { background: var(--primary); color: #fff; font-weight: 600; }
64
+ .btn-primary:hover { filter: brightness(1.1); }
65
+ .btn-primary:disabled { opacity: 0.5; cursor: not-allowed; }
66
+ .btn-secondary { background: var(--surface2); color: var(--text); border: 1px solid var(--border); }
67
+ .btn-secondary:hover { background: var(--border); }
68
+ .btn-danger { background: var(--error); color: #fff; }
69
+ .btn-danger:hover { filter: brightness(1.1); }
70
+ .btn-sm { padding: 5px 10px; font-size: 0.8rem; }
71
+ .btn-group { display: flex; gap: 8px; flex-wrap: wrap; }
72
+
73
+ /* ── Status indicators ─────────────────────────────────────────────────── */
74
+ .dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; }
75
+ .dot-ok { background: var(--success); }
76
+ .dot-warn { background: var(--warning); }
77
+ .dot-err { background: var(--error); }
78
+ .dot-gray { background: var(--text2); }
79
+ .badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 600; }
80
+ .badge-ok { background: var(--success-dim); color: var(--success); }
81
+ .badge-warn { background: var(--warning-dim); color: var(--warning); }
82
+ .badge-err { background: var(--error-dim); color: var(--error); }
83
+ .badge-gray { background: var(--surface2); color: var(--text2); }
84
+
85
+ /* ── Check list ────────────────────────────────────────────────────────── */
86
+ .check-row { display: flex; align-items: center; gap: 10px; padding: 8px 0; border-bottom: 1px solid var(--border); }
87
+ .check-row:last-child { border-bottom: none; }
88
+ .check-label { flex: 1; }
89
+ .check-detail { color: var(--text2); font-size: 0.85rem; font-family: var(--mono); }
90
+
91
+ /* ── Tool cards ────────────────────────────────────────────────────────── */
92
+ .tool-card { display: flex; align-items: center; gap: 12px; padding: 14px; background: var(--surface);
93
+ border: 1px solid var(--border); border-radius: var(--radius); }
94
+ .tool-icon { font-size: 1.5rem; width: 40px; text-align: center; }
95
+ .tool-info { flex: 1; }
96
+ .tool-info .name { font-weight: 600; font-size: 0.95rem; }
97
+ .tool-info .meta { font-size: 0.8rem; color: var(--text2); margin-top: 2px; }
98
+ .tool-actions { display: flex; gap: 6px; }
99
+
100
+ /* ── Console ───────────────────────────────────────────────────────────── */
101
+ .console { background: #111; color: #ccc; font-family: var(--mono); font-size: 0.8rem; padding: 14px;
102
+ border-radius: var(--radius); max-height: 300px; overflow-y: auto; white-space: pre-wrap; word-break: break-all;
103
+ line-height: 1.5; margin-top: 12px; }
104
+ .console .ok { color: #4ade80; }
105
+ .console .err { color: #f87171; }
106
+ .console .warn { color: #fbbf24; }
107
+ .console .info { color: #60a5fa; }
108
+
109
+ /* ── Wizard steps ──────────────────────────────────────────────────────── */
110
+ .steps { display: flex; gap: 0; margin-bottom: 20px; }
111
+ .step { flex: 1; text-align: center; padding: 10px 6px; font-size: 0.8rem; color: var(--text2);
112
+ border-bottom: 3px solid var(--border); transition: all .2s; }
113
+ .step.active { color: var(--primary); border-color: var(--primary); font-weight: 600; }
114
+ .step.done { color: var(--success); border-color: var(--success); }
115
+
116
+ /* ── Checkbox group ────────────────────────────────────────────────────── */
117
+ .checkbox-group { display: flex; flex-direction: column; gap: 8px; }
118
+ .checkbox-item { display: flex; align-items: center; gap: 10px; padding: 10px 14px; background: var(--surface2);
119
+ border-radius: 8px; cursor: pointer; transition: background .15s; border: 1px solid transparent; }
120
+ .checkbox-item:hover { border-color: var(--primary); }
121
+ .checkbox-item input { width: 18px; height: 18px; accent-color: var(--primary); cursor: pointer; }
122
+ .checkbox-item .cb-label { font-weight: 500; }
123
+ .checkbox-item .cb-desc { font-size: 0.8rem; color: var(--text2); }
124
+
125
+ /* ── Page visibility ───────────────────────────────────────────────────── */
126
+ .page { display: none; }
127
+ .page.active { display: block; }
128
+
129
+ /* ── Misc ──────────────────────────────────────────────────────────────── */
130
+ .loading { color: var(--text2); padding: 20px; text-align: center; }
131
+ .mt { margin-top: 12px; }
132
+ .mb { margin-bottom: 12px; }
133
+ .flex-between { display: flex; justify-content: space-between; align-items: center; }
134
+ .text-sm { font-size: 0.85rem; }
135
+ .text-muted { color: var(--text2); }
136
+ .mono { font-family: var(--mono); }
137
+ hr { border: none; border-top: 1px solid var(--border); margin: 16px 0; }
138
+ .hidden { display: none !important; }
139
+ </style>
140
+ </head>
141
+ <body>
142
+ <div class="app" id="app">
143
+ <!-- Header -->
144
+ <div class="header">
145
+ <h1>🐑 <span>HolySheep</span> WebUI</h1>
146
+ <span class="ver" id="version"></span>
147
+ </div>
148
+
149
+ <!-- Tabs -->
150
+ <div class="tabs" id="tabs">
151
+ <button class="tab active" data-page="dashboard" id="tab-dashboard"></button>
152
+ <button class="tab" data-page="setup" id="tab-setup"></button>
153
+ <button class="tab" data-page="tools" id="tab-tools"></button>
154
+ <button class="tab" data-page="doctor" id="tab-doctor"></button>
155
+ </div>
156
+
157
+ <!-- ── Dashboard ─────────────────────────────────────────────────────── -->
158
+ <div class="page active" id="page-dashboard">
159
+ <div class="card-grid">
160
+ <div class="card">
161
+ <h3 id="lbl-login-status"></h3>
162
+ <div id="login-status-content" class="loading"></div>
163
+ </div>
164
+ <div class="card">
165
+ <h3 id="lbl-balance"></h3>
166
+ <div id="balance-content" class="loading"></div>
167
+ </div>
168
+ </div>
169
+ <div class="card">
170
+ <h3 id="lbl-quick-actions"></h3>
171
+ <div class="btn-group">
172
+ <button class="btn-primary" onclick="switchTab('setup')" id="btn-go-setup"></button>
173
+ <button class="btn-secondary" onclick="switchTab('doctor')" id="btn-go-doctor"></button>
174
+ <button class="btn-secondary" onclick="runUpgrade()" id="btn-go-upgrade"></button>
175
+ </div>
176
+ </div>
177
+ </div>
178
+
179
+ <!-- ── Setup Wizard ──────────────────────────────────────────────────── -->
180
+ <div class="page" id="page-setup">
181
+ <div class="steps" id="setup-steps"></div>
182
+ <div id="setup-content"></div>
183
+ </div>
184
+
185
+ <!-- ── Tools ─────────────────────────────────────────────────────────── -->
186
+ <div class="page" id="page-tools">
187
+ <div class="flex-between mb">
188
+ <h3 id="lbl-tools-title"></h3>
189
+ <button class="btn-secondary btn-sm" onclick="loadTools()" id="btn-refresh-tools"></button>
190
+ </div>
191
+ <div id="tools-list" class="loading"></div>
192
+ </div>
193
+
194
+ <!-- ── Doctor ────────────────────────────────────────────────────────── -->
195
+ <div class="page" id="page-doctor">
196
+ <div class="flex-between mb">
197
+ <h3 id="lbl-doctor-title"></h3>
198
+ <button class="btn-secondary btn-sm" onclick="loadDoctor()" id="btn-refresh-doctor"></button>
199
+ </div>
200
+ <div id="doctor-content" class="loading"></div>
201
+ </div>
202
+
203
+ <!-- ── Upgrade Modal ─────────────────────────────────────────────────── -->
204
+ <div id="upgrade-modal" class="hidden">
205
+ <div class="card">
206
+ <div class="flex-between mb">
207
+ <h3 id="lbl-upgrade-title"></h3>
208
+ <button class="btn-secondary btn-sm" onclick="closeUpgrade()">✕</button>
209
+ </div>
210
+ <div class="console" id="upgrade-console"></div>
211
+ </div>
212
+ </div>
213
+ </div>
214
+
215
+ <script>
216
+ // ── i18n ──────────────────────────────────────────────────────────────────
217
+ const I18N = {
218
+ 'zh': {
219
+ dashboard: '仪表盘', setup: '配置向导', tools: '工具管理', doctor: '环境诊断',
220
+ loginStatus: '登录状态', balance: '余额', quickActions: '快捷操作',
221
+ loggedIn: '已登录', notLoggedIn: '未登录', keyValid: 'Key 有效', keyInvalid: 'Key 已失效',
222
+ checking: '检查中...', login: '登录', logout: '退出登录', recharge: '充值',
223
+ balanceLabel: '余额', todayCost: '今日消费', monthCost: '本月消费', totalCalls: '累计调用',
224
+ goSetup: '一键配置', goDoctor: '环境检查', goUpgrade: '升级工具',
225
+ apiKey: 'API Key', apiKeyPlaceholder: '请输入 API Key (cr_xxx)',
226
+ validate: '验证', validating: '验证中...',
227
+ next: '下一步', prev: '上一步', startSetup: '开始配置', done: '完成',
228
+ selectModels: '选择模型', selectTools: '选择工具', configuring: '配置中', summary: '配置结果',
229
+ installed: '已安装', notInstalled: '未安装', configured: '已配置', notConfigured: '未配置',
230
+ version: '版本', install: '安装', configure: '配置', reset: '重置', upgrade: '升级',
231
+ autoInstall: '自动安装未安装的工具',
232
+ confirmReset: '确认重置所有 HolySheep 配置?此操作不可撤销。',
233
+ resetSuccess: '已重置所有配置', resetFail: '重置失败',
234
+ refresh: '刷新', upgradeTitle: '升级工具',
235
+ nodeVersion: 'Node.js 版本', envVars: '环境变量', set: '已设置', notSet: '未设置',
236
+ connectivity: 'API 连通性', connected: '连通', notConnected: '未连通',
237
+ modelsAvailable: '个模型可用', toolsStatus: '工具状态',
238
+ savedAt: '保存时间',
239
+ step1: 'API Key', step2: '选择模型', step3: '选择工具', step4: '执行配置', step5: '完成',
240
+ configOk: '配置成功', configErr: '配置失败', configManual: '需手动配置',
241
+ configSkip: '已跳过', configWarning: '有警告',
242
+ hotReload: '热切换,无需重启', needRestart: '重启终端生效',
243
+ close: '关闭', noApiKey: '未登录',
244
+ loginFirst: '请先登录后查看', times: '次',
245
+ },
246
+ 'en': {
247
+ dashboard: 'Dashboard', setup: 'Setup', tools: 'Tools', doctor: 'Diagnostics',
248
+ loginStatus: 'Login Status', balance: 'Balance', quickActions: 'Quick Actions',
249
+ loggedIn: 'Logged In', notLoggedIn: 'Not Logged In', keyValid: 'Key Valid', keyInvalid: 'Key Invalid',
250
+ checking: 'Checking...', login: 'Login', logout: 'Logout', recharge: 'Recharge',
251
+ balanceLabel: 'Balance', todayCost: 'Today', monthCost: 'Month', totalCalls: 'Total Calls',
252
+ goSetup: 'Setup', goDoctor: 'Diagnostics', goUpgrade: 'Upgrade',
253
+ apiKey: 'API Key', apiKeyPlaceholder: 'Enter API Key (cr_xxx)',
254
+ validate: 'Validate', validating: 'Validating...',
255
+ next: 'Next', prev: 'Back', startSetup: 'Start', done: 'Done',
256
+ selectModels: 'Select Models', selectTools: 'Select Tools', configuring: 'Configuring', summary: 'Summary',
257
+ installed: 'Installed', notInstalled: 'Not Installed', configured: 'Configured', notConfigured: 'Not Configured',
258
+ version: 'Version', install: 'Install', configure: 'Configure', reset: 'Reset', upgrade: 'Upgrade',
259
+ autoInstall: 'Auto-install missing tools',
260
+ confirmReset: 'Reset all HolySheep config? This cannot be undone.',
261
+ resetSuccess: 'All config reset', resetFail: 'Reset failed',
262
+ refresh: 'Refresh', upgradeTitle: 'Upgrade Tools',
263
+ nodeVersion: 'Node.js Version', envVars: 'Environment Variables', set: 'Set', notSet: 'Not Set',
264
+ connectivity: 'API Connectivity', connected: 'Connected', notConnected: 'Not Connected',
265
+ modelsAvailable: 'models available', toolsStatus: 'Tool Status',
266
+ savedAt: 'Saved at',
267
+ step1: 'API Key', step2: 'Models', step3: 'Tools', step4: 'Configure', step5: 'Done',
268
+ configOk: 'Configured', configErr: 'Failed', configManual: 'Manual Config',
269
+ configSkip: 'Skipped', configWarning: 'Warning',
270
+ hotReload: 'Hot reload, no restart', needRestart: 'Restart terminal to apply',
271
+ close: 'Close', noApiKey: 'Not logged in',
272
+ loginFirst: 'Please login first', times: 'calls',
273
+ },
274
+ }
275
+ const lang = navigator.language.startsWith('zh') ? 'zh' : 'en'
276
+ const t = (k) => I18N[lang]?.[k] || I18N['en'][k] || k
277
+
278
+ // ── State ─────────────────────────────────────────────────────────────────
279
+ let currentTab = 'dashboard'
280
+ let setupStep = 0
281
+ let setupState = { apiKey: '', models: [], toolIds: [], autoInstall: true }
282
+ let allModels = []
283
+ let allTools = []
284
+
285
+ // ── Init ──────────────────────────────────────────────────────────────────
286
+ document.addEventListener('DOMContentLoaded', () => {
287
+ // Set i18n labels
288
+ document.getElementById('tab-dashboard').textContent = t('dashboard')
289
+ document.getElementById('tab-setup').textContent = t('setup')
290
+ document.getElementById('tab-tools').textContent = t('tools')
291
+ document.getElementById('tab-doctor').textContent = t('doctor')
292
+ document.getElementById('lbl-login-status').textContent = t('loginStatus')
293
+ document.getElementById('lbl-balance').textContent = t('balance')
294
+ document.getElementById('lbl-quick-actions').textContent = t('quickActions')
295
+ document.getElementById('btn-go-setup').textContent = t('goSetup')
296
+ document.getElementById('btn-go-doctor').textContent = t('goDoctor')
297
+ document.getElementById('btn-go-upgrade').textContent = t('goUpgrade')
298
+ document.getElementById('lbl-tools-title').textContent = t('tools')
299
+ document.getElementById('btn-refresh-tools').textContent = t('refresh')
300
+ document.getElementById('lbl-doctor-title').textContent = t('doctor')
301
+ document.getElementById('btn-refresh-doctor').textContent = t('refresh')
302
+ document.getElementById('lbl-upgrade-title').textContent = t('upgradeTitle')
303
+
304
+ // Tab clicks
305
+ document.querySelectorAll('.tab').forEach(tab => {
306
+ tab.addEventListener('click', () => switchTab(tab.dataset.page))
307
+ })
308
+
309
+ // Load initial data
310
+ loadDashboard()
311
+ })
312
+
313
+ function switchTab(page) {
314
+ currentTab = page
315
+ document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.page === page))
316
+ document.querySelectorAll('.page').forEach(p => p.classList.toggle('active', p.id === 'page-' + page))
317
+ if (page === 'dashboard') loadDashboard()
318
+ if (page === 'tools') loadTools()
319
+ if (page === 'doctor') loadDoctor()
320
+ if (page === 'setup') initSetup()
321
+ }
322
+
323
+ // ── API helpers ───────────────────────────────────────────────────────────
324
+ async function api(path, opts) {
325
+ const res = await fetch('/api/' + path, opts)
326
+ return res.json()
327
+ }
328
+
329
+ // ── Dashboard ─────────────────────────────────────────────────────────────
330
+ async function loadDashboard() {
331
+ loadStatus()
332
+ loadBalance()
333
+ }
334
+
335
+ async function loadStatus() {
336
+ const el = document.getElementById('login-status-content')
337
+ el.innerHTML = `<span class="text-muted">${t('checking')}</span>`
338
+ try {
339
+ const data = await api('status')
340
+ document.getElementById('version').textContent = 'v' + data.version
341
+ if (data.loggedIn) {
342
+ el.innerHTML = `
343
+ <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px">
344
+ <span class="dot dot-ok"></span>
345
+ <span style="font-weight:600">${t('loggedIn')}</span>
346
+ </div>
347
+ <div class="text-sm mono" style="margin-bottom:4px">Key: ${esc(data.apiKey)}</div>
348
+ ${data.savedAt ? `<div class="text-sm text-muted">${t('savedAt')}: ${new Date(data.savedAt).toLocaleString()}</div>` : ''}
349
+ <div class="mt">
350
+ <button class="btn-danger btn-sm" onclick="doLogout()">${t('logout')}</button>
351
+ </div>`
352
+ } else {
353
+ el.innerHTML = `
354
+ <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px">
355
+ <span class="dot dot-gray"></span>
356
+ <span>${t('notLoggedIn')}</span>
357
+ </div>
358
+ <div style="display:flex;gap:8px;align-items:center;margin-top:8px">
359
+ <input type="password" id="dash-key" placeholder="${t('apiKeyPlaceholder')}" style="flex:1">
360
+ <button class="btn-primary btn-sm" onclick="doLogin()">${t('login')}</button>
361
+ </div>
362
+ <div class="text-sm text-muted mt">
363
+ <a href="https://holysheep.ai/register" target="_blank">holysheep.ai/register</a>
364
+ </div>`
365
+ }
366
+ } catch (e) {
367
+ el.innerHTML = `<span class="text-muted">Error: ${esc(e.message)}</span>`
368
+ }
369
+ }
370
+
371
+ async function loadBalance() {
372
+ const el = document.getElementById('balance-content')
373
+ el.innerHTML = `<span class="text-muted">${t('checking')}</span>`
374
+ try {
375
+ const data = await api('balance')
376
+ if (data.error) {
377
+ el.innerHTML = `<span class="text-muted">${data.error === '未登录' ? t('loginFirst') : esc(data.error)}</span>`
378
+ return
379
+ }
380
+ el.innerHTML = `
381
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
382
+ <div class="stat"><div class="value">$${data.balance.toFixed(2)}</div><div class="label">${t('balanceLabel')}</div></div>
383
+ <div class="stat"><div class="value">$${data.todayCost.toFixed(4)}</div><div class="label">${t('todayCost')}</div></div>
384
+ <div class="stat"><div class="value">$${data.monthCost.toFixed(4)}</div><div class="label">${t('monthCost')}</div></div>
385
+ <div class="stat"><div class="value">${data.totalCalls.toLocaleString()}</div><div class="label">${t('totalCalls')}</div></div>
386
+ </div>
387
+ <div class="mt text-sm"><a href="https://holysheep.ai/app/recharge" target="_blank">${t('recharge')} →</a></div>`
388
+ } catch (e) {
389
+ el.innerHTML = `<span class="text-muted">${t('loginFirst')}</span>`
390
+ }
391
+ }
392
+
393
+ async function doLogin() {
394
+ const input = document.getElementById('dash-key')
395
+ const key = input.value.trim()
396
+ if (!key) return
397
+ input.disabled = true
398
+ try {
399
+ const data = await api('login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ apiKey: key }) })
400
+ if (data.success) { loadDashboard() } else { alert(data.message) }
401
+ } catch (e) { alert(e.message) }
402
+ input.disabled = false
403
+ }
404
+
405
+ async function doLogout() {
406
+ await api('logout', { method: 'POST' })
407
+ loadDashboard()
408
+ }
409
+
410
+ // ── Setup Wizard ──────────────────────────────────────────────────────────
411
+ async function initSetup() {
412
+ setupStep = 0
413
+ setupState = { apiKey: '', models: [], toolIds: [], autoInstall: true }
414
+ // Load models & tools
415
+ try {
416
+ allModels = await api('models')
417
+ allTools = await api('tools')
418
+ const status = await api('status')
419
+ if (status.loggedIn) {
420
+ const config = await api('whoami')
421
+ // We have the masked key, but we need the real one for setup
422
+ // Check if we already have a key saved
423
+ setupState.apiKey = '__saved__'
424
+ }
425
+ } catch {}
426
+ renderSetup()
427
+ }
428
+
429
+ function renderSetup() {
430
+ const stepsEl = document.getElementById('setup-steps')
431
+ const contentEl = document.getElementById('setup-content')
432
+ const stepLabels = [t('step1'), t('step2'), t('step3'), t('step4'), t('step5')]
433
+ stepsEl.innerHTML = stepLabels.map((s, i) =>
434
+ `<div class="step ${i === setupStep ? 'active' : i < setupStep ? 'done' : ''}">${i + 1}. ${s}</div>`
435
+ ).join('')
436
+
437
+ if (setupStep === 0) renderSetupStep1(contentEl)
438
+ else if (setupStep === 1) renderSetupStep2(contentEl)
439
+ else if (setupStep === 2) renderSetupStep3(contentEl)
440
+ else if (setupStep === 3) renderSetupStep4(contentEl)
441
+ else if (setupStep === 4) renderSetupStep5(contentEl)
442
+ }
443
+
444
+ function renderSetupStep1(el) {
445
+ const saved = setupState.apiKey === '__saved__'
446
+ el.innerHTML = `
447
+ <div class="card">
448
+ <h3>${t('apiKey')}</h3>
449
+ ${saved ? `
450
+ <div style="display:flex;align-items:center;gap:8px;margin-bottom:12px">
451
+ <span class="dot dot-ok"></span>
452
+ <span>${t('loggedIn')}</span>
453
+ </div>
454
+ <p class="text-sm text-muted mb">${lang === 'zh' ? '将使用已保存的 API Key 继续配置' : 'Will use saved API Key'}</p>
455
+ <p class="text-sm text-muted mb">${lang === 'zh' ? '或输入新的 Key:' : 'Or enter a new Key:'}</p>
456
+ ` : ''}
457
+ <div style="display:flex;gap:8px">
458
+ <input type="password" id="setup-key" placeholder="${t('apiKeyPlaceholder')}" style="flex:1">
459
+ <button class="btn-secondary btn-sm" onclick="validateSetupKey()" id="setup-validate-btn">${t('validate')}</button>
460
+ </div>
461
+ <div id="setup-key-status" class="text-sm mt"></div>
462
+ <div class="mt" style="text-align:right">
463
+ <button class="btn-primary" onclick="setupNext()">${t('next')}</button>
464
+ </div>
465
+ </div>`
466
+ }
467
+
468
+ async function validateSetupKey() {
469
+ const input = document.getElementById('setup-key')
470
+ const status = document.getElementById('setup-key-status')
471
+ const key = input.value.trim()
472
+ if (!key) return
473
+ if (!key.startsWith('cr_')) { status.innerHTML = `<span style="color:var(--error)">Key must start with cr_</span>`; return }
474
+ status.innerHTML = `<span class="text-muted">${t('validating')}</span>`
475
+ const btn = document.getElementById('setup-validate-btn')
476
+ btn.disabled = true
477
+ try {
478
+ const res = await api('login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ apiKey: key }) })
479
+ if (res.success) {
480
+ setupState.apiKey = key
481
+ status.innerHTML = `<span style="color:var(--success)">✓ ${t('keyValid')}</span>`
482
+ loadDashboard()
483
+ } else {
484
+ status.innerHTML = `<span style="color:var(--error)">✗ ${res.message}</span>`
485
+ }
486
+ } catch (e) {
487
+ status.innerHTML = `<span style="color:var(--error)">✗ ${e.message}</span>`
488
+ }
489
+ btn.disabled = false
490
+ }
491
+
492
+ function setupNext() {
493
+ if (setupStep === 0) {
494
+ const input = document.getElementById('setup-key')
495
+ if (input && input.value.trim()) setupState.apiKey = input.value.trim()
496
+ if (!setupState.apiKey) { alert(lang === 'zh' ? '请输入或验证 API Key' : 'Please enter API Key'); return }
497
+ }
498
+ if (setupStep === 1) {
499
+ setupState.models = [...document.querySelectorAll('#model-checks input:checked')].map(c => c.value)
500
+ if (setupState.models.length === 0) { alert(lang === 'zh' ? '请至少选择一个模型' : 'Select at least one model'); return }
501
+ }
502
+ if (setupStep === 2) {
503
+ setupState.toolIds = [...document.querySelectorAll('#tool-checks input:checked')].map(c => c.value)
504
+ setupState.autoInstall = document.getElementById('auto-install-toggle')?.checked || false
505
+ if (setupState.toolIds.length === 0) { alert(lang === 'zh' ? '请至少选择一个工具' : 'Select at least one tool'); return }
506
+ }
507
+ setupStep++
508
+ renderSetup()
509
+ if (setupStep === 3) executeSetup()
510
+ }
511
+
512
+ function setupPrev() {
513
+ if (setupStep > 0) { setupStep--; renderSetup() }
514
+ }
515
+
516
+ function renderSetupStep2(el) {
517
+ el.innerHTML = `
518
+ <div class="card">
519
+ <h3>${t('selectModels')}</h3>
520
+ <div class="checkbox-group" id="model-checks">
521
+ ${allModels.map(m => `
522
+ <label class="checkbox-item">
523
+ <input type="checkbox" value="${m.id}" checked>
524
+ <div>
525
+ <div class="cb-label">${esc(m.label)}</div>
526
+ <div class="cb-desc">${esc(m.id)} — ${esc(m.desc)}</div>
527
+ </div>
528
+ </label>
529
+ `).join('')}
530
+ </div>
531
+ <div class="mt" style="display:flex;justify-content:space-between">
532
+ <button class="btn-secondary" onclick="setupPrev()">${t('prev')}</button>
533
+ <button class="btn-primary" onclick="setupNext()">${t('next')}</button>
534
+ </div>
535
+ </div>`
536
+ }
537
+
538
+ function renderSetupStep3(el) {
539
+ const installed = allTools.filter(t => t.installed)
540
+ const notInstalled = allTools.filter(t => !t.installed)
541
+ el.innerHTML = `
542
+ <div class="card">
543
+ <h3>${t('selectTools')}</h3>
544
+ <div class="checkbox-group" id="tool-checks">
545
+ ${installed.length ? `<div class="text-sm text-muted mb" style="padding:4px 0">${t('installed')}</div>` : ''}
546
+ ${installed.map(tool => `
547
+ <label class="checkbox-item">
548
+ <input type="checkbox" value="${tool.id}" checked>
549
+ <div style="flex:1">
550
+ <div class="cb-label">${esc(tool.name)} <span class="badge badge-ok">${t('installed')}</span>
551
+ ${tool.configured ? `<span class="badge badge-ok">${t('configured')}</span>` : ''}
552
+ </div>
553
+ <div class="cb-desc">${tool.version || ''}</div>
554
+ </div>
555
+ </label>
556
+ `).join('')}
557
+ ${notInstalled.length ? `<div class="text-sm text-muted mb" style="padding:8px 0 4px">${t('notInstalled')}</div>` : ''}
558
+ ${notInstalled.map(tool => `
559
+ <label class="checkbox-item">
560
+ <input type="checkbox" value="${tool.id}">
561
+ <div style="flex:1">
562
+ <div class="cb-label">${esc(tool.name)} <span class="badge badge-gray">${t('notInstalled')}</span>
563
+ ${tool.canAutoInstall ? `<span class="badge badge-warn">${lang === 'zh' ? '可自动安装' : 'Auto-installable'}</span>` : ''}
564
+ </div>
565
+ <div class="cb-desc">${esc(tool.installCmd)}</div>
566
+ </div>
567
+ </label>
568
+ `).join('')}
569
+ </div>
570
+ <label class="checkbox-item mt" style="background:var(--primary-dim)">
571
+ <input type="checkbox" id="auto-install-toggle" checked>
572
+ <div class="cb-label">${t('autoInstall')}</div>
573
+ </label>
574
+ <div class="mt" style="display:flex;justify-content:space-between">
575
+ <button class="btn-secondary" onclick="setupPrev()">${t('prev')}</button>
576
+ <button class="btn-primary" onclick="setupNext()">${t('startSetup')}</button>
577
+ </div>
578
+ </div>`
579
+ }
580
+
581
+ function renderSetupStep4(el) {
582
+ el.innerHTML = `
583
+ <div class="card">
584
+ <h3>${t('configuring')}...</h3>
585
+ <div class="console" id="setup-console"></div>
586
+ </div>`
587
+ }
588
+
589
+ async function executeSetup() {
590
+ const consoleEl = document.getElementById('setup-console')
591
+ const actualKey = setupState.apiKey === '__saved__' ? null : setupState.apiKey
592
+
593
+ // If using saved key, we need to get it from the backend
594
+ let keyToUse = actualKey
595
+ if (!keyToUse) {
596
+ // Fetch real key from server config — we'll send a special marker
597
+ // Actually, the server can read the saved key itself
598
+ keyToUse = '__use_saved__'
599
+ }
600
+
601
+ const body = JSON.stringify({
602
+ apiKey: keyToUse,
603
+ models: setupState.models,
604
+ toolIds: setupState.toolIds,
605
+ autoInstall: setupState.autoInstall,
606
+ })
607
+
608
+ try {
609
+ const res = await fetch('/api/setup', {
610
+ method: 'POST',
611
+ headers: { 'Content-Type': 'application/json' },
612
+ body,
613
+ })
614
+
615
+ const reader = res.body.getReader()
616
+ const decoder = new TextDecoder()
617
+ let buffer = ''
618
+
619
+ while (true) {
620
+ const { done, value } = await reader.read()
621
+ if (done) break
622
+ buffer += decoder.decode(value, { stream: true })
623
+ const parts = buffer.split('\n\n')
624
+ buffer = parts.pop()
625
+ for (const part of parts) {
626
+ const line = part.split('\n').find(l => l.startsWith('data: '))
627
+ if (!line) continue
628
+ const data = JSON.parse(line.slice(6))
629
+ appendConsole(consoleEl, data)
630
+ if (data.type === 'done') {
631
+ setupState.summary = data.summary
632
+ setupStep = 4
633
+ renderSetup()
634
+ return
635
+ }
636
+ }
637
+ }
638
+ } catch (e) {
639
+ appendConsole(consoleEl, { type: 'error', message: e.message })
640
+ }
641
+ }
642
+
643
+ function appendConsole(el, data) {
644
+ if (data.type === 'progress') {
645
+ const cls = data.status === 'ok' ? 'ok' : data.status === 'error' ? 'err' : data.status === 'warning' ? 'warn' : 'info'
646
+ el.innerHTML += `<span class="${cls}">${data.status === 'ok' ? '✓' : data.status === 'error' ? '✗' : '→'} ${esc(data.message)}</span>\n`
647
+ } else if (data.type === 'output') {
648
+ el.innerHTML += esc(data.text)
649
+ } else if (data.type === 'error') {
650
+ el.innerHTML += `<span class="err">✗ ${esc(data.message)}</span>\n`
651
+ }
652
+ el.scrollTop = el.scrollHeight
653
+ }
654
+
655
+ function renderSetupStep5(el) {
656
+ const s = setupState.summary || { ok: 0, errors: 0, total: 0, results: [] }
657
+ const results = s.results || []
658
+ el.innerHTML = `
659
+ <div class="card">
660
+ <h3>✅ ${t('done')}</h3>
661
+ <div style="display:flex;gap:20px;margin:16px 0">
662
+ <div class="stat"><div class="value" style="color:var(--success)">${s.ok}</div><div class="label">${t('configOk')}</div></div>
663
+ <div class="stat"><div class="value" style="color:var(--error)">${s.errors}</div><div class="label">${t('configErr')}</div></div>
664
+ </div>
665
+ <div>
666
+ ${results.map(r => {
667
+ const icon = r.status === 'ok' ? '✓' : r.status === 'error' ? '✗' : r.status === 'manual' ? '⚠' : r.status === 'skip' ? '○' : '!'
668
+ const badge = r.status === 'ok' ? 'badge-ok' : r.status === 'error' ? 'badge-err' : 'badge-warn'
669
+ const label = t('config' + r.status.charAt(0).toUpperCase() + r.status.slice(1)) || r.status
670
+ return `
671
+ <div class="check-row">
672
+ <span>${icon}</span>
673
+ <span class="check-label">${esc(r.tool)}</span>
674
+ <span class="badge ${badge}">${label}</span>
675
+ ${r.file ? `<span class="check-detail">${esc(r.file)}</span>` : ''}
676
+ ${r.hot ? `<span class="text-sm text-muted">${t('hotReload')}</span>` : ''}
677
+ </div>`
678
+ }).join('')}
679
+ </div>
680
+ <div class="mt" style="text-align:right">
681
+ <button class="btn-primary" onclick="switchTab('dashboard')">${t('done')}</button>
682
+ </div>
683
+ </div>`
684
+ }
685
+
686
+ // ── Tools ─────────────────────────────────────────────────────────────────
687
+ async function loadTools() {
688
+ const el = document.getElementById('tools-list')
689
+ el.innerHTML = `<span class="text-muted">${t('checking')}</span>`
690
+ try {
691
+ const tools = await api('tools')
692
+ allTools = tools
693
+ el.innerHTML = `<div class="card-grid">${tools.map(tool => `
694
+ <div class="tool-card">
695
+ <div class="tool-info">
696
+ <div class="name">${esc(tool.name)}</div>
697
+ <div class="meta">
698
+ ${tool.installed
699
+ ? `<span class="badge badge-ok">${t('installed')}</span> ${tool.configured ? `<span class="badge badge-ok">${t('configured')}</span>` : `<span class="badge badge-warn">${t('notConfigured')}</span>`}`
700
+ : `<span class="badge badge-gray">${t('notInstalled')}</span>`}
701
+ ${tool.version ? `<span class="text-muted" style="margin-left:4px">${esc(tool.version)}</span>` : ''}
702
+ </div>
703
+ ${tool.hint ? `<div class="meta">${esc(tool.hint)}</div>` : ''}
704
+ ${tool.launchCmd ? `<div class="meta mono">${esc(tool.launchCmd)}</div>` : ''}
705
+ </div>
706
+ <div class="tool-actions">
707
+ ${!tool.installed && tool.canAutoInstall ? `<button class="btn-secondary btn-sm" onclick="installTool('${tool.id}','${esc(tool.name)}')">${t('install')}</button>` : ''}
708
+ </div>
709
+ </div>
710
+ `).join('')}</div>`
711
+ } catch (e) {
712
+ el.innerHTML = `<span class="text-muted">Error: ${esc(e.message)}</span>`
713
+ }
714
+ }
715
+
716
+ async function installTool(id, name) {
717
+ const el = document.getElementById('tools-list')
718
+ const consoleHtml = `<div class="card mt"><h3>${t('install')}: ${esc(name)}</h3><div class="console" id="install-console"></div></div>`
719
+ el.insertAdjacentHTML('beforeend', consoleHtml)
720
+ const consoleEl = document.getElementById('install-console')
721
+
722
+ try {
723
+ const res = await fetch('/api/tool/install', {
724
+ method: 'POST',
725
+ headers: { 'Content-Type': 'application/json' },
726
+ body: JSON.stringify({ toolId: id }),
727
+ })
728
+ const reader = res.body.getReader()
729
+ const decoder = new TextDecoder()
730
+ let buffer = ''
731
+ while (true) {
732
+ const { done, value } = await reader.read()
733
+ if (done) break
734
+ buffer += decoder.decode(value, { stream: true })
735
+ const parts = buffer.split('\n\n')
736
+ buffer = parts.pop()
737
+ for (const part of parts) {
738
+ const line = part.split('\n').find(l => l.startsWith('data: '))
739
+ if (!line) continue
740
+ const data = JSON.parse(line.slice(6))
741
+ if (data.type === 'output') consoleEl.innerHTML += esc(data.text)
742
+ else if (data.type === 'done') {
743
+ consoleEl.innerHTML += data.success
744
+ ? `\n<span class="ok">✓ ${lang === 'zh' ? '安装完成' : 'Installed'}</span>\n`
745
+ : `\n<span class="err">✗ ${lang === 'zh' ? '安装失败' : 'Install failed'}</span>\n`
746
+ setTimeout(() => loadTools(), 1000)
747
+ }
748
+ consoleEl.scrollTop = consoleEl.scrollHeight
749
+ }
750
+ }
751
+ } catch (e) {
752
+ consoleEl.innerHTML += `<span class="err">Error: ${esc(e.message)}</span>`
753
+ }
754
+ }
755
+
756
+ // ── Doctor ─────────────────────────────────────────────────────────────────
757
+ async function loadDoctor() {
758
+ const el = document.getElementById('doctor-content')
759
+ el.innerHTML = `<span class="text-muted">${t('checking')}</span>`
760
+ try {
761
+ const d = await api('doctor')
762
+ el.innerHTML = `
763
+ <div class="card">
764
+ <h3>${t('nodeVersion')}</h3>
765
+ <div class="check-row">
766
+ <span class="dot ${d.node.ok ? 'dot-ok' : 'dot-err'}"></span>
767
+ <span class="check-label">Node.js ${esc(d.node.version)}</span>
768
+ <span class="badge ${d.node.ok ? 'badge-ok' : 'badge-err'}">${d.node.ok ? '≥ 16 ✓' : '< 16 ✗'}</span>
769
+ </div>
770
+ </div>
771
+
772
+ <div class="card">
773
+ <h3>API Key</h3>
774
+ <div class="check-row">
775
+ <span class="dot ${d.apiKey.set ? 'dot-ok' : 'dot-err'}"></span>
776
+ <span class="check-label">${d.apiKey.set ? esc(d.apiKey.masked) : t('notSet')}</span>
777
+ </div>
778
+ </div>
779
+
780
+ <div class="card">
781
+ <h3>${t('envVars')}</h3>
782
+ ${Object.entries(d.envVars).map(([k, v]) => `
783
+ <div class="check-row">
784
+ <span class="dot ${v ? 'dot-ok' : 'dot-gray'}"></span>
785
+ <span class="check-label mono text-sm">${k}</span>
786
+ <span class="check-detail">${v ? t('set') : t('notSet')}</span>
787
+ </div>
788
+ `).join('')}
789
+ </div>
790
+
791
+ <div class="card">
792
+ <h3>${t('connectivity')}</h3>
793
+ <div class="check-row">
794
+ <span class="dot ${d.connectivity.ok ? 'dot-ok' : 'dot-err'}"></span>
795
+ <span class="check-label">${d.connectivity.ok ? t('connected') : t('notConnected')}</span>
796
+ ${d.connectivity.ok ? `<span class="check-detail">${d.connectivity.modelCount} ${t('modelsAvailable')}</span>` : ''}
797
+ </div>
798
+ </div>
799
+
800
+ <div class="card">
801
+ <h3>${t('toolsStatus')}</h3>
802
+ ${d.tools.map(tool => `
803
+ <div class="check-row">
804
+ <span class="dot ${tool.installed ? (tool.configured ? 'dot-ok' : 'dot-warn') : 'dot-gray'}"></span>
805
+ <span class="check-label">${esc(tool.name)}</span>
806
+ ${tool.installed
807
+ ? `<span class="badge ${tool.configured ? 'badge-ok' : 'badge-warn'}">${tool.configured ? t('configured') : t('notConfigured')}</span>
808
+ ${tool.version ? `<span class="check-detail">${esc(tool.version)}</span>` : ''}`
809
+ : `<span class="badge badge-gray">${t('notInstalled')}</span>`}
810
+ </div>
811
+ `).join('')}
812
+ </div>`
813
+ } catch (e) {
814
+ el.innerHTML = `<span class="text-muted">Error: ${esc(e.message)}</span>`
815
+ }
816
+ }
817
+
818
+ // ── Upgrade ───────────────────────────────────────────────────────────────
819
+ async function runUpgrade() {
820
+ const modal = document.getElementById('upgrade-modal')
821
+ const consoleEl = document.getElementById('upgrade-console')
822
+ modal.classList.remove('hidden')
823
+ consoleEl.innerHTML = ''
824
+
825
+ try {
826
+ const res = await fetch('/api/upgrade', { method: 'POST' })
827
+ const reader = res.body.getReader()
828
+ const decoder = new TextDecoder()
829
+ let buffer = ''
830
+ while (true) {
831
+ const { done, value } = await reader.read()
832
+ if (done) break
833
+ buffer += decoder.decode(value, { stream: true })
834
+ const parts = buffer.split('\n\n')
835
+ buffer = parts.pop()
836
+ for (const part of parts) {
837
+ const line = part.split('\n').find(l => l.startsWith('data: '))
838
+ if (!line) continue
839
+ const data = JSON.parse(line.slice(6))
840
+ if (data.type === 'tool') {
841
+ const cls = data.status === 'ok' ? 'ok' : data.status === 'error' ? 'err' : data.status === 'not-installed' ? 'warn' : 'info'
842
+ const msg = data.status === 'not-installed' ? `${data.name}: ${t('notInstalled')}`
843
+ : data.status === 'upgrading' ? `${data.name}: ${t('upgrade')}... (${data.localVer || '?'})`
844
+ : data.status === 'ok' ? `${data.name}: ✓ ${data.localVer || '?'} → ${data.newVer || 'latest'}`
845
+ : `${data.name}: ✗ ${t('configErr')}`
846
+ consoleEl.innerHTML += `<span class="${cls}">${msg}</span>\n`
847
+ } else if (data.type === 'output') {
848
+ consoleEl.innerHTML += esc(data.text)
849
+ } else if (data.type === 'done') {
850
+ consoleEl.innerHTML += `\n<span class="ok">✓ ${t('done')}</span>\n`
851
+ }
852
+ consoleEl.scrollTop = consoleEl.scrollHeight
853
+ }
854
+ }
855
+ } catch (e) {
856
+ consoleEl.innerHTML += `<span class="err">Error: ${esc(e.message)}</span>`
857
+ }
858
+ }
859
+
860
+ function closeUpgrade() {
861
+ document.getElementById('upgrade-modal').classList.add('hidden')
862
+ }
863
+
864
+ // ── Util ──────────────────────────────────────────────────────────────────
865
+ function esc(s) {
866
+ if (!s) return ''
867
+ const d = document.createElement('div')
868
+ d.textContent = String(s)
869
+ return d.innerHTML
870
+ }
871
+ </script>
872
+ </body>
873
+ </html>