dsh-opencode-status 0.3.0 → 0.4.1
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 +35 -0
- package/README.md +25 -10
- package/package.json +1 -1
- package/src/client.js +326 -38
- package/src/index.js +22 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,40 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.1
|
|
4
|
+
|
|
5
|
+
- 新增**按当前消耗速率的可用时长估算**:用量面板的窗口行在「剩余 %」与「⏱ 重置倒计时」之间给出「按现在的用法还能撑多久」。估算用最近的实测采样外推(只用首尾两点,不做回归),三种状态严格区分:
|
|
6
|
+
- `约 13h10m 后耗尽`(警告色):按当前速率会在窗口重置前用完;
|
|
7
|
+
- `可支撑到重置`(中性色):按当前速率能撑到重置,不再显示多余数字;
|
|
8
|
+
- **完全不渲染**:样本不足(少于 3 个采样点,或首尾跨度不足 10 分钟)、速率为 0、剩余为 0、重置时间缺失或已过期时,该位置直接不出现,也不用「估算中」「--」之类占位凑数。
|
|
9
|
+
- 三条诚实性边界(本功能的定位是「仅供参考的描述」,不是预测):
|
|
10
|
+
1. **只基于页面打开期间的采样**:采样存在模块级内存里(每窗口最近 60 分钟、最多 120 个点,按 `fetchedAt` 去重),页面刷新或重启即清空,需要重新积累约 10 分钟才可能再次出现估算;不落盘、不上报、不做跨会话推断。
|
|
11
|
+
2. **整数 percent 下估不出来就不显示**:上游只给整数百分比,最小窗口 10 分钟内 1%→2% 的量化误差会把 ETA 放大成很宽的区间(示例场景真实区间约 8h47m–26h20m,界面只能显示一个点值),所以样本或跨度不足时宁可不出数,也不给一个看起来精确的假时长。行内保留「约」字,`title` 写明「按最近 N 分钟的消耗速率估算(按当前速率),仅供参考」,全文不用「预计 / 将」这类预测口吻。
|
|
12
|
+
3. **先与重置时间比较再下结论**:「可支撑到重置」与「约 X 后耗尽」是对比 `resetAt` 后的二选一(仅当 `etaMs < untilResetMs` 才判耗尽),不是两套独立文案;重置时间缺失或已过期时两者都不给。
|
|
13
|
+
- 重置安全:`usedPct` 回落或 `resetsAt` 变化视为窗口已重置,立即清空该窗口历史样本重新积累,避免算出负数或荒谬时长。
|
|
14
|
+
- 布局与可访问性:估算与「剩余 %」「⏱」同处一行且 `nowrap`,面板行高不变(实测 17px,有没有估算都一样);「剩余 %」、档位徽标、估算、倒计时均 `flexShrink: 0` 不截断,只有窗口标签可收缩为 ellipsis;不改动进度条的 `aria-valuetext`,不新增行。
|
|
15
|
+
- 220ms 悬浮微卡**有意不展示**估算:外宽约 220px,一行塞不下「名称 / 条 / 剩余 / 估算 / 倒计时」五项,缩字号、砍进度条或截断文案都不可接受,因此宁可不显示(估算逻辑与面板共用同一套,只是呈现密度不同)。
|
|
16
|
+
- 纯前端实现:无新增依赖、无新增网络请求与端点,数据仍只来自既有的 30 秒轮询与手动刷新。
|
|
17
|
+
- 测试:42 → 47,新增 5 个真实运行时用例(估算 null 场景、时长文案短于/长于重置、采样去重/回落/`resetsAt` 清空、120 上限与 60 分钟裁剪、三态渲染与布局 props);既有用例全部保留,唯一断言调整是把 F2 静态用例收紧为「采样先于落库」的结构断言。
|
|
18
|
+
- 版本号升至 `0.4.1`(`0.4.0` 的可访问性与信息设计改动见下一条)。
|
|
19
|
+
|
|
20
|
+
## 0.4.0
|
|
21
|
+
|
|
22
|
+
- 可访问性与键盘:用量面板从无语义裸容器改为 `role="dialog"`,`aria-label` 随视图变化(「OpenCode GO 用量」/「OpenCode GO 连接配置」);`Esc` 关闭面板,`Tab` 在面板内首尾循环;打开时焦点移入面板(容器 `tabIndex: -1`),关闭(含 Esc)后焦点归还打开前的触发按钮,点击面板外关闭时不抢焦点(焦点留在用户新点的控件上)。面板允许点击外部关闭、属非模态,因此**不声明** `aria-modal`(WAI-ARIA 要求 `aria-modal=true` 时外部内容不可交互,而本面板没有 inert 实现,声明反而误导读屏)。
|
|
23
|
+
- 进度条语义化:每个窗口轨道改为 `role="progressbar"`,带 `aria-valuemin=0` / `aria-valuemax=100` / `aria-valuenow`(取整后的剩余额度)与 `aria-valuetext`(「剩余 X%,已用 Y%,档位」);数据不可用时只给 `aria-valuetext="数据不可用"`,不输出 `aria-valuenow`。
|
|
24
|
+
- 告警不再只靠颜色:剩余 ≤20% 追加 `⚠ 即将耗尽`、≤50% 追加 `⚠ 偏低` 的文字徽标,并并入 `aria-valuetext`;颜色阈值与颜色逻辑一字未改,色觉障碍用户与灰度截图同样能读出档位。
|
|
25
|
+
- 信息去重与层级:
|
|
26
|
+
- 窗口行主百分比只显示剩余额度,进度条条长与主百分比同源(条长 = 剩余占比,条色 = 剩余档位),「已用」降级到 `title` 与 `aria-valuetext`,同一行不再并列「已用 X% / 剩余 Y%」表达同一个数字。
|
|
27
|
+
- 头部去掉与标题行重复的 host;「月剩余 N%」改为判断性摘要「最紧张 <窗口> N%」(取剩余最小的窗口),具体数字只保留在窗口行。
|
|
28
|
+
- 免责说明(上游 `/v1/usage` 只提供百分比、界面不展示金额余额)移出用量视图正文,落到设置视图底部,用量视图只保留结论。
|
|
29
|
+
- 相对时间:底部操作条与悬浮卡的上次同步改为相对时间(刚刚 / 12s 前 / 3 分钟前 / …),绝对时刻(HH:MM:SS)保留在 `title`;同步数据超过 2 分钟追加「· 可能已过期」并用警告色,避免把旧额度当实时值。
|
|
30
|
+
- 倒计时图标:窗口行与悬浮卡的倒计时由 `↻` 改为 `⏱`,与刷新动作的 `↻` 区分,两个语义不再共用一个图标。
|
|
31
|
+
- 宽度自适应:面板宽度改为 `width: min(360px, calc(100vw - 24px))` + `maxWidth: calc(100vw - 24px)` + `boxSizing: border-box`;窄视口(<372px)不再右侧溢出,宽视口仍固定 360px。
|
|
32
|
+
- 数值规整:宿主对三个窗口与月度百分比的 used/remaining 统一取整并双侧钳制到 0–100,且由取整后的 used 反推 remaining,保证两者恒和 100(12.5 → 13/87,旧实现为 13/88);上游拉取失败时不再前移「上次同步」,失败不会伪装成新鲜数据。
|
|
33
|
+
- 轮询策略:仍为 30 秒自动刷新;页面不可见(`document.hidden`)时暂停轮询,元素重新可见时立即补拉一次,避免后台空转和回到前台看到陈旧值;手动刷新仍是唯一绕过服务端 30 秒缓存的入口。
|
|
34
|
+
- 动效收敛:状态灯呼吸动画由无限循环改为进场一次(`ocPulse 1.2s ease-out 1 both`)并绑定 `fetchedAt`,只在数据真正更新时触发;`prefers-reduced-motion: reduce` 下禁用动画。
|
|
35
|
+
- 测试:用例从 36 增至 42,新增 dialog/`aria-label`/无 `aria-modal`、progressbar 数值语义、非颜色档位标记、免责说明位置、最紧张摘要、相对时间与过期提示、百分比规整(含 12.5 边界)等断言;原有用例(含安全、配置、竞态回归)全部保留,未削弱。
|
|
36
|
+
- 版本号升至 `0.4.0`;README 的功能特性与交互说明同步更新。`0.3.0` 已于 2026-11-08 单独发布,其改动不在本版本内重复。
|
|
37
|
+
|
|
3
38
|
## 0.3.0
|
|
4
39
|
|
|
5
40
|
- 重构点击交互:侧栏常驻按钮改为打开用量面板(默认用量视图),不再直接弹出连接配置表单;参考 dsh-cpa-status 的双视图范式。
|
package/README.md
CHANGED
|
@@ -8,21 +8,36 @@ OpenCode GO 套餐用量与配额状态监控面板插件(DeepSeek Harness)
|
|
|
8
8
|
- **固定底部操作条**:
|
|
9
9
|
- `↻ 刷新`:通过 `POST /api/opencode-status/sync` 绕过 30 秒缓存,强制重新拉取当前剩余额度;刷新期间按钮禁用并显示旋转与「刷新中…」,完成后面板与侧栏数值同步更新,失败时在面板内显示错误文案而不是静默。
|
|
10
10
|
- `⚙ 设置`:进入面板内的独立连接设置视图,可随时 `← 返回用量`。
|
|
11
|
-
-
|
|
12
|
-
- **3
|
|
13
|
-
- **滚动窗口 (5h)
|
|
14
|
-
- **周窗口 (Weekly)
|
|
15
|
-
- **月窗口 (Monthly)
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
11
|
+
- 右侧显示相对时间「上次同步 12s 前」(刚刚 / Ns 前 / N 分钟前 / N 小时前 / N 天前),绝对时刻 HH:MM:SS 保留在 `title`;同步数据超过 2 分钟追加「· 可能已过期」并用警告色,避免把旧额度当成实时值。
|
|
12
|
+
- **3 维度用量行**:主百分比只给剩余额度,进度条条长与它同源(条长 = 剩余占比,条色 = 剩余档位),「已用」放在 `title` 与 `aria-valuetext` 里,同一行不再重复表达同一个数字;窗口状态非 `ok` 时给出可见提示。
|
|
13
|
+
- **滚动窗口 (5h)**:`剩余 70% · 约 13h10m 后耗尽 · ⏱ 4h20m`
|
|
14
|
+
- **周窗口 (Weekly)**:周额度剩余 % + 可用时长估算 + ⏱ 重置倒计时
|
|
15
|
+
- **月窗口 (Monthly)**:月额度剩余 % + 可用时长估算 + ⏱ 重置倒计时
|
|
16
|
+
- 面板头部只给判断性摘要「最紧张 <窗口> N%」(取剩余最小的窗口),具体数字留在窗口行。
|
|
17
|
+
- **可用时长估算(按当前速率,仅供参考)**:窗口行会顺带告诉你「按现在的用法还能撑多久」。三种状态严格区分,不存在第四种:
|
|
18
|
+
- `约 13h10m 后耗尽`(警告色):按当前速率会在窗口重置前用完;
|
|
19
|
+
- `可支撑到重置`(中性色):按当前速率能撑到重置,此时不再显示具体时长;
|
|
20
|
+
- **不显示**:采样点少于 3 个、首尾跨度不足 10 分钟、速率为 0、剩余为 0,或重置时间缺失/已过期时,这个位置直接不出现,也不会用「估算中」「--」占位。
|
|
21
|
+
- 鼠标悬停会说明依据:「按最近 N 分钟的消耗速率估算(按当前速率),仅供参考」。它是对已有采样点的机械外推(只用首尾两点,不做回归),**不是预测或承诺**。
|
|
22
|
+
- 采样只存在于页面打开期间的内存里(每窗口最近 60 分钟、最多 120 个点),刷新页面即清空,需要重新积累约 10 分钟才可能再次出现;上游只给整数百分比,样本不足时宁可不出数,也不给看起来精确的假时长。
|
|
23
|
+
- 纯前端计算:不新增网络请求、不新增依赖,数据仍只来自既有的 30 秒轮询与手动刷新。220ms 悬浮微卡不显示估算(一行放不下五项,缩字号或截断都不可接受,因此有意省略)。
|
|
24
|
+
- **可访问性与键盘交互**:
|
|
25
|
+
- 面板是 `role="dialog"`,`aria-label` 随视图切换(「OpenCode GO 用量」/「OpenCode GO 连接配置」)。
|
|
26
|
+
- `Esc` 关闭面板;`Tab` 在面板内首尾循环;打开时焦点移入面板,关闭(含 Esc)后归还到打开前的触发按钮,点击面板外关闭时不抢焦点。
|
|
27
|
+
- 面板允许点击外部关闭,属非模态对话框,因此**不声明** `aria-modal`。
|
|
28
|
+
- 每个窗口的进度条是 `role="progressbar"`,带 `aria-valuemin` / `aria-valuemax` / `aria-valuenow`(取整剩余额度)与 `aria-valuetext`(「剩余 X%,已用 Y%,档位」);数据不可用时只报「数据不可用」,不给数值。
|
|
29
|
+
- 低额度除颜色外还有文字徽标(`⚠ 即将耗尽` ≤20%、`⚠ 偏低` ≤50%),色觉障碍与灰度截图也能读出档位。
|
|
30
|
+
- 面板宽度为 `min(360px, calc(100vw - 24px))`,窄窗口(<372px)不再右侧溢出。
|
|
31
|
+
- **连接设置视图**:未配置(`mode === 'needs_config'`)时面板直接显示设置视图;保存成功后自动回到用量视图;「取消」丢弃未保存的编辑并关闭面板。密钥仅存入宿主凭据库(`OPENCODE_GO_API_KEY`),API 响应不回传明文。数据口径说明(上游只提供百分比、界面不展示金额余额)放在此视图底部,不占用用量视图。
|
|
32
|
+
- **220ms 悬浮微卡**:鼠标悬停常驻按钮 220ms 后在面板关闭且连接正常时出现,展示标题 + GO 标识 + 最近同步时间(相对时间)、三个窗口的紧凑行(名称 / 剩余 % / ⏱ 重置倒计时 / 细进度条)与底部「点击查看详情」;纯展示卡片,不拦截按钮点击。
|
|
33
|
+
- **缓存与刷新**:服务端 30 秒缓存 + 客户端 30 秒自动刷新;页面不可见时暂停轮询,元素重新可见时立即补拉一次;打开面板、切换视图不会额外探测上游,手动刷新是唯一绕过缓存的入口。
|
|
34
|
+
- **额度语义**:上游 `/v1/usage` 只提供 rolling/weekly/monthly 百分比,没有 USD 余额接口([anomalyco/opencode#10448](https://github.com/anomalyco/opencode/issues/10448) 仍 open),因此界面只展示「剩余额度 / 可用百分比」,不编造金额余额;百分比由宿主统一取整并钳制到 0–100,剩余与已用恒和 100。
|
|
20
35
|
|
|
21
36
|
## 安装与更新
|
|
22
37
|
|
|
23
38
|
### 兼容性(DSH 0.2.x)
|
|
24
39
|
|
|
25
|
-
- 本版本(`0.
|
|
40
|
+
- 本版本(`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
41
|
- 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
42
|
- 升级方式:先把 DSH 升级到 0.2.x,再执行下面的安装命令(默认拉取 `@latest`),然后重启 `dsh web`。Base URL 会以插件配置写入当前 profile 的 `cordis.patch.yml`,API Key 仍保存在宿主凭据库,无需迁移。
|
|
28
43
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-opencode-status",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
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
|
-
|
|
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,162 @@ 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
|
+
|
|
173
|
+
// ---------- 消耗速率估算(按当前速率还能撑多久) ----------
|
|
174
|
+
// 采样放模块级而不是 store:每次采样不触发整树重渲染,渲染时按需读取。
|
|
175
|
+
const ETA_SAMPLE_WINDOW_MS = 60 * 60_000
|
|
176
|
+
const ETA_MAX_SAMPLES = 120
|
|
177
|
+
const ETA_MIN_SAMPLES = 3
|
|
178
|
+
const ETA_MIN_SPAN_MS = 10 * 60_000
|
|
179
|
+
|
|
180
|
+
/** windowId -> { resetAt, samples: [{ at, used }] };at 取 status.fetchedAt(不是 Date.now)。 */
|
|
181
|
+
const etaSamples = new Map()
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 记录一次成功刷新的样本:按窗口分组,用 fetchedAt 去重(宿主 30s 缓存会让多次轮询拿到同一个时间),
|
|
185
|
+
* usedPct 回落或 resetsAt 变化说明窗口已重置,立即清空该窗口历史重新采样,避免算出负数或荒谬 ETA。
|
|
186
|
+
*/
|
|
187
|
+
function recordSamples(status) {
|
|
188
|
+
if (!status?.ok || typeof status.fetchedAt !== 'number') return
|
|
189
|
+
const windows = Array.isArray(status.windows) ? status.windows : []
|
|
190
|
+
for (const w of windows) {
|
|
191
|
+
const id = w?.id
|
|
192
|
+
if (!id || typeof w?.usedPct !== 'number') continue
|
|
193
|
+
const at = status.fetchedAt
|
|
194
|
+
const used = w.usedPct
|
|
195
|
+
const resetAt = typeof w.resetAt === 'number' && Number.isFinite(w.resetAt) ? w.resetAt : null
|
|
196
|
+
let entry = etaSamples.get(id)
|
|
197
|
+
if (!entry) {
|
|
198
|
+
entry = { resetAt, samples: [] }
|
|
199
|
+
etaSamples.set(id, entry)
|
|
200
|
+
}
|
|
201
|
+
const last = entry.samples[entry.samples.length - 1]
|
|
202
|
+
if (last && last.at === at) continue // 同一份缓存数据不重复采样
|
|
203
|
+
if (last && (used < last.used || resetAt !== entry.resetAt)) entry.samples = []
|
|
204
|
+
entry.resetAt = resetAt
|
|
205
|
+
entry.samples.push({ at, used })
|
|
206
|
+
// 只保留最近 60 分钟、每窗口最多 120 个样本。
|
|
207
|
+
const cutoff = at - ETA_SAMPLE_WINDOW_MS
|
|
208
|
+
while (entry.samples.length && entry.samples[0].at < cutoff) entry.samples.shift()
|
|
209
|
+
if (entry.samples.length > ETA_MAX_SAMPLES) entry.samples.splice(0, entry.samples.length - ETA_MAX_SAMPLES)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 估算「按当前速率还能撑多久」。样本 ≥3、首尾跨度 ≥10 分钟、速率 >0 三者缺一即返回 null;
|
|
215
|
+
* 速率只用首尾两点(不做回归,抗噪且好解释)。resetAt 缺失或已过期时无法判断能否撑到重置,同样返回 null。
|
|
216
|
+
* 返回 { etaMs, untilResetMs, exhaustsBeforeReset, spanMs }:能否撑到重置由调用方决定怎么展示。
|
|
217
|
+
*/
|
|
218
|
+
function estimateEta(samples, remainingPct, resetAt, now = Date.now()) {
|
|
219
|
+
if (!Array.isArray(samples) || samples.length < ETA_MIN_SAMPLES) return null
|
|
220
|
+
if (typeof remainingPct !== 'number' || !Number.isFinite(remainingPct) || remainingPct <= 0) return null
|
|
221
|
+
if (typeof resetAt !== 'number' || !Number.isFinite(resetAt)) return null
|
|
222
|
+
const first = samples[0]
|
|
223
|
+
const last = samples[samples.length - 1]
|
|
224
|
+
if (typeof first?.at !== 'number' || typeof last?.at !== 'number') return null
|
|
225
|
+
if (typeof first?.used !== 'number' || typeof last?.used !== 'number') return null
|
|
226
|
+
const spanMs = last.at - first.at
|
|
227
|
+
if (!(spanMs >= ETA_MIN_SPAN_MS)) return null
|
|
228
|
+
const ratePerMs = (last.used - first.used) / spanMs
|
|
229
|
+
if (!(ratePerMs > 0)) return null
|
|
230
|
+
const etaMs = remainingPct / ratePerMs
|
|
231
|
+
if (!Number.isFinite(etaMs) || etaMs <= 0) return null
|
|
232
|
+
const untilResetMs = resetAt - now
|
|
233
|
+
if (!Number.isFinite(untilResetMs) || untilResetMs <= 0) return null
|
|
234
|
+
return { etaMs, untilResetMs, exhaustsBeforeReset: etaMs < untilResetMs, spanMs }
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** 时长短文案:<1h 用分钟,<24h 用 h+m,更长用 d+h(「还能撑多久」不需要精确到分秒)。 */
|
|
238
|
+
function fmtEtaDuration(ms) {
|
|
239
|
+
const mins = Math.max(1, Math.round(ms / 60_000))
|
|
240
|
+
if (mins < 60) return `${mins}m`
|
|
241
|
+
const hours = Math.floor(mins / 60)
|
|
242
|
+
if (hours < 24) return `${hours}h${mins % 60 ? `${mins % 60}m` : ''}`
|
|
243
|
+
const days = Math.floor(hours / 24)
|
|
244
|
+
return `${days}d${hours % 24 ? `${hours % 24}h` : ''}`
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* 估算文案的三态:不可估算返回 null(调用方完全不渲染节点,不显示 "--"/"估算中" 之类占位);
|
|
249
|
+
* 撑不到重置用告警色「约 X 后耗尽」,撑得到用中性色「可支撑到重置」。
|
|
250
|
+
* 文案只用「按当前速率」的描述,不用「预计/将」这种预测口吻。
|
|
251
|
+
* 行内必须保留「约」与「后」:这是常驻可见的唯一表述(悬浮卡等场景 title 不可达),
|
|
252
|
+
* 缺了「约」会被读成确定性断言,与「仅供参考」的定位冲突。
|
|
253
|
+
* compact(悬浮微卡,外宽约 220px)整段不展示:一行放不下「名称/条/剩余/估算/倒计时」五项,
|
|
254
|
+
* 缩字号、砍进度条/倒计时、截断估算都不可接受,所以宁可不显示;估算逻辑仍共用 estimateEta,只是呈现密度不同。
|
|
255
|
+
* 这是有意为之,不是漏渲染。
|
|
256
|
+
*/
|
|
257
|
+
function etaView(w, options = {}) {
|
|
258
|
+
if (options?.compact) return null
|
|
259
|
+
const entry = etaSamples.get(w?.id)
|
|
260
|
+
if (!entry) return null
|
|
261
|
+
const estimate = estimateEta(entry.samples, w?.remainingPct, w?.resetAt)
|
|
262
|
+
if (!estimate) return null
|
|
263
|
+
const minutes = Math.max(1, Math.round(estimate.spanMs / 60_000))
|
|
264
|
+
// 文案只说「按最近 N 分钟的消耗速率(按当前速率)」的实测依据,不写「预计/将」这类预测口吻。
|
|
265
|
+
const title = `按最近 ${minutes} 分钟的消耗速率估算(按当前速率),仅供参考`
|
|
266
|
+
// 保留完整字面「约 X 后耗尽」:真实 Chrome 实测在 326px/262px 内容宽下都不会截断,只会让标签多收缩。
|
|
267
|
+
return estimate.exhaustsBeforeReset
|
|
268
|
+
? { text: `约 ${fmtEtaDuration(estimate.etaMs)} 后耗尽`, color: T.warn, title }
|
|
269
|
+
: { text: '可支撑到重置', color: T.secondary, title }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 仅供测试与诊断:读取某个窗口的采样副本。 */
|
|
273
|
+
function getSamples(windowId) {
|
|
274
|
+
const entry = etaSamples.get(windowId)
|
|
275
|
+
return entry ? entry.samples.map((s) => ({ ...s })) : []
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** 仅供测试与诊断:清空所有采样。 */
|
|
279
|
+
function resetEtaSamples() {
|
|
280
|
+
etaSamples.clear()
|
|
281
|
+
}
|
|
282
|
+
|
|
127
283
|
/** 月窗口剩余百分比;上游只给百分比,不存在金额余额。 */
|
|
128
284
|
function monthlyRemainingOf(status) {
|
|
129
285
|
if (!status) return null
|
|
@@ -190,7 +346,10 @@ window.__ModuleLoader__.load({
|
|
|
190
346
|
try {
|
|
191
347
|
const status = await api('/api/opencode-status')
|
|
192
348
|
// 只接受最新 epoch 的响应:手动刷新之后返回的在途 GET 一律丢弃。
|
|
193
|
-
if (epoch === statusEpoch)
|
|
349
|
+
if (epoch === statusEpoch) {
|
|
350
|
+
recordSamples(status)
|
|
351
|
+
store.set({ status, error: null })
|
|
352
|
+
}
|
|
194
353
|
} catch (err) {
|
|
195
354
|
if (epoch === statusEpoch) store.set({ error: String(err?.message ?? err) })
|
|
196
355
|
} finally {
|
|
@@ -219,6 +378,7 @@ window.__ModuleLoader__.load({
|
|
|
219
378
|
headers: { 'content-type': 'application/json' },
|
|
220
379
|
})
|
|
221
380
|
// 手动刷新自身的响应始终落库(刷新期间已阻止新的 GET)。
|
|
381
|
+
recordSamples(status)
|
|
222
382
|
store.set({ status, error: null })
|
|
223
383
|
} catch (err) {
|
|
224
384
|
store.set({ error: String(err?.message ?? err) })
|
|
@@ -256,8 +416,22 @@ window.__ModuleLoader__.load({
|
|
|
256
416
|
|
|
257
417
|
useEffect(() => {
|
|
258
418
|
refreshStatus()
|
|
259
|
-
|
|
260
|
-
|
|
419
|
+
// 30 秒 GET 自动刷新;页面隐藏时暂停轮询,恢复可见时立即补拉一次,避免后台空转探测上游。
|
|
420
|
+
let timer = setInterval(() => refreshStatus(), 30_000)
|
|
421
|
+
const onVisibilityChange = () => {
|
|
422
|
+
clearInterval(timer)
|
|
423
|
+
timer = null
|
|
424
|
+
if (typeof document !== 'undefined' && document.hidden) return
|
|
425
|
+
refreshStatus()
|
|
426
|
+
timer = setInterval(() => refreshStatus(), 30_000)
|
|
427
|
+
}
|
|
428
|
+
// 测试与 SSR 沙箱里 document 可能没有事件接口,先探测再注册。
|
|
429
|
+
const canListen = typeof document !== 'undefined' && typeof document.addEventListener === 'function'
|
|
430
|
+
if (canListen) document.addEventListener('visibilitychange', onVisibilityChange)
|
|
431
|
+
return () => {
|
|
432
|
+
if (timer !== null) clearInterval(timer)
|
|
433
|
+
if (canListen) document.removeEventListener('visibilitychange', onVisibilityChange)
|
|
434
|
+
}
|
|
261
435
|
}, [])
|
|
262
436
|
|
|
263
437
|
const onMouseEnter = () => {
|
|
@@ -375,7 +549,12 @@ window.__ModuleLoader__.load({
|
|
|
375
549
|
},
|
|
376
550
|
onClick: toggleOverlay,
|
|
377
551
|
},
|
|
378
|
-
h('span', {
|
|
552
|
+
h('span', {
|
|
553
|
+
// 呼吸动画只播一次:key 绑定 fetchedAt,新数据到达时换新节点重播一次,而不是无限循环。
|
|
554
|
+
key: color === T.ok ? `live-${st?.fetchedAt ?? 0}` : 'live',
|
|
555
|
+
className: color === T.ok ? 'oc-dot-live' : undefined,
|
|
556
|
+
style: dotStyle(color),
|
|
557
|
+
}),
|
|
379
558
|
labelEl,
|
|
380
559
|
)
|
|
381
560
|
|
|
@@ -402,6 +581,8 @@ window.__ModuleLoader__.load({
|
|
|
402
581
|
'div',
|
|
403
582
|
{
|
|
404
583
|
className: 'oc-panel-enter oc-hover-card',
|
|
584
|
+
// 只读微卡是面板的视觉重复,对读屏隐藏,避免同一份数据播报两遍。
|
|
585
|
+
'aria-hidden': true,
|
|
405
586
|
style: {
|
|
406
587
|
position: 'absolute',
|
|
407
588
|
left: 0,
|
|
@@ -443,8 +624,13 @@ window.__ModuleLoader__.load({
|
|
|
443
624
|
),
|
|
444
625
|
h(
|
|
445
626
|
'span',
|
|
446
|
-
{
|
|
447
|
-
|
|
627
|
+
{
|
|
628
|
+
key: 'at',
|
|
629
|
+
// 相对时间更易读;绝对时刻保留在 title 里,需要精确对时再悬停查看。
|
|
630
|
+
title: st?.fetchedAt ? `上次同步 ${fmtClock(st.fetchedAt)}` : '尚未同步',
|
|
631
|
+
style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums', flexShrink: 0 },
|
|
632
|
+
},
|
|
633
|
+
st?.fetchedAt ? `上次同步 ${fmtRelative(st.fetchedAt)}` : '尚未同步',
|
|
448
634
|
),
|
|
449
635
|
]),
|
|
450
636
|
h(
|
|
@@ -461,11 +647,14 @@ window.__ModuleLoader__.load({
|
|
|
461
647
|
)
|
|
462
648
|
}
|
|
463
649
|
|
|
464
|
-
/** 悬浮卡紧凑行:名称 / 剩余 % /
|
|
650
|
+
/** 悬浮卡紧凑行:名称 / 剩余 % / ⏱ 重置倒计时 / 细进度条(紧凑视图不展示估算)。 */
|
|
465
651
|
function MiniQuotaRow(props) {
|
|
466
652
|
const w = props.window
|
|
467
653
|
const remaining = w?.remainingPct ?? null
|
|
468
654
|
const color = remainingColor(remaining)
|
|
655
|
+
// compact:悬浮微卡外宽约 220px,五个元素塞不进去。这里整段不渲染估算(etaView 返回 null),
|
|
656
|
+
// 不缩字号、不砍进度条/倒计时、不截断成残句;面板 QuotaRow 仍照常展示。
|
|
657
|
+
const eta = etaView(w, { compact: true })
|
|
469
658
|
return h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
|
|
470
659
|
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
660
|
h(
|
|
@@ -475,8 +664,13 @@ window.__ModuleLoader__.load({
|
|
|
475
664
|
? null
|
|
476
665
|
: h('div', { style: { height: '100%', width: `${clampPct(remaining)}%`, background: color, borderRadius: 2 } }),
|
|
477
666
|
),
|
|
478
|
-
h('span', { key: 'v', style: { minWidth: 30, textAlign: 'right', fontSize: 10, fontWeight: 600, color, fontVariantNumeric: 'tabular-nums' } }, remaining === null ? '—' :
|
|
479
|
-
|
|
667
|
+
h('span', { key: 'v', style: { minWidth: 30, flexShrink: 0, textAlign: 'right', fontSize: 10, fontWeight: 600, color, fontVariantNumeric: 'tabular-nums' } }, remaining === null ? '—' : pctText(remaining)),
|
|
668
|
+
// 紧凑视图不会走到这里(etaView(compact) 恒为 null);保留非截断样式,避免以后误开时变成残句。
|
|
669
|
+
eta
|
|
670
|
+
? h('span', { key: 'e', title: eta.title, style: { flexShrink: 0, fontSize: 10, color: eta.color, whiteSpace: 'nowrap' } }, eta.text)
|
|
671
|
+
: null,
|
|
672
|
+
// 倒计时用 ⏱ 区分刷新动作的 ↻,避免两个图标同义混淆。
|
|
673
|
+
h('span', { key: 'r', style: { minWidth: 34, flexShrink: 0, textAlign: 'right', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } }, w?.resetAt ? `⏱ ${timeUntil(w.resetAt)}` : ''),
|
|
480
674
|
])
|
|
481
675
|
}
|
|
482
676
|
|
|
@@ -490,19 +684,23 @@ window.__ModuleLoader__.load({
|
|
|
490
684
|
}
|
|
491
685
|
|
|
492
686
|
const windows = Array.isArray(st.windows) ? st.windows : []
|
|
493
|
-
|
|
494
|
-
const
|
|
687
|
+
// 头部只给判断性摘要(最紧张窗口),具体数字留给下方窗口行,避免同一数字说两遍。
|
|
688
|
+
const tightest = tightestWindow(st)
|
|
495
689
|
|
|
496
690
|
return h('div', null, [
|
|
497
691
|
h('div', { key: 'sum', style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
|
|
498
692
|
h('span', { key: 'd', style: dotStyle(st.ok ? T.ok : T.err) }),
|
|
499
693
|
h('span', { key: 't', style: { fontSize: 12, fontWeight: 600, color: T.label } }, st.ok ? 'OpenCode GO 已连接' : 'OpenCode GO 异常'),
|
|
500
|
-
|
|
501
|
-
monthlyRemaining !== null
|
|
694
|
+
tightest
|
|
502
695
|
? h(
|
|
503
696
|
'span',
|
|
504
|
-
{
|
|
505
|
-
|
|
697
|
+
{
|
|
698
|
+
key: 'm',
|
|
699
|
+
// host 只在面板标题行展示一次;这里不再重复。
|
|
700
|
+
title: `最紧张窗口:${tightest.label ?? tightest.id ?? '—'},剩余 ${pctText(tightest.remainingPct)}`,
|
|
701
|
+
style: { marginLeft: 'auto', fontSize: 11, fontWeight: 600, color: remainingColor(tightest.remainingPct), fontVariantNumeric: 'tabular-nums', flexShrink: 0 },
|
|
702
|
+
},
|
|
703
|
+
`最紧张 ${tightest.shortLabel ?? tightest.label ?? '—'} ${pctText(tightest.remainingPct)}`,
|
|
506
704
|
)
|
|
507
705
|
: null,
|
|
508
706
|
].filter(Boolean)),
|
|
@@ -518,32 +716,54 @@ window.__ModuleLoader__.load({
|
|
|
518
716
|
st.ok && !windows.length
|
|
519
717
|
? h('div', { key: 'empty', style: { fontSize: 11, color: T.secondary, marginTop: 10 } }, '暂无用量窗口数据')
|
|
520
718
|
: null,
|
|
521
|
-
h(
|
|
522
|
-
'div',
|
|
523
|
-
{ key: 'note', style: { fontSize: 10, color: T.secondary, marginTop: 6, lineHeight: '15px' } },
|
|
524
|
-
'上游 /v1/usage 仅提供百分比额度,界面不展示金额余额。',
|
|
525
|
-
),
|
|
526
719
|
].filter(Boolean))
|
|
527
720
|
}
|
|
528
721
|
|
|
529
|
-
/**
|
|
722
|
+
/**
|
|
723
|
+
* 面板窗口行:主百分比只显示剩余额度(进度条填充同源),「已用」降级到 aria-valuetext 与 title。
|
|
724
|
+
* 语义约定:条长 = 剩余额度占比,条色 = 剩余额度档位;不再同一行并列「已用 X% / 剩余 Y%」重复表达。
|
|
725
|
+
*/
|
|
530
726
|
function QuotaRow(props) {
|
|
531
727
|
const w = props.window
|
|
532
728
|
const used = w?.usedPct ?? null
|
|
533
729
|
const remaining = w?.remainingPct ?? null
|
|
534
730
|
const color = remainingColor(remaining)
|
|
731
|
+
const band = remainingBand(remaining)
|
|
732
|
+
const eta = etaView(w)
|
|
535
733
|
const statusText = w?.status && w.status !== 'ok' ? w.status : null
|
|
734
|
+
const detail = remaining === null ? '数据不可用' : `已用 ${pctText(used)} · 剩余 ${pctText(remaining)}`
|
|
536
735
|
return h('div', { style: { marginBottom: 12 } }, [
|
|
537
736
|
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: '
|
|
540
|
-
|
|
541
|
-
|
|
737
|
+
h('span', { key: 'l', style: { color: T.label, fontWeight: 500, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, w?.label ?? '—'),
|
|
738
|
+
h('span', { key: 'r', title: detail, style: { marginLeft: 'auto', color, fontWeight: 600, flexShrink: 0 } }, remaining === null ? '剩余 —' : `剩余 ${pctText(remaining)}`),
|
|
739
|
+
// 估算整段展示、不截断:flexShrink:0 且无 ellipsis;空间不足时只让窗口标签 ellipsis,
|
|
740
|
+
// 档位徽标(告警不只靠颜色)、剩余 % 与倒计时都不收缩。
|
|
741
|
+
eta
|
|
742
|
+
? h('span', { key: 'eta', title: eta.title, style: { flexShrink: 0, fontSize: 10, color: eta.color, whiteSpace: 'nowrap' } }, eta.text)
|
|
743
|
+
: null,
|
|
744
|
+
// 低额度除颜色外再给文字标记:色觉障碍与灰度截图里也能看出档位。
|
|
745
|
+
band
|
|
746
|
+
? h(
|
|
747
|
+
'span',
|
|
748
|
+
{ key: 'band', style: { color, flexShrink: 0, fontSize: 10, lineHeight: '14px', padding: '0 4px', borderRadius: 4, border: `1px solid ${color}` } },
|
|
749
|
+
`⚠ ${band}`,
|
|
750
|
+
)
|
|
751
|
+
: null,
|
|
752
|
+
// 倒计时用 ⏱ 区分刷新动作的 ↻,避免两个图标同义混淆。
|
|
753
|
+
w?.resetAt ? h('span', { key: 't', style: { color: T.secondary, flexShrink: 0 } }, `⏱ ${timeUntil(w.resetAt)}`) : null,
|
|
542
754
|
].filter(Boolean)),
|
|
543
755
|
h(
|
|
544
756
|
'div',
|
|
545
757
|
{
|
|
546
758
|
key: 'track',
|
|
759
|
+
// 进度条语义:aria-valuenow 取剩余额度,与条长、右侧主百分比同源。
|
|
760
|
+
role: 'progressbar',
|
|
761
|
+
'aria-label': `${w?.label ?? '用量窗口'}剩余额度`,
|
|
762
|
+
'aria-valuemin': 0,
|
|
763
|
+
'aria-valuemax': 100,
|
|
764
|
+
...(remaining === null ? {} : { 'aria-valuenow': Math.round(clampPct(remaining)) }),
|
|
765
|
+
'aria-valuetext': remaining === null ? '数据不可用' : `剩余 ${pctText(remaining)},已用 ${pctText(used)}${band ? `,${band}` : ''}`,
|
|
766
|
+
title: detail,
|
|
547
767
|
style: {
|
|
548
768
|
height: 6,
|
|
549
769
|
borderRadius: 3,
|
|
@@ -662,6 +882,12 @@ window.__ModuleLoader__.load({
|
|
|
662
882
|
? h('button', { className: 'oc-btn', style: { ...btnBase, color: T.err, marginLeft: 'auto' }, disabled: saving, onClick: clearKey }, '清除')
|
|
663
883
|
: null,
|
|
664
884
|
].filter(Boolean)),
|
|
885
|
+
// 数据口径说明放设置视图:用量视图保持只读结论,正文不再常驻免责声明。
|
|
886
|
+
h(
|
|
887
|
+
'div',
|
|
888
|
+
{ key: 'note', style: { fontSize: 10, color: T.secondary, marginTop: 14, lineHeight: '15px' } },
|
|
889
|
+
'上游 /v1/usage 仅提供百分比额度,界面不展示金额余额。',
|
|
890
|
+
),
|
|
665
891
|
])
|
|
666
892
|
}
|
|
667
893
|
|
|
@@ -669,7 +895,17 @@ window.__ModuleLoader__.load({
|
|
|
669
895
|
function OpsBar(props) {
|
|
670
896
|
const state = useStore()
|
|
671
897
|
const st = state.status
|
|
672
|
-
|
|
898
|
+
// 相对时间更好读;绝对时刻保留在 title,同步超过 2 分钟再给弱过期提示。
|
|
899
|
+
const lastSync = st?.fetchedAt ? fmtRelative(st.fetchedAt) : null
|
|
900
|
+
const lastSyncTitle = st?.fetchedAt ? `上次同步 ${fmtClock(st.fetchedAt)}` : '尚未同步'
|
|
901
|
+
const lastSyncStale = Boolean(st?.fetchedAt) && Date.now() - st.fetchedAt > STALE_AFTER_MS
|
|
902
|
+
const syncText = lastSync ? `上次同步 ${lastSync}${lastSyncStale ? ' · 可能已过期' : ''}` : '尚未同步'
|
|
903
|
+
const syncSpan = (key, extraStyle) =>
|
|
904
|
+
h(
|
|
905
|
+
'span',
|
|
906
|
+
{ key, title: lastSyncTitle, style: { ...extraStyle, fontVariantNumeric: 'tabular-nums' } },
|
|
907
|
+
syncText,
|
|
908
|
+
)
|
|
673
909
|
|
|
674
910
|
if (props?.settings) {
|
|
675
911
|
return h('div', { style: barStyle }, [
|
|
@@ -688,11 +924,7 @@ window.__ModuleLoader__.load({
|
|
|
688
924
|
'← 返回用量',
|
|
689
925
|
)
|
|
690
926
|
: null,
|
|
691
|
-
|
|
692
|
-
'span',
|
|
693
|
-
{ style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } },
|
|
694
|
-
lastSync ? `上次同步 ${lastSync}` : '尚未同步',
|
|
695
|
-
),
|
|
927
|
+
syncSpan('at', { marginLeft: 'auto', fontSize: 10, color: T.secondary }),
|
|
696
928
|
].filter(Boolean))
|
|
697
929
|
}
|
|
698
930
|
|
|
@@ -713,11 +945,7 @@ window.__ModuleLoader__.load({
|
|
|
713
945
|
state.refreshing ? '刷新中…' : '刷新',
|
|
714
946
|
),
|
|
715
947
|
h('button', { key: 'set', className: 'oc-btn', style: btnBase, onClick: openSettings, title: '配置 Base URL 与 API Key' }, '⚙ 设置'),
|
|
716
|
-
|
|
717
|
-
'span',
|
|
718
|
-
{ key: 'at', style: { marginLeft: 'auto', fontSize: 10, color: T.secondary, fontVariantNumeric: 'tabular-nums' } },
|
|
719
|
-
lastSync ? `上次同步 ${lastSync}` : '尚未同步',
|
|
720
|
-
),
|
|
948
|
+
syncSpan('at', { marginLeft: 'auto', fontSize: 10, color: lastSyncStale ? T.warn : T.secondary }),
|
|
721
949
|
],
|
|
722
950
|
)
|
|
723
951
|
}
|
|
@@ -761,6 +989,56 @@ window.__ModuleLoader__.load({
|
|
|
761
989
|
return () => window.removeEventListener('mousedown', handleClickOutside)
|
|
762
990
|
}, [state.open])
|
|
763
991
|
|
|
992
|
+
// Esc 关闭:与面板同开同卸载;Tab 焦点保持在面板内,避免键盘用户掉到背后的不可见区域。
|
|
993
|
+
useEffect(() => {
|
|
994
|
+
if (!state.open) return
|
|
995
|
+
const handleKeyDown = (e) => {
|
|
996
|
+
if (e.key === 'Escape') {
|
|
997
|
+
e.stopPropagation()
|
|
998
|
+
closeOverlay()
|
|
999
|
+
return
|
|
1000
|
+
}
|
|
1001
|
+
if (e.key !== 'Tab' || !panelRef.current || typeof panelRef.current.querySelectorAll !== 'function') return
|
|
1002
|
+
const focusables = [...panelRef.current.querySelectorAll(FOCUSABLE)]
|
|
1003
|
+
if (!focusables.length) {
|
|
1004
|
+
e.preventDefault()
|
|
1005
|
+
panelRef.current.focus()
|
|
1006
|
+
return
|
|
1007
|
+
}
|
|
1008
|
+
const first = focusables[0]
|
|
1009
|
+
const last = focusables[focusables.length - 1]
|
|
1010
|
+
if (e.shiftKey && (e.target === first || e.target === panelRef.current)) {
|
|
1011
|
+
e.preventDefault()
|
|
1012
|
+
last.focus()
|
|
1013
|
+
} else if (!e.shiftKey && e.target === last) {
|
|
1014
|
+
e.preventDefault()
|
|
1015
|
+
first.focus()
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
window.addEventListener('keydown', handleKeyDown)
|
|
1019
|
+
return () => window.removeEventListener('keydown', handleKeyDown)
|
|
1020
|
+
}, [state.open])
|
|
1021
|
+
|
|
1022
|
+
// 焦点管理:面板挂载(phase 进入 open)后把焦点移入面板(容器 tabIndex=-1),关闭时归还打开前的触发元素(footer 按钮)。
|
|
1023
|
+
// 依赖必须带上 phase:面板 DOM 要等 phase effect 把 phase 推到 'open' 才挂载,只依赖 state.open 时
|
|
1024
|
+
// 首次执行 panelRef.current 还是 null,panel.focus() 会静默失效(运行时复现由 /tmp/verify-focus.mjs 手工验证,CI 无 jsdom 依赖)。
|
|
1025
|
+
useEffect(() => {
|
|
1026
|
+
if (!state.open || phase !== 'open') return
|
|
1027
|
+
if (typeof document === 'undefined') return
|
|
1028
|
+
const previous = document.activeElement
|
|
1029
|
+
const panel = panelRef.current
|
|
1030
|
+
if (panel && typeof panel.focus === 'function') panel.focus()
|
|
1031
|
+
return () => {
|
|
1032
|
+
if (!previous || typeof previous.focus !== 'function') return
|
|
1033
|
+
// 只把焦点从面板(或已失焦的 body)收回触发按钮:点击外部关闭时不要抢走用户刚点中的控件焦点。
|
|
1034
|
+
// cleanup 里不能用打开时捕获的 panel(闭包可能拿到 null),改用当前 ref。
|
|
1035
|
+
const current = panelRef.current
|
|
1036
|
+
const active = document.activeElement
|
|
1037
|
+
if (active && active !== document.body && typeof current?.contains === 'function' && !current.contains(active)) return
|
|
1038
|
+
previous.focus()
|
|
1039
|
+
}
|
|
1040
|
+
}, [state.open, phase])
|
|
1041
|
+
|
|
764
1042
|
if (phase === 'closed') return null
|
|
765
1043
|
|
|
766
1044
|
const st = state.status
|
|
@@ -772,11 +1050,18 @@ window.__ModuleLoader__.load({
|
|
|
772
1050
|
{
|
|
773
1051
|
ref: panelRef,
|
|
774
1052
|
className: phase === 'closing' ? 'oc-panel-exit' : 'oc-panel-enter',
|
|
1053
|
+
// 非模态对话框:允许点击外部关闭,因此不声明 aria-modal(WAI-ARIA 要求 aria-modal=true 时外部内容不可交互)。
|
|
1054
|
+
role: 'dialog',
|
|
1055
|
+
'aria-label': settingsView ? 'OpenCode GO 连接配置' : 'OpenCode GO 用量',
|
|
1056
|
+
tabIndex: -1,
|
|
775
1057
|
style: {
|
|
776
1058
|
position: 'fixed',
|
|
777
1059
|
left: 12,
|
|
778
1060
|
bottom: 52,
|
|
779
|
-
|
|
1061
|
+
// 窄视口(<384px)不再右侧溢出:宽度随视口收缩,border-box 让 1px 边框不额外撑宽。
|
|
1062
|
+
width: 'min(360px, calc(100vw - 24px))',
|
|
1063
|
+
maxWidth: 'calc(100vw - 24px)',
|
|
1064
|
+
boxSizing: 'border-box',
|
|
780
1065
|
maxHeight: 'calc(100vh - 80px)',
|
|
781
1066
|
overflow: 'hidden',
|
|
782
1067
|
display: 'flex',
|
|
@@ -804,6 +1089,7 @@ window.__ModuleLoader__.load({
|
|
|
804
1089
|
style: { ...btnBase, marginLeft: 'auto', border: 'none', padding: '2px 6px' },
|
|
805
1090
|
onClick: closeOverlay,
|
|
806
1091
|
title: '关闭',
|
|
1092
|
+
'aria-label': '关闭面板',
|
|
807
1093
|
},
|
|
808
1094
|
'✕',
|
|
809
1095
|
),
|
|
@@ -839,6 +1125,8 @@ window.__ModuleLoader__.load({
|
|
|
839
1125
|
|
|
840
1126
|
exports.apply = apply
|
|
841
1127
|
exports.inject = ['slots']
|
|
1128
|
+
// 仅供测试与诊断:估算/采样是纯函数 + 模块内状态,导出以便做真实单元测试(宿主侧不消费)。
|
|
1129
|
+
exports.__internal = { estimateEta, recordSamples, getSamples, resetEtaSamples, fmtEtaDuration, etaView }
|
|
842
1130
|
return module.exports
|
|
843
1131
|
},
|
|
844
1132
|
})
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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) },
|