dsh-llm-key-loop 0.0.0-stage → 2.4.1

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/client.js ADDED
@@ -0,0 +1,676 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-llm-key-loop',
3
+ factory: (require) => {
4
+ const module = { exports: {} }
5
+ const React = require('react')
6
+ const h = React.createElement
7
+
8
+ const MAX_CHAIN = 9
9
+ /** Status markers the server half writes next to a key when it fails; cleared when the key works again. */
10
+ const MARKERS = [
11
+ { suffix: 'LIMIT', label: 'Limit' },
12
+ { suffix: 'REJECTED', label: 'Rejected' },
13
+ { suffix: 'RATELIMITED', label: 'Throttled' },
14
+ { suffix: 'ERROR', label: 'Error' },
15
+ ]
16
+ /** Every per-key status ref the panel reads: failures, test OK, and a pending test request. */
17
+ const STATUS = [...MARKERS.map((m) => m.suffix), 'OK', 'TESTREQ', 'USAGE', 'USAGE2', 'USAGE3', 'LOCAL']
18
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
19
+ const WINDOWS = { w: ['Weekly', 'weekly'], m: ['Monthly', 'monthly'], h: ['5-hour', '5-hour'], p: ['Plan', 'plan'], f: ['Free', 'free'], d: ['Daily', 'daily'] }
20
+ /** Decode the server's local count `<ref>_LOCAL`: l-RRRRZ••••••••TTTT. */
21
+ const decodeLocal = (masked) => {
22
+ const m = typeof masked === 'string' ? masked.match(/^l-(\d{4})([pl])•+(.{4})$/) : null
23
+ if (!m) return undefined
24
+ const t = m[3]
25
+ const tokens = /^\d{4}$/.test(t) ? String(Number(t)) : t.replace(/_+$/, '')
26
+ return { requests: Number(m[1]), zone: m[2], tokens }
27
+ }
28
+ /** Next local midnight, as clock text. */
29
+ const nextResetText = () => {
30
+ const now = new Date()
31
+ const at = new Date(now); at.setHours(24, 0, 0, 0)
32
+ return `tomorrow ${at.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}`
33
+ }
34
+ /** Decode the server's `<ref>_USAGE*` masked preview: u-PPPFW••••••••MMDD. */
35
+ const decodeUsage = (masked) => {
36
+ const m = typeof masked === 'string' ? masked.match(/^u-(\d{3})([nxfF])(\w)•+(\d{2})(\d{2})$/) : null
37
+ if (!m) return undefined
38
+ const month = Number(m[4]); const day = Number(m[5])
39
+ const kind = WINDOWS[m[3]] ? m[3] : m[2] === 'f' || m[2] === 'F' ? 'f' : 'w'
40
+ return { pct: Number(m[1]), spent: m[2] === 'x' || m[2] === 'F', kind, name: WINDOWS[kind][0], reset: month >= 1 && month <= 12 ? `${MONTHS[month - 1]} ${day}` : null }
41
+ }
42
+ const resetText = (u) => (u.reset ? `${u.kind === 'p' ? 'ends' : 'resets'} ${u.reset}` : '')
43
+ const usageColor = (u) => (u.spent || u.pct >= 90 ? '#e05252' : u.pct >= 70 ? '#e0a13a' : '#2fbf6b')
44
+ const usageTitle = (u) => `${u.pct}% of the ${WINDOWS[u.kind][1]} allowance used${u.spent ? ' (spent)' : ''}${u.reset ? ` · ${resetText(u)}` : ''}`
45
+ /** Ordered, de-duplicated key rows for a provider, as the panel numbers them. */
46
+ const keyRowsOf = (provider, info) => {
47
+ const active = envRefOf(provider)
48
+ const refs = listRefsOf(active)
49
+ const seen = new Set()
50
+ const rows = refs.filter((r) => info[r]?.configured).filter((r) => {
51
+ const m = info[r]?.masked
52
+ if (m === undefined) return true
53
+ if (seen.has(m)) return false
54
+ seen.add(m); return true
55
+ })
56
+ const pending = !info[refs[0]]?.configured && info[active]?.configured === true
57
+ if (pending) rows.unshift(active)
58
+ const label = (i) => (i === 0 && (rows[0] === active || rows[0] === refs[0]) ? 'Main key' : `Key ${i + (rows[0] === active || rows[0] === refs[0] ? 0 : 1)}`)
59
+ const activeMasked = info[active]?.masked
60
+ const inUse = rows.findIndex((r) => activeMasked !== undefined && info[r]?.masked === activeMasked)
61
+ return { active, refs, rows, label, inUse }
62
+ }
63
+ const PLUG = 'M7 2v4M13 2v4M5 6h10v3a5 5 0 0 1-10 0V6zM10 14v4'
64
+
65
+
66
+ const REF_ALIASES = { 'deepseek-official': 'DEEPSEEK_API_KEY' }
67
+ const envRefOf = (p) => REF_ALIASES[p] ?? `${p.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
68
+ const listRefsOf = (a) => [`${a}_DEFAULT`, ...Array.from({ length: MAX_CHAIN }, (_, i) => `${a}_CHAIN_${i + 1}`)]
69
+ const labelOf = (a, ref) => (ref === `${a}_DEFAULT` ? 'Default' : `Key ${ref.slice(a.length + 7)}`)
70
+
71
+ const S = {
72
+ wrap: { marginTop: 24, padding: 16, borderRadius: 12, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', display: 'flex', flexDirection: 'column', gap: 16 },
73
+ title: { margin: 0, fontSize: 16, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' },
74
+ sub: { margin: 0, fontSize: 13, lineHeight: 1.5, color: 'var(--dsw-alias-label-secondary)' },
75
+ prov: { border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: 12, display: 'flex', flexDirection: 'column', gap: 8 },
76
+ provName: { fontWeight: 600, fontSize: 14, color: 'var(--dsw-alias-label-primary)' },
77
+ row: { display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: 'var(--dsw-alias-label-primary)' },
78
+ num: { width: 22, color: 'var(--dsw-alias-label-secondary)' },
79
+ lbl: { width: 112 },
80
+ mono: { fontFamily: 'monospace', fontSize: 12, color: 'var(--dsw-alias-label-secondary)', flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
81
+ failed: { fontSize: 10, fontWeight: 600, lineHeight: '14px', padding: '1px 7px', borderRadius: 999, background: '#d64545', color: '#ffffff', whiteSpace: 'nowrap' },
82
+ active: { fontSize: 10, fontWeight: 600, lineHeight: '14px', padding: '1px 7px', borderRadius: 999, background: '#1f9d55', color: '#ffffff', whiteSpace: 'nowrap' },
83
+ hint: { margin: 0, fontSize: 12, lineHeight: 1.5, color: 'var(--dsw-alias-label-secondary)' },
84
+ ok: { fontSize: 10, fontWeight: 600, lineHeight: '12px', padding: '1px 6px', borderRadius: 999, border: '1px solid #1f9d55', color: '#2fbf6b', whiteSpace: 'nowrap' },
85
+ icon: { width: 30, height: 28, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)', background: 'transparent', color: 'var(--dsw-alias-label-primary)', cursor: 'pointer' },
86
+ btn: { fontSize: 12, padding: '4px 10px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)', background: 'transparent', color: 'var(--dsw-alias-label-primary)', cursor: 'pointer' },
87
+ input: { flex: 1, minWidth: 0, fontSize: 12, padding: '6px 8px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-2)', color: 'var(--dsw-alias-label-primary)' },
88
+ err: { fontSize: 12, color: 'var(--dsw-alias-danger, #d33)' },
89
+ }
90
+
91
+ function ProviderBlock({ remote, provider, info, reload, onRemove }) {
92
+ const active = envRefOf(provider.id)
93
+ const refs = listRefsOf(active)
94
+ const [draft, setDraft] = React.useState('')
95
+ const [error, setError] = React.useState(null)
96
+ const activeMasked = info[active]?.masked
97
+ const stored = refs.filter((r) => info[r]?.configured)
98
+ const seen = new Set()
99
+ const rows = stored.filter((r) => {
100
+ const m = info[r]?.masked
101
+ if (m === undefined) return true
102
+ if (seen.has(m)) return false
103
+ seen.add(m)
104
+ return true
105
+ })
106
+ // A provider not yet in the loop: its current key becomes Default on the first switch.
107
+ const pendingDefault = !info[refs[0]]?.configured && info[active]?.configured === true
108
+ if (pendingDefault) rows.unshift(active)
109
+ const freeSlot = (pendingDefault ? refs.slice(1) : refs).find((r) => !info[r]?.configured)
110
+ const mismatch = provider.apiKeyEnv !== undefined && provider.apiKeyEnv !== active
111
+ const run = async (fn) => {
112
+ setError(null)
113
+ try {
114
+ const r = await fn()
115
+ if (r && r.ok === false) setError(r.error?.message ?? r.error?.code ?? 'The app rejected this change.')
116
+ reload()
117
+ } catch (e) { setError(e?.message ?? String(e)) }
118
+ }
119
+ return h('div', { style: S.prov },
120
+ h('div', { style: S.row },
121
+ h('span', { style: { ...S.provName, flex: 1 } }, `${provider.name} · ${rows.length} key(s)`),
122
+ h('button', { style: S.btn, title: 'Stop looping keys for this provider', onClick: onRemove }, '✕')),
123
+ h('p', { style: S.hint }, 'Main key = the key you entered in Models (a copy is kept here). Keys are used in order when the key in use fails. Red = that key failed the last time it was used; it clears when the key works again. The key field in Models always shows the key in use.'),
124
+ mismatch ? h('div', { style: S.err }, `This provider reads its key from ${provider.apiKeyEnv}, but the loop writes ${active}. Rename its API-key variable to ${active} for the loop to work.`) : null,
125
+ rows.length === 0 ? h('div', { style: S.sub }, 'No keys stored yet.') : null,
126
+ ...rows.map((ref, i) => h('div', { key: ref, style: S.row },
127
+ h('span', { style: S.num }, `${i + 1}.`),
128
+ h('span', { style: S.lbl }, i === 0 && (ref === active || ref === refs[0]) ? 'Main key' : `Key ${i - (rows[0] === active || rows[0] === refs[0] ? 0 : -1)}`),
129
+ h('span', { style: S.mono }, info[ref]?.masked ?? 'stored'),
130
+ (() => { const u = decodeUsage(info[`${ref}_USAGE`]?.masked); return u ? h('span', { title: usageTitle(u), style: { fontSize: 11, fontWeight: 600, color: usageColor(u), minWidth: 34, textAlign: 'right' } }, `${u.pct}%`) : null })(),
131
+ ...MARKERS.filter((m) => info[`${ref}_${m.suffix}`]?.configured || (ref === active && info[`${refs[0]}_${m.suffix}`]?.configured)).map((m) => h('span', { key: m.suffix, style: S.failed }, m.label)),
132
+ activeMasked !== undefined && info[ref]?.masked === activeMasked ? h('span', { style: S.active }, 'Active') : null,
133
+ h('button', {
134
+ style: { ...S.icon, opacity: info[`${ref}_TESTREQ`]?.configured ? 0.5 : 1, ...(info[`${ref}_OK`]?.configured ? { color: '#2fbf6b', borderColor: '#1f9d55' } : {}) },
135
+ title: info[`${ref}_TESTREQ`]?.configured ? 'Testing…' : info[`${ref}_OK`]?.configured ? 'Key works — click to test again' : 'Test this key',
136
+ disabled: info[`${ref}_TESTREQ`]?.configured === true,
137
+ onClick: () => run(() => remote.credentials.set(`${ref}_TESTREQ`, `at-${Date.now()}`)),
138
+ }, info[`${ref}_TESTREQ`]?.configured
139
+ ? h('span', { style: { fontSize: 12 } }, '…')
140
+ : h('svg', { width: 16, height: 16, viewBox: '0 0 20 20', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' }, h('path', { d: PLUG }))),
141
+ ref === active ? null : h('button', { style: S.btn, onClick: () => run(async () => { for (const x of STATUS) if (info[`${ref}_${x}`]?.configured) await remote.credentials.unset(`${ref}_${x}`); return remote.credentials.unset(ref) }) }, 'Remove'),
142
+ )),
143
+ freeSlot === undefined ? null : h('div', { style: S.row },
144
+ h('input', { style: S.input, type: 'password', placeholder: freeSlot === refs[0] ? 'Paste your main key…' : `Paste a key to add as Key ${rows.filter((r) => r !== active && r !== refs[0]).length + 1}…`, value: draft, onChange: (e) => setDraft(e.target.value) }),
145
+ h('button', { style: S.btn, disabled: draft.trim() === '', onClick: () => run(async () => { const r = await remote.credentials.set(freeSlot, draft.trim()); if (!r || r.ok !== false) setDraft(''); return r }) }, 'Add key'),
146
+ ),
147
+ error ? h('div', { style: S.err }, error) : null,
148
+ )
149
+ }
150
+
151
+ /** Unwrap the remote `{ ok, value }` envelope. */
152
+ const unwrap = (r) => (r && r.ok === true ? r.value : r && r.ok === undefined ? r : undefined)
153
+ /** Describe any number of refs: the app accepts at most 64 names per call, so ask in batches. */
154
+ const describeAll = async (remote, refs) => {
155
+ const unique = [...new Set(refs)]
156
+ const parts = []
157
+ for (let i = 0; i < unique.length; i += 60) parts.push(unique.slice(i, i + 60))
158
+ const answers = await Promise.all(parts.map((c) => remote.credentials.describe(c).then(unwrap).catch(() => undefined)))
159
+ return Object.assign({}, ...answers.filter(Boolean))
160
+ }
161
+
162
+ /** Provider catalog: the ones set up in Models plus the "Add model provider" list. */
163
+ function useProviders(remote) {
164
+ const [all, setAll] = React.useState([])
165
+ const [listError, setListError] = React.useState(null)
166
+ React.useEffect(() => {
167
+ let live = true
168
+ Promise.allSettled([remote.llm.listProviders(), remote.llm.listConfigurableProviders()]).then(([reg, dec]) => {
169
+ if (!live) return
170
+ const errs = []
171
+ const regRows = reg.status === 'fulfilled' ? unwrap(reg.value) : undefined
172
+ const decRows = dec.status === 'fulfilled' ? unwrap(dec.value) : undefined
173
+ if (regRows === undefined) errs.push(`providers: ${reg.reason?.message ?? reg.value?.error?.message ?? 'unavailable'}`)
174
+ if (decRows === undefined) errs.push(`catalog: ${dec.reason?.message ?? dec.value?.error?.message ?? 'unavailable'}`)
175
+ const usable = new Set((regRows ?? []).map((e) => e.id))
176
+ const byId = new Map()
177
+ for (const e of regRows ?? []) byId.set(e.id, { id: e.id, name: e.name ?? e.id, usable: true })
178
+ for (const d of decRows ?? []) {
179
+ if (d.provider === 'deepseek-account') continue
180
+ const prev = byId.get(d.provider)
181
+ byId.set(d.provider, { id: d.provider, name: d.displayName ?? prev?.name ?? d.provider, apiKeyEnv: d.apiKeyEnv, usable: usable.has(d.provider) })
182
+ }
183
+ setAll([...byId.values()].sort((a, b) => a.name.localeCompare(b.name)))
184
+ setListError(errs.length ? errs.join(' · ') : null)
185
+ })
186
+ return () => { live = false }
187
+ }, [])
188
+ return { all, listError }
189
+ }
190
+
191
+ const PAGE_CSS = `
192
+ .lkp{display:flex;width:100%;height:100%;min-height:0;color:var(--dsw-alias-label-primary);font-size:13px}
193
+ .lkp-side{box-sizing:border-box;flex:none;width:248px;border-right:.5px solid var(--dsw-alias-border-l2);padding:16px 10px;overflow:auto;display:flex;flex-direction:column;gap:2px}
194
+ .lkp-sideTitle{margin:0 8px 10px;font-size:15px;font-weight:600}
195
+ .lkp-item{box-sizing:border-box;width:100%;display:flex;flex-direction:column;gap:3px;text-align:left;background:0 0;border:none;border-radius:var(--dsw-radius-md);padding:8px 10px;color:inherit;font:inherit;cursor:pointer}
196
+ .lkp-item:hover{background:var(--dsw-alias-interactive-bg-hover)}
197
+ .lkp-item[aria-current=true]{background:var(--dsw-alias-interactive-bg-hover)}
198
+ .lkp-itemTop{display:flex;align-items:center;gap:8px;min-width:0}
199
+ .lkp-dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--dsw-alias-border-l2)}
200
+ .lkp-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}
201
+ .lkp-meta{padding-left:16px;font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
202
+ .lkp-hint{margin:12px 8px 0;font-size:11px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
203
+ .lkp-main{box-sizing:border-box;flex:1;min-width:0;overflow:auto;padding:24px 32px 40px}
204
+ .lkp-body{max-width:760px;display:flex;flex-direction:column;gap:20px}
205
+ .lkp-head h2{margin:0;font-size:20px;font-weight:600}
206
+ .lkp-head p{margin:4px 0 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary)}
207
+ .lkp-sec{display:flex;flex-direction:column;gap:10px}
208
+ .lkp-secTitle{margin:0;font-size:11px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--dsw-alias-label-tertiary)}
209
+ .lkp-card{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-3);padding:12px 14px;display:flex;flex-direction:column;gap:10px}
210
+ .lkp-cardHead{display:flex;align-items:center;gap:8px}
211
+ .lkp-cardName{font-weight:500}
212
+ .lkp-cardMask{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:monospace;font-size:11px;color:var(--dsw-alias-label-tertiary)}
213
+ .lkp-win{display:grid;grid-template-columns:76px minmax(0,1fr) 44px auto;align-items:center;gap:12px;font-variant-numeric:tabular-nums}
214
+ .lkp-win .lkp-wlabel{color:var(--dsw-alias-label-secondary)}
215
+ .lkp-track{height:6px;border-radius:3px;background:var(--dsw-alias-border-l2);overflow:hidden}
216
+ .lkp-track>i{display:block;height:100%;border-radius:3px}
217
+ .lkp-pct{text-align:right;font-weight:600}
218
+ .lkp-reset{font-size:11px;color:var(--dsw-alias-label-tertiary);white-space:nowrap}
219
+ .lkp-kv{display:grid;grid-template-columns:96px minmax(0,1fr);gap:6px 12px;margin:0;align-items:center}
220
+ .lkp-kv dt{color:var(--dsw-alias-label-secondary)}
221
+ .lkp-kv dd{margin:0;font-variant-numeric:tabular-nums}
222
+ .lkp-note{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}
223
+ .lkp-key{padding:8px 14px;gap:8px}
224
+ .lkp-keyTop{display:flex;align-items:center;gap:10px;cursor:pointer;min-height:32px}
225
+ .lkp-chev{flex:none;width:12px;color:var(--dsw-alias-label-tertiary);transition:transform .16s}
226
+ .lkp-keyBar{flex:1;min-width:40px;display:flex}
227
+ .lkp-keyBar .lkp-track{width:100%}
228
+ .lkp-keyTop .lkp-pct{min-width:48px}
229
+ .lkp-keyMore{display:flex;flex-direction:column;gap:10px;padding:4px 0 6px 22px}
230
+ .lkp-add{display:flex;gap:10px;align-items:center}
231
+ .lkp-empty{margin:auto;color:var(--dsw-alias-label-tertiary)}
232
+ `
233
+ const PanelIcon = ({ size = 18 }) => h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.25, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
234
+ h('circle', { cx: 5.25, cy: 10.75, r: 2.75 }),
235
+ h('path', { d: 'M7.2 8.8 13 3M11 5l1.6 1.6M12.6 3.4 14 4.8' }))
236
+
237
+ const USAGE_KEYS = ['USAGE', 'USAGE2', 'USAGE3']
238
+ const windowsFor = (info, ref, active, isCurrent) => {
239
+ const own = USAGE_KEYS.map((x) => decodeUsage(info[`${ref}_${x}`]?.masked)).filter(Boolean)
240
+ const list = own.length > 0 || !isCurrent ? own : USAGE_KEYS.map((x) => decodeUsage(info[`${active}_${x}`]?.masked)).filter(Boolean)
241
+ return list.sort((a, b) => 'hwmpf'.indexOf(a.kind) - 'hwmpf'.indexOf(b.kind))
242
+ }
243
+ const localFor = (info, ref, active, isCurrent) => decodeLocal(info[`${ref}_LOCAL`]?.masked) ?? (isCurrent ? decodeLocal(info[`${active}_LOCAL`]?.masked) : undefined)
244
+ const rpdOf = (info, active) => { const m = (info[`${active}_RPD`]?.masked ?? '').match(/^r-(\d+)/); return m ? Number(m[1]) : undefined }
245
+
246
+ /** One merged row per key: usage bar, badges, test, remove; click to expand the details. */
247
+ function KeyRow({ remote, ctxInfo, ref_, i, rows, label, inUse, active, refs, run, rpd }) {
248
+ const info = ctxInfo
249
+ const [open, setOpen] = React.useState(false)
250
+ const isCur = i === inUse
251
+ const windows = windowsFor(info, ref_, active, isCur)
252
+ const local = localFor(info, ref_, active, isCur)
253
+ const failed = MARKERS.filter((m) => info[`${ref_}_${m.suffix}`]?.configured || (isCur && info[`${active}_${m.suffix}`]?.configured)).map((m) => m.label)
254
+ const testing = info[`${ref_}_TESTREQ`]?.configured === true
255
+ const works = info[`${ref_}_OK`]?.configured === true
256
+ const top = windows[0]
257
+ const stop = (e) => e.stopPropagation()
258
+ return h('div', { className: 'lkp-card lkp-key', 'data-open': open },
259
+ h('div', { className: 'lkp-keyTop', onClick: () => setOpen(!open), role: 'button', tabIndex: 0, 'aria-expanded': open, onKeyDown: (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(!open) } } },
260
+ h('span', { className: 'lkp-chev', style: { transform: open ? 'rotate(90deg)' : 'none' } }, '›'),
261
+ h('span', { className: 'lkp-cardName' }, label(i)),
262
+ isCur ? h('span', { style: S.active }, 'Active') : null,
263
+ failed.map((f) => h('span', { key: f, style: S.failed }, f)),
264
+ h('span', { className: 'lkp-keyBar' },
265
+ top ? h('span', { className: 'lkp-track' }, h('i', { style: { width: `${Math.max(2, Math.min(100, top.pct))}%`, background: usageColor(top) } })) : null),
266
+ h('span', { className: 'lkp-pct', style: top ? (top.spent || top.pct >= 90 ? { color: usageColor(top) } : null) : { fontWeight: 400, color: 'var(--dsw-alias-label-secondary)' } },
267
+ top ? `${top.pct}%` : local ? `${local.requests} req` : '—'),
268
+ h('button', { style: { ...S.icon, opacity: testing ? 0.5 : 1, ...(works ? { color: '#2fbf6b', borderColor: '#1f9d55' } : {}) }, title: testing ? 'Testing…' : works ? 'Key works — click to test again' : 'Test this key', disabled: testing,
269
+ onClick: (e) => { stop(e); run(() => remote.credentials.set(`${ref_}_TESTREQ`, `at-${Date.now()}`)) } },
270
+ testing ? h('span', { style: { fontSize: 12 } }, '…') : h('svg', { width: 16, height: 16, viewBox: '0 0 20 20', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' }, h('path', { d: PLUG }))),
271
+ ref_ === active ? null : h('button', { style: S.btn, onClick: (e) => { stop(e); run(async () => { for (const x of STATUS) if (info[`${ref_}_${x}`]?.configured) await remote.credentials.unset(`${ref_}_${x}`); return remote.credentials.unset(ref_) }) } }, 'Remove')),
272
+ open ? h('div', { className: 'lkp-keyMore' },
273
+ h('div', { className: 'lkp-cardMask', style: { flex: 'none' } }, info[ref_]?.masked ?? 'stored'),
274
+ windows.map((u) => h('div', { key: u.kind, className: 'lkp-win', title: usageTitle(u) },
275
+ h('span', { className: 'lkp-wlabel' }, u.name),
276
+ h('span', { className: 'lkp-track' }, h('i', { style: { width: `${Math.max(2, Math.min(100, u.pct))}%`, background: usageColor(u) } })),
277
+ h('span', { className: 'lkp-pct', style: u.spent || u.pct >= 90 ? { color: usageColor(u) } : null }, `${u.pct}%`),
278
+ h('span', { className: 'lkp-reset' }, [u.spent ? 'spent' : '', resetText(u)].filter(Boolean).join(' · ')))),
279
+ windows.length === 0 ? h('dl', { className: 'lkp-kv' },
280
+ h('dt', null, 'Requests today'), h('dd', null, local ? (rpd ? `${local.requests} of ${rpd}` : String(local.requests)) : '0'),
281
+ h('dt', null, 'Tokens today'), h('dd', null, local ? local.tokens : '0'),
282
+ h('dt', null, 'Resets'), h('dd', null, nextResetText())) : null) : null)
283
+ }
284
+
285
+ function ProviderDetail({ remote, provider, info, reload, onRemove }) {
286
+ const { rows, label, inUse, active, refs } = keyRowsOf(provider.id, info)
287
+ const anyReported = rows.some((ref, i) => windowsFor(info, ref, active, i === inUse).length > 0)
288
+ const rpd = rpdOf(info, active)
289
+ const [draft, setDraft] = React.useState('')
290
+ const [error, setError] = React.useState(null)
291
+ const pendingDefault = !info[refs[0]]?.configured && info[active]?.configured === true
292
+ const freeSlot = (pendingDefault ? refs.slice(1) : refs).find((r) => !info[r]?.configured)
293
+ const mismatch = provider.apiKeyEnv !== undefined && provider.apiKeyEnv !== active
294
+ const run = async (fn) => {
295
+ setError(null)
296
+ try {
297
+ const r = await fn()
298
+ if (r && r.ok === false) setError(r.error?.message ?? r.error?.code ?? 'The app rejected this change.')
299
+ reload()
300
+ } catch (e) { setError(e?.message ?? String(e)) }
301
+ }
302
+ return h('div', { className: 'lkp-body' },
303
+ h('div', { className: 'lkp-head' },
304
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
305
+ h('h2', { style: { flex: 1 } }, provider.name),
306
+ rows.length > 1 ? h('button', { style: S.btn, title: 'Stop looping keys for this provider', onClick: onRemove }, 'Stop looping') : null),
307
+ h('p', null, `${rows.length} key${rows.length === 1 ? '' : 's'}. ${rows.length > 1 ? 'Used in order; when the key in use fails the next one takes over — never another provider. Click a key for details.' : 'Add a backup key below to switch automatically when this one runs out.'}`)),
308
+ mismatch ? h('div', { style: S.err }, `This provider reads its key from ${provider.apiKeyEnv}, but the loop writes ${active}. Rename its API-key variable to ${active} for the loop to work.`) : null,
309
+ h('div', { className: 'lkp-sec' },
310
+ h('h3', { className: 'lkp-secTitle' }, 'Keys'),
311
+ rows.length === 0 ? h('p', { className: 'lkp-note' }, 'No keys stored yet. Paste one below.') : null,
312
+ ...rows.map((ref, i) => h(KeyRow, { key: ref, remote, ctxInfo: info, ref_: ref, i, rows, label, inUse, active, refs, run, rpd })),
313
+ freeSlot === undefined ? null : h('div', { className: 'lkp-add' },
314
+ h('input', { style: S.input, type: 'password', placeholder: freeSlot === refs[0] ? 'Paste your main key…' : `Paste a key to add as Key ${rows.filter((r) => r !== active && r !== refs[0]).length + 1}…`, value: draft, onChange: (e) => setDraft(e.target.value) }),
315
+ h('button', { style: S.btn, disabled: draft.trim() === '', onClick: () => run(async () => { const r = await remote.credentials.set(freeSlot, draft.trim()); if (!r || r.ok !== false) setDraft(''); return r }) }, 'Add key')),
316
+ error ? h('div', { style: S.err }, error) : null),
317
+ rows.length > 0 && !anyReported
318
+ ? h('div', { className: 'lkp-sec' },
319
+ h('h3', { className: 'lkp-secTitle' }, 'Daily limit'),
320
+ h('div', { className: 'lkp-card' },
321
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } },
322
+ h('input', { type: 'number', min: 1, key: `rpd-${rpd ?? 'none'}`, placeholder: 'requests/day', defaultValue: rpd ?? '', style: { ...S.input, flex: 'none', width: 120 },
323
+ onKeyDown: (e) => { if (e.key === 'Enter') e.currentTarget.blur() },
324
+ onBlur: (e) => {
325
+ const n = Math.floor(Number(e.currentTarget.value))
326
+ if (Number.isFinite(n) && n > 0) remote.credentials.set(`${active}_RPD`, `r-${String(Math.min(n, 99999)).padStart(5, '0')}${'0'.repeat(8)}0000`).then(reload).catch(() => {})
327
+ else if (e.currentTarget.value === '' && rpd !== undefined) remote.credentials.unset(`${active}_RPD`).then(reload).catch(() => {})
328
+ } }),
329
+ h('p', { className: 'lkp-note', style: { flex: 1 } }, `${provider.name} does not report usage to API keys, so this app counts its own requests and tokens (today, from this app). Set a limit to see a percentage.`))))
330
+ : null)
331
+ }
332
+
333
+ /** Left-menu page: providers on the left, the selected provider's keys and usage on the right. */
334
+ function KeyLoopPage({ remote }) {
335
+ const { all, listError } = useProviders(remote)
336
+ const [info, setInfo] = React.useState({})
337
+ const [tick, setTick] = React.useState(0)
338
+ const reload = React.useCallback(() => setTick((t) => t + 1), [])
339
+ const [sel, setSel] = React.useState(() => { try { return window.localStorage.getItem('llm-key-loop:page') } catch { return null } })
340
+ const visible = all.filter((p) => p.usable && !/^deepseek-account/.test(p.id) && p.name !== 'DeepSeek Account')
341
+ const current = visible.find((p) => p.id === sel) ?? visible[0]
342
+
343
+ React.useEffect(() => {
344
+ let live = true
345
+ const refs = []
346
+ for (const p of visible) {
347
+ const a = envRefOf(p.id)
348
+ const chain = listRefsOf(a)
349
+ refs.push(a, ...chain, ...USAGE_KEYS.map((x) => `${a}_${x}`), `${a}_LOCAL`)
350
+ if (p.id === current?.id) refs.push(`${a}_RPD`, `${a}_PIN`, ...STATUS.map((x) => `${a}_${x}`), ...chain.flatMap((r) => STATUS.map((x) => `${r}_${x}`)))
351
+ }
352
+ describeAll(remote, refs).then((v) => { if (live) setInfo(v) }).catch(() => {})
353
+ return () => { live = false }
354
+ }, [tick, all, current?.id])
355
+ React.useEffect(() => {
356
+ const off = remote.$on?.('credentials/reference-updated', reload)
357
+ const timer = setInterval(reload, 2500)
358
+ return () => { clearInterval(timer); if (typeof off === 'function') off() }
359
+ }, [])
360
+
361
+ const removeProvider = async (p) => {
362
+ if (!window.confirm(`Stop key looping for ${p.name}? This deletes its Default and backup key copies from the loop. The key the provider is using now is kept.`)) return
363
+ for (const ref of listRefsOf(envRefOf(p.id))) if (info[ref]?.configured) await remote.credentials.unset(ref).catch(() => {})
364
+ reload()
365
+ }
366
+
367
+ const summary = (p) => {
368
+ const { rows, inUse, active } = keyRowsOf(p.id, info)
369
+ const w = windowsFor(info, rows[inUse] ?? active, active, true)
370
+ const top = w[0]
371
+ const local = localFor(info, rows[inUse] ?? active, active, true)
372
+ const bad = (r) => MARKERS.some((m) => info[`${r}_${m.suffix}`]?.configured)
373
+ const curBad = MARKERS.some((m) => info[`${active}_${m.suffix}`]?.configured) || (rows[inUse] !== undefined && bad(rows[inUse]))
374
+ const hot = rows.length > 0 && (curBad || rows.every(bad))
375
+ const some = rows.some(bad)
376
+ return { count: rows.length, top, local, hot, some }
377
+ }
378
+
379
+ return h('div', { className: 'lkp' },
380
+ h('nav', { className: 'lkp-side', 'aria-label': 'Providers' },
381
+ h('h1', { className: 'lkp-sideTitle' }, 'Key Loop'),
382
+ visible.length === 0 ? h('p', { className: 'lkp-hint' }, listError ? `Could not load providers (${listError}).` : 'Loading providers…') : null,
383
+ ...visible.map((p) => {
384
+ const s = summary(p)
385
+ const color = s.hot ? '#d64545' : s.some && !(s.top && (s.top.spent || s.top.pct >= 90)) ? '#e0a13a' : s.top ? usageColor(s.top) : s.count > 0 ? '#2fbf6b' : undefined
386
+ const meta = s.count === 0 ? 'No key' : [`${s.count} key${s.count === 1 ? '' : 's'}`, s.top ? `${s.top.name} ${s.top.pct}%` : s.local ? `${s.local.requests} req today` : null].filter(Boolean).join(' · ')
387
+ return h('button', { key: p.id, type: 'button', className: 'lkp-item', 'aria-current': p.id === current?.id, onClick: () => { setSel(p.id); try { window.localStorage.setItem('llm-key-loop:page', p.id) } catch {} } },
388
+ h('span', { className: 'lkp-itemTop' }, h('span', { className: 'lkp-dot', style: color ? { background: color } : null }), h('span', { className: 'lkp-name' }, p.name)),
389
+ h('span', { className: 'lkp-meta' }, meta))
390
+ }),
391
+ h('p', { className: 'lkp-hint' }, 'Providers appear here once they are set up in Settings → Models.')),
392
+ h('main', { className: 'lkp-main' },
393
+ current
394
+ ? h(ProviderDetail, { key: current.id, remote, provider: current, info, reload, onRemove: () => removeProvider(current) })
395
+ : h('p', { className: 'lkp-empty' }, 'Set up a provider in Settings → Models to manage its keys here.')))
396
+ }
397
+
398
+ /** What stays in Settings → Models: a pointer to the page. */
399
+ function SettingsNote() {
400
+ return h('section', { style: S.wrap }, h('h3', { style: S.title }, 'Key Loop'), h('p', { style: S.sub }, 'Backup keys, usage and key tests now live on their own page: click the key icon in the left menu.'))
401
+ }
402
+
403
+ // ── Status-line entry under the composer (matches the native stats items) ──
404
+ const DOCK_CSS = `
405
+ .lkl-anchor{min-width:0;font-size:calc(var(--dsh-content-font-size-secondary,13px) - 1px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));display:inline-flex}
406
+ .lkl-pill{box-sizing:border-box;border-radius:var(--dsw-radius-sm);max-width:100%;color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;line-height:inherit;white-space:nowrap;background:0 0;border:none;align-items:center;gap:6px;padding:1px 8px;display:inline-flex;cursor:pointer}
407
+ .lkl-pill svg{flex:none;width:14px;height:14px}
408
+ .lkl-pill[aria-expanded=true]{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}
409
+ @media (hover:hover){.lkl-pill:hover{background:var(--dsw-alias-interactive-bg-hover);color:var(--dsw-alias-label-secondary)}}
410
+ .lkl-sep{color:var(--dsw-alias-separator-primary);margin:0 6px}
411
+ .lkl-panel{z-index:1100;box-sizing:border-box;border-radius:var(--dsw-radius-lg);background:var(--dsw-specific-menu);width:max-content;min-width:min(300px,100vw - 24px);max-width:min(440px,100vw - 24px);backdrop-filter:var(--dsw-menu-backdrop-filter);--dsw-elevation-stroke-color:var(--dsw-alias-border-l1);box-shadow:var(--dsw-elevation-prominent);color:var(--dsw-alias-label-secondary);cursor:default;position:fixed;padding:16px;font-size:12px;line-height:18px;max-height:calc(100dvh - 24px);overflow:hidden auto}
412
+ .lkl-title{color:var(--dsw-alias-label-primary);justify-content:space-between;gap:16px;margin-bottom:8px;font-weight:500;display:flex}
413
+ .lkl-titleLabel{align-items:center;gap:6px;min-width:0;display:inline-flex}
414
+ .lkl-titleLabel svg{flex:none;width:14px;height:14px}
415
+ .lkl-titleValue{font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary);font-weight:400}
416
+ .lkl-rule{border-top:.5px solid var(--dsw-alias-border-l2);margin-bottom:10px}
417
+ .lkl-details{color:var(--dsw-alias-label-tertiary);grid-template-columns:minmax(76px,auto) minmax(0,1fr);gap:8px 16px;margin:0;display:grid;align-items:center}
418
+ .lkl-details dt,.lkl-details dd{min-width:0;margin:0}
419
+ .lkl-details dt.lkl-cur{color:var(--dsw-alias-label-primary)}
420
+ .lkl-details dd{color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;display:flex;align-items:center;justify-content:flex-end;gap:8px;white-space:nowrap}
421
+ .lkl-bar{width:56px;height:4px;border-radius:2px;background:var(--dsw-alias-border-l2);overflow:hidden;flex:none}
422
+ .lkl-bar>i{display:block;height:100%;border-radius:2px}
423
+ .lkl-note{margin-top:10px;color:var(--dsw-alias-label-tertiary)}
424
+ .lkl-cell{box-sizing:border-box;border-radius:var(--dsw-radius-md);width:auto;min-width:100%;height:34px;color:var(--dsw-alias-label-primary);cursor:pointer;text-align:left;background:0 0;border:none;outline:none;align-items:center;gap:6px;padding:0 8px;font-size:13px;line-height:20px;display:flex}
425
+ .lkl-cell:hover,.lkl-cell:focus-visible,.lkl-opt:hover,.lkl-opt:focus-visible{background:var(--dsw-alias-interactive-bg-hover)}
426
+ .lkl-cell:disabled,.lkl-opt:disabled{color:var(--dsw-alias-label-dimmed);cursor:default;background:0 0}
427
+ .lkl-cellLabel{white-space:nowrap;flex:none}
428
+ .lkl-cellValue{text-overflow:ellipsis;white-space:nowrap;text-align:right;min-width:0;color:var(--dsw-alias-label-tertiary);flex:auto;overflow:hidden}
429
+ .lkl-chev{width:12px;height:12px;color:var(--dsw-alias-menu-icon);flex:none;transition:transform .16s}
430
+ .lkl-chevOpen{transform:rotate(90deg)}
431
+ .lkl-opts{display:flex;flex-direction:column;padding:2px 0 4px}
432
+ .lkl-opt{box-sizing:border-box;border-radius:var(--dsw-radius-md);width:100%;min-height:34px;color:var(--dsw-alias-label-primary);text-align:left;cursor:pointer;background:0 0;border:none;outline:none;align-items:center;gap:6px;padding:5px 8px 5px 10px;font-size:13px;line-height:18px;display:flex}
433
+ .lkl-check{color:var(--dsw-alias-label-primary);flex:0 0 14px;place-items:center;display:grid}
434
+ .lkl-optText{display:flex;flex-direction:column;min-width:0;flex:auto}
435
+ .lkl-optSub{font-size:11px;line-height:15px;color:var(--dsw-alias-label-tertiary)}
436
+ .lkl-optMeta{flex:none;font-size:12px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-tertiary)}
437
+ `
438
+ const KeyIcon = () => h('svg', { viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.25, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
439
+ h('circle', { cx: 5.25, cy: 10.75, r: 2.75 }),
440
+ h('path', { d: 'M7.2 8.8 13 3M11 5l1.6 1.6M12.6 3.4 14 4.8' }))
441
+
442
+ let ReactDOM
443
+ try { ReactDOM = require('react-dom') } catch { ReactDOM = undefined }
444
+
445
+ /** Status-line item: "Key 1 · 74%". Click for every key's usage. */
446
+ function KeyDock({ remote, directory }) {
447
+ const snap = React.useSyncExternalStore((cb) => directory.subscribe(cb), () => directory.getSnapshot())
448
+ const provider = snap?.pending?.provider ?? snap?.current?.provider
449
+ const providerName = (snap?.groups ?? []).find((g) => g?.id === provider)?.name
450
+ const [info, setInfo] = React.useState({})
451
+ const [tick, setTick] = React.useState(0)
452
+ const [open, setOpen] = React.useState(false)
453
+ const [pos, setPos] = React.useState(null)
454
+ const btnRef = React.useRef(null)
455
+ const panelRef = React.useRef(null)
456
+
457
+ React.useEffect(() => {
458
+ const off = remote.$on?.('credentials/reference-updated', () => setTick((t) => t + 1))
459
+ const timer = setInterval(() => setTick((t) => t + 1), 10000)
460
+ return () => { clearInterval(timer); if (typeof off === 'function') off() }
461
+ }, [])
462
+ React.useEffect(() => {
463
+ if (typeof provider !== 'string') return undefined
464
+ let live = true
465
+ const active = envRefOf(provider)
466
+ const U = ['USAGE', 'USAGE2', 'USAGE3']
467
+ const refs = [active, `${active}_PIN`, `${active}_RPD`, `${active}_LOCAL`, ...U.map((x) => `${active}_${x}`), ...listRefsOf(active).flatMap((r) => [r, `${r}_LOCAL`, ...U.map((x) => `${r}_${x}`), `${r}_LIMIT`, `${r}_REJECTED`, `${r}_RATELIMITED`])]
468
+ describeAll(remote, refs).then((v) => { if (live) setInfo(v) }).catch(() => {})
469
+ return () => { live = false }
470
+ }, [provider, tick])
471
+ React.useEffect(() => {
472
+ if (!open) return undefined
473
+ const place = () => {
474
+ const r = btnRef.current?.getBoundingClientRect()
475
+ if (r) setPos({ left: Math.max(12, Math.min(r.left, window.innerWidth - 460)), bottom: window.innerHeight - r.top + 8 })
476
+ }
477
+ place()
478
+ const onDown = (e) => { if (!panelRef.current?.contains(e.target) && !btnRef.current?.contains(e.target)) setOpen(false) }
479
+ const onKey = (e) => { if (e.key === 'Escape') setOpen(false) }
480
+ window.addEventListener('pointerdown', onDown, true)
481
+ window.addEventListener('keydown', onKey)
482
+ window.addEventListener('resize', place)
483
+ return () => { window.removeEventListener('pointerdown', onDown, true); window.removeEventListener('keydown', onKey); window.removeEventListener('resize', place) }
484
+ }, [open])
485
+
486
+ if (typeof provider !== 'string') return null
487
+ const { rows, label, inUse, active } = keyRowsOf(provider, info)
488
+ if (rows.length === 0 || inUse < 0) return null
489
+ const single = rows.length === 1
490
+ /** All limit windows reported for a key (the first is the one closest to its limit). */
491
+ const windowsOf = (ref) => {
492
+ const own = ['USAGE', 'USAGE2', 'USAGE3'].map((x) => decodeUsage(info[`${ref}_${x}`]?.masked)).filter(Boolean)
493
+ if (own.length > 0 || ref !== rows[inUse]) return own
494
+ return ['USAGE', 'USAGE2', 'USAGE3'].map((x) => decodeUsage(info[`${active}_${x}`]?.masked)).filter(Boolean)
495
+ }
496
+ const usageOf = (ref) => windowsOf(ref)[0]
497
+ const cur = usageOf(rows[inUse])
498
+ const warn = cur && (cur.spent || cur.pct >= 90)
499
+ const name = providerName ?? provider
500
+ const localOf = (ref) => decodeLocal(info[`${ref}_LOCAL`]?.masked) ?? (ref === rows[inUse] ? decodeLocal(info[`${active}_LOCAL`]?.masked) : undefined)
501
+ const curLocal = localOf(rows[inUse])
502
+ const reported = cur !== undefined && cur.kind !== 'd'
503
+ const limitSet = /^r-\d/.test(info[`${active}_RPD`]?.masked ?? '')
504
+ const text = single
505
+ ? (cur ? `${cur.name} · ${cur.pct}%` : curLocal ? `Today · ${curLocal.requests} req` : name)
506
+ : (cur ? `${label(inUse)} · ${cur.pct}%` : curLocal ? `${label(inUse)} · ${curLocal.requests} req` : label(inUse))
507
+ const failedOf = (ref) => (info[`${ref}_LIMIT`]?.configured ? 'limit' : info[`${ref}_REJECTED`]?.configured ? 'rejected' : info[`${ref}_RATELIMITED`]?.configured ? 'throttled' : null)
508
+ const muted = { color: 'var(--dsw-alias-label-tertiary)' }
509
+
510
+ /** One label/value row: bar, percent, reset text. */
511
+ const usageRow = (key, title, u, extra, current) => {
512
+ const color = u ? usageColor(u) : 'var(--dsw-alias-label-tertiary)'
513
+ const parts = []
514
+ if (u) parts.push(h('span', { key: 'b', className: 'lkl-bar' }, h('i', { style: { width: `${Math.max(2, u.pct)}%`, background: color } })))
515
+ parts.push(h('span', { key: 'p', style: u && (u.spent || u.pct >= 90) ? { color } : null }, u ? `${u.pct}%` : (extra ?? '—')))
516
+ if (u && (u.reset || u.spent)) parts.push(h('span', { key: 'r', style: muted }, [u.spent ? 'spent' : '', resetText(u)].filter(Boolean).join(' · ')))
517
+ else if (u && extra) parts.push(h('span', { key: 'f', style: muted }, extra))
518
+ return [h('dt', { key: `t${key}`, className: current ? 'lkl-cur' : undefined }, title), h('dd', { key: `d${key}` }, ...parts)]
519
+ }
520
+
521
+ const curWindows = windowsOf(rows[inUse])
522
+ const sections = []
523
+ if (!single) {
524
+ sections.push(h('dl', { key: 'keys', className: 'lkl-details' },
525
+ ...rows.flatMap((ref, i) => usageRow(ref, i === inUse ? `${label(i)} · in use` : label(i), usageOf(ref), failedOf(ref), i === inUse))))
526
+ }
527
+ if (single ? curWindows.length > 0 : curWindows.length > 1) {
528
+ if (!single) sections.push(h('div', { key: 'r2', className: 'lkl-rule', style: { margin: '12px 0 10px' }, 'aria-hidden': true }))
529
+ sections.push(h('dl', { key: 'win', className: 'lkl-details' },
530
+ ...(!single ? [h('dt', { key: 'wh', style: { gridColumn: '1 / -1', color: 'var(--dsw-alias-label-secondary)' } }, `${label(inUse)} limits`)] : []),
531
+ ...[...curWindows].sort((a, b) => 'hwmpf'.indexOf(a.kind) - 'hwmpf'.indexOf(b.kind)).flatMap((u) => usageRow(`w${u.kind}`, u.name, u, null, false))))
532
+ }
533
+ const pinned = info[`${active}_PIN`]?.configured === true
534
+ if (!reported) {
535
+ const loc = curLocal ?? { requests: 0, tokens: '0', zone: 'l' }
536
+ sections.push(h('div', { key: 'r3', className: 'lkl-rule', style: { margin: sections.length ? '12px 0 10px' : '0 0 10px', borderTop: sections.length ? undefined : 'none' }, 'aria-hidden': true }))
537
+ sections.push(h('dl', { key: 'loc', className: 'lkl-details' },
538
+ h('dt', { key: 'lh', style: { gridColumn: '1 / -1', color: 'var(--dsw-alias-label-secondary)' } }, single ? 'Today (counted in this app)' : `${label(inUse)} · today (counted in this app)`),
539
+ h('dt', { key: 'lr' }, 'Requests'), h('dd', { key: 'lrv' }, limitSet ? `${loc.requests} of ${Number(info[`${active}_RPD`].masked.match(/^r-(\d+)/)[1])}` : String(loc.requests)),
540
+ h('dt', { key: 'lt' }, 'Tokens'), h('dd', { key: 'ltv' }, loc.tokens),
541
+ h('dt', { key: 'lz' }, 'Resets'), h('dd', { key: 'lzv' }, nextResetText()),
542
+ h('dt', { key: 'll' }, 'Daily limit'),
543
+ h('dd', { key: 'llv' },
544
+ h('input', { type: 'number', min: 1, placeholder: 'requests/day', defaultValue: limitSet ? Number(info[`${active}_RPD`].masked.match(/^r-(\d+)/)[1]) : '', style: { width: 96, fontSize: 12, padding: '2px 6px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l2)', background: 'transparent', color: 'var(--dsw-alias-label-primary)', textAlign: 'right' },
545
+ onKeyDown: (e) => { if (e.key === 'Enter') e.currentTarget.blur() },
546
+ onBlur: (e) => {
547
+ const n = Math.floor(Number(e.currentTarget.value))
548
+ if (Number.isFinite(n) && n > 0) remote.credentials.set(`${active}_RPD`, `r-${String(Math.min(n, 99999)).padStart(5, '0')}${'0'.repeat(8)}0000`).then(() => setTick((t) => t + 1)).catch(() => {})
549
+ else if (e.currentTarget.value === '' && limitSet) remote.credentials.unset(`${active}_RPD`).then(() => setTick((t) => t + 1)).catch(() => {})
550
+ } }))))
551
+ }
552
+ const note = pinned ? `${label(inUse)} was chosen by hand, so automatic switching is paused. Pick Key → Default in the model menu to resume.` : reported
553
+ ? (single ? `Usage reported by ${name}. Add backup keys in Settings → Models → Key Loop to switch automatically.` : 'Switches to the next key when the one in use runs out.')
554
+ : `${name} does not report usage to API keys, so this app counts its own requests.${single ? '' : ' Switches to the next key when the one in use fails.'}`
555
+
556
+ const panel = h('div', { ref: panelRef, className: 'lkl-panel', role: 'dialog', 'aria-label': 'API keys', style: pos ? { left: pos.left, bottom: pos.bottom } : { visibility: 'hidden' } },
557
+ h('div', { className: 'lkl-title' },
558
+ h('span', { className: 'lkl-titleLabel' }, h(KeyIcon), single ? `Usage · ${name}` : `API keys · ${name}`),
559
+ h('span', { className: 'lkl-titleValue' }, single ? (cur ? `${cur.pct}% used` : '1 key') : `${label(inUse)} in use${pinned ? ' · manual' : ''}`)),
560
+ h('div', { className: 'lkl-rule', 'aria-hidden': true }),
561
+ ...sections,
562
+ h('div', { className: 'lkl-note' }, note))
563
+
564
+ return h('span', { className: 'lkl-anchor', 'data-composer-stat': 'key-loop' },
565
+ h('button', { ref: btnRef, type: 'button', className: 'lkl-pill', 'aria-haspopup': 'dialog', 'aria-expanded': open, title: open ? undefined : `${text} — click for all keys`, onClick: () => setOpen(!open) },
566
+ h(KeyIcon),
567
+ h('span', { style: warn ? { color: usageColor(cur) } : null }, text)),
568
+ open ? (ReactDOM?.createPortal ? ReactDOM.createPortal(panel, document.body) : panel) : null)
569
+ }
570
+
571
+ /** Pin code for a key slot: D0000 main key, C000N chain slot N, A0000 the key in use. */
572
+ const pinCodeOf = (active, ref) => {
573
+ if (ref === `${active}_DEFAULT`) return 'D0000'
574
+ const m = ref.match(/_CHAIN_(\d+)$/)
575
+ if (m) return `C${m[1].padStart(4, '0')}`
576
+ return 'A0000'
577
+ }
578
+ const pinRefOf = (active, masked) => {
579
+ const m = typeof masked === 'string' ? masked.match(/^p-([DCA])(\d{4})/) : null
580
+ if (!m) return undefined
581
+ return m[1] === 'D' ? `${active}_DEFAULT` : m[1] === 'C' ? `${active}_CHAIN_${Number(m[2])}` : active
582
+ }
583
+ const Check = () => h('svg', { width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('path', { d: 'M3.5 8.5 6.5 11.5 12.5 4.5' }))
584
+ const Chevron = ({ open }) => h('svg', { className: `lkl-chev${open ? ' lkl-chevOpen' : ''}`, viewBox: '0 0 12 12', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }, h('path', { d: 'M4.5 2.5 8 6l-3.5 3.5' }))
585
+
586
+ /** Model menu row: "Key Default · Key 1 ›" — expands to Default (automatic) and each key. */
587
+ function KeyMenuRow({ remote, directory, locked, dismiss, reportFailure }) {
588
+ const snap = React.useSyncExternalStore((cb) => directory.subscribe(cb), () => directory.getSnapshot())
589
+ const provider = snap?.pending?.provider ?? snap?.current?.provider
590
+ const [info, setInfo] = React.useState({})
591
+ const [open, setOpen] = React.useState(false)
592
+ const [busy, setBusy] = React.useState(false)
593
+ const [tick, setTick] = React.useState(0)
594
+ React.useEffect(() => {
595
+ if (typeof provider !== 'string') return undefined
596
+ let live = true
597
+ const active = envRefOf(provider)
598
+ const U = ['USAGE', 'USAGE2', 'USAGE3']
599
+ const refs = [active, `${active}_PIN`, ...U.map((x) => `${active}_${x}`), ...listRefsOf(active).flatMap((r) => [r, ...U.map((x) => `${r}_${x}`), `${r}_LIMIT`, `${r}_REJECTED`, `${r}_RATELIMITED`])]
600
+ describeAll(remote, refs).then((v) => { if (live) setInfo(v) }).catch(() => {})
601
+ return () => { live = false }
602
+ }, [provider, tick])
603
+ if (typeof provider !== 'string') return null
604
+ const { rows, label, inUse, active } = keyRowsOf(provider, info)
605
+ if (rows.length < 2) return null
606
+ const pinnedRef = pinRefOf(active, info[`${active}_PIN`]?.masked)
607
+ const pinnedIdx = pinnedRef === undefined ? -1 : rows.findIndex((r) => r === pinnedRef || (pinnedRef === active && r === rows[inUse]))
608
+ const value = pinnedIdx >= 0 ? label(pinnedIdx) : inUse >= 0 ? `Default · ${label(inUse)}` : 'Default'
609
+ const statusOf = (ref) => {
610
+ const u = ['USAGE', 'USAGE2', 'USAGE3'].map((x) => decodeUsage(info[`${ref}_${x}`]?.masked)).find(Boolean)
611
+ if (info[`${ref}_LIMIT`]?.configured || u?.spent) return { text: u ? `${u.pct}% · limit` : 'limit', warn: true }
612
+ if (info[`${ref}_REJECTED`]?.configured) return { text: 'rejected', warn: true }
613
+ if (info[`${ref}_RATELIMITED`]?.configured) return { text: 'throttled', warn: true }
614
+ return u ? { text: `${u.pct}%`, warn: u.pct >= 90 } : null
615
+ }
616
+ const choose = async (ref) => {
617
+ setBusy(true)
618
+ try {
619
+ const r = ref === undefined
620
+ ? (info[`${active}_PIN`]?.configured ? await remote.credentials.unset(`${active}_PIN`) : { ok: true })
621
+ : await remote.credentials.set(`${active}_PIN`, `p-${pinCodeOf(active, ref)}${'0'.repeat(8)}0000`)
622
+ if (r && r.ok === false) reportFailure?.(r.error?.message ?? 'Could not change the key.')
623
+ else { setTick((t) => t + 1); dismiss?.() }
624
+ } catch (e) { reportFailure?.(e?.message ?? String(e)) } finally { setBusy(false) }
625
+ }
626
+ const disabled = locked === true || busy
627
+ const opt = (key, selected, title, sub, meta, onClick) => h('button', { key, type: 'button', role: 'menuitemradio', 'aria-checked': selected, className: 'lkl-opt', disabled, onClick },
628
+ h('span', { className: 'lkl-check' }, selected ? h(Check) : null),
629
+ h('span', { className: 'lkl-optText' }, h('span', null, title), sub ? h('span', { className: 'lkl-optSub' }, sub) : null),
630
+ meta ? h('span', { className: 'lkl-optMeta', style: meta.warn ? { color: '#e05252' } : null }, meta.text) : null)
631
+ return h(React.Fragment, null,
632
+ h('button', { type: 'button', role: 'menuitem', 'aria-expanded': open, className: 'lkl-cell', disabled: locked === true, onClick: () => setOpen(!open) },
633
+ h('span', { className: 'lkl-cellLabel' }, 'Key'),
634
+ h('span', { className: 'lkl-cellValue' }, value),
635
+ h(Chevron, { open })),
636
+ open ? h('div', { className: 'lkl-opts', role: 'group', 'aria-label': 'API key' },
637
+ opt('auto', pinnedIdx < 0, 'Default', 'Automatic — switches when a key runs out', null, () => choose(undefined)),
638
+ ...rows.map((ref, i) => opt(ref, pinnedIdx === i, label(i), i === inUse ? 'in use' : null, statusOf(ref), () => choose(ref)))) : null)
639
+ }
640
+
641
+ module.exports.inject = ['slots', 'remote', 'remote.credentials', 'remote.llm']
642
+ module.exports.apply = function apply(ctx) {
643
+ ctx.effect(() => {
644
+ const tag = document.createElement('style')
645
+ tag.dataset.pluginCss = 'dsh-llm-key-loop/dock'
646
+ tag.textContent = DOCK_CSS + PAGE_CSS
647
+ document.head.appendChild(tag)
648
+ return () => tag.remove()
649
+ }, 'llm-key-loop: dock styles')
650
+ ctx.inject(['slots', 'modelDirectories'], (scope) => {
651
+ const models = scope.modelDirectories
652
+ scope.slots.inject('conversation.input.model.options', () => scope.slots.register({
653
+ name: 'conversation.input.model.options',
654
+ id: 'key-loop',
655
+ order: -10,
656
+ label: 'Key',
657
+ inject: (sessionId) => ({ directory: models.directoryFor(sessionId).store }),
658
+ }, (props) => h(KeyMenuRow, { remote: ctx.remote, directory: props.directory, locked: props.locked, dismiss: props.dismiss, reportFailure: props.reportFailure })))
659
+ scope.slots.inject('conversation.composer.dock', () => scope.slots.register({
660
+ name: 'conversation.composer.dock',
661
+ id: 'key-loop',
662
+ order: 3,
663
+ inject: (sessionId) => ({ directory: models.directoryFor(sessionId).store }),
664
+ }, (props) => h(KeyDock, { remote: ctx.remote, directory: props.directory })))
665
+ })
666
+ const Page = () => h(KeyLoopPage, { remote: ctx.remote })
667
+ ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: 'key-loop' }, Page)), 'llm-key-loop: page')
668
+ ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: 'key-loop', order: 20, label: 'Key Loop' }, PanelIcon)), 'llm-key-loop: left menu')
669
+ ctx.effect(() => ctx.slots.inject('settings.models.footer', () => ctx.slots.register(
670
+ { name: 'settings.models.footer', id: 'llm-key-loop', order: 100 },
671
+ SettingsNote,
672
+ )), 'llm-key-loop: models footer note')
673
+ }
674
+ return module.exports
675
+ },
676
+ })