A bar above the prompt in the Switchboard profile's colour, with its name, plan and rate limits left

Run multiple Claude accounts at the same time on one Mac, and multiple ChatGPT or Codex accounts too. Two, or as many as you have memory for. Keep a personal account and a work account both signed in, in their own desktop windows and their own terminals, instead of logging out and back in every time you switch. Each account also gets a live rate-limit bar, so you can see which one has headroom left before you start.

It is for accounts you own. Native profiles use their own account. Codex desktop profiles can also use a shared proxy bucket, which selects accounts and handles inference quota failover. See Proxy buckets.
Yes to both, and the same goes for Codex. There is no limit built in. Both desktop apps are Chromium-based, so each account gets its own user-data directory and runs as a genuinely separate window with its own session. The command-line tools are separated the same way, with an environment variable per account.
Each profile is isolated twice over, because the two halves hold different state. Both desktop apps embed an agent that reads the same config-home variable the command-line tool does, so the flag alone is not enough.
| App | Signed-in session | Agent home: sessions, plugins, config |
|---|---|---|
| Claude | --user-data-dir=<…>/desktop | CLAUDE_CONFIG_DIR=<…>/home |
| Codex | --user-data-dir=<…>/desktop | CODEX_HOME=<…>/home |
Every account is a profile owning an isolated directory tree under ~/.switchboard/<vendor>/<profile>/. Profiles never share cookies, tokens, chat history or session state, and you can run as many at once as you have memory for.
The "Default" profiles point at the normal locations, ~/.claude, ~/.codex and ~/Library/Application Support/{Claude,Codex}. Switchboard never writes to them itself.
Two Claude apps on different profiles look the same, so Switchboard marks every Claude profile but the Default one. When it launches that profile's desktop app it passes a small Claude Code plugin (plugins/profile-band), and each Code session shows the profile band: a bar in the profile's colour just above the prompt. On the left are its name in bold, its plan, how full this session's context window is and what the session has cost. On the right, each of the 5-hour and 7-day limits shows a bar of what is left, when it resets (a countdown for the 5-hour window, a local day and time for the 7-day one), and its pace: "on track" for the 7-day window when less of it is used than of the week, or "runs out Fri 14:00" for either window when use so far would empty it before the reset. A narrow window gives up the cost, the "on track" note, the 7-day reset, the context, the 5-hour reset, the bars and the plan, in that order, then whole windows, keeping a window with a pace warning longest; the name always stays. The limits refresh every five minutes from Switchboard's cache, fetched live when that is over 15 minutes old, and need the switchboard command installed; context and cost update after every turn, and a compaction hides the context until the next one. The Default profile's app has no band. A rename or recolour shows after the profile's next launch.
Yes. Each profile gets its own CLI login, and the Terminal button opens a shell already inside that account, so claude or codex in that window uses it. The copy icon on each profile copies the one-line command, which can go into an alias.
Profiles show as a list or as cards; pick either with the toggle above them. Drag a profile to reorder it within its app; the Default profile stays first.
Signing a profile's CLI in is also what enables its usage bars.
Every window the account has: the 5-hour and 7-day windows for Claude, including model-scoped ones such as a separate Opus pool, and the weekly and model-specific pools for Codex. Each shows how much is used, or how much is left if you prefer, with the time until it resets. They turn amber and then red as a window runs out.
You can read them in the menu bar without opening the window.
Choose Usage resets… in a signed-in profile’s menu or a bucket account’s menu. A dialog opens in the window with the account’s current usage bars and each saved reset: how many are left, when it expires, which windows it clears, and why it can’t be used yet when it can’t. Pick one and choose Use reset… to see a confirmation that names the account and what will be spent; only Use reset on that screen spends it. Closing at any earlier point spends nothing. The last screen shows the provider’s answer beside the refreshed bars, with the old percentages struck through.
Claude’s next eligible grant and ChatGPT’s Codex reset credits are supported. A routed profile labels its own action Native account resets…. To reset a proxy account, use that account’s menu in Proxy buckets. The proxy supplies the selected account’s token; no native profile is required. After the vendor confirms a reset, Switchboard clears that account’s proxy cooldown, rechecks usage and updates its routing weight. Paused accounts stay paused. Other accounts keep their existing cooldowns. It never buys credits or changes a plan. A recent Claude CLI must be installed for Claude reset checks.
Existing bucket workers need a restart after installing this feature. Until a worker supports the targeted refresh, its reset dialog shows grants but does not allow redemption. Switchboard does not restart an active bucket for you.
These are private vendor interfaces and can change. Unknown responses stop the action; failed requests are never retried automatically. Pending request IDs are stored locally so an uncertain reply can be retried without spending a second reset. Check the vendor’s Usage page if a result is uncertain.
The CLI uses the same checks and confirmation flow. Listing never spends a reset; select an exact grant ID from the output to redeem it. resets PROFILE always targets the native account, even when that profile routes through a bucket. Bucket accounts can be selected by their exact name or an unambiguous email.
switchboard resets claude
switchboard resets codex --redeem GRANT_ID --yes
switchboard bucket resets BUCKET ACCOUNT
switchboard bucket resets BUCKET ACCOUNT --redeem GRANT_ID --yes
Results are JSON by default; add --human for readable output. Each offer carries remaining, expiresAt, clears and, when it can’t be used, reason. Without --yes, redemption prompts in a terminal and refuses in noninteractive calls. Check the JSON outcome for the vendor result and proxyRecovery for not-needed, refreshed, deferred or unconfirmed. An exit of zero alone does not mean quota was reset. Run switchboard usage PROFILE --refresh for fresh native usage. bun run test:usage-resets runs the isolated app and proxy worker integration checks.
skills/switchboard/SKILL.md is the canonical agent guide. The CLI tab's Copy agent prompt button copies that file, and switchboard guide prints the same Markdown from the installed app. Packaging includes the guide, so instructions and executable commands update together.
Agentfiles and other skill managers can use a short entrypoint that tells the agent to run switchboard guide before operating Switchboard, rather than maintaining a separate copy of the operating instructions. For older installations without guide, update Switchboard; switchboard --help can identify the available commands.
Each profile shows whether its desktop app is running: a green dot in the list, a pill on a card, and "(not running)" after its line in the menu bar. It keeps up on its own. Launching or quitting an app from anywhere, the Dock, Cmd+Q or the switchboard command, shows up within about a second, so there is no need to press Refresh, which is for the usage numbers.
Launch is the black play button and Quit the red power button. While one is on its way the button spins and the profile reads Starting… or Quitting…. An app still running ten seconds after Quit reads Won't quit, usually because it is asking you to confirm; switch to the app and answer it, or use Force quit, which loses anything unsaved in it.
Closing an app's window with its red button leaves the app running. Turn on Notice closed windows in Settings and such a profile reads No window, with a hollow dot, instead of Running. This needs Accessibility permission: turning the switch on asks macOS for it, and the switch stays off until you allow Switchboard in System Settings, then turns on by itself. Because the app is ad-hoc signed, macOS forgets the permission after each rebuild; the switch then reads off again, with a link to the settings pane, where you turn Switchboard off and on. A window that is minimised, hidden or on another desktop still counts as open. Whether or not the setting is on, Show window (a button on a No window row, and in each running profile's menu) brings that profile's window back, as clicking its Dock icon would.
Yes, and reply and approve from it too. Open the Phone tab, turn on phone access, press Publish to put it on your tailnet, and scan the pairing QR code with your phone. The phone app lists what needs you and what is working across every profile, each profile's usage, and each session's transcript with its steps, diffs and the PRs it opened. Reply in a session, answer its questions and approve its commands from the phone, and turn on notifications for when one needs you or finishes. It reads the session files the desktop apps already write, so the apps work exactly as before. An app you opened from the Dock can be watched but not replied to until you relaunch it from the Phone tab or the phone; Default Claude can instead take replies however it was opened, with Default Claude from the Dock in the Phone tab. Read Phone access for setup and how it is secured.
Use Keep awake beside Refresh to turn macOS's system sleep setting on or off. macOS handles administrator authorization. The control reads the actual setting, including after you reopen Switchboard; closing or crashing the app leaves the setting as you chose it.
For implementation details and closed-lid hardware verification, read Keep awake.
open supports --env, which is how a profile's config home reaches the app. Confirmed on macOS 26; I have not established the earliest version that carries the flag, so check with man open if you are on something older./Applications. Other locations are not detected yet.claude or codex CLI for the usage bars. Switchboard asks your login shell for its environment, so a version manager such as nvm, fnm, volta or mise is fine, and so is fish or bash rather than zsh.Worth knowing before you run an unsigned app that touches your accounts.
find-generic-password` for the entry the Claude Code CLI already created. macOS will ask for your password the first time. It asks again after each rebuild, because ad-hoc signing produces a new code hash and the keychain entry's permission no longer recognises the app. Codex tokens are read from a file instead, so they produce no prompt.
/usr/bin/expect, safe mode, no tools or MCP servers, and no model prompt. Only the trust menu for that empty directory is accepted. Recovery has a 20-second deadline plus bounded process cleanup; failed attempts have a one-minute cooldown. If Claude requires interactive sign-in, renewal stops and the profile must be opened in Terminal. A rejected token that has not expired also requires sign-in, unless another CLI has already replaced it.bun install
bun run install-app
That builds Switchboard.app, copies it to /Applications, ad-hoc signs it and opens it. Launch it like any other app afterwards. Re-run the same command after changing the source. For a dev run without installing, use bun start.
The app is not signed with a Developer ID and not notarised, so macOS may warn about it. Building it yourself, as above, is the intended path.
It also lives in the menu bar with launch, quit and usage per profile, so you can close the window and leave it running. Settings has an "Open at login" switch; started that way it stays in the menu bar until you click it.
claude auth login or codex login inside that profile. This is what enables the usage bars.Remove on a card deletes the profile and everything under its directory: the CLI login, the desktop session, history and settings. There is no way to remove a profile and keep its data. The Default profiles cannot be removed.
Items you bring over can be linked or copied, and the difference matters.
Keep in sync makes the new profile's file a symlink to the source profile's. One edit then applies to both, which is the point for skills you maintain in one place. It also means the reverse: if the second account's agent rewrites a file, for example when it updates CLAUDE.md or AGENTS.md from a memory shortcut, that write lands in the source profile too. Choose Copy once for anything you want the two accounts to be able to change independently.
Chat history is always copied, never linked, because two accounts writing into one session folder would corrupt each other's resume lists. For Codex it also carries the sidebar's project list and which project each thread sits in, since the app keeps that separately from the sessions and would otherwise show the threads unplaced or, for ones run in worktrees, not at all.
Logins, memories and session state are never brought over at all. Connectors and plugins are offered but off by default, because they reach the source account's Slack, Notion and so on.
Everything the window does is also a switchboard command, with results as JSON so an agent can read them and a person can pipe them into jq. The common questions have one-line answers:
switchboard list # profiles, running state, signed-in account
switchboard usage --max-age 15m # rate-limit windows, refreshed if older than 15 minutes
switchboard pick claude # the Claude profile with the most quota left
switchboard exec work -- claude -p "…" # run anything inside a profile's account
eval "$(switchboard env work)" # put the current shell into a profile
switchboard launch work # open its desktop window
switchboard focus work # show its existing window; never launch another profile
switchboard quit work --force --yes # force quit; reports whether it actually stopped
switchboard awake status # read the system keep-awake setting
switchboard accessibility status # permission of the running Switchboard app
switchboard export work --format t3 # print a T3 provider configuration
switchboard add codex Client --from codex # a new profile, set up like the Default
switchboard routed work app-server # Codex through work's proxy bucket, as its window runs
awake status|on|off|recheck, accessibility status|open, focus and forced quit use the running Switchboard app through a local socket accessible only to your user account. Start the matching app first; these commands never start it implicitly. Keep-awake shares the window's controller and macOS authorization. Its result reports the observed state and any cancellation or failure notice; exit 0 alone does not mean the requested setting was applied. Accessibility reports the app's executable identity, not the terminal's permission. open opens the macOS Accessibility pane. Force quit asks for confirmation unless --yes is supplied and waits for the result; stopped: false means the app has not exited. Ordinary quit still works without Switchboard running.
export PROFILE --format t3 prints a providerInstances fragment containing the profile's name, colour and actual CLI home, with driver claudeAgent or codex. It contains no credentials and never edits T3 settings. IDs longer than T3’s 64-character provider-key limit are refused with manual setup guidance. Proxy-routed Codex profiles are refused because exporting their native home would silently lose routing. Use a native-account profile for export, or the routed command below.
A Codex profile assigned to a proxy bucket reaches the pool through a local port that changes whenever the bucket's worker restarts. A client Switchboard does not launch, such as T3 Code or a script, should run switchboard routed PROFILE as its Codex binary; it starts the worker if needed and finds the current port on every call.
Install it from the CLI tab in the window, or once with switchboard install-cli (or node out/cli.js install-cli from this checkout) after bun run install-app. The command runs on the installed app's own runtime and code, so it is always the same version as the app, and bun run install-app updates both. bun run cli -- list runs it from source without installing.
Profiles are addressed by id (claude-work), by vendor (claude means that vendor's Default), by vendor/name, or by a name that only one profile has. switchboard --help lists every command.
The contract, for anything that parses the output: a successful command prints its result as JSON on stdout and exits 0. A failed one prints nothing on stdout, one JSON object on stderr with a stable error code, a message and usually a hint, and exits 1 (it ran and failed), 2 (usage), 3 (not found) or 4 (refused by a safety rule, such as removing a profile whose window is open, or --yes missing). exec, cli and routed exit with the child's own status. Per-profile usage errors are data inside a successful result, with a status of ok, stale, not-signed-in, error or none.
The CLI reads the app's cached usage numbers by default and fetches live only with --max-age or --refresh; it never polls. It writes profiles.json directly, and a running app notices and reloads within about a second, so the window and the command line never disagree about which profiles exist.
--user-data-dir flag or the usage endpoints. The Default profiles keep working regardless.ChatGPT.app bundle, and every profile launches that one bundle, so an update to it applies to all of them. macOS registers each instance separately, which means one Dock icon per running profile rather than one for the app.ANTHROPIC_API_KEY in your shell makes Claude Code bill the API instead of your subscription. Switchboard never sets it; check your own shell config.The source is TypeScript. The main process is compiled by tsc into out/, which is what Electron runs. The window is a small Preact app under src/renderer/, bundled by bun build into out/renderer/main.js; its styling is one stylesheet of tokens and primitives modelled on Wispr Flow, with Figtree and EB Garamond bundled. Tests import the .ts files directly.
bun test # profile isolation, setup logic and the usage parsers
bun run test # the same, after oxlint and a type check
bun run test:claude-pty # compiled PTY integration checks under Node, on macOS
bun run typecheck # tsc --noEmit
bun run lint # oxlint
bun format # oxfmt; bun run fmt is also supported (CSS/HTML excluded by config)
bun start # build, then run without installing
bun run demo # regenerate the screenshot and social carhooks/register.tsx 274 lines1// A Claude Code mod that Switchboard passes to every Claude profile it
2// launches (CLAUDE_CODE_PLUGIN_DIRS, see src/launch.ts). It fills the band
3// above the prompt with the profile's colour, so which profile an app belongs
4// to, and whether it has room for more work, can be spotted from across the
5// screen. On the left: the profile's name and plan, then how full this
6// session's context window is and what the session has cost. On the right:
7// the 5-hour and 7-day rate limits, each as a bar of what is left, when it
8// resets, and whether use so far would run it out before then.
9//
10// The limits come from `switchboard usage` every five minutes: Switchboard's
11// cache, fetched live when that is over 15 minutes old, and never renewing the
12// sign-in this session is using. Context and cost come from the session itself
13// when it starts and after every turn; a compaction hides the context until
14// the next turn. A narrow band drops
15// detail in a fixed order (DROPS), then whole windows, a window with a pace
16// warning last, and never the name. The Default profile is launched without
17// the variables and draws nothing.
18
19import { atom, read, update } from 'claude-code';
20import type { EngineInterface, Register } from 'claude-code';
21
22import type { BandSession, BandUsage, BandWindow } from '../types';
23import { clockTime, pace, resetsOn, until } from './limits';
24
25export { pace, resetsOn, until };
26
27const REFRESH_MS = 5 * 60 * 1000;
28const usage = atom({ plugin: 'switchboard-profile-band', key: 'usage' } as const, null);
29const session = atom({ plugin: 'switchboard-profile-band', key: 'session' } as const, null);
30
31const BAR_CELLS = 10;
32
33type Profile = { id: string | undefined; name: string; color: string; command: string | undefined };
34
35// Text on the profile's colour: dark on a light colour, light on a dark one.
36// `undefined` for anything but #rrggbb, which then colours the name instead.
37export function labelColor(hex: string): string | undefined {
38 const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
39 if (!m) return undefined;
40 const [r, g, b] = m.slice(1).map((c) => {
41 const v = parseInt(c, 16) / 255;
42 return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
43 });
44 const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
45 return luminance > 0.4 ? '#1a1a1a' : '#ffffff';
46}
47
48// The profile's plan and its 5-hour and 7-day windows from `switchboard usage
49// PROFILE` output; null when there are no numbers to show.
50export function parseUsage(stdout: string): BandUsage | null {
51 try {
52 const row = JSON.parse(stdout).profiles?.[0]?.usage;
53 if (!row || (row.status !== 'ok' && row.status !== 'stale')) return null;
54 const windows: BandWindow[] = (row.windows ?? [])
55 .filter((w: BandWindow) => w.label === '5h' || w.label === '7d')
56 .map((w: BandWindow) => ({
57 label: w.label,
58 remaining: w.remaining,
59 resetsAt: w.resetsAt ?? null,
60 severity: w.severity,
61 }));
62 return { plan: row.plan ?? null, windows };
63 } catch {
64 return null;
65 }
66}
67
68// "███████░░░": what is left of a window, in tenths.
69export function bar(remaining: number): string {
70 const full = Math.max(0, Math.min(BAR_CELLS, Math.round(remaining / 10)));
71 return '█'.repeat(full) + '░'.repeat(BAR_CELLS - full);
72}
73
74// What the band can say, before it is fitted to the width it has.
75export type BandFacts = {
76 name: string;
77 plan: string | null;
78 context: number | null;
79 costUsd: number | null;
80 limits: {
81 label: string;
82 remaining: number;
83 // "resets in 1h 47m" or "resets Sat 02:00".
84 resets: string | null;
85 // "on track", "runs out Fri 14:00", or nothing to say.
86 pace: { text: string; isWarning: boolean } | null;
87 isLow: boolean;
88 }[];
89};
90
91// What a narrow band gives up, first to last, before it drops whole windows.
92const DROPS = ['cost', 'onTrack', 'reset7d', 'context', 'reset5h', 'bars', 'plan'] as const;
93type Drop = (typeof DROPS)[number];
94
95export type BandLayout = { detail: string; limits: { key: string; text: string; isBold: boolean }[] };
96
97function layout(f: BandFacts, dropped: Set<Drop>, hidden: Set<string>): BandLayout {
98 const detail = [
99 !dropped.has('plan') && f.plan,
100 !dropped.has('context') && f.context !== null && `context ${f.context}%`,
101 // Less than a cent is not worth the room.
102 !dropped.has('cost') && f.costUsd !== null && f.costUsd >= 0.005 && `$${f.costUsd.toFixed(2)}`,
103 ].filter(Boolean);
104 const limits = f.limits
105 .filter((l) => !hidden.has(l.label))
106 .map((l) => {
107 const parts = [
108 `${l.label} ${dropped.has('bars') ? '' : `${bar(l.remaining)} `}${l.remaining}%`,
109 !dropped.has(`reset${l.label}` as Drop) && l.resets,
110 l.pace && (l.pace.isWarning || !dropped.has('onTrack')) && l.pace.text,
111 ].filter(Boolean);
112 return { key: l.label, text: parts.join(' · '), isBold: l.isLow || !!l.pace?.isWarning };
113 });
114 return { detail: detail.length ? ` ${detail.join(' · ')}` : '', limits };
115}
116
117// The most of the band that fits in `columns` cells, the padding included.
118// Windows go from the right, those with a pace warning after the rest.
119export function fitBand(f: BandFacts, columns: number): BandLayout {
120 const windows = [...f.limits]
121 .reverse()
122 .sort((a, b) => Number(!!a.pace?.isWarning) - Number(!!b.pace?.isWarning))
123 .map((l) => l.label);
124 const steps = DROPS.length + windows.length;
125 for (let n = 0; ; n++) {
126 const dropped = new Set(DROPS.slice(0, n));
127 const shown = layout(f, dropped, new Set(windows.slice(0, Math.max(0, n - DROPS.length))));
128 const width = 2 + f.name.length + shown.detail.length + shown.limits.reduce((w, l) => w + l.text.length + 4, 0);
129 if (width <= columns || n === steps) return shown;
130 }
131}
132
133export function bandFacts(
134 p: { name: string },
135 u: BandUsage | null,
136 s: BandSession | null,
137 now: number,
138 timeZone?: string,
139): BandFacts {
140 return {
141 name: p.name,
142 plan: u?.plan ?? null,
143 context: s?.context ?? null,
144 costUsd: s?.costUsd ?? null,
145 limits: (u?.windows ?? []).map((w) => {
146 const is5h = w.label === '5h';
147 const reset = is5h ? until(w.resetsAt, now) : resetsOn(w.resetsAt, now, timeZone);
148 const paced = pace(w, now);
149 return {
150 label: w.label,
151 remaining: w.remaining,
152 resets: reset && `resets ${is5h ? 'in ' : ''}${reset}`,
153 // The 5-hour window speaks up only when it is running out.
154 pace:
155 paced === 'ok'
156 ? is5h
157 ? null
158 : { text: 'on track', isWarning: false }
159 : paced && { text: `runs out ${clockTime(paced.runsOutAt, !is5h, timeZone)}`, isWarning: true },
160 // Low as Switchboard's own window colours it: warned, or 70% used.
161 isLow: w.severity === 'warning' || w.severity === 'critical' || w.remaining <= 30,
162 };
163 }),
164 };
165}
166
167// The launch environment does not change while the session runs.
168let profile: Promise<Profile | null> | undefined;
169
170function loadProfile($: EngineInterface): Promise<Profile | null> {
171 profile ??= (async () => {
172 const name = await $.env.get('SWITCHBOARD_PROFILE_NAME');
173 if (!name) return null;
174 return {
175 id: await $.env.get('SWITCHBOARD_PROFILE'),
176 name,
177 color: (await $.env.get('SWITCHBOARD_PROFILE_COLOR')) ?? '',
178 command: await $.env.get('SWITCHBOARD_COMMAND'),
179 };
180 })();
181 return profile;
182}
183
184async function readSession($: EngineInterface): Promise<void> {
185 try {
186 const s = await $.session.usage();
187 await update($, session, () => ({ context: s.context.percent ?? null, costUsd: s.cost?.usd ?? null }));
188 } catch {
189 // The band keeps the last figures.
190 }
191}
192
193export const register: Register = (on) => {
194 on('session.start', async ($, e, next) => {
195 const started = await next(e);
196 const p = await loadProfile($);
197 if (!p) return started;
198 void readSession($);
199 const id = p.id;
200 const command = p.command;
201 if (!id || !command) return started;
202
203 const refresh = async () => {
204 try {
205 const { exitCode, stdout } = await $.process.run([command, 'usage', id, '--max-age', '15m', '--no-renew'], {
206 timeoutMs: 20000,
207 });
208 if (exitCode !== 0) return;
209 const latest = parseUsage(stdout);
210 if (latest) await update($, usage, () => latest);
211 } catch {
212 // No numbers this round; the band keeps the last ones.
213 }
214 };
215 void refresh();
216 $.clock.every(REFRESH_MS, () => void refresh());
217 return started;
218 });
219
220 // The main conversation's, not a subagent's: the band shows this session.
221 on('turn.complete', async ($, e, next) => {
222 const done = await next(e);
223 if (!e.agentId && (await loadProfile($))) void readSession($);
224 return done;
225 });
226
227 // The session reports the last response's fill until the next one, which a
228 // compaction makes wrong: show none until the next turn reads it again.
229 on('session.compact', async ($, e, next) => {
230 const done = await next(e);
231 if (!e.agentId) await update($, session, (s) => s && { ...s, context: null });
232 return done;
233 });
234
235 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
236 if (e.props.hasSurvey) return next(e);
237 const p = await loadProfile($);
238 if (!p) return next(e);
239
240 const { Box, Text } = $.ui.resolve(e);
241 const label = labelColor(p.color);
242 if (!label) {
243 return (
244 <Text color={p.color || undefined} bold>
245 {`● ${p.name}`}
246 </Text>
247 );
248 }
249
250 const u = await read($, usage);
251 const s = await read($, session);
252 const now = u?.windows.length ? await $.clock.now() : 0;
253 const shown = fitBand(bandFacts(p, u, s, now), e.props.bodyColumns);
254
255 return (
256 <Box width="100%" backgroundColor={p.color} paddingX={1} flexDirection="row" justifyContent="space-between">
257 <Box flexDirection="row">
258 <Text color={label} bold>
259 {p.name}
260 </Text>
261 {shown.detail ? <Text color={label}>{shown.detail}</Text> : null}
262 </Box>
263 <Box flexDirection="row">
264 {shown.limits.map((l, i) => (
265 <Text key={l.key} color={label} bold={l.isBold}>
266 {`${i ? ' ' : ''}${l.text}`}
267 </Text>
268 ))}
269 </Box>
270 </Box>
271 );
272 });
273};
274hooks/limits.ts 57 lines1// The band's arithmetic on a rate-limit window: how long until it resets,
2// when, and whether it lasts until then. Kept apart from register.tsx so
3// Switchboard's own tests can hold `pace` to the app's copy in
4// src/shared/usage.ts, which this mod, running inside Claude's engine,
5// cannot import.
6
7import type { BandWindow } from '../types';
8
9const HOUR = 60 * 60 * 1000;
10const WINDOW_MS: Record<string, number> = { '5h': 5 * HOUR, '7d': 7 * 24 * HOUR };
11
12// "2h 5m", "40m", "3d": how long until a window resets.
13export function until(resetsAt: string | null, now: number): string | null {
14 const at = resetsAt ? Date.parse(resetsAt) : NaN;
15 if (Number.isNaN(at) || at <= now) return null;
16 const minutes = Math.round((at - now) / 60000);
17 if (minutes < 60) return `${minutes}m`;
18 if (minutes < 48 * 60) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
19 return `${Math.round(minutes / 1440)}d`;
20}
21
22// "Sat 02:00", or "16:20" without the day: a local time, for the 7-day reset,
23// whose reset is days off and easier to plan around as a date than a count.
24// Rounded to the minute: resets land a moment before the hour (01:59:59.9).
25export function clockTime(at: number, withDay: boolean, timeZone?: string): string {
26 return new Date(Math.round(at / 60000) * 60000).toLocaleString('en-GB', {
27 ...(withDay ? { weekday: 'short' } : {}),
28 hour: '2-digit',
29 minute: '2-digit',
30 timeZone,
31 });
32}
33
34export function resetsOn(resetsAt: string | null, now: number, timeZone?: string): string | null {
35 const at = resetsAt ? Date.parse(resetsAt) : NaN;
36 if (Number.isNaN(at) || at <= now) return null;
37 return clockTime(at, true, timeZone);
38}
39
40// Whether the window lasts to its reset at the rate it has been used so far:
41// 'ok' when it does, the moment it would run out when it does not, null when
42// there is too little of the window behind us to say (its first tenth) or no
43// reset time, or nothing left, which the bar already says. The two answers are
44// exact complements: a window runs out early precisely when less of it is left
45// than of the time.
46export function pace(w: BandWindow, now: number): 'ok' | { runsOutAt: number } | null {
47 const windowMs = WINDOW_MS[w.label];
48 const at = w.resetsAt ? Date.parse(w.resetsAt) : NaN;
49 if (!windowMs || Number.isNaN(at) || at <= now || w.remaining <= 0) return null;
50 const timeLeft = at - now;
51 const elapsed = windowMs - timeLeft;
52 if (elapsed < windowMs / 10) return null;
53 const used = 100 - w.remaining;
54 if (used <= 0 || w.remaining * elapsed >= used * timeLeft) return 'ok';
55 return { runsOutAt: now + (w.remaining * elapsed) / used };
56}
57types/index.d.ts 13 lines1// What the band keeps between draws: the profile's plan and rate-limit
2// windows, as `switchboard usage` last reported them, and this session's
3// context fill (a whole percentage) and cost, as the session last reported them.
4export type BandWindow = { label: string; remaining: number; resetsAt: string | null; severity: string | null };
5export type BandUsage = { plan: string | null; windows: BandWindow[] };
6export type BandSession = { context: number | null; costUsd: number | null };
7
8declare module 'claude-code' {
9 interface PluginState {
10 'switchboard-profile-band': { usage: BandUsage | null; session: BandSession | null };
11 }
12}
13