opencode-account-quota 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +82 -2
- package/claude.js +351 -0
- package/codex.js +87 -0
- package/deepseek.js +102 -0
- package/index.js +12 -0
- package/inventory.js +43 -0
- package/package.json +33 -4
- package/preferences.js +97 -0
- package/routing.js +219 -0
- package/rpc.js +233 -0
- package/rules.js +259 -0
- package/server.js +617 -0
- package/sync.js +60 -0
- package/tui.tsx +623 -0
- package/view.js +954 -0
package/tui.tsx
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin/tui"
|
|
2
|
+
import { TextAttributes } from "@opentui/core"
|
|
3
|
+
import { useTerminalDimensions } from "@opentui/solid"
|
|
4
|
+
import { createMemo, createSignal, Index, onMount, Show } from "solid-js"
|
|
5
|
+
import { contract } from "./rpc.js"
|
|
6
|
+
import { createAdvisor, TURN_END } from "./rules.js"
|
|
7
|
+
import { createDedupe, createLoader } from "./sync.js"
|
|
8
|
+
import {
|
|
9
|
+
accountRefs, activeAccount, batchRefs, batchSummary, compactParts, conflicted, decide, KEYS, keyAction, modalLayout, nextExpiry, NO_REFRESH, refreshRpcError,
|
|
10
|
+
pickCurrency, pickDestination, proposalFrom, putRoute, routeMove, routeProposal, routeRemove, routeStep,
|
|
11
|
+
sessionRef, setAmount, shiftCurrency, staleRefs, startMinimum, startRoute, turnOff,
|
|
12
|
+
} from "./view.js"
|
|
13
|
+
|
|
14
|
+
// The command keeps its descriptive name in the palette; the modal itself has a short title.
|
|
15
|
+
const title = "Account quota and routing"
|
|
16
|
+
|
|
17
|
+
export default Plugin.define({
|
|
18
|
+
id: "account-quota.tui",
|
|
19
|
+
setup(context) {
|
|
20
|
+
let opening = false
|
|
21
|
+
let shown = false
|
|
22
|
+
let asking = false
|
|
23
|
+
let batching = false
|
|
24
|
+
let target: unknown
|
|
25
|
+
const [snapshot, setSnapshot] = createSignal<any>()
|
|
26
|
+
const [failed, setFailed] = createSignal(false)
|
|
27
|
+
const [now, setNow] = createSignal(Date.now())
|
|
28
|
+
const [cursor, setCursor] = createSignal<string>()
|
|
29
|
+
const [minimum, setMinimum] = createSignal<any>()
|
|
30
|
+
// The route order draft (rotation plan R3), edited locally until Save; its preview reads nothing.
|
|
31
|
+
const [route, setRoute] = createSignal<any>()
|
|
32
|
+
const [message, setMessage] = createSignal<string>()
|
|
33
|
+
const [tick, setTick] = createSignal(0)
|
|
34
|
+
const advisor = createAdvisor()
|
|
35
|
+
// All the advisor may look at: the snapshot held here, at one instant. Never a request.
|
|
36
|
+
const view = (held: any, at: number) => ({
|
|
37
|
+
account: (sel: any) => activeAccount(held, sel),
|
|
38
|
+
evaluate: (sel: any) => decide(withCatalog(held), sel, at),
|
|
39
|
+
})
|
|
40
|
+
// While a notice is up, one timeout at the next instant a held sample reaches its TTL or reset, so the notice
|
|
41
|
+
// is revalidated then and not at the next turn. Not a per-second countdown.
|
|
42
|
+
let expiry: ReturnType<typeof setTimeout> | undefined
|
|
43
|
+
const revise = () => {
|
|
44
|
+
clearTimeout(expiry)
|
|
45
|
+
expiry = undefined
|
|
46
|
+
const at = advisor.pending() ? nextExpiry(snapshot(), Date.now()) : undefined
|
|
47
|
+
if (at !== undefined) {
|
|
48
|
+
expiry = setTimeout(() => {
|
|
49
|
+
const moment = Date.now()
|
|
50
|
+
setNow(moment)
|
|
51
|
+
advisor.observe(view(snapshot(), moment))
|
|
52
|
+
revise()
|
|
53
|
+
}, Math.max(0, at - Date.now()) + 25)
|
|
54
|
+
}
|
|
55
|
+
setTick((n) => n + 1)
|
|
56
|
+
}
|
|
57
|
+
// `context.client` is read per call: it changes when the TUI reconnects to a restarted server.
|
|
58
|
+
const rpc = () => context.client.rpc(contract)
|
|
59
|
+
// The route order and this session's routing mode travel with the snapshot. A server without `routingView` (an
|
|
60
|
+
// older plugin) leaves it unavailable; the accounts still load.
|
|
61
|
+
const sessionOnScreen = () => {
|
|
62
|
+
const route = context.ui.router.current()
|
|
63
|
+
return route.type === "session" ? route.sessionID : undefined
|
|
64
|
+
}
|
|
65
|
+
const loader = createLoader({
|
|
66
|
+
read: async (location) => {
|
|
67
|
+
const sessionID = sessionOnScreen()
|
|
68
|
+
const [value, routing] = await Promise.all([rpc().snapshot({}, { location }),
|
|
69
|
+
rpc().routingView(sessionID ? { sessionID } : {}, { location }).catch(() => ({ state: "unavailable" }))])
|
|
70
|
+
return { ...value, routing }
|
|
71
|
+
},
|
|
72
|
+
apply: (value) => {
|
|
73
|
+
const at = Date.now()
|
|
74
|
+
// The data held until now is checked at this instant before it is replaced: a notice whose sample went
|
|
75
|
+
// stale or failed meanwhile is withdrawn and cannot come back with the new read. Then the new data.
|
|
76
|
+
advisor.observe(view(snapshot(), at))
|
|
77
|
+
setSnapshot(value)
|
|
78
|
+
setFailed(false)
|
|
79
|
+
setNow(at)
|
|
80
|
+
advisor.observe(view(value, at))
|
|
81
|
+
revise()
|
|
82
|
+
},
|
|
83
|
+
fail: () => setFailed(true),
|
|
84
|
+
})
|
|
85
|
+
// Freshness changes with time; minute-level text, no per-second countdown. Only the modal's relative texts ("3 min
|
|
86
|
+
// ago", Stale) need it, so it runs while the modal is open; otherwise each reload (`apply`) and the notice's expiry
|
|
87
|
+
// timer (`revise`) move `now`.
|
|
88
|
+
let clock: ReturnType<typeof setInterval> | undefined
|
|
89
|
+
|
|
90
|
+
function location() {
|
|
91
|
+
const route = context.ui.router.current()
|
|
92
|
+
return route.type === "session"
|
|
93
|
+
? context.data.session.get(route.sessionID)?.location
|
|
94
|
+
: context.location ?? context.data.location.default()
|
|
95
|
+
}
|
|
96
|
+
const load = (where = location()) => {
|
|
97
|
+
if (where) target = where
|
|
98
|
+
return loader.invalidate(where)
|
|
99
|
+
}
|
|
100
|
+
const selection = () => context.ui.model.current()
|
|
101
|
+
const withCatalog = (held: any) => held && { ...held, catalog: context.data.location.model.list(location()) }
|
|
102
|
+
async function pickerCatalog() {
|
|
103
|
+
const where = location()
|
|
104
|
+
const models = context.data.location.model
|
|
105
|
+
if (models.list(where) === undefined) await models.sync(where).catch(() => {})
|
|
106
|
+
return models.list(where)
|
|
107
|
+
}
|
|
108
|
+
// The notice of the session on screen, revalidated with the held snapshot and the clock on every render.
|
|
109
|
+
const notice = () => {
|
|
110
|
+
tick()
|
|
111
|
+
const route = context.ui.router.current()
|
|
112
|
+
const sel = selection()
|
|
113
|
+
const held = snapshot()
|
|
114
|
+
if (route.type !== "session" || !sel || !held || failed()) return undefined
|
|
115
|
+
const current = advisor.current({ sessionID: route.sessionID, selection: sel, ...view(held, now()) })
|
|
116
|
+
return current && { ...current, integrationID: current.selection.providerID }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let stopChanged = () => {}
|
|
120
|
+
const listen = () => {
|
|
121
|
+
stopChanged()
|
|
122
|
+
// A new subscription starts afresh: a copy of a change seen before it still reloads.
|
|
123
|
+
const first = createDedupe()
|
|
124
|
+
try {
|
|
125
|
+
stopChanged = context.client.rpc(contract).events.on("changed", (event: any) => {
|
|
126
|
+
// A repeated copy is dropped first, so a revision that does not reload is seen too. Without the modal, a notice
|
|
127
|
+
// or an episode nobody uses the snapshot until the next turn end or opening, and both read it again.
|
|
128
|
+
if (first(event?.data?.revision) && (shown || opening || advisor.watching())) void loader.invalidate()
|
|
129
|
+
})
|
|
130
|
+
} catch {
|
|
131
|
+
stopChanged = () => {}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
listen()
|
|
135
|
+
const stops: Array<() => void> = []
|
|
136
|
+
try {
|
|
137
|
+
// Events missed while disconnected are not replayed: resubscribe and read the current snapshot.
|
|
138
|
+
stops.push(context.data.on("server.connected" as never, () => {
|
|
139
|
+
listen()
|
|
140
|
+
void loader.invalidate()
|
|
141
|
+
}))
|
|
142
|
+
} catch {}
|
|
143
|
+
// Turn end of the session on screen first reads the plugin's own snapshot again, so the usage of that turn's last
|
|
144
|
+
// step counts, then evaluates it: a local read, no provider queried, no switch, no prompt (B03.5). It is the only
|
|
145
|
+
// place a notice is born. A failed read evaluates whatever snapshot is held.
|
|
146
|
+
const onTurn = async (event: any) => {
|
|
147
|
+
const before = context.ui.router.current()
|
|
148
|
+
if (before.type !== "session" || event?.data?.sessionID !== before.sessionID) return
|
|
149
|
+
await load()
|
|
150
|
+
// Route, selection and snapshot may have changed during the read.
|
|
151
|
+
const route = context.ui.router.current()
|
|
152
|
+
const sel = selection()
|
|
153
|
+
const held = snapshot()
|
|
154
|
+
if (route.type !== "session" || !sel || !held) return
|
|
155
|
+
advisor.turnEnded(event, { sessionID: route.sessionID, selection: sel, ...view(held, Date.now()) })
|
|
156
|
+
revise()
|
|
157
|
+
}
|
|
158
|
+
for (const type of TURN_END) {
|
|
159
|
+
try {
|
|
160
|
+
stops.push(context.data.on(type as never, (event: any) => void onTurn(event).catch(() => {})))
|
|
161
|
+
} catch {}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Native theme roles only, no fixed colors; color only adds to the words. Feedback tokens are state objects
|
|
165
|
+
// (`text.feedback.error.base`); some may be missing in older hosts, so every role falls back to the main text.
|
|
166
|
+
// The dialog surface, when the host offers it, is what native dialogs draw on; the focused row uses the host's own
|
|
167
|
+
// list focus (`background/text.action.primary.focused`, `text.formfield.focused` for its margin).
|
|
168
|
+
const theme: any = context.theme
|
|
169
|
+
const surface = () => {
|
|
170
|
+
try {
|
|
171
|
+
return (typeof theme.surface === "function" && theme.surface("dialog")) || theme
|
|
172
|
+
} catch {
|
|
173
|
+
return theme
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const focusBg = () => surface().background?.action?.primary?.focused
|
|
177
|
+
const focusFg = () => (focusBg() ? surface().text?.action?.primary?.focused : undefined) ?? tone("base")
|
|
178
|
+
function tone(name?: string): any {
|
|
179
|
+
const text = surface().text ?? theme.text
|
|
180
|
+
const role = (read: (t: any) => any) => read(text) ?? read(theme.text)
|
|
181
|
+
if (name?.startsWith("icon:")) {
|
|
182
|
+
const scale = (surface().categorical ?? theme.categorical)?.[Number(name.slice(5))]
|
|
183
|
+
return scale?.[400] ?? text.action?.primary?.base ?? text.base ?? theme.text.base
|
|
184
|
+
}
|
|
185
|
+
return (name === "error" ? role((t) => t?.feedback?.error?.base)
|
|
186
|
+
: name === "warning" ? role((t) => t?.feedback?.warning?.base)
|
|
187
|
+
: name === "success" ? role((t) => t?.feedback?.success?.base)
|
|
188
|
+
: name === "info" ? role((t) => t?.feedback?.info?.base) ?? role((t) => t?.muted)
|
|
189
|
+
: name === "muted" ? role((t) => t?.muted)
|
|
190
|
+
: name === "faint" ? role((t) => t?.faint) ?? role((t) => t?.muted)
|
|
191
|
+
: name === "accent" ? text.action?.primary?.base
|
|
192
|
+
: name === "focus" ? role((t) => t?.formfield?.focused) ?? focusFg()
|
|
193
|
+
: undefined) ?? text.base ?? theme.text.base
|
|
194
|
+
}
|
|
195
|
+
// Chips: a key of the footer or a count on the raised background; a state on its feedback background.
|
|
196
|
+
const chipBg = (name?: string) => {
|
|
197
|
+
const background = surface().background ?? theme.background
|
|
198
|
+
return name === "key" ? background?.raised?.high ?? theme.background?.raised?.high
|
|
199
|
+
: background?.feedback?.[name ?? ""]?.base ?? theme.background?.feedback?.[name ?? ""]?.base
|
|
200
|
+
}
|
|
201
|
+
const chipFg = (name?: string) => (name === "key" ? tone("base") : tone(name))
|
|
202
|
+
const rule = () => surface().border?.base ?? theme.border?.base ?? tone("muted")
|
|
203
|
+
// In the focused row the words take the focus color; marks and chips keep theirs.
|
|
204
|
+
const partFg = (part: any, focused: boolean) => (part.chip ? chipFg(part.tone) : focused && !part.keep ? focusFg() : tone(part.tone))
|
|
205
|
+
const partBg = (part: any, focused: boolean) => (part.chip ? chipBg(part.tone) : focused ? focusBg() : undefined)
|
|
206
|
+
|
|
207
|
+
const idle = () => !minimum() && !route() && !asking
|
|
208
|
+
// Account rows in screen order.
|
|
209
|
+
const refs = () => accountRefs(snapshot())
|
|
210
|
+
const step = (delta: number) => {
|
|
211
|
+
const list = refs()
|
|
212
|
+
if (list.length === 0) return
|
|
213
|
+
const index = list.indexOf(cursor() ?? "")
|
|
214
|
+
setCursor(list[index < 0 ? 0 : Math.max(0, Math.min(list.length - 1, index + delta))])
|
|
215
|
+
}
|
|
216
|
+
const selected = () => (cursor() ? (JSON.parse(cursor() as string) as [string, string]) : undefined)
|
|
217
|
+
|
|
218
|
+
// `manual` marks a read the user asked for; reads started by opening the view never carry it.
|
|
219
|
+
async function refresh(integrationID: string, connectionID: string, manual: boolean) {
|
|
220
|
+
try {
|
|
221
|
+
return (await rpc().refresh({ integrationID, connectionID, ...(manual ? { manual: true } : {}) }, { location: target })).status
|
|
222
|
+
} catch (error) {
|
|
223
|
+
return refreshRpcError(error)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
async function refreshSelected() {
|
|
227
|
+
const ref = selected()
|
|
228
|
+
if (!ref || minimum() || route()) return
|
|
229
|
+
const integration = snapshot()?.integrations.find((i: any) => i.id === ref[0])
|
|
230
|
+
// An account without a reader: one short line says so, nothing is called. With `experimentalClaudeUsage`, `r` on
|
|
231
|
+
// Claude reads Claude Code `/usage` once (manual reader).
|
|
232
|
+
if (!integration?.refreshable) {
|
|
233
|
+
setMessage(NO_REFRESH)
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
setMessage("Refreshing…")
|
|
237
|
+
const status = await refresh(ref[0], ref[1], true)
|
|
238
|
+
setMessage(status === "read" ? undefined
|
|
239
|
+
: status.startsWith("RPC: ") ? status
|
|
240
|
+
: status === "deferred" ? "Refresh deferred after a failure. Try again later."
|
|
241
|
+
: status === "unsupported" ? NO_REFRESH
|
|
242
|
+
: "Refresh failed.")
|
|
243
|
+
await load(target)
|
|
244
|
+
}
|
|
245
|
+
// Each manual read goes through the same per-account RPC and shared scheduler as `r`.
|
|
246
|
+
async function refreshAll() {
|
|
247
|
+
if (batching || minimum()) return
|
|
248
|
+
const due = batchRefs(snapshot())
|
|
249
|
+
if (due.length === 0) {
|
|
250
|
+
setMessage("No accounts available to refresh.")
|
|
251
|
+
return
|
|
252
|
+
}
|
|
253
|
+
batching = true
|
|
254
|
+
setMessage("Refreshing accounts…")
|
|
255
|
+
try {
|
|
256
|
+
const statuses = await Promise.all(due.map((ref) => refresh(ref.integrationID, ref.connectionID, true)))
|
|
257
|
+
setMessage(batchSummary(statuses))
|
|
258
|
+
} finally {
|
|
259
|
+
batching = false
|
|
260
|
+
}
|
|
261
|
+
await load(target)
|
|
262
|
+
}
|
|
263
|
+
function beginMinimum() {
|
|
264
|
+
const next = startMinimum(snapshot())
|
|
265
|
+
setMessage(next ? undefined : "The low-balance notice cannot be edited now.")
|
|
266
|
+
if (next) setMinimum(next)
|
|
267
|
+
}
|
|
268
|
+
// Native dialogs replace their parent. Keep the draft alive for the whole picker sequence and restore it once.
|
|
269
|
+
async function subdialog<T>(run: () => Promise<T>): Promise<T | undefined> {
|
|
270
|
+
if (asking || !shown) return
|
|
271
|
+
asking = true
|
|
272
|
+
try {
|
|
273
|
+
const value = await run()
|
|
274
|
+
return shown ? value : undefined
|
|
275
|
+
} catch {
|
|
276
|
+
if (shown) setMessage("Could not open the dialog.")
|
|
277
|
+
} finally {
|
|
278
|
+
asking = false
|
|
279
|
+
if (shown) showModal()
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const pick = (options: any) => shown ? context.ui.dialog.select<any>(options) : Promise.resolve(undefined)
|
|
283
|
+
async function editAmount() {
|
|
284
|
+
const draft = minimum()
|
|
285
|
+
if (!draft || asking) return
|
|
286
|
+
const value = await subdialog(() => context.ui.dialog.prompt({ title: `DeepSeek ${draft.currency} low-balance notice`, placeholder: "Amount, for example 0.20" }))
|
|
287
|
+
if (minimum() !== draft) return
|
|
288
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
289
|
+
setMessage("Amount unchanged.")
|
|
290
|
+
return
|
|
291
|
+
}
|
|
292
|
+
const next = setAmount(draft, value)
|
|
293
|
+
setMessage(next ? undefined : "Use digits and an optional dot, like 0.20.")
|
|
294
|
+
if (next) setMinimum(next)
|
|
295
|
+
}
|
|
296
|
+
// Route order: `o` opens a draft of the stored list; Save sends it whole with the route order's own revision.
|
|
297
|
+
function beginRoute() {
|
|
298
|
+
const next = startRoute(snapshot())
|
|
299
|
+
setMessage(next ? undefined : "The route order cannot be edited now.")
|
|
300
|
+
if (next) setRoute(next)
|
|
301
|
+
}
|
|
302
|
+
const changeRoute = (next: any, failure?: string) => {
|
|
303
|
+
if (next) setRoute(next)
|
|
304
|
+
setMessage(next ? undefined : failure)
|
|
305
|
+
}
|
|
306
|
+
async function editRoute(add = false) {
|
|
307
|
+
const draft = route()
|
|
308
|
+
if (!draft || asking) return
|
|
309
|
+
const item = draft.targets[draft.index]
|
|
310
|
+
await subdialog(async () => {
|
|
311
|
+
const edit = add || !item ? "add" : await pick({ title: "Edit destination", options: [
|
|
312
|
+
{ title: "Model", value: "model" }, { title: "Effort", value: "effort" }, { title: "Change account", value: "account" },
|
|
313
|
+
...(draft.index > 0 ? [{ title: "Move up", value: "up" }] : []),
|
|
314
|
+
...(draft.index + 1 < draft.targets.length ? [{ title: "Move down", value: "down" }] : []),
|
|
315
|
+
{ title: "Remove from order", value: "remove" },
|
|
316
|
+
] })
|
|
317
|
+
if (!edit || route() !== draft) return
|
|
318
|
+
if (edit === "up" || edit === "down") return changeRoute(routeMove(draft, edit === "up" ? -1 : 1))
|
|
319
|
+
if (edit === "remove") return changeRoute(routeRemove(draft))
|
|
320
|
+
const row = await pickDestination({ snapshot: snapshot(), target: item, edit, selection: sessionOnScreen() ? selection() : undefined, catalog: pickerCatalog, pick })
|
|
321
|
+
if (row && route() === draft) changeRoute(putRoute(draft, row, edit === "add" ? draft.targets.length : draft.index),
|
|
322
|
+
"Already in this order, or the list is full.")
|
|
323
|
+
})
|
|
324
|
+
}
|
|
325
|
+
async function routeOptions() {
|
|
326
|
+
const prefs = snapshot()?.preferences
|
|
327
|
+
const sess = snapshot()?.routing?.session
|
|
328
|
+
const watching = sess?.mode === "preview"
|
|
329
|
+
const last = sess?.decision
|
|
330
|
+
const draft = route()
|
|
331
|
+
if (!draft || asking) return
|
|
332
|
+
const choice = await subdialog(async () => {
|
|
333
|
+
const what = await pick({ title: "Order options", options: [
|
|
334
|
+
{ title: "Quota threshold", value: "threshold", footer: `${prefs?.threshold ?? "—"}%`, disabled: prefs?.state !== "available" },
|
|
335
|
+
...(sess ? [{ title: watching ? "Stop watching turns" : "Watch turn ends", value: "watch",
|
|
336
|
+
description: last ? `Last turn: ${last.kind === "suggest" ? `choice ${last.target + 1}` : last.kind}${last.reason ? ` · ${last.reason}` : ""}` : undefined },
|
|
337
|
+
{ title: sess.paid ? "Exclude metered API" : "Allow metered API", value: "paid",
|
|
338
|
+
description: watching ? "For this session's turn previews" : "Also starts watching this session" }] : []),
|
|
339
|
+
] })
|
|
340
|
+
if (what !== "threshold") return what
|
|
341
|
+
return pick({ title: "Quota threshold", current: prefs.threshold, options: Array.from({ length: 11 }, (_, i) => ({ title: `${90 + i}% used`, value: 90 + i })) })
|
|
342
|
+
})
|
|
343
|
+
if (choice === undefined || route() !== draft) return
|
|
344
|
+
if (choice === "watch") return sessionMode((s) => ({ mode: s.mode === "preview" ? "off" : "preview", paid: s.mode === "preview" ? false : s.paid }))
|
|
345
|
+
if (choice === "paid") return sessionMode((s) => ({ mode: "preview", paid: !s.paid }))
|
|
346
|
+
try {
|
|
347
|
+
await rpc().savePreferences(proposalFrom(snapshot(), { revision: prefs.revision, threshold: choice }), { location: target })
|
|
348
|
+
setMessage(`Threshold saved: ${choice}% used.`)
|
|
349
|
+
} catch (error: any) {
|
|
350
|
+
setMessage(conflicted(error) ? "Preferences changed. Reload before saving." : "Threshold was not saved.")
|
|
351
|
+
}
|
|
352
|
+
await load(target)
|
|
353
|
+
}
|
|
354
|
+
// Watching and paid consent belong to the session on screen, in the server's memory only; they apply at once.
|
|
355
|
+
async function sessionMode(change: (session: any) => any) {
|
|
356
|
+
const sessionID = sessionOnScreen()
|
|
357
|
+
const session = snapshot()?.routing?.session
|
|
358
|
+
if (!route() || !sessionID || !session) return setMessage("Open a session to watch its turns.")
|
|
359
|
+
const next = change(session)
|
|
360
|
+
try {
|
|
361
|
+
await rpc().setSessionRouting({ sessionID, mode: next.mode, paid: next.paid }, { location: target })
|
|
362
|
+
setMessage(next.mode === "preview" ? `Watching this session's turns · Paid API ${next.paid ? "allowed" : "not allowed"}.` : "Not watching this session.")
|
|
363
|
+
} catch {
|
|
364
|
+
setMessage("The session mode was not changed.")
|
|
365
|
+
}
|
|
366
|
+
await load(target)
|
|
367
|
+
}
|
|
368
|
+
async function saveRoute() {
|
|
369
|
+
const draft = route()
|
|
370
|
+
if (!draft || asking) return
|
|
371
|
+
try {
|
|
372
|
+
await rpc().saveRouting(routeProposal(draft), { location: target })
|
|
373
|
+
setMessage("Route order saved.")
|
|
374
|
+
setRoute(undefined)
|
|
375
|
+
} catch (error: any) {
|
|
376
|
+
setMessage(conflicted(error) ? "Order changed elsewhere. Reopen it to load the latest order." : "Route order was not saved.")
|
|
377
|
+
}
|
|
378
|
+
await load(target)
|
|
379
|
+
}
|
|
380
|
+
// The notice minimum goes through the preferences flow (`snapshot.preferences.revision`), keeping the stored order
|
|
381
|
+
// and threshold.
|
|
382
|
+
async function save() {
|
|
383
|
+
if (route()) return saveRoute()
|
|
384
|
+
const draft = minimum()
|
|
385
|
+
if (!draft || asking) return
|
|
386
|
+
try {
|
|
387
|
+
await rpc().savePreferences(proposalFrom(snapshot(), draft), { location: target })
|
|
388
|
+
setMessage("Low-balance notice saved.")
|
|
389
|
+
} catch (error: any) {
|
|
390
|
+
setMessage(conflicted(error) ? "Preferences changed. Reload before saving." : "Low-balance notice was not saved.")
|
|
391
|
+
}
|
|
392
|
+
setMinimum(undefined)
|
|
393
|
+
await load(target)
|
|
394
|
+
}
|
|
395
|
+
// Esc cancels an open edit and keeps the modal; otherwise it lets the host close the modal (return false).
|
|
396
|
+
function escape() {
|
|
397
|
+
if (!minimum() && !route()) return false
|
|
398
|
+
setMinimum(undefined)
|
|
399
|
+
setRoute(undefined)
|
|
400
|
+
setMessage(undefined)
|
|
401
|
+
}
|
|
402
|
+
// A click on `esc` at the top right does what the key does.
|
|
403
|
+
const close = () => {
|
|
404
|
+
if (escape() === false) context.ui.dialog.clear()
|
|
405
|
+
}
|
|
406
|
+
// One table of actions for the keys and the clicks on the footer, so both always run the same with the same guards.
|
|
407
|
+
const actions: Record<string, () => void> = {
|
|
408
|
+
refresh: () => void refreshSelected(),
|
|
409
|
+
refreshAll: () => { if (idle()) void refreshAll() },
|
|
410
|
+
notice: () => { if (idle()) beginMinimum() },
|
|
411
|
+
amount: () => void editAmount(),
|
|
412
|
+
off: () => { if (minimum() && !asking) setMinimum(turnOff(minimum())) },
|
|
413
|
+
save: () => void save(),
|
|
414
|
+
dismiss: () => { if (notice()) { advisor.dismiss(); revise() } },
|
|
415
|
+
route: () => { if (idle()) beginRoute() },
|
|
416
|
+
routeAdd: () => void editRoute(true),
|
|
417
|
+
routeEdit: () => void editRoute(),
|
|
418
|
+
routeOptions: () => void routeOptions(),
|
|
419
|
+
}
|
|
420
|
+
const perform = (action?: string) => {
|
|
421
|
+
if (action && actions[action]) actions[action]()
|
|
422
|
+
}
|
|
423
|
+
// A click on a row: an account or a provider's first account moves the cursor (never while the notice editor is
|
|
424
|
+
// open); a currency row of the editor selects it; a destination row of the route order selects that row.
|
|
425
|
+
function choose(click: any) {
|
|
426
|
+
if (!click || asking) return
|
|
427
|
+
if (route()) {
|
|
428
|
+
if (click.kind === "route") {
|
|
429
|
+
setRoute({ ...route(), index: click.index })
|
|
430
|
+
void editRoute()
|
|
431
|
+
}
|
|
432
|
+
return
|
|
433
|
+
}
|
|
434
|
+
const draft = minimum()
|
|
435
|
+
if (click.kind === "currency") {
|
|
436
|
+
if (draft) setMinimum(pickCurrency(draft, click.currency))
|
|
437
|
+
return
|
|
438
|
+
}
|
|
439
|
+
if (draft) return
|
|
440
|
+
setCursor(click.ref)
|
|
441
|
+
}
|
|
442
|
+
// The wheel over the list moves the cursor as the arrow keys do.
|
|
443
|
+
const wheel = (event: any) => {
|
|
444
|
+
if (minimum() || asking) return
|
|
445
|
+
const direction = event?.scroll?.direction
|
|
446
|
+
if (direction === "up") arrow(-1)
|
|
447
|
+
else if (direction === "down") arrow(1)
|
|
448
|
+
}
|
|
449
|
+
const left = (event: any) => event?.button === 0
|
|
450
|
+
// ↑↓ and the wheel: the route row in the route editor, the currency in the notice editor, otherwise the account.
|
|
451
|
+
function arrow(delta: number) {
|
|
452
|
+
if (route()) setRoute(routeStep(route(), delta))
|
|
453
|
+
else if (minimum()) setMinimum(shiftCurrency(minimum(), delta))
|
|
454
|
+
else step(delta)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function AccountModal() {
|
|
458
|
+
context.ui.dialog.set({ size: "xlarge", centered: true })
|
|
459
|
+
const size = useTerminalDimensions()
|
|
460
|
+
// Keys of the modal only, gone with it; above the host's own dialog keys so Esc can cancel an edit first.
|
|
461
|
+
context.keymap.layer(() => ({
|
|
462
|
+
mode: "modal",
|
|
463
|
+
priority: 10,
|
|
464
|
+
commands: [
|
|
465
|
+
{ bind: "escape", run: escape },
|
|
466
|
+
{ bind: "up", run: () => arrow(-1) },
|
|
467
|
+
{ bind: "down", run: () => arrow(1) },
|
|
468
|
+
...Object.keys(KEYS).map((bind) => ({ bind, run: () => perform(keyAction(bind, { route: route(), minimum: minimum() })) })),
|
|
469
|
+
],
|
|
470
|
+
}))
|
|
471
|
+
// Two panels when wide, one column otherwise. The list scrolls with the focused account (or the open editor) and
|
|
472
|
+
// moves only as far as needed; every row is at most its panel's width, so one row is one physical line.
|
|
473
|
+
let start = 0
|
|
474
|
+
const layout = createMemo(() => {
|
|
475
|
+
const value = modalLayout(route() ? withCatalog(snapshot()) : snapshot(), {
|
|
476
|
+
now: now(), cursor: cursor(), minimum: minimum(), route: route(), selection: route() && !sessionOnScreen() ? undefined : selection(), columns: size().width,
|
|
477
|
+
rows: size().height, start, notice: notice(), message: message(), flags: { failed: failed() },
|
|
478
|
+
})
|
|
479
|
+
start = value.start
|
|
480
|
+
return value
|
|
481
|
+
})
|
|
482
|
+
const divider = () => Array.from({ length: layout().height }, () => " │ ")
|
|
483
|
+
// A row is drawn as its parts (margin, dot, alias, chips, figure, meter fill and track) in their own roles; the
|
|
484
|
+
// focused row in the host's list focus colors, bold, with its ┃ margin, so it reads without color too. A click
|
|
485
|
+
// on any line of an account, provider or currency row picks it.
|
|
486
|
+
const Line = (props: { row: () => any }) => {
|
|
487
|
+
const parts = () => props.row().parts ?? [{ text: props.row().text, tone: props.row().tone }]
|
|
488
|
+
const focused = () => !!props.row().selected
|
|
489
|
+
return (
|
|
490
|
+
<text fg={focused() ? focusFg() : tone(props.row().tone)} bg={focused() ? focusBg() : undefined}
|
|
491
|
+
attributes={props.row().bold || focused() ? TextAttributes.BOLD : 0} wrapMode="none"
|
|
492
|
+
onMouseDown={(event: any) => { if (left(event) && props.row().click?.kind !== "route") choose(props.row().click) }}
|
|
493
|
+
onMouseUp={(event: any) => { if (left(event) && props.row().click?.kind === "route") choose(props.row().click) }}>
|
|
494
|
+
<Index each={parts()}>
|
|
495
|
+
{(part: () => any) => <span style={{ fg: partFg(part(), focused()), bg: partBg(part(), focused()) }}>{part().text}</span>}
|
|
496
|
+
</Index>
|
|
497
|
+
</text>
|
|
498
|
+
)
|
|
499
|
+
}
|
|
500
|
+
// One line of keys, centered; each key with its action is one text that runs it on a click.
|
|
501
|
+
const Keys = (props: { line: () => any }) => (
|
|
502
|
+
<box flexDirection="row" height={1} gap={props.line().gap} paddingLeft={props.line().left}>
|
|
503
|
+
<Index each={props.line().cells}>
|
|
504
|
+
{(item: () => any) => (
|
|
505
|
+
<text width={item().width} height={1} wrapMode="none" onMouseUp={(event: any) => { if (left(event)) perform(item().action) }}>
|
|
506
|
+
<span style={{ fg: tone("base"), attributes: TextAttributes.BOLD }}>{item().keyText}</span>
|
|
507
|
+
<span style={{ fg: tone("muted") }}>{` ${item().label}`}</span>
|
|
508
|
+
</text>
|
|
509
|
+
)}
|
|
510
|
+
</Index>
|
|
511
|
+
</box>
|
|
512
|
+
)
|
|
513
|
+
const List = (props: { rows: () => any[] }) => <Index each={props.rows()}>{(row: () => any) => <Line row={row} />}</Index>
|
|
514
|
+
return (
|
|
515
|
+
<box flexDirection="column" paddingLeft={2} paddingRight={2} paddingBottom={1}>
|
|
516
|
+
<box flexDirection="row" justifyContent="space-between">
|
|
517
|
+
<text fg={tone("base")} wrapMode="none"><b>{layout().header.title}</b></text>
|
|
518
|
+
<text fg={tone("muted")} wrapMode="none" onMouseUp={(event: any) => { if (left(event)) close() }}>esc</text>
|
|
519
|
+
</box>
|
|
520
|
+
<text fg={rule()} wrapMode="none">{"─".repeat(layout().width)}</text>
|
|
521
|
+
{/* One text node per line position, updated in place: a new snapshot changes words, not the node tree. */}
|
|
522
|
+
<Show when={layout().mode === "split"} fallback={
|
|
523
|
+
<box flexDirection="column" height={layout().height} onMouseScroll={wheel}><List rows={() => layout().left.rows} /></box>
|
|
524
|
+
}>
|
|
525
|
+
<box flexDirection="row">
|
|
526
|
+
<box flexDirection="column" width={layout().left.width} flexShrink={0} onMouseScroll={wheel}>
|
|
527
|
+
<List rows={() => layout().left.rows} />
|
|
528
|
+
</box>
|
|
529
|
+
<box flexDirection="column" width={3} flexShrink={0}>
|
|
530
|
+
<Index each={divider()}>{(line: () => string) => <text fg={rule()} wrapMode="none">{line()}</text>}</Index>
|
|
531
|
+
</box>
|
|
532
|
+
<box flexDirection="column" flexGrow={1}><List rows={() => layout().right.rows} /></box>
|
|
533
|
+
</box>
|
|
534
|
+
</Show>
|
|
535
|
+
<List rows={() => layout().alerts} />
|
|
536
|
+
<text fg={rule()} wrapMode="none">{"─".repeat(layout().width)}</text>
|
|
537
|
+
<Index each={layout().footer}>{(line: () => any) => <Keys line={line} />}</Index>
|
|
538
|
+
</box>
|
|
539
|
+
)
|
|
540
|
+
}
|
|
541
|
+
// Only our own child dialogs retain the draft when the parent is replaced.
|
|
542
|
+
function showModal() {
|
|
543
|
+
// Also called when a child dialog returns: never a second interval.
|
|
544
|
+
clock ??= setInterval(() => setNow(Date.now()), 30_000)
|
|
545
|
+
context.ui.dialog.show(() => <AccountModal />, () => {
|
|
546
|
+
if (asking) return
|
|
547
|
+
clearInterval(clock)
|
|
548
|
+
clock = undefined
|
|
549
|
+
shown = false
|
|
550
|
+
setMinimum(undefined)
|
|
551
|
+
setRoute(undefined)
|
|
552
|
+
setMessage(undefined)
|
|
553
|
+
})
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// `/quota`, the palette and a click on the composer line. The cursor starts on the account in use for the
|
|
557
|
+
// session's model, so the detail shows at once what the composer line used to say; otherwise where it was, or the
|
|
558
|
+
// first account.
|
|
559
|
+
async function open() {
|
|
560
|
+
if (opening || shown) return
|
|
561
|
+
opening = true
|
|
562
|
+
try {
|
|
563
|
+
const where = location()
|
|
564
|
+
if (!where) throw new Error("Unknown location")
|
|
565
|
+
listen()
|
|
566
|
+
await load(where)
|
|
567
|
+
if (failed()) throw new Error("Account data is unavailable")
|
|
568
|
+
const list = refs()
|
|
569
|
+
const session = sessionRef(snapshot(), selection())
|
|
570
|
+
setCursor(session && list.includes(session) ? session : list.includes(cursor() ?? "") ? cursor() : list[0])
|
|
571
|
+
shown = true
|
|
572
|
+
showModal()
|
|
573
|
+
// Reads only accounts whose data is missing or stale, once per opening (B06.1). A manual reader (the
|
|
574
|
+
// experimental Codex one, Claude's /usage) is never listed: it reads only when the user presses r or a.
|
|
575
|
+
const due = staleRefs(snapshot(), Date.now())
|
|
576
|
+
if (due.length > 0) void Promise.all(due.map((ref) => refresh(ref.integrationID, ref.connectionID, false))).then(() => load(target))
|
|
577
|
+
} catch {
|
|
578
|
+
context.ui.toast.show({ title, message: "Account data is unavailable.", variant: "error" })
|
|
579
|
+
} finally {
|
|
580
|
+
opening = false
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function CompactLine() {
|
|
585
|
+
// Local inventory and preferences only; no provider is queried by showing this line. It stays mounted with
|
|
586
|
+
// nothing to draw: its first load is the snapshot a turn end is evaluated against.
|
|
587
|
+
onMount(() => void load())
|
|
588
|
+
const parts = () => (failed() ? undefined : compactParts(snapshot(), selection(), notice()))
|
|
589
|
+
const lineTone = (name: string) => (name === "warning" ? theme.text.feedback?.warning?.base ?? theme.text.base : theme.text.muted)
|
|
590
|
+
// Only while a turn-end notice is up; a click on it opens the modal.
|
|
591
|
+
return (
|
|
592
|
+
<Show when={parts()}>
|
|
593
|
+
{(list: () => any[]) => (
|
|
594
|
+
<text fg={context.theme.text.muted} wrapMode="word" onMouseUp={(event: any) => { if (left(event)) void open() }}>
|
|
595
|
+
<Index each={list()}>{(part: () => any) => <span style={{ fg: lineTone(part().tone) }}>{part().text}</span>}</Index>
|
|
596
|
+
</text>
|
|
597
|
+
)}
|
|
598
|
+
</Show>
|
|
599
|
+
)
|
|
600
|
+
}
|
|
601
|
+
const removeLine = context.ui.slot({ append: "session.composer.top", render: () => <CompactLine /> })
|
|
602
|
+
|
|
603
|
+
context.keymap.layer(() => ({
|
|
604
|
+
mode: "global",
|
|
605
|
+
commands: [{
|
|
606
|
+
id: "account-quota.accounts.open",
|
|
607
|
+
title,
|
|
608
|
+
palette: true,
|
|
609
|
+
slash: { name: "quota" },
|
|
610
|
+
run: open,
|
|
611
|
+
}],
|
|
612
|
+
}))
|
|
613
|
+
|
|
614
|
+
return () => {
|
|
615
|
+
clearInterval(clock)
|
|
616
|
+
clearTimeout(expiry)
|
|
617
|
+
if (shown) { shown = false; context.ui.dialog.clear() }
|
|
618
|
+
removeLine()
|
|
619
|
+
stopChanged()
|
|
620
|
+
for (const stop of stops) stop()
|
|
621
|
+
}
|
|
622
|
+
},
|
|
623
|
+
})
|