dsh-opencode-status 0.1.5 → 0.3.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/src/client.js CHANGED
@@ -1,9 +1,12 @@
1
1
  /**
2
- * dsh-opencode-status — Client half.
2
+ * dsh-opencode-status — Client half (0.3.0).
3
3
  *
4
4
  * 槽位:
5
- * sidebar.footer.action 常驻极简单行按钮(状态灯 + 月用量 %;点击呼出详情面板)
6
- * shell.overlay 轻量浮层面板(展示 Rolling 5h、Weekly、Monthly 进度条与重置倒计时)
5
+ * sidebar.footer.action 常驻紧凑按钮(状态灯 + 月剩余摘要;点击打开用量面板)
6
+ * shell.overlay 用量面板(状态视图:三个窗口 + 固定操作条;设置视图:Base URL / API Key)
7
+ *
8
+ * 上游 /v1/usage 只提供 rolling/weekly/monthly 百分比,没有 USD 余额接口
9
+ * (anomalyco/opencode#10448 仍 open),界面只表述「剩余额度 / 可用百分比」,不编造金额。
7
10
  */
8
11
  window.__ModuleLoader__.load({
9
12
  id: 'dsh-opencode-status',
@@ -22,14 +25,17 @@ window.__ModuleLoader__.load({
22
25
  @keyframes ocPulse { 0% { box-shadow: 0 0 0 0 rgba(34,197,94,.45) } 70% { box-shadow: 0 0 0 5px rgba(34,197,94,0) } 100% { box-shadow: 0 0 0 0 rgba(34,197,94,0) } }
23
26
  .oc-panel-enter { animation: ocFadeSlideUp .2s cubic-bezier(.2,.9,.3,1.2) both }
24
27
  .oc-panel-exit { animation: ocFadeSlideDown .15s ease-in both; pointer-events: none !important }
25
- .oc-btn { min-width: 0; transition: background .15s ease, border-color .15s ease, color .15s ease, transform .1s ease }
26
- .oc-btn:hover:not(:disabled):not(.oc-btn-primary) { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-1)); border-color: var(--dsw-alias-border-l2) }
27
- .oc-btn-primary:hover:not(:disabled) { filter: brightness(1.12) }
28
+ .oc-btn { min-width: 0; transition: background .15s ease, border-color .15s ease, color .15s ease, transform .1s ease, opacity .15s ease }
29
+ .oc-btn:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, var(--dsw-alias-bg-layer-1)); border-color: var(--dsw-alias-border-l2) }
28
30
  .oc-btn:active:not(:disabled) { transform: scale(.98) }
31
+ .oc-btn:disabled { opacity: .55; cursor: default }
29
32
  .oc-spin { display: inline-block; animation: ocSpin .8s linear infinite }
30
33
  .oc-dot-live { animation: ocPulse 2.4s ease-out infinite }
34
+ /* 悬浮微卡只读:不接收任何指针事件,避免遮挡 footer 按钮的点击 */
35
+ .oc-hover-card { pointer-events: none !important }
31
36
  @media (prefers-reduced-motion: reduce) {
32
37
  .oc-panel-enter, .oc-panel-exit, .oc-spin, .oc-dot-live { animation: none !important }
38
+ .oc-btn { transition: none !important }
33
39
  }
34
40
  `
35
41
 
@@ -85,6 +91,8 @@ window.__ModuleLoader__.load({
85
91
  outline: 'none',
86
92
  }
87
93
 
94
+ const labelStyle = { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 }
95
+
88
96
  function timeUntil(ts) {
89
97
  if (!ts) return ''
90
98
  const diff = ts - Date.now()
@@ -96,18 +104,49 @@ window.__ModuleLoader__.load({
96
104
  return `${Math.floor(hours / 24)}d${hours % 24 ? `${hours % 24}h` : ''}`
97
105
  }
98
106
 
99
- function usageColor(percent) {
100
- if (percent === null || percent === undefined) return T.secondary
101
- if (percent >= 90) return T.err
102
- if (percent >= 70) return T.warn
103
- return T.ok
107
+ /** 同步时间显示为 HH:MM:SS(本地时区,取 status.fetchedAt)。 */
108
+ function fmtClock(ts) {
109
+ if (!ts) return ''
110
+ const d = new Date(ts)
111
+ const pad = (n) => String(n).padStart(2, '0')
112
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
113
+ }
114
+
115
+ /** 剩余额度阈值着色:>50 正常、>20 警告、其余错误(与 cpa 的 QuotaBar 语义一致)。 */
116
+ function remainingColor(remaining) {
117
+ if (remaining === null || remaining === undefined) return T.secondary
118
+ if (remaining > 50) return T.ok
119
+ if (remaining > 20) return T.warn
120
+ return T.err
121
+ }
122
+
123
+ function clampPct(value) {
124
+ return Math.max(0, Math.min(100, value))
125
+ }
126
+
127
+ /** 月窗口剩余百分比;上游只给百分比,不存在金额余额。 */
128
+ function monthlyRemainingOf(status) {
129
+ if (!status) return null
130
+ const windows = Array.isArray(status.windows) ? status.windows : []
131
+ const monthly = windows.find((w) => w?.id === 'monthly')
132
+ if (monthly && typeof monthly.remainingPct === 'number') return monthly.remainingPct
133
+ if (typeof status.monthlyUsedPct === 'number') return Math.max(0, 100 - status.monthlyUsedPct)
134
+ return null
135
+ }
136
+
137
+ function hostOf(url) {
138
+ try {
139
+ return new URL(url).host
140
+ } catch {
141
+ return url
142
+ }
104
143
  }
105
144
 
106
145
  // ---------- Store ----------
107
146
  const store = {
108
147
  state: {
109
148
  open: false,
110
- editing: false,
149
+ view: 'status', // 'status' 用量视图 | 'settings' 连接设置视图
111
150
  status: null,
112
151
  config: null,
113
152
  refreshing: false,
@@ -128,6 +167,7 @@ window.__ModuleLoader__.load({
128
167
  return React.useSyncExternalStore(store.subscribe, () => store.state)
129
168
  }
130
169
 
170
+ // ---------- 本机 API ----------
131
171
  async function api(path, options) {
132
172
  const res = await fetch(path, options)
133
173
  const data = await res.json().catch(() => ({}))
@@ -135,15 +175,29 @@ window.__ModuleLoader__.load({
135
175
  return data
136
176
  }
137
177
 
138
- async function refreshStatus(force = false) {
139
- try {
140
- const status = force
141
- ? await api('/api/opencode-status/sync', { method: 'POST' })
142
- : await api('/api/opencode-status')
143
- store.set({ status, error: null })
144
- } catch (err) {
145
- store.set({ error: String(err?.message ?? err) })
146
- }
178
+ // 请求序号:手动刷新会推进 epoch,使所有更早发出的 GET 响应(成功或失败)失效,
179
+ // 避免极端时序下旧数据覆盖手动刷新的新结果。
180
+ let statusEpoch = 0
181
+
182
+ /** GET 状态:走宿主 30 秒缓存,打开面板/切换视图都不会额外探测上游。 */
183
+ let statusInFlight = null
184
+ async function refreshStatus() {
185
+ // 并发去重:挂载、打开面板与 30s 轮询同时触发时只发一个 GET,避免首个请求未写入缓存前重复探测。
186
+ if (store.state.refreshing) return
187
+ if (statusInFlight) return statusInFlight
188
+ const epoch = statusEpoch
189
+ statusInFlight = (async () => {
190
+ try {
191
+ const status = await api('/api/opencode-status')
192
+ // 只接受最新 epoch 的响应:手动刷新之后返回的在途 GET 一律丢弃。
193
+ if (epoch === statusEpoch) store.set({ status, error: null })
194
+ } catch (err) {
195
+ if (epoch === statusEpoch) store.set({ error: String(err?.message ?? err) })
196
+ } finally {
197
+ statusInFlight = null
198
+ }
199
+ })()
200
+ return statusInFlight
147
201
  }
148
202
 
149
203
  async function refreshConfig() {
@@ -153,15 +207,56 @@ window.__ModuleLoader__.load({
153
207
  } catch {}
154
208
  }
155
209
 
156
- // ---------- 常驻入口(上下结构单行按钮 + 悬停微卡) ----------
210
+ /** 手动刷新唯一入口:绕过 30 秒缓存,强制重新拉取当前剩余额度。 */
211
+ async function manualRefresh() {
212
+ if (store.state.refreshing) return
213
+ // 先推进序号:手动刷新发起后,任何更早发出的在途 GET 响应都不再落库。
214
+ statusEpoch += 1
215
+ store.set({ refreshing: true, error: null })
216
+ try {
217
+ const status = await api('/api/opencode-status/sync', {
218
+ method: 'POST',
219
+ headers: { 'content-type': 'application/json' },
220
+ })
221
+ // 手动刷新自身的响应始终落库(刷新期间已阻止新的 GET)。
222
+ store.set({ status, error: null })
223
+ } catch (err) {
224
+ store.set({ error: String(err?.message ?? err) })
225
+ } finally {
226
+ store.set({ refreshing: false })
227
+ }
228
+ }
229
+
230
+ function openOverlay() {
231
+ store.set({ open: true, view: 'status' })
232
+ // 面板默认落用量视图;GET 命中 30 秒缓存,不触发额外上游探测。
233
+ refreshStatus()
234
+ refreshConfig()
235
+ }
236
+
237
+ function closeOverlay() {
238
+ store.set({ open: false })
239
+ }
240
+
241
+ function toggleOverlay() {
242
+ if (store.state.open) closeOverlay()
243
+ else openOverlay()
244
+ }
245
+
246
+ function openSettings() {
247
+ refreshConfig()
248
+ store.set({ view: 'settings' })
249
+ }
250
+
251
+ // ---------- 常驻入口(状态灯 + 月剩余摘要 + 220ms 悬浮微卡) ----------
157
252
  function FooterEntry(props) {
158
253
  const state = useStore()
159
254
  const [hovering, setHovering] = useState(false)
160
255
  const hoverTimerRef = useRef(null)
161
256
 
162
257
  useEffect(() => {
163
- refreshStatus(false)
164
- const timer = setInterval(() => refreshStatus(false), 30_000)
258
+ refreshStatus()
259
+ const timer = setInterval(() => refreshStatus(), 30_000)
165
260
  return () => clearInterval(timer)
166
261
  }, [])
167
262
 
@@ -175,95 +270,117 @@ window.__ModuleLoader__.load({
175
270
  }
176
271
 
177
272
  const st = state.status
273
+ const monthlyRemaining = monthlyRemainingOf(st)
178
274
  let color = T.warn
179
- let text = '连接 OpenCode'
275
+ let label = '连接 OpenCode'
180
276
  let value = null
181
277
 
182
278
  if (state.error) {
183
279
  color = T.err
184
- text = 'OpenCode ?'
280
+ label = 'OpenCode ?'
281
+ } else if (st?.mode === 'needs_config') {
282
+ color = T.warn
283
+ label = 'OpenCode'
284
+ value = '未配置'
185
285
  } else if (st?.mode === 'ready') {
186
286
  if (st.ok) {
187
- const pct = st.monthlyUsedPct
188
- color = usageColor(pct)
189
- text = 'OpenCode'
190
- value = pct !== null ? `月用量 ${pct}%` : '在线'
287
+ color = monthlyRemaining === null ? T.warn : remainingColor(monthlyRemaining)
288
+ label = 'OpenCode'
289
+ value = monthlyRemaining !== null ? `月剩余 ${monthlyRemaining}%` : '在线'
191
290
  } else {
192
291
  color = T.err
193
- text = 'OpenCode'
292
+ label = 'OpenCode'
194
293
  value = '异常'
195
294
  }
196
295
  }
197
296
 
297
+ const title = state.error
298
+ ? `本机状态接口异常:${state.error}`
299
+ : st?.mode === 'needs_config'
300
+ ? '尚未配置 OpenCode API Key,点击设置'
301
+ : st?.mode === 'ready' && !st.ok
302
+ ? `用量拉取异常:${st.error?.message ?? '未知错误'}`
303
+ : monthlyRemaining !== null
304
+ ? `OpenCode GO · 月剩余 ${monthlyRemaining}% · 点击查看详情`
305
+ : 'OpenCode GO,点击查看详情'
306
+
307
+ // rail 模式:真正的 button(键盘可达、可点击),同样打开用量视图
198
308
  if (props?.wide === false) {
199
309
  return h(
200
- 'div',
310
+ 'button',
201
311
  {
202
- className: 'oc-btn',
312
+ className: 'oc-btn oc-footer-btn',
313
+ type: 'button',
314
+ title,
315
+ 'aria-label': '打开 OpenCode GO 用量面板',
203
316
  style: {
204
- boxSizing: 'border-box',
205
317
  width: 36,
206
318
  height: 36,
207
319
  display: 'flex',
208
320
  alignItems: 'center',
209
321
  justifyContent: 'center',
210
322
  borderRadius: 8,
323
+ border: `1px solid ${color === T.err ? T.err : T.border}`,
324
+ background: 'transparent',
325
+ color,
211
326
  fontSize: 10,
212
327
  fontWeight: 700,
213
- color: T.label,
214
328
  cursor: 'pointer',
215
329
  margin: '2px auto',
330
+ padding: 0,
331
+ fontVariantNumeric: 'tabular-nums',
216
332
  },
217
- title: st?.error?.message || `OpenCode GO ${value || ''}`,
218
- onClick: () => store.set({ open: !state.open, editing: false }),
333
+ onClick: toggleOverlay,
219
334
  },
220
- st?.monthlyUsedPct !== null && st?.monthlyUsedPct !== undefined ? `${st.monthlyUsedPct}%` : 'GO',
335
+ monthlyRemaining !== null ? `${monthlyRemaining}%` : 'GO',
221
336
  )
222
337
  }
223
338
 
339
+ const segments = [
340
+ { text: label, color: T.label },
341
+ value ? { text: value, color } : null,
342
+ ].filter(Boolean)
343
+ const labelEl = h(
344
+ 'span',
345
+ { style: { display: 'inline-flex', alignItems: 'center', lineHeight: '18px', whiteSpace: 'nowrap', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } },
346
+ segments.flatMap((s, i) =>
347
+ i === 0
348
+ ? [h('span', { key: `s${i}`, style: { color: s.color, fontWeight: 500, flexShrink: 0 } }, s.text)]
349
+ : [
350
+ h('span', { key: `sep${i}`, style: { color: T.secondary, margin: '0 5px', opacity: 0.7, flexShrink: 0 } }, '·'),
351
+ h('span', { key: `s${i}`, style: { color: s.color, fontWeight: 500, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis' } }, s.text),
352
+ ],
353
+ ),
354
+ )
355
+
224
356
  const node = h(
225
357
  'button',
226
358
  {
227
359
  className: 'oc-btn oc-footer-btn',
360
+ type: 'button',
361
+ title,
228
362
  onMouseEnter,
229
363
  onMouseLeave,
230
364
  style: {
231
365
  ...btnBase,
232
- display: props?.wide === false ? 'inline-flex' : 'flex',
233
- width: props?.wide === false ? undefined : '100%',
366
+ display: 'flex',
367
+ width: '100%',
234
368
  boxSizing: 'border-box',
235
- justifyContent: props?.wide === false ? 'center' : 'flex-start',
369
+ justifyContent: 'flex-start',
236
370
  margin: '2px 0',
237
371
  minWidth: 0,
238
372
  flexShrink: 0,
239
373
  borderColor: state.open ? T.brand : T.border,
240
374
  background: state.open ? 'var(--dsw-alias-interactive-bg-hover, rgba(59,130,246,.12))' : 'transparent',
241
375
  },
242
- onClick: () => {
243
- store.set({ open: !state.open, editing: false })
244
- if (!state.open) {
245
- refreshStatus(false)
246
- refreshConfig()
247
- }
248
- },
376
+ onClick: toggleOverlay,
249
377
  },
250
378
  h('span', { className: color === T.ok ? 'oc-dot-live' : undefined, style: dotStyle(color) }),
251
- h(
252
- 'span',
253
- { style: { display: 'inline-flex', alignItems: 'center', lineHeight: '18px', whiteSpace: 'nowrap', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' } },
254
- [
255
- h('span', { key: 't', style: { color: T.label, fontWeight: 500, flexShrink: 0 } }, text),
256
- value
257
- ? [
258
- h('span', { key: 'sep', style: { color: T.secondary, margin: '0 5px', opacity: 0.7, flexShrink: 0 } }, '·'),
259
- h('span', { key: 'v', style: { color, fontWeight: 500, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis' } }, value),
260
- ]
261
- : null,
262
- ].flat().filter(Boolean),
263
- ),
379
+ labelEl,
264
380
  )
265
381
 
266
- if (!hovering || state.open || !st?.ok || !st?.windows?.length) return node
382
+ // 悬浮微卡:面板关闭、悬停 220ms、且 ready + ok 时才出现
383
+ if (!hovering || state.open || st?.mode !== 'ready' || !st.ok) return node
267
384
 
268
385
  return h(
269
386
  'div',
@@ -273,55 +390,156 @@ window.__ModuleLoader__.load({
273
390
  onMouseLeave,
274
391
  },
275
392
  node,
276
- h(
277
- 'div',
278
- {
279
- className: 'oc-panel-enter',
280
- style: {
281
- position: 'absolute',
282
- left: 0,
283
- right: 0,
284
- bottom: 'calc(100% + 6px)',
285
- background: T.bg,
286
- border: `1px solid ${T.border2}`,
287
- borderRadius: '10px',
288
- boxShadow: '0 8px 24px rgba(0,0,0,.18)',
289
- padding: '12px 14px 4px 14px',
290
- fontSize: '11px',
291
- color: T.label,
292
- zIndex: 100,
293
- fontFamily: 'system-ui, -apple-system, sans-serif',
294
- },
393
+ h(HoverCard, { status: st }),
394
+ )
395
+ }
396
+
397
+ // ---------- 220ms 悬浮微卡(只读概览,无假按钮) ----------
398
+ function HoverCard(props) {
399
+ const st = props.status
400
+ const windows = Array.isArray(st?.windows) ? st.windows : []
401
+ return h(
402
+ 'div',
403
+ {
404
+ className: 'oc-panel-enter oc-hover-card',
405
+ style: {
406
+ position: 'absolute',
407
+ left: 0,
408
+ right: 0,
409
+ bottom: 'calc(100% + 6px)',
410
+ pointerEvents: 'none',
411
+ background: T.bg,
412
+ border: `1px solid ${T.border2}`,
413
+ borderRadius: 10,
414
+ boxShadow: '0 8px 24px rgba(0,0,0,.18)',
415
+ padding: '10px 12px 8px',
416
+ fontSize: 11,
417
+ color: T.label,
418
+ zIndex: 100,
419
+ fontFamily: 'system-ui, -apple-system, sans-serif',
295
420
  },
421
+ },
422
+ [
423
+ h('div', { key: 'hd', style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 } }, [
424
+ h('span', { key: 't', style: { fontWeight: 600, fontSize: 12, color: T.label } }, 'OpenCode GO 用量'),
425
+ // Go 标识(纯展示徽章,不是按钮)
426
+ h(
427
+ 'span',
428
+ {
429
+ key: 'go',
430
+ style: {
431
+ fontSize: 9,
432
+ fontWeight: 700,
433
+ letterSpacing: 0.4,
434
+ color: '#fff',
435
+ background: T.brand,
436
+ borderRadius: 4,
437
+ padding: '1px 5px',
438
+ lineHeight: '13px',
439
+ flexShrink: 0,
440
+ },
441
+ },
442
+ 'GO',
443
+ ),
444
+ h(
445
+ 'span',
446
+ { key: 'at', style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums', flexShrink: 0 } },
447
+ st?.fetchedAt ? `上次同步 ${fmtClock(st.fetchedAt)}` : '尚未同步',
448
+ ),
449
+ ]),
296
450
  h(
297
451
  'div',
298
- {
299
- style: {
300
- display: 'flex',
301
- alignItems: 'center',
302
- justifyContent: 'space-between',
303
- marginBottom: 10,
304
- },
305
- },
306
- h('span', { style: { fontWeight: 600, fontSize: '12px' } }, '🚀 OpenCode GO 用量概览'),
307
- st.plan ? h('span', { style: { fontSize: '10px', color: T.brand, fontWeight: 600 } }, st.plan) : null,
452
+ { key: 'rows', style: { display: 'flex', flexDirection: 'column', gap: 6 } },
453
+ windows.map((w, i) => h(MiniQuotaRow, { key: w.id ?? i, window: w })),
308
454
  ),
309
- st.windows.map((w, i) => h(QuotaRow, { key: i, window: w })),
310
- ),
455
+ h(
456
+ 'div',
457
+ { key: 'hint', style: { marginTop: 8, paddingTop: 6, borderTop: `1px dashed ${T.border}`, fontSize: 10, color: T.secondary, textAlign: 'center' } },
458
+ '点击查看详情',
459
+ ),
460
+ ],
311
461
  )
312
462
  }
313
463
 
314
- // ---------- 配额进度条 ----------
464
+ /** 悬浮卡紧凑行:名称 / 剩余 % / ↻ 重置倒计时 / 细进度条。 */
465
+ function MiniQuotaRow(props) {
466
+ const w = props.window
467
+ const remaining = w?.remainingPct ?? null
468
+ const color = remainingColor(remaining)
469
+ return h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
470
+ h('span', { key: 'n', style: { width: 46, flexShrink: 0, fontSize: 10, color: T.secondary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, w?.shortLabel ?? w?.label ?? '—'),
471
+ h(
472
+ 'div',
473
+ { key: 'bar', style: { flex: 1, minWidth: 0, height: 3, borderRadius: 2, background: `color-mix(in srgb, ${color} 16%, transparent)`, overflow: 'hidden' } },
474
+ remaining === null
475
+ ? null
476
+ : h('div', { style: { height: '100%', width: `${clampPct(remaining)}%`, background: color, borderRadius: 2 } }),
477
+ ),
478
+ h('span', { key: 'v', style: { minWidth: 30, textAlign: 'right', fontSize: 10, fontWeight: 600, color, fontVariantNumeric: 'tabular-nums' } }, remaining === null ? '—' : `${remaining}%`),
479
+ h('span', { key: 'r', style: { minWidth: 34, textAlign: 'right', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } }, w?.resetAt ? `↻ ${timeUntil(w.resetAt)}` : ''),
480
+ ])
481
+ }
482
+
483
+ // ---------- 用量视图 ----------
484
+ function StatusView() {
485
+ const state = useStore()
486
+ const st = state.status
487
+
488
+ if (!st) {
489
+ return h('div', { style: { fontSize: 12, color: T.secondary } }, state.error ? `读取状态失败:${state.error}` : '加载中…')
490
+ }
491
+
492
+ const windows = Array.isArray(st.windows) ? st.windows : []
493
+ const monthlyRemaining = monthlyRemainingOf(st)
494
+ const host = hostOf(st.config?.baseUrl)
495
+
496
+ return h('div', null, [
497
+ h('div', { key: 'sum', style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
498
+ h('span', { key: 'd', style: dotStyle(st.ok ? T.ok : T.err) }),
499
+ h('span', { key: 't', style: { fontSize: 12, fontWeight: 600, color: T.label } }, st.ok ? 'OpenCode GO 已连接' : 'OpenCode GO 异常'),
500
+ host ? h('span', { key: 'h', style: { fontSize: 10, color: T.secondary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, host) : null,
501
+ monthlyRemaining !== null
502
+ ? h(
503
+ 'span',
504
+ { key: 'm', style: { marginLeft: 'auto', fontSize: 11, fontWeight: 600, color: remainingColor(monthlyRemaining), fontVariantNumeric: 'tabular-nums', flexShrink: 0 } },
505
+ `月剩余 ${monthlyRemaining}%`,
506
+ )
507
+ : null,
508
+ ].filter(Boolean)),
509
+ state.error
510
+ ? h('div', { key: 'ce', style: { fontSize: 11, color: T.err, marginTop: 8 } }, `刷新失败:${state.error}`)
511
+ : null,
512
+ !st.ok
513
+ ? h('div', { key: 'se', style: { fontSize: 12, color: T.err, marginTop: 10 } }, st.error?.message ?? '网关返回异常,稍后重试')
514
+ : null,
515
+ st.ok && windows.length
516
+ ? h('div', { key: 'w', style: { marginTop: 14 } }, windows.map((w, i) => h(QuotaRow, { key: w.id ?? i, window: w })))
517
+ : null,
518
+ st.ok && !windows.length
519
+ ? h('div', { key: 'empty', style: { fontSize: 11, color: T.secondary, marginTop: 10 } }, '暂无用量窗口数据')
520
+ : null,
521
+ h(
522
+ 'div',
523
+ { key: 'note', style: { fontSize: 10, color: T.secondary, marginTop: 6, lineHeight: '15px' } },
524
+ '上游 /v1/usage 仅提供百分比额度,界面不展示金额余额。',
525
+ ),
526
+ ].filter(Boolean))
527
+ }
528
+
529
+ /** 面板窗口行:已用 % + 剩余 % + 重置倒计时 + 进度条(按剩余额度着色)。 */
315
530
  function QuotaRow(props) {
316
531
  const w = props.window
317
- const used = w.usedPct
318
- const color = usageColor(used)
319
- return h('div', { style: { marginBottom: 10 } }, [
320
- h('div', { key: 'label', style: { display: 'flex', fontSize: 11, marginBottom: 3, fontVariantNumeric: 'tabular-nums' } }, [
321
- h('span', { style: { color: T.label, fontWeight: 500 } }, w.label),
322
- h('span', { style: { marginLeft: 'auto', color, fontWeight: 600 } }, used !== null ? `${used}%` : '—'),
323
- w.resetAt ? h('span', { style: { color: T.secondary, marginLeft: 6 } }, `↻ ${timeUntil(w.resetAt)}`) : null,
324
- ]),
532
+ const used = w?.usedPct ?? null
533
+ const remaining = w?.remainingPct ?? null
534
+ const color = remainingColor(remaining)
535
+ const statusText = w?.status && w.status !== 'ok' ? w.status : null
536
+ return h('div', { style: { marginBottom: 12 } }, [
537
+ h('div', { key: 'meta', style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: 11, marginBottom: 4, fontVariantNumeric: 'tabular-nums' } }, [
538
+ h('span', { key: 'l', style: { color: T.label, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, w?.label ?? '—'),
539
+ h('span', { key: 'u', style: { marginLeft: 'auto', color: T.secondary, flexShrink: 0 } }, used === null ? '已用 —' : `已用 ${used}%`),
540
+ h('span', { key: 'r', style: { color, fontWeight: 600, flexShrink: 0 } }, remaining === null ? '剩余 —' : `剩余 ${remaining}%`),
541
+ w?.resetAt ? h('span', { key: 't', style: { color: T.secondary, flexShrink: 0 } }, `↻ ${timeUntil(w.resetAt)}`) : null,
542
+ ].filter(Boolean)),
325
543
  h(
326
544
  'div',
327
545
  {
@@ -334,22 +552,25 @@ window.__ModuleLoader__.load({
334
552
  overflow: 'hidden',
335
553
  },
336
554
  },
337
- used === null
555
+ remaining === null
338
556
  ? null
339
557
  : h('div', {
340
558
  style: {
341
559
  height: '100%',
342
- width: `${Math.max(0, Math.min(100, used))}%`,
560
+ width: `${clampPct(remaining)}%`,
343
561
  background: color,
344
562
  borderRadius: 3,
345
563
  transition: 'width 0.4s ease',
346
564
  },
347
565
  }),
348
566
  ),
349
- ])
567
+ statusText
568
+ ? h('div', { key: 'st', style: { fontSize: 10, color: T.warn, marginTop: 3 } }, `窗口状态异常:${statusText}`)
569
+ : null,
570
+ ].filter(Boolean))
350
571
  }
351
572
 
352
- // ---------- 配置卡片 ----------
573
+ // ---------- 连接设置视图 ----------
353
574
  function ConfigCard() {
354
575
  const state = useStore()
355
576
  const cfg = state.config
@@ -372,7 +593,8 @@ window.__ModuleLoader__.load({
372
593
  headers: { 'content-type': 'application/json' },
373
594
  body: JSON.stringify({ baseUrl, ...(apiKey ? { apiKey } : {}) }),
374
595
  })
375
- store.set({ status: result.status, config: result.config, editing: false })
596
+ // 保存成功后回到用量视图
597
+ store.set({ status: result.status, config: result.config, view: 'status', error: null })
376
598
  setApiKey('')
377
599
  } catch (e) {
378
600
  setError(e?.message ?? '保存失败')
@@ -391,7 +613,7 @@ window.__ModuleLoader__.load({
391
613
  headers: { 'content-type': 'application/json' },
392
614
  body: JSON.stringify({ baseUrl, clearApiKey: true }),
393
615
  })
394
- store.set({ status: result.status, config: result.config, editing: false })
616
+ store.set({ status: result.status, config: result.config, error: null })
395
617
  } catch (e) {
396
618
  setError(e?.message ?? '清除失败')
397
619
  } finally {
@@ -399,9 +621,17 @@ window.__ModuleLoader__.load({
399
621
  }
400
622
  }
401
623
 
624
+ /** 放弃未保存的编辑并关闭面板:重新打开时表单会从已保存的配置重新渲染。 */
625
+ function cancel() {
626
+ setBaseUrl(cfg?.baseUrl ?? '')
627
+ setApiKey('')
628
+ setError(null)
629
+ store.set({ open: false, view: 'status' })
630
+ }
631
+
402
632
  return h('div', null, [
403
633
  h('div', { key: 'u', style: { marginBottom: 10 } }, [
404
- h('label', { style: { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 } }, 'Base URL'),
634
+ h('label', { style: labelStyle }, 'Base URL'),
405
635
  h('input', {
406
636
  style: inputStyle,
407
637
  value: baseUrl,
@@ -410,7 +640,7 @@ window.__ModuleLoader__.load({
410
640
  }),
411
641
  ]),
412
642
  h('div', { key: 'k', style: { marginBottom: 10 } }, [
413
- h('label', { style: { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 } }, `API Key *${keyState.configured ? `(已保存 ${keyState.hint})` : ''}`),
643
+ h('label', { style: labelStyle }, `API Key *${keyState.configured ? `(已保存 ${keyState.hint})` : ''}`),
414
644
  h('input', {
415
645
  style: { ...inputStyle, opacity: keyState.writable ? 1 : 0.6 },
416
646
  type: 'password',
@@ -424,43 +654,107 @@ window.__ModuleLoader__.load({
424
654
  h('div', { key: 'btns', style: { display: 'flex', gap: 8, marginTop: 12, alignItems: 'center' } }, [
425
655
  h(
426
656
  'button',
427
- { className: 'oc-btn oc-btn-primary', style: { ...btnBase, background: T.brand, borderColor: T.brand, color: '#fff' }, disabled: saving, onClick: save },
657
+ { className: 'oc-btn', style: { ...btnBase, background: T.brand, borderColor: T.brand, color: '#fff' }, disabled: saving, onClick: save },
428
658
  saving ? '保存中…' : '保存并连接',
429
659
  ),
430
- state.status?.mode === 'ready'
431
- ? h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: () => store.set({ editing: false }) }, '取消')
432
- : null,
660
+ h('button', { className: 'oc-btn', style: btnBase, disabled: saving, onClick: cancel }, '取消'),
433
661
  keyState.configured && keyState.writable
434
662
  ? h('button', { className: 'oc-btn', style: { ...btnBase, color: T.err, marginLeft: 'auto' }, disabled: saving, onClick: clearKey }, '清除')
435
663
  : null,
436
- ]),
664
+ ].filter(Boolean)),
437
665
  ])
438
666
  }
439
667
 
440
- // ---------- 浮层配置面板(点击进入控制台管理,用量已在悬浮卡片展示) ----------
668
+ // ---------- 固定底部操作条 ----------
669
+ function OpsBar(props) {
670
+ const state = useStore()
671
+ const st = state.status
672
+ const lastSync = st?.fetchedAt ? fmtClock(st.fetchedAt) : null
673
+
674
+ if (props?.settings) {
675
+ return h('div', { style: barStyle }, [
676
+ // 只有未配置(needs_config)时没有可返回的用量视图;status 尚未加载时也要保留返回入口。
677
+ st?.mode !== 'needs_config'
678
+ ? h(
679
+ 'button',
680
+ {
681
+ className: 'oc-btn',
682
+ style: btnBase,
683
+ onClick: () => {
684
+ store.set({ view: 'status' })
685
+ refreshStatus()
686
+ },
687
+ },
688
+ '← 返回用量',
689
+ )
690
+ : null,
691
+ h(
692
+ 'span',
693
+ { style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } },
694
+ lastSync ? `上次同步 ${lastSync}` : '尚未同步',
695
+ ),
696
+ ].filter(Boolean))
697
+ }
698
+
699
+ return h(
700
+ 'div',
701
+ { style: barStyle },
702
+ [
703
+ h(
704
+ 'button',
705
+ {
706
+ className: 'oc-btn',
707
+ style: btnBase,
708
+ disabled: state.refreshing,
709
+ onClick: manualRefresh,
710
+ title: '绕过 30 秒缓存,强制重新拉取当前剩余额度',
711
+ },
712
+ h('span', { key: 'i', className: state.refreshing ? 'oc-spin' : undefined }, '↻'),
713
+ state.refreshing ? '刷新中…' : '刷新',
714
+ ),
715
+ h('button', { key: 'set', className: 'oc-btn', style: btnBase, onClick: openSettings, title: '配置 Base URL 与 API Key' }, '⚙ 设置'),
716
+ h(
717
+ 'span',
718
+ { key: 'at', style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } },
719
+ lastSync ? `上次同步 ${lastSync}` : '尚未同步',
720
+ ),
721
+ ],
722
+ )
723
+ }
724
+
725
+ const barStyle = {
726
+ flexShrink: 0,
727
+ borderTop: `1px solid ${T.border}`,
728
+ padding: '10px 16px 12px',
729
+ display: 'flex',
730
+ alignItems: 'center',
731
+ gap: 8,
732
+ }
733
+
734
+ // ---------- Overlay 面板(状态视图 / 设置视图) ----------
441
735
  function OverlayPanel() {
442
736
  const state = useStore()
443
737
  const panelRef = useRef(null)
738
+ // 相位机:closed → open → closing(播完退场动画)→ closed。
739
+ // 拆成两个 effect:否则 phase 变化会清掉「170ms 后置 closed」的定时器,面板卡在不可见仍拦截点击的状态。
444
740
  const [phase, setPhase] = useState('closed')
445
-
446
741
  useEffect(() => {
447
742
  if (state.open) setPhase('open')
448
743
  else setPhase((p) => (p === 'open' ? 'closing' : p))
449
744
  }, [state.open])
450
-
451
745
  useEffect(() => {
452
746
  if (phase !== 'closing') return
453
- const timer = setTimeout(() => setPhase('closed'), 160)
747
+ const timer = setTimeout(() => setPhase('closed'), 170)
454
748
  return () => clearTimeout(timer)
455
749
  }, [phase])
456
750
 
457
- // 点击外部关闭
751
+ // 点击外部关闭;footer 常驻按钮自身不在面板内,放行它的点击。
458
752
  useEffect(() => {
459
753
  if (!state.open) return
460
754
  const handleClickOutside = (e) => {
461
755
  if (panelRef.current && !panelRef.current.contains(e.target)) {
462
756
  const isBtn = e.target.closest && e.target.closest('.oc-footer-btn')
463
- if (!isBtn) store.set({ open: false, editing: false })
757
+ if (!isBtn) store.set({ open: false })
464
758
  }
465
759
  }
466
760
  window.addEventListener('mousedown', handleClickOutside)
@@ -470,6 +764,8 @@ window.__ModuleLoader__.load({
470
764
  if (phase === 'closed') return null
471
765
 
472
766
  const st = state.status
767
+ // 未配置时必须直接落在设置视图;其余情况由 store.view 决定。
768
+ const settingsView = state.view === 'settings' || st?.mode === 'needs_config'
473
769
 
474
770
  return h(
475
771
  'div',
@@ -480,75 +776,42 @@ window.__ModuleLoader__.load({
480
776
  position: 'fixed',
481
777
  left: 12,
482
778
  bottom: 52,
483
- width: 320,
779
+ width: 360,
780
+ maxHeight: 'calc(100vh - 80px)',
781
+ overflow: 'hidden',
782
+ display: 'flex',
783
+ flexDirection: 'column',
484
784
  background: T.bg,
485
785
  border: `1px solid ${T.border}`,
486
786
  borderRadius: 16,
487
787
  boxShadow: 'var(--dsw-shadow-lv3, 0 10px 32px rgba(0,0,0,0.4))',
488
- padding: '14px 16px 12px',
489
788
  zIndex: 60,
490
789
  pointerEvents: phase === 'closing' ? 'none' : 'auto',
491
790
  },
492
791
  },
493
792
  [
494
- // 头部
495
- h('div', { key: 'hd', style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, borderBottom: `1px solid ${T.border}`, paddingBottom: 8 } }, [
496
- h('span', { style: { fontSize: 13, fontWeight: 600, color: T.label } }, '⚙ OpenCode GO 连接配置'),
497
- h('div', { style: { display: 'flex', gap: 4, alignItems: 'center' } }, [
498
- h(
499
- 'button',
500
- {
501
- className: 'oc-btn',
502
- style: {
503
- width: 26,
504
- height: 26,
505
- padding: 0,
506
- display: 'inline-flex',
507
- alignItems: 'center',
508
- justifyContent: 'center',
509
- fontSize: 14,
510
- border: 'none',
511
- borderRadius: 6,
512
- cursor: 'pointer',
513
- color: T.secondary,
514
- background: 'transparent',
515
- },
516
- onClick: async () => {
517
- store.set({ refreshing: true })
518
- await refreshStatus(true)
519
- store.set({ refreshing: false })
520
- },
521
- title: '强制刷新同步',
522
- },
523
- state.refreshing ? h('span', { className: 'oc-spin' }, '↻') : '↻',
524
- ),
525
- h(
526
- 'button',
527
- {
528
- className: 'oc-btn',
529
- style: {
530
- width: 26,
531
- height: 26,
532
- padding: 0,
533
- display: 'inline-flex',
534
- alignItems: 'center',
535
- justifyContent: 'center',
536
- fontSize: 13,
537
- border: 'none',
538
- borderRadius: 6,
539
- cursor: 'pointer',
540
- color: T.secondary,
541
- background: 'transparent',
542
- },
543
- onClick: () => store.set({ open: false, editing: false }),
544
- title: '关闭',
545
- },
546
- '✕',
547
- ),
548
- ]),
549
- ]),
550
- // 内容:直接展示配置与连接管理
551
- h(ConfigCard),
793
+ // 固定头部:标题 + 关闭
794
+ h('div', { key: 'hd', style: { display: 'flex', alignItems: 'center', padding: '14px 16px 10px', borderBottom: `1px solid ${T.border}`, flexShrink: 0 } }, [
795
+ h('span', { key: 't', style: { fontSize: 13, fontWeight: 600, color: T.label } }, settingsView ? '⚙ OpenCode GO 连接配置' : 'OpenCode GO 用量'),
796
+ !settingsView && st?.config?.baseUrl
797
+ ? h('span', { key: 'h', style: { fontSize: 10, color: T.secondary, marginLeft: 8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, hostOf(st.config.baseUrl))
798
+ : null,
799
+ h(
800
+ 'button',
801
+ {
802
+ key: 'x',
803
+ className: 'oc-btn',
804
+ style: { ...btnBase, marginLeft: 'auto', border: 'none', padding: '2px 6px' },
805
+ onClick: closeOverlay,
806
+ title: '关闭',
807
+ },
808
+ '✕',
809
+ ),
810
+ ].filter(Boolean)),
811
+ // 滚动内容区
812
+ h('div', { key: 'body', style: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 16px' } }, settingsView ? h(ConfigCard) : h(StatusView)),
813
+ // 固定底部操作条:刷新 / 设置 / 上次同步
814
+ h(OpsBar, { key: 'ops', settings: settingsView }),
552
815
  ],
553
816
  )
554
817
  }