opencode-usage-limits 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,81 @@
1
+ # Changelog
2
+
3
+ All notable changes to `usage-limits` are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ [简体中文](./CHANGELOG.md) · [English](./CHANGELOG.en.md)
8
+
9
+ ## 0.2.0 - 2026-10-06
10
+
11
+ ### Added
12
+
13
+ - Added the [MIT](./LICENSE) license file.
14
+ - **ClinePass spend display**: reads `inferenceCapThreshold` from `GET /users/me/plan` and shows
15
+ `used / limit` like OpenCode Go. The unit was calibrated against live data: caps and `costUsd`
16
+ share a unit, **1 unit = 1e-8 USD** ($10 / $25 / $50). Caps are cached for 6 hours and a failed
17
+ read never affects the usage reading itself.
18
+ - **Partial-data notice**: shows `partial data · N/3 windows` when fewer windows are returned.
19
+ - **Rate-limit backoff**: 429 / 5xx / network failures back off exponentially (capped at 5 minutes) and
20
+ the error line shows `retry in Ns`; auth and shape errors are not retried. Polling moved from a fixed
21
+ `setInterval` to result-driven `setTimeout` scheduling.
22
+ - **Configurable budgets**: a new `limits` option overrides the built-in budgets
23
+ (e.g. `{ "opencode-go": { "monthly": 100 } }`); it is also the fallback when a ClinePass plan read fails.
24
+ - **Minimal re-render**: the window list moved from `<For>` to `<Index>`, so a usage refresh no longer
25
+ destroys and rebuilds the three rows; the tick moved from every second to **minute boundaries**
26
+ (second-precision only while a retry countdown is on screen); countdown and age text are wrapped in
27
+ `createMemo` so unchanged text is never written to the DOM; the title row's right side is now a
28
+ **fixed-width cell**, removing the layout jitter on each refresh. Update frequency drops from 4 spots
29
+ per second to once a minute.
30
+ - **Freshness only shown when stale**: the title row's right cell stays blank while data is fresh; the
31
+ age (`2m` / `5m`) appears only once the reading is older than 2.5 polling intervals (~75s), in the
32
+ warning colour. The previously always-on `now` label is gone.
33
+
34
+ ### Fixed
35
+
36
+ - **Usage request dropped when switching models**: the in-flight guard is now tracked
37
+ **per provider** instead of a single global boolean. Previously, if a request was still in
38
+ flight, the request for the newly selected provider was skipped and the panel only refreshed on
39
+ the next poll (up to 30 seconds later). It now fires immediately, and the stale response is
40
+ dropped by the provider check so it cannot pollute the panel.
41
+ - **Window status ignored**: each OpenCode Go window carries a `status` field that was previously
42
+ read as a percentage only. A non-`ok` status now forces the danger colour and prints the status
43
+ word, instead of showing a disabled window as healthy.
44
+ - **Missing windows silently dropped**: if one of the three windows was absent the row simply
45
+ disappeared with no warning; incomplete readings are now called out explicitly.
46
+ - **Multiple credentials**: `extractKey` only handled a single credential object, so an `auth.json`
47
+ holding an array (several accounts/connections) resolved to no key at all; it now takes the first
48
+ usable one.
49
+
50
+ ## 0.1.0 - 2026-10-06
51
+
52
+ Initial release.
53
+
54
+ ### Added
55
+
56
+ - Sidebar usage block supporting **OpenCode Go** (`opencode-go`) and **ClinePass** (`cline-pass`).
57
+ - Three rolling windows: **5 hours / weekly / monthly**, with percentage, progress bar and reset countdown.
58
+ - OpenCode Go additionally shows the `used / limit` amount ($12 / $30 / $60).
59
+ - Green / yellow / red usage indication: < 50% green, 50–79% yellow, ≥ 80% red.
60
+ - Collapsible panel: click the title row to collapse to one line, toggle via the command palette
61
+ command **Toggle usage panel**; the state is persisted.
62
+ - The API key is read live from OpenCode's `auth.json`; the plugin stores no credentials.
63
+ - `refreshMs` option (default 30000 ms).
64
+ - Nothing is rendered for other providers, so the sidebar is never taken up needlessly.
65
+ - Offline preview script [`preview.mjs`](./preview.mjs).
66
+
67
+ ### Changed
68
+
69
+ - The sidebar claim now uses `prepend`, placing the block between the cache stats, Context and MCP.
70
+ - The normal state colour moved from the theme's primary colour to the theme's `success` (green),
71
+ giving a consistent semantic green / yellow / red set.
72
+ - The unfilled progress track moved from `background.raised.base` to `border.base`, so it no longer
73
+ blends into the panel background.
74
+ - The reset countdown label is uniformly `↻ ` (a single space after the glyph).
75
+ - Thresholds changed from 70 / 90 to **50 / 80**.
76
+
77
+ ### Notes
78
+
79
+ - The usage endpoints are provider **undocumented** APIs and their fields may change at any time;
80
+ on error the block shows an error line and keeps the last data.
81
+ - The ClinePass endpoint returns percentages only, so no dollar amount is shown.
package/CHANGELOG.md ADDED
@@ -0,0 +1,53 @@
1
+ # 变更日志
2
+
3
+ 本文件记录 `usage-limits` 的版本变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
+
5
+ [简体中文](./CHANGELOG.md) · [English](./CHANGELOG.en.md)
6
+
7
+ ## 0.2.0 - 2026-10-06
8
+
9
+ ### 新增
10
+
11
+ - 补充 [MIT](./LICENSE) 许可文件。
12
+ - **ClinePass 显示金额**:新增读取 `GET /users/me/plan` 的 `inferenceCapThreshold`,与 OpenCode Go 一样显示 `已用 / 限额`。额度单位经实测标定:`cap` 与 `costUsd` 同单位,**1 单位 = 1e-8 USD**(即 $10 / $25 / $50),上限缓存 6 小时,读取失败不影响用量本身。
13
+ - **部分数据提示**:窗口数不足时显示 `partial data · N/3 windows`。
14
+ - **限流退避**:429 / 5xx / 网络失败时指数退避(最长 5 分钟),错误行显示 `retry in Ns`;鉴权与数据形状错误不重试。轮询由固定 `setInterval` 改为按结果调度的 `setTimeout`。
15
+ - **额度可配置**:新增 `limits` 选项可覆盖内置额度(如 `{ "opencode-go": { "monthly": 100 } }`);ClinePass 读不到套餐上限时也会回退到该配置。
16
+ - **渲染更新最小化**:窗口列表由 `<For>` 改为 `<Index>`,用量刷新时不再销毁重建三行组件;tick 由每秒改为**对齐分钟边界**(仅在有重试倒计时时恢复每秒);倒计时与年龄文本用 `createMemo` 包裹,文本未变则不写 DOM;标题行右侧改为**固定宽度单元格**,消除刷新瞬间的布局抖动。更新频率由每秒 4 处降为每分钟 1 次。
17
+ - **新鲜度只在过期时提示**:标题行右侧平时留空,只有数据超过 2.5 个轮询间隔(约 75 秒)时才显示年龄(`2m` / `5m`)并转为警告色;此前恒显的 `now` 已移除,不再制造噪音。
18
+
19
+ ### 修复
20
+
21
+ - **切换模型时用量请求被丢弃**:并发守卫由全局布尔改为**按 provider** 记录在途状态。此前若上一个请求尚未返回,切换到另一 provider 的这次请求会被直接跳过,需等下一个轮询周期(最多 30 秒)才刷新;现在会立即发起,迟到的旧响应由 provider 校验丢弃,不会污染面板。
22
+ - **窗口状态被忽略**:OpenCode Go 的每个窗口带有 `status` 字段,此前只读百分比。现在状态非 `ok` 时该窗口强制显示为红色并标注状态词,不再把已停用的窗口显示成正常。
23
+ - **缺失窗口静默跳过**:此前三个窗口缺哪个就少哪一行且不告警,现在会显式提示数据不完整。
24
+ - **多凭据兼容**:`extractKey` 此前只处理单个凭据对象,若 `auth.json` 以数组存放多个账号/连接,会完全读不到密钥;现在会取第一个可用的密钥。
25
+
26
+ ## 0.1.0 - 2026-10-06
27
+
28
+ 首个版本。
29
+
30
+ ### 新增
31
+
32
+ - 侧边栏用量区块,支持 **OpenCode Go**(`opencode-go`)与 **ClinePass**(`cline-pass`)。
33
+ - 三个滚动窗口:**5 小时 / 周 / 月**,展示百分比、进度条与重置倒计时。
34
+ - OpenCode Go 额外显示 `已用 / 限额` 金额($12 / $30 / $60)。
35
+ - 绿黄红用量提醒:< 50% 绿、50–79% 黄、≥ 80% 红。
36
+ - 整体折叠:点击标题行收起为一行,并通过命令面板 **Toggle usage panel** 切换;状态持久化。
37
+ - 密钥从 OpenCode 的 `auth.json` 实时读取,插件不存储任何凭据。
38
+ - `refreshMs` 配置项(默认 30000 毫秒)。
39
+ - 选中其他 provider 时完全不渲染,不占空间。
40
+ - 离线预览脚本 [`preview.mjs`](./preview.mjs)。
41
+
42
+ ### 变更
43
+
44
+ - 侧边栏插入位置改用 `prepend`,区块排在缓存统计、Context、MCP 之间。
45
+ - 正常态配色由主题主色改为主题 `success`(绿色),与黄 / 红构成统一语义色。
46
+ - 进度条未填充轨道由 `background.raised.base` 改为 `border.base`,避免与面板同色而隐形。
47
+ - 重置倒计时标签统一为 `↻ `(感叹号后保留一个空格)。
48
+ - 阈值由 70 / 90 调整为 **50 / 80**。
49
+
50
+ ### 说明
51
+
52
+ - 用量接口为 provider 的**非公开**接口,字段可能随时变化;接口异常时区块会显示错误行并保留上次数据。
53
+ - ClinePass 接口仅返回百分比,因此不显示金额。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 GamingNowEdward
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,141 @@
1
+ # usage-limits
2
+
3
+ > Show your subscription usage limits (5-hour / weekly / monthly) in the OpenCode sidebar.
4
+
5
+ [简体中文](./README.md) · [English](./README.en.md)
6
+
7
+ An [OpenCode](https://opencode.ai/v2/docs/) **V2 TUI plugin**. When the selected model belongs
8
+ to **OpenCode Go** or **ClinePass**, a usage block appears automatically in the sidebar, showing
9
+ the percentage, a progress bar and the reset countdown for three rolling windows.
10
+
11
+ ```text
12
+ ▾ USAGE · OpenCode Go
13
+ 5 hours 0%
14
+ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
15
+ ↻ 5h $0.00 / $12.00
16
+
17
+ Weekly 1%
18
+ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
19
+ ↻ 6d 4h $0.30 / $30.00
20
+
21
+ Monthly 60%
22
+ ███████████████████░░░░░░░░░░░░░░░░░
23
+ ↻ 7d 14h $36.00 / $60.00
24
+ ```
25
+
26
+ ## Features
27
+
28
+ - **Two usage sources**: OpenCode Go and ClinePass, switched automatically by the current model.
29
+ - **Three windows**: rolling 5 hours / weekly / monthly, with percentage, bar and reset countdown.
30
+ - **Green / yellow / red**: < 50% green, 50–79% yellow, ≥ 80% red (thresholds live in `core.ts`).
31
+ - **Spend display**: OpenCode Go shows `used / limit` ($12 / $30 / $60); ClinePass reads its caps live from `/users/me/plan`.
32
+ - **Collapsible**: click the title row to collapse to a single line; the state is persisted.
33
+ - **Unobtrusive**: nothing is rendered for any other provider, so it never takes up space.
34
+ - **Rate-limit backoff**: 429 / 5xx / network failures back off exponentially (capped at 5 minutes) and show `retry in Ns`.
35
+ - **Stale-data warning**: once a reading is older than ~75 seconds (2.5 polling intervals) the title row
36
+ shows its age in yellow; while the data is fresh nothing is shown, so there is no constant noise.
37
+ - **Key safety**: the API key is read live from OpenCode's `auth.json`; the plugin stores nothing.
38
+
39
+ ## Supported sources
40
+
41
+ | Provider ID | Name | Usage endpoint | Spend shown |
42
+ | --- | --- | --- | --- |
43
+ | `opencode-go` | [OpenCode Go](https://opencode.ai/docs/go) | `GET https://opencode.ai/zen/go/v1/usage` | Yes ($12 / $30 / $60) |
44
+ | `cline-pass` | [ClinePass](https://docs.cline.bot/getting-started/clinepass) | `GET https://api.cline.bot/api/v1/users/me/plan/usage-limits` | Yes (plan caps read live from `/users/me/plan`) |
45
+
46
+ > Cline's public documentation is at [Cline API](https://docs.cline.bot/api/overview).
47
+
48
+ ## Install
49
+
50
+ **From npm (recommended)**:
51
+
52
+ ```sh
53
+ opencode plugin add opencode-usage-limits
54
+ ```
55
+
56
+ Restart the TUI afterwards. A Git specifier works too:
57
+
58
+ ```sh
59
+ opencode plugin add github:GamingNowEdward/opencode-usage-limits
60
+ ```
61
+
62
+ **From a local directory**: add the plugin directory to OpenCode's CLI config `cli.json`
63
+ (global path: `~/.config/opencode/cli.json`):
64
+
65
+ ```jsonc
66
+ {
67
+ "plugins": [
68
+ {
69
+ "package": "C:/path/to/opencode-usage-limits",
70
+ "options": { "refreshMs": 30000 }
71
+ }
72
+ ]
73
+ }
74
+ ```
75
+
76
+ CLI plugins run inside the local TUI process, so they can read `auth.json` and reach the network
77
+ directly, and they stay active even when the CLI is connected to a remote server. See the
78
+ [CLI plugin documentation](https://opencode.ai/v2/docs/build/plugins/cli).
79
+
80
+ ## Usage
81
+
82
+ - Select any model from `opencode-go` or `cline-pass` and the matching block appears in the sidebar.
83
+ - **Click the title row** to collapse/expand, or search **Toggle usage panel** in the command palette.
84
+ - Switch to another provider and the block disappears.
85
+
86
+ ## Options
87
+
88
+ | Option | Type | Default | Description |
89
+ | --- | --- | --- | --- |
90
+ | `refreshMs` | number | `30000` | Polling interval in milliseconds |
91
+ | `limits` | object | — | Overrides the built-in budgets, e.g. `{ "opencode-go": { "monthly": 100 } }` |
92
+
93
+ Thresholds and colours live in the source: `WARN_AT` / `DANGER_AT` in `core.ts`, `readPalette` in `tui.tsx`.
94
+
95
+ ## How it works
96
+
97
+ In `setup()` the plugin does three things:
98
+
99
+ 1. **Registers a sidebar slot**: `context.ui.slot({ prepend: "sidebar.content", ... })`.
100
+ 2. **Reads the current model**: `context.ui.model.current()?.providerID` (reactive).
101
+ 3. **Fetches usage per provider**: resolves the key from `auth.json`, calls the usage endpoint with
102
+ `Authorization: Bearer`, polls every 30 seconds and ticks the countdown every second.
103
+
104
+ Key resolution order: the `<PROVIDER>_API_KEY` environment variable → `~/.local/share/opencode/auth.json`.
105
+
106
+ ## File layout
107
+
108
+ | File | Purpose |
109
+ | --- | --- |
110
+ | [`tui.tsx`](./tui.tsx) | The TUI plugin itself |
111
+ | [`core.ts`](./core.ts) | Auth, API client, formatting, thresholds (pure logic, no JSX) |
112
+ | [`index.ts`](./index.ts) | Server entrypoint (no-op) |
113
+ | [`tui.ts`](./tui.ts) | Discovery entrypoint, re-exports `tui.tsx` |
114
+ | [`preview.mjs`](./preview.mjs) | Offline preview script |
115
+ | [`AGENTS.md`](./AGENTS.md) | Development conventions |
116
+ | [`CHANGELOG.md`](./CHANGELOG.md) | Changelog |
117
+
118
+ ## Offline preview
119
+
120
+ Verify the API and layout without starting the TUI (it reads your real local key):
121
+
122
+ ```powershell
123
+ node preview.mjs # both sources
124
+ node preview.mjs cline-pass # a single source
125
+ ```
126
+
127
+ ## Troubleshooting
128
+
129
+ 1. Make sure the current model belongs to `opencode-go` or `cline-pass`.
130
+ 2. Plugin files **hot reload on save** — no restart needed. Only adding or removing an imported file requires restarting the TUI.
131
+ 3. Check the log: `~/.local/share/opencode/log/opencode.log`, filter by `role=cli` and `plugin`.
132
+
133
+ ## See also
134
+
135
+ - [OpenCode V2 documentation](https://opencode.ai/v2/docs/)
136
+ - [Building plugins](https://opencode.ai/v2/docs/build/plugins) · [CLI plugins](https://opencode.ai/v2/docs/build/plugins/cli)
137
+ - Similar community plugin: [leleor/opencode-usage-limits-sidebar](https://github.com/leleor/opencode-usage-limits-sidebar)
138
+
139
+ ## License
140
+
141
+ [MIT](./LICENSE) © 2026 GamingNowEdward
package/README.md ADDED
@@ -0,0 +1,138 @@
1
+ # usage-limits
2
+
3
+ > 在 OpenCode 右侧侧边栏实时显示订阅方案的用量限额(5 小时 / 周 / 月)。
4
+
5
+ [简体中文](./README.md) · [English](./README.en.md)
6
+
7
+ 一个 [OpenCode](https://opencode.ai/v2/docs/) **V2 TUI 插件**。当当前选中的模型属于
8
+ **OpenCode Go** 或 **ClinePass** 时,右侧侧边栏会自动出现用量区块,展示三个滚动窗口的
9
+ 占用百分比、进度条与重置倒计时。
10
+
11
+ ```text
12
+ ▾ USAGE · OpenCode Go
13
+ 5 hours 0%
14
+ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
15
+ ↻ 5h $0.00 / $12.00
16
+
17
+ Weekly 1%
18
+ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
19
+ ↻ 6d 4h $0.30 / $30.00
20
+
21
+ Monthly 60%
22
+ ███████████████████░░░░░░░░░░░░░░░░░
23
+ ↻ 7d 14h $36.00 / $60.00
24
+ ```
25
+
26
+ ## 功能
27
+
28
+ - **两个用量来源**:OpenCode Go、ClinePass,按当前模型自动切换。
29
+ - **三个窗口**:5 小时滚动 / 周 / 月,含百分比、进度条、重置倒计时。
30
+ - **绿黄红提醒**:< 50% 绿、50–79% 黄、≥ 80% 红(阈值见 `core.ts`)。
31
+ - **金额显示**:OpenCode Go 显示 `已用 / 限额`($12 / $30 / $60);ClinePass 的限额从 `/users/me/plan` 实时读取。
32
+ - **整体折叠**:点标题行收起,只留一行;状态持久化,重启保持。
33
+ - **不打扰**:选中其他 provider 时**完全不渲染**,不占空间。
34
+ - **限流退避**:遇 429 / 5xx / 网络失败自动指数退避(最长 5 分钟),并显示 `retry in Ns`。
35
+ - **数据过期提示**:数据变旧(超过约 75 秒,即 2.5 个轮询间隔)时,标题行才显示年龄并变黄;平时不显示,不产生噪音。
36
+ - **密钥安全**:从 OpenCode 的 `auth.json` 实时读取,插件不存储任何凭据。
37
+
38
+ ## 支持的数据源
39
+
40
+ | Provider ID | 名称 | 用量接口 | 显示金额 |
41
+ | --- | --- | --- | --- |
42
+ | `opencode-go` | [OpenCode Go](https://opencode.ai/docs/go) | `GET https://opencode.ai/zen/go/v1/usage` | 是($12 / $30 / $60) |
43
+ | `cline-pass` | [ClinePass](https://docs.cline.bot/getting-started/clinepass) | `GET https://api.cline.bot/api/v1/users/me/plan/usage-limits` | 是(从 `/users/me/plan` 实时读取套餐上限) |
44
+
45
+ > Cline 的公开文档见 [Cline API](https://docs.cline.bot/api/overview)。
46
+
47
+ ## 安装
48
+
49
+ **从 npm 安装(推荐)**:
50
+
51
+ ```sh
52
+ opencode plugin add opencode-usage-limits
53
+ ```
54
+
55
+ 装完重启 TUI 即可。也可使用 Git 规格安装:
56
+
57
+ ```sh
58
+ opencode plugin add github:GamingNowEdward/opencode-usage-limits
59
+ ```
60
+
61
+ **从本地目录安装**:把插件目录加入 OpenCode 的 CLI 配置 `cli.json`(全局位于 `~/.config/opencode/cli.json`):
62
+
63
+ ```jsonc
64
+ {
65
+ "plugins": [
66
+ {
67
+ "package": "C:/path/to/opencode-usage-limits",
68
+ "options": { "refreshMs": 30000 }
69
+ }
70
+ ]
71
+ }
72
+ ```
73
+
74
+ CLI 插件在本地 TUI 进程内运行,因此可以直接读取 `auth.json` 与访问网络;它也会在连接
75
+ 远程 server 时保持可用。详见 [CLI 插件文档](https://opencode.ai/v2/docs/build/plugins/cli)。
76
+
77
+ ## 使用
78
+
79
+ - 选中 `opencode-go` 或 `cline-pass` 的任意模型,侧边栏即出现对应区块。
80
+ - **点击标题行**折叠 / 展开,或在命令面板搜索 **Toggle usage panel**。
81
+ - 切换到其他 provider 时区块自动消失。
82
+
83
+ ## 配置项
84
+
85
+ | 选项 | 类型 | 默认 | 说明 |
86
+ | --- | --- | --- | --- |
87
+ | `refreshMs` | number | `30000` | 轮询间隔(毫秒) |
88
+ | `limits` | object | — | 覆盖内置额度,如 `{ "opencode-go": { "monthly": 100 } }` |
89
+
90
+ 配色阈值写在源码中:`core.ts` 的 `WARN_AT` / `DANGER_AT`,`tui.tsx` 的 `readPalette`。
91
+
92
+ ## 工作原理
93
+
94
+ 插件在 `setup()` 中做三件事:
95
+
96
+ 1. **注册侧边栏 slot**:`context.ui.slot({ prepend: "sidebar.content", ... })`。
97
+ 2. **读取当前模型**:`context.ui.model.current()?.providerID`(响应式)。
98
+ 3. **按 provider 拉取用量**:从 `auth.json` 取密钥,带 `Authorization: Bearer` 请求用量接口,
99
+ 30 秒轮询一次,1 秒刷新倒计时。
100
+
101
+ 密钥解析顺序:环境变量 `<PROVIDER>_API_KEY` → `~/.local/share/opencode/auth.json`。
102
+
103
+ ## 文件结构
104
+
105
+ | 文件 | 说明 |
106
+ | --- | --- |
107
+ | [`tui.tsx`](./tui.tsx) | TUI 插件主体 |
108
+ | [`core.ts`](./core.ts) | 鉴权、API 客户端、格式化、阈值(纯逻辑,无 JSX) |
109
+ | [`index.ts`](./index.ts) | server 入口(no-op) |
110
+ | [`tui.ts`](./tui.ts) | 发现入口,re-export `tui.tsx` |
111
+ | [`preview.mjs`](./preview.mjs) | 离线预览脚本 |
112
+ | [`AGENTS.md`](./AGENTS.md) | 开发约定 |
113
+ | [`CHANGELOG.md`](./CHANGELOG.md) | 变更日志 |
114
+
115
+ ## 离线预览
116
+
117
+ 无需启动 TUI 即可验证接口与排版(会读取你本机的真实密钥):
118
+
119
+ ```powershell
120
+ node preview.mjs # 两个来源
121
+ node preview.mjs cline-pass # 只预览一个
122
+ ```
123
+
124
+ ## 排障
125
+
126
+ 1. 确认当前模型属于 `opencode-go` 或 `cline-pass`。
127
+ 2. 插件文件**保存即热重载**,无需重启;只有新增/删除被 import 的文件时才需退出 TUI 重进。
128
+ 3. 查看日志:`~/.local/share/opencode/log/opencode.log`,筛 `role=cli` 与 `plugin`。
129
+
130
+ ## 相关
131
+
132
+ - [OpenCode V2 文档](https://opencode.ai/v2/docs/)
133
+ - [插件开发](https://opencode.ai/v2/docs/build/plugins) · [CLI 插件](https://opencode.ai/v2/docs/build/plugins/cli)
134
+ - 社区同类插件:[leleor/opencode-usage-limits-sidebar](https://github.com/leleor/opencode-usage-limits-sidebar)
135
+
136
+ ## 许可
137
+
138
+ [MIT](./LICENSE) © 2026 GamingNowEdward
package/core.ts ADDED
@@ -0,0 +1,324 @@
1
+ // Shared logic for the usage-limits TUI plugin.
2
+ // No JSX here so it can also be imported by the preview script.
3
+ import { readFile } from "node:fs/promises"
4
+ import { existsSync } from "node:fs"
5
+ import { homedir } from "node:os"
6
+ import { join } from "node:path"
7
+
8
+ export type WindowKind = "hour5" | "weekly" | "monthly"
9
+
10
+ export interface UsageWindow {
11
+ kind: WindowKind
12
+ label: string
13
+ percent: number
14
+ /** USD budget for this window; OpenCode Go uses fixed budgets, ClinePass reads them from the plan. */
15
+ limit?: number
16
+ /** Epoch ms when the window resets, or null when unknown. */
17
+ resetsAt: number | null
18
+ /** Provider-reported window status (OpenCode Go only), e.g. "ok". */
19
+ status?: string
20
+ }
21
+
22
+ export interface ProviderConfig {
23
+ id: string
24
+ title: string
25
+ baseUrl: string
26
+ path: string
27
+ /** Endpoint exposing the plan's per-window USD caps, when the provider has one. */
28
+ planPath?: string
29
+ /** Dollar budgets per window (OpenCode Go only). */
30
+ limits?: Record<WindowKind, number>
31
+ }
32
+
33
+ export const PROVIDERS: Record<string, ProviderConfig> = {
34
+ "opencode-go": {
35
+ id: "opencode-go",
36
+ title: "OpenCode Go",
37
+ baseUrl: "https://opencode.ai/zen/go/v1",
38
+ path: "/usage",
39
+ limits: { hour5: 12, weekly: 30, monthly: 60 },
40
+ },
41
+ "cline-pass": {
42
+ id: "cline-pass",
43
+ title: "ClinePass",
44
+ baseUrl: "https://api.cline.bot/api/v1",
45
+ path: "/users/me/plan/usage-limits",
46
+ planPath: "/users/me/plan",
47
+ },
48
+ }
49
+
50
+ const WINDOW_LABEL: Record<WindowKind, string> = {
51
+ hour5: "5 hours",
52
+ weekly: "Weekly",
53
+ monthly: "Monthly",
54
+ }
55
+
56
+ /** Provider configuration with any user-supplied limit overrides applied. */
57
+ export function resolveProvider(providerID: string, options?: any): ProviderConfig | undefined {
58
+ const base = PROVIDERS[providerID]
59
+ if (!base) return undefined
60
+ const override = options?.limits?.[providerID]
61
+ if (!override) return base
62
+ return { ...base, limits: { ...(base.limits ?? {}), ...override } as Record<WindowKind, number> }
63
+ }
64
+
65
+ const WINDOW_ORDER: WindowKind[] = ["hour5", "weekly", "monthly"]
66
+
67
+ /** Number of windows a complete reading contains. */
68
+ export const WINDOW_COUNT = WINDOW_ORDER.length
69
+
70
+ // ---- API key resolution -------------------------------------------------
71
+
72
+ function authPaths(): string[] {
73
+ const home = homedir()
74
+ const paths = [join(home, ".local", "share", "opencode", "auth.json")]
75
+ if (process.env.XDG_DATA_HOME) paths.push(join(process.env.XDG_DATA_HOME, "opencode", "auth.json"))
76
+ if (process.env.LOCALAPPDATA) paths.push(join(process.env.LOCALAPPDATA, "opencode", "auth.json"))
77
+ if (process.env.APPDATA) paths.push(join(process.env.APPDATA, "opencode", "auth.json"))
78
+ return paths
79
+ }
80
+
81
+ /**
82
+ * Pull an API key out of an auth-store entry. The store may hold a single
83
+ * credential object, or an array of them when several accounts/connections
84
+ * exist for one provider; in that case the first usable key wins.
85
+ */
86
+ function extractKey(entry: any): string | undefined {
87
+ if (!entry) return undefined
88
+ if (Array.isArray(entry)) {
89
+ for (const item of entry) {
90
+ const key = extractKey(item)
91
+ if (key) return key
92
+ }
93
+ return undefined
94
+ }
95
+ if (typeof entry !== "object") return undefined
96
+ for (const field of ["key", "apiKey", "access", "token"]) {
97
+ const value = entry[field]
98
+ if (typeof value === "string" && value.length > 0) return value
99
+ }
100
+ return undefined
101
+ }
102
+
103
+ /** Resolve the provider API key from the env or OpenCode's auth store. */
104
+ export async function resolveKey(providerID: string): Promise<string | undefined> {
105
+ const envName = `${providerID.toUpperCase().replace(/-/g, "_")}_API_KEY`
106
+ const fromEnv = process.env[envName]
107
+ if (fromEnv) return fromEnv
108
+
109
+ for (const path of authPaths()) {
110
+ try {
111
+ if (!existsSync(path)) continue
112
+ const store = JSON.parse(await readFile(path, "utf-8"))
113
+ const key = extractKey(store?.[providerID])
114
+ if (key) return key
115
+ } catch {
116
+ // try the next candidate path
117
+ }
118
+ }
119
+ return undefined
120
+ }
121
+
122
+ // ---- API fetching -------------------------------------------------------
123
+
124
+ function toMs(value: unknown): number | null {
125
+ if (typeof value !== "string") return null
126
+ const ms = new Date(value).getTime()
127
+ return Number.isFinite(ms) ? ms : null
128
+ }
129
+
130
+ function buildWindow(
131
+ kind: WindowKind,
132
+ percent: number,
133
+ resetsAt: number | null,
134
+ limits?: Record<WindowKind, number>,
135
+ status?: string,
136
+ ): UsageWindow {
137
+ return { kind, label: WINDOW_LABEL[kind], percent, limit: limits?.[kind], resetsAt, status }
138
+ }
139
+
140
+ /**
141
+ * ClinePass reports plan caps as fixed-point integers. Calibrated against the
142
+ * live API: the sum of `costUsd` over a rolling window matches
143
+ * `percent x cap` in the same unit, and a single ~144k-token request costs
144
+ * ~82,000 units. 1 unit = 1e-8 USD, i.e. $10 / $25 / $50 for 5h / weekly / monthly.
145
+ */
146
+ export const CLINE_CAP_UNIT_USD = 1e-8
147
+
148
+ const capCache = new Map<string, { at: number; caps: Record<WindowKind, number> }>()
149
+ const CAP_TTL_MS = 6 * 60 * 60 * 1000
150
+
151
+ /**
152
+ * Read the plan's per-window USD caps. Caps change rarely, so they are cached.
153
+ * Caps are a nice-to-have: any failure returns undefined and never fails the
154
+ * usage fetch itself.
155
+ */
156
+ async function fetchPlanCaps(
157
+ config: ProviderConfig,
158
+ key: string,
159
+ timeoutMs: number,
160
+ ): Promise<Record<WindowKind, number> | undefined> {
161
+ if (!config.planPath) return undefined
162
+ const hit = capCache.get(config.id)
163
+ if (hit && Date.now() - hit.at < CAP_TTL_MS) return hit.caps
164
+ try {
165
+ const url = config.baseUrl.replace(/\/$/, "") + config.planPath
166
+ const data = await readJson(url, key, timeoutMs)
167
+ const threshold = data?.data?.plan?.entitlements?.cline_pass?.inferenceCapThreshold
168
+ if (!threshold) return undefined
169
+ const caps: Record<WindowKind, number> = {
170
+ hour5: Number(threshold.last5HoursUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
171
+ weekly: Number(threshold.last7daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
172
+ monthly: Number(threshold.last30daysUsageCostUSDPerUser) * CLINE_CAP_UNIT_USD,
173
+ }
174
+ if (!Object.values(caps).every((n) => Number.isFinite(n) && n > 0)) return undefined
175
+ capCache.set(config.id, { at: Date.now(), caps })
176
+ return caps
177
+ } catch {
178
+ return undefined
179
+ }
180
+ }
181
+
182
+ /** HTTP failure carrying the status code so callers can decide on a backoff. */
183
+ function httpError(status: number, message: string): Error {
184
+ const error = new Error(message)
185
+ ;(error as any).status = status
186
+ return error
187
+ }
188
+
189
+ async function readJson(url: string, key: string, timeoutMs: number): Promise<any> {
190
+ const controller = new AbortController()
191
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
192
+ try {
193
+ const res = await fetch(url, {
194
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
195
+ signal: controller.signal,
196
+ })
197
+ if (res.status === 401 || res.status === 403) throw httpError(res.status, "API key rejected")
198
+ if (res.status === 429) throw httpError(429, "rate limited by the usage API")
199
+ if (!res.ok) throw httpError(res.status, `usage API ${res.status}`)
200
+ return await res.json()
201
+ } finally {
202
+ clearTimeout(timer)
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Whether a failure is worth retrying with a growing delay, and how long to
208
+ * wait. Rate limits and server errors back off; auth and shape errors do not.
209
+ */
210
+ export function backoffFor(error: unknown, currentMs: number, baseMs: number, maxMs = 5 * 60_000): number {
211
+ const status = Number((error as any)?.status) || 0
212
+ // A 0 status means a network/abort failure, which is also transient.
213
+ const transient = status === 0 || status === 429 || (status >= 500 && status < 600)
214
+ if (!transient) return baseMs
215
+ return Math.min(Math.max(currentMs, baseMs) * 2, maxMs)
216
+ }
217
+
218
+ /** True when the error is transient (used to label the retry countdown). */
219
+ export function isTransient(error: unknown): boolean {
220
+ const status = Number((error as any)?.status) || 0
221
+ return status === 0 || status === 429 || (status >= 500 && status < 600)
222
+ }
223
+
224
+ /**
225
+ * Fetch the three usage windows for a provider.
226
+ * OpenCode Go reports percentages and we map them onto its $12/$30/$60 budgets.
227
+ * ClinePass reports percentages only, so no dollar amount is shown.
228
+ */
229
+ export async function fetchUsage(config: ProviderConfig, key: string, timeoutMs = 10000): Promise<UsageWindow[]> {
230
+ const url = config.baseUrl.replace(/\/$/, "") + config.path
231
+ const data = await readJson(url, key, timeoutMs)
232
+
233
+ if (config.id === "cline-pass") {
234
+ const limits: any[] = Array.isArray(data?.data?.limits) ? data.data.limits : []
235
+ const map: Record<string, WindowKind> = { five_hour: "hour5", weekly: "weekly", monthly: "monthly" }
236
+ const caps = await fetchPlanCaps(config, key, timeoutMs)
237
+ const windows: UsageWindow[] = []
238
+ for (const kind of WINDOW_ORDER) {
239
+ const hit = limits.find((l) => map[l?.type] === kind)
240
+ if (!hit) continue
241
+ windows.push(buildWindow(kind, Number(hit.percentUsed) || 0, toMs(hit.resetsAt), caps ?? config.limits))
242
+ }
243
+ if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
244
+ return windows
245
+ }
246
+
247
+ const usage = data?.usage
248
+ const sources: Record<WindowKind, any> = {
249
+ hour5: usage?.rolling,
250
+ weekly: usage?.weekly,
251
+ monthly: usage?.monthly,
252
+ }
253
+ const windows: UsageWindow[] = []
254
+ for (const kind of WINDOW_ORDER) {
255
+ const src = sources[kind]
256
+ if (!src) continue
257
+ const status = typeof src.status === "string" ? src.status : undefined
258
+ windows.push(buildWindow(kind, Number(src.percent) || 0, toMs(src.resetsAt), config.limits, status))
259
+ }
260
+ if (windows.length === 0) throw new Error("usage API returned an unexpected shape")
261
+ return windows
262
+ }
263
+
264
+ // ---- Formatting ---------------------------------------------------------
265
+
266
+ const MINUTE = 60_000
267
+ const HOUR = 60 * MINUTE
268
+ const DAY = 24 * HOUR
269
+
270
+ export function clampPercent(value: number): number {
271
+ return Math.max(0, Math.min(100, Math.round(value)))
272
+ }
273
+
274
+ export function formatUsd(value: number): string {
275
+ return `$${value.toFixed(2)}`
276
+ }
277
+
278
+ export function usedUsd(window: UsageWindow): number | undefined {
279
+ if (window.limit == null) return undefined
280
+ return (window.percent / 100) * window.limit
281
+ }
282
+
283
+ export function rightAlign(value: string, width: number): string {
284
+ return value.padStart(width)
285
+ }
286
+
287
+ /** Compact countdown such as `1h12m`, `5d 4h`, `now`. */
288
+ export function resetText(resetsAt: number | null, now: number): string {
289
+ if (resetsAt == null) return "--"
290
+ const remaining = resetsAt - now
291
+ if (remaining <= 0) return "now"
292
+ if (remaining < HOUR) return `${Math.max(1, Math.floor(remaining / MINUTE))}m`
293
+ if (remaining < DAY) {
294
+ const h = Math.floor(remaining / HOUR)
295
+ const m = Math.floor((remaining % HOUR) / MINUTE)
296
+ return m > 0 && h < 10 ? `${h}h${m}m` : `${h}h`
297
+ }
298
+ const d = Math.floor(remaining / DAY)
299
+ const h = Math.floor((remaining % DAY) / HOUR)
300
+ return h > 0 ? `${d}d ${h}h` : `${d}d`
301
+ }
302
+
303
+ export type Severity = "ok" | "warn" | "danger"
304
+
305
+ /** Percentage thresholds for the green/yellow/red usage colour. */
306
+ export const WARN_AT = 50
307
+ export const DANGER_AT = 80
308
+
309
+ export function severity(percent: number): Severity {
310
+ if (percent >= DANGER_AT) return "danger"
311
+ if (percent >= WARN_AT) return "warn"
312
+ return "ok"
313
+ }
314
+
315
+ /** True when the provider itself reports the window as not usable. */
316
+ export function isWindowLimited(window: UsageWindow): boolean {
317
+ return Boolean(window.status && window.status !== "ok")
318
+ }
319
+
320
+ /** Severity for a window, taking the provider-reported status into account. */
321
+ export function windowSeverity(window: UsageWindow): Severity {
322
+ if (isWindowLimited(window)) return "danger"
323
+ return severity(window.percent)
324
+ }
package/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { Plugin } from "@opencode/plugin"
2
+
3
+ // Server-side entrypoint. This plugin is TUI-only, so the server side is a no-op.
4
+ export default Plugin.define({
5
+ id: "usage-limits",
6
+ setup() {},
7
+ })
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "opencode-usage-limits",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Show OpenCode Go and ClinePass subscription usage (5-hour / weekly / monthly) in the OpenCode TUI sidebar.",
6
+ "license": "MIT",
7
+ "author": "GamingNowEdward",
8
+ "keywords": [
9
+ "opencode",
10
+ "opencode-plugin",
11
+ "tui",
12
+ "usage",
13
+ "quota",
14
+ "sidebar",
15
+ "opencode-go",
16
+ "clinepass"
17
+ ],
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/GamingNowEdward/opencode-usage-limits.git"
21
+ },
22
+ "homepage": "https://github.com/GamingNowEdward/opencode-usage-limits#readme",
23
+ "bugs": {
24
+ "url": "https://github.com/GamingNowEdward/opencode-usage-limits/issues"
25
+ },
26
+ "exports": {
27
+ ".": "./index.ts",
28
+ "./server": "./index.ts",
29
+ "./tui": "./tui.tsx"
30
+ },
31
+ "files": [
32
+ "index.ts",
33
+ "tui.ts",
34
+ "tui.tsx",
35
+ "core.ts",
36
+ "README.md",
37
+ "README.en.md",
38
+ "CHANGELOG.md",
39
+ "CHANGELOG.en.md",
40
+ "LICENSE"
41
+ ],
42
+ "peerDependencies": {
43
+ "@opencode/plugin": ">=2.0.0",
44
+ "@opentui/core": ">=0.4.5",
45
+ "@opentui/solid": ">=0.4.5",
46
+ "solid-js": ">=1.9.0"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "@opencode/plugin": { "optional": true },
50
+ "@opentui/core": { "optional": true },
51
+ "@opentui/solid": { "optional": true }
52
+ },
53
+ "publishConfig": {
54
+ "registry": "https://registry.npmjs.org",
55
+ "access": "public"
56
+ }
57
+ }
package/tui.ts ADDED
@@ -0,0 +1,3 @@
1
+ // Discovery entrypoint: OpenCode looks for `tui.ts`/`tui.tsx` in a plugin
2
+ // directory. This re-export keeps both names working.
3
+ export { default } from "./tui.tsx"
package/tui.tsx ADDED
@@ -0,0 +1,293 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { Plugin } from "@opencode/plugin/tui"
3
+ import { Index, Show, createEffect, createMemo, createSignal, onCleanup, onMount } from "solid-js"
4
+ import {
5
+ WINDOW_COUNT,
6
+ backoffFor,
7
+ clampPercent,
8
+ fetchUsage,
9
+ formatUsd,
10
+ isTransient,
11
+ isWindowLimited,
12
+ resetText,
13
+ resolveKey,
14
+ resolveProvider,
15
+ rightAlign,
16
+ usedUsd,
17
+ windowSeverity,
18
+ type UsageWindow,
19
+ } from "./core.ts"
20
+
21
+ const REFRESH_MS = 30_000
22
+ const MAX_BACKOFF_MS = 5 * 60_000
23
+ /** Fixed width of the title row's right-hand status cell (spinner or age). */
24
+ const STATUS_WIDTH = 4
25
+
26
+ type Palette = {
27
+ text: any
28
+ muted: any
29
+ accent: any
30
+ green: any
31
+ warn: any
32
+ danger: any
33
+ track: any
34
+ }
35
+
36
+ function readPalette(theme: any): Palette {
37
+ const action = theme?.text?.action?.primary
38
+ const base = theme?.text?.base
39
+ return {
40
+ text: base,
41
+ muted: theme?.text?.muted,
42
+ accent: action?.base ?? base,
43
+ // Green / yellow / red usage states come from the theme's semantic feedback
44
+ // colours so they stay consistent with the active theme.
45
+ green: theme?.text?.feedback?.success?.base ?? "#3FB950",
46
+ warn: theme?.text?.feedback?.warning?.base ?? base,
47
+ danger: theme?.text?.feedback?.error?.base ?? base,
48
+ // Use the theme's border colour for the unfilled track: it is guaranteed to
49
+ // contrast with the sidebar panel background (raised.base is the panel
50
+ // colour itself, which made the track invisible).
51
+ track: theme?.border?.base ?? theme?.background?.raised?.base,
52
+ }
53
+ }
54
+
55
+ function severityColor(palette: Palette, window: UsageWindow) {
56
+ const level = windowSeverity(window)
57
+ if (level === "danger") return palette.danger
58
+ if (level === "warn") return palette.warn
59
+ return palette.green
60
+ }
61
+
62
+ function ProgressBar(props: { percent: number; color: any; track: any }) {
63
+ const pct = () => Math.max(0, Math.min(100, props.percent))
64
+ return (
65
+ <box width="100%" height={1} flexDirection="row">
66
+ <box flexGrow={Math.max(pct(), 0.01)} backgroundColor={props.color} />
67
+ <box flexGrow={Math.max(100 - pct(), 0.01)} backgroundColor={props.track} />
68
+ </box>
69
+ )
70
+ }
71
+
72
+ function WindowRow(props: { window: UsageWindow; palette: Palette; now: number }) {
73
+ const pct = () => clampPercent(props.window.percent)
74
+ const color = () => severityColor(props.palette, props.window)
75
+ const used = () => usedUsd(props.window)
76
+ const hasAmount = () => used() != null && props.window.limit != null
77
+ const limited = () => isWindowLimited(props.window)
78
+ // Memoised so the ticking clock only writes to the DOM when the rendered text
79
+ // actually changes (Solid memos compare with ===).
80
+ const resetLabel = createMemo(() => `↻ ${resetText(props.window.resetsAt, props.now)}`)
81
+
82
+ return (
83
+ <box flexDirection="column" width="100%" marginTop={1}>
84
+ <box flexDirection="row" width="100%">
85
+ <box flexGrow={1} flexDirection="row">
86
+ <text fg={color()}>{props.window.label}</text>
87
+ <Show when={limited()}>
88
+ <text fg={color()}>{` ${props.window.status}`}</text>
89
+ </Show>
90
+ </box>
91
+ <text fg={color()}>{rightAlign(`${pct()}%`, 5)}</text>
92
+ </box>
93
+ <ProgressBar percent={props.window.percent} color={color()} track={props.palette.track} />
94
+ <box flexDirection="row" width="100%">
95
+ <text fg={props.palette.muted}>{resetLabel()}</text>
96
+ <box flexGrow={1} />
97
+ <Show when={hasAmount()}>
98
+ <text fg={props.palette.muted}>{`${formatUsd(used() as number)} / ${formatUsd(props.window.limit as number)}`}</text>
99
+ </Show>
100
+ </box>
101
+ </box>
102
+ )
103
+ }
104
+
105
+ function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
106
+ const ctx = props.context
107
+ const palette = createMemo<Palette>(() => readPalette(ctx.theme))
108
+ const providerID = createMemo<string | undefined>(() => ctx.ui.model.current()?.providerID)
109
+ const config = createMemo(() => {
110
+ const id = providerID()
111
+ return id ? resolveProvider(id, ctx.options) : undefined
112
+ })
113
+
114
+ const [windows, setWindows] = createSignal<UsageWindow[]>([])
115
+ const [loading, setLoading] = createSignal(false)
116
+ const [error, setError] = createSignal("")
117
+ const [now, setNow] = createSignal(Date.now())
118
+ const [lastOkAt, setLastOkAt] = createSignal<number | undefined>(undefined)
119
+ const [nextRetryAt, setNextRetryAt] = createSignal<number | undefined>(undefined)
120
+
121
+ const baseMs = Number(props.context?.options?.refreshMs) || REFRESH_MS
122
+ let pollMs = baseMs
123
+
124
+ // Guard per provider: if the user switches providers while a request is
125
+ // still in flight, the new provider's request must fire immediately instead
126
+ // of waiting for the next poll. Stale responses are dropped by the
127
+ // `config()?.id === cfg.id` check below, so they cannot pollute the panel.
128
+ const inflight = new Set<string>()
129
+ const refresh = async () => {
130
+ const cfg = config()
131
+ if (!cfg || inflight.has(cfg.id)) return
132
+ inflight.add(cfg.id)
133
+ setLoading(true)
134
+ try {
135
+ const key = await resolveKey(cfg.id)
136
+ if (!key) {
137
+ setWindows([])
138
+ setError("API key not found")
139
+ setNextRetryAt(undefined)
140
+ return
141
+ }
142
+ const next = await fetchUsage(cfg, key)
143
+ if (config()?.id === cfg.id) {
144
+ setWindows(next)
145
+ setError("")
146
+ setLastOkAt(Date.now())
147
+ setNextRetryAt(undefined)
148
+ }
149
+ pollMs = baseMs
150
+ } catch (err: any) {
151
+ const message = err?.message ?? "usage API unavailable"
152
+ if (isTransient(err)) {
153
+ // Rate limits and network/server failures back off instead of hammering
154
+ // the endpoint on every tick.
155
+ pollMs = backoffFor(err, pollMs, baseMs, MAX_BACKOFF_MS)
156
+ setNextRetryAt(Date.now() + pollMs)
157
+ } else {
158
+ pollMs = baseMs
159
+ setNextRetryAt(undefined)
160
+ }
161
+ setError(message)
162
+ } finally {
163
+ inflight.delete(cfg.id)
164
+ setLoading(inflight.size > 0)
165
+ }
166
+ }
167
+
168
+ let pollTimer: any
169
+ let tickTimer: any
170
+ onMount(() => {
171
+ let cancelled = false
172
+ const loop = async () => {
173
+ if (cancelled) return
174
+ await refresh()
175
+ if (cancelled) return
176
+ pollTimer = setTimeout(loop, pollMs)
177
+ }
178
+ pollTimer = setTimeout(loop, baseMs)
179
+
180
+ // The countdown only ever shows minute precision, so tick on minute
181
+ // boundaries instead of every second. While a retry countdown is on screen
182
+ // tick every second so the remaining seconds stay live.
183
+ const scheduleTick = () => {
184
+ const delay = nextRetryAt() !== undefined ? 1000 : 60_000 - (Date.now() % 60_000)
185
+ tickTimer = setTimeout(() => {
186
+ if (cancelled) return
187
+ setNow(Date.now())
188
+ scheduleTick()
189
+ }, delay)
190
+ }
191
+ scheduleTick()
192
+
193
+ onCleanup(() => {
194
+ cancelled = true
195
+ clearTimeout(pollTimer)
196
+ clearTimeout(tickTimer)
197
+ })
198
+ })
199
+
200
+ createEffect(() => {
201
+ const cfg = config()
202
+ setWindows([])
203
+ setError("")
204
+ setNextRetryAt(undefined)
205
+ pollMs = baseMs
206
+ if (cfg) {
207
+ setLastOkAt(undefined)
208
+ void refresh()
209
+ }
210
+ })
211
+
212
+ // Age of the reading currently on screen, and whether it is older than two
213
+ // polling intervals (i.e. the panel is showing stale data after a failure).
214
+ const ageSeconds = () => {
215
+ const at = lastOkAt()
216
+ if (!at) return undefined
217
+ return Math.max(0, Math.floor((now() - at) / 1000))
218
+ }
219
+ const isStale = createMemo(() => {
220
+ const s = ageSeconds()
221
+ return s !== undefined && s * 1000 > baseMs * 2.5
222
+ })
223
+ // Minute precision: the label stays identical between ticks, and the memo
224
+ // stops Solid from rewriting the text node every time the clock advances.
225
+ const ageText = createMemo(() => {
226
+ const s = ageSeconds()
227
+ if (s === undefined) return ""
228
+ if (s < 60) return "now"
229
+ if (s < 3600) return `${Math.floor(s / 60)}m`
230
+ return `${Math.floor(s / 3600)}h`
231
+ })
232
+ // Only surface the age once the reading is actually stale: while the data is
233
+ // fresh the cell stays blank so the title row carries no noise. The spinner
234
+ // keeps using the same fixed-width cell, so it never shifts the layout.
235
+ const statusText = createMemo(() => rightAlign(loading() ? "⋯" : isStale() ? ageText() : "", STATUS_WIDTH))
236
+ const retryText = createMemo(() => {
237
+ const at = nextRetryAt()
238
+ if (at === undefined) return ""
239
+ return ` · retry in ${Math.max(0, Math.ceil((at - now()) / 1000))}s`
240
+ })
241
+
242
+ return (
243
+ <Show when={config()}>
244
+ {(cfg) => (
245
+ <box flexDirection="column" width="100%" marginTop={1}>
246
+ <box flexDirection="row" width="100%" onMouseUp={() => props.toggle()}>
247
+ <box flexGrow={1}>
248
+ <text fg={palette().text}>{`${props.panel.collapsed ? "▸" : "▾"} USAGE · ${cfg().title}`}</text>
249
+ </box>
250
+ <text fg={isStale() && !loading() ? palette().warn : palette().muted}>{statusText()}</text>
251
+ </box>
252
+ <Show when={!props.panel.collapsed}>
253
+ <Show when={error()}>
254
+ <text fg={palette().danger}>{`${error()}${retryText()}`}</text>
255
+ </Show>
256
+ <Show when={windows().length > 0 && windows().length < WINDOW_COUNT}>
257
+ <text fg={palette().warn}>{`partial data · ${windows().length}/${WINDOW_COUNT} windows`}</text>
258
+ </Show>
259
+ <Index each={windows()}>{(w) => <WindowRow window={w()} palette={palette()} now={now()} />}</Index>
260
+ </Show>
261
+ </box>
262
+ )}
263
+ </Show>
264
+ )
265
+ }
266
+
267
+ export default Plugin.define({
268
+ id: "usage-limits",
269
+ setup(context) {
270
+ const [panel, updatePanel] = context.storage.store("usage-limits.panel", {
271
+ initial: { collapsed: false },
272
+ })
273
+ const toggle = () => void updatePanel((draft: any) => { draft.collapsed = !draft.collapsed })
274
+
275
+ context.keymap.layer(() => ({
276
+ mode: "global",
277
+ commands: [
278
+ {
279
+ id: "usage-limits.toggle",
280
+ title: "Toggle usage panel",
281
+ group: "Usage Limits",
282
+ palette: true,
283
+ run: toggle,
284
+ },
285
+ ],
286
+ }))
287
+
288
+ return context.ui.slot({
289
+ prepend: "sidebar.content",
290
+ render: () => <UsagePanel context={context} panel={panel} toggle={toggle} />,
291
+ })
292
+ },
293
+ })