ccswap inside Claude Code: /ccswap to list and switch accounts, an accounts pane, a switch toast, and a quota band above the prompt

A Claude Code mod that shows your ccswap accounts inside the session. It reads everything from the ccswap CLI on your PATH (ccswap list --json), so install ccswap first (uv tool install ccswap).
<img src="../assets/mod-pane-claude.png" width="760" alt="The ccswap pane in Claude Code: each account's 5h and 7d usage bars, emails masked, with a key to switch to #2">
/ccswap lists accounts with 5h and 7d usage. /ccswap best, /ccswap next, or /ccswap <slot|email> switches accounts. /ccswap pane opens the accounts pane, and /ccswap refresh re-reads usage. Each command answers right away, without starting a Claude turn.ccswap auto or the menu bar.c Claude (5h and 7d bars, the slot's digit switches to it), x Codex (the slot's digit switches; restart Codex afterwards), h History (recent switches from ccswap's log) and s Settings (t threshold, 5 5h gate, 7 weekly gate, f Fable gate, g strategy, w binding windows, l statusline). r refreshes the open tab, Esc closes the pane.autoswitch.threshold, default 90%). It names the account with the most room before a gate, and its button switches there. Typing that digit into an empty prompt presses it.claude plugin marketplace add errhythm/ccswap
claude plugin install ccswap@ccswap
Or, inside a session: /plugin install ccswap --marketplace errhythm/ccswap.
After a switch, Claude Code can take about 30s to pick up the new login (macOS Keychain cache). If it doesn't, restart Claude Code.
claude plugin validate mod
claude plugin test mod
claude --plugin-dir modhooks/register.tsx 769 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type {
5 CcswapAccount,
6 CcswapCodexView,
7 CcswapGates,
8 CcswapHistoryView,
9 CcswapScoped,
10 CcswapSettingsView,
11 CcswapSnapshot,
12 CcswapSwitchEntry,
13 CcswapTab,
14 CcswapTone,
15 CcswapWindow,
16} from '../types'
17
18type $ = EngineInterface
19
20const PANE = 'ccswap'
21const POLL_MS = 60_000
22const NOT_FOUND = 'ccswap not found on PATH. Install: uv tool install ccswap'
23const KEYCHAIN_NOTE =
24 "Claude Code may take ~30s to pick up the new login (macOS Keychain cache); restart if it doesn't."
25const USAGE = [
26 'Usage: /ccswap [best | next | <number|email> | pane | refresh]',
27 ' (no args) list accounts',
28 ' best switch to the account with the most headroom',
29 ' next rotate to the next account that is not at its limit',
30 ' <n|email> switch to that account',
31 ' pane open the accounts pane',
32 ' refresh re-read usage now',
33].join('\n')
34
35const snapshot = atom({ plugin: 'ccswap', key: 'snapshot' } as const, null)
36const tone = atom({ plugin: 'ccswap', key: 'tone' } as const, 'theme')
37const switching = atom({ plugin: 'ccswap', key: 'switching' } as const, false)
38const tab = atom({ plugin: 'ccswap', key: 'tab' } as const, 'claude')
39const codexView = atom({ plugin: 'ccswap', key: 'codex' } as const, null)
40const historyView = atom({ plugin: 'ccswap', key: 'history' } as const, null)
41const settingsView = atom({ plugin: 'ccswap', key: 'settings' } as const, null)
42
43const PALETTES = {
44 dark: { accent: '#d7875f', fg: '#e8e4de', muted: '#8a8a8a', ok: '#87af87', warn: '#d7af5f', crit: '#d75f5f', track: '#3a3a3a' },
45 light: { accent: '#954c2a', fg: '#2b2723', muted: '#635d55', ok: '#3d6b3d', warn: '#795911', crit: '#ad3128', track: '#cec7ba' },
46 theme: { accent: 'claude', fg: 'text', muted: 'inactive', ok: 'success', warn: 'warning', crit: 'error', track: 'subtle' },
47} as const
48
49// Letters, so the digits stay free to switch to that slot on the open tab.
50const TABS: { id: CcswapTab; label: string; hotkey: string }[] = [
51 { id: 'claude', label: 'Claude', hotkey: 'c' },
52 { id: 'codex', label: 'Codex', hotkey: 'x' },
53 { id: 'history', label: 'History', hotkey: 'h' },
54 { id: 'settings', label: 'Settings', hotkey: 's' },
55]
56
57// What each Settings press moves to next.
58const THRESHOLDS = [70, 80, 85, 90, 95]
59// Same stops as the TUI settings ladder (tui/dashboard.py _GATE_STOPS).
60const GATE_PCTS: (number | null)[] = [null, 40, 50, 60, 70, 75, 80, 85, 90, 95]
61const STRATEGIES = ['best', 'consume-first']
62const WINDOWS = ['both', '5h', '7d']
63
64function defaultGates(threshold = 90): CcswapGates {
65 return {
66 threshold,
67 threshold5h: null,
68 threshold7d: null,
69 windows: 'both',
70 models: [],
71 modelThresholds: {},
72 }
73}
74
75type Raw = { ok: true; stdout: string; stderr: string; exitCode: number } | { ok: false; error: string }
76type Ran = { ok: true; data: any } | { ok: false; error: string }
77
78/** Runs `ccswap <args>`; never throws. */
79async function runRaw($: $, args: string[]): Promise<Raw> {
80 try {
81 const out = await $.process.run(['ccswap', ...args], { timeoutMs: 20_000 })
82 if (out.exitCode === 127) return { ok: false, error: NOT_FOUND }
83 return { ok: true, stdout: out.stdout, stderr: out.stderr, exitCode: out.exitCode }
84 } catch (err) {
85 const msg = err instanceof Error ? err.message : String(err)
86 return { ok: false, error: /timed? ?out|still running/i.test(msg) ? `ccswap timed out: ${msg}` : NOT_FOUND }
87 }
88}
89
90/** Runs `ccswap <args>` expecting JSON on stdout; never throws. */
91async function ccswap($: $, args: string[]): Promise<Ran> {
92 const out = await runRaw($, args)
93 if (!out.ok) return out
94 let data: any
95 try {
96 data = JSON.parse(out.stdout)
97 } catch {
98 return { ok: false, error: out.stderr.trim() || `ccswap exited ${out.exitCode} without JSON` }
99 }
100 if (data?.error) return { ok: false, error: String(data.error.message ?? data.error) }
101 return { ok: true, data }
102}
103
104function toWindow(w: any): CcswapWindow | null {
105 return typeof w?.pct === 'number' ? { pct: Math.round(w.pct), countdown: w.countdown ?? null } : null
106}
107
108function toScoped(list: any): CcswapScoped[] {
109 if (!Array.isArray(list)) return []
110 return list.flatMap((s: any) =>
111 typeof s?.name === 'string' && typeof s?.pct === 'number'
112 ? [{ name: s.name, pct: Math.round(s.pct) }]
113 : [],
114 )
115}
116
117// Same shape as the TUI's mask (tui/data.py mask_email): alice@acme.com -> a•••e@a•••.com.
118const EMAIL_RE = /[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}/g
119
120function maskName(name: string): string {
121 const parts = name.split(/\s+/).filter(Boolean)
122 return parts.length ? parts.map(p => (p.length <= 1 ? '•' : p[0] + '•'.repeat(Math.min(3, p.length - 1)))).join(' ') : name
123}
124
125export function maskEmail(email: string): string {
126 const raw = email.trim()
127 if (!raw) return raw
128 const at = raw.lastIndexOf('@')
129 if (at < 0) return maskName(raw)
130 const local = raw.slice(0, at)
131 const domain = raw.slice(at + 1)
132 const n = local.length
133 const l = n <= 1 ? '•' : n === 2 ? local[0] + '•' : local[0] + '•'.repeat(Math.min(3, n - 2)) + local[n - 1]
134 const dot = domain.indexOf('.')
135 const head = dot < 0 ? domain : domain.slice(0, dot)
136 const h = head.length <= 1 ? '•' : head[0] + '•'.repeat(Math.min(3, head.length - 1))
137 return `${l}@${dot < 0 ? h : h + domain.slice(dot)}`
138}
139
140// ccswap's `ui.mask` setting, re-read with each Claude or Codex list.
141let masking = false
142
143function shown(text: string): string {
144 return masking ? text.replace(EMAIL_RE, maskEmail) : text
145}
146
147async function loadMask($: $): Promise<void> {
148 masking = (await readConfig($, 'ui.mask'))?.value === true
149}
150
151function toSnapshot(data: any, gates: CcswapGates): CcswapSnapshot {
152 const accounts: CcswapAccount[] = (Array.isArray(data?.accounts) ? data.accounts : []).map((a: any) => ({
153 number: Number(a.number),
154 email: shown(String(a.email ?? '')),
155 active: a.active === true,
156 status: String(a.usageStatus ?? 'ok'),
157 fiveHour: toWindow(a.usage?.fiveHour),
158 sevenDay: toWindow(a.usage?.sevenDay),
159 scoped: toScoped(a.usage?.scoped),
160 }))
161 const active = typeof data?.activeAccountNumber === 'number' ? data.activeAccountNumber : null
162 return { active, threshold: gates.threshold, gates, accounts, error: null }
163}
164
165function parseModels(value: unknown): string[] {
166 if (typeof value !== 'string') return []
167 const seen = new Set<string>()
168 const out: string[] = []
169 for (const part of value.split(',')) {
170 const name = part.trim()
171 const key = name.toLowerCase()
172 if (name && !seen.has(key)) {
173 seen.add(key)
174 out.push(key)
175 }
176 }
177 return out
178}
179
180function parseModelThresholds(value: unknown): Record<string, number> {
181 const out: Record<string, number> = {}
182 if (typeof value !== 'string') return out
183 for (const part of value.split(',')) {
184 const eq = part.indexOf('=')
185 if (eq < 0) continue
186 const name = part.slice(0, eq).trim().toLowerCase()
187 const pct = Number(part.slice(eq + 1).trim())
188 if (name && Number.isFinite(pct) && !(name in out)) out[name] = pct
189 }
190 return out
191}
192
193/** null when this label is not a gate (windows filter, or an unwatched model). */
194function gateThreshold(label: string, cfg: CcswapGates): number | null {
195 const key = label.toLowerCase()
196 if (key === '5h') return cfg.windows === '7d' ? null : (cfg.threshold5h ?? cfg.threshold)
197 if (key === '7d') return cfg.windows === '5h' ? null : (cfg.threshold7d ?? cfg.threshold)
198 if (key in cfg.modelThresholds) return cfg.modelThresholds[key] ?? null
199 if (cfg.models.includes('all') || cfg.models.includes(key)) return cfg.threshold
200 return null
201}
202
203/** The gate closest to its own wall: the one that binds. */
204export function binding(a: CcswapAccount, cfg: CcswapGates = defaultGates()): { label: string; pct: number; threshold: number } | null {
205 const hits: { label: string; pct: number; threshold: number }[] = []
206 const push = (label: string, pct: number | undefined) => {
207 if (pct === undefined) return
208 const threshold = gateThreshold(label, cfg)
209 if (threshold === null) return
210 hits.push({ label, pct, threshold })
211 }
212 push('5h', a.fiveHour?.pct)
213 push('7d', a.sevenDay?.pct)
214 for (const scoped of a.scoped ?? []) push(scoped.name, scoped.pct)
215 if (hits.length === 0) return null
216 let worst = hits[0]!
217 let margin = worst.threshold - worst.pct
218 for (const hit of hits.slice(1)) {
219 const next = hit.threshold - hit.pct
220 if (next < margin || (next === margin && hit.pct > worst.pct)) {
221 worst = hit
222 margin = next
223 }
224 }
225 return worst
226}
227
228function bestOther(snap: CcswapSnapshot): CcswapAccount | null {
229 const cfg = snap.gates ?? defaultGates(snap.threshold)
230 let best: CcswapAccount | null = null
231 let bestMargin = -Infinity
232 for (const a of snap.accounts) {
233 const b = binding(a, cfg)
234 if (a.active || a.status !== 'ok' || b === null) continue
235 const margin = b.threshold - b.pct
236 if (best === null || margin > bestMargin) {
237 best = a
238 bestMargin = margin
239 }
240 }
241 return best
242}
243
244async function readConfig($: $, key: string): Promise<{ value: unknown } | null> {
245 const cfg = await ccswap($, ['config', 'get', key, '--json'])
246 if (!cfg.ok || cfg.data?.key !== key) return null
247 return { value: cfg.data.value }
248}
249
250function finiteOr(value: unknown, fallback: number): number {
251 const n = Number(value)
252 return Number.isFinite(n) ? n : fallback
253}
254
255function finiteOrNull(value: unknown): number | null {
256 if (value === null || value === undefined || value === '') return null
257 const n = Number(value)
258 return Number.isFinite(n) ? n : null
259}
260
261async function loadGates($: $): Promise<CcswapGates> {
262 const [threshold, t5, t7, windows, model, modelThresholds] = await Promise.all([
263 readConfig($, 'autoswitch.threshold'),
264 readConfig($, 'autoswitch.threshold5h'),
265 readConfig($, 'autoswitch.threshold7d'),
266 readConfig($, 'autoswitch.windows'),
267 readConfig($, 'autoswitch.model'),
268 readConfig($, 'autoswitch.modelThresholds'),
269 ])
270 const win = windows?.value
271 return {
272 threshold: finiteOr(threshold?.value, 90),
273 threshold5h: finiteOrNull(t5?.value),
274 threshold7d: finiteOrNull(t7?.value),
275 windows: win === '5h' || win === '7d' || win === 'both' ? win : 'both',
276 models: parseModels(model?.value),
277 modelThresholds: parseModelThresholds(modelThresholds?.value),
278 }
279}
280
281// Polls overlap (timer, Refresh, post-switch, /ccswap). Each takes a number when it
282// starts; a result older than the last one written is dropped, toast included.
283let issued = 0
284let applied = 0
285
286async function poll($: $): Promise<CcswapSnapshot> {
287 const gen = ++issued
288 const [list, gates] = await Promise.all([
289 ccswap($, ['list', '--provider', 'claude', '--json']),
290 loadGates($),
291 loadMask($),
292 ])
293 const threshold = gates.threshold
294 let prev: CcswapSnapshot | null = null
295 let snap: CcswapSnapshot | null = null
296 // update() re-runs this on a version miss, so the staleness check and the
297 // write it guards happen together.
298 await update($, snapshot, p => {
299 prev = p
300 if (gen < applied) {
301 snap = null
302 return p
303 }
304 applied = gen
305 snap = list.ok
306 ? toSnapshot(list.data, gates)
307 : { active: p?.active ?? null, threshold, gates, accounts: [], error: list.error }
308 return snap
309 })
310 const was = prev as CcswapSnapshot | null
311 const now = snap as CcswapSnapshot | null
312 if (now === null) return was ?? { active: null, threshold, gates, accounts: [], error: null }
313
314 if (was && was.active !== null && now.active !== null && was.active !== now.active) {
315 const acct = now.accounts.find(a => a.number === now.active)
316 const five = acct?.fiveHour ? ` (5h ${acct.fiveHour.pct}%)` : ''
317 $.ui.toast(`ccswap: now on #${now.active} ${acct?.email ?? ''}${five}`)
318 }
319 return now
320}
321
322function pollQuietly($: $): void {
323 poll($).catch(() => undefined)
324}
325
326async function loadCodex($: $): Promise<void> {
327 const [ran] = await Promise.all([ccswap($, ['list', '--provider', 'codex', '--json']), loadMask($)])
328 const view: CcswapCodexView = ran.ok
329 ? {
330 accounts: (Array.isArray(ran.data?.accounts) ? ran.data.accounts : []).map((a: any) => ({
331 number: Number(a.number),
332 email: shown(String(a.email ?? '')),
333 label: String(a.label ?? a.authMode ?? ''),
334 active: a.active === true,
335 })),
336 error: null,
337 }
338 : { accounts: [], error: ran.error }
339 await update($, codexView, () => view)
340}
341
342const SWITCH_LINE = /^(\d{4}-\d\d-\d\d \d\d:\d\d).* - Switched from account (\d+) to (\d+)/
343
344/** Claude Code switches in ccswap's log, newest first, as the menu bar lists them. */
345export function parseHistory(text: string, limit = 15): CcswapSwitchEntry[] {
346 const out: CcswapSwitchEntry[] = []
347 for (const line of text.split('\n')) {
348 const m = SWITCH_LINE.exec(line)
349 if (m) out.push({ at: m[1]!, from: Number(m[2]), to: Number(m[3]) })
350 }
351 return out.slice(-limit).reverse()
352}
353
354async function loadHistory($: $): Promise<void> {
355 // The log sits next to settings.json in ccswap's backup folder.
356 const where = await runRaw($, ['config', 'path'])
357 let view: CcswapHistoryView
358 if (!where.ok || where.exitCode !== 0) {
359 view = { entries: [], error: where.ok ? where.stderr.trim() || 'ccswap config path failed' : where.error }
360 } else {
361 const settingsPath = where.stdout.trim()
362 const log = settingsPath.replace(/[^\\/]+$/, 'claude-swap.log')
363 let text = ''
364 try {
365 text = String(await $.fs.read(log))
366 } catch {
367 // no log yet: nothing has been switched
368 }
369 view = { entries: parseHistory(text), error: null }
370 }
371 await update($, historyView, () => view)
372}
373
374async function loadSettings($: $): Promise<void> {
375 const ran = await ccswap($, ['config', 'list', '--json'])
376 const rows: any[] = ran.ok && Array.isArray(ran.data?.settings) ? ran.data.settings : []
377 const value = (key: string) => rows.find(r => r?.key === key)?.value
378 const rawThresholds = value('autoswitch.modelThresholds')
379 const view: CcswapSettingsView = {
380 threshold: Number(value('autoswitch.threshold') ?? 90),
381 threshold5h: finiteOrNull(value('autoswitch.threshold5h')),
382 threshold7d: finiteOrNull(value('autoswitch.threshold7d')),
383 modelThresholds: typeof rawThresholds === 'string' && rawThresholds.trim() ? rawThresholds : null,
384 strategy: String(value('autoswitch.strategy') ?? 'best'),
385 windows: String(value('autoswitch.windows') ?? 'both'),
386 statusline: value('claude.statusline') === true,
387 mod: value('claude.mod') === true,
388 error: ran.ok ? null : ran.error,
389 }
390 await update($, settingsView, () => view)
391}
392
393async function loadTab($: $, t: CcswapTab): Promise<void> {
394 if (t === 'claude') await poll($)
395 else if (t === 'codex') await loadCodex($)
396 else if (t === 'history') await loadHistory($)
397 else await loadSettings($)
398}
399
400function nextOf<T>(list: readonly T[], current: T): T {
401 const i = list.indexOf(current)
402 return list[(i + 1) % list.length]!
403}
404
405/** Next `modelThresholds` after one press of the Fable row.
406 *
407 * Only Fable moves along `GATE_PCTS` (inherit, then 40–95). Other models stay,
408 * in their original order. A Fable percentage that is not one of those stops
409 * steps onto the ladder. Null when nothing remains, which unsets the key.
410 */
411export function nextFableThresholds(current: string | null): string | null {
412 const parts = (current ?? '').split(',').map(part => part.trim()).filter(Boolean)
413 const others = parts.filter(part => part.split('=')[0]!.trim().toLowerCase() !== 'fable')
414 const currentPct = parseModelThresholds(current).fable
415 const onLadder = currentPct !== undefined && GATE_PCTS.includes(currentPct)
416 const next = nextOf(GATE_PCTS, onLadder ? currentPct : null)
417 const merged = next === null ? others : [...others, `Fable=${next}`]
418 return merged.length ? merged.join(',') : null
419}
420
421/** `ccswap config set` or `unset` (null), then re-reads the Settings tab. */
422async function setSetting($: $, key: string, value: string | null): Promise<void> {
423 const out = value === null
424 ? await runRaw($, ['config', 'unset', key])
425 : await runRaw($, ['config', 'set', key, value])
426 if (!out.ok) $.ui.toast(`ccswap: ${out.error}`)
427 else if (out.exitCode !== 0) $.ui.toast(`ccswap: ${(out.stderr.trim() || out.stdout.trim()).split('\n')[0]}`)
428 await loadSettings($)
429 if (key.startsWith('autoswitch.')) await poll($).catch(() => undefined)
430}
431
432async function readTone($: $): Promise<CcswapTone> {
433 try {
434 const row = (await $.config.list()).find(r => r.key === 'theme')
435 const value = String(row?.value ?? '')
436 if (value.startsWith('light')) return 'light'
437 if (value.startsWith('dark')) return 'dark'
438 } catch {
439 // no config rows reachable: theme keys follow the person's theme anyway
440 }
441 return 'theme'
442}
443
444function cell(w: CcswapWindow | null): string {
445 if (w === null) return ' -'
446 return `${String(w.pct).padStart(3)}%${w.countdown ? ` (${w.countdown})` : ''}`
447}
448
449function listText(snap: CcswapSnapshot): string {
450 if (snap.error) return snap.error
451 if (snap.accounts.length === 0) return 'ccswap manages no Claude accounts yet. Run: ccswap add'
452 const width = Math.max(...snap.accounts.map(a => a.email.length))
453 const rows = snap.accounts.map(a => {
454 const mark = a.active ? '●' : '○'
455 const usage = a.status === 'ok' ? `5h ${cell(a.fiveHour)} 7d ${cell(a.sevenDay)}` : a.status
456 return `${mark} #${a.number} ${a.email.padEnd(width)} ${usage}`
457 })
458 return [`accounts (● active, switch threshold ${snap.threshold}%)`, ...rows].join('\n')
459}
460
461const BUSY = 'a switch is already running'
462// Module-level so the guard is synchronous; the `switching` atom mirrors it for drawing.
463let switchInFlight = false
464
465async function doSwitch(
466 $: $,
467 target: 'best' | 'next' | string,
468 provider: 'claude' | 'codex' = 'claude',
469): Promise<{ text: string; switched: boolean }> {
470 if (switchInFlight) return { text: BUSY, switched: false }
471 switchInFlight = true
472 await update($, switching, () => true).catch(() => undefined)
473 try {
474 if (provider === 'codex') {
475 const ran = await ccswap($, ['codex', 'switch', target, '--json'])
476 if (!ran.ok) return { text: ran.error, switched: false }
477 await loadCodex($).catch(() => undefined)
478 const to = ran.data?.to
479 return ran.data?.switched === true
480 ? { text: `Switched Codex to #${to?.number} ${shown(String(to?.email ?? ''))}. Restart Codex to use it.`, switched: true }
481 : { text: `Codex is already on #${to?.number ?? target}.`, switched: false }
482 }
483 const args =
484 target === 'best'
485 ? ['switch', '--strategy', 'best', '--json']
486 : target === 'next'
487 ? ['switch', '--strategy', 'next-available', '--json']
488 : ['switch', target, '--json']
489 const ran = await ccswap($, args)
490 if (!ran.ok) return { text: ran.error, switched: false }
491 await poll($).catch(() => undefined)
492 const warnings: string[] = Array.isArray(ran.data.warnings) ? ran.data.warnings.map(String) : []
493 const lines = [String(ran.data.message ?? (ran.data.switched ? 'Switched.' : 'No switch.')), ...warnings].map(shown)
494 if (ran.data.switched) lines.push(KEYCHAIN_NOTE)
495 return { text: lines.join('\n'), switched: ran.data.switched === true }
496 } finally {
497 switchInFlight = false
498 await update($, switching, () => false).catch(() => undefined)
499 }
500}
501
502// Slots 1-9 double as hotkeys: the slot's own digit switches to it.
503function slotKey(n: number): string | undefined {
504 return n >= 1 && n <= 9 ? String(n) : undefined
505}
506
507function severity(pct: number, threshold: number): 'ok' | 'warn' | 'crit' {
508 return pct >= Math.min(90, threshold) ? 'crit' : pct >= 70 ? 'warn' : 'ok'
509}
510
511export const register: Register = on => {
512 on('session.start', async ($, e, next) => {
513 // $.state outlives a reload, switchInFlight does not: clear a flag a reload left set.
514 await update($, switching, () => false).catch(() => undefined)
515 await $.command.register({
516 name: 'ccswap',
517 description: 'ccswap accounts: list, switch (best, next, a slot or email), pane, refresh',
518 argumentHint: '[best|next|<n|email>|pane|refresh]',
519 immediate: true,
520 })
521 void (async () => {
522 const t = await readTone($)
523 await update($, tone, () => t)
524 await poll($)
525 })().catch(() => undefined)
526 $.clock.every(POLL_MS, () => pollQuietly($))
527
528 return next(e)
529 })
530
531 on('command.run', { command: 'ccswap' }, async ($, e) => {
532 const arg = e.args.trim()
533 if (arg === '' || arg === 'refresh') {
534 const snap = await poll($)
535 return { text: arg === '' ? listText(snap) : snap.error ?? `Refreshed: ${snap.accounts.length} accounts, active #${snap.active ?? '?'}.` }
536 }
537 if (arg === 'pane') {
538 void loadTab($, await read($, tab)).catch(() => undefined)
539 // focus so the buttons get keys; Esc hands them back to the prompt and closes
540 await $.ui.open({ id: PANE, title: 'ccswap', focus: true, closeOnEscape: true })
541 return { text: 'pane opened.' }
542 }
543 if (arg === 'best' || arg === 'next' || /^\d+$/.test(arg) || arg.includes('@')) {
544 return { text: (await doSwitch($, arg)).text }
545 }
546 return { text: USAGE }
547 })
548
549 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
550 const { Box, Text, Button } = $.ui.resolve(e)
551 const c = PALETTES[await read($, tone)]
552 const busy = await read($, switching)
553 const open = await read($, tab)
554
555 const tabBar = (
556 <Box flexDirection="row" columnGap={3}>
557 {TABS.map(t => (
558 <Button
559 key={`tab-${t.id}`}
560 label={t.label}
561 hotkey={t.hotkey}
562 plain
563 {...(t.id === open ? {} : { dimColor: true })}
564 onPress={async () => {
565 await update($, tab, () => t.id)
566 await loadTab($, t.id).catch(() => undefined)
567 }}
568 />
569 ))}
570 </Box>
571 )
572 const refresh = (
573 <Button key="refresh" label="Refresh" hotkey="r" plain onPress={() => loadTab($, open).catch(() => undefined)} />
574 )
575 const page = (...body: JSX.Element[]) => (
576 <Box flexDirection="column">
577 {tabBar}
578 <Text> </Text>
579 {...body}
580 {busy && <Text color={c.muted}>switching…</Text>}
581 {refresh}
582 </Box>
583 )
584 const switchButton = (n: number, provider: 'claude' | 'codex') => (
585 <Button
586 key={`${provider === 'codex' ? 'codex-' : ''}switch-${n}`}
587 label={`Switch to #${n}`}
588 plain
589 {...(slotKey(n) ? { hotkey: slotKey(n) } : {})}
590 onPress={async () => {
591 const done = await doSwitch($, String(n), provider)
592 // a real Claude switch already raised poll()'s "now on #N" toast
593 if (!done.switched || provider === 'codex') $.ui.toast(`ccswap: ${done.text.split('\n')[0] ?? ''}`)
594 }}
595 />
596 )
597
598 if (open === 'codex') {
599 const view = await read($, codexView)
600 if (view === null) return page(<Text color={c.muted}>Reading Codex accounts…</Text>)
601 if (view.error) return page(<Text color={c.crit}>{view.error}</Text>)
602 if (view.accounts.length === 0) {
603 return page(<Text color={c.muted}>No Codex accounts. Run `codex login`, then `ccswap codex add`.</Text>)
604 }
605 const width = Math.max(...view.accounts.map(a => a.email.length))
606 return page(
607 ...view.accounts.map(a => (
608 <Box key={`codex-row-${a.number}`} flexDirection="row">
609 <Text color={a.active ? c.accent : c.muted}>{a.active ? '● ' : '○ '}</Text>
610 <Text color={a.active ? c.accent : c.fg} bold={a.active}>
611 #{a.number} {a.email.padEnd(width)}{' '}
612 </Text>
613 <Text color={c.muted}>{a.label} </Text>
614 {!a.active && !busy && switchButton(a.number, 'codex')}
615 </Box>
616 )),
617 <Text color={c.muted}>Codex reads its login once at start: restart it after a switch.</Text>,
618 )
619 }
620
621 if (open === 'history') {
622 const view = await read($, historyView)
623 if (view === null) return page(<Text color={c.muted}>Reading the switch log…</Text>)
624 if (view.error) return page(<Text color={c.crit}>{view.error}</Text>)
625 if (view.entries.length === 0) return page(<Text color={c.muted}>No switches logged yet.</Text>)
626 const emails = new Map((await read($, snapshot))?.accounts.map(a => [a.number, a.email]) ?? [])
627 return page(
628 ...view.entries.map((s, i) => (
629 <Text key={`switch-log-${i}`}>
630 <Text color={c.muted}>{s.at} </Text>
631 <Text color={c.fg}>#{s.from}</Text>
632 <Text color={c.muted}> → </Text>
633 <Text color={c.accent}>#{s.to}</Text>
634 <Text color={c.muted}>{emails.has(s.to) ? ` ${emails.get(s.to)}` : ''}</Text>
635 </Text>
636 )),
637 )
638 }
639
640 if (open === 'settings') {
641 const view = await read($, settingsView)
642 if (view === null) return page(<Text color={c.muted}>Reading ccswap settings…</Text>)
643 if (view.error) return page(<Text color={c.crit}>{view.error}</Text>)
644 const row = (key: string, hotkey: string, label: string, value: string, onPress: () => Promise<void>) => (
645 <Box key={`setting-row-${key}`} flexDirection="row" columnGap={2}>
646 <Button key={`setting-${key}`} label={label} hotkey={hotkey} plain onPress={() => onPress().catch(() => undefined)} />
647 <Text color={c.accent}>{value}</Text>
648 </Box>
649 )
650 return page(
651 row('threshold', 't', 'Auto-switch threshold', `${view.threshold}%`, () =>
652 setSetting($, 'autoswitch.threshold', String(nextOf(THRESHOLDS, view.threshold) ?? 90)),
653 ),
654 row('threshold5h', '5', '5h gate', view.threshold5h === null ? 'inherit' : `${view.threshold5h}%`, () => {
655 const next = nextOf(GATE_PCTS, view.threshold5h)
656 return setSetting($, 'autoswitch.threshold5h', next === null ? null : String(next))
657 }),
658 row('threshold7d', '7', 'Weekly gate', view.threshold7d === null ? 'inherit' : `${view.threshold7d}%`, () => {
659 const next = nextOf(GATE_PCTS, view.threshold7d)
660 return setSetting($, 'autoswitch.threshold7d', next === null ? null : String(next))
661 }),
662 row('fable', 'f', 'Fable gate', view.modelThresholds ?? 'inherit', () =>
663 setSetting($, 'autoswitch.modelThresholds', nextFableThresholds(view.modelThresholds)),
664 ),
665 row('strategy', 'g', 'Auto-switch strategy', view.strategy, () =>
666 setSetting($, 'autoswitch.strategy', nextOf(STRATEGIES, view.strategy)),
667 ),
668 row('windows', 'w', 'Windows that bind', view.windows, () =>
669 setSetting($, 'autoswitch.windows', nextOf(WINDOWS, view.windows)),
670 ),
671 row('statusline', 'l', 'Claude statusline', view.statusline ? 'on' : 'off', () =>
672 setSetting($, 'claude.statusline', view.statusline ? 'off' : 'on'),
673 ),
674 <Box key="setting-row-mod" flexDirection="row" columnGap={2}>
675 <Text color={c.fg}>Claude Code mod</Text>
676 <Text color={c.accent}>{view.mod ? 'on' : 'off'}</Text>
677 <Text color={c.muted}>(turn off with: ccswap config set claude.mod off)</Text>
678 </Box>,
679 <Text color={c.muted}>Press a setting's key to move it to its next value.</Text>,
680 )
681 }
682
683 const snap = await read($, snapshot)
684 if (snap === null || snap.error) {
685 return page(<Text color={snap?.error ? c.crit : c.muted}>{snap?.error ?? 'Reading ccswap…'}</Text>)
686 }
687 const bar = (w: CcswapWindow | null, label: string) => {
688 if (w === null) return <Text color={c.muted}>{label} - </Text>
689 const filled = Math.max(0, Math.min(10, Math.round(w.pct / 10)))
690 return (
691 <Text>
692 <Text color={c.muted}>{label} </Text>
693 <Text color={c[severity(w.pct, snap.threshold)]}>{'━'.repeat(filled)}</Text>
694 <Text color={c.track}>{'─'.repeat(10 - filled)}</Text>
695 <Text color={c.fg}> {String(w.pct).padStart(3)}% </Text>
696 </Text>
697 )
698 }
699 const width = Math.max(...snap.accounts.map(a => a.email.length))
700 return page(
701 ...snap.accounts.map(a => (
702 <Box key={`row-${a.number}`} flexDirection="row">
703 <Text color={a.active ? c.accent : c.muted}>{a.active ? '● ' : '○ '}</Text>
704 <Text color={a.active ? c.accent : c.fg} bold={a.active}>
705 #{a.number} {a.email.padEnd(width)}{' '}
706 </Text>
707 {a.status === 'ok' ? (
708 <Text>
709 {bar(a.fiveHour, '5h')}
710 {bar(a.sevenDay, '7d')}
711 </Text>
712 ) : (
713 <Text color={c.warn}>{a.status} </Text>
714 )}
715 {!a.active && !busy && switchButton(a.number, 'claude')}
716 </Box>
717 )),
718 )
719 })
720
721 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
722 if (e.props.hasSurvey) return next(e)
723 const snap = await read($, snapshot)
724 const active = snap?.accounts.find(a => a.active)
725 const bound = active ? binding(active, snap.gates ?? defaultGates(snap.threshold)) : null
726 if (!snap || snap.error || !active || bound === null || bound.pct < bound.threshold) return next(e)
727
728 const { Box, Text, Button } = $.ui.resolve(e)
729 const c = PALETTES[await read($, tone)]
730 const busy = await read($, switching)
731 const best = bestOther(snap)
732 const bestPct = best ? binding(best, snap.gates ?? defaultGates(snap.threshold))?.pct : undefined
733 // Other mods' bands, or the engine's own, still draw beneath ours.
734 const below = await next(e)
735 return (
736 <Box flexDirection="column">
737 <Box flexDirection="row">
738 <Text>
739 <Text color={c.accent} bold>ccswap</Text>
740 <Text color={c.muted}> · </Text>
741 <Text color={c[severity(bound.pct, bound.threshold)]}>
742 {bound.label} {bound.pct}%
743 </Text>
744 <Text color={c.fg}> on #{active.number}</Text>
745 <Text color={c.muted}> · </Text>
746 <Text color={best ? c.ok : c.muted}>{best ? `best: #${best.number} (${bestPct}%)` : 'no account with more headroom'}</Text>
747 <Text> </Text>
748 </Text>
749 {busy && <Text color={c.muted}>switching…</Text>}
750 {best && !busy && (
751 <Button
752 key="switch-best"
753 label={`Switch to #${best.number}`}
754 plain
755 // a digit hotkey on the band also fires from an empty prompt
756 {...(slotKey(best.number) ? { hotkey: slotKey(best.number) } : {})}
757 onPress={async () => {
758 const done = await doSwitch($, 'best')
759 if (!done.switched) $.ui.toast(`ccswap: ${done.text.split('\n')[0] ?? ''}`)
760 }}
761 />
762 )}
763 </Box>
764 {below}
765 </Box>
766 )
767 })
768}
769types/index.d.ts 70 lines1export type CcswapWindow = { pct: number; countdown: string | null }
2
3export type CcswapScoped = { name: string; pct: number }
4
5export type CcswapGates = {
6 threshold: number
7 threshold5h: number | null
8 threshold7d: number | null
9 windows: string
10 models: string[]
11 modelThresholds: Record<string, number>
12}
13
14export type CcswapAccount = {
15 number: number
16 email: string
17 active: boolean
18 status: string
19 fiveHour: CcswapWindow | null
20 sevenDay: CcswapWindow | null
21 scoped: CcswapScoped[]
22}
23
24export type CcswapSnapshot = {
25 active: number | null
26 threshold: number
27 gates: CcswapGates
28 accounts: CcswapAccount[]
29 error: string | null
30}
31
32// 'dark' / 'light' use ccswap's hex palette; 'theme' falls back to theme keys.
33export type CcswapTone = 'dark' | 'light' | 'theme'
34
35export type CcswapTab = 'claude' | 'codex' | 'history' | 'settings'
36
37export type CcswapCodexAccount = { number: number; email: string; label: string; active: boolean }
38
39export type CcswapCodexView = { accounts: CcswapCodexAccount[]; error: string | null }
40
41export type CcswapSwitchEntry = { from: number; to: number; at: string }
42
43export type CcswapHistoryView = { entries: CcswapSwitchEntry[]; error: string | null }
44
45export type CcswapSettingsView = {
46 threshold: number
47 threshold5h: number | null
48 threshold7d: number | null
49 modelThresholds: string | null
50 strategy: string
51 windows: string
52 statusline: boolean
53 mod: boolean
54 error: string | null
55}
56
57declare module 'claude-code' {
58 interface PluginState {
59 ccswap: {
60 snapshot: CcswapSnapshot | null
61 tone: CcswapTone
62 switching: boolean
63 tab: CcswapTab
64 codex: CcswapCodexView | null
65 history: CcswapHistoryView | null
66 settings: CcswapSettingsView | null
67 }
68 }
69}
70