Repository navigation
Expand file tree
/
Copy pathtui.tsx
More file actions
262 lines (236 loc) · 10.3 KB
/
Copy pathtui.tsx
File metadata and controls
262 lines (236 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/** @jsxImportSource @opentui/solid */
/**
* usage — Context and subscription Usage, in the built-in session sidebar, under Jobs.
*
* Context
* 48,210 tokens
* 24% used
* $0.83 spent only for pay-per-token models; hidden for subscription and self-hosted
*
* Usage
* ✳ Claude
* 5h ▃ 32% ⇩55m ↻ 2:25pm
* week ▆ 69% ↻ Thu
* ⚡ Codex
* week █ 90% ↻ Fri
*
* Replaces the built-in opencode.sidebar.context (disabled in cli.json) so both sit together.
* Usage shows each subscription the connected providers bill against, one row per window it
* reports, as what is left; rows and extras are explained in usage.ts. Readings (Meridian
* for Claude, the Codex CLI login for ChatGPT) come every POLL_MS.
*/
import { Plugin, usePlugin } from "@opencode/plugin/tui"
import { createMemo, createSignal, For, onCleanup, Show } from "solid-js"
import { glyphCell } from "./model-icons"
import { readSources, statusText, type UsageStatus } from "./poll"
import { fetchCodex, fetchQuota, POLL_MS, providerPressureLabel, record, rows, SOURCE_INFO, sourceOf, type Level, type Reading, type Samples, type Source } from "./usage"
// ------------------------------------------------------------------ tunables
const LABEL_WIDTH = 6
const PERCENT_WIDTH = 3
const RETRY_MS = 10_000
// ------------------------------------------------------------------ helpers
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
const isLocal = (url: unknown) => /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])[:/]/i.test(String(url ?? ""))
// Same token count as the built-in section: last assistant turn after the last compaction.
function contextUsage(messages: readonly any[], models: readonly any[] | undefined, boundary?: string) {
const stop = boundary ? messages.findIndex((m) => m.id === boundary) : -1
if (boundary && stop === -1) return undefined
const end = stop === -1 ? messages.length : stop
const compaction = messages.findLastIndex((m, i) => m.type === "compaction" && m.status === "completed" && i < end)
const last = messages.findLast((m, i) => m.type === "assistant" && m.tokens !== undefined && i > compaction && i < end)
if (!last) return undefined
const t = last.tokens
const tokens = t.input + t.output + t.reasoning + t.cache.read + t.cache.write
if (tokens <= 0) return undefined
const model = models?.find((m) => m.providerID === last.model.providerID && m.id === last.model.id)
return { tokens, percent: model?.limit.context ? Math.round((tokens / model.limit.context) * 100) : undefined }
}
// ------------------------------------------------------------------ the sidebar section
function Sidebar(props: { sessionID: string }) {
const context = usePlugin()
const theme = context.theme as any
const data = context.data
const [live, setLive] = context.storage.memory("usage/v3", {
initial: {
reading: {} as Reading,
samples: {} as Partial<Record<Source, Samples>>,
},
})
const [now, setNow] = createSignal(Date.now())
const [status, setStatus] = createSignal<Record<Source, UsageStatus>>({ claude: "loading", codex: "loading" })
const [retryAt, setRetryAt] = createSignal<number>()
const retrySeconds = createMemo(() => Math.max(0, Math.ceil(((retryAt() ?? now()) - now()) / 1_000)))
const session = createMemo(() => data.session.get(props.sessionID))
const providers = createMemo(() => data.location.provider.list(session()?.location) ?? [])
const models = createMemo(() => data.location.model.list(session()?.location) ?? [])
const oauth = (provider: any) => {
const integration: any = (data.location.integration.list(session()?.location) ?? []).find(
(i) => i.id === provider.integrationID,
)
const credentials = (integration?.connections ?? []).filter((c: any) => c.type === "credential")
return credentials.length ? credentials.some((c: any) => c.method === "oauth") : undefined
}
// Which usage reading each provider is billed against; none for API keys and self-hosted.
const sources = createMemo(() => {
const out = new Map<string, Source>()
for (const p of providers() as any[]) {
const source = sourceOf({ id: p.id, baseURL: p.settings?.baseURL, oauth: oauth(p) })
if (source) out.set(p.id, source)
}
return out
})
// ---------------------------------------------------------------- context
const state = createMemo(() =>
contextUsage(data.session.message.list(props.sessionID), models(), session()?.revert?.messageID),
)
const cost = createMemo(() => data.session.cost(props.sessionID))
// Spent means something only when paying per token: not on a subscription, not self-hosted.
const paysPerToken = createMemo(() => {
const providerID = session()?.model?.providerID
const provider: any = providers().find((p) => p.id === providerID)
if (!provider) return true
if (isLocal(provider.settings?.baseURL)) return false
return oauth(provider) !== true
})
// ---------------------------------------------------------------- usage
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
let countdown: ReturnType<typeof setInterval> | undefined
async function poll() {
//pre-condition : mounted sidebar
if (controller.signal.aborted) return
//operation : independent readings, error reporting, scheduled retry
clearInterval(countdown)
setRetryAt(undefined)
setStatus((current) => ({
claude: current.claude === "error" ? "retrying" : current.claude,
codex: current.codex === "error" ? "retrying" : current.codex,
}))
const results = await readSources((signal) => fetchQuota(undefined, signal), fetchCodex, controller.signal)
if (controller.signal.aborted) return
const active = new Set(sources().values())
let failed = active.size === 0
const next = { ...status() }
for (const source of Object.keys(results) as Source[]) {
const result = results[source]
if ("error" in result) {
if (active.has(source)) console.error(`[usage-sidebar] ${source}: ${result.error}`)
next[source] = "error"
failed ||= active.has(source)
continue
}
next[source] = "ready"
setLive((d) => {
d.reading ??= {}
d.samples ??= {}
d.reading[source] = result.buckets
record((d.samples[source] ??= {}), result.buckets)
})
}
setStatus(next)
setNow(Date.now())
const delay = failed ? RETRY_MS : POLL_MS
if (failed) {
setRetryAt(Date.now() + delay)
countdown = setInterval(() => setNow(Date.now()), 1_000)
}
timer = setTimeout(() => void poll(), delay)
}
onCleanup(() => {
controller.abort()
clearTimeout(timer)
clearInterval(countdown)
})
void poll()
// One group per subscription in use; rows undefined means the reading went stale.
const groups = createMemo(() => {
const t = now()
const inUse = new Set(sources().values())
return (Object.keys(SOURCE_INFO) as Source[])
.filter((source) => inUse.has(source))
.flatMap((source) => {
const list = rows(live.reading[source] ?? [], live.samples[source] ?? {}, t)
return [{ source, ...SOURCE_INFO[source], rows: list, status: status()[source], pressure: providerPressureLabel(source, live.reading, t) }]
})
})
const color = (level: Level) =>
level === "crit"
? theme.text.feedback.error.base
: level === "warn"
? theme.text.feedback.warning.base
: level === "dim"
? theme.border.base
: theme.text.muted
const pad = (label: string) => (label.length > LABEL_WIDTH ? label.slice(0, LABEL_WIDTH - 1) + "…" : label.padEnd(LABEL_WIDTH))
// ---------------------------------------------------------------- view
return (
<box flexDirection="column">
<Show when={state() || (paysPerToken() && cost() > 0)}>
<box>
<text fg={theme.text.base}>
<b>Context</b>
</text>
<Show when={state()}>
{(value) => (
<>
<text fg={theme.text.muted}>{value().tokens.toLocaleString()} tokens</text>
<Show when={value().percent !== undefined}>
<text fg={theme.text.muted}>{value().percent}% used</text>
</Show>
</>
)}
</Show>
<Show when={paysPerToken() && cost() > 0}>
<text fg={theme.text.muted}>{money.format(cost())} spent</text>
</Show>
</box>
</Show>
<Show when={groups().length || !providers().length}>
<box paddingTop={1} flexDirection="column">
<text fg={theme.text.base}>
<b>Usage</b>
</text>
<Show when={!groups().length}>
<text fg={theme.text.muted}>Loading usage…</text>
</Show>
<For each={groups()}>
{(group) => (
<>
<text fg={theme.text.base} wrapMode="none">
<span style={{ fg: group.color }}>{glyphCell(group.icon)}</span> {group.name}
<Show when={group.pressure}>
{(pressure) => <span style={{ fg: theme.text.muted }}>{" " + pressure()}</span>}
</Show>
<Show when={statusText(group.status, !!group.rows, retrySeconds())}>
{(label) => <span style={{ fg: color("dim") }}>{label()}</span>}
</Show>
</text>
<For each={group.rows ?? []}>
{(row) => (
<text fg={theme.text.base} wrapMode="none">
{" "}
{pad(row.label)}{" "}
<span style={{ fg: color(row.cell.level) }}>{row.cell.text}</span>
<span style={{ fg: color(row.percent.level) }}>{" " + row.percent.text.padStart(PERCENT_WIDTH)}</span>
<span style={{ fg: theme.text.muted }}>%</span>
<span style={{ fg: color(row.extra.level) }}>{" " + row.extra.text}</span>
</text>
)}
</For>
</>
)}
</For>
</box>
</Show>
</box>
)
}
export default Plugin.define({
id: "usage-sidebar",
setup(context) {
return context.ui.slot({
prepend: "sidebar.content",
render: ({ sessionID }) => <Sidebar sessionID={sessionID} />,
})
},
})