opencode-usage-limits 0.3.0 → 0.3.2

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/tui.tsx DELETED
@@ -1,319 +0,0 @@
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
- modelAllowance,
13
- resetText,
14
- resolveKey,
15
- resolveProvider,
16
- rightAlign,
17
- usedUsd,
18
- windowSeverity,
19
- type UsageWindow,
20
- } from "./core.ts"
21
-
22
- const REFRESH_MS = 30_000
23
- const MAX_BACKOFF_MS = 5 * 60_000
24
- /** Fixed width of the title row's right-hand status cell (spinner or age). */
25
- const STATUS_WIDTH = 4
26
-
27
- type Palette = {
28
- text: any
29
- muted: any
30
- accent: any
31
- green: any
32
- warn: any
33
- danger: any
34
- track: any
35
- }
36
-
37
- function readPalette(theme: any): Palette {
38
- const action = theme?.text?.action?.primary
39
- const base = theme?.text?.base
40
- return {
41
- text: base,
42
- muted: theme?.text?.muted,
43
- accent: action?.base ?? base,
44
- // Green / yellow / red usage states come from the theme's semantic feedback
45
- // colours so they stay consistent with the active theme.
46
- green: theme?.text?.feedback?.success?.base ?? "#3FB950",
47
- warn: theme?.text?.feedback?.warning?.base ?? base,
48
- danger: theme?.text?.feedback?.error?.base ?? base,
49
- // Use the theme's border colour for the unfilled track: it is guaranteed to
50
- // contrast with the sidebar panel background (raised.base is the panel
51
- // colour itself, which made the track invisible).
52
- track: theme?.border?.base ?? theme?.background?.raised?.base,
53
- }
54
- }
55
-
56
- function severityColor(palette: Palette, window: UsageWindow) {
57
- const level = windowSeverity(window)
58
- if (level === "danger") return palette.danger
59
- if (level === "warn") return palette.warn
60
- return palette.green
61
- }
62
-
63
- function ProgressBar(props: { percent: number; color: any; track: any }) {
64
- const pct = () => Math.max(0, Math.min(100, props.percent))
65
- return (
66
- <box width="100%" height={1} flexDirection="row">
67
- <box flexGrow={Math.max(pct(), 0.01)} backgroundColor={props.color} />
68
- <box flexGrow={Math.max(100 - pct(), 0.01)} backgroundColor={props.track} />
69
- </box>
70
- )
71
- }
72
-
73
- function WindowRow(props: { window: UsageWindow; palette: Palette; now: number }) {
74
- const pct = () => clampPercent(props.window.percent)
75
- const color = () => severityColor(props.palette, props.window)
76
- const limited = () => isWindowLimited(props.window)
77
- // Memoised so the ticking clock only writes to the DOM when the rendered text
78
- // actually changes (Solid memos compare with ===).
79
- const resetLabel = createMemo(() => `↻ ${resetText(props.window.resetsAt, props.now)}`)
80
- // Only providers with a real dollar cap (ClinePass) have one; computing this
81
- // here keeps the Show guard from being the only thing preventing a crash on
82
- // an undefined amount.
83
- const amountText = createMemo(() => {
84
- const used = usedUsd(props.window)
85
- if (used == null || props.window.limit == null) return ""
86
- return `${formatUsd(used)} / ${formatUsd(props.window.limit)}`
87
- })
88
-
89
- return (
90
- <box flexDirection="column" width="100%" marginTop={1}>
91
- <box flexDirection="row" width="100%">
92
- <box flexGrow={1} flexDirection="row">
93
- <text fg={color()}>{props.window.label}</text>
94
- <Show when={limited()}>
95
- <text fg={color()}>{` ${props.window.status}`}</text>
96
- </Show>
97
- </box>
98
- <text fg={color()}>{rightAlign(`${pct()}%`, 5)}</text>
99
- </box>
100
- <ProgressBar percent={props.window.percent} color={color()} track={props.palette.track} />
101
- <box flexDirection="row" width="100%">
102
- <text fg={props.palette.muted}>{resetLabel()}</text>
103
- <box flexGrow={1} />
104
- <Show when={amountText() !== ""}>
105
- <text fg={props.palette.muted}>{amountText()}</text>
106
- </Show>
107
- </box>
108
- </box>
109
- )
110
- }
111
-
112
- function UsagePanel(props: { context: any; panel: any; toggle: () => void }) {
113
- const ctx = props.context
114
- const palette = createMemo<Palette>(() => readPalette(ctx.theme))
115
- const providerID = createMemo<string | undefined>(() => ctx.ui.model.current()?.providerID)
116
- const modelID = createMemo<string | undefined>(() => ctx.ui.model.current()?.modelID)
117
- const config = createMemo(() => {
118
- const id = providerID()
119
- return id ? resolveProvider(id, ctx.options) : undefined
120
- })
121
-
122
- // How expensive the selected model is, shown as a reference line under the
123
- // windows. Purely informational: the usage API reports percentages only.
124
- const allowanceText = createMemo(() => {
125
- if (providerID() !== "opencode-go") return ""
126
- const allowance = modelAllowance(modelID())
127
- if (allowance === "free") return "∞"
128
- if (!allowance) return "—"
129
- return `$${allowance.go}/$${allowance.plus}`
130
- })
131
-
132
- const [windows, setWindows] = createSignal<UsageWindow[]>([])
133
- const [loading, setLoading] = createSignal(false)
134
- const [error, setError] = createSignal("")
135
- const [now, setNow] = createSignal(Date.now())
136
- const [lastOkAt, setLastOkAt] = createSignal<number | undefined>(undefined)
137
- const [nextRetryAt, setNextRetryAt] = createSignal<number | undefined>(undefined)
138
-
139
- const baseMs = Number(props.context?.options?.refreshMs) || REFRESH_MS
140
- let pollMs = baseMs
141
-
142
- // Guard per provider: if the user switches providers while a request is
143
- // still in flight, the new provider's request must fire immediately instead
144
- // of waiting for the next poll. Stale responses are dropped by the
145
- // `config()?.id === cfg.id` check below, so they cannot pollute the panel.
146
- const inflight = new Set<string>()
147
- const refresh = async () => {
148
- const cfg = config()
149
- if (!cfg || inflight.has(cfg.id)) return
150
- inflight.add(cfg.id)
151
- setLoading(true)
152
- try {
153
- const key = await resolveKey(cfg.id)
154
- if (!key) {
155
- setWindows([])
156
- setError("API key not found")
157
- setNextRetryAt(undefined)
158
- return
159
- }
160
- const next = await fetchUsage(cfg, key)
161
- if (config()?.id === cfg.id) {
162
- setWindows(next)
163
- setError("")
164
- setLastOkAt(Date.now())
165
- setNextRetryAt(undefined)
166
- }
167
- pollMs = baseMs
168
- } catch (err: any) {
169
- const message = err?.message ?? "usage API unavailable"
170
- if (isTransient(err)) {
171
- // Rate limits and network/server failures back off instead of hammering
172
- // the endpoint on every tick.
173
- pollMs = backoffFor(err, pollMs, baseMs, MAX_BACKOFF_MS)
174
- setNextRetryAt(Date.now() + pollMs)
175
- } else {
176
- pollMs = baseMs
177
- setNextRetryAt(undefined)
178
- }
179
- setError(message)
180
- } finally {
181
- inflight.delete(cfg.id)
182
- setLoading(inflight.size > 0)
183
- }
184
- }
185
-
186
- let pollTimer: any
187
- let tickTimer: any
188
- onMount(() => {
189
- let cancelled = false
190
- const loop = async () => {
191
- if (cancelled) return
192
- await refresh()
193
- if (cancelled) return
194
- pollTimer = setTimeout(loop, pollMs)
195
- }
196
- pollTimer = setTimeout(loop, baseMs)
197
-
198
- // The countdown only ever shows minute precision, so tick on minute
199
- // boundaries instead of every second. While a retry countdown is on screen
200
- // tick every second so the remaining seconds stay live.
201
- const scheduleTick = () => {
202
- const delay = nextRetryAt() !== undefined ? 1000 : 60_000 - (Date.now() % 60_000)
203
- tickTimer = setTimeout(() => {
204
- if (cancelled) return
205
- setNow(Date.now())
206
- scheduleTick()
207
- }, delay)
208
- }
209
- scheduleTick()
210
-
211
- onCleanup(() => {
212
- cancelled = true
213
- clearTimeout(pollTimer)
214
- clearTimeout(tickTimer)
215
- })
216
- })
217
-
218
- createEffect(() => {
219
- const cfg = config()
220
- setWindows([])
221
- setError("")
222
- setNextRetryAt(undefined)
223
- pollMs = baseMs
224
- if (cfg) {
225
- setLastOkAt(undefined)
226
- void refresh()
227
- }
228
- })
229
-
230
- // Age of the reading currently on screen, and whether it is older than two
231
- // polling intervals (i.e. the panel is showing stale data after a failure).
232
- const ageSeconds = () => {
233
- const at = lastOkAt()
234
- if (!at) return undefined
235
- return Math.max(0, Math.floor((now() - at) / 1000))
236
- }
237
- const isStale = createMemo(() => {
238
- const s = ageSeconds()
239
- return s !== undefined && s * 1000 > baseMs * 2.5
240
- })
241
- // Minute precision: the label stays identical between ticks, and the memo
242
- // stops Solid from rewriting the text node every time the clock advances.
243
- const ageText = createMemo(() => {
244
- const s = ageSeconds()
245
- if (s === undefined) return ""
246
- if (s < 60) return "now"
247
- if (s < 3600) return `${Math.floor(s / 60)}m`
248
- return `${Math.floor(s / 3600)}h`
249
- })
250
- // Only surface the age once the reading is actually stale: while the data is
251
- // fresh the cell stays blank so the title row carries no noise. The spinner
252
- // keeps using the same fixed-width cell, so it never shifts the layout.
253
- const statusText = createMemo(() => rightAlign(loading() ? "⋯" : isStale() ? ageText() : "", STATUS_WIDTH))
254
- const retryText = createMemo(() => {
255
- const at = nextRetryAt()
256
- if (at === undefined) return ""
257
- return ` · retry in ${Math.max(0, Math.ceil((at - now()) / 1000))}s`
258
- })
259
-
260
- return (
261
- <Show when={config()}>
262
- {(cfg) => (
263
- <box flexDirection="column" width="100%" marginTop={1}>
264
- <box flexDirection="row" width="100%" onMouseUp={() => props.toggle()}>
265
- <box flexGrow={1}>
266
- <text fg={palette().text}>{`${props.panel.collapsed ? "▸" : "▾"} USAGE · ${cfg().title}`}</text>
267
- </box>
268
- <text fg={isStale() && !loading() ? palette().warn : palette().muted}>{statusText()}</text>
269
- </box>
270
- <Show when={!props.panel.collapsed}>
271
- <Show when={error()}>
272
- <text fg={palette().danger}>{`${error()}${retryText()}`}</text>
273
- </Show>
274
- <Show when={windows().length > 0 && windows().length < WINDOW_COUNT}>
275
- <text fg={palette().warn}>{`partial data · ${windows().length}/${WINDOW_COUNT} windows`}</text>
276
- </Show>
277
- <Index each={windows()}>{(w) => <WindowRow window={w()} palette={palette()} now={now()} />}</Index>
278
- <Show when={allowanceText() !== ""}>
279
- <box flexDirection="row" width="100%" marginTop={1}>
280
- <box flexGrow={1}>
281
- <text fg={palette().text}>{modelID() ?? ""}</text>
282
- </box>
283
- <text fg={palette().text}>{allowanceText()}</text>
284
- </box>
285
- </Show>
286
- </Show>
287
- </box>
288
- )}
289
- </Show>
290
- )
291
- }
292
-
293
- export default Plugin.define({
294
- id: "usage-limits",
295
- setup(context) {
296
- const [panel, updatePanel] = context.storage.store("usage-limits.panel", {
297
- initial: { collapsed: false },
298
- })
299
- const toggle = () => void updatePanel((draft: any) => { draft.collapsed = !draft.collapsed })
300
-
301
- context.keymap.layer(() => ({
302
- mode: "global",
303
- commands: [
304
- {
305
- id: "usage-limits.toggle",
306
- title: "Toggle usage panel",
307
- group: "Usage Limits",
308
- palette: true,
309
- run: toggle,
310
- },
311
- ],
312
- }))
313
-
314
- return context.ui.slot({
315
- prepend: "sidebar.content",
316
- render: () => <UsagePanel context={context} panel={panel} toggle={toggle} />,
317
- })
318
- },
319
- })