dsh-zcode-startplan 0.0.0-stage → 0.2.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/client.js ADDED
@@ -0,0 +1,659 @@
1
+ /**
2
+ * Client 模块:官方插件详情页(Plugin Manager → ZCode Start Plan)里的
3
+ * 「账号池管理」面板。
4
+ *
5
+ * ## 挂载点(照抄 dsh-workbuddy-connect 的实证写法)
6
+ *
7
+ * `plugins.bundle.config` 是官方插件页按**包名 key 派发**的配置区块座位,
8
+ * 渲染在详情页「包含的组件」列表上方;宿主只在本包的详情页派发
9
+ * `key === 'dsh-zcode-startplan'` 的条目,列表页则以 `view === 'summary'`
10
+ * 请求一行简介。组件无需自己做 subject 过滤。
11
+ *
12
+ * ## 数据通道
13
+ *
14
+ * 面板与 Host 之间走同源 fetch:宿主 webserver 上的
15
+ * `/api/zcode-start-plan/*` 路由(`lib/manage-routes.js`,仅 loopback)。
16
+ * 凭据永不外发 —— Host 侧已做脱敏;设备授权的 secret 也留在 Host。
17
+ *
18
+ * ## 实现约束(与宿主一致)
19
+ *
20
+ * - React 来自浏览器模块表(`require('react')`),不自带、不走 CDN;
21
+ * - 样式用宿主主题 token(`--dsw-alias-*`),以组件局部 `<style>` 注入,
22
+ * 卸载即移除;
23
+ * - 工厂无副作用;slot 注册在 `ctx.slots.inject(ownerKey, cb)` 里完成,
24
+ * 宿主负责其生命周期。
25
+ */
26
+ window.__ModuleLoader__.load({
27
+ id: 'dsh-zcode-startplan',
28
+ factory(require) {
29
+ const React = require('react')
30
+ const h = React.createElement
31
+ const { useCallback, useEffect, useRef, useState } = React
32
+
33
+ const SLOT = 'plugins.bundle.config'
34
+ /** 宿主按包名派发此座位(workbuddy 实证:key 必须与安装的包名一字不差)。 */
35
+ const BUNDLE_KEY = 'dsh-zcode-startplan'
36
+ const API = '/api/zcode-start-plan'
37
+ const CONFIRM_RESET_MS = 3000
38
+
39
+ const CSS = `
40
+ .zsp-panel{display:flex;flex-direction:column;gap:10px;width:100%;min-width:0;color:var(--dsw-alias-label-primary);font-size:12.5px;line-height:18px}
41
+ .zsp-head{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
42
+ .zsp-title{margin:0;font-size:13px;font-weight:600;line-height:20px}
43
+ .zsp-muted{color:var(--dsw-alias-label-tertiary);font-size:12px;word-break:break-word;min-width:0}
44
+ .zsp-spacer{flex:1}
45
+ .zsp-btn{font:inherit;cursor:pointer;border:1px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-sm,6px);color:var(--dsw-alias-label-primary);background:transparent;padding:3px 10px;font-size:12px;line-height:18px;flex:none}
46
+ .zsp-btn:hover:enabled{background:var(--dsw-alias-interactive-bg-hover)}
47
+ .zsp-btn:disabled{cursor:default;opacity:.55}
48
+ .zsp-btn:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
49
+ .zsp-btn[data-danger=true]{color:var(--dsw-alias-label-danger)}
50
+ .zsp-error{color:var(--dsw-alias-label-danger);margin:0;font-size:12px;word-break:break-word}
51
+ .zsp-ok{color:var(--dsw-alias-state-success-primary);font-size:12px;word-break:break-word;margin:0}
52
+ .zsp-card{display:flex;flex-direction:column;gap:6px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);border-radius:8px;padding:10px 12px;min-width:0}
53
+ .zsp-card[data-next=true]{border-color:var(--dsw-alias-state-business-primary)}
54
+ .zsp-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px;min-width:0}
55
+ .zsp-dot{width:7px;height:7px;border-radius:50%;background:var(--dsw-alias-label-tertiary);flex:none}
56
+ .zsp-dot[data-on=true]{background:var(--dsw-alias-state-success-primary)}
57
+ .zsp-name{font-weight:600}
58
+ .zsp-name-edit{font:inherit;font-weight:600;color:inherit;background:transparent;border:0;padding:0;cursor:text;text-align:left}
59
+ .zsp-name-edit:hover:enabled{text-decoration:underline dotted var(--dsw-alias-label-tertiary)}
60
+ .zsp-name-edit:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
61
+ .zsp-name-input{font:inherit;font-weight:600;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-state-business-primary);border-radius:4px;padding:1px 6px;width:180px;max-width:100%}
62
+ .zsp-name-input:focus-visible{outline:none}
63
+ .zsp-chip{display:inline-flex;align-items:center;gap:4px;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;padding:1px 8px;font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary)}
64
+ .zsp-chip[data-limited=true]{color:var(--dsw-alias-label-danger);border-color:var(--dsw-alias-label-danger)}
65
+ .zsp-bar{height:6px;border-radius:3px;background:var(--dsw-alias-bg-layer-2);overflow:hidden;width:100%}
66
+ .zsp-bar>span{display:block;height:100%;background:var(--dsw-alias-state-business-primary)}
67
+ .zsp-actions{display:flex;flex-wrap:wrap;gap:6px;margin-top:2px}
68
+ .zsp-add{display:flex;flex-direction:column;gap:8px;border:1px dashed var(--dsw-alias-border-l2);border-radius:8px;padding:10px 12px;min-width:0}
69
+ .zsp-link{color:var(--dsw-alias-state-business-primary);word-break:break-all}
70
+ .zsp-select{position:relative;display:inline-flex;min-width:0}
71
+ .zsp-select-trigger{display:inline-flex;align-items:center;gap:8px;font:inherit;cursor:pointer;border:1px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-sm,6px);color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-layer-1);padding:4px 10px;font-size:12px;line-height:18px;min-width:0}
72
+ .zsp-select-trigger:hover{background:var(--dsw-alias-interactive-bg-hover)}
73
+ .zsp-select-trigger:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
74
+ .zsp-select-trigger[aria-expanded=true]{border-color:var(--dsw-alias-state-business-primary)}
75
+ .zsp-select-label{font-weight:600;white-space:nowrap}
76
+ .zsp-select-desc{color:var(--dsw-alias-label-tertiary);font-size:11px;white-space:nowrap}
77
+ .zsp-caret{flex:none;width:0;height:0;border-left:4px solid transparent;border-right:4px solid transparent;border-top:5px solid var(--dsw-alias-label-tertiary);transition:transform .15s ease}
78
+ .zsp-select-trigger[aria-expanded=true] .zsp-caret{transform:rotate(180deg)}
79
+ .zsp-select-menu{position:absolute;top:calc(100% + 4px);left:0;z-index:30;display:flex;flex-direction:column;gap:2px;min-width:100%;max-height:260px;overflow:auto;padding:4px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-2);box-shadow:0 8px 24px rgb(0 0 0 / 18%);animation:zsp-pop .14s ease}
80
+ @keyframes zsp-pop{from{opacity:0;transform:translateY(-3px)}to{opacity:1;transform:none}}
81
+ .zsp-option{display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:6px;cursor:pointer;color:var(--dsw-alias-label-primary);font-size:12px;line-height:18px;border:0;background:transparent;text-align:left;width:100%}
82
+ .zsp-option:hover,.zsp-option[data-active=true]{background:var(--dsw-alias-interactive-bg-hover)}
83
+ .zsp-option[aria-selected=true]{background:var(--dsw-alias-interactive-bg-selected,var(--dsw-alias-interactive-bg-hover))}
84
+ .zsp-option-check{flex:none;color:var(--dsw-alias-state-business-primary);font-size:12px;visibility:hidden}
85
+ .zsp-option[aria-selected=true] .zsp-option-check{visibility:visible}
86
+ .zsp-option-text{display:flex;flex-direction:column;min-width:0}
87
+ .zsp-badge{flex:none;display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:5px;font-size:10px;font-weight:700;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-interactive-bg-hover)}
88
+ @media (max-width: 520px){
89
+ .zsp-head{gap:6px}
90
+ .zsp-title{font-size:12.5px}
91
+ .zsp-card{padding:8px 10px}
92
+ .zsp-add{padding:8px 10px}
93
+ .zsp-actions{gap:4px}
94
+ }
95
+ `
96
+
97
+ /** 同源 API 调用;非 2xx 抛出服务端给的可读 error。 */
98
+ async function api(path, body) {
99
+ const init =
100
+ body === undefined
101
+ ? {}
102
+ : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }
103
+ const response = await fetch(API + path, init)
104
+ const data = await response.json().catch(() => ({}))
105
+ if (!response.ok) {
106
+ throw new Error(typeof data?.error === 'string' ? data.error : `HTTP ${response.status}`)
107
+ }
108
+ return data
109
+ }
110
+
111
+ /** 渠道显示名:直接用官方 provider id(zai / bigmodel),不做本地化称呼。 */
112
+ function channelLabel(channel) {
113
+ if (channel === 'zai') return 'zai'
114
+ if (channel === 'bigmodel') return 'bigmodel'
115
+ return channel === null || channel === undefined ? 'bigmodel' : String(channel)
116
+ }
117
+
118
+ function formatReset(resetAt) {
119
+ const ms = Number(resetAt)
120
+ if (!Number.isFinite(ms) || ms <= 0) return ''
121
+ return new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
122
+ }
123
+
124
+ /**
125
+ * 卡片标题行的可编辑昵称:点一下变输入框,Enter 提交 / Esc 或失焦取消。
126
+ * 什么都不填直接失焦 = 不改名。
127
+ */
128
+ function NicknameEdit(props) {
129
+ const { nickname, busy, onCommit } = props
130
+ const [editing, setEditing] = useState(false)
131
+ const [draft, setDraft] = useState(nickname)
132
+ const inputRef = useRef(undefined)
133
+
134
+ useEffect(() => {
135
+ if (editing === true) {
136
+ setDraft(nickname)
137
+ /** 进入编辑态后自动聚焦并全选,方便整段替换。 */
138
+ inputRef.current?.focus()
139
+ inputRef.current?.select()
140
+ }
141
+ }, [editing, nickname])
142
+
143
+ if (editing !== true) {
144
+ return h(
145
+ 'button',
146
+ {
147
+ type: 'button',
148
+ className: 'zsp-name zsp-name-edit',
149
+ title: '点击重命名',
150
+ disabled: busy,
151
+ onClick: () => setEditing(true),
152
+ },
153
+ nickname,
154
+ )
155
+ }
156
+ return h('input', {
157
+ ref: inputRef,
158
+ className: 'zsp-name-input',
159
+ value: draft,
160
+ disabled: busy,
161
+ maxLength: 40,
162
+ 'aria-label': '账号备注',
163
+ onChange: (event) => setDraft(event.target.value),
164
+ onKeyDown: (event) => {
165
+ if (event.key === 'Enter') {
166
+ const next = draft.trim()
167
+ if (next.length > 0 && next !== nickname) onCommit(next)
168
+ setEditing(false)
169
+ } else if (event.key === 'Escape') {
170
+ setEditing(false)
171
+ }
172
+ },
173
+ onBlur: () => setEditing(false),
174
+ })
175
+ }
176
+
177
+ /**
178
+ * 单个账号卡片:状态点、可编辑昵称、渠道、限流 chips、余额条、操作按钮。
179
+ * 按钮只有两个:「使用」(置顶,下次请求即用它)与「删除」。
180
+ */
181
+ function AccountCard(props) {
182
+ const { account, balance, busy, isNext, confirmId, setConfirmId, onUse, onRemove, onRename } = props
183
+ /** Host 下发的是 `modelRateLimits` 对象(model → resetAt),摊平成 chips。 */
184
+ const limited = Object.entries(account.modelRateLimits ?? {})
185
+ .map(([model, resetAt]) => ({ model, resetAt }))
186
+ .filter((item) => Number(item.resetAt) > Date.now())
187
+ const percent =
188
+ balance !== undefined &&
189
+ balance.ok === true &&
190
+ balance.enterprise !== true &&
191
+ typeof balance.total === 'number' &&
192
+ balance.total > 0
193
+ ? Math.max(0, Math.min(100, Math.round(((balance.remaining ?? 0) / balance.total) * 100)))
194
+ : undefined
195
+ return h(
196
+ 'div',
197
+ { className: 'zsp-card', 'data-next': isNext === true },
198
+ h(
199
+ 'div',
200
+ { className: 'zsp-row' },
201
+ h('span', { className: 'zsp-dot', 'data-on': account.enabled === true }),
202
+ h(NicknameEdit, {
203
+ nickname: account.nickname,
204
+ busy,
205
+ onCommit: (next) => onRename(next),
206
+ }),
207
+ h(
208
+ 'span',
209
+ { className: 'zsp-muted' },
210
+ `#${account.index} · ${channelLabel(account.channel)}`,
211
+ ),
212
+ limited.map((item) =>
213
+ h(
214
+ 'span',
215
+ { key: item.model, className: 'zsp-chip', 'data-limited': 'true' },
216
+ `${item.model} 限额至 ${formatReset(item.resetAt)}`,
217
+ ),
218
+ ),
219
+ ),
220
+ balance === undefined
221
+ ? null
222
+ : balance.ok === true
223
+ ? balance.enterprise === true
224
+ ? h('span', { className: 'zsp-muted' }, '企业版:服务端不下发用量数字')
225
+ : h(
226
+ React.Fragment,
227
+ null,
228
+ h('div', { className: 'zsp-bar' }, h('span', { style: { width: `${percent ?? 0}%` } })),
229
+ h(
230
+ 'span',
231
+ { className: 'zsp-muted' },
232
+ `剩余 ${balance.remaining}/${balance.total}${balance.planName ? ` · ${balance.planName}` : ''}`,
233
+ ),
234
+ )
235
+ : h('span', { className: 'zsp-error' }, balance.error ?? '余额查询失败'),
236
+ h(
237
+ 'div',
238
+ { className: 'zsp-actions' },
239
+ /**
240
+ * 「使用」= 把该账号置顶(手动顺序即选号优先级,`pick()` 取第一个
241
+ * 启用且未限流的账号);正在使用时显示「使用中」并禁用。
242
+ */
243
+ h(
244
+ 'button',
245
+ { className: 'zsp-btn', onClick: onUse, disabled: busy || isNext === true },
246
+ isNext === true ? '使用中' : '使用',
247
+ ),
248
+ confirmId === account.id
249
+ ? h(
250
+ 'button',
251
+ {
252
+ className: 'zsp-btn',
253
+ 'data-danger': 'true',
254
+ disabled: busy,
255
+ onClick: () => {
256
+ setConfirmId(undefined)
257
+ onRemove()
258
+ },
259
+ },
260
+ '确认删除?',
261
+ )
262
+ : h(
263
+ 'button',
264
+ {
265
+ className: 'zsp-btn',
266
+ 'data-danger': 'true',
267
+ disabled: busy,
268
+ onClick: () => {
269
+ setConfirmId(account.id)
270
+ setTimeout(
271
+ () => setConfirmId((current) => (current === account.id ? undefined : current)),
272
+ CONFIRM_RESET_MS,
273
+ )
274
+ },
275
+ },
276
+ '删除',
277
+ ),
278
+ ),
279
+ )
280
+ }
281
+
282
+ /**
283
+ * 渠道选项(登录渠道与 lib/upstream-api.js 的 LOGIN_CHANNELS 对齐)。
284
+ */
285
+ const CHANNEL_OPTIONS = [
286
+ { value: 'bigmodel', label: 'bigmodel', desc: '智谱开放平台 · bigmodel.cn', badge: '智' },
287
+ { value: 'zai', label: 'zai', desc: 'Z.AI · z.ai', badge: 'Z' },
288
+ ]
289
+
290
+ /**
291
+ * 现代化下拉(零依赖手写):渠道徽标 + 两行选项 + hover 高亮 +
292
+ * 点击外部关闭;不做键盘导航(用不到,从简)。
293
+ */
294
+ function ChannelSelect(props) {
295
+ const { value, onChange, disabled } = props
296
+ const [open, setOpen] = useState(false)
297
+ const rootRef = useRef(undefined)
298
+
299
+ const selected = CHANNEL_OPTIONS.find((item) => item.value === value) ?? CHANNEL_OPTIONS[0]
300
+
301
+ useEffect(() => {
302
+ if (open !== true) return undefined
303
+ const onPointerDown = (event) => {
304
+ if (rootRef.current !== undefined && !rootRef.current.contains(event.target)) setOpen(false)
305
+ }
306
+ document.addEventListener('pointerdown', onPointerDown, true)
307
+ return () => document.removeEventListener('pointerdown', onPointerDown, true)
308
+ }, [open])
309
+
310
+ const commit = useCallback(
311
+ (nextValue) => {
312
+ if (!CHANNEL_OPTIONS.some((item) => item.value === nextValue)) return
313
+ onChange(nextValue)
314
+ setOpen(false)
315
+ },
316
+ [onChange],
317
+ )
318
+
319
+ const onKeyDown = useCallback(
320
+ (event) => {
321
+ /** 键盘只保留 Esc 关闭(一般用不到键盘选渠道,从简)。 */
322
+ if (event.key === 'Escape') setOpen(false)
323
+ else if (event.key === 'Tab') setOpen(false)
324
+ },
325
+ [],
326
+ )
327
+
328
+ return h(
329
+ 'div',
330
+ { className: 'zsp-select', ref: rootRef, onKeyDown },
331
+ h(
332
+ 'button',
333
+ {
334
+ type: 'button',
335
+ className: 'zsp-select-trigger',
336
+ 'aria-haspopup': 'listbox',
337
+ 'aria-expanded': open === true,
338
+ disabled,
339
+ onClick: () => setOpen((current) => !current),
340
+ },
341
+ h('span', { className: 'zsp-badge' }, selected.badge),
342
+ h('span', { className: 'zsp-select-label' }, selected.label),
343
+ h('span', { className: 'zsp-select-desc' }, selected.desc),
344
+ h('span', { className: 'zsp-caret', 'aria-hidden': 'true' }),
345
+ ),
346
+ open === true
347
+ ? h(
348
+ 'div',
349
+ { className: 'zsp-select-menu', role: 'listbox', 'aria-label': '登录渠道' },
350
+ CHANNEL_OPTIONS.map((option) =>
351
+ h(
352
+ 'button',
353
+ {
354
+ key: option.value,
355
+ type: 'button',
356
+ role: 'option',
357
+ className: 'zsp-option',
358
+ 'aria-selected': option.value === value,
359
+ onClick: () => commit(option.value),
360
+ },
361
+ h('span', { className: 'zsp-badge' }, option.badge),
362
+ h(
363
+ 'span',
364
+ { className: 'zsp-option-text' },
365
+ h('span', null, option.label),
366
+ h('span', { className: 'zsp-select-desc' }, option.desc),
367
+ ),
368
+ h('span', { className: 'zsp-option-check', 'aria-hidden': 'true' }, '✓'),
369
+ ),
370
+ ),
371
+ )
372
+ : null,
373
+ )
374
+ }
375
+
376
+ /**
377
+ * 「添加账号」区块:渠道选择 → 发起授权 → 展示授权链接 → 轮询直到 ready。
378
+ *
379
+ * 两段式设备授权与 CLI 相同:Host 持 flowSecret,Client 只拿 authorizeUrl
380
+ * 和 flowId,凭据永远不经过页面。
381
+ */
382
+ function AddAccountSection(props) {
383
+ const { busy, onAdded } = props
384
+ const [channel, setChannel] = useState('bigmodel')
385
+ const [phase, setPhase] = useState('idle') // idle | starting | waiting | ready | failed
386
+ const [flow, setFlow] = useState(undefined) // { flowId, authorizeUrl, pollIntervalMs }
387
+ const [message, setMessage] = useState(undefined)
388
+ const [copied, setCopied] = useState(false)
389
+ const timerRef = useRef(undefined)
390
+
391
+ useEffect(() => {
392
+ /** 组件卸载/流程结束时停掉轮询定时器。 */
393
+ return () => {
394
+ if (timerRef.current !== undefined) clearTimeout(timerRef.current)
395
+ }
396
+ }, [])
397
+
398
+ const stopPolling = useCallback(() => {
399
+ if (timerRef.current !== undefined) {
400
+ clearTimeout(timerRef.current)
401
+ timerRef.current = undefined
402
+ }
403
+ }, [])
404
+
405
+ const poll = useCallback(
406
+ (flowId, intervalMs) => {
407
+ timerRef.current = setTimeout(async () => {
408
+ try {
409
+ const outcome = await api('/login/poll', { flowId })
410
+ if (outcome.status === 'pending') {
411
+ poll(flowId, intervalMs)
412
+ return
413
+ }
414
+ if (outcome.status === 'ready') {
415
+ setPhase('ready')
416
+ setMessage(
417
+ `${outcome.created === false ? '已更新' : '已添加'}账号「${outcome.account?.nickname ?? ''}」`,
418
+ )
419
+ stopPolling()
420
+ if (typeof onAdded === 'function') onAdded()
421
+ return
422
+ }
423
+ setPhase('failed')
424
+ setMessage(outcome.error ?? '授权失败')
425
+ } catch (caught) {
426
+ setPhase('failed')
427
+ setMessage(caught instanceof Error ? caught.message : String(caught))
428
+ }
429
+ }, intervalMs)
430
+ },
431
+ [onAdded, stopPolling],
432
+ )
433
+
434
+ const start = useCallback(async () => {
435
+ stopPolling()
436
+ setPhase('starting')
437
+ setMessage(undefined)
438
+ setCopied(false)
439
+ try {
440
+ const started = await api('/login/start', { channel })
441
+ setFlow({ flowId: started.flowId, authorizeUrl: started.authorizeUrl, pollIntervalMs: started.pollIntervalMs ?? 2000 })
442
+ setPhase('waiting')
443
+ setMessage(undefined)
444
+ poll(started.flowId, Math.max(1500, started.pollIntervalMs ?? 2000))
445
+ } catch (caught) {
446
+ setPhase('failed')
447
+ setMessage(caught instanceof Error ? caught.message : String(caught))
448
+ }
449
+ }, [channel, poll, stopPolling])
450
+
451
+ const cancel = useCallback(() => {
452
+ stopPolling()
453
+ setPhase('idle')
454
+ setFlow(undefined)
455
+ setMessage(undefined)
456
+ }, [stopPolling])
457
+
458
+ const copyLink = useCallback(async () => {
459
+ if (flow?.authorizeUrl === undefined) return
460
+ try {
461
+ await navigator.clipboard.writeText(flow.authorizeUrl)
462
+ setCopied(true)
463
+ } catch {
464
+ setCopied(false)
465
+ }
466
+ }, [flow])
467
+
468
+ return h(
469
+ 'div',
470
+ { className: 'zsp-add' },
471
+ h(
472
+ 'div',
473
+ { className: 'zsp-row' },
474
+ h('span', { className: 'zsp-name' }, '添加账号'),
475
+ h(ChannelSelect, {
476
+ value: channel,
477
+ onChange: setChannel,
478
+ disabled: busy || phase === 'starting' || phase === 'waiting',
479
+ }),
480
+ phase === 'waiting' || phase === 'starting'
481
+ ? h('button', { className: 'zsp-btn', onClick: cancel }, '取消')
482
+ : h(
483
+ 'button',
484
+ { className: 'zsp-btn', onClick: () => void start(), disabled: busy },
485
+ phase === 'starting' ? '申请中…' : '发起登录',
486
+ ),
487
+ ),
488
+ phase === 'starting' ? h('span', { className: 'zsp-muted' }, '正在向 ZCode 申请设备授权…') : null,
489
+ phase === 'waiting' && flow !== undefined
490
+ ? h(
491
+ React.Fragment,
492
+ null,
493
+ h(
494
+ 'span',
495
+ { className: 'zsp-muted' },
496
+ '① 在浏览器打开授权链接并用对应站点的账号登录授权(链接 10 分钟内有效):',
497
+ ),
498
+ h('a', { className: 'zsp-link', href: flow.authorizeUrl, target: '_blank', rel: 'noreferrer' }, flow.authorizeUrl),
499
+ h(
500
+ 'div',
501
+ { className: 'zsp-row' },
502
+ h('button', { className: 'zsp-btn', onClick: () => void copyLink() }, copied ? '已复制' : '复制链接'),
503
+ h('span', { className: 'zsp-muted' }, '② 授权完成后本面板会自动入池(无需其它操作)。'),
504
+ ),
505
+ )
506
+ : null,
507
+ phase === 'ready' ? h('p', { className: 'zsp-ok' }, message) : null,
508
+ phase === 'failed' ? h('p', { className: 'zsp-error' }, message ?? '授权失败') : null,
509
+ )
510
+ }
511
+
512
+ /**
513
+ * 面板主体。
514
+ *
515
+ * 宿主以两种 view 调用(workbuddy 实证):
516
+ * - `view === 'summary'`:插件列表页的一行简介,返回纯文本;
517
+ * - 其余:详情页完整面板。
518
+ *
519
+ * ⚠ Hooks 全部先于 summary 早退调用(React hooks 顺序约束)。
520
+ */
521
+ function Panel(props) {
522
+ const [data, setData] = useState(undefined)
523
+ const [error, setError] = useState(undefined)
524
+ const [balances, setBalances] = useState({})
525
+ const [busy, setBusy] = useState(false)
526
+ const [confirmId, setConfirmId] = useState(undefined)
527
+
528
+ /**
529
+ * 统一刷新:/summary 已带每账号余额;个别账号缺失(拉取失败/新入池)
530
+ * 时再逐个补拉,不再单设「刷新余额」按钮。
531
+ */
532
+ const load = useCallback(async () => {
533
+ try {
534
+ const summary = await api('/summary')
535
+ setData(summary)
536
+ const seeded = {}
537
+ const missing = []
538
+ for (const item of Array.isArray(summary?.accounts) ? summary.accounts : []) {
539
+ if (item.balance !== null && item.balance !== undefined) {
540
+ seeded[item.id] = { ok: true, ...item.balance }
541
+ } else if (item.enabled === true) {
542
+ missing.push(item.id)
543
+ }
544
+ }
545
+ if (missing.length > 0) {
546
+ const extra = await Promise.all(
547
+ missing.map(async (id) => {
548
+ try {
549
+ const result = await api(`/balance?id=${encodeURIComponent(id)}`)
550
+ return [
551
+ id,
552
+ result.balance === null || result.balance === undefined
553
+ ? { ok: false, error: typeof result.error === 'string' ? result.error : '余额不可用' }
554
+ : { ok: true, ...result.balance },
555
+ ]
556
+ } catch (caught) {
557
+ return [id, { ok: false, error: caught instanceof Error ? caught.message : String(caught) }]
558
+ }
559
+ }),
560
+ )
561
+ for (const [id, value] of extra) seeded[id] = value
562
+ }
563
+ setBalances(seeded)
564
+ setError(undefined)
565
+ } catch (caught) {
566
+ setError(caught instanceof Error ? caught.message : String(caught))
567
+ }
568
+ }, [])
569
+
570
+ useEffect(() => {
571
+ void load()
572
+ }, [load])
573
+
574
+ const act = useCallback(
575
+ async (path, body) => {
576
+ setBusy(true)
577
+ try {
578
+ await api(path, body)
579
+ await load()
580
+ setError(undefined)
581
+ } catch (caught) {
582
+ setError(caught instanceof Error ? caught.message : String(caught))
583
+ } finally {
584
+ setBusy(false)
585
+ }
586
+ },
587
+ [load],
588
+ )
589
+
590
+ /** 插件列表页的摘要视图:一行文本,不发起请求。 */
591
+ if ((props || {}).view === 'summary') {
592
+ return '管理 ZCode 赠送免费 plan 的账号池:选择使用的账号、查看余额与限流、面板内登录添加账号(bigmodel / z.ai)。'
593
+ }
594
+
595
+ const accounts = data !== undefined && Array.isArray(data.accounts) ? data.accounts : undefined
596
+ /** 「按序下一个」= 列表里第一个启用的账号(pool.pick 的取号规则)。 */
597
+ const nextAccount = accounts !== undefined ? accounts.find((account) => account.enabled === true) : undefined
598
+
599
+ return h(
600
+ 'section',
601
+ { className: 'zsp-panel' },
602
+ h('style', null, CSS),
603
+ h(
604
+ 'div',
605
+ { className: 'zsp-head' },
606
+ h('h3', { className: 'zsp-title' }, '账号池管理'),
607
+ data !== undefined
608
+ ? h(
609
+ 'span',
610
+ { className: 'zsp-muted' },
611
+ `${[data.displayName ?? data.provider, `${accounts.length} 个账号`].filter(Boolean).join(' · ')}`,
612
+ )
613
+ : null,
614
+ h('span', { className: 'zsp-spacer' }),
615
+ h('button', { className: 'zsp-btn', onClick: () => void load(), disabled: busy }, '刷新'),
616
+ ),
617
+ error !== undefined ? h('p', { className: 'zsp-error' }, error) : null,
618
+ data === undefined && error === undefined ? h('span', { className: 'zsp-muted' }, '加载中…') : null,
619
+ h(AddAccountSection, { busy, onAdded: () => void load() }),
620
+ accounts !== undefined && accounts.length === 0
621
+ ? h('span', { className: 'zsp-muted' }, '账号池为空:用上方「添加账号」登录,或在插件目录运行 node bin/cli.mjs login。')
622
+ : null,
623
+ accounts !== undefined
624
+ ? accounts.map((account) =>
625
+ h(AccountCard, {
626
+ key: account.id,
627
+ account,
628
+ balance: balances[account.id],
629
+ busy,
630
+ isNext: nextAccount !== undefined && nextAccount.id === account.id,
631
+ confirmId,
632
+ setConfirmId,
633
+ onUse: () => void act('/use', { id: account.id }),
634
+ onRemove: () => void act('/remove', { id: account.id }),
635
+ onRename: (nickname) => void act('/rename', { id: account.id, nickname }),
636
+ }),
637
+ )
638
+ : null,
639
+ data !== undefined && data.storeInMemory === true
640
+ ? h(
641
+ 'span',
642
+ { className: 'zsp-muted' },
643
+ '⚠ 账号库当前是内存库(数据目录不可写),重启后账号会消失。',
644
+ )
645
+ : null,
646
+ )
647
+ }
648
+
649
+ return {
650
+ inject: ['slots'],
651
+ apply(ctx) {
652
+ ctx.slots.inject(SLOT, () =>
653
+ /** key = 包名:宿主只在 dsh-zcode-startplan 的详情页派发本条目。 */
654
+ ctx.slots.register({ name: SLOT, key: BUNDLE_KEY }, Panel),
655
+ )
656
+ },
657
+ }
658
+ },
659
+ })
@@ -0,0 +1,30 @@
1
+ # dsh-zcode-startplan bundle patch
2
+ #
3
+ # 安装后这里就是「开关面板」:改完重启 Harness 生效(fiber 一次性 apply)。
4
+ #
5
+ # provider / displayName DSH 里的路由名与展示名(与 llm-pi-ai 的路由不能重名)
6
+ # models 暴露给 DSH 的模型 id(与上游目录求交集)
7
+ # captcha.debugPort 宿主 Electron 的 CDP 端口(DSH 桌面端需以
8
+ # --remote-debugging-port=9229 启动;captcha 用它产出)
9
+ # captcha.mode cdp = 自动产出;manual = 只认人工粘贴(见 CLI)
10
+ # endpoint.enabled true 才启动本地 Anthropic 端点(仅 llm-pi-ai 回落路线需要)
11
+ # statusTool 是否注册 zcode_start_plan_status 工具
12
+ - insert:
13
+ - id: zcode-start-plan
14
+ name: dsh-zcode-startplan
15
+ config:
16
+ provider: zcode-start-plan
17
+ displayName: ZCode Start Plan(赠送免费 plan)
18
+ models:
19
+ - GLM-5.3-Flash
20
+ - GLM-5.3
21
+ dataDir: ''
22
+ modelCacheMs: 600000
23
+ captcha:
24
+ mode: cdp
25
+ debugPort: 9229
26
+ origin: https://zcode.z.ai/
27
+ endpoint:
28
+ enabled: false
29
+ port: 17899
30
+ statusTool: true