dsh-opencode-status 0.3.0 → 0.4.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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ - 可访问性与键盘:用量面板从无语义裸容器改为 `role="dialog"`,`aria-label` 随视图变化(「OpenCode GO 用量」/「OpenCode GO 连接配置」);`Esc` 关闭面板,`Tab` 在面板内首尾循环;打开时焦点移入面板(容器 `tabIndex: -1`),关闭(含 Esc)后焦点归还打开前的触发按钮,点击面板外关闭时不抢焦点(焦点留在用户新点的控件上)。面板允许点击外部关闭、属非模态,因此**不声明** `aria-modal`(WAI-ARIA 要求 `aria-modal=true` 时外部内容不可交互,而本面板没有 inert 实现,声明反而误导读屏)。
6
+ - 进度条语义化:每个窗口轨道改为 `role="progressbar"`,带 `aria-valuemin=0` / `aria-valuemax=100` / `aria-valuenow`(取整后的剩余额度)与 `aria-valuetext`(「剩余 X%,已用 Y%,档位」);数据不可用时只给 `aria-valuetext="数据不可用"`,不输出 `aria-valuenow`。
7
+ - 告警不再只靠颜色:剩余 ≤20% 追加 `⚠ 即将耗尽`、≤50% 追加 `⚠ 偏低` 的文字徽标,并并入 `aria-valuetext`;颜色阈值与颜色逻辑一字未改,色觉障碍用户与灰度截图同样能读出档位。
8
+ - 信息去重与层级:
9
+ - 窗口行主百分比只显示剩余额度,进度条条长与主百分比同源(条长 = 剩余占比,条色 = 剩余档位),「已用」降级到 `title` 与 `aria-valuetext`,同一行不再并列「已用 X% / 剩余 Y%」表达同一个数字。
10
+ - 头部去掉与标题行重复的 host;「月剩余 N%」改为判断性摘要「最紧张 <窗口> N%」(取剩余最小的窗口),具体数字只保留在窗口行。
11
+ - 免责说明(上游 `/v1/usage` 只提供百分比、界面不展示金额余额)移出用量视图正文,落到设置视图底部,用量视图只保留结论。
12
+ - 相对时间:底部操作条与悬浮卡的上次同步改为相对时间(刚刚 / 12s 前 / 3 分钟前 / …),绝对时刻(HH:MM:SS)保留在 `title`;同步数据超过 2 分钟追加「· 可能已过期」并用警告色,避免把旧额度当实时值。
13
+ - 倒计时图标:窗口行与悬浮卡的倒计时由 `↻` 改为 `⏱`,与刷新动作的 `↻` 区分,两个语义不再共用一个图标。
14
+ - 宽度自适应:面板宽度改为 `width: min(360px, calc(100vw - 24px))` + `maxWidth: calc(100vw - 24px)` + `boxSizing: border-box`;窄视口(<372px)不再右侧溢出,宽视口仍固定 360px。
15
+ - 数值规整:宿主对三个窗口与月度百分比的 used/remaining 统一取整并双侧钳制到 0–100,且由取整后的 used 反推 remaining,保证两者恒和 100(12.5 → 13/87,旧实现为 13/88);上游拉取失败时不再前移「上次同步」,失败不会伪装成新鲜数据。
16
+ - 轮询策略:仍为 30 秒自动刷新;页面不可见(`document.hidden`)时暂停轮询,元素重新可见时立即补拉一次,避免后台空转和回到前台看到陈旧值;手动刷新仍是唯一绕过服务端 30 秒缓存的入口。
17
+ - 动效收敛:状态灯呼吸动画由无限循环改为进场一次(`ocPulse 1.2s ease-out 1 both`)并绑定 `fetchedAt`,只在数据真正更新时触发;`prefers-reduced-motion: reduce` 下禁用动画。
18
+ - 测试:用例从 36 增至 42,新增 dialog/`aria-label`/无 `aria-modal`、progressbar 数值语义、非颜色档位标记、免责说明位置、最紧张摘要、相对时间与过期提示、百分比规整(含 12.5 边界)等断言;原有用例(含安全、配置、竞态回归)全部保留,未削弱。
19
+ - 版本号升至 `0.4.0`;README 的功能特性与交互说明同步更新。`0.3.0` 已于 2026-11-08 单独发布,其改动不在本版本内重复。
20
+
3
21
  ## 0.3.0
4
22
 
5
23
  - 重构点击交互:侧栏常驻按钮改为打开用量面板(默认用量视图),不再直接弹出连接配置表单;参考 dsh-cpa-status 的双视图范式。
package/README.md CHANGED
@@ -8,21 +8,29 @@ OpenCode GO 套餐用量与配额状态监控面板插件(DeepSeek Harness)
8
8
  - **固定底部操作条**:
9
9
  - `↻ 刷新`:通过 `POST /api/opencode-status/sync` 绕过 30 秒缓存,强制重新拉取当前剩余额度;刷新期间按钮禁用并显示旋转与「刷新中…」,完成后面板与侧栏数值同步更新,失败时在面板内显示错误文案而不是静默。
10
10
  - `⚙ 设置`:进入面板内的独立连接设置视图,可随时 `← 返回用量`。
11
- - 右侧固定显示「上次同步 HH:MM:SS」(取 `status.fetchedAt`)。
12
- - **3 维度用量行**:每行同时给出已用 % 与剩余 %、重置倒计时和进度条,颜色按剩余额度阈值着色(与 dsh-cpa-status 的 QuotaBar 语义一致);窗口状态非 `ok` 时给出可见提示。
13
- - **滚动窗口 (5h)**:`已用 30% · 剩余 70% · ↻ 4h20m`
14
- - **周窗口 (Weekly)**:周额度消耗与剩余 % + 重置倒计时
15
- - **月窗口 (Monthly)**:月额度消耗与剩余 % + 重置倒计时
16
- - **连接设置视图**:未配置(`mode === 'needs_config'`)时面板直接显示设置视图;保存成功后自动回到用量视图;「取消」丢弃未保存的编辑并关闭面板。密钥仅存入宿主凭据库(`OPENCODE_GO_API_KEY`),API 响应不回传明文。
17
- - **220ms 悬浮微卡**:鼠标悬停常驻按钮 220ms 后在面板关闭且连接正常时出现,展示标题 + GO 标识 + 最近同步时间、三个窗口的紧凑行(名称 / 剩余 % / ↻ 重置倒计时 / 细进度条)与底部「点击查看详情」;纯展示卡片,不拦截按钮点击。
18
- - **缓存与刷新**:服务端 30 秒缓存 + 客户端 30 秒自动刷新;打开面板、切换视图不会额外探测上游,手动刷新是唯一绕过缓存的入口。
19
- - **额度语义**:上游 `/v1/usage` 只提供 rolling/weekly/monthly 百分比,没有 USD 余额接口([anomalyco/opencode#10448](https://github.com/anomalyco/opencode/issues/10448) 仍 open),因此界面只展示「剩余额度 / 可用百分比」,不编造金额余额。
11
+ - 右侧显示相对时间「上次同步 12s 前」(刚刚 / Ns 前 / N 分钟前 / N 小时前 / N 天前),绝对时刻 HH:MM:SS 保留在 `title`;同步数据超过 2 分钟追加「· 可能已过期」并用警告色,避免把旧额度当成实时值。
12
+ - **3 维度用量行**:主百分比只给剩余额度,进度条条长与它同源(条长 = 剩余占比,条色 = 剩余档位),「已用」放在 `title` 与 `aria-valuetext` 里,同一行不再重复表达同一个数字;窗口状态非 `ok` 时给出可见提示。
13
+ - **滚动窗口 (5h)**:`剩余 70% · ⏱ 4h20m`
14
+ - **周窗口 (Weekly)**:周额度剩余 % + ⏱ 重置倒计时
15
+ - **月窗口 (Monthly)**:月额度剩余 % + ⏱ 重置倒计时
16
+ - 面板头部只给判断性摘要「最紧张 <窗口> N%」(取剩余最小的窗口),具体数字留在窗口行。
17
+ - **可访问性与键盘交互**:
18
+ - 面板是 `role="dialog"`,`aria-label` 随视图切换(「OpenCode GO 用量」/「OpenCode GO 连接配置」)。
19
+ - `Esc` 关闭面板;`Tab` 在面板内首尾循环;打开时焦点移入面板,关闭(含 Esc)后归还到打开前的触发按钮,点击面板外关闭时不抢焦点。
20
+ - 面板允许点击外部关闭,属非模态对话框,因此**不声明** `aria-modal`。
21
+ - 每个窗口的进度条是 `role="progressbar"`,带 `aria-valuemin` / `aria-valuemax` / `aria-valuenow`(取整剩余额度)与 `aria-valuetext`(「剩余 X%,已用 Y%,档位」);数据不可用时只报「数据不可用」,不给数值。
22
+ - 低额度除颜色外还有文字徽标(`⚠ 即将耗尽` ≤20%、`⚠ 偏低` ≤50%),色觉障碍与灰度截图也能读出档位。
23
+ - 面板宽度为 `min(360px, calc(100vw - 24px))`,窄窗口(<372px)不再右侧溢出。
24
+ - **连接设置视图**:未配置(`mode === 'needs_config'`)时面板直接显示设置视图;保存成功后自动回到用量视图;「取消」丢弃未保存的编辑并关闭面板。密钥仅存入宿主凭据库(`OPENCODE_GO_API_KEY`),API 响应不回传明文。数据口径说明(上游只提供百分比、界面不展示金额余额)放在此视图底部,不占用用量视图。
25
+ - **220ms 悬浮微卡**:鼠标悬停常驻按钮 220ms 后在面板关闭且连接正常时出现,展示标题 + GO 标识 + 最近同步时间(相对时间)、三个窗口的紧凑行(名称 / 剩余 % / ⏱ 重置倒计时 / 细进度条)与底部「点击查看详情」;纯展示卡片,不拦截按钮点击。
26
+ - **缓存与刷新**:服务端 30 秒缓存 + 客户端 30 秒自动刷新;页面不可见时暂停轮询,元素重新可见时立即补拉一次;打开面板、切换视图不会额外探测上游,手动刷新是唯一绕过缓存的入口。
27
+ - **额度语义**:上游 `/v1/usage` 只提供 rolling/weekly/monthly 百分比,没有 USD 余额接口([anomalyco/opencode#10448](https://github.com/anomalyco/opencode/issues/10448) 仍 open),因此界面只展示「剩余额度 / 可用百分比」,不编造金额余额;百分比由宿主统一取整并钳制到 0–100,剩余与已用恒和 100。
20
28
 
21
29
  ## 安装与更新
22
30
 
23
31
  ### 兼容性(DSH 0.2.x)
24
32
 
25
- - 本版本(`0.3.x`)面向 **DeepSeek Harness 0.2.x**,已在 `0.2.2-rc.1` 上验证;`package.json` 通过 `engines.dsh: ">=0.2.0 <0.3.0-0"` 声明兼容范围(上界带 `-0` 显式排除 0.3.0 的预发布版;宿主用 semver `includePrerelease` 校验,已用其 `evaluatePluginCompatibility` 验证 `0.2.2-rc.1` 为 COMPATIBLE、`0.3.0-rc.1`/`0.3.0-rc.2`/`0.3.0` 为 UNMET)。
33
+ - 本版本(`0.4.x`)面向 **DeepSeek Harness 0.2.x**,已在 `0.2.2-rc.1` 上验证;`package.json` 通过 `engines.dsh: ">=0.2.0 <0.3.0-0"` 声明兼容范围(上界带 `-0` 显式排除 0.3.0 的预发布版;宿主用 semver `includePrerelease` 校验,已用其 `evaluatePluginCompatibility` 验证 `0.2.2-rc.1` 为 COMPATIBLE、`0.3.0-rc.1`/`0.3.0-rc.2`/`0.3.0` 为 UNMET)。
26
34
  - DSH 0.2.x 移除了旧的插件配置注册接口,改为读取插件导出的 schemastery `Config`:`baseUrl`、`keyRef` 声明为 `volatile` 字段,由宿主生成配置表单并以 live ref 传入 `apply(ctx, config)`。因此 `0.1.x` 及更早版本在 DSH 0.2.x 上无法激活,请升级到 `0.2.0` 或更高版本。
27
35
  - 升级方式:先把 DSH 升级到 0.2.x,再执行下面的安装命令(默认拉取 `@latest`),然后重启 `dsh web`。Base URL 会以插件配置写入当前 profile 的 `cordis.patch.yml`,API Key 仍保存在宿主凭据库,无需迁移。
28
36
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-opencode-status",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "OpenCode GO quota status panel for DeepSeek Harness: click to open a usage panel with manual refresh, per-window remaining quota, a hover overview card, and in-app connection settings",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/src/client.js CHANGED
@@ -30,7 +30,8 @@ window.__ModuleLoader__.load({
30
30
  .oc-btn:active:not(:disabled) { transform: scale(.98) }
31
31
  .oc-btn:disabled { opacity: .55; cursor: default }
32
32
  .oc-spin { display: inline-block; animation: ocSpin .8s linear infinite }
33
- .oc-dot-live { animation: ocPulse 2.4s ease-out infinite }
33
+ /* 状态灯呼吸只播一次:数据/状态变化时由 React key 换新节点重播,不再无限循环抢注意力 */
34
+ .oc-dot-live { animation: ocPulse 1.2s ease-out 1 both }
34
35
  /* 悬浮微卡只读:不接收任何指针事件,避免遮挡 footer 按钮的点击 */
35
36
  .oc-hover-card { pointer-events: none !important }
36
37
  @media (prefers-reduced-motion: reduce) {
@@ -93,6 +94,9 @@ window.__ModuleLoader__.load({
93
94
 
94
95
  const labelStyle = { display: 'block', fontSize: 12, color: T.secondary, marginBottom: 4 }
95
96
 
97
+ // 面板内的可聚焦元素:仅用于 Tab 首尾循环,不是完整的焦点陷阱。
98
+ const FOCUSABLE = 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])'
99
+
96
100
  function timeUntil(ts) {
97
101
  if (!ts) return ''
98
102
  const diff = ts - Date.now()
@@ -120,10 +124,52 @@ window.__ModuleLoader__.load({
120
124
  return T.err
121
125
  }
122
126
 
127
+ /** 额度档位文字:颜色之外再给一个非颜色信号(色盲用户与读屏都不能只靠颜色),阈值与 remainingColor 对齐。 */
128
+ function remainingBand(remaining) {
129
+ if (remaining === null || remaining === undefined) return null
130
+ if (remaining <= 20) return '即将耗尽'
131
+ if (remaining <= 50) return '偏低'
132
+ return null
133
+ }
134
+
135
+ /** 相对时间:面板显示「12s 前」「3 分钟前」,绝对时间放 title,避免每次轮询都盯着一串时分秒。 */
136
+ function fmtRelative(ts, now = Date.now()) {
137
+ if (!ts) return ''
138
+ const diff = Math.max(0, now - ts)
139
+ if (diff < 10_000) return '刚刚'
140
+ const secs = Math.floor(diff / 1000)
141
+ if (secs < 60) return `${secs}s 前`
142
+ const mins = Math.floor(secs / 60)
143
+ if (mins < 60) return `${mins} 分钟前`
144
+ const hours = Math.floor(mins / 60)
145
+ if (hours < 24) return `${hours} 小时前`
146
+ return `${Math.floor(hours / 24)} 天前`
147
+ }
148
+
149
+ /** 同步数据超过 2 分钟未更新:给弱过期提示,避免把旧额度当成实时值。 */
150
+ const STALE_AFTER_MS = 2 * 60_000
151
+
123
152
  function clampPct(value) {
124
153
  return Math.max(0, Math.min(100, value))
125
154
  }
126
155
 
156
+ /** 百分比显示值:取整并钳制到 0–100(宿主已规整,这里再兜一层,旧数据也不会出现小数或越界值)。 */
157
+ function pctText(value) {
158
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
159
+ return `${Math.round(clampPct(value))}%`
160
+ }
161
+
162
+ /** 最紧张的用量窗口:头部只给判断性摘要,避免与窗口行重复表达同一个数字。 */
163
+ function tightestWindow(status) {
164
+ const windows = Array.isArray(status?.windows) ? status.windows : []
165
+ let tightest = null
166
+ for (const w of windows) {
167
+ if (typeof w?.remainingPct !== 'number') continue
168
+ if (!tightest || w.remainingPct < tightest.remainingPct) tightest = w
169
+ }
170
+ return tightest
171
+ }
172
+
127
173
  /** 月窗口剩余百分比;上游只给百分比,不存在金额余额。 */
128
174
  function monthlyRemainingOf(status) {
129
175
  if (!status) return null
@@ -256,8 +302,22 @@ window.__ModuleLoader__.load({
256
302
 
257
303
  useEffect(() => {
258
304
  refreshStatus()
259
- const timer = setInterval(() => refreshStatus(), 30_000)
260
- return () => clearInterval(timer)
305
+ // 30 秒 GET 自动刷新;页面隐藏时暂停轮询,恢复可见时立即补拉一次,避免后台空转探测上游。
306
+ let timer = setInterval(() => refreshStatus(), 30_000)
307
+ const onVisibilityChange = () => {
308
+ clearInterval(timer)
309
+ timer = null
310
+ if (typeof document !== 'undefined' && document.hidden) return
311
+ refreshStatus()
312
+ timer = setInterval(() => refreshStatus(), 30_000)
313
+ }
314
+ // 测试与 SSR 沙箱里 document 可能没有事件接口,先探测再注册。
315
+ const canListen = typeof document !== 'undefined' && typeof document.addEventListener === 'function'
316
+ if (canListen) document.addEventListener('visibilitychange', onVisibilityChange)
317
+ return () => {
318
+ if (timer !== null) clearInterval(timer)
319
+ if (canListen) document.removeEventListener('visibilitychange', onVisibilityChange)
320
+ }
261
321
  }, [])
262
322
 
263
323
  const onMouseEnter = () => {
@@ -375,7 +435,12 @@ window.__ModuleLoader__.load({
375
435
  },
376
436
  onClick: toggleOverlay,
377
437
  },
378
- h('span', { className: color === T.ok ? 'oc-dot-live' : undefined, style: dotStyle(color) }),
438
+ h('span', {
439
+ // 呼吸动画只播一次:key 绑定 fetchedAt,新数据到达时换新节点重播一次,而不是无限循环。
440
+ key: color === T.ok ? `live-${st?.fetchedAt ?? 0}` : 'live',
441
+ className: color === T.ok ? 'oc-dot-live' : undefined,
442
+ style: dotStyle(color),
443
+ }),
379
444
  labelEl,
380
445
  )
381
446
 
@@ -402,6 +467,8 @@ window.__ModuleLoader__.load({
402
467
  'div',
403
468
  {
404
469
  className: 'oc-panel-enter oc-hover-card',
470
+ // 只读微卡是面板的视觉重复,对读屏隐藏,避免同一份数据播报两遍。
471
+ 'aria-hidden': true,
405
472
  style: {
406
473
  position: 'absolute',
407
474
  left: 0,
@@ -443,8 +510,13 @@ window.__ModuleLoader__.load({
443
510
  ),
444
511
  h(
445
512
  'span',
446
- { key: 'at', style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums', flexShrink: 0 } },
447
- st?.fetchedAt ? `上次同步 ${fmtClock(st.fetchedAt)}` : '尚未同步',
513
+ {
514
+ key: 'at',
515
+ // 相对时间更易读;绝对时刻保留在 title 里,需要精确对时再悬停查看。
516
+ title: st?.fetchedAt ? `上次同步 ${fmtClock(st.fetchedAt)}` : '尚未同步',
517
+ style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums', flexShrink: 0 },
518
+ },
519
+ st?.fetchedAt ? `上次同步 ${fmtRelative(st.fetchedAt)}` : '尚未同步',
448
520
  ),
449
521
  ]),
450
522
  h(
@@ -461,7 +533,7 @@ window.__ModuleLoader__.load({
461
533
  )
462
534
  }
463
535
 
464
- /** 悬浮卡紧凑行:名称 / 剩余 % / ↻ 重置倒计时 / 细进度条。 */
536
+ /** 悬浮卡紧凑行:名称 / 剩余 % / ⏱ 重置倒计时 / 细进度条。 */
465
537
  function MiniQuotaRow(props) {
466
538
  const w = props.window
467
539
  const remaining = w?.remainingPct ?? null
@@ -475,8 +547,9 @@ window.__ModuleLoader__.load({
475
547
  ? null
476
548
  : h('div', { style: { height: '100%', width: `${clampPct(remaining)}%`, background: color, borderRadius: 2 } }),
477
549
  ),
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)}` : ''),
550
+ h('span', { key: 'v', style: { minWidth: 30, textAlign: 'right', fontSize: 10, fontWeight: 600, color, fontVariantNumeric: 'tabular-nums' } }, remaining === null ? '—' : pctText(remaining)),
551
+ // 倒计时用 ⏱ 区分刷新动作的 ↻,避免两个图标同义混淆。
552
+ h('span', { key: 'r', style: { minWidth: 34, textAlign: 'right', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } }, w?.resetAt ? `⏱ ${timeUntil(w.resetAt)}` : ''),
480
553
  ])
481
554
  }
482
555
 
@@ -490,19 +563,23 @@ window.__ModuleLoader__.load({
490
563
  }
491
564
 
492
565
  const windows = Array.isArray(st.windows) ? st.windows : []
493
- const monthlyRemaining = monthlyRemainingOf(st)
494
- const host = hostOf(st.config?.baseUrl)
566
+ // 头部只给判断性摘要(最紧张窗口),具体数字留给下方窗口行,避免同一数字说两遍。
567
+ const tightest = tightestWindow(st)
495
568
 
496
569
  return h('div', null, [
497
570
  h('div', { key: 'sum', style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
498
571
  h('span', { key: 'd', style: dotStyle(st.ok ? T.ok : T.err) }),
499
572
  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
573
+ tightest
502
574
  ? h(
503
575
  'span',
504
- { key: 'm', style: { marginLeft: 'auto', fontSize: 11, fontWeight: 600, color: remainingColor(monthlyRemaining), fontVariantNumeric: 'tabular-nums', flexShrink: 0 } },
505
- `月剩余 ${monthlyRemaining}%`,
576
+ {
577
+ key: 'm',
578
+ // host 只在面板标题行展示一次;这里不再重复。
579
+ title: `最紧张窗口:${tightest.label ?? tightest.id ?? '—'},剩余 ${pctText(tightest.remainingPct)}`,
580
+ style: { marginLeft: 'auto', fontSize: 11, fontWeight: 600, color: remainingColor(tightest.remainingPct), fontVariantNumeric: 'tabular-nums', flexShrink: 0 },
581
+ },
582
+ `最紧张 ${tightest.shortLabel ?? tightest.label ?? '—'} ${pctText(tightest.remainingPct)}`,
506
583
  )
507
584
  : null,
508
585
  ].filter(Boolean)),
@@ -518,32 +595,48 @@ window.__ModuleLoader__.load({
518
595
  st.ok && !windows.length
519
596
  ? h('div', { key: 'empty', style: { fontSize: 11, color: T.secondary, marginTop: 10 } }, '暂无用量窗口数据')
520
597
  : null,
521
- h(
522
- 'div',
523
- { key: 'note', style: { fontSize: 10, color: T.secondary, marginTop: 6, lineHeight: '15px' } },
524
- '上游 /v1/usage 仅提供百分比额度,界面不展示金额余额。',
525
- ),
526
598
  ].filter(Boolean))
527
599
  }
528
600
 
529
- /** 面板窗口行:已用 % + 剩余 % + 重置倒计时 + 进度条(按剩余额度着色)。 */
601
+ /**
602
+ * 面板窗口行:主百分比只显示剩余额度(进度条填充同源),「已用」降级到 aria-valuetext 与 title。
603
+ * 语义约定:条长 = 剩余额度占比,条色 = 剩余额度档位;不再同一行并列「已用 X% / 剩余 Y%」重复表达。
604
+ */
530
605
  function QuotaRow(props) {
531
606
  const w = props.window
532
607
  const used = w?.usedPct ?? null
533
608
  const remaining = w?.remainingPct ?? null
534
609
  const color = remainingColor(remaining)
610
+ const band = remainingBand(remaining)
535
611
  const statusText = w?.status && w.status !== 'ok' ? w.status : null
612
+ const detail = remaining === null ? '数据不可用' : `已用 ${pctText(used)} · 剩余 ${pctText(remaining)}`
536
613
  return h('div', { style: { marginBottom: 12 } }, [
537
614
  h('div', { key: 'meta', style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: 11, marginBottom: 4, fontVariantNumeric: 'tabular-nums' } }, [
538
615
  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,
616
+ h('span', { key: 'r', title: detail, style: { marginLeft: 'auto', color, fontWeight: 600, flexShrink: 0 } }, remaining === null ? '剩余 —' : `剩余 ${pctText(remaining)}`),
617
+ // 低额度除颜色外再给文字标记:色觉障碍与灰度截图里也能看出档位。
618
+ band
619
+ ? h(
620
+ 'span',
621
+ { key: 'band', style: { color, flexShrink: 0, fontSize: 10, lineHeight: '14px', padding: '0 4px', borderRadius: 4, border: `1px solid ${color}` } },
622
+ `⚠ ${band}`,
623
+ )
624
+ : null,
625
+ // 倒计时用 ⏱ 区分刷新动作的 ↻,避免两个图标同义混淆。
626
+ w?.resetAt ? h('span', { key: 't', style: { color: T.secondary, flexShrink: 0 } }, `⏱ ${timeUntil(w.resetAt)}`) : null,
542
627
  ].filter(Boolean)),
543
628
  h(
544
629
  'div',
545
630
  {
546
631
  key: 'track',
632
+ // 进度条语义:aria-valuenow 取剩余额度,与条长、右侧主百分比同源。
633
+ role: 'progressbar',
634
+ 'aria-label': `${w?.label ?? '用量窗口'}剩余额度`,
635
+ 'aria-valuemin': 0,
636
+ 'aria-valuemax': 100,
637
+ ...(remaining === null ? {} : { 'aria-valuenow': Math.round(clampPct(remaining)) }),
638
+ 'aria-valuetext': remaining === null ? '数据不可用' : `剩余 ${pctText(remaining)},已用 ${pctText(used)}${band ? `,${band}` : ''}`,
639
+ title: detail,
547
640
  style: {
548
641
  height: 6,
549
642
  borderRadius: 3,
@@ -662,6 +755,12 @@ window.__ModuleLoader__.load({
662
755
  ? h('button', { className: 'oc-btn', style: { ...btnBase, color: T.err, marginLeft: 'auto' }, disabled: saving, onClick: clearKey }, '清除')
663
756
  : null,
664
757
  ].filter(Boolean)),
758
+ // 数据口径说明放设置视图:用量视图保持只读结论,正文不再常驻免责声明。
759
+ h(
760
+ 'div',
761
+ { key: 'note', style: { fontSize: 10, color: T.secondary, marginTop: 14, lineHeight: '15px' } },
762
+ '上游 /v1/usage 仅提供百分比额度,界面不展示金额余额。',
763
+ ),
665
764
  ])
666
765
  }
667
766
 
@@ -669,7 +768,17 @@ window.__ModuleLoader__.load({
669
768
  function OpsBar(props) {
670
769
  const state = useStore()
671
770
  const st = state.status
672
- const lastSync = st?.fetchedAt ? fmtClock(st.fetchedAt) : null
771
+ // 相对时间更好读;绝对时刻保留在 title,同步超过 2 分钟再给弱过期提示。
772
+ const lastSync = st?.fetchedAt ? fmtRelative(st.fetchedAt) : null
773
+ const lastSyncTitle = st?.fetchedAt ? `上次同步 ${fmtClock(st.fetchedAt)}` : '尚未同步'
774
+ const lastSyncStale = Boolean(st?.fetchedAt) && Date.now() - st.fetchedAt > STALE_AFTER_MS
775
+ const syncText = lastSync ? `上次同步 ${lastSync}${lastSyncStale ? ' · 可能已过期' : ''}` : '尚未同步'
776
+ const syncSpan = (key, extraStyle) =>
777
+ h(
778
+ 'span',
779
+ { key, title: lastSyncTitle, style: { ...extraStyle, fontVariantNumeric: 'tabular-nums' } },
780
+ syncText,
781
+ )
673
782
 
674
783
  if (props?.settings) {
675
784
  return h('div', { style: barStyle }, [
@@ -688,11 +797,7 @@ window.__ModuleLoader__.load({
688
797
  '← 返回用量',
689
798
  )
690
799
  : null,
691
- h(
692
- 'span',
693
- { style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } },
694
- lastSync ? `上次同步 ${lastSync}` : '尚未同步',
695
- ),
800
+ syncSpan('at', { marginLeft: 'auto', fontSize: 10, color: T.secondary }),
696
801
  ].filter(Boolean))
697
802
  }
698
803
 
@@ -713,11 +818,7 @@ window.__ModuleLoader__.load({
713
818
  state.refreshing ? '刷新中…' : '刷新',
714
819
  ),
715
820
  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
- ),
821
+ syncSpan('at', { marginLeft: 'auto', fontSize: 10, color: lastSyncStale ? T.warn : T.secondary }),
721
822
  ],
722
823
  )
723
824
  }
@@ -761,6 +862,56 @@ window.__ModuleLoader__.load({
761
862
  return () => window.removeEventListener('mousedown', handleClickOutside)
762
863
  }, [state.open])
763
864
 
865
+ // Esc 关闭:与面板同开同卸载;Tab 焦点保持在面板内,避免键盘用户掉到背后的不可见区域。
866
+ useEffect(() => {
867
+ if (!state.open) return
868
+ const handleKeyDown = (e) => {
869
+ if (e.key === 'Escape') {
870
+ e.stopPropagation()
871
+ closeOverlay()
872
+ return
873
+ }
874
+ if (e.key !== 'Tab' || !panelRef.current || typeof panelRef.current.querySelectorAll !== 'function') return
875
+ const focusables = [...panelRef.current.querySelectorAll(FOCUSABLE)]
876
+ if (!focusables.length) {
877
+ e.preventDefault()
878
+ panelRef.current.focus()
879
+ return
880
+ }
881
+ const first = focusables[0]
882
+ const last = focusables[focusables.length - 1]
883
+ if (e.shiftKey && (e.target === first || e.target === panelRef.current)) {
884
+ e.preventDefault()
885
+ last.focus()
886
+ } else if (!e.shiftKey && e.target === last) {
887
+ e.preventDefault()
888
+ first.focus()
889
+ }
890
+ }
891
+ window.addEventListener('keydown', handleKeyDown)
892
+ return () => window.removeEventListener('keydown', handleKeyDown)
893
+ }, [state.open])
894
+
895
+ // 焦点管理:面板挂载(phase 进入 open)后把焦点移入面板(容器 tabIndex=-1),关闭时归还打开前的触发元素(footer 按钮)。
896
+ // 依赖必须带上 phase:面板 DOM 要等 phase effect 把 phase 推到 'open' 才挂载,只依赖 state.open 时
897
+ // 首次执行 panelRef.current 还是 null,panel.focus() 会静默失效(运行时复现由 /tmp/verify-focus.mjs 手工验证,CI 无 jsdom 依赖)。
898
+ useEffect(() => {
899
+ if (!state.open || phase !== 'open') return
900
+ if (typeof document === 'undefined') return
901
+ const previous = document.activeElement
902
+ const panel = panelRef.current
903
+ if (panel && typeof panel.focus === 'function') panel.focus()
904
+ return () => {
905
+ if (!previous || typeof previous.focus !== 'function') return
906
+ // 只把焦点从面板(或已失焦的 body)收回触发按钮:点击外部关闭时不要抢走用户刚点中的控件焦点。
907
+ // cleanup 里不能用打开时捕获的 panel(闭包可能拿到 null),改用当前 ref。
908
+ const current = panelRef.current
909
+ const active = document.activeElement
910
+ if (active && active !== document.body && typeof current?.contains === 'function' && !current.contains(active)) return
911
+ previous.focus()
912
+ }
913
+ }, [state.open, phase])
914
+
764
915
  if (phase === 'closed') return null
765
916
 
766
917
  const st = state.status
@@ -772,11 +923,18 @@ window.__ModuleLoader__.load({
772
923
  {
773
924
  ref: panelRef,
774
925
  className: phase === 'closing' ? 'oc-panel-exit' : 'oc-panel-enter',
926
+ // 非模态对话框:允许点击外部关闭,因此不声明 aria-modal(WAI-ARIA 要求 aria-modal=true 时外部内容不可交互)。
927
+ role: 'dialog',
928
+ 'aria-label': settingsView ? 'OpenCode GO 连接配置' : 'OpenCode GO 用量',
929
+ tabIndex: -1,
775
930
  style: {
776
931
  position: 'fixed',
777
932
  left: 12,
778
933
  bottom: 52,
779
- width: 360,
934
+ // 窄视口(<384px)不再右侧溢出:宽度随视口收缩,border-box 让 1px 边框不额外撑宽。
935
+ width: 'min(360px, calc(100vw - 24px))',
936
+ maxWidth: 'calc(100vw - 24px)',
937
+ boxSizing: 'border-box',
780
938
  maxHeight: 'calc(100vh - 80px)',
781
939
  overflow: 'hidden',
782
940
  display: 'flex',
@@ -804,6 +962,7 @@ window.__ModuleLoader__.load({
804
962
  style: { ...btnBase, marginLeft: 'auto', border: 'none', padding: '2px 6px' },
805
963
  onClick: closeOverlay,
806
964
  title: '关闭',
965
+ 'aria-label': '关闭面板',
807
966
  },
808
967
  '✕',
809
968
  ),
package/src/index.js CHANGED
@@ -53,6 +53,19 @@ function isJsonContentType(value) {
53
53
  return typeof value === 'string' && /^application\/json\s*(?:;|$)/i.test(value.trim())
54
54
  }
55
55
 
56
+ /** 百分比取整并钳制到 0–100:上游给小数或越界值时,界面不会出现 12.34% 或 120%。 */
57
+ function normalizePct(value) {
58
+ if (typeof value !== 'number' || !Number.isFinite(value)) return null
59
+ return Math.round(Math.min(100, Math.max(0, value)))
60
+ }
61
+
62
+ /** 从上游「已用百分比」派生互斥整数对:先取整 used,再 remaining = 100 - used,保证两者之和恒为 100。 */
63
+ function pctPair(percent) {
64
+ const usedPct = normalizePct(percent)
65
+ if (usedPct === null) return { usedPct: null, remainingPct: null }
66
+ return { usedPct, remainingPct: 100 - usedPct }
67
+ }
68
+
56
69
  /** 读取请求头;Node 的 headers 是名字归一化后的普通对象。 */
57
70
  function headerValue(headers, name) {
58
71
  const value = headers?.[name]
@@ -154,6 +167,8 @@ async function fetchUsageFromGateway(baseUrl, apiKey) {
154
167
  export function apply(ctx, config = {}) {
155
168
  /** @type {{ at: number, baseUrl: string, keyRef: string, data: any } | null} */
156
169
  let usageCache = null
170
+ // 最后一次成功拉取的时间:失败分支沿用它,避免「上次同步」在拉取失败时反而前移。
171
+ let lastSuccessAt = null
157
172
 
158
173
  function invalidateCache() {
159
174
  usageCache = null
@@ -265,8 +280,7 @@ export function apply(ctx, config = {}) {
265
280
  id: 'rolling',
266
281
  label: '滚动窗口 (5h)',
267
282
  shortLabel: '5h',
268
- usedPct: typeof u.rolling?.percent === 'number' ? u.rolling.percent : null,
269
- remainingPct: typeof u.rolling?.percent === 'number' ? Math.max(0, 100 - u.rolling.percent) : null,
283
+ ...pctPair(u.rolling?.percent),
270
284
  status: u.rolling?.status ?? 'ok',
271
285
  resetAt: u.rolling?.resetsAt ? Date.parse(u.rolling.resetsAt) : null,
272
286
  },
@@ -274,8 +288,7 @@ export function apply(ctx, config = {}) {
274
288
  id: 'weekly',
275
289
  label: '周窗口',
276
290
  shortLabel: 'Weekly',
277
- usedPct: typeof u.weekly?.percent === 'number' ? u.weekly.percent : null,
278
- remainingPct: typeof u.weekly?.percent === 'number' ? Math.max(0, 100 - u.weekly.percent) : null,
291
+ ...pctPair(u.weekly?.percent),
279
292
  status: u.weekly?.status ?? 'ok',
280
293
  resetAt: u.weekly?.resetsAt ? Date.parse(u.weekly.resetsAt) : null,
281
294
  },
@@ -283,8 +296,7 @@ export function apply(ctx, config = {}) {
283
296
  id: 'monthly',
284
297
  label: '月窗口',
285
298
  shortLabel: 'Monthly',
286
- usedPct: typeof u.monthly?.percent === 'number' ? u.monthly.percent : null,
287
- remainingPct: typeof u.monthly?.percent === 'number' ? Math.max(0, 100 - u.monthly.percent) : null,
299
+ ...pctPair(u.monthly?.percent),
288
300
  status: u.monthly?.status ?? 'ok',
289
301
  resetAt: u.monthly?.resetsAt ? Date.parse(u.monthly.resetsAt) : null,
290
302
  },
@@ -295,17 +307,19 @@ export function apply(ctx, config = {}) {
295
307
  mode: 'ready',
296
308
  fetchedAt: now,
297
309
  config: { baseUrl, hasKey: true },
298
- monthlyUsedPct: typeof u.monthly?.percent === 'number' ? u.monthly.percent : null,
310
+ monthlyUsedPct: typeof u.monthly?.percent === 'number' ? normalizePct(u.monthly.percent) : null,
299
311
  windows,
300
312
  error: null,
301
313
  }
302
314
  usageCache = { at: now, baseUrl, keyRef, data: result }
315
+ lastSuccessAt = now
303
316
  return result
304
317
  } catch (error) {
305
318
  return {
306
319
  ok: false,
307
320
  mode: 'ready',
308
- fetchedAt: now,
321
+ // 拉取失败不前移「上次同步」:沿用最后一次成功的时间;从未成功过则为 null,界面改说「同步失败」。
322
+ fetchedAt: lastSuccessAt,
309
323
  config: { baseUrl, hasKey: true },
310
324
  windows: [],
311
325
  error: { code: 'GATEWAY_ERROR', message: String(error?.message ?? error) },