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/view.js
ADDED
|
@@ -0,0 +1,954 @@
|
|
|
1
|
+
// Plain-text presentation of a validated snapshot (B04, B05). Every state is a word, never only a color; the
|
|
2
|
+
// tone only picks a theme token. Native labels cannot inject terminal controls. The modal is laid out here as
|
|
3
|
+
// lines of a known width (two panels when it is wide, one column otherwise), so node tests read the text the TUI
|
|
4
|
+
// draws.
|
|
5
|
+
import { refKey } from "./inventory.js"
|
|
6
|
+
import { targetKey, validTarget } from "./preferences.js"
|
|
7
|
+
import { catalogModel, dataOf, decideRoute, nextChange, routeModelID } from "./routing.js"
|
|
8
|
+
import { freshness, isDecimal, percent, recommend, sampleState, selectionKey, windowLabel } from "./rules.js"
|
|
9
|
+
|
|
10
|
+
const control = /[\u0000-\u001f\u007f-\u009f]/g
|
|
11
|
+
export const clean = (text) => String(text).replace(control, " ")
|
|
12
|
+
|
|
13
|
+
const NAMES = { openai: "OpenAI", deepseek: "DeepSeek", anthropic: "Anthropic API", "claude-agent": "Claude Code" }
|
|
14
|
+
// Logins come before API keys (user decision); in each section OpenAI, then Claude Code and Anthropic, then the rest
|
|
15
|
+
// as listed. The sections are not called subscriptions: an OAuth login proves no billed plan (S16).
|
|
16
|
+
const FIRST = ["openai", "claude-agent", "anthropic"]
|
|
17
|
+
// Plain Unicode marks in a theme color: decoration only, the provider is always named in words.
|
|
18
|
+
const ICONS = { openai: "◎", "claude-agent": "✻", anthropic: "✻", deepseek: "◆" }
|
|
19
|
+
const TYPES = { key: "API key", oauth: "OAuth login", external: "External (unverified)" }
|
|
20
|
+
// When no saved connection is the one in use: the short tag of the provider row and the detail's `In use`.
|
|
21
|
+
const USE = { environment: ["env", "Environment variable"], none: ["none", "None"], unknown: ["unknown", "Unknown"] }
|
|
22
|
+
// Currencies of the DeepSeek low-balance notice (S09). One minimum per currency for every DeepSeek account of
|
|
23
|
+
// this server; an absent currency is off.
|
|
24
|
+
const CURRENCIES = ["USD", "CNY"]
|
|
25
|
+
const NOTICE = "Informational only, not a spending limit: when a turn ends, a notice appears if the active" +
|
|
26
|
+
" DeepSeek account has a fresh balance at or below this amount in the same currency. Usage is never blocked" +
|
|
27
|
+
" and accounts are never switched."
|
|
28
|
+
// The experimental Codex legacy reader (E06) is not a public API: its figures and its offer carry an Experimental
|
|
29
|
+
// chip and this source. While it is off (the default) nothing experimental is offered or shown.
|
|
30
|
+
const CODEX = "ChatGPT, not a public API"
|
|
31
|
+
// Claude's usage (E02) belongs to the one Claude Code profile OpenCode uses, never to the connection's alias:
|
|
32
|
+
// OpenCode does not verify the account behind it and the CLI can switch accounts on its own. With that usage on and a
|
|
33
|
+
// single login, the row is named by the profile. A manual refresh reads Claude Code `/usage` once (same option).
|
|
34
|
+
const PROFILE = "Claude"
|
|
35
|
+
const REASONS = {
|
|
36
|
+
auth: "authentication failed (401)", balance: "insufficient balance (402)", "rate-limit": "rate limited (429)",
|
|
37
|
+
timeout: "timed out", network: "network error", redirect: "redirect refused", "too-large": "response too large",
|
|
38
|
+
invalid: "unrecognized response", http: "server error", login: "not a verified Codex legacy login",
|
|
39
|
+
changed: "the account changed during the read; data discarded", unknown: "unknown error",
|
|
40
|
+
profile: "not the single Claude Code profile", missing: "Claude Code not found", exit: "Claude Code exited with an error",
|
|
41
|
+
busy: "a /usage read is already running", model: "/usage was not answered locally; data discarded",
|
|
42
|
+
}
|
|
43
|
+
// Label column of the detail's table and the split threshold of the modal (text columns).
|
|
44
|
+
const LABEL = 14
|
|
45
|
+
const SPLIT = 84
|
|
46
|
+
// Lines the host and the modal keep around the body: the host's top padding, the title, two rules, the bottom
|
|
47
|
+
// padding and two spare lines so the centered dialog never touches the terminal edges.
|
|
48
|
+
const CHROME = 7
|
|
49
|
+
const label = (connection) => clean(connection.label).trim() || "(no alias)"
|
|
50
|
+
// English words (the UI language) with the 12 or 24 hour clock of the user's locale.
|
|
51
|
+
const hour12 = new Intl.DateTimeFormat(undefined, { hour: "numeric" }).resolvedOptions().hour12 ?? false
|
|
52
|
+
const clock = { hour: hour12 ? "numeric" : "2-digit", minute: "2-digit", hour12 }
|
|
53
|
+
const time = (ms) => new Date(ms).toLocaleTimeString("en-US", clock)
|
|
54
|
+
const weekdayTime = (ms) => new Date(ms).toLocaleString("en-US", { weekday: "short", ...clock })
|
|
55
|
+
// A reset across midnight names its weekday even when it is less than 24 hours away.
|
|
56
|
+
const when = (ms, now) => new Date(ms).toDateString() === new Date(now).toDateString() ? `at ${time(ms)}` : weekdayTime(ms)
|
|
57
|
+
const age = (ms, now) => {
|
|
58
|
+
const minutes = Math.max(0, Math.floor((now - ms) / 60_000))
|
|
59
|
+
return minutes < 1 ? "just now" : minutes < 120 ? `${minutes} min ago` : `${Math.floor(minutes / 60)} h ago`
|
|
60
|
+
}
|
|
61
|
+
const capital = (text) => text.charAt(0).toUpperCase() + text.slice(1)
|
|
62
|
+
// Cut to `room` columns with an ellipsis; text that fits is left alone.
|
|
63
|
+
const clip = (text, room) => (text.length <= room ? text : room <= 1 ? "…" : `${text.slice(0, room - 1).trimEnd()}…`)
|
|
64
|
+
const join = (parts) => parts.map((part) => part.text).join("")
|
|
65
|
+
const size = (parts) => parts.reduce((n, part) => n + part.text.length, 0)
|
|
66
|
+
|
|
67
|
+
// Every sample the server holds for a connection is on screen with its state. Past its freshness or its reset it says
|
|
68
|
+
// Stale and keeps its last percentage and age (`Updated`); it never turns current or 0%. Claude's figures are the last
|
|
69
|
+
// ones attributable to its single profile: what makes them unattributable (another login, a credential event, a
|
|
70
|
+
// sign-in to redo) drops them in the server, never the clock alone. Samples and failures get their owner IDs with
|
|
71
|
+
// routing.dataOf.
|
|
72
|
+
// The freshness of the snapshot's own server instance, its location: `usageFreshnessSeconds` of the DTO, the default
|
|
73
|
+
// when a server sends none. Everything the TUI shows or advises from a snapshot is evaluated with it.
|
|
74
|
+
export const freshnessOf = (snapshot) => freshness(snapshot?.usageFreshnessSeconds)
|
|
75
|
+
const profiled = (integration) => integration.passive === true && integration.connections?.length === 1
|
|
76
|
+
const title = (integration, connection) => (profiled(integration) ? PROFILE : label(connection))
|
|
77
|
+
// What `r` says on an account without a reader.
|
|
78
|
+
export const NO_REFRESH = "Refresh is not available for this account."
|
|
79
|
+
const isCodexLogin = (integration, connection) => integration.id === "openai" && connection.method === "oauth"
|
|
80
|
+
// These are candidates from the visible inventory; each reader verifies the native login before accessing it.
|
|
81
|
+
const manualUsageLogin = (integration, connection) => integration.refreshable && integration.manual && !connection.reconnectRequired &&
|
|
82
|
+
(isCodexLogin(integration, connection) ||
|
|
83
|
+
(integration.id === "claude-agent" && integration.connections.length === 1 && connection.method === "external"))
|
|
84
|
+
|
|
85
|
+
// Measures of one connection: [{ kind, text, state, tone, label?, window?, used?, renews?, amounts?, lines? }].
|
|
86
|
+
// `text` is a one-line form ("5 h: 64% used · Fresh"); the modal draws quota windows as meters from the same fields.
|
|
87
|
+
// Model-scoped windows show only for the exact current selection. Absence is a word, never an empty meter. `ttl` is the
|
|
88
|
+
// freshness table of the snapshot (freshnessOf); the default one when left out.
|
|
89
|
+
export function measures(integration, connection, now, { threshold = 95, selection, ttl } = {}) {
|
|
90
|
+
const { samples, failure } = dataOf(integration, connection)
|
|
91
|
+
const scope = selection && selectionKey(selection)
|
|
92
|
+
// Only a failure of the sample's own source makes it undecidable, as in rules.js and routing.js: a failed Claude
|
|
93
|
+
// /usage read leaves the turn's figure standing, and the detail's Error row tells of the failure.
|
|
94
|
+
const same = (s) => failure && failure.source === s.source
|
|
95
|
+
const failed = (s) => (same(s) ? failure : undefined)
|
|
96
|
+
const out = []
|
|
97
|
+
for (const s of samples.filter((x) => x.scope === "general" || x.scope === scope)) {
|
|
98
|
+
const state = sampleState(s, failed(s), now, ttl)
|
|
99
|
+
const tone = state === "Refresh failed" ? "error" : state === "Stale" ? "muted"
|
|
100
|
+
: (s.used !== undefined && s.used >= threshold) || s.available === false ? "warning" : "base"
|
|
101
|
+
if (s.balances) {
|
|
102
|
+
const lines = s.balances.map((b) => `${clean(b.currency)} ${isDecimal(b.total) ? b.total : "?"}`)
|
|
103
|
+
const amounts = lines.join(" · ")
|
|
104
|
+
let text = "Balance: " + amounts
|
|
105
|
+
if (!s.available) text += " · not available for API calls"
|
|
106
|
+
out.push({ kind: "balance", text: `${text} · ${state}`, amounts, lines, available: s.available, state, tone })
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
const name = windowLabel(clean(s.window), clean(s.scope))
|
|
110
|
+
out.push({
|
|
111
|
+
kind: "quota", label: name, window: s.window, used: s.used, state, tone,
|
|
112
|
+
text: `${name}: ${percent(s.used)} used · ${state}`,
|
|
113
|
+
// A renewal is shown only while the window's data is fresh and the reset still ahead (confirmed).
|
|
114
|
+
...(s.resetsAt > now && state === "Fresh" ? { renews: s.resetsAt } : {}),
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
if (failure && !samples.some(same)) {
|
|
118
|
+
out.push({ kind: "none", text: "No data · Refresh failed", state: "Refresh failed", tone: "error" })
|
|
119
|
+
}
|
|
120
|
+
if (out.length === 0) out.push({ kind: "none", text: "No data", state: "No data", tone: "muted" })
|
|
121
|
+
return out
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// "USD 0.20 · CNY off": the minimum as stored, never converted or summed; "0" is a minimum, absent is off.
|
|
125
|
+
const amount = (minimums, currency) => (isDecimal(minimums?.[currency]) ? minimums[currency] : "off")
|
|
126
|
+
export const minimumText = (minimums) => CURRENCIES.map((c) => `${c} ${amount(minimums, c)}`).join(" · ")
|
|
127
|
+
|
|
128
|
+
// Inner text width of the modal: the host draws an "xlarge" dialog min(116, columns − 2) wide and the modal pads two
|
|
129
|
+
// columns on each side, as native dialogs do (DIALOG_INSET).
|
|
130
|
+
export const modalWidth = (columns) => Math.max(20, Math.min(116, columns - 2) - 4)
|
|
131
|
+
|
|
132
|
+
// Word wrap to `width` columns; continuation lines start with `indent`. A word longer than a line is cut, not lost.
|
|
133
|
+
// A percentage keeps its unit on the same line ("95% used"), so it never reads as a bare number.
|
|
134
|
+
export function wrap(text, width, indent = "") {
|
|
135
|
+
const lead = text.match(/^ */)[0]
|
|
136
|
+
const out = []
|
|
137
|
+
let line = lead
|
|
138
|
+
let empty = true
|
|
139
|
+
const words = []
|
|
140
|
+
for (const word of text.slice(lead.length).split(/ +/).filter(Boolean)) {
|
|
141
|
+
if (word.startsWith("used") && words.at(-1)?.endsWith("%")) words[words.length - 1] += ` ${word}`
|
|
142
|
+
else words.push(word)
|
|
143
|
+
}
|
|
144
|
+
for (let word of words) {
|
|
145
|
+
while (word) {
|
|
146
|
+
const join = empty ? word : ` ${word}`
|
|
147
|
+
if (line.length + join.length <= width) {
|
|
148
|
+
line += join
|
|
149
|
+
empty = false
|
|
150
|
+
word = ""
|
|
151
|
+
} else if (!empty) {
|
|
152
|
+
out.push(line)
|
|
153
|
+
line = indent
|
|
154
|
+
empty = true
|
|
155
|
+
} else {
|
|
156
|
+
const room = Math.max(1, width - line.length)
|
|
157
|
+
out.push(line + word.slice(0, room))
|
|
158
|
+
word = word.slice(room)
|
|
159
|
+
line = indent
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (!empty || out.length === 0) out.push(line)
|
|
164
|
+
return out
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The list compares like with like: 5 h usage, never a weekly substitute; balances stay in their own currencies.
|
|
168
|
+
function figure(connection, list) {
|
|
169
|
+
if (connection.reconnectRequired) return { text: "Sign in again", tone: "warning" }
|
|
170
|
+
const balance = list.find((m) => m.kind === "balance")
|
|
171
|
+
if (balance) {
|
|
172
|
+
if (balance.state === "Fresh") return { text: balance.amounts, tone: balance.tone, balance: true }
|
|
173
|
+
return balance.state === "Refresh failed" ? { text: "Failed", tone: "error" } : { text: "Stale", tone: "muted" }
|
|
174
|
+
}
|
|
175
|
+
const five = list.filter((m) => m.window === "5h")
|
|
176
|
+
const top = five.filter((m) => m.state === "Fresh" && m.used !== undefined).sort((a, b) => b.used - a.used)[0]
|
|
177
|
+
if (top) return { text: `${top.label} ${percent(top.used)} used`, tone: top.tone }
|
|
178
|
+
if (list.some((m) => m.state === "Refresh failed")) return { text: "Failed", tone: "error" }
|
|
179
|
+
if (five.some((m) => m.state === "Stale")) return { text: "Stale", tone: "muted" }
|
|
180
|
+
return { text: "—", tone: "muted" }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// The groups of the list in screen order: Logins (OAuth and external) before API keys; a provider with both kinds is
|
|
184
|
+
// in both, each group with its own accounts in the saved (legacy) priority order. A provider without a saved account
|
|
185
|
+
// is alone in API keys.
|
|
186
|
+
function sections(snapshot) {
|
|
187
|
+
const integrations = snapshot?.inventory === "available" ? snapshot.integrations ?? [] : []
|
|
188
|
+
const rank = (id) => (FIRST.includes(id) ? FIRST.indexOf(id) : FIRST.length)
|
|
189
|
+
const ordered = integrations.map((integration, index) => ({ integration, index }))
|
|
190
|
+
.sort((a, b) => rank(a.integration.id) - rank(b.integration.id) || a.index - b.index).map(({ integration }) => integration)
|
|
191
|
+
const of = (keys) => ordered.map((integration) => ({ integration, connections: integration.connections.filter((c) => (c.method === "key") === keys) }))
|
|
192
|
+
return [
|
|
193
|
+
{ name: "Logins", groups: of(false).filter((g) => g.connections.length > 0) },
|
|
194
|
+
{ name: "API keys", groups: of(true).filter((g) => g.connections.length > 0 || g.integration.connections.length === 0) },
|
|
195
|
+
].filter((section) => section.groups.length > 0)
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Account rows in screen order: what ↑↓, the wheel and the initial cursor move through.
|
|
199
|
+
export const accountRefs = (snapshot) =>
|
|
200
|
+
sections(snapshot).flatMap((s) => s.groups.flatMap((g) => g.connections.map((c) => refKey(g.integration.id, c.id))))
|
|
201
|
+
|
|
202
|
+
// The account in use for the selected model, where the modal's cursor starts.
|
|
203
|
+
export function sessionRef(snapshot, selection) {
|
|
204
|
+
const id = activeAccount(snapshot, selection)
|
|
205
|
+
return id === undefined ? undefined : refKey(selection.providerID, id)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// A fixed categorical step of the theme per provider for its icon; OpenAI in the main text color.
|
|
209
|
+
function iconTone(snapshot, id) {
|
|
210
|
+
if (id === "openai") return "base"
|
|
211
|
+
if (id === "claude-agent" || id === "anthropic") return "icon:0"
|
|
212
|
+
if (id === "deepseek") return "icon:1"
|
|
213
|
+
const rest = (snapshot?.integrations ?? []).map((i) => i.id).filter((other) => !(other in ICONS))
|
|
214
|
+
return `icon:${2 + Math.max(0, rest.indexOf(id))}`
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// A provider row: icon, name in bold and, at the right, a chip with its accounts in this group, or which kind of
|
|
218
|
+
// connection is in use when it is not a saved one (env, none, unknown). Clicking it selects its first account.
|
|
219
|
+
function groupRow(snapshot, integration, connections, { width }) {
|
|
220
|
+
const icon = { text: ICONS[integration.id] ?? "◇", tone: iconTone(snapshot, integration.id) }
|
|
221
|
+
const name = NAMES[integration.id] ?? clean(integration.id)
|
|
222
|
+
const use = integration.active === "connection" ? undefined : USE[integration.active] ?? USE.unknown
|
|
223
|
+
const tag = use?.[0] ?? ""
|
|
224
|
+
const parts = [icon, { text: ` ${clip(name, width - 3 - tag.length).padEnd(width - 2 - tag.length)}`, tone: "base" }, { text: tag, tone: "muted" }]
|
|
225
|
+
return { text: join(parts), parts, bold: true, ...(connections.length > 0 ? { click: { kind: "group", ref: refKey(integration.id, connections[0].id) } } : {}) }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// The focus margin is independent of the active dot.
|
|
229
|
+
function accountLines({ name, active, selected, fig, column, width, cut }) {
|
|
230
|
+
const lead = [
|
|
231
|
+
selected ? { text: "┃", tone: "focus", keep: true } : { text: " ", tone: "base" },
|
|
232
|
+
active ? { text: "●", tone: "success", keep: true } : { text: "○", tone: "faint", keep: true },
|
|
233
|
+
{ text: " ", tone: "base" },
|
|
234
|
+
]
|
|
235
|
+
const indent = size(lead)
|
|
236
|
+
// A balance wider than the column is cut in a split panel; one column gives it a line instead.
|
|
237
|
+
const wide = fig.balance && fig.text.length > column
|
|
238
|
+
const right = [{ text: " " + (wide ? clip(fig.text, column) : fig.text).padStart(column), tone: fig.tone }]
|
|
239
|
+
const room = width - indent - size(right)
|
|
240
|
+
if ((name.length <= room && (cut || !wide)) || (cut && room >= 4)) return [[...lead, { text: clip(name, room).padEnd(room), tone: "base" }, ...right]]
|
|
241
|
+
const short = [{ text: fig.text, tone: fig.tone }]
|
|
242
|
+
if (indent + name.length + 2 + size(short) <= width) return [[...lead, { text: name.padEnd(width - indent - size(short)), tone: "base" }, ...short]]
|
|
243
|
+
const pad = { text: " ".repeat(indent), tone: "base" }
|
|
244
|
+
const names = wrap(name, width - indent).map((line, i) => [...(i === 0 ? lead : [pad]), { text: line.padEnd(width - indent), tone: "base" }])
|
|
245
|
+
const tails = size(short) <= width ? [[{ text: " ".repeat(width - size(short)), tone: "base" }, ...short]]
|
|
246
|
+
: wrap(fig.text, width).map((line) => [{ text: line.padStart(width), tone: fig.tone }])
|
|
247
|
+
return [...names, ...tails]
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// States of the inventory and preferences, above the list.
|
|
251
|
+
function messages(snapshot, width) {
|
|
252
|
+
const rows = []
|
|
253
|
+
const add = (text, tone) => {
|
|
254
|
+
for (const line of wrap(text, width, " ")) rows.push({ text: line, tone })
|
|
255
|
+
}
|
|
256
|
+
const prefs = snapshot?.preferences
|
|
257
|
+
if (snapshot?.inventory !== "available") add("Inventory unavailable.", "error")
|
|
258
|
+
else {
|
|
259
|
+
if (prefs?.state !== "available") add(prefs?.state === "unsupported" ? "Preferences use an unknown format; not changed." : "Preferences unavailable.", "warning")
|
|
260
|
+
if (snapshot.integrations.length === 0) add("No saved connections.", "muted")
|
|
261
|
+
}
|
|
262
|
+
return rows
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// The list: Logins, then API keys, each with its providers and their accounts. `cursor` is a refKey; the focused
|
|
266
|
+
// account's lines carry `selected` and `anchor`, and every line of an account or provider row says what a click picks.
|
|
267
|
+
function listRows(snapshot, { now = Date.now(), cursor, minimum, selection, width, cut = false }) {
|
|
268
|
+
const threshold = snapshot?.preferences?.threshold ?? 95
|
|
269
|
+
const ttl = freshnessOf(snapshot)
|
|
270
|
+
const all = sections(snapshot)
|
|
271
|
+
const figures = new Map()
|
|
272
|
+
for (const { integration, connections } of all.flatMap((section) => section.groups)) {
|
|
273
|
+
for (const c of connections) figures.set(refKey(integration.id, c.id), figure(c, measures(integration, c, now, { threshold, selection, ttl })))
|
|
274
|
+
}
|
|
275
|
+
// Leave a gutter after the figures, inside the focus band and click target.
|
|
276
|
+
const gutter = { text: " ", tone: "base" }
|
|
277
|
+
const accountWidth = width - gutter.text.length
|
|
278
|
+
const widest = Math.max(0, ...[...figures.values()].map((f) => f.text.length))
|
|
279
|
+
const column = Math.min(Math.max(13, widest), Math.max(13, accountWidth - 4 - 10))
|
|
280
|
+
const rows = []
|
|
281
|
+
for (const [index, section] of all.entries()) {
|
|
282
|
+
if (section.name) {
|
|
283
|
+
if (index > 0) rows.push({ text: "" })
|
|
284
|
+
rows.push({ text: section.name.padEnd(width), tone: "muted", bold: true })
|
|
285
|
+
}
|
|
286
|
+
for (const { integration, connections } of section.groups) {
|
|
287
|
+
rows.push(groupRow(snapshot, integration, connections, { width }))
|
|
288
|
+
for (const connection of connections) {
|
|
289
|
+
const key = refKey(integration.id, connection.id)
|
|
290
|
+
const selected = key === cursor && !minimum
|
|
291
|
+
const lines = accountLines({
|
|
292
|
+
name: title(integration, connection), active: connection.active, selected,
|
|
293
|
+
fig: figures.get(key), column, width: accountWidth, cut,
|
|
294
|
+
})
|
|
295
|
+
lines.forEach((line, n) => {
|
|
296
|
+
const parts = [...line, gutter]
|
|
297
|
+
rows.push({ text: join(parts), parts, click: { kind: "account", ref: key },
|
|
298
|
+
...(selected ? { selected: true, anchor: true } : {}), ...(n === 0 ? { ref: key } : {}) })
|
|
299
|
+
})
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return rows
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// A row of the detail's table: the label dimmed in its column, the value in the main color or its state's tone; a
|
|
307
|
+
// long value wraps under its column.
|
|
308
|
+
function field(name, value, width, tone = "base", extra = {}) {
|
|
309
|
+
const room = Math.max(1, width - LABEL)
|
|
310
|
+
const own = name.length < LABEL
|
|
311
|
+
const lines = wrap(value, room).map((line, i) => {
|
|
312
|
+
const lead = (i === 0 && own ? name : "").padEnd(LABEL)
|
|
313
|
+
return { text: lead + line, parts: [{ text: lead, tone: "muted" }, { text: line, tone }], ...extra }
|
|
314
|
+
})
|
|
315
|
+
return own ? lines : [{ text: clip(name, width), parts: [{ text: clip(name, width), tone: "muted" }], ...extra }, ...lines]
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// A name at the left and its value at the right of one line, or the value right-aligned below when narrow.
|
|
319
|
+
function spread(name, value, width, tone) {
|
|
320
|
+
if (name.length + 2 + value.length <= width) {
|
|
321
|
+
const head = name.padEnd(width - value.length)
|
|
322
|
+
return [{ text: head + value, parts: [{ text: head, tone: "base" }, { text: value, tone }] }]
|
|
323
|
+
}
|
|
324
|
+
return [{ text: name, tone: "base" }, ...wrap(value, width).map((line) => ({ text: line.padStart(width), parts: [{ text: line.padStart(width), tone }] }))]
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Both patterns occupy the full height of one cell, so fill and track meet even without color.
|
|
328
|
+
function meter(m, width, threshold) {
|
|
329
|
+
const late = m.state === "Fresh" ? "" : ` · ${m.state}`
|
|
330
|
+
const tone = m.state === "Refresh failed" ? "error" : late ? "muted" : m.used >= threshold ? "warning" : "base"
|
|
331
|
+
const value = `${percent(m.used)} used${late}`
|
|
332
|
+
const name = m.label.padEnd(6) + " "
|
|
333
|
+
const track = width - name.length - value.length - 1
|
|
334
|
+
if (track < 1) return spread(m.label, value, width, tone)
|
|
335
|
+
const fill = Math.floor((m.used / 100) * track)
|
|
336
|
+
const bar = m.used >= threshold ? "warning" : late ? "muted" : m.window === "5h" ? "success" : "accent"
|
|
337
|
+
const parts = [{ text: name, tone: "base" }, { text: "█".repeat(fill), tone: bar },
|
|
338
|
+
{ text: "░".repeat(track - fill), tone: "faint" }, { text: ` ${value}`, tone }]
|
|
339
|
+
return [{ text: join(parts), parts }]
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// The detail's first line: icon and title in bold (the alias, or Claude for the profile), its chips at the right or
|
|
343
|
+
// below it when they do not fit.
|
|
344
|
+
function heading(snapshot, integration, connection, { width, codex }) {
|
|
345
|
+
const icon = { text: ICONS[integration.id] ?? "◇", tone: iconTone(snapshot, integration.id) }
|
|
346
|
+
const name = title(integration, connection)
|
|
347
|
+
const chips = [
|
|
348
|
+
...(connection.reconnectRequired ? [{ text: " Sign in again ", tone: "warning", chip: true }] : []),
|
|
349
|
+
...(codex ? [{ text: " Experimental ", tone: "info", chip: true }] : []),
|
|
350
|
+
]
|
|
351
|
+
const spaced = (list) => list.flatMap((chip, i) => (i > 0 ? [{ text: " ", tone: "base" }, chip] : [chip]))
|
|
352
|
+
const row = (parts) => ({ text: join(parts), parts, bold: true, keep: true })
|
|
353
|
+
const beside = size(spaced(chips))
|
|
354
|
+
if (2 + name.length + (chips.length > 0 ? 1 + beside : 0) <= width) {
|
|
355
|
+
return [row([icon, { text: ` ${name.padEnd(width - 2 - beside)}`, tone: "base" }, ...spaced(chips)])]
|
|
356
|
+
}
|
|
357
|
+
const rows = wrap(name, width - 2).map((line, i) => row([i === 0 ? icon : { text: " ", tone: "base" }, { text: ` ${line}`, tone: "base" }]))
|
|
358
|
+
let line = []
|
|
359
|
+
for (const chip of chips) {
|
|
360
|
+
if (line.length > 0 && 2 + size(spaced([...line, chip])) > width) {
|
|
361
|
+
rows.push(row([{ text: " ", tone: "base" }, ...spaced(line)]))
|
|
362
|
+
line = []
|
|
363
|
+
}
|
|
364
|
+
line.push(chip)
|
|
365
|
+
}
|
|
366
|
+
if (line.length > 0) rows.push(row([{ text: " ", tone: "base" }, ...spaced(line)]))
|
|
367
|
+
return rows
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Each window owns its renewal. Account-wide facts follow the usage block.
|
|
371
|
+
function accountDetail(snapshot, integration, connection, { now, width, selection }) {
|
|
372
|
+
const prefs = snapshot.preferences
|
|
373
|
+
const threshold = prefs?.threshold ?? 95
|
|
374
|
+
const list = measures(integration, connection, now, { threshold, selection, ttl: freshnessOf(snapshot) })
|
|
375
|
+
const { samples, failure } = dataOf(integration, connection)
|
|
376
|
+
const reader = integration.refreshable === true && integration.manual === true
|
|
377
|
+
// Active or not, a Codex read is bound to this login and never switches the active account.
|
|
378
|
+
const codex = samples.some((s) => s.source === "codex-usage") || (isCodexLogin(integration, connection) && reader)
|
|
379
|
+
const rows = [...heading(snapshot, integration, connection, { width, codex }), { text: "" }]
|
|
380
|
+
const quotas = list.filter((m) => m.kind === "quota")
|
|
381
|
+
const balance = list.find((m) => m.kind === "balance")
|
|
382
|
+
if (quotas.length > 0) {
|
|
383
|
+
for (const [i, m] of quotas.entries()) {
|
|
384
|
+
if (i) rows.push({ text: "", spare: true })
|
|
385
|
+
rows.push(...meter(m, width, threshold).map((row) => ({ ...row, measure: true })))
|
|
386
|
+
if (m.renews !== undefined) {
|
|
387
|
+
const caption = `Resets ${when(m.renews, now)}`
|
|
388
|
+
rows.push({ text: caption.padStart(Math.min(width, Math.max(6, m.label.length) + 1 + caption.length)), tone: "muted" })
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
} else if (balance) {
|
|
392
|
+
const late = balance.state === "Fresh" ? "" : ` · ${balance.state}`
|
|
393
|
+
const tone = balance.state === "Refresh failed" ? "error" : late ? "muted" : balance.tone
|
|
394
|
+
balance.lines.forEach((line, i) => rows.push(...field(i === 0 ? "Balance" : "", i === 0 ? line + late : line, width, tone)))
|
|
395
|
+
} else {
|
|
396
|
+
const ask = !failure && manualUsageLogin(integration, connection)
|
|
397
|
+
rows.push(...field("Usage", ask ? "Press r to read" : "—", width, ask ? "base" : "muted"))
|
|
398
|
+
}
|
|
399
|
+
rows.push({ text: "" })
|
|
400
|
+
if (failure) rows.push(...field("Error", `${capital(REASONS[failure.reason] ?? REASONS.unknown)} at ${time(failure.at)}`, width, "error"))
|
|
401
|
+
if (failure?.retryAt > now) rows.push(...field("Retry", `After ${time(failure.retryAt)}`, width))
|
|
402
|
+
if (balance?.available === false) rows.push(...field("API calls", "Not available", width, "warning"))
|
|
403
|
+
const latest = samples.length > 0 ? Math.max(...samples.map((s) => s.observedAt)) : undefined
|
|
404
|
+
if (latest !== undefined) rows.push(...field("Updated", age(latest, now), width))
|
|
405
|
+
// Kept when a low terminal cuts the table: experimental figures always say they are not a public API.
|
|
406
|
+
if (codex) rows.push(...field("Source", CODEX, width, "base", { keep: true }))
|
|
407
|
+
// One source: that of the most recent sample on screen.
|
|
408
|
+
const newest = samples.reduce((a, b) => (b.observedAt > (a?.observedAt ?? -Infinity) ? b : a), undefined)
|
|
409
|
+
if (integration.passive) rows.push(...field("Source", newest?.source === "claude-usage" ? "Claude Code /usage" : "Claude Code turns", width))
|
|
410
|
+
if (integration.id === "deepseek") rows.push(...field("Notice at", prefs?.state === "available" ? minimumText(prefs.minimums) : "Unavailable", width))
|
|
411
|
+
if (integration.active !== "connection") rows.push(...field("In use", (USE[integration.active] ?? USE.unknown)[1], width))
|
|
412
|
+
rows.push(...field("Type", TYPES[connection.method] ?? clean(connection.method), width))
|
|
413
|
+
return rows
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// The DeepSeek low-balance notice editor, shown where the detail is while it is open: it is the focus then, so
|
|
417
|
+
// it is anchored and the list shows no account cursor. The current currency has the focus margin and band.
|
|
418
|
+
function minimumRows(draft, width) {
|
|
419
|
+
return [
|
|
420
|
+
{ text: "Low-balance notice", tone: "base", bold: true },
|
|
421
|
+
{ text: "" },
|
|
422
|
+
...CURRENCIES.map((c) => {
|
|
423
|
+
const selected = c === draft.currency
|
|
424
|
+
const parts = [selected ? { text: "┃", tone: "focus", keep: true } : { text: " ", tone: "base" },
|
|
425
|
+
{ text: `${c.padEnd(7)}${amount(draft.minimums, c)}`.padEnd(width - 1), tone: "base" }]
|
|
426
|
+
return { text: join(parts), parts, click: { kind: "currency", currency: c }, ...(selected ? { selected: true } : {}) }
|
|
427
|
+
}),
|
|
428
|
+
{ text: "" },
|
|
429
|
+
...wrap(NOTICE, width).map((text) => ({ text, tone: "muted" })),
|
|
430
|
+
...wrap("esc discards changes.", width).map((text) => ({ text, tone: "muted" })),
|
|
431
|
+
].map((row) => ({ ...row, anchor: true }))
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function picked(snapshot, cursor) {
|
|
435
|
+
if (snapshot?.inventory !== "available" || typeof cursor !== "string") return undefined
|
|
436
|
+
let ref
|
|
437
|
+
try {
|
|
438
|
+
ref = JSON.parse(cursor)
|
|
439
|
+
} catch {
|
|
440
|
+
return undefined
|
|
441
|
+
}
|
|
442
|
+
const integration = snapshot.integrations.find((i) => i.id === ref?.[0])
|
|
443
|
+
const connection = integration?.connections.find((c) => c.id === ref?.[1])
|
|
444
|
+
return connection && { integration, connection }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ---- Route order and next-turn preview (rotation plan R3) -----------------------------------------------------------
|
|
448
|
+
// The list of destinations is edited locally until Save; the preview evaluates it against the snapshot held here, the
|
|
449
|
+
// session's selection and the clock. Opening, editing or previewing reads nothing, switches nothing and sends nothing.
|
|
450
|
+
const providerName = (id) => NAMES[id] ?? clean(id)
|
|
451
|
+
function routeAccount(snapshot, t, withProvider = true) {
|
|
452
|
+
const provider = providerName(t.providerID)
|
|
453
|
+
if (t.binding === "current") return `${provider} · Active account`
|
|
454
|
+
const i = snapshot.integrations.find((i) => i.id === t.integrationID)
|
|
455
|
+
const c = i?.connections.find((c) => c.id === t.connectionID)
|
|
456
|
+
const name = c ? title(i, c) : "(removed)"
|
|
457
|
+
return withProvider ? `${name} · ${provider}` : name
|
|
458
|
+
}
|
|
459
|
+
export function accountChoices(snapshot) {
|
|
460
|
+
return snapshot.integrations.flatMap((i) => {
|
|
461
|
+
const base = { integrationID: i.id, providerID: i.id }
|
|
462
|
+
const category = providerName(i.id)
|
|
463
|
+
return [...i.connections.map((c) => ({ title: title(i, c), category, value: { ...base, binding: "exact", connectionID: c.id } })),
|
|
464
|
+
{ title: "Active account", category, description: "Follows /connect", value: { ...base, binding: "current" } }]
|
|
465
|
+
})
|
|
466
|
+
}
|
|
467
|
+
// Empty string is an explicit Keep choice (IDs cannot be empty); undefined from a native picker is cancellation.
|
|
468
|
+
export function modelChoices(catalog, providerID) {
|
|
469
|
+
return [{ title: "Keep current model", description: `When already using ${providerName(providerID)}`, value: "" },
|
|
470
|
+
...(catalog ?? []).filter((m) => m.enabled && m.providerID === providerID).map((m) => ({ title: clean(m.name || m.id), value: m.id }))]
|
|
471
|
+
}
|
|
472
|
+
export function effortChoices(catalog, t, selection) {
|
|
473
|
+
const model = catalogModel(catalog, t.providerID, routeModelID(t, selection))
|
|
474
|
+
return [{ title: "Automatic", description: "Keep effort on the same model; otherwise use its default", value: "" },
|
|
475
|
+
...(model?.variants ?? []).map((v) => ({ title: clean(v.id), value: v.id }))]
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
// Work on one copy. Cancel at any step discards that entire row edit, including any preceding account/model choice.
|
|
479
|
+
export async function pickDestination({ snapshot, target, edit, selection, catalog, pick }) {
|
|
480
|
+
let row = { ...target }
|
|
481
|
+
if (edit === "add" || edit === "account") {
|
|
482
|
+
const account = await pick({ title: "Choose account", options: accountChoices(snapshot) })
|
|
483
|
+
if (!account) return
|
|
484
|
+
if (edit === "account" && account.providerID === row.providerID) {
|
|
485
|
+
return { ...account, ...(row.modelID ? { modelID: row.modelID } : {}), ...(row.variant ? { variant: row.variant } : {}) }
|
|
486
|
+
}
|
|
487
|
+
row = { ...account }
|
|
488
|
+
}
|
|
489
|
+
const models = await catalog()
|
|
490
|
+
if (edit !== "effort") {
|
|
491
|
+
const options = modelChoices(models, row.providerID)
|
|
492
|
+
const modelID = await pick({ title: "Choose model", options, current: row.modelID ?? "",
|
|
493
|
+
placeholder: options.length === 1 ? "No models listed here" : "Find a model" })
|
|
494
|
+
if (modelID === undefined) return
|
|
495
|
+
if (modelID !== (row.modelID ?? "")) delete row.variant
|
|
496
|
+
if (modelID) row.modelID = modelID
|
|
497
|
+
else delete row.modelID
|
|
498
|
+
}
|
|
499
|
+
const options = effortChoices(models, row, selection)
|
|
500
|
+
if (edit === "effort" || row.variant || options.length > 1) {
|
|
501
|
+
const variant = await pick({ title: "Choose effort", options, current: options.some((o) => o.value === row.variant) ? row.variant : "",
|
|
502
|
+
placeholder: options.length > 1 ? "Find an effort" : !routeModelID(row, selection) ? "Choose a model to set an effort" : "No efforts listed here" })
|
|
503
|
+
if (variant === undefined) return
|
|
504
|
+
if (variant) row.variant = variant
|
|
505
|
+
else delete row.variant
|
|
506
|
+
}
|
|
507
|
+
return row
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const modelName = (snapshot, providerID, id) => clean(catalogModel(snapshot.catalog, providerID, id)?.name || id)
|
|
511
|
+
|
|
512
|
+
export function startRoute(snapshot) {
|
|
513
|
+
const routing = snapshot?.routing
|
|
514
|
+
if (routing?.state !== "available") return undefined
|
|
515
|
+
return { revision: routing.revision, targets: routing.targets.map((t) => ({ ...t })), index: 0 }
|
|
516
|
+
}
|
|
517
|
+
const at = (draft, targets, index = draft.index) => ({ ...draft, targets, index: Math.max(0, Math.min(Math.max(0, targets.length - 1), index)) })
|
|
518
|
+
export function putRoute(draft, target, index = draft.targets.length) {
|
|
519
|
+
if (!validTarget(target) || index >= 64 || draft.targets.some((t, i) => i !== index && targetKey(t) === targetKey(target))) return undefined
|
|
520
|
+
const targets = [...draft.targets]
|
|
521
|
+
targets[index] = target
|
|
522
|
+
return at(draft, targets, index)
|
|
523
|
+
}
|
|
524
|
+
export function routeMove(draft, delta) {
|
|
525
|
+
const to = draft.index + delta
|
|
526
|
+
if (to < 0 || to >= draft.targets.length) return draft
|
|
527
|
+
const targets = [...draft.targets]
|
|
528
|
+
targets.splice(to, 0, ...targets.splice(draft.index, 1))
|
|
529
|
+
return at(draft, targets, to)
|
|
530
|
+
}
|
|
531
|
+
export const routeStep = (draft, delta) => at(draft, draft.targets, draft.index + delta)
|
|
532
|
+
export const routeRemove = (draft) => (draft.targets.length ? at(draft, draft.targets.filter((_, i) => i !== draft.index)) : draft)
|
|
533
|
+
export const routeProposal = (draft) => ({ revision: draft.revision, targets: draft.targets })
|
|
534
|
+
|
|
535
|
+
// The engine on held data only: no policy reader, so whatever needs data says so instead of being read.
|
|
536
|
+
export function routePreview(snapshot, targets, selection, now) {
|
|
537
|
+
if (snapshot?.inventory !== "available" || snapshot.preferences?.state !== "available") return undefined
|
|
538
|
+
return decideRoute({ selection, targets, catalog: snapshot.catalog, integrations: snapshot.integrations, threshold: snapshot.preferences.threshold,
|
|
539
|
+
minimums: snapshot.preferences.minimums, now, readable: new Set(), visited: new Set(), budget: { origin: 0, candidates: 0 },
|
|
540
|
+
paid: snapshot.routing?.session?.paid === true, ttl: freshnessOf(snapshot) })
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function nextTurn(snapshot, targets, d) {
|
|
544
|
+
if (!d) return ["Unavailable", "muted"]
|
|
545
|
+
if (d.kind === "keep") return [d.reason ? `Keep current model · ${d.reason}` : "Keep current model", d.reason ? "muted" : "base"]
|
|
546
|
+
if (d.kind === "suggest") {
|
|
547
|
+
const m = d.model
|
|
548
|
+
return [`Suggested: ${d.target + 1}. ${routeAccount(snapshot, targets[d.target])} · ${modelName(snapshot, m.providerID, m.modelID)}${m.variant ? ` #${clean(m.variant)}` : ""}`, "warning"]
|
|
549
|
+
}
|
|
550
|
+
if (d.kind === "needRead") return [`Refresh required: ${d.read.purpose === "origin" ? "the account in use" : "a destination"}`, "muted"]
|
|
551
|
+
return [`No destination · ${d.reason}`, "warning"]
|
|
552
|
+
}
|
|
553
|
+
const manualText = (d) => d?.kind === "suggest" ? `Manual: ${d.reason} · ${d.reason === "Account switch is global" ? "/connect" : "/models"}` : undefined
|
|
554
|
+
|
|
555
|
+
function routeListRows(snapshot, draft, width) {
|
|
556
|
+
const rows = [{ text: "Route order".padEnd(width), tone: "base", bold: true }]
|
|
557
|
+
if (draft.targets.length === 0) {
|
|
558
|
+
for (const line of wrap("Add an account to start.", width)) rows.push({ text: line, tone: "muted" })
|
|
559
|
+
return rows
|
|
560
|
+
}
|
|
561
|
+
draft.targets.forEach((t, i) => {
|
|
562
|
+
const selected = i === draft.index
|
|
563
|
+
const lead = selected ? { text: "┃", tone: "focus", keep: true } : { text: " ", tone: "base" }
|
|
564
|
+
const fixed = t.modelID || t.variant
|
|
565
|
+
const detail = fixed ? ` · ${t.modelID ? modelName(snapshot, t.providerID, t.modelID) : "Current model"}${t.variant ? ` #${clean(t.variant)}` : ""}` : ""
|
|
566
|
+
const name = clip(`${i + 1}. ${routeAccount(snapshot, t, !fixed)}${detail}`, width - 1)
|
|
567
|
+
const parts = [lead, { text: name.padEnd(width - 1), tone: "base" }]
|
|
568
|
+
rows.push({ text: join(parts), parts, click: { kind: "route", index: i }, ...(selected ? { selected: true, anchor: true } : {}) })
|
|
569
|
+
})
|
|
570
|
+
return rows
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function routePreviewRows(snapshot, draft, { now, selection, width }) {
|
|
574
|
+
const d = routePreview(snapshot, draft.targets, selection, now)
|
|
575
|
+
const [next, tone] = nextTurn(snapshot, draft.targets, d)
|
|
576
|
+
const rows = [{ text: "Preview next turn", tone: "base", bold: true, keep: true }]
|
|
577
|
+
const lines = (value, tone, keep = false) => wrap(value, width).map((text) => ({ text, tone, keep }))
|
|
578
|
+
rows.push(...lines(!selection ? "Open a chat to preview its next turn." : next, tone, true))
|
|
579
|
+
if (d?.trigger) rows.push(...lines(d.trigger, "muted"))
|
|
580
|
+
const manual = manualText(d)
|
|
581
|
+
if (manual) rows.push(...lines(manual, "muted"))
|
|
582
|
+
const t = draft.targets[draft.index]
|
|
583
|
+
if (t) {
|
|
584
|
+
const status = d?.rows[draft.index]
|
|
585
|
+
rows.push({ text: "" }, ...wrap(routeAccount(snapshot, t), width).map((text) => ({ text, bold: true })),
|
|
586
|
+
...field("Model", t.modelID ? modelName(snapshot, t.providerID, t.modelID) : "Keep current model", width),
|
|
587
|
+
...field("Effort", t.variant ? clean(t.variant) : "Automatic", width))
|
|
588
|
+
if (status?.reason) rows.push(...lines(status.reason, "muted"))
|
|
589
|
+
}
|
|
590
|
+
return rows
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// The right panel (below the list in one column): the route preview, the open notice editor or the selected account.
|
|
594
|
+
function detailRows(snapshot, { now = Date.now(), cursor, minimum, route, selection, width }) {
|
|
595
|
+
if (route) return routePreviewRows(snapshot, route, { now, selection, width })
|
|
596
|
+
if (minimum) return minimumRows(minimum, width)
|
|
597
|
+
const found = picked(snapshot, cursor)
|
|
598
|
+
return found ? accountDetail(snapshot, found.integration, found.connection, { now, width, selection }) : []
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// The body in one column, each row at most `width`: the list, then (zone "detail") a dotted rule and the detail.
|
|
602
|
+
// Without accounts, the state and the single pointer to native account management.
|
|
603
|
+
export function modalRows(snapshot, options = {}) {
|
|
604
|
+
const { width = 72 } = options
|
|
605
|
+
const list = [...messages(snapshot, width), ...(options.route ? routeListRows(snapshot, options.route, width) : listRows(snapshot, { ...options, width }))]
|
|
606
|
+
const detail = detailRows(snapshot, { ...options, width })
|
|
607
|
+
const ready = snapshot?.inventory === "available" && snapshot.integrations.length > 0
|
|
608
|
+
const tail = detail.length > 0 ? [{ text: "┄".repeat(width), tone: "faint", rule: true, keep: true }, ...detail]
|
|
609
|
+
: ready ? [] : [{ text: "", spare: true }, { text: "Manage accounts: /connect", tone: "muted", spare: true }]
|
|
610
|
+
return [...list, ...tail.map((row) => ({ tone: "muted", ...row, zone: "detail" }))]
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// The first line to show so that the anchored lines stay visible: the top of the list when they fit there,
|
|
614
|
+
// otherwise as little movement as possible from the previous position; when they are taller than the room, their
|
|
615
|
+
// start wins (with one line of context above, unless that would leave no room for the anchored line itself).
|
|
616
|
+
export function scrollStart(rows, room, previous = 0) {
|
|
617
|
+
if (rows.length <= room) return 0
|
|
618
|
+
let start = Math.max(0, Math.min(previous, rows.length - room))
|
|
619
|
+
const first = rows.findIndex((row) => row.anchor)
|
|
620
|
+
if (first < 0) return start
|
|
621
|
+
const last = rows.findLastIndex((row) => row.anchor)
|
|
622
|
+
if (last < room) return 0
|
|
623
|
+
const context = room > 1 ? 1 : 0
|
|
624
|
+
if (last >= start + room) start = last - room + 1
|
|
625
|
+
if (first - context < start) start = Math.max(0, first - context)
|
|
626
|
+
return Math.min(start, rows.length - room)
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// What fits in `height` lines: everything, or a scrolled window with a line above and below saying how many more
|
|
630
|
+
// (with fewer than 3 lines, just the window). A single hidden line is shown in its slot instead of "1 more".
|
|
631
|
+
// `previous` is the last start, so moving scrolls only as needed.
|
|
632
|
+
export function windowRows(rows, height, previous = 0) {
|
|
633
|
+
if (rows.length <= height) return { start: 0, rows }
|
|
634
|
+
if (height < 3) {
|
|
635
|
+
const start = scrollStart(rows, height, previous)
|
|
636
|
+
return { start, rows: rows.slice(start, start + height) }
|
|
637
|
+
}
|
|
638
|
+
const room = height - 2
|
|
639
|
+
const start = scrollStart(rows, room, previous)
|
|
640
|
+
const hidden = rows.length - start - room
|
|
641
|
+
return {
|
|
642
|
+
start,
|
|
643
|
+
rows: [
|
|
644
|
+
start === 1 ? rows[0] : { text: start > 0 ? `↑ ${start} more` : "", tone: "muted" },
|
|
645
|
+
...rows.slice(start, start + room),
|
|
646
|
+
hidden === 1 ? rows.at(-1) : { text: hidden > 0 ? `↓ ${hidden} more` : "", tone: "muted" },
|
|
647
|
+
],
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// What fits of a detail in `room` lines: blank spacing gives way first, then lines from the end (spare ones first).
|
|
652
|
+
// Rows that must stay (the heading, the source of experimental figures) are kept in order while they fit. Never
|
|
653
|
+
// ends on a blank line.
|
|
654
|
+
function trim(rows, room) {
|
|
655
|
+
if (room <= 0) return []
|
|
656
|
+
let out = rows.length > room ? rows.filter((row) => !row.spare) : [...rows]
|
|
657
|
+
for (let i = out.length - 1; i > 0 && out.length > room; i -= 1) if (out[i].text.trim() === "" && !out[i].keep) out.splice(i, 1)
|
|
658
|
+
// Captions and metadata give way before the measurements they explain.
|
|
659
|
+
for (const cutMeasures of [false, true]) {
|
|
660
|
+
for (let i = out.length - 1; i >= 0 && out.length > room; i--) if (!out[i].keep && (cutMeasures || !out[i].measure)) out.splice(i, 1)
|
|
661
|
+
}
|
|
662
|
+
out = out.slice(0, room)
|
|
663
|
+
while (out.length > 1 && out.at(-1).text.trim() === "") out.pop()
|
|
664
|
+
return out
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// The one-column body in `height` physical lines (every row is at most the width, so one row is one line). The list
|
|
668
|
+
// scrolls to keep the focused account visible; when both need the room they split it, with the odd line for detail.
|
|
669
|
+
// With one line, only the focused account. While the notice editor is
|
|
670
|
+
// open it is the focus, so the detail goes first.
|
|
671
|
+
export function fitBody(rows, height, previous = 0) {
|
|
672
|
+
const h = Math.max(1, height)
|
|
673
|
+
const split = rows.findIndex((row) => row.zone === "detail")
|
|
674
|
+
const list = split < 0 ? rows : rows.slice(0, split)
|
|
675
|
+
let detail = split < 0 ? [] : rows.slice(split)
|
|
676
|
+
if (list.length + detail.length <= h) return { start: 0, rows }
|
|
677
|
+
detail = detail.filter((row) => !row.spare)
|
|
678
|
+
if (list.length + detail.length <= h) return { start: 0, rows: [...list, ...detail] }
|
|
679
|
+
const focus = detail.some((row) => row.anchor)
|
|
680
|
+
const listMin = Math.min(list.length, focus ? 0 : h < 4 ? h : h < 6 ? 1 : Math.floor(h / 2))
|
|
681
|
+
let room = Math.min(detail.length, h - listMin)
|
|
682
|
+
if (focus && room < detail.length) {
|
|
683
|
+
// Editor taller than the room: from its first anchored line.
|
|
684
|
+
const first = detail.findIndex((row) => row.anchor)
|
|
685
|
+
detail = detail.slice(Math.max(0, first - 1))
|
|
686
|
+
room = Math.min(detail.length, h)
|
|
687
|
+
}
|
|
688
|
+
// The editor takes every line: no list above it, and so no rule either.
|
|
689
|
+
const whole = focus && room >= h
|
|
690
|
+
if (whole && detail[0]?.rule) {
|
|
691
|
+
detail = detail.slice(1)
|
|
692
|
+
room = Math.min(detail.length, h)
|
|
693
|
+
}
|
|
694
|
+
// A rule with one line under it says little: below two lines the list keeps the room.
|
|
695
|
+
const below = room < 2 && !focus ? [] : trim(detail, room)
|
|
696
|
+
const fit = windowRows(list, h - below.length, previous)
|
|
697
|
+
return { start: fit.start, rows: [...(whole || h - below.length <= 0 ? [] : fit.rows), ...below] }
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// Keys of the current mode only, never Esc (named once, at the top right): { key, label, action }, shortened in a
|
|
701
|
+
// narrow modal. `action` names what a click on it runs, the same as the key. Every entry is an action: ↑↓, the wheel
|
|
702
|
+
// and clicks still move the focus in every mode (row, currency or destination), but the footer does not spell them
|
|
703
|
+
// out. Edits and the turn-end notice never share one line with another mode's keys.
|
|
704
|
+
const entry = (key, label, action) => ({ key, label, action })
|
|
705
|
+
export function legend({ minimum, route, notice, deepseek, refreshAll } = {}, width = 110) {
|
|
706
|
+
const narrow = width < 50
|
|
707
|
+
if (route) {
|
|
708
|
+
return [entry("a", narrow ? "Add" : "Add account", "routeAdd"), ...(route.targets?.length ? [entry("Enter", "Edit", "routeEdit")] : []),
|
|
709
|
+
entry("o", "Options", "routeOptions"), entry("s", "Save", "save")]
|
|
710
|
+
}
|
|
711
|
+
if (minimum) return [entry("e", narrow ? "Amount" : "Edit amount", "amount"), entry("o", "Off", "off"), entry("s", "Save", "save")]
|
|
712
|
+
return [
|
|
713
|
+
entry("r", "Refresh", "refresh"), ...(refreshAll ? [entry("a", narrow ? "All" : "Refresh all", "refreshAll")] : []),
|
|
714
|
+
entry("o", narrow ? "Route" : "Route order", "route"),
|
|
715
|
+
...(deepseek ? [entry("m", narrow ? "Notice" : "Balance notice", "notice")] : []),
|
|
716
|
+
...(notice ? [entry("x", "Dismiss", "dismiss")] : []),
|
|
717
|
+
]
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
// What each key of the modal runs per mode; one key may mean different things in different modes. `legend` shows
|
|
721
|
+
// only the current mode's keys.
|
|
722
|
+
export const KEYS = {
|
|
723
|
+
r: { other: "refresh" }, a: { other: "refreshAll", route: "routeAdd" }, m: { other: "notice" },
|
|
724
|
+
e: { minimum: "amount" }, o: { minimum: "off", other: "route", route: "routeOptions" },
|
|
725
|
+
return: { route: "routeEdit" }, s: { minimum: "save", route: "save" }, x: { other: "dismiss" },
|
|
726
|
+
}
|
|
727
|
+
// The action of a key in the current mode: the route editor has only its own; the notice editor falls back to the
|
|
728
|
+
// keys of the list. An unknown key runs nothing.
|
|
729
|
+
export function keyAction(bind, { route, minimum } = {}) {
|
|
730
|
+
if (!Object.hasOwn(KEYS, bind)) return undefined
|
|
731
|
+
const key = KEYS[bind]
|
|
732
|
+
return route ? key.route : minimum ? key.minimum ?? key.other : key.other
|
|
733
|
+
}
|
|
734
|
+
// A save refused because the stored data changed since it was read (the RPC error type or the server's message).
|
|
735
|
+
export const conflicted = (error) =>
|
|
736
|
+
/conflict|changed\. Reload/.test(`${error?.type ?? ""} ${error?.name ?? ""} ${error?.message ?? ""} ${error?.data?.type ?? ""}`)
|
|
737
|
+
|
|
738
|
+
// A centered grid of clickable key/label pairs. Both starts align down each column (keys right-aligned). The grid is
|
|
739
|
+
// centered as a whole: a shorter last row sits under the first columns, at the same `left`, never centered alone.
|
|
740
|
+
export function modalFooter(items, width) {
|
|
741
|
+
const gap = width < 50 ? 2 : 3
|
|
742
|
+
for (let n = items.length; n > 0; n--) {
|
|
743
|
+
if (n > Math.ceil(items.length / Math.ceil(items.length / n))) continue
|
|
744
|
+
const cols = Array.from({ length: n }, (_, col) => {
|
|
745
|
+
const cells = items.filter((_, i) => i % n === col)
|
|
746
|
+
const key = Math.max(...cells.map((c) => c.key.length))
|
|
747
|
+
return { key, width: key + 1 + Math.max(...cells.map((c) => c.label.length)) }
|
|
748
|
+
})
|
|
749
|
+
const gridWidth = cols.reduce((total, col) => total + col.width, gap * (n - 1))
|
|
750
|
+
if (gridWidth > width) continue
|
|
751
|
+
const left = Math.floor((width - gridWidth) / 2)
|
|
752
|
+
const lines = []
|
|
753
|
+
for (let i = 0; i < items.length; i += n) {
|
|
754
|
+
const row = items.slice(i, i + n)
|
|
755
|
+
const cells = row.map((item, j) => ({ ...item, keyText: item.key.padStart(cols[j].key), width: cols[j].width }))
|
|
756
|
+
const content = cells.map((c) => `${c.keyText} ${c.label}`.padEnd(c.width)).join(" ".repeat(gap))
|
|
757
|
+
lines.push({ items: row, cells, gap, left, text: " ".repeat(left) + content })
|
|
758
|
+
}
|
|
759
|
+
return lines
|
|
760
|
+
}
|
|
761
|
+
return []
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// The turn-end notice and the last message, between the body and the bottom rule, wrapped to the width.
|
|
765
|
+
export function alertRows(snapshot, { notice, message } = {}, width = 110) {
|
|
766
|
+
const rows = []
|
|
767
|
+
for (const [text, tone] of [[notice && noticeText(snapshot, notice), "warning"], [message, "warning"]]) {
|
|
768
|
+
if (text) for (const line of wrap(text, width, " ")) rows.push({ text: line, tone })
|
|
769
|
+
}
|
|
770
|
+
return rows
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
const UNAVAILABLE = [{ text: "Account data is unavailable.", tone: "error" }, { text: "Manage accounts: /connect", tone: "muted" }]
|
|
774
|
+
|
|
775
|
+
// The whole modal for a terminal of `columns` × `rows`: { mode: "split" | "stacked", width, header, left, right,
|
|
776
|
+
// alerts, footer, start }. Split (84 text columns or more): the list at the left, a divider and the detail at the
|
|
777
|
+
// right, each cut to the body's height (the list scrolls with its focus, the detail loses its end). Stacked: one
|
|
778
|
+
// column, the list over the detail. `start` is the scroll position to pass back next time.
|
|
779
|
+
export function modalLayout(snapshot, { now = Date.now(), cursor, minimum, route, selection, columns = 120, rows: lines = 40,
|
|
780
|
+
start = 0, notice, message, flags = {} } = {}) {
|
|
781
|
+
const width = modalWidth(columns)
|
|
782
|
+
const failed = flags.failed === true
|
|
783
|
+
const header = { title: "Accounts", text: "Accounts".padEnd(width - 3) + "esc" }
|
|
784
|
+
const keys = legend({ minimum, route, notice, deepseek: !!snapshot?.integrations?.some((i) => i.id === "deepseek"),
|
|
785
|
+
refreshAll: batchRefs(snapshot).length > 0 }, width)
|
|
786
|
+
const footer = failed ? [] : modalFooter(keys, width)
|
|
787
|
+
const room = Math.min(lines - 2, 22) - (CHROME - 2) - footer.length
|
|
788
|
+
const alerts = failed ? [] : alertRows(snapshot, { notice, message }, width).slice(0, Math.max(0, room - 1))
|
|
789
|
+
const height = Math.max(1, room - alerts.length)
|
|
790
|
+
const options = { now, cursor, minimum, route, selection }
|
|
791
|
+
const ready = !failed && snapshot?.inventory === "available" && (snapshot.integrations?.length ?? 0) > 0
|
|
792
|
+
if (!ready || width < SPLIT) {
|
|
793
|
+
const fit = fitBody(failed ? UNAVAILABLE : modalRows(snapshot, { ...options, width }), height, start)
|
|
794
|
+
return { mode: "stacked", width, height, header, left: { width, rows: fit.rows }, right: { width: 0, rows: [] }, alerts, footer, start: fit.start }
|
|
795
|
+
}
|
|
796
|
+
const left = Math.round((width - 3) / 3)
|
|
797
|
+
const right = width - left - 3
|
|
798
|
+
const fit = windowRows([...messages(snapshot, left), ...(route ? routeListRows(snapshot, route, left)
|
|
799
|
+
: listRows(snapshot, { ...options, width: left, cut: true }))], height, start)
|
|
800
|
+
return {
|
|
801
|
+
mode: "split", width, height, header, left: { width: left, rows: fit.rows },
|
|
802
|
+
right: { width: right, rows: trim(detailRows(snapshot, { ...options, width: right }), height) }, alerts, footer, start: fit.start,
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// The modal as plain text, line by line, as a terminal shows it (no trailing blanks): for tests and synthetic screens.
|
|
807
|
+
export function screenText(layout) {
|
|
808
|
+
const rule = "─".repeat(layout.width)
|
|
809
|
+
const body = layout.mode === "split"
|
|
810
|
+
? Array.from({ length: layout.height }, (_, i) =>
|
|
811
|
+
`${(layout.left.rows[i]?.text ?? "").padEnd(layout.left.width)} │ ${layout.right.rows[i]?.text ?? ""}`)
|
|
812
|
+
: Array.from({ length: layout.height }, (_, i) => layout.left.rows[i]?.text ?? "")
|
|
813
|
+
return [layout.header.text, rule, ...body, ...layout.alerts.map((row) => row.text), rule, ...layout.footer.map((line) => line.text)]
|
|
814
|
+
.map((line) => line.trimEnd())
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// `a` asks once per saved OpenAI OAuth login and once for a sole Claude Code login. The server verifies the
|
|
818
|
+
// Codex method and the Claude profile; each read keeps its own scheduler slot, result and retry wait.
|
|
819
|
+
export function batchRefs(snapshot) {
|
|
820
|
+
return (snapshot?.integrations ?? []).flatMap((i) => i.connections.filter((c) => manualUsageLogin(i, c))
|
|
821
|
+
.map((c) => ({ integrationID: i.id, connectionID: c.id })))
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// One line for the result of `a`: how many accounts were read, failed (each says why in its own detail) or were
|
|
825
|
+
// deferred by a running wait. Counts only; no account names, IDs or provider text.
|
|
826
|
+
// Only fixed categories and HTTP codes reach the screen, never server messages or response bodies.
|
|
827
|
+
export function refreshRpcError(error) {
|
|
828
|
+
if ([error?.type, error?.data?.type].includes("not_found")) return "RPC: unknown account reference"
|
|
829
|
+
const code = [error?.status, error?.statusCode, error?.response?.status].find(n => Number.isInteger(n) && n >= 400 && n <= 599)
|
|
830
|
+
if (code) return `RPC: HTTP ${code}`
|
|
831
|
+
if (error?.name === "TimeoutError") return "RPC: timed out"
|
|
832
|
+
if (error?.name === "AbortError") return "RPC: cancelled"
|
|
833
|
+
return "RPC: refresh call failed"
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
export function batchSummary(statuses) {
|
|
837
|
+
const count = (status) => statuses.filter((s) => s === status).length
|
|
838
|
+
const parts = ["read", "failed", "deferred", "unsupported"].filter(s => statuses.includes(s)).map(s => `${count(s)} ${s}`)
|
|
839
|
+
for (const reason of new Set(statuses.filter(s => s.startsWith("RPC: ")))) parts.push(`${reason} (${count(reason)})`)
|
|
840
|
+
return `Refresh all: ${parts.join(" · ")}.`
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
export function noticeText(snapshot, notice) {
|
|
844
|
+
const { result } = notice
|
|
845
|
+
const head = (notice.afterFailure ? "Last turn failed. " : "") + result.trigger.text
|
|
846
|
+
// From the global engine: the preview's own `Next turn` and `Manual` texts; nothing is switched.
|
|
847
|
+
if (result.route) return `${head}. ${result.next}${result.manual ? `. ${result.manual}` : ""}`
|
|
848
|
+
return `${head}. No confirmed alternative: ${result.reason}`
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
// The line above the composer exists only while a turn-end notice is up: the account in use, what crossed (in the
|
|
852
|
+
// warning tone), what to do and where. Without a notice there is nothing to draw; the modal shows the account.
|
|
853
|
+
export function compactParts(snapshot, selection, notice) {
|
|
854
|
+
const integration = notice && selection && snapshot?.integrations?.find((i) => i.id === selection.providerID)
|
|
855
|
+
const active = integration?.connections.find((c) => c.active)
|
|
856
|
+
if (!active) return undefined
|
|
857
|
+
const result = notice.result
|
|
858
|
+
const next = result.route ? result.next : "No confirmed alternative"
|
|
859
|
+
return [
|
|
860
|
+
{ text: `${title(integration, active)} · `, tone: "muted" },
|
|
861
|
+
{ text: result.trigger.text, tone: "warning" },
|
|
862
|
+
{ text: ` · ${next} · /quota`, tone: "muted" },
|
|
863
|
+
]
|
|
864
|
+
}
|
|
865
|
+
export const compactLine = (snapshot, selection, notice) => {
|
|
866
|
+
const parts = compactParts(snapshot, selection, notice)
|
|
867
|
+
return parts && join(parts)
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
export const activeAccount = (snapshot, selection) =>
|
|
871
|
+
snapshot?.integrations?.find((i) => i.id === selection?.providerID)?.connections.find((c) => c.active)?.id
|
|
872
|
+
|
|
873
|
+
// The next instant at which a held sample stops being fresh (TTL or reset), if any: when a notice needs to be
|
|
874
|
+
// revalidated by the clock alone. With a saved route order, also a known reset that ends a "Waiting for reset" mark
|
|
875
|
+
// of the global engine (routing.nextChange).
|
|
876
|
+
export const nextExpiry = (snapshot, now) => nextChange(snapshot?.integrations, now, freshnessOf(snapshot), routesSaved(snapshot))
|
|
877
|
+
|
|
878
|
+
// A saved, readable route order with at least one destination: then the global engine decides the turn-end advice.
|
|
879
|
+
export const routesSaved = (snapshot) => snapshot?.routing?.state === "available" && Array.isArray(snapshot.routing.targets) &&
|
|
880
|
+
snapshot.routing.targets.length > 0
|
|
881
|
+
|
|
882
|
+
// The advice for the session's selection from the snapshot the TUI already holds: evaluating a turn never reads,
|
|
883
|
+
// switches or sends anything. Without a saved route order: rules.recommend() inside the selection's integration, over
|
|
884
|
+
// the legacy saved order, as before. With one: the same routePreview() the modal's `Preview next turn` shows, over the
|
|
885
|
+
// stored order (what the route editor opens with), so the notice names the same destination, provider and reason.
|
|
886
|
+
// The trigger and its recovery keys are the recommendation's own (both engines measure the trigger alike), so an
|
|
887
|
+
// episode ends only on a fresh sample of what triggered.
|
|
888
|
+
export function decide(snapshot, selection, now) {
|
|
889
|
+
const integration = snapshot?.integrations?.find((i) => i.id === selection?.providerID)
|
|
890
|
+
if (!integration || snapshot.preferences?.state !== "available") return { kind: "idle" }
|
|
891
|
+
const all = integration.connections.map((c) => dataOf(integration, c))
|
|
892
|
+
const legacy = recommend({
|
|
893
|
+
integration: { id: integration.id, connections: integration.connections },
|
|
894
|
+
selection, threshold: snapshot.preferences.threshold, minimums: snapshot.preferences.minimums, now,
|
|
895
|
+
samples: all.flatMap((a) => a.samples), failures: all.flatMap((a) => (a.failure ? [a.failure] : [])), ttl: freshnessOf(snapshot),
|
|
896
|
+
})
|
|
897
|
+
if (!routesSaved(snapshot)) return legacy
|
|
898
|
+
const targets = snapshot.routing.targets
|
|
899
|
+
const d = routePreview(snapshot, targets, selection, now)
|
|
900
|
+
if (!d?.trigger) return { kind: "idle", ...(legacy.kind === "idle" && legacy.measured ? { measured: legacy.measured } : {}) }
|
|
901
|
+
const [next] = nextTurn(snapshot, targets, d)
|
|
902
|
+
return {
|
|
903
|
+
kind: d.kind, route: true, next, ...(manualText(d) ? { manual: manualText(d) } : {}),
|
|
904
|
+
// What the advice is about, for the advisor's motive: the destination row and why it is manual, or the reason.
|
|
905
|
+
...(d.kind === "suggest" ? { to: JSON.stringify([d.target, targets[d.target], d.reason]) } : { reason: d.reason ?? next }),
|
|
906
|
+
trigger: { text: d.trigger, keys: legacy.trigger?.keys ?? [JSON.stringify(["route", d.trigger])] },
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
// Accounts the view may read when it opens: refreshable, connected, without fresh data and not waiting. A manual
|
|
911
|
+
// usage reader is never among them: it reads only on an explicit refresh.
|
|
912
|
+
export function staleRefs(snapshot, now) {
|
|
913
|
+
const ttl = freshnessOf(snapshot)
|
|
914
|
+
return (snapshot?.integrations ?? []).filter((i) => i.refreshable && !i.manual).flatMap((integration) =>
|
|
915
|
+
integration.connections.filter((c) => !c.reconnectRequired && !(c.failure?.retryAt > now) &&
|
|
916
|
+
!measures(integration, c, now, { ttl }).some((m) => m.state === "Fresh"))
|
|
917
|
+
.map((c) => ({ integrationID: integration.id, connectionID: c.id })))
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// The DeepSeek low-balance notice, edited locally until Save; it starts from the stored minimums.
|
|
921
|
+
export function startMinimum(snapshot) {
|
|
922
|
+
if (snapshot?.preferences?.state !== "available" || !snapshot.integrations?.some((i) => i.id === "deepseek")) return undefined
|
|
923
|
+
return { revision: snapshot.preferences.revision, minimums: { ...snapshot.preferences.minimums }, currency: CURRENCIES[0] }
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
export function shiftCurrency(draft, delta) {
|
|
927
|
+
const index = Math.max(0, Math.min(CURRENCIES.length - 1, CURRENCIES.indexOf(draft.currency) + delta))
|
|
928
|
+
return { ...draft, currency: CURRENCIES[index] }
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
// A click on a currency row of the editor: that currency, if it is one of the notice's.
|
|
932
|
+
export const pickCurrency = (draft, currency) => (CURRENCIES.includes(currency) ? { ...draft, currency } : draft)
|
|
933
|
+
|
|
934
|
+
// Exact decimal text as typed, never a float: digits with an optional dot ("0.20", "5", "0"). Anything else,
|
|
935
|
+
// including a sign, a comma or an exponent, is rejected and leaves the draft unchanged.
|
|
936
|
+
export function setAmount(draft, text) {
|
|
937
|
+
const value = typeof text === "string" ? text.trim() : ""
|
|
938
|
+
if (!isDecimal(value) || value.startsWith("-")) return undefined
|
|
939
|
+
return { ...draft, minimums: { ...draft.minimums, [draft.currency]: value } }
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
export function turnOff(draft) {
|
|
943
|
+
const { [draft.currency]: _, ...minimums } = draft.minimums
|
|
944
|
+
return { ...draft, minimums }
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// Complete proposal with the revision the draft was read at (`snapshot.preferences.revision`): every integration
|
|
948
|
+
// keeps its saved (legacy) order as shown, which the modal no longer edits; the threshold or the notice minimums
|
|
949
|
+
// change only when the draft carries them, the rest stays as stored.
|
|
950
|
+
export function proposalFrom(snapshot, draft) {
|
|
951
|
+
const order = {}
|
|
952
|
+
for (const integration of snapshot.integrations) order[integration.id] = integration.connections.map((c) => c.id)
|
|
953
|
+
return { revision: draft.revision, threshold: draft.threshold ?? snapshot.preferences.threshold, minimums: draft.minimums ?? snapshot.preferences.minimums, order }
|
|
954
|
+
}
|