Moves Claude Code between your Claude accounts as their usage limits fill, shows each account's usage under the prompt, and signs an account back in with one…

A Claude Code mod for people with more than one Claude account. It shows each account's usage under the prompt, and moves your session to another account before the one in use runs out.

<sub>A real session fed imitated accounts (demo/harness), so no real account appears.</sub>
/plugin install account-rotator --marketplace ivokund/claude-account-rotator
Turn on auto-update, or you stay on the version you installed: in /plugin, open Marketplaces, pick claude-account-rotator and choose Enable auto-update. Claude Code then updates the mod each time it starts. It is off by default for every marketplace but Anthropic's own.
Then click the usage in the footer, press + Add an account and approve the sign-in in your browser. The account you are signed in with now is account 1.
To update by hand instead, pull the marketplace, then the mod, and start a new session:
claude plugin marketplace update claude-account-rotator
claude plugin update account-rotator@claude-account-rotator
The changelog says what each version changed.
A column per account. The top row is the room it has right now (its 5-hour window, or none once its week is spent), the bottom row its week: green with plenty left, red with little. The percents are the account in use's.
Click it for the panel: each account's usage and reset times, Sign in, Use now and Remove, + Add an account, Rotate now, Chrome, which picks the account Claude in Chrome uses, Usage based rotation, which picks the account the rotation moves to, and Display, which picks the footer's look:

/login. /login signs in the account the session is on, which after a switch isn't Claude Code's login. The mod checks who each account's sign-in belongs to: one that now holds another account's asks for its own again, and the session moves off it; one signed in as an account not on the list becomes that account./tui fullscreen), the only one that passes clicks on: the panel opens with a click.set -g mouse on, and iTerm2's tmux -CC mode can't run fullscreen./login a personal account, Pro or Max: see Team and Enterprise accounts.Claude Code's own "You've used N% of your session limit" warning can still show for a minute after a switch: the switch lands within about 35 seconds, and warnings Claude Code queued before it still play. No mod can hide it.
Mods are early access in Claude Code, and this one relies on internals a release can change: where sign-ins are stored, and the usage endpoint behind /usage.
The mod moves between personal accounts and Team or Enterprise seats. But Claude Code stops plugins from switching accounts, for the rest of a session, when:
/reload-plugins, or installing, enabling or disabling a plugin (since 2.1.299).The block comes from a built-in security default that stops plugins you install from changing where Claude Code reads its sign-in. It also runs on any machine with managed settings. The mod tells you when a session is blocked, and marks it in the footer.
Ways around it, best first:
| Way | Rotates | For |
|---|---|---|
| 1. Start on a personal account | Yes | Anyone with a personal account, Pro or Max |
| 2. Start on a chosen account | No: restart Claude to change accounts | When all your accounts are seats |
| 3. Turn the security default off | Yes, untested | A machine you alone control: read its warning first |
The fix. A session that starts on a personal account can switch, to seats as well. New sessions start on Claude Code's login, which the panel's second line names:
/login with your personal account (Pro or Max) in a new session. /login changes Claude Code's login only in a session on it; in a session the mod moved, it signs in that account instead. It doesn't unblock the session it runs in: restart Claude after./login: + Add an account, and Sign in to renew.claude --continue or claude --resume to keep your conversation (or plain claude). Each starts on your /login. Not /restart: it stays on the account in use.Not a fix: a session started on a seat this way still can't switch. It only picks the account: with only seats, start on the one the footer shows with room, and restart Claude on another when it runs low.
CLAUDE_SECURESTORAGE_CONFIG_DIR="$HOME/.claude/accounts/2" claude --continue
2 is the account's number in the footer and the panel; plain claude starts on account 1, Claude Code's login. Type the path as here, with no / at the end and no ~ in quotes: Claude Code and the mod know the account by its exact text, so any other spelling can start signed out, and shows in the panel as a new account. Set it on the command, not with export, or every later claude in that shell starts there too. Numbers are reused after Remove: check the panel before putting one in an alias.
Started this way on a personal account, a session rotates as in 1, with your /login left a seat.
[!WARNING] This removes a security protection for every plugin and every session on the machine. With it off, a plugin you install can override what an organization's policy sets for Claude Code (its hooks, prompt content, settings, tool and MCP server rules) and change where Claude Code reads sign-ins and settings from. Anthropic's Usage Policy forbids intentionally bypassing restrictions or guardrails built into its products. This is a setting Claude Code offers administrators, but using it so a Team session can switch accounts may count as bypassing. Do it only on a machine you alone control, with plugins you trust. Never do it where an organization manages Claude Code, or where your Team or Enterprise organization's rules forbid it.
Managed settings decide whether the default runs: once they set prependPlugins, it runs only if listed there. The file must be owned by an administrator, since Claude Code ignores this key in a file your account can write. If the file below already exists, it holds your organization's policy: leave it alone. Otherwise:
# macOS
sudo mkdir -p "/Library/Application Support/ClaudeCode"
echo '{ "prependPlugins": [] }' | sudo tee "/Library/Application Support/ClaudeCode/managed-settings.json"
# Linux
sudo mkdir -p /etc/claude-code
echo '{ "prependPlugins": [] }' | sudo tee /etc/claude-code/managed-settings.json
It applies to sessions started after. Delete the file to turn the default back on. Managed settings an organization sends from Anthropic's servers can override it.
Untested: this follows how Claude Code 2.1.301 describes and reads the setting, but it has not been tried end to end, and a release can change it. You use it at your own risk.
The Claude extension in Chrome is signed in to one claude.ai account and answers only Claude Code connections made as that account. Claude Code connects Claude in Chrome at a session's first browser call, as the account the session is on then, and keeps that connection until it drops. With the rotation moving sessions between accounts, that is often not the extension's: Claude Code then says the extension is signed in to a different account and suggests /login, which doesn't fix it, and in a session the mod moved signs in the wrong account.
/mcp reconnect claude-in-chrome, and once a browser answers tells Claude to carry on. Connect above the prompt does the same by hand. While the window visits the extension's account, its line in the panel says Connecting Chrome…, not in use.A window Claude Code stops from switching can connect only as the account it is on. Where that isn't the extension's, the line above the prompt gives the command that brings the conversation back in a new session, which starts free to switch: claude --resume <id>.
~/.claude/accounts/<n>, and Claude Code keeps its sign-in in the keychain under that folder's name (on Linux, in that folder's .credentials.json), as for any config folder. A switch points the session at another account's sign-in./usage reads, and once per sign-in who it belongs to, from the one Claude Code asks at a sign-in, each with that account's own token. In a session with Claude in Chrome it also asks Claude Code's own Claude in Chrome which browsers answer, as the session opens, before moving off the extension's account, and on Use for Chrome, Try to connect and Connect. Tokens stay where Claude Code keeps them; the mod stores each account's email, organization, plan and last usage, a digest of its token, to tell a new sign-in, and which account your Chrome extension is signed in to.Remove each account in the panel, which signs it out. Then run claude plugin marketplace remove claude-account-rotator, which uninstalls the mod and deletes what it stored, and delete ~/.claude/accounts.
As of October 2026:
claude auth login and keeps no tokens of its own.Terms change; this is not legal advice. Not affiliated with or endorsed by Anthropic.
claude --plugin-dir . # a session with the mod loaded from this folder
claude plugin validate .
claude plugin test .
--plugin-dir loads this folder over the installed release for that session only, with a list of accounts of its own, so a broken working tree breaks only that window. Keep the marketplace installed from GitHub: added from this folder instead, every window loads the folder as it stands. /release publishes a version, by the steps in .claude/skills/release.
demo/record.mjs records the GIF and demo/looks.mjs draws the footer's looks, both from a real session fed imitated accounts; their headers say what they need.
hooks/register.tsx 1114 lines1import { atom, read, update } from 'claude-code'
2import type {
3 EngineInterface,
4 HookStream,
5 McpToolResult,
6 ProcessSpawnChunk,
7 ProcessSpawnResult,
8 Register,
9 SessionRateLimit,
10 Timer,
11} from 'claude-code'
12
13import type { Account, FooterStyle, Health, Holder, Reading, RotateTo, View } from '../types'
14import {
15 CHROME_SERVER,
16 CHROME_TOOL,
17 EMPTY_VIEW,
18 LEAVE_FIVE_HOUR,
19 blockedText,
20 browsersFrom,
21 canConnectChrome,
22 chromeNote,
23 credentialFrom,
24 credentialsFile,
25 fingerprint,
26 footerStyleFrom,
27 freeId,
28 healthOf,
29 identityFromProfile,
30 identityFromStatus,
31 isLoginOf,
32 isNoBrowser,
33 isOnNormalLogin,
34 isPolicyRefusal,
35 keychainItem,
36 keychainUser,
37 label,
38 pickTarget,
39 rotateToFrom,
40 readingFromLimits,
41 readingFromUsage,
42 sameLogin,
43 sameUsage,
44 shouldLeave,
45 slotEnv,
46 windowPct,
47} from './model'
48import type { Credential, Identity } from './model'
49import { Band, Footer, Pane } from './view'
50import type { Actions } from './view'
51
52type Host = EngineInterface
53
54const PANE = 'claude-accounts'
55const TITLE = 'Claude accounts'
56/** The dock width the pane asks for: a login's line, its buttons and its usage rows fit on one line each. */
57const PANE_COLUMNS = 64
58/** Claude Code caches a keychain read for 30 s, so a switch lands within this. */
59const SETTLE_MS = 35_000
60/** A switch no response has shown after this long is reported as not taken. */
61const CONFIRM_GIVE_UP_MS = 4 * 60_000
62/**
63 * Claude Code refreshes a token 5 minutes before it expires. A refresh that
64 * runs while the old login's read is still cached is saved under the new
65 * slot, overwriting that login: so no switch this close to the expiry.
66 */
67const REFRESH_GUARD_MS = 8 * 60_000
68/** How long the mod waits on Claude in Chrome to list its browsers, connecting first, before going on without. */
69const CHROME_WAIT_MS = 15_000
70/** A file only macOS has: there Claude Code keeps logins in the keychain, elsewhere (Linux) in a file each. */
71const MACOS_MARKER = '/System/Library/CoreServices/SystemVersion.plist'
72const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
73const PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile'
74const CONTINUE =
75 'Claude Code switched to another of your Claude accounts because the previous one hit its usage limit or lost its sign-in. Continue where you left off.'
76
77const viewAtom = atom({ plugin: 'account-rotator', key: 'view' } as const, EMPTY_VIEW)
78
79/**
80 * Whether this session's pane shows. A press opens or closes it in its own
81 * turn, with no read before: the engine counts an open as the person's only
82 * there, and places it at any width; one made after an await waits undrawn
83 * below 144 columns. Kept in step with closes by the person and with reloads.
84 */
85let isPaneShown = false
86/** The `claude auth login` child of the sign-in under way, so Cancel can end it. */
87let running: HookStream<ProcessSpawnChunk, ProcessSpawnResult> | undefined
88/** The login this session is signing in; a stored 'logging-in' from a session that died is checked again. */
89let signingIn: string | undefined
90let signInQueue: Promise<void> = Promise.resolve()
91/** A switch the refresh guard holds back: the latest one asked for, tried again each minute until it goes. */
92let held: { target: Account; why: string; timer: Timer } | undefined
93/** Logins a switch to did not take this session: the rotation leaves them be; Use now still tries. */
94const untaken = new Set<string>()
95/** When this session last moved to another login: until SETTLE_MS after, its requests may still go out as the one before. */
96let movedAt: number | undefined
97/** Connect is under way: the rotation waits for it, and browser calls are held back. */
98let isConnectingChrome = false
99
100// ---------------------------------------------------------------- state
101// The view is this session's; the store is one JSON file every session of the
102// mod shares: the list of logins, each login's last reading and health under a
103// key of its own, so sessions writing different logins never collide, the
104// footer's look, and which login the rotation moves to.
105
106/** The view survives a hot reload as the code before wrote it: what this code added starts as in a new session. */
107const current = (v: View): View => ({ ...EMPTY_VIEW, ...v })
108const getView = async ($: Host): Promise<View> => current(await read($, viewAtom))
109const setView = ($: Host, fn: (v: View) => View): Promise<View> => update($, viewAtom, v => fn(current(v)))
110/** Something the person should know that nothing on screen says: a toast, on screen for a while. */
111const tell = ($: Host, text: string) => $.ui.toast(text, { timeoutMs: 8000 })
112const debug = ($: Host, text: string) => $.ui.log(`account-rotator: ${text}`, { to: 'debug' })
113
114function isAccount(value: unknown): value is Account {
115 if (typeof value !== 'object' || value === null) return false
116 const { id, slot } = value as Record<string, unknown>
117 return typeof id === 'string' && typeof slot === 'string'
118}
119
120async function loadAccounts($: Host): Promise<Account[]> {
121 const stored = await $.store.get('accounts')
122 return Array.isArray(stored) ? stored.filter(isAccount) : []
123}
124
125async function saveAccounts($: Host, accounts: Account[]): Promise<void> {
126 await $.store.set('accounts', accounts)
127 await setView($, v => ({ ...v, accounts }))
128}
129
130async function saveReading($: Host, id: string, reading: Reading): Promise<void> {
131 await $.store.set(`reading:${id}`, reading)
132 await setView($, v => ({ ...v, readings: { ...v.readings, [id]: reading } }))
133}
134
135/** Stores a login's health; answers what it was before. */
136async function saveHealth($: Host, id: string, health: Health): Promise<Health | undefined> {
137 const before = (await getView($)).health[id]
138 await $.store.set(`health:${id}`, health)
139 await setView($, v => ({ ...v, health: { ...v.health, [id]: health } }))
140 return before
141}
142
143async function saveHolder($: Host, id: string, holder: Holder): Promise<void> {
144 await $.store.set(`holder:${id}`, holder)
145 await setView($, v => ({ ...v, holders: { ...v.holders, [id]: holder } }))
146}
147
148/** Folds what other sessions stored into this session's view. */
149async function mergeStore($: Host): Promise<void> {
150 const accounts = await loadAccounts($)
151 const readings: Record<string, Reading> = {}
152 const health: Record<string, Health> = {}
153 const holders: Record<string, Holder> = {}
154 for (const a of accounts) {
155 const r = await $.store.get(`reading:${a.id}`)
156 if (typeof r === 'object' && r !== null && typeof (r as Reading).at === 'number') readings[a.id] = r as Reading
157 const h = await $.store.get(`health:${a.id}`)
158 if (typeof h === 'object' && h !== null && typeof (h as Health).kind === 'string') health[a.id] = h as Health
159 const s = await $.store.get(`holder:${a.id}`)
160 if (typeof s === 'object' && s !== null && typeof (s as Holder).token === 'string' && typeof (s as Holder).who?.email === 'string') {
161 holders[a.id] = s as Holder
162 }
163 }
164 const footer = footerStyleFrom(await $.store.get('footer'))
165 const rotateTo = rotateToFrom(await $.store.get('rotate-to'))
166 const chrome = await $.store.get('chrome-account')
167 const chromeAccountId = typeof chrome === 'string' && accounts.some(a => a.id === chrome) ? chrome : undefined
168 const seen = await $.store.get('chrome-accounts')
169 const chromeAccountIds = (Array.isArray(seen) ? seen : []).filter((id): id is string => typeof id === 'string' && accounts.some(a => a.id === id))
170 await setView($, v => {
171 const nextReadings: Record<string, Reading> = {}
172 const nextHealth: Record<string, Health> = {}
173 const nextHolders: Record<string, Holder> = {}
174 for (const a of accounts) {
175 const mine = v.readings[a.id]
176 const theirs = readings[a.id]
177 const reading = mine !== undefined && (theirs === undefined || mine.at >= theirs.at) ? mine : theirs
178 if (reading !== undefined) nextReadings[a.id] = reading
179 const own = v.health[a.id]
180 const h = signingIn === a.id ? own : (health[a.id] ?? own)
181 if (h !== undefined) nextHealth[a.id] = h
182 const holder = holders[a.id] ?? v.holders[a.id]
183 if (holder !== undefined) nextHolders[a.id] = holder
184 }
185 return { ...v, accounts, readings: nextReadings, health: nextHealth, holders: nextHolders, footer, rotateTo, chromeAccountId, chromeAccountIds }
186 })
187}
188
189/** Changes the footer's look for every session. */
190async function setFooter($: Host, change: Partial<FooterStyle>): Promise<void> {
191 const footer = { ...(await getView($)).footer, ...change }
192 await $.store.set('footer', footer)
193 await setView($, v => ({ ...v, footer }))
194}
195
196/** Changes which login the rotation moves to, for every session. */
197async function setRotateTo($: Host, rotateTo: RotateTo): Promise<void> {
198 await $.store.set('rotate-to', rotateTo)
199 await setView($, v => ({ ...v, rotateTo }))
200}
201
202/** Names the account the Chrome extension is signed in to, for every session; none forgets it. */
203async function setChromeAccount($: Host, id: string | undefined): Promise<void> {
204 if (id === undefined) await $.store.delete('chrome-account')
205 else await $.store.set('chrome-account', id)
206 await setView($, v => ({ ...v, chromeAccountId: id }))
207}
208
209/** A Chrome extension answered as `id`, or none did, or the account is gone: the Chrome box lists it, or not, for every session. */
210async function noteChromeAccount($: Host, id: string, isSeen: boolean): Promise<void> {
211 const stored = await $.store.get('chrome-accounts')
212 const before = Array.isArray(stored) ? stored.filter((x): x is string => typeof x === 'string') : []
213 const ids = isSeen ? [...new Set([...before, id])] : before.filter(x => x !== id)
214 if (ids.length !== before.length) await $.store.set('chrome-accounts', ids)
215 await setView($, v => ({ ...v, chromeAccountIds: ids }))
216}
217
218// ---------------------------------------------------------------- host
219
220type Stored = { state: 'present'; credential: Credential | undefined } | { state: 'absent' } | { state: 'unreadable'; code: number }
221
222/** A slot's stored login, from the keychain on macOS or its file elsewhere (Linux); the secret stays in this module. */
223async function readStored($: Host, slot: string): Promise<Stored> {
224 return (await $.fs.exists(MACOS_MARKER)) ? readKeychain($, slot) : readCredentialsFile($, slot)
225}
226
227async function readKeychain($: Host, slot: string): Promise<Stored> {
228 const user = keychainUser(await $.env.get('USER'))
229 const argv = ['security', 'find-generic-password', '-a', user, '-w', '-s', await keychainItem(slot)]
230 const { exitCode, stdout } = await $.process.run(argv, { timeoutMs: 10_000 })
231 if (exitCode === 44) return { state: 'absent' }
232 if (exitCode !== 0) return { state: 'unreadable', code: exitCode }
233 return { state: 'present', credential: credentialFrom(stdout.trim()) }
234}
235
236/**
237 * A file that cannot be read holds no login, as Claude Code counts it: a
238 * missing or locked file, and one caught mid-write (Claude Code renames a new
239 * one into place, rewriting it in place only where that fails).
240 */
241async function readCredentialsFile($: Host, slot: string): Promise<Stored> {
242 const path = credentialsFile(slot, await $.env.get('HOME'))
243 const text = path === undefined ? undefined : await $.fs.read(path).catch(() => undefined)
244 return text === undefined ? { state: 'absent' } : { state: 'present', credential: credentialFrom(text) }
245}
246
247type UsageAnswer = { kind: 'ok'; body: unknown } | { kind: 'rejected' } | { kind: 'failed'; status: number }
248
249const oauthHeaders = (accessToken: string) => ({
250 Authorization: `Bearer ${accessToken}`,
251 'anthropic-beta': 'oauth-2025-04-20',
252 'Content-Type': 'application/json',
253})
254
255/** The usage of the login a token belongs to, as `/usage` reads it. */
256async function fetchUsage($: Host, accessToken: string): Promise<UsageAnswer> {
257 const res = await $.http.fetch(USAGE_URL, { headers: oauthHeaders(accessToken) })
258 if (res.status === 401 || res.status === 403) return { kind: 'rejected' }
259 if (!res.ok) return { kind: 'failed', status: res.status }
260 try {
261 return { kind: 'ok', body: JSON.parse(res.text) }
262 } catch {
263 // A 2xx that is not JSON counts as a failed call; the next check asks again.
264 return { kind: 'failed', status: res.status }
265 }
266}
267
268/** Who a token signs in, as Claude Code asks at a sign-in: email, organization and plan; undefined when the call fails. */
269async function fetchIdentity($: Host, accessToken: string): Promise<Identity | undefined> {
270 const res = await $.http.fetch(PROFILE_URL, { headers: oauthHeaders(accessToken) })
271 if (!res.ok) return undefined
272 try {
273 return identityFromProfile(JSON.parse(res.text))
274 } catch {
275 // A body that is not JSON says nothing of who; the next check asks again.
276 return undefined
277 }
278}
279
280/** Who a slot is signed in as: email, organization and plan. */
281async function signedInAs($: Host, slot: string): Promise<Identity | undefined> {
282 const { exitCode, stdout } = await $.process.run(['claude', 'auth', 'status', '--json'], {
283 env: slotEnv(slot),
284 timeoutMs: 20_000,
285 })
286 return exitCode === 0 ? identityFromStatus(stdout) : undefined
287}
288
289/** Points this session's requests, and every child it starts after, at a slot's login. */
290async function useSlot($: Host, slot: string): Promise<void> {
291 if (slot === '') await $.env.set('CLAUDE_SECURESTORAGE_CONFIG_DIR', undefined)
292 else await $.env.set('CLAUDE_SECURESTORAGE_CONFIG_DIR', slot)
293}
294
295/**
296 * Claude Code's security policy refuses switching in this session: says so
297 * once, as a toast and a notification, and the pane says so while it lasts.
298 * False when it was said already.
299 */
300async function blocked($: Host): Promise<boolean> {
301 const view = await getView($)
302 if (view.isSwitchBlocked) return false
303 await setView($, v => ({ ...v, isSwitchBlocked: true }))
304 const text = blockedText(isOnNormalLogin(view))
305 $.ui.toast(text, { timeoutMs: 15_000 })
306 await $.ui.notify(text, { title: TITLE })
307 return true
308}
309
310/**
311 * Sets the slot already in use, which changes nothing: the policy that refuses
312 * a switch refuses this too, so a session that cannot switch says so at its start.
313 */
314async function checkSwitching($: Host, slot: string): Promise<void> {
315 try {
316 await useSlot($, slot)
317 } catch (error) {
318 if (isPolicyRefusal(error)) await blocked($)
319 else await debug($, `switch check failed: ${String(error)}`)
320 }
321}
322
323// ---------------------------------------------------------------- checks and switching
324
325async function announceLockout($: Host, account: Account, why: string): Promise<void> {
326 const text = `Claude account ${label(account)} needs a sign-in (${why}). Click ⚠${account.id} under the prompt.`
327 $.ui.toast(text, { timeoutMs: 8000 })
328 await $.ui.notify(text, { title: TITLE })
329}
330
331/**
332 * Who a login's sign-in belongs to: as answered for its token before, else
333 * asked while the token is live. A /login in a session on a login signs in
334 * there, and a new sign-in brings a new token, so it is asked about again.
335 */
336async function holderOf($: Host, account: Account, credential: Credential, isLive: boolean): Promise<Holder | undefined> {
337 const token = await fingerprint(credential.refreshToken ?? credential.accessToken)
338 const known = (await getView($)).holders[account.id]
339 if (known?.token === token) return known
340 if (!isLive) return undefined
341 const who = await fetchIdentity($, credential.accessToken)
342 if (who?.email === undefined) return undefined
343 const holder = { token, who: { ...who, email: who.email, ...(credential.plan === undefined ? {} : { plan: credential.plan }) } }
344 await saveHolder($, account.id, holder)
345 return holder
346}
347
348/**
349 * A login's sign-in belongs to `who`. Another login on the list: this one
350 * holds that one's sign-in, answered so it asks for its own again. Else the
351 * login is who signed in, its name and plan kept current, and told when that
352 * is another account than before: a /login in a session on it did that.
353 */
354async function followSignIn($: Host, account: Account, who: Identity): Promise<Account | undefined> {
355 const accounts = await loadAccounts($)
356 const own = accounts.find(a => a.id === account.id)
357 if (own === undefined) return undefined
358 const isSame = own.email === undefined || isLoginOf(own, who)
359 const twin = isSame ? undefined : accounts.find(a => a.id !== own.id && isLoginOf(a, who))
360 if (twin !== undefined) return twin
361 const followed = { ...own, ...who }
362 if (followed.email !== own.email || followed.orgId !== own.orgId || followed.orgName !== own.orgName || followed.plan !== own.plan) {
363 await saveAccounts($, accounts.map(a => (a.id === own.id ? followed : a)))
364 }
365 if (!isSame) {
366 const name = `${followed.email}${followed.orgName ? ` · ${followed.orgName}` : ''}`
367 tell(
368 $,
369 own.slot === ''
370 ? `Claude Code's login, account ${own.id}, is ${name} now: new sessions start on it.`
371 : `Claude account ${own.id} is ${name} now: a /login in a session on account ${own.id} signs in there, not Claude Code's login.`,
372 )
373 }
374 return undefined
375}
376
377/**
378 * Re-reads one login's stored sign-in: who it belongs to and, while its token
379 * is live, its usage. One that is another login's on the list leaves this
380 * login needing its own, its usage that other's.
381 */
382async function checkAccount($: Host, account: Account): Promise<void> {
383 const now = await $.clock.now()
384 if (signingIn === account.id) return
385 const stored = await readStored($, account.slot)
386 if (stored.state === 'unreadable') {
387 tell($, `Could not read Claude account ${account.id} from the keychain (exit ${stored.code}); is it locked?`)
388 return
389 }
390 const credential = stored.state === 'present' ? stored.credential : undefined
391 let health = healthOf(credential, now)
392 if (health.kind === 'ok' && credential !== undefined) {
393 const isLive = credential.expiresAt > now + 60_000
394 const holder = await holderOf($, account, credential, isLive)
395 const twin = holder === undefined ? undefined : await followSignIn($, account, holder.who)
396 if (twin !== undefined) health = { kind: 'login-needed', why: `signed in as account ${twin.id} now` }
397 else if (isLive) {
398 const usage = await fetchUsage($, credential.accessToken)
399 if (usage.kind === 'rejected') health = { kind: 'login-needed', why: 'sign-in rejected' }
400 if (usage.kind === 'failed') await debug($, `usage for account ${account.id}: HTTP ${usage.status}`)
401 if (usage.kind === 'ok') {
402 const reading = readingFromUsage(usage.body, now)
403 if (reading !== undefined) await saveReading($, account.id, reading)
404 }
405 }
406 }
407 const before = await saveHealth($, account.id, health)
408 if (health.kind === 'login-needed' && before?.kind !== 'login-needed') {
409 await announceLockout($, account, health.why)
410 }
411}
412
413async function checkAll($: Host): Promise<void> {
414 for (const account of (await getView($)).accounts) {
415 try {
416 await checkAccount($, account)
417 } catch (error) {
418 await debug($, `checking account ${account.id} failed: ${String(error)}`)
419 }
420 }
421 await maybeRotate($)
422}
423
424/** Why the login in use is left, counted the way the footer shows it: room left, or what is used. */
425function whyLeave(view: View, now: number): string {
426 if (view.health[view.activeId]?.kind === 'login-needed') return `account ${view.activeId} needs a sign-in`
427 const r = view.readings[view.activeId]
428 const five = windowPct(r?.fiveHour, now) ?? 0
429 const [window, used] = five >= LEAVE_FIVE_HOUR ? ['5-hour window', five] : ['week', windowPct(r?.sevenDay, now) ?? 0]
430 return view.footer.fill === 'left'
431 ? `account ${view.activeId} has ${Math.round(100 - used)}% of its ${window} left`
432 : `account ${view.activeId} has used ${Math.round(used)}% of its ${window}`
433}
434
435/**
436 * Once the active login is spent or locked out, moves to the one the pane's
437 * Rotation setting picks; never while it is off, Claude Code's policy refuses
438 * it, or Connect holds the session where it is.
439 */
440async function maybeRotate($: Host): Promise<boolean> {
441 const now = await $.clock.now()
442 const view = await getView($)
443 if (isConnectingChrome || view.rotateTo === 'off' || view.isSwitchBlocked || view.pending !== undefined || !shouldLeave(view, now)) return false
444 // With none to move to, the band above the prompt says when the next login frees up.
445 const target = pickTarget({ ...view, accounts: view.accounts.filter(a => !untaken.has(a.id)) }, now)
446 return target === undefined ? false : switchTo($, target, whyLeave(view, now))
447}
448
449/** The login in use, when its token refreshes too soon for the refresh guard to let the session leave it for `target`. */
450async function refreshingSoon($: Host, view: View, target: Account, now: number): Promise<Account | undefined> {
451 const active = view.accounts.find(a => a.id === view.activeId)
452 if (active === undefined || active.id === target.id) return undefined
453 const stored = await readStored($, active.slot)
454 const credential = stored.state === 'present' ? stored.credential : undefined
455 const isSoon = credential !== undefined && credential.expiresAt > now && credential.expiresAt - now < REFRESH_GUARD_MS
456 return isSoon ? active : undefined
457}
458
459/** Points this session at `target`; false while the refresh guard holds it back, or Claude Code's policy refuses it. Quiet: no toast. */
460async function switchTo($: Host, target: Account, why: string, isQuiet = false): Promise<boolean> {
461 const active = await refreshingSoon($, await getView($), target, await $.clock.now())
462 if (active !== undefined) {
463 if (held === undefined) {
464 tell($, `Switching to Claude account ${target.id} in a few minutes, once account ${active.id}'s token has refreshed.`)
465 const retry = () => {
466 if (held !== undefined) void switchTo($, held.target, held.why)
467 }
468 held = { target, why, timer: $.clock.every(60_000, retry) }
469 } else held = { ...held, target, why }
470 return false
471 }
472 held?.timer.cancel()
473 held = undefined
474 await keepChrome($)
475 try {
476 await useSlot($, target.slot)
477 } catch (error) {
478 if (!isPolicyRefusal(error)) throw error
479 // A press of Use now or Rotate now gets an answer, even once the notice has shown.
480 if (!(await blocked($))) tell($, blockedText(isOnNormalLogin(await getView($))))
481 return false
482 }
483 const now = await $.clock.now()
484 movedAt = now
485 await setView($, v => ({
486 ...v,
487 activeId: target.id,
488 pending: { id: target.id, from: v.activeId, since: now },
489 removing: undefined,
490 }))
491 if (!isQuiet) $.ui.toast(`Switched to Claude account ${label(target)}: ${why}.`, { timeoutMs: 6000 })
492 return true
493}
494
495/**
496 * After a switch: which login answered the latest response? The new one
497 * (confirmed), or too soon to say. Only a response still answered by the old
498 * login minutes later is reported: an idle session has no new response to tell.
499 * Then the session is pointed back at the old login, and the footer and pane
500 * mark it in use again, as it is the one spending.
501 */
502async function settlePending($: Host, isResponse: boolean): Promise<void> {
503 const { pending, accounts } = await getView($)
504 if (pending === undefined) return
505 const now = await $.clock.now()
506 if (now - pending.since < SETTLE_MS) return
507 const reading = readingFromLimits((await $.session.usage()).rateLimits, now)
508 const target = accounts.find(a => a.id === pending.id)
509 if (target !== undefined) await checkAccount($, target)
510 if (sameUsage(reading, (await getView($)).readings[pending.id], now)) {
511 untaken.delete(pending.id)
512 await setView($, v => ({ ...v, pending: undefined }))
513 } else if (isResponse && now - pending.since > CONFIRM_GIVE_UP_MS) {
514 const from = accounts.find(a => a.id === pending.from)
515 if (from !== undefined) await checkAccount($, from)
516 if (from === undefined || !sameUsage(reading, (await getView($)).readings[from.id], now)) {
517 await setView($, v => ({ ...v, pending: undefined }))
518 tell($, `The switch to Claude account ${pending.id} has not shown in responses.`)
519 return
520 }
521 untaken.add(pending.id)
522 try {
523 await useSlot($, from.slot)
524 movedAt = now
525 } catch (error) {
526 await debug($, `switch back failed: ${String(error)}`)
527 }
528 await setView($, v => ({ ...v, activeId: from.id, pending: undefined }))
529 tell(
530 $,
531 `The switch to Claude account ${pending.id} did not take: responses still use account ${label(from)}, so it shows in use again. ` +
532 `The rotation leaves account ${pending.id} be in this session; Use now tries it again.`,
533 )
534 }
535}
536
537/** A response's own usage: the active login's, unless a switch is still settling. */
538async function onMeasure($: Host, limits: readonly SessionRateLimit[]): Promise<void> {
539 const view = await getView($)
540 if (view.pending !== undefined) {
541 await settlePending($, true)
542 return
543 }
544 const reading = readingFromLimits(limits, await $.clock.now())
545 if (reading === undefined) return
546 await saveReading($, view.activeId, reading)
547 await maybeRotate($)
548}
549
550/** A turn that died on a usage limit or a rejected sign-in: switch, then carry on. */
551async function onStopFailure($: Host, error: string): Promise<void> {
552 if (error !== 'rate_limit' && error !== 'authentication_failed') return
553 const view = await getView($)
554 const active = view.accounts.find(a => a.id === view.activeId)
555 if (active === undefined) return
556 if (error === 'authentication_failed') {
557 const before = await saveHealth($, active.id, { kind: 'login-needed', why: 'sign-in rejected' })
558 if (before?.kind !== 'login-needed') await announceLockout($, active, 'sign-in rejected')
559 } else {
560 await checkAccount($, active)
561 const now = await $.clock.now()
562 const after = await getView($)
563 if (!shouldLeave(after, now)) {
564 // The limit was hit before the usage call shows it: count the 5-hour window as full.
565 const r = after.readings[active.id]
566 const resetsAt = r?.fiveHour?.resetsAt
567 await saveReading($, active.id, { ...r, fiveHour: { pct: 100, ...(resetsAt ? { resetsAt } : {}) }, at: now })
568 }
569 }
570 await setView($, v => ({ ...v, pending: undefined }))
571 if (await maybeRotate($)) {
572 $.clock.after(SETTLE_MS, () => void $.prompt.submit({ text: CONTINUE }))
573 } else if (isConnectingChrome) isCutByVisit = true
574}
575
576// ---------------------------------------------------------------- Claude in Chrome
577// The Chrome extension answers only connections made as the claude.ai account
578// it is signed in to. Claude in Chrome connects at its first call, as the login
579// the session's requests use then, and keeps that until it reconnects. So
580// Connect moves the session to the extension's account and connects there: as
581// the session opens, while it can still move, and when a browser call finds no
582// browser. The connection stays as the rotation moves the session on.
583
584type ChromeAnswer = 'paired' | 'unpaired' | 'failed' | 'absent'
585
586/** Claude was held back from the browser, or found none: once Claude in Chrome connects, it is told to carry on. */
587let isChromeAwaited = false
588/** Connect found no browser as the extension's account: until one answers, a browser call that finds none asks the person instead. */
589let hasChromeMissed = false
590/** The mod's own call to Claude in Chrome is under way: Connect does not hold it back. */
591let isAskingChrome = false
592/** A turn hit a usage limit while Connect held the session on the extension's account: it carries on once the session is back. */
593let isCutByVisit = false
594
595/**
596 * Asks Claude in Chrome which browsers answer, connecting it if this session
597 * has not yet: 'failed' when it could not tell (no connection, or no answer in
598 * time), 'absent' in a session without Claude in Chrome.
599 */
600async function askChrome($: Host): Promise<ChromeAnswer> {
601 let answer: McpToolResult | undefined
602 isAskingChrome = true
603 try {
604 const late = $.clock.sleep(CHROME_WAIT_MS).then(() => undefined)
605 answer = await Promise.race([$.mcp.call(CHROME_SERVER, 'list_connected_browsers', {}), late])
606 } catch (error) {
607 // No Claude in Chrome tools in this session, or a hook refused the call.
608 await debug($, `Claude in Chrome not reached: ${String(error)}`)
609 return 'absent'
610 } finally {
611 isAskingChrome = false
612 }
613 if (answer === undefined || answer.isError) return 'failed'
614 const browsers = browsersFrom(answer.content.map(block => block.text ?? '').join(''))
615 return browsers === undefined ? 'failed' : browsers > 0 ? 'paired' : 'unpaired'
616}
617
618/** With no account named for the Chrome extension yet, the one a browser answered as is it, for every session. */
619async function learnChrome($: Host, account: Account): Promise<void> {
620 if ((await getView($)).chromeAccountId !== undefined) return
621 await setChromeAccount($, account.id)
622 tell($, `Claude in Chrome connects as Claude account ${label(account)}: your Chrome extension is signed in to it.`)
623}
624
625/**
626 * What an answer tells, Claude in Chrome having connected as `as`: whether the
627 * session has it, how its connection stands, whether the Chrome box lists the
628 * account, and, a browser answering, the extension's account. A guess at
629 * Claude Code's login that finds none is kept, so it is not tried again.
630 */
631async function noteChrome($: Host, as: Account, answer: ChromeAnswer): Promise<void> {
632 if (answer === 'absent' || answer === 'failed') {
633 await setView($, v => ({ ...v, hasChrome: answer === 'failed' }))
634 return
635 }
636 const isPaired = answer === 'paired'
637 await setView($, v => ({
638 ...v,
639 hasChrome: true,
640 chrome: { as: as.id, isPaired, ...(!isPaired && v.chrome?.hasFailed ? { hasFailed: true } : {}) },
641 }))
642 await noteChromeAccount($, as.id, isPaired)
643 if (isPaired) await learnChrome($, as)
644 else if ((await getView($)).chromeAccountId === undefined && as.slot === '') await $.store.set('chrome-miss', as.id)
645}
646
647/**
648 * Before the session moves off the login it is on: where that is the account
649 * the Chrome extension is signed in to (or, none named yet, Claude Code's
650 * login, where it most often is), connects Claude in Chrome there first, once a
651 * session. The connection keeps that account as the session moves on.
652 */
653async function keepChrome($: Host): Promise<void> {
654 const view = await getView($)
655 if (view.chrome !== undefined || view.hasChrome === false || isConnectingChrome) return
656 // Until a switch lands, the connection could be made as either login.
657 if (movedAt !== undefined && (await $.clock.now()) - movedAt < SETTLE_MS) return
658 const active = view.accounts.find(a => a.id === view.activeId)
659 if (active === undefined) return
660 const isGuess = view.chromeAccountId === undefined && active.slot === '' && (await $.store.get('chrome-miss')) !== active.id
661 if (view.chromeAccountId !== active.id && !isGuess) return
662 await noteChrome($, active, await askChrome($))
663}
664
665/**
666 * Whether the session connects Claude in Chrome as it opens: an account is
667 * named for the extension, signed in. Whatever usage it has left: connecting
668 * uses its sign-in, not its usage. Later, a session Claude Code stops from
669 * switching couldn't go there.
670 */
671function shouldConnectAtOpen(view: View): boolean {
672 const target = view.accounts.find(a => a.id === view.chromeAccountId)
673 if (target === undefined || !canConnectChrome(view)) return false
674 const health = view.health[target.id]?.kind
675 return target.id === view.activeId || (health !== 'login-needed' && health !== 'logging-in')
676}
677
678/**
679 * Connect: visits the account the Chrome extension is signed in to, or one
680 * tried for it, as Claude Code connects Claude in Chrome with the sign-in the
681 * session uses: moves the session there, has Claude in Chrome connect once the
682 * move lands (again, where it connected before), asks which browsers answer,
683 * and moves back. The connection stays. Then Claude carries on: held back from
684 * the browser, or cut by a usage limit on the way. Quiet as the session opens:
685 * the pane says how it went. Answers what the browsers did, where it asked them.
686 */
687function connectChrome($: Host, isQuiet = false, tryId?: string): Promise<ChromeAnswer | undefined> {
688 if (isConnectingChrome) return Promise.resolve(undefined)
689 isConnectingChrome = true
690 return (async () => {
691 let done: { target: Account; answer: ChromeAnswer; isVisit: boolean } | undefined
692 try {
693 done = await connectingChrome($, isQuiet, tryId)
694 } finally {
695 isConnectingChrome = false
696 await setView($, v => ({ ...v, chromeConnecting: undefined }))
697 }
698 const isMoved = (await maybeRotate($)) || done?.isVisit === true
699 const isConnected = done?.answer === 'paired' && isChromeAwaited
700 const text = isConnected && done !== undefined ? `Claude in Chrome is connected as Claude account ${label(done.target)}. Continue where you left off.` : isCutByVisit ? CONTINUE : undefined
701 if (isConnected) isChromeAwaited = false
702 isCutByVisit = false
703 if (text !== undefined) {
704 // Once the move back lands: until then the turn's requests may go out as the extension's account.
705 if (isMoved) $.clock.after(SETTLE_MS, () => void $.prompt.submit({ text }))
706 else void $.prompt.submit({ text })
707 }
708 return done?.answer
709 })()
710}
711
712/**
713 * Use for Chrome, on an account a browser answered as, or Try to connect, on
714 * another: Claude in Chrome connects as the account, which once a browser
715 * answers there is the extension's, in this session now and in every session
716 * from now on. Where none answers, the Chrome box lists it no more, and Claude
717 * in Chrome connects again as the account picked before.
718 */
719async function tryChromeAccount($: Host, id: string): Promise<void> {
720 const answer = await connectChrome($, false, id)
721 const picked = (await getView($)).chromeAccountId
722 if (answer === 'paired') await setView($, v => ({ ...v, isChromeOthersShown: false }))
723 else if ((answer === 'unpaired' || answer === 'failed') && picked !== undefined && picked !== id) await connectChrome($)
724}
725
726async function connectingChrome(
727 $: Host,
728 isQuiet: boolean,
729 tryId: string | undefined,
730): Promise<{ target: Account; answer: ChromeAnswer; isVisit: boolean } | undefined> {
731 const view = await getView($)
732 const target = view.accounts.find(a => a.id === (tryId ?? view.chromeAccountId))
733 const from = view.accounts.find(a => a.id === view.activeId)
734 if (target === undefined || from === undefined || !canConnectChrome({ ...view, chromeAccountId: target.id })) return undefined
735 // Tried for the extension: the account picked before stays its own until a browser answers as this one.
736 const isTrial = target.id !== view.chromeAccountId
737 const active = await refreshingSoon($, view, target, await $.clock.now())
738 if (active !== undefined) {
739 if (!isQuiet) tell($, `Chrome can connect as account ${target.id} once account ${active.id}'s token has refreshed: try again in a few minutes.`)
740 return undefined
741 }
742 await setView($, v => ({ ...v, chromeConnecting: target.id }))
743 const isVisit = from.id !== target.id
744 if (isVisit && !(await switchTo($, target, 'Claude in Chrome connects as it', true))) return undefined
745 const wait = movedAt === undefined ? 0 : movedAt + SETTLE_MS - (await $.clock.now())
746 if (wait > 0) await $.clock.sleep(wait)
747 // A connection made before, as whichever login the session was on then, is made again as this one.
748 const before = await getView($)
749 if (before.chrome !== undefined || before.hasChrome === true) {
750 try {
751 await $.command.run({ command: 'mcp', args: `reconnect ${CHROME_SERVER}` })
752 } catch (error) {
753 await debug($, `/mcp reconnect ${CHROME_SERVER} failed: ${String(error)}`)
754 }
755 }
756 const answer = await askChrome($)
757 if (isTrial && answer === 'paired') await setChromeAccount($, target.id)
758 await noteChrome($, target, answer)
759 // Whether a browser answers as the extension's account: a trial that found none didn't ask there.
760 if (!isTrial || answer === 'paired') hasChromeMissed = answer === 'unpaired'
761 if (answer === 'paired') {
762 // A browser answering as the account shows the switch took: the rotation need not wait for a response to say so.
763 untaken.delete(target.id)
764 await setView($, v => (v.pending?.id === target.id ? { ...v, pending: undefined } : v))
765 }
766 if (isVisit) await leaveVisit($, from)
767 if (!isQuiet && answer === 'paired') tell($, `Claude in Chrome is connected as Claude account ${label(target)}.`)
768 if (!isQuiet && answer === 'unpaired') {
769 const back = isTrial ? view.accounts.find(a => a.id === view.chromeAccountId) : undefined
770 tell(
771 $,
772 `No Chrome extension answers as Claude account ${label(target)}. Open Chrome and check its Claude extension is signed in with that email; if it is, restart Chrome${isTrial ? ' and try again' : ''}.` +
773 (back === undefined ? '' : ` Claude in Chrome goes back to account ${label(back)}.`),
774 )
775 }
776 return { target, answer, isVisit }
777}
778
779/**
780 * After Connect's visit: back to the login the session was on, while it can
781 * serve, or with the rotation off; else on to the one the rotation picks. The
782 * extension's account's usage is not the session's to spend.
783 */
784async function leaveVisit($: Host, from: Account): Promise<void> {
785 const now = await $.clock.now()
786 const view = await getView($)
787 const health = view.health[from.id]?.kind
788 const canServe = health !== 'login-needed' && health !== 'logging-in' && !shouldLeave({ ...view, activeId: from.id }, now)
789 if (view.rotateTo === 'off' || canServe) {
790 await switchTo($, from, 'back from connecting Claude in Chrome', true)
791 return
792 }
793 const target = pickTarget({ ...view, accounts: view.accounts.filter(a => !untaken.has(a.id)) }, now)
794 if (target !== undefined) await switchTo($, target, whyLeave({ ...view, activeId: from.id }, now))
795}
796
797/**
798 * After a call to one of Claude in Chrome's tools. One answered marks the
799 * connection paired and, as the session's first, names the extension's
800 * account where none is. One that found no browser marks it so, for the band,
801 * and returns what Claude reads in place of Claude Code's advice to /login:
802 * that the mod connects it now, or what to ask the person.
803 */
804async function onBrowserCall($: Host, isUnanswered: boolean): Promise<string | undefined> {
805 const view = await getView($)
806 const isSure = movedAt === undefined || (await $.clock.now()) - movedAt >= SETTLE_MS
807 const as = view.chrome?.as ?? (isSure ? view.activeId : undefined)
808 const chrome = { ...(as === undefined ? {} : { as }), isPaired: !isUnanswered, ...(isUnanswered ? { hasFailed: true } : {}) }
809 const after = await setView($, v => ({ ...v, hasChrome: true, chrome }))
810 if (!isUnanswered) {
811 hasChromeMissed = false
812 if (as !== undefined) await noteChromeAccount($, as, true)
813 const active = view.accounts.find(a => a.id === view.activeId)
814 if (view.chrome === undefined && isSure && active !== undefined) await learnChrome($, active)
815 return undefined
816 }
817 if (after.chromeAccountId === undefined) {
818 isChromeAwaited = true
819 return chromeNote(after, 'unset')
820 }
821 // Where Connect can't run: connected as the extension's account already, so Chrome may be closed, or the session can't move there.
822 if (!canConnectChrome(after)) return chromeNote(after, after.chrome?.as === after.chromeAccountId ? 'no-browser' : 'blocked')
823 isChromeAwaited = true
824 if (hasChromeMissed) return chromeNote(after, 'no-browser')
825 // Once this hook is done: the turn waits on it, and Connect's /mcp reconnect waits on the turn.
826 $.clock.after(0, () => void connectChrome($).catch(error => debug($, `Chrome connect failed: ${String(error)}`)))
827 return chromeNote(after, 'connecting')
828}
829
830// ---------------------------------------------------------------- sign-in
831
832/** Signs one login in through the browser; its slot gets the new credential. */
833async function signIn($: Host, account: Account): Promise<void> {
834 const since = await $.clock.now()
835 await saveHealth($, account.id, { kind: 'logging-in', since })
836 const argv = ['claude', 'auth', 'login', '--claudeai', ...(account.email ? ['--email', account.email] : [])]
837 // The child opens the browser itself. The link it prints is the paste-a-code
838 // flow, which a background child cannot finish, so stdout goes unread.
839 const child = $.process.spawn({ argv, env: slotEnv(account.slot) })
840 running = child
841 signingIn = account.id
842 let errors = ''
843 try {
844 for await (const { stream, text } of child) {
845 if (stream === 'stderr') errors += text
846 }
847 } catch (error) {
848 errors += String(error)
849 } finally {
850 running = undefined
851 signingIn = undefined
852 }
853 const code = await child.result.then(r => r.code, () => null)
854 await saveHealth($, account.id, { kind: 'login-needed', why: 'sign-in not finished' })
855 if (code !== 0) {
856 tell($, `Sign-in for Claude account ${account.id} did not finish${errors.trim() ? `: ${errors.trim().slice(0, 160)}` : '.'}`)
857 return
858 }
859 await adoptSignIn($, account)
860}
861
862/** After a browser sign-in: who signed in, and is it a login already on the list? */
863async function adoptSignIn($: Host, account: Account): Promise<void> {
864 const who = await signedInAs($, account.slot)
865 const accounts = await loadAccounts($)
866 const twin = who === undefined ? undefined : accounts.find(a => a.id !== account.id && sameLogin(a, who))
867 if (twin !== undefined) {
868 await saveHealth($, account.id, { kind: 'login-needed', why: `that was account ${label(twin)} again` })
869 tell(
870 $,
871 `Claude account ${account.id} signed in as account ${label(twin)}. Sign out of claude.ai in your browser (or pick another organization), then sign in again.`,
872 )
873 return
874 }
875 const updated = accounts.map(a => (a.id === account.id && who !== undefined ? { ...a, ...who } : a))
876 await saveAccounts($, updated)
877 await saveHealth($, account.id, { kind: 'ok' })
878 const fresh = updated.find(a => a.id === account.id) ?? account
879 await checkAccount($, fresh)
880 await maybeRotate($)
881}
882
883function queueSignIn(work: () => Promise<void>): Promise<void> {
884 signInQueue = signInQueue.then(work, work)
885 return signInQueue
886}
887
888/** Signs in, one after another, every login that needs it. */
889const signInAll = ($: Host) =>
890 queueSignIn(async () => {
891 const view = await getView($)
892 for (const account of view.accounts.filter(a => view.health[a.id]?.kind === 'login-needed')) {
893 await signIn($, account)
894 }
895 })
896
897const signInOne = ($: Host, id: string) =>
898 queueSignIn(async () => {
899 const account = (await getView($)).accounts.find(a => a.id === id)
900 if (account !== undefined) await signIn($, account)
901 })
902
903/** Adds a login in a new slot under ~/.claude/accounts and signs it in. */
904async function addAccount($: Host): Promise<void> {
905 const accounts = await loadAccounts($)
906 const id = freeId(accounts)
907 const slot = `${(await $.env.get('HOME')) ?? ''}/.claude/accounts/${id}`
908 await $.fs.write(`${slot}/README`, `Claude account ${id}, kept by the account-rotator mod.\n`)
909 await saveAccounts($, [...accounts, { id, slot }])
910 await saveHealth($, id, { kind: 'login-needed', why: 'not signed in yet' })
911 await signInOne($, id)
912}
913
914/** The second press of Remove: signs the slot out, then drops it from the list. */
915async function removeAccount($: Host, id: string): Promise<void> {
916 const view = await getView($)
917 const account = view.accounts.find(a => a.id === id)
918 if (account === undefined || account.slot === '') return
919 if (view.activeId === id) {
920 const other = view.accounts.find(a => a.id !== id && view.health[a.id]?.kind === 'ok')
921 if (other === undefined || !(await switchTo($, other, `account ${id} is being removed`))) {
922 tell($, `Claude account ${id} is in use and no other account can take over yet; not removed.`)
923 return
924 }
925 }
926 await $.process.run(['claude', 'auth', 'logout'], { env: slotEnv(account.slot), timeoutMs: 20_000 })
927 await saveAccounts($, view.accounts.filter(a => a.id !== id))
928 if (view.chromeAccountId === id) await setChromeAccount($, undefined)
929 await noteChromeAccount($, id, false)
930 await $.store.delete(`reading:${id}`)
931 await $.store.delete(`health:${id}`)
932 await $.store.delete(`holder:${id}`)
933 await setView($, v => {
934 const readings = { ...v.readings }
935 const health = { ...v.health }
936 const holders = { ...v.holders }
937 delete readings[id]
938 delete health[id]
939 delete holders[id]
940 return { ...v, readings, health, holders, removing: undefined }
941 })
942}
943
944// ---------------------------------------------------------------- wiring
945
946/** The footer's one press: opens the pane, or closes it while it shows. */
947function togglePane($: Host): Promise<unknown> {
948 isPaneShown = !isPaneShown
949 return isPaneShown ? $.ui.open({ id: PANE, title: TITLE, columns: PANE_COLUMNS }) : $.ui.close({ id: PANE })
950}
951
952/** After a /login, which signs in the login this session is on: who it is now, and a move off it when that is another login's account. */
953async function checkActive($: Host): Promise<void> {
954 const view = await getView($)
955 const active = view.accounts.find(a => a.id === view.activeId)
956 if (active !== undefined) await checkAccount($, active)
957 await maybeRotate($)
958}
959
960/** Rotate now: moves to the login the pane's Rotation setting picks, as the rotation would once this one runs low; with it off, the most room. */
961async function rotate($: Host): Promise<void> {
962 const view = await getView($)
963 const target = pickTarget(view, await $.clock.now())
964 if (target === undefined) tell($, 'No other Claude account can take over right now.')
965 else await switchTo($, target, 'you pressed Rotate now')
966}
967
968/** Every press starts its work in the background: a sign-in outlives the press. */
969function actions($: Host): Actions {
970 const background = (work: Promise<unknown>) => {
971 work.catch(error => tell($, `Something went wrong: ${String(error)}`))
972 }
973 return {
974 togglePane: () => background(togglePane($)),
975 rotate: () => background(rotate($)),
976 signInAll: () => background(signInAll($)),
977 signInOne: id => background(signInOne($, id)),
978 cancelSignIn: () => background(Promise.resolve(running?.return({ code: null, signal: 'SIGTERM' }))),
979 add: () => background(addAccount($)),
980 use: id =>
981 background(
982 getView($).then(view => {
983 const account = view.accounts.find(a => a.id === id)
984 return account === undefined ? false : switchTo($, account, 'you picked it')
985 }),
986 ),
987 askRemove: id => background(setView($, v => ({ ...v, removing: id }))),
988 remove: id => background(removeAccount($, id)),
989 setFooter: change => background(setFooter($, change)),
990 setRotateTo: rotateTo => background(setRotateTo($, rotateTo)),
991 tryChromeAccount: id => background(tryChromeAccount($, id)),
992 toggleChromeOthers: () => background(setView($, v => ({ ...v, isChromeOthersShown: !v.isChromeOthersShown }))),
993 connectChrome: () => background(connectChrome($)),
994 setDemo: on => background(setView($, v => ({ ...v, demo: on }))),
995 }
996}
997
998/** First run makes the normal login number 1; then: which login this session uses, and Claude in Chrome connected as the extension's account. */
999async function boot($: Host, isInteractive: boolean): Promise<void> {
1000 // Terminal.app is the terminal that names itself so and draws block characters from its font.
1001 const hasFontBlocks = (await $.env.get('TERM_PROGRAM')) === 'Apple_Terminal'
1002 await setView($, v => ({ ...v, hasFontBlocks }))
1003 let accounts = await loadAccounts($)
1004 if (accounts.length === 0) {
1005 accounts = [{ id: '1', slot: '' }]
1006 await saveAccounts($, accounts)
1007 }
1008 const slot = (await $.env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR')) ?? ''
1009 let active = accounts.find(a => a.slot === slot)
1010 if (active === undefined) {
1011 // Started on a slot nobody registered (set by hand, or by another tool): adopt it.
1012 active = { id: freeId(accounts), slot }
1013 accounts = [...accounts, active]
1014 await saveAccounts($, accounts)
1015 }
1016 const activeId = active.id
1017 const sessionId = await $.session.id().catch(() => undefined)
1018 await mergeStore($)
1019 await setView($, v => ({ ...v, activeId, ...(sessionId === undefined ? {} : { sessionId }) }))
1020 await checkSwitching($, slot)
1021 // First, while the session can still move: the rotation waits for it.
1022 if (isInteractive && shouldConnectAtOpen(await getView($))) {
1023 void connectChrome($, true).catch(error => debug($, `Chrome connect failed: ${String(error)}`))
1024 }
1025 // A live sign-in names its login as it checks; one whose token has run out, from what `claude auth login` left in its folder.
1026 await checkAll($)
1027 for (const account of (await loadAccounts($)).filter(a => a.email === undefined || a.orgId === undefined)) {
1028 const who = await signedInAs($, account.slot)
1029 if (who === undefined) continue
1030 const latest = await loadAccounts($)
1031 await saveAccounts($, latest.map(a => (a.id === account.id ? { ...a, ...who } : a)))
1032 }
1033}
1034
1035export const register: Register = on => {
1036 on('session.start', async ($, e, next) => {
1037 const started = await next(e)
1038 void boot($, e.isInteractive).catch(error => debug($, `start failed: ${String(error)}`))
1039 void $.ui.panes().then(panes => {
1040 isPaneShown = panes.some(p => p.id === PANE && p.isShown)
1041 })
1042 $.clock.every(60_000, () => {
1043 void mergeStore($)
1044 .then(() => settlePending($, false))
1045 .then(() => maybeRotate($))
1046 .catch(error => debug($, `sync failed: ${String(error)}`))
1047 })
1048 $.clock.every(10 * 60_000, () => {
1049 void checkAll($).catch(error => debug($, `check failed: ${String(error)}`))
1050 })
1051 return started
1052 })
1053
1054 on('session.measure', async ($, e, next) => {
1055 if (e.changed.includes('rateLimits')) {
1056 void onMeasure($, e.rateLimits).catch(error => debug($, `measure failed: ${String(error)}`))
1057 }
1058 return next(e)
1059 })
1060
1061 on('classic.StopFailure', async ($, e, next) => {
1062 void onStopFailure($, e.error).catch(error => debug($, `stop failure handling failed: ${String(error)}`))
1063 return next(e)
1064 }).catch(($, e, next) => next(e))
1065
1066 // Typed at the prompt, /login answers once its sign-in is done; run mid-turn, at once, and the checks find it later.
1067 on('command.run', { command: 'login' }, async ($, e, next) => {
1068 const ran = await next(e)
1069 void checkActive($).catch(error => debug($, `check after /login failed: ${String(error)}`))
1070 return ran
1071 }).catch(($, e, next) => next(e))
1072
1073 // While Connect is under way a browser call would connect as the login being left: Claude waits, and is told when to carry on.
1074 on('tool.check', { tool: CHROME_TOOL }, async ($, e, next) => {
1075 if (!isConnectingChrome || isAskingChrome) return next(e)
1076 if (e.tool_use_id !== undefined) isChromeAwaited = true
1077 return { decision: 'deny' as const, reason: chromeNote(await getView($), 'held') }
1078 }).catch(($, e, next) => next(e))
1079
1080 // Claude Code's words for a browser call that found no browser send the person to /login, which here signs in the wrong account.
1081 on('tool.call', { tool: CHROME_TOOL }, async ($, e, next) => {
1082 const done = await next(e)
1083 if (done.deny !== undefined) return done
1084 const note = await onBrowserCall($, done.isError === true && isNoBrowser(done.text ?? '')).catch(async error => {
1085 await debug($, `browser call handling failed: ${String(error)}`)
1086 return undefined
1087 })
1088 return note === undefined ? done : { ...done, context: [...(done.context ?? []), note] }
1089 }).catch(($, e, next) => next(e))
1090
1091 on('ui.close', async ($, e, next) => {
1092 if (e.id === PANE) isPaneShown = false
1093 return next(e)
1094 })
1095
1096
1097 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
1098 const view = await getView($)
1099 if (view.accounts.length === 0) return next(e)
1100 return Footer($.ui.resolve(e), view, e.props.modes, await $.clock.now(), actions($))
1101 })
1102
1103 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1104 if (e.props.hasSurvey) return next(e)
1105 const view = await getView($)
1106 return Band($.ui.resolve(e), view, await $.clock.now(), actions($)) ?? next(e)
1107 })
1108
1109 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1110 const view = await getView($)
1111 return Pane($.ui.resolve(e), view, await $.clock.now(), actions($))
1112 })
1113}
1114hooks/model.ts 548 lines1import type { Account, Fill, FooterStyle, Glyphs, Health, Highlight, Reading, RotateTo, UsageWindow, View } from '../types'
2
3/** Leave a login once its 5-hour window is this full (percent). */
4export const LEAVE_FIVE_HOUR = 90
5/** Leave a login once its weekly window is this full (percent). */
6export const LEAVE_SEVEN_DAY = 95
7/** Warn this long before a login's refresh token runs out. */
8export const SIGN_IN_WARN_MS = 3 * 24 * 3600_000
9
10export const DEFAULT_FOOTER: FooterStyle = { session: 'braille', week: 'bars', sessionPercent: true, weekPercent: true, active: 'lines', fill: 'left' }
11
12export const DEFAULT_ROTATE_TO: RotateTo = 'reset'
13
14export const EMPTY_VIEW: View = {
15 accounts: [],
16 readings: {},
17 health: {},
18 holders: {},
19 activeId: '1',
20 footer: DEFAULT_FOOTER,
21 rotateTo: DEFAULT_ROTATE_TO,
22 hasFontBlocks: false,
23}
24
25export const GLYPHS: readonly Glyphs[] = ['bars', 'pie', 'braille', 'none']
26export const HIGHLIGHTS: readonly Highlight[] = ['lines', 'tile', 'dim']
27export const FILLS: readonly Fill[] = ['left', 'used']
28export const ROTATE_TOS: readonly RotateTo[] = ['reset', 'room', 'order', 'off']
29
30const isOneOf = <T extends string>(value: unknown, allowed: readonly T[]): value is T =>
31 typeof value === 'string' && (allowed as readonly string[]).includes(value)
32
33/** Which login the rotation moves to, as stored; unknown is the default's. */
34export function rotateToFrom(value: unknown): RotateTo {
35 return isOneOf(value, ROTATE_TOS) ? value : DEFAULT_ROTATE_TO
36}
37
38/** The footer's look as stored; any part missing or unknown is the default's. */
39export function footerStyleFrom(value: unknown): FooterStyle {
40 const v = typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {}
41 return {
42 session: isOneOf(v.session, GLYPHS) ? v.session : DEFAULT_FOOTER.session,
43 week: isOneOf(v.week, GLYPHS) ? v.week : DEFAULT_FOOTER.week,
44 sessionPercent: typeof v.sessionPercent === 'boolean' ? v.sessionPercent : DEFAULT_FOOTER.sessionPercent,
45 weekPercent: typeof v.weekPercent === 'boolean' ? v.weekPercent : DEFAULT_FOOTER.weekPercent,
46 active: isOneOf(v.active, HIGHLIGHTS) ? v.active : DEFAULT_FOOTER.active,
47 fill: isOneOf(v.fill, FILLS) ? v.fill : DEFAULT_FOOTER.fill,
48 }
49}
50
51/** A window's percent now: 0 once its reset time has passed. */
52export function windowPct(w: UsageWindow | undefined, now: number): number | undefined {
53 if (w === undefined) return undefined
54 if (w.resetsAt !== undefined && Date.parse(w.resetsAt) <= now) return 0
55 return w.pct
56}
57
58/**
59 * What a login can serve right now, percent of its 5-hour window: a week's
60 * percent is a far bigger budget, so the session decides until the week is
61 * spent, and then nothing is. Undefined before any 5-hour reading.
62 */
63export function availableNow(r: Reading | undefined, now: number): number | undefined {
64 const five = roomLeft(r?.fiveHour, now)
65 if (five === undefined) return undefined
66 return (windowPct(r?.sevenDay, now) ?? 0) >= LEAVE_SEVEN_DAY ? 0 : five
67}
68
69export function isSpent(r: Reading | undefined, now: number): boolean {
70 return (
71 (windowPct(r?.fiveHour, now) ?? 0) >= LEAVE_FIVE_HOUR ||
72 (windowPct(r?.sevenDay, now) ?? 0) >= LEAVE_SEVEN_DAY
73 )
74}
75
76export function shouldLeave(view: View, now: number): boolean {
77 return view.health[view.activeId]?.kind === 'login-needed' || isSpent(view.readings[view.activeId], now)
78}
79
80/** When a login's 5-hour window resets, epoch ms; Infinity while none is running. */
81function fiveHourReset(r: Reading | undefined, now: number): number {
82 const w = r?.fiveHour
83 if (w?.resetsAt === undefined || (windowPct(w, now) ?? 0) === 0) return Infinity
84 return Date.parse(w.resetsAt)
85}
86
87/**
88 * The signed-in login below both thresholds to move to, as `rotateTo` picks:
89 * the one that can serve the most right now (unread counts as fresh); the one
90 * whose 5-hour window resets soonest, so room about to refill is used first,
91 * the most room breaking ties; or the next in the list after the one in use.
92 * With the rotation off, Rotate now takes the one with the most room.
93 */
94export function pickTarget(view: View, now: number): Account | undefined {
95 const ready = view.accounts.filter(
96 a => a.id !== view.activeId && view.health[a.id]?.kind === 'ok' && !isSpent(view.readings[a.id], now),
97 )
98 const available = (a: Account) => availableNow(view.readings[a.id], now) ?? 100
99 const byRoom = (a: Account, b: Account) => available(b) - available(a)
100 switch (view.rotateTo) {
101 case 'room':
102 case 'off':
103 return ready.sort(byRoom)[0]
104 case 'reset': {
105 const reset = (a: Account) => fiveHourReset(view.readings[a.id], now)
106 return ready.sort((a, b) => (reset(a) === reset(b) ? byRoom(a, b) : reset(a) < reset(b) ? -1 : 1))[0]
107 }
108 case 'order': {
109 const at = view.accounts.findIndex(a => a.id === view.activeId)
110 const after = [...view.accounts.slice(at + 1), ...view.accounts.slice(0, at + 1)]
111 return after.find(a => ready.includes(a))
112 }
113 }
114}
115
116/** When the soonest spent window among all logins resets, epoch ms. */
117export function nextReset(view: View, now: number): number | undefined {
118 const times = view.accounts.flatMap(a => {
119 const r = view.readings[a.id]
120 return [r?.fiveHour, r?.sevenDay]
121 .filter((w): w is UsageWindow => w !== undefined && w.resetsAt !== undefined && (windowPct(w, now) ?? 0) > 0)
122 .map(w => Date.parse(w.resetsAt ?? ''))
123 })
124 return times.length === 0 ? undefined : Math.min(...times)
125}
126
127function windowFrom(value: unknown): UsageWindow | undefined {
128 if (typeof value !== 'object' || value === null) return undefined
129 const { utilization, resets_at } = value as { utilization?: unknown; resets_at?: unknown }
130 if (typeof utilization !== 'number') return undefined
131 return { pct: utilization, ...(typeof resets_at === 'string' ? { resetsAt: resets_at } : {}) }
132}
133
134/** A reading from the body of GET /api/oauth/usage. */
135export function readingFromUsage(body: unknown, now: number): Reading | undefined {
136 if (typeof body !== 'object' || body === null) return undefined
137 const { five_hour, seven_day } = body as { five_hour?: unknown; seven_day?: unknown }
138 const fiveHour = windowFrom(five_hour)
139 const sevenDay = windowFrom(seven_day)
140 if (fiveHour === undefined && sevenDay === undefined) return undefined
141 return { ...(fiveHour ? { fiveHour } : {}), ...(sevenDay ? { sevenDay } : {}), at: now }
142}
143
144/** A reading from the rate-limit windows the last response reported. */
145export function readingFromLimits(
146 limits: readonly { kind: string; percentUsed: number; resetsAt?: string }[],
147 now: number,
148): Reading | undefined {
149 const pick = (kind: string): UsageWindow | undefined => {
150 const w = limits.find(l => l.kind === kind)
151 return w && { pct: w.percentUsed, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) }
152 }
153 const fiveHour = pick('five_hour')
154 const sevenDay = pick('seven_day')
155 if (fiveHour === undefined && sevenDay === undefined) return undefined
156 return { ...(fiveHour ? { fiveHour } : {}), ...(sevenDay ? { sevenDay } : {}), at: now }
157}
158
159/** True when two readings agree within a few points on every shared window. */
160export function sameUsage(a: Reading | undefined, b: Reading | undefined, now: number): boolean {
161 if (a === undefined || b === undefined) return false
162 const pairs: [UsageWindow | undefined, UsageWindow | undefined][] = [
163 [a.fiveHour, b.fiveHour],
164 [a.sevenDay, b.sevenDay],
165 ]
166 const shared = pairs.filter(([x, y]) => x !== undefined && y !== undefined)
167 return (
168 shared.length > 0 &&
169 shared.every(([x, y]) => Math.abs((windowPct(x, now) ?? 0) - (windowPct(y, now) ?? 0)) <= 3)
170 )
171}
172
173/** The part of a stored login Claude Code keeps in the keychain (on Linux, a file) that matters here. */
174export type Credential = {
175 accessToken: string
176 expiresAt: number
177 refreshTokenExpiresAt?: number
178 /** A new sign-in brings a new one. */
179 refreshToken?: string
180 /** `subscriptionType`, the plan Claude Code reads from the sign-in: on a Team or Enterprise one it keeps plugins from switching. */
181 plan?: string
182}
183
184export function credentialFrom(text: string): Credential | undefined {
185 let parsed: unknown
186 try {
187 parsed = JSON.parse(text)
188 } catch {
189 // An entry that is not JSON is no usable login: the caller asks for a sign-in.
190 return undefined
191 }
192 const oauth = (parsed as { claudeAiOauth?: unknown } | null)?.claudeAiOauth
193 if (typeof oauth !== 'object' || oauth === null) return undefined
194 const { accessToken, expiresAt, refreshTokenExpiresAt, refreshToken, subscriptionType } = oauth as Record<string, unknown>
195 if (typeof accessToken !== 'string' || typeof expiresAt !== 'number') return undefined
196 return {
197 accessToken,
198 expiresAt,
199 ...(typeof refreshTokenExpiresAt === 'number' ? { refreshTokenExpiresAt } : {}),
200 ...(typeof refreshToken === 'string' ? { refreshToken } : {}),
201 ...(typeof subscriptionType === 'string' ? { plan: subscriptionType } : {}),
202 }
203}
204
205/** A login's health from its stored credential alone. */
206export function healthOf(cred: Credential | undefined, now: number): Health {
207 if (cred === undefined) return { kind: 'login-needed', why: 'not signed in' }
208 if (cred.refreshTokenExpiresAt !== undefined && cred.refreshTokenExpiresAt <= now) {
209 return { kind: 'login-needed', why: 'sign-in expired' }
210 }
211 return { kind: 'ok', ...(cred.refreshTokenExpiresAt ? { refreshExpiresAt: cred.refreshTokenExpiresAt } : {}) }
212}
213
214/** The percent a glyph or bar fills to and the footer prints: the room left, or what is used. */
215export function shown(fill: Fill, leftPct: number): number {
216 return fill === 'left' ? leftPct : 100 - leftPct
217}
218
219/** Percent of a window still free; undefined when the window has no reading. */
220export function roomLeft(w: UsageWindow | undefined, now: number): number | undefined {
221 const pct = windowPct(w, now)
222 return pct === undefined ? undefined : Math.round(100 - pct)
223}
224
225/**
226 * The color for a percent of room left: green with all of it, through yellow,
227 * to red with none (hue 120 down to 0); lighter while the pointer is over it.
228 */
229export function roomColor(leftPct: number, isLit = false): string {
230 const hue = Math.max(0, Math.min(100, leftPct)) * 1.2
231 const [s, l] = [0.75, isLit ? 0.72 : 0.55]
232 const a = s * Math.min(l, 1 - l)
233 const channel = (n: number) => {
234 const k = (n + hue / 30) % 12
235 const v = l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1))
236 return Math.round(v * 255).toString(16).padStart(2, '0')
237 }
238 return `#${channel(0)}${channel(8)}${channel(4)}`
239}
240
241const BARS = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']
242
243/** A vertical bar for a percentage, an eighth to full height. */
244export function bar(pct: number): string {
245 return BARS[Math.min(7, Math.max(0, Math.round((pct / 100) * 7)))] ?? '█'
246}
247
248const BRAILLE = ['⡀', '⣀', '⣄', '⣤', '⣦', '⣶', '⣷', '⣿']
249
250/** A braille cell filled from the bottom for a percentage, one dot to all eight. */
251export function braille(pct: number): string {
252 return BRAILLE[Math.min(7, Math.max(0, Math.round((pct / 100) * 7)))] ?? '⣿'
253}
254
255const PIES = ['○', '◔', '◑', '◕', '●']
256
257/** A pie for a percentage, empty to full in quarters; a dot when unknown. */
258export function pie(pct: number | undefined): string {
259 if (pct === undefined) return '·'
260 return PIES[Math.min(4, Math.max(0, Math.round(pct / 25)))] ?? '●'
261}
262
263/** One login's glyph for a percentage in a footer row's style. */
264export function glyph(style: Glyphs, pct: number): string {
265 switch (style) {
266 case 'bars':
267 return bar(pct)
268 case 'pie':
269 return pie(pct)
270 case 'braille':
271 return braille(pct)
272 case 'none':
273 return ''
274 }
275}
276
277/** A ten-cell bar for the pane, filled by a percentage. */
278export function longBar(pct: number | undefined): string {
279 if (pct === undefined) return '··········'
280 const full = Math.min(10, Math.max(0, Math.round(pct / 10)))
281 return '▰'.repeat(full) + '▱'.repeat(10 - full)
282}
283
284/** "in 1h 20m", "in 3d 4h": relative, so it needs no time zone. */
285export function untilText(at: number | string | undefined, now: number): string {
286 if (at === undefined) return ''
287 const ms = (typeof at === 'string' ? Date.parse(at) : at) - now
288 if (!Number.isFinite(ms)) return ''
289 if (ms <= 0) return 'now'
290 const minutes = Math.round(ms / 60_000)
291 if (minutes < 60) return `in ${minutes}m`
292 const hours = Math.floor(minutes / 60)
293 if (hours < 24) return `in ${hours}h ${minutes % 60}m`
294 return `in ${Math.floor(hours / 24)}d ${hours % 24}h`
295}
296
297export function label(account: Account | undefined): string {
298 if (account === undefined) return '?'
299 if (account.email === undefined) return account.id
300 return `${account.id} (${account.email}${account.orgName ? ` · ${account.orgName}` : ''})`
301}
302
303/**
304 * The keychain entry Claude Code keeps a slot's login in. Mirrors Claude Code
305 * 2.1.296: the normal login has no suffix; any other slot is suffixed with
306 * the first 8 hex digits of the SHA-256 of its directory, NFC-normalized.
307 */
308export async function keychainItem(slot: string): Promise<string> {
309 if (slot === '') return 'Claude Code-credentials'
310 return `Claude Code-credentials-${(await sha256(slot.normalize('NFC'))).slice(0, 8)}`
311}
312
313async function sha256(text: string): Promise<string> {
314 const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
315 return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('')
316}
317
318/** A digest of a sign-in's token: tells a new sign-in from the one asked about, without keeping the token. */
319export async function fingerprint(token: string): Promise<string> {
320 return (await sha256(token)).slice(0, 16)
321}
322
323/**
324 * The file Claude Code keeps a slot's login in where there is no keychain
325 * (Linux): where 2.1.296 puts it for a `claude` child run with `slotEnv`, the
326 * normal login's in ~/.claude and any other slot's in its own directory,
327 * NFC-normalized. Undefined for the normal login with no home. A session
328 * started with CLAUDE_CONFIG_DIR set keeps its normal login in that directory
329 * instead, which this misses as `keychainItem` does on macOS.
330 */
331export function credentialsFile(slot: string, home: string | undefined): string | undefined {
332 const dir = slot === '' ? home && `${home}/.claude` : slot
333 return dir ? `${dir.normalize('NFC')}/.credentials.json` : undefined
334}
335
336/** The environment that points a `claude` child at a slot's login. */
337export function slotEnv(slot: string): Record<string, string> {
338 return slot === ''
339 ? { CLAUDE_SECURESTORAGE_CONFIG_DIR: '' }
340 : { CLAUDE_SECURESTORAGE_CONFIG_DIR: slot, CLAUDE_CONFIG_DIR: slot }
341}
342
343/**
344 * Whether an error is Claude Code's security default refusing the switch: in
345 * a session on a Team or Enterprise account, or on a machine with managed
346 * settings, it keeps a plugin you install from changing where sign-ins are read.
347 */
348export function isPolicyRefusal(error: unknown): boolean {
349 return String(error).includes('is not for plugins outside policy to change')
350}
351
352/** Whether this session reads the normal login, the one `/login` signs in, rather than a slot the mod moved it to. */
353export function isOnNormalLogin(view: View): boolean {
354 return (view.accounts.find(a => a.id === view.activeId)?.slot ?? '') === ''
355}
356
357/**
358 * Why switching is blocked, and how to get a session that can switch. One on
359 * the normal login started on a Team seat: signing that login in to a personal
360 * account fixes the next session. One on a seat reloaded plugins there, or
361 * started there, as `/restart` keeps the slot in use; a new session from the
362 * terminal starts on the normal login already. `/login` there would sign in
363 * the seat instead, as sign-ins follow the slot in use.
364 */
365export function blockedAdvice(isNormalLogin: boolean): string {
366 return isNormalLogin
367 ? "Claude Code doesn't let plugins switch accounts in a session that starts on a Team or Enterprise account. " +
368 'Fix: /login with your personal (Pro or Max) account, then restart Claude.'
369 : "Claude Code doesn't let plugins switch accounts once a session on a Team or Enterprise account starts or reloads plugins. " +
370 'Fix: quit Claude and run `claude --continue` or `claude --resume`. Not /restart, which keeps this account.'
371}
372
373/** What the mod says once Claude Code's security default refuses switching. */
374export function blockedText(isNormalLogin: boolean): string {
375 return (
376 `Can't switch accounts in this session. ${blockedAdvice(isNormalLogin)} ` +
377 'More: https://github.com/ivokund/claude-account-rotator#team-and-enterprise-accounts'
378 )
379}
380
381/** The MCP server Claude Code runs Claude in Chrome as, and the names of its tools. */
382export const CHROME_SERVER = 'claude-in-chrome'
383export const CHROME_TOOL = /^mcp__claude-in-chrome__/
384
385/**
386 * How many browsers `list_connected_browsers` lists: the Chrome extensions
387 * signed in to the account Claude in Chrome connected as. Undefined for an
388 * answer that is no list.
389 */
390export function browsersFrom(text: string): number | undefined {
391 try {
392 const parsed: unknown = JSON.parse(text)
393 return Array.isArray(parsed) ? parsed.length : undefined
394 } catch {
395 // Words, not a list: an error, which counts no browsers either way.
396 return undefined
397 }
398}
399
400/** Whether a browser call's error says no browser answered, as Claude Code words it over its bridge or its local socket. */
401export function isNoBrowser(text: string): boolean {
402 return /Browser extension is not connected|isn't paired with your browser|No Chrome extension connected/.test(text)
403}
404
405/**
406 * Whether Connect can run in a session: an account is named for the Chrome
407 * extension, and the session is on it or free to move there.
408 */
409export function canConnectChrome(view: View): boolean {
410 const own = view.chromeAccountId
411 return own !== undefined && view.hasChrome !== false && (!view.isSwitchBlocked || view.activeId === own)
412}
413
414/** What brings this conversation back in a new session, which starts on Claude Code's login, free to switch. */
415export function resumeCommand(view: View): string {
416 return view.sessionId === undefined ? 'claude --continue' : `claude --resume ${view.sessionId}`
417}
418
419/**
420 * Why Claude is told about Claude in Chrome: a call held back while Connect is
421 * under way, or one that found no browser, and then the mod connects it now,
422 * or no browser answered there before, or the session can't move to the
423 * extension's account, or no account is named for the extension.
424 */
425export type ChromeNoteKind = 'held' | 'connecting' | 'no-browser' | 'blocked' | 'unset'
426
427/**
428 * What Claude reads about Claude in Chrome, in place of Claude Code's advice
429 * to /login, which in a session the mod moved signs in the account the
430 * session is on: what happens now, and what to tell the user.
431 */
432export function chromeNote(view: View, kind: ChromeNoteKind): string {
433 const named = (id: string | undefined) => {
434 const a = view.accounts.find(x => x.id === id)
435 return a === undefined ? undefined : `Claude account ${a.id}${a.email === undefined ? '' : ` (${a.email})`}`
436 }
437 const own = `${named(view.chromeAccountId) ?? 'one account'}, the account the user's Chrome extension is signed in to`
438 const as = named(view.chrome?.as)
439 const found = as === undefined ? 'Claude in Chrome found no browser.' : `Claude in Chrome connected as ${as} and found no browser.`
440 const wait = "End your turn now: you'll get a message once it's connected."
441 const noLogin = "Don't suggest /login: it doesn't fix this."
442 switch (kind) {
443 case 'held':
444 return `The account-rotator mod is connecting Claude in Chrome as ${own}, which takes under a minute; browser calls wait until then. ${wait}`
445 case 'connecting':
446 return `${found} The account-rotator mod is now ${view.chrome?.as === view.chromeAccountId ? 'reconnecting' : 'connecting'} it as ${own}, which takes under a minute. ${wait} ${noLogin}`
447 case 'no-browser':
448 return (
449 `No Chrome extension answers as ${named(view.chromeAccountId) ?? 'that account'}, the account picked for it in the Claude accounts panel: Chrome may be closed, its Claude extension signed in with another email, or its connection stuck. ` +
450 "Ask the user to open Chrome and check the email its Claude extension is signed in with. If it is another account, they press Use for Chrome or Try to connect next to it under Chrome in the Claude accounts panel (click the usage under the prompt; under Other accounts if it isn't listed). " +
451 (canConnectChrome(view)
452 ? `If it matches, they restart Chrome and press Connect above the prompt. You'll get a message once it's connected. ${noLogin}`
453 : `If it matches, they restart Chrome, then you try again. ${noLogin}`)
454 )
455 case 'blocked':
456 return (
457 `${found} This session can't connect it as ${own}: Claude Code doesn't let this session switch accounts. ` +
458 `Tell the user that to use Chrome, they quit Claude Code and run \`${resumeCommand(view)}\` in this terminal, which brings this conversation back with Chrome connected. ${noLogin}`
459 )
460 case 'unset':
461 return (
462 `${found} The user's Chrome extension answers only the Claude account it is signed in to, and the account-rotator mod doesn't know which one that is. ` +
463 `Ask the user to press Use for Chrome or Try to connect next to it under Chrome in the Claude accounts panel (click the usage under the prompt; under Other accounts if it isn't listed). You'll get a message once it's connected. ${noLogin}`
464 )
465 }
466}
467
468/** The keychain account name Claude Code files its entries under. */
469export function keychainUser(user: string | undefined): string {
470 return user !== undefined && /^[a-zA-Z0-9._-]+$/.test(user) ? user : 'claude-code-user'
471}
472
473/** The first number from 2 up that no login uses yet. */
474export function freeId(accounts: readonly Account[]): string {
475 const taken = new Set(accounts.map(a => a.id))
476 let n = 2
477 while (taken.has(String(n))) n += 1
478 return String(n)
479}
480
481export type Identity = Pick<Account, 'email' | 'orgId' | 'orgName' | 'plan'>
482
483/** Who a slot is signed in as, from `claude auth status --json`; undefined when signed out. */
484export function identityFromStatus(stdout: string): Identity | undefined {
485 let status: Record<string, unknown>
486 try {
487 const parsed: unknown = JSON.parse(stdout)
488 if (typeof parsed !== 'object' || parsed === null) return undefined
489 status = parsed as Record<string, unknown>
490 } catch {
491 // Output that is not JSON leaves who it is unknown; the label falls back to the number.
492 return undefined
493 }
494 if (status.loggedIn !== true || typeof status.email !== 'string') return undefined
495 return {
496 email: status.email,
497 ...(typeof status.orgId === 'string' ? { orgId: status.orgId } : {}),
498 ...(typeof status.orgName === 'string' ? { orgName: status.orgName } : {}),
499 ...(typeof status.subscriptionType === 'string' ? { plan: status.subscriptionType } : {}),
500 }
501}
502
503/** The same login: one email in one organization. */
504export function sameLogin(a: Identity, b: Identity): boolean {
505 return a.email !== undefined && a.email === b.email && (a.orgId ?? '') === (b.orgId ?? '')
506}
507
508/** A listed login is the account `who` signed in as, as far as it is known: by its email, and its organization once known. */
509export function isLoginOf(a: Identity, who: Identity): boolean {
510 return a.email !== undefined && a.email === who.email && (a.orgId === undefined || a.orgId === who.orgId)
511}
512
513/**
514 * Who a token signs in, from the body of GET /api/oauth/profile, which Claude
515 * Code asks at a sign-in: email and organization. The plan is the sign-in's own.
516 */
517export function identityFromProfile(body: unknown): Identity | undefined {
518 const field = (value: unknown, key: string) => (typeof value === 'object' && value !== null ? (value as Record<string, unknown>)[key] : undefined)
519 const { account, organization } = (typeof body === 'object' && body !== null ? body : {}) as Record<string, unknown>
520 const [email, orgId, orgName] = [field(account, 'email'), field(organization, 'uuid'), field(organization, 'name')]
521 if (typeof email !== 'string' || email === '') return undefined
522 return {
523 email,
524 ...(typeof orgId === 'string' ? { orgId } : {}),
525 ...(typeof orgName === 'string' ? { orgName } : {}),
526 }
527}
528
529/** A Team or Enterprise plan: Claude Code keeps plugins from switching accounts in a session that starts on one. */
530export const isSeatPlan = (plan: string | undefined): boolean => plan === 'team' || plan === 'enterprise'
531
532/** A plan as the pane names it: personal Max or Pro, or a Team or Enterprise seat. */
533export function planText(plan: string): string {
534 switch (plan) {
535 case 'max':
536 return 'personal Max'
537 case 'pro':
538 return 'personal Pro'
539 case 'team':
540 return 'a Team seat'
541 case 'enterprise':
542 return 'an Enterprise seat'
543 default:
544 return plan
545 }
546}
547
548hooks/view.tsx 720 lines1import type { Elements, RenderChildren, RenderSurface } from 'claude-code'
2
3import type { Account, Fill, FooterRun, FooterStyle, Glyphs, Highlight, RotateTo, UsageWindow, View } from '../types'
4import {
5 GLYPHS,
6 LEAVE_FIVE_HOUR,
7 LEAVE_SEVEN_DAY,
8 SIGN_IN_WARN_MS,
9 availableNow,
10 blockedAdvice,
11 canConnectChrome,
12 glyph,
13 isOnNormalLogin,
14 isSeatPlan,
15 longBar,
16 nextReset,
17 planText,
18 resumeCommand,
19 roomColor,
20 roomLeft,
21 shown,
22 untilText,
23 windowPct,
24} from './model'
25
26export type Ui = Pick<Elements[RenderSurface], 'Box' | 'Text' | 'Button'>
27
28export type Actions = {
29 togglePane: () => void
30 rotate: () => void
31 signInAll: () => void
32 signInOne: (id: string) => void
33 cancelSignIn: () => void
34 add: () => void
35 use: (id: string) => void
36 askRemove: (id: string) => void
37 remove: (id: string) => void
38 setFooter: (change: Partial<FooterStyle>) => void
39 setRotateTo: (rotateTo: RotateTo) => void
40 tryChromeAccount: (id: string) => void
41 toggleChromeOthers: () => void
42 connectChrome: () => void
43 setDemo: (on: boolean) => void
44}
45
46const needsSignIn = (view: View) => view.accounts.filter(a => view.health[a.id]?.kind === 'login-needed')
47
48/** Imitated room left per login, [right now, week], for the pane's demo preview: every color shows. */
49const DEMO: readonly (readonly [number, number])[] = [[85, 70], [60, 40], [35, 90], [15, 20], [95, 55]]
50
51/** A login's room left right now and in its week, or the demo's; undefined where it has none. */
52function rooms(view: View, a: Account, i: number, now: number): readonly [number | undefined, number | undefined] {
53 if (view.demo) return DEMO[i % DEMO.length] ?? [undefined, undefined]
54 const r = view.readings[a.id]
55 return [availableNow(r, now), roomLeft(r?.sevenDay, now)]
56}
57
58/** A percent's room color, lighter while the pointer is over the footer. */
59const roomRun = (leftPct: number) => ({ color: roomColor(leftPct), lit: roomColor(leftPct, true) })
60
61/**
62 * A login's glyph in a footer row, green with all of its room left to red with
63 * none. The session row says when a login needs a sign-in; a login without the
64 * room (a plan with no weekly limit) leaves its place blank.
65 */
66function glyphOf(view: View, a: Account, style: Glyphs, row: 0 | 1, room: number | undefined): FooterRun {
67 const health = view.health[a.id]?.kind
68 if (health === 'login-needed') return row === 0 ? { text: '⚠', color: 'error' } : { text: ' ' }
69 if (health === 'logging-in') return row === 0 ? { text: '◌', color: 'warning' } : { text: ' ' }
70 if (room === undefined) return { text: row === 0 ? '·' : ' ' }
71 return { text: glyph(style, shown(view.footer.fill, room)), ...roomRun(room) }
72}
73
74/** The tile's color: the theme's dim gray, the lines' own, which stands apart from the screen and from the shade under the pointer. */
75const TILE = 'subtle'
76/** The lines' color: the theme's dim gray, so they frame the column without outshining it; its lighter gray under the pointer. */
77const LINE = { color: 'subtle', lit: 'inactive' }
78
79/** How a login's glyph shows it is the one in use, as the pane's setting picks. */
80function marked(highlight: Highlight, isActive: boolean): Partial<FooterRun> {
81 switch (highlight) {
82 case 'tile':
83 return isActive ? { backgroundColor: TILE } : {}
84 case 'dim':
85 return isActive ? {} : { dimColor: true }
86 case 'lines':
87 return {}
88 }
89}
90
91/** The highlights drawn in the cells either side of a column: every row keeps those cells. */
92const IN_GAPS: readonly Highlight[] = ['lines', 'tile']
93
94/** A row's room left for the account in use, or undefined where it has none. */
95function activeRoom(view: View, now: number, row: 0 | 1): number | undefined {
96 const i = view.accounts.findIndex(a => a.id === view.activeId)
97 const active = view.accounts[i]
98 return active === undefined ? undefined : rooms(view, active, i, now)[row]
99}
100
101/**
102 * The cell before column `i`, or after the last one at `i` = the number of
103 * accounts: a space between columns, nothing at the ends, unless the highlight
104 * draws there. The lines stand mid-cell either side of the column in use, half
105 * a cell clear of its glyphs. The tile pads it with half of each of those
106 * cells, in half blocks, which most terminals draw to fill their cells; where
107 * the terminal draws them from its font, short of the line, they would notch
108 * the shade, so there it takes the whole cells.
109 */
110function edge(view: View, i: number, inGaps: boolean): FooterRun[] {
111 if (!inGaps) return i > 0 && i < view.accounts.length ? [{ text: ' ' }] : []
112 const active = view.accounts.findIndex(a => a.id === view.activeId)
113 if (i !== active && i - 1 !== active) return [{ text: ' ' }]
114 if (view.footer.active === 'lines') return [{ text: '│', ...LINE }]
115 if (view.hasFontBlocks) return [{ text: ' ', backgroundColor: TILE }]
116 return [{ text: i === active ? '▐' : '▌', color: TILE }]
117}
118
119/**
120 * One footer row as runs of text: a glyph per account, a space apart, then the
121 * account in use's percent at the right end. While another row draws glyphs, a
122 * row with its own off keeps their columns blank, so its percent lines up
123 * under the other's.
124 */
125function footerRow(view: View, now: number, row: 0 | 1, style: Glyphs, showPercent: boolean, hasColumns: boolean): FooterRun[] {
126 const pct = activeRoom(view, now, row)
127 const inGaps = hasColumns && IN_GAPS.includes(view.footer.active)
128 const columns = hasColumns
129 ? [
130 ...view.accounts.flatMap((a, i) => [
131 ...edge(view, i, inGaps),
132 {
133 ...(style === 'none' ? { text: ' ' } : glyphOf(view, a, style, row, rooms(view, a, i, now)[row])),
134 ...marked(view.footer.active, a.id === view.activeId),
135 },
136 ]),
137 ...edge(view, view.accounts.length, inGaps),
138 ]
139 : []
140 // A cell of the hover shade left of the glyphs where no highlight keeps one before the first column.
141 const lead: FooterRun[] = inGaps ? [] : [{ text: ' ' }]
142 if (!showPercent) return [...lead, ...columns]
143 const text = `${hasColumns ? (inGaps ? ' ' : ' ') : ''}${(pct === undefined ? '' : `${shown(view.footer.fill, pct)}%`).padStart(4)}`
144 return [...lead, ...columns, { text, ...(pct === undefined ? {} : roomRun(pct)) }]
145}
146
147/** The shade the footer's glyphs stand on under the pointer: the theme's own behind a message the person sent. */
148const HOVER_SHADE = 'userMessageBackground'
149
150const widthOf = (row: readonly FooterRun[]) => row.reduce((n, run) => n + run.text.length, 0)
151
152/**
153 * The rows' runs as Text, rows a line apart and padded a cell past the widest,
154 * so the hover shade is one even block with room right of the percents, as the
155 * cell before the glyphs gives it at the left. Under the pointer a Button is
156 * drawn inverted, its colors swapped, so each run's hover is given swapped: its
157 * lighter color as the background, the shade as the color. Inverted, that is
158 * the glyphs lit on the shade, and the tile's cells on their own color.
159 */
160function runsText({ Text }: Ui, rows: readonly FooterRun[][]) {
161 const width = Math.max(...rows.map(widthOf)) + 1
162 return rows.flatMap((row, i) => [
163 ...(i > 0 ? ['\n'] : []),
164 <Text>
165 {[...row, ...(widthOf(row) < width ? [{ text: ' '.repeat(width - widthOf(row)) }] : [])].map(run => (
166 <Text
167 color={run.color}
168 backgroundColor={run.backgroundColor}
169 dimColor={run.dimColor}
170 hover={{ color: run.backgroundColor ?? HOVER_SHADE, backgroundColor: run.lit ?? run.color ?? 'text', dimColor: false }}
171 >
172 {run.text}
173 </Text>
174 ))}
175 </Text>,
176 ])
177}
178
179/** What each footer row counts, said left of it while the pointer is over the footer. */
180const ROW_NAMES = ['Session:', 'Weekly:'] as const
181
182/**
183 * The footer, right of the prompt: the engine's mode labels, then a row per
184 * row picked in the pane (right now, the week), glyphs and percent each on or
185 * off, as one control that opens the pane, or closes it while it shows. Under
186 * the pointer the glyphs light up on a shade, and each row's name shows at its
187 * left. A week row with nothing to show is left out; with both rows off, a
188 * word keeps the control.
189 */
190export function Footer(ui: Ui, view: View, modes: readonly string[], now: number, act: Actions) {
191 const { Box, Text, Button } = ui
192 const { session, week, sessionPercent, weekPercent } = view.footer
193 const hasWeek = view.accounts.some((a, i) => rooms(view, a, i, now)[1] !== undefined)
194 const sessionGlyphs = session !== 'none'
195 const weekGlyphs = week !== 'none' && hasWeek
196 const hasColumns = sessionGlyphs || weekGlyphs
197 const weekShown = weekGlyphs || (weekPercent && activeRoom(view, now, 1) !== undefined)
198 const shownRows = [...(sessionGlyphs || sessionPercent ? [0 as const] : []), ...(weekShown ? [1 as const] : [])]
199 const rows = shownRows.map(row =>
200 row === 0 ? footerRow(view, now, 0, session, sessionPercent, hasColumns) : footerRow(view, now, 1, week, weekPercent, hasColumns),
201 )
202 return (
203 <Box flexDirection="row" columnGap={1}>
204 {modes.length > 0 && <Text dimColor>{modes.join(' & ')}</Text>}
205 <Box key="accounts-area" flexDirection="row" columnGap={1}>
206 {rows.length > 0 && (
207 <Box display="none" hover={{ display: 'flex' }} flexDirection="column" alignItems="flex-end">
208 {shownRows.map(row => (
209 <Text dimColor>{ROW_NAMES[row]}</Text>
210 ))}
211 </Box>
212 )}
213 {/* Switching is blocked: a press opens the pane, whose first line says why. */}
214 {view.isSwitchBlocked && (
215 <Button key="switch-blocked" label="Switching blocked" plain onPress={act.togglePane}>
216 <Text color="warning">⚠</Text>
217 </Button>
218 )}
219 {/* A scope of its own: the glyphs light only while the pointer is on them, as the control inverts. */}
220 <Box key="accounts-glyphs">
221 <Button key="accounts" label="Claude accounts" plain onPress={act.togglePane}>
222 {rows.length === 0 ? <Text dimColor>accounts</Text> : runsText(ui, rows)}
223 </Button>
224 </Box>
225 </Box>
226 </Box>
227 )
228}
229
230/** The pane's mark for what is in use or picked: the theme's yellow. */
231const ACCENT = 'warning'
232
233/** A setting that is on or off, as a press that flips it. */
234function toggle(ui: Ui, key: string, label: string, on: boolean, set: (on: boolean) => void) {
235 const { Text, Button } = ui
236 return (
237 <Button key={key} plain onPress={() => set(!on)}>
238 <Text color={on ? ACCENT : undefined} dimColor={!on}>
239 {on ? '■' : '□'} {label}
240 </Text>
241 </Button>
242 )
243}
244
245/** Settings' names take a column of their own; their presses wrap under each other on a narrow pane. */
246const NAME_WIDTH = 9
247
248/** One setting: its name, then its options as presses, the picked one marked. */
249function choice<T extends string>(
250 ui: Ui,
251 key: string,
252 name: string,
253 options: readonly (readonly [T, string])[],
254 picked: T,
255 pick: (value: T) => void,
256) {
257 const { Box, Text, Button } = ui
258 return (
259 <Box key={key} flexDirection="row">
260 <Box width={NAME_WIDTH} flexShrink={0}>
261 <Text dimColor>{name}</Text>
262 </Box>
263 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
264 {options.map(([value, label]) => (
265 <Button key={`${key}-${value}`} plain onPress={() => pick(value)}>
266 <Text color={value === picked ? ACCENT : undefined} dimColor={value !== picked}>
267 {value === picked ? '●' : '○'} {label}
268 </Text>
269 </Button>
270 ))}
271 </Box>
272 </Box>
273 )
274}
275
276const GLYPH_CHOICES = GLYPHS.map(g => [g, g] as const)
277const HIGHLIGHT_CHOICES = [
278 ['lines', 'lines'],
279 ['tile', 'tile'],
280 ['dim', 'dim the rest'],
281] as const
282const FILL_CHOICES = [
283 ['left', 'room left'],
284 ['used', 'used'],
285] as const satisfies readonly (readonly [Fill, string])[]
286const ROTATE_CHOICES = [
287 ['reset', 'soonest reset'],
288 ['room', 'most room'],
289 ['order', 'next in list'],
290 ['off', 'disabled'],
291] as const satisfies readonly (readonly [RotateTo, string])[]
292const PREVIEW_CHOICES = [
293 ['real', 'your usage'],
294 ['demo', 'demo values'],
295] as const
296
297/**
298 * A group of the pane in a box of its own, its name set in the top border: the
299 * name is painted over the border as the wrapper's last child.
300 */
301function section(ui: Ui, key: string, title: string, children: RenderChildren) {
302 const { Box, Text } = ui
303 return (
304 <Box key={key} flexDirection="column">
305 <Box flexDirection="column" borderStyle="round" borderColor="subtle" paddingX={1}>
306 {children}
307 </Box>
308 <Box position="absolute" top={0} left={2}>
309 <Text bold> {title} </Text>
310 </Box>
311 </Box>
312 )
313}
314
315/** The footer's settings: a style and a percent per row, what glyphs fill with, how the login in use stands out, and a demo preview. */
316function FooterSettings(ui: Ui, view: View, act: Actions) {
317 const { Box, Text } = ui
318 return section(ui, 'display', 'Display', [
319 choice(ui, 'footer-session', 'Session', GLYPH_CHOICES, view.footer.session, session => act.setFooter({ session })),
320 choice(ui, 'footer-week', 'Week', GLYPH_CHOICES, view.footer.week, week => act.setFooter({ week })),
321 <Box key="footer-percent" flexDirection="row">
322 <Box width={NAME_WIDTH} flexShrink={0}>
323 <Text dimColor>Percent</Text>
324 </Box>
325 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
326 {toggle(ui, 'footer-percent-session', 'session', view.footer.sessionPercent, on => act.setFooter({ sessionPercent: on }))}
327 {toggle(ui, 'footer-percent-week', 'week', view.footer.weekPercent, on => act.setFooter({ weekPercent: on }))}
328 </Box>
329 </Box>,
330 choice(ui, 'footer-fill', 'Show', FILL_CHOICES, view.footer.fill, fill => act.setFooter({ fill })),
331 choice(ui, 'footer-active', 'In use', HIGHLIGHT_CHOICES, view.footer.active, active => act.setFooter({ active })),
332 choice(ui, 'footer-preview', 'Preview', PREVIEW_CHOICES, view.demo ? 'demo' : 'real', v => act.setDemo(v === 'demo')),
333 ])
334}
335
336/** Which login the rotation moves to. */
337function RotationSettings(ui: Ui, view: View, act: Actions) {
338 return section(ui, 'rotation', 'Usage based rotation', [
339 choice(ui, 'rotate-to', 'Move to', ROTATE_CHOICES, view.rotateTo, act.setRotateTo),
340 ])
341}
342
343/** An account as the band names it: its number, and its email once known. */
344function named(view: View, id: string): string {
345 const email = view.accounts.find(a => a.id === id)?.email
346 return email === undefined ? `account ${id}` : `account ${id} (${email})`
347}
348
349/**
350 * What keeps Claude in Chrome from working in this window, in a sentence: no
351 * browser answering where it connected, or no move to the extension's account.
352 */
353function chromeProblem(view: View): string | undefined {
354 const own = view.chromeAccountId
355 const link = view.chrome
356 if (own === undefined || view.chromeConnecting !== undefined || link?.isPaired) return undefined
357 if (link?.as === own) {
358 return `No Chrome extension answers as ${named(view, own)}. Open Chrome and check its Claude extension is signed in with that email; if it is, restart Chrome.`
359 }
360 if (!canConnectChrome(view)) return `This window can't switch to ${named(view, own)}. Quit, then run: ${resumeCommand(view)}`
361 return undefined
362}
363
364/**
365 * One account in the Chrome box: who it is, then in use, connecting, or a
366 * press: Use for Chrome where a browser answered as it, else Try to connect.
367 */
368function chromeRow(ui: Ui, view: View, a: Account, act: Actions) {
369 const { Box, Text, Button } = ui
370 const link = view.chrome
371 const isConnecting = view.chromeConnecting === a.id
372 const isInUse = !isConnecting && link?.isPaired === true && (link.as ?? view.chromeAccountId) === a.id
373 const canTry = view.chromeConnecting === undefined && (!view.isSwitchBlocked || view.activeId === a.id)
374 const isAnswered = view.chromeAccountIds?.includes(a.id) === true
375 const end = isConnecting ? (
376 <Text color="warning">◌ Connecting Chrome…</Text>
377 ) : isInUse ? (
378 <Text color={ACCENT}>● in use</Text>
379 ) : (
380 canTry && (
381 <Button key={`chrome-${isAnswered ? 'use' : 'try'}-${a.id}`} onPress={() => act.tryChromeAccount(a.id)}>
382 {isAnswered ? 'Use for Chrome' : 'Try to connect'}
383 </Button>
384 )
385 )
386 return (
387 <Box key={`chrome-row-${a.id}`} flexDirection="row" flexWrap="wrap" columnGap={2}>
388 <Box flexDirection="row" flexShrink={1}>
389 <Box width={3} flexShrink={0}>
390 <Text bold={isInUse} dimColor={!isInUse}>{a.id}</Text>
391 </Box>
392 <Text bold={isInUse} dimColor={!isInUse}>{a.email ?? `account ${a.id}`}</Text>
393 </Box>
394 <Box flexDirection="row" flexGrow={1} justifyContent="flex-end">
395 {end}
396 </Box>
397 </Box>
398 )
399}
400
401/**
402 * Claude in Chrome: the accounts a Chrome extension answered as the last time
403 * Claude in Chrome connected as them, and the one it is connecting as, the one
404 * this window's Chrome is connected as in use, as in Accounts, the others a
405 * press away; then what keeps it from working. With none found yet, every
406 * account, to pick the extension's; after, the rest on a press, under a line
407 * of their own, for a Chrome opened on another account.
408 */
409function ChromeSettings(ui: Ui, view: View, act: Actions) {
410 const { Box, Text, Button } = ui
411 if (view.hasChrome === false) return section(ui, 'chrome', 'Chrome', [<Text key="chrome-none" dimColor>Not available in this window.</Text>])
412 const found = view.accounts.filter(a => view.chromeAccountIds?.includes(a.id) || a.id === view.chromeConnecting)
413 const others = found.length === 0 ? [] : view.accounts.filter(a => !found.includes(a))
414 const shownOthers = view.isChromeOthersShown ? others : []
415 const listed = found.length === 0 ? view.accounts : [...found, ...shownOthers]
416 // A window that can't switch accounts has a press on its own account only: it says why, once.
417 const isStuck = view.isSwitchBlocked === true && listed.some(a => a.id !== view.activeId)
418 const problem =
419 chromeProblem(view) ?? (isStuck ? `This window can't switch accounts, so Chrome can't move to another one here. Quit, then run: ${resumeCommand(view)}` : undefined)
420 return section(ui, 'chrome', 'Chrome', [
421 found.length === 0 ? (
422 <Text key="chrome-intro" dimColor>No Chrome extension found yet. Which account is yours signed in to?</Text>
423 ) : (
424 <Box key="chrome-intro" flexDirection="row" flexWrap="wrap" columnGap={2}>
425 <Text dimColor>Active Claude extension accounts from your Chrome windows:</Text>
426 {others.length > 0 && (
427 <Button key="chrome-others" plain onPress={act.toggleChromeOthers}>
428 <Text dimColor>{`${view.isChromeOthersShown ? '▾' : '▸'} Other accounts`}</Text>
429 </Button>
430 )}
431 </Box>
432 ),
433 ...(found.length === 0 ? view.accounts : found).map(a => chromeRow(ui, view, a, act)),
434 ...(shownOthers.length === 0
435 ? []
436 : [<Text key="chrome-others-intro" dimColor>No Chrome extension is known to answer as these:</Text>, ...shownOthers.map(a => chromeRow(ui, view, a, act))]),
437 ...(problem === undefined ? [] : [<Text key="chrome-problem" color="warning">{`⚠ ${problem}`}</Text>]),
438 ])
439}
440
441/**
442 * The band while Connect is under way, or once a browser call found no
443 * browser: what keeps Claude in Chrome from working, and Connect where it can help.
444 */
445function ChromeBand(ui: Ui, view: View, act: Actions) {
446 const { Box, Text, Button } = ui
447 if (view.chromeConnecting !== undefined) {
448 return <Text color="warning">{`◌ Connecting Chrome as ${named(view, view.chromeConnecting)}…`}</Text>
449 }
450 if (!view.chrome?.hasFailed) return undefined
451 const own = view.chromeAccountId
452 if (own === undefined) {
453 return (
454 <Box flexDirection="row" columnGap={2}>
455 <Text color="warning">⚠ Claude in Chrome: which account is your Chrome extension signed in to?</Text>
456 <Button key="chrome-pick" onPress={act.togglePane}>Pick it</Button>
457 </Box>
458 )
459 }
460 return (
461 <Box flexDirection="row" columnGap={2}>
462 <Text color="warning">{`⚠ ${chromeProblem(view) ?? `Chrome isn't connected as ${named(view, own)}.`}`}</Text>
463 {canConnectChrome(view) && (
464 <Button key="chrome-connect-band" variant="primary" onPress={act.connectChrome}>
465 Connect
466 </Button>
467 )}
468 </Box>
469 )
470}
471
472/** The band above the prompt, drawn only while a login needs the person. */
473export function Band(ui: Ui, view: View, now: number, act: Actions) {
474 const { Box, Text, Button } = ui
475 const signingIn = view.accounts.find(a => view.health[a.id]?.kind === 'logging-in')
476 if (signingIn !== undefined) {
477 return (
478 <Box flexDirection="row" columnGap={2}>
479 <Text color="warning">
480 ◌ Account {signingIn.id}: in your browser, approve as {signingIn.email ?? 'the account to add'} and pick the
481 organization. Wrong account there? Sign out of claude.ai in another tab, then reload the sign-in page.
482 </Text>
483 <Button key="cancel-sign-in" onPress={act.cancelSignIn}>Cancel</Button>
484 </Box>
485 )
486 }
487 const locked = needsSignIn(view)
488 if (locked.length > 0) {
489 const names = locked.map(a => (a.email ? `${a.id} (${a.email})` : a.id)).join(', ')
490 const why = locked.map(a => view.health[a.id]).find(h => h?.kind === 'login-needed')
491 return (
492 <Box flexDirection="row" columnGap={2}>
493 <Text color="error">
494 ⚠ Claude account {names} needs a sign-in{why?.kind === 'login-needed' ? ` (${why.why})` : ''}.
495 </Text>
496 <Button key="sign-in-all" variant="primary" hotkey="s" onPress={act.signInAll}>
497 {locked.length > 1 ? 'Sign in all' : 'Sign in'}
498 </Button>
499 </Box>
500 )
501 }
502 const chrome = ChromeBand(ui, view, act)
503 if (chrome !== undefined) return chrome
504 const spent = view.accounts.every(a => {
505 const r = view.readings[a.id]
506 return (windowPct(r?.fiveHour, now) ?? 0) >= LEAVE_FIVE_HOUR || (windowPct(r?.sevenDay, now) ?? 0) >= LEAVE_SEVEN_DAY
507 })
508 if (view.accounts.length > 0 && spent) {
509 const at = nextReset(view, now)
510 return (
511 <Text color="warning">
512 Every Claude account is near its limit{at === undefined ? '' : `; the next frees up ${untilText(at, now)}`}.
513 </Text>
514 )
515 }
516 return undefined
517}
518
519/** A window's bar and percent at their widest ("▰▰▰▰▰▰▰▰▰▰ 100% left"), so the reset times line up. */
520const BAR_WIDTH = 20
521
522/**
523 * One usage window of a login, filled and colored as the footer draws it, and
524 * when it resets: beside it, or under the bar on a narrow pane. A plan that
525 * reports no such window (a Team seat's week) says so.
526 */
527function windowRow(ui: Ui, fill: Fill, isActive: boolean, name: string, hasReading: boolean, w: UsageWindow | undefined, now: number) {
528 const { Box, Text } = ui
529 const left = roomLeft(w, now)
530 return (
531 <Box flexDirection="row" marginLeft={3}>
532 <Box width={5} flexShrink={0}>
533 <Text dimColor={!isActive}>{name}</Text>
534 </Box>
535 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
536 <Box minWidth={BAR_WIDTH}>
537 {left === undefined ? (
538 <Text dimColor>
539 {longBar(undefined)}
540 {hasReading ? ' none reported' : ' no reading yet'}
541 </Text>
542 ) : (
543 <Text color={roomColor(left)}>{`${longBar(shown(fill, left))} ${shown(fill, left)}% ${fill === 'left' ? 'left' : 'used'}`}</Text>
544 )}
545 </Box>
546 {w?.resetsAt !== undefined && left !== undefined && left < 100 && <Text dimColor={!isActive}>resets {untilText(w.resetsAt, now)}</Text>}
547 </Box>
548 </Box>
549 )
550}
551
552/** The slot at the right end of a login's line: as wide as a button the terminal draws, `[ Use now ]`, so the Removes beside it line up. */
553const USE_WIDTH = '[ Use now ]'.length
554
555/**
556 * The right end of a login's line: what it needs, then Remove, then rightmost
557 * always its use, in a slot of its own: in use, Use now, Sign in while it
558 * needs one, or signing in.
559 */
560function lineEnd(ui: Ui, view: View, a: Account, act: Actions) {
561 const { Box, Text, Button } = ui
562 const health = view.health[a.id]
563 const remove =
564 a.slot !== '' &&
565 health?.kind !== 'logging-in' &&
566 (view.removing === a.id ? (
567 <Button key={`remove-${a.id}`} onPress={() => act.remove(a.id)}>Press again to remove</Button>
568 ) : (
569 <Button key={`ask-remove-${a.id}`} dimColor onPress={() => act.askRemove(a.id)}>Remove</Button>
570 ))
571 const use = (end: RenderChildren) => (
572 <Box minWidth={USE_WIDTH} justifyContent="flex-end">
573 {end}
574 </Box>
575 )
576 switch (health?.kind) {
577 case 'login-needed':
578 return [
579 <Text color="error">⚠ {health.why}</Text>,
580 remove,
581 use(<Button key={`sign-in-${a.id}`} variant="primary" onPress={() => act.signInOne(a.id)}>Sign in</Button>),
582 ]
583 case 'logging-in':
584 return [use(<Text color="warning">◌ signing in…</Text>)]
585 default:
586 return [
587 remove,
588 use(
589 a.id === view.activeId ? (
590 view.chromeConnecting === a.id ? (
591 <Text color="warning">◌ Connecting Chrome…</Text>
592 ) : (
593 <Text color={ACCENT}>● in use</Text>
594 )
595 ) : (
596 health?.kind === 'ok' && <Button key={`use-${a.id}`} onPress={() => act.use(a.id)}>Use now</Button>
597 ),
598 ),
599 ]
600 }
601}
602
603/**
604 * One login: who it is at the left of its first line, its state and presses
605 * at the right (under it, still at the right, on a pane too narrow for both),
606 * then its two windows. The login in use is drawn bright, the rest dim.
607 */
608function accountRows(ui: Ui, view: View, a: Account, now: number, act: Actions) {
609 const { Box, Text } = ui
610 const health = view.health[a.id]
611 const r = view.readings[a.id]
612 const isActive = a.id === view.activeId
613 const expiry = health?.kind === 'ok' ? health.refreshExpiresAt : undefined
614 // Its organization and plan, and whether the Chrome extension is signed in to it.
615 const about = [
616 ...(a.orgName === undefined ? [] : [a.plan ? `${a.orgName} · ${a.plan}` : a.orgName]),
617 ...(view.chromeAccountId === a.id ? ['Chrome'] : []),
618 ]
619 return (
620 <Box key={`account-${a.id}`} flexDirection="column" marginBottom={1}>
621 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
622 <Box flexDirection="row" flexShrink={1}>
623 <Box width={3} flexShrink={0}>
624 <Text bold={isActive} dimColor={!isActive}>{a.id}</Text>
625 </Box>
626 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
627 <Text bold={isActive} dimColor={!isActive}>{a.email ?? (a.slot === '' ? 'your normal account' : 'not signed in yet')}</Text>
628 {about.length > 0 && <Text dimColor>{about.join(' · ')}</Text>}
629 </Box>
630 </Box>
631 <Box flexDirection="row" flexGrow={1} flexWrap="wrap" justifyContent="flex-end" columnGap={2}>
632 {lineEnd(ui, view, a, act)}
633 </Box>
634 </Box>
635 {windowRow(ui, view.footer.fill, isActive, '5h', r !== undefined, r?.fiveHour, now)}
636 {windowRow(ui, view.footer.fill, isActive, 'week', r !== undefined, r?.sevenDay, now)}
637 {expiry !== undefined && expiry - now < SIGN_IN_WARN_MS && (
638 <Text color="warning"> sign-in runs out {untilText(expiry, now)}; signing in again renews it</Text>
639 )}
640 </Box>
641 )
642}
643
644/** Where the rotation moves to, as its setting picks. */
645const RULE_TARGETS: Record<Exclude<RotateTo, 'off'>, string> = {
646 reset: 'the account whose 5-hour window resets soonest',
647 room: 'the account with the most room right now',
648 order: 'the next account in the list with room',
649}
650
651/** When the rotation moves on, counted the way the footer shows it (room left, or what is used), and where to. */
652function rule(fill: Fill, rotateTo: RotateTo): string {
653 if (rotateTo === 'off') return 'Rotation is disabled: the session stays on the account in use until you pick another.'
654 const when =
655 fill === 'left'
656 ? `Once the account in use has ${100 - LEAVE_FIVE_HOUR}% of its 5-hour window or ${100 - LEAVE_SEVEN_DAY}% of its week left`
657 : `Once the account in use has used ${LEAVE_FIVE_HOUR}% of its 5-hour window or ${LEAVE_SEVEN_DAY}% of its week`
658 return `${when}, moves to ${RULE_TARGETS[rotateTo]}.`
659}
660
661/** The pane's first line while Claude Code's security policy refuses every switch. */
662function blockedRule(view: View): string {
663 return (
664 `Can't switch accounts in this session. ${blockedAdvice(isOnNormalLogin(view))} More in the README.`
665 )
666}
667
668/**
669 * Claude Code's own login, the one new sessions start on, as its sign-in
670 * says: whose account it is, and its plan, a Team or Enterprise one keeping
671 * those sessions from switching. In a session on another login, /login signs
672 * in that one instead.
673 */
674function LoginLine({ Text }: Ui, view: View) {
675 const normal = view.accounts.find(a => a.slot === '')
676 if (normal === undefined) return undefined
677 const who = view.holders[normal.id]?.who ?? normal
678 const isSeat = isSeatPlan(who.plan)
679 const text = [
680 `Claude Code's login: account ${normal.id}${who.email === undefined ? '' : ` (${who.email})`}${who.plan === undefined ? '' : `, ${planText(who.plan)}`}.`,
681 isSeat
682 ? "New sessions start on it, and can't switch accounts: /login with your personal (Pro or Max) account in a session on it, then restart Claude."
683 : 'New sessions start on it.',
684 ...(view.activeId === normal.id ? [] : [`/login in this session signs in account ${view.activeId} instead.`]),
685 ]
686 return (
687 <Text key="login" color={isSeat ? 'warning' : undefined} dimColor={!isSeat}>
688 {text.join(' ')}
689 </Text>
690 )
691}
692
693/**
694 * The pane: when the rotation moves on (or that it can't), and Claude Code's
695 * own login, then every account, its usage and what can be done with it, then
696 * Claude in Chrome in a session that has it, where the rotation moves to, and
697 * the footer's settings, each group in its box.
698 */
699export function Pane(ui: Ui, view: View, now: number, act: Actions) {
700 const { Box, Text, Button } = ui
701 const accounts = [
702 ...view.accounts.map(a => accountRows(ui, view, a, now, act)),
703 <Box key="add-row" flexDirection="row" columnGap={2}>
704 <Button key="add" onPress={act.add}>+ Add an account</Button>
705 {view.accounts.length > 1 && <Button key="rotate" onPress={act.rotate}>Rotate now</Button>}
706 {needsSignIn(view).length > 1 && <Button key="pane-sign-in-all" variant="primary" onPress={act.signInAll}>Sign in all</Button>}
707 </Box>,
708 ]
709 return (
710 <Box flexDirection="column" rowGap={1}>
711 {view.isSwitchBlocked ? <Text color="warning">{blockedRule(view)}</Text> : <Text dimColor>{rule(view.footer.fill, view.rotateTo)}</Text>}
712 {LoginLine(ui, view)}
713 {section(ui, 'accounts', 'Accounts', accounts)}
714 {(view.hasChrome === true || view.chromeAccountId !== undefined || (view.chromeAccountIds?.length ?? 0) > 0) && ChromeSettings(ui, view, act)}
715 {RotationSettings(ui, view, act)}
716 {FooterSettings(ui, view, act)}
717 </Box>
718 )
719}
720types/index.d.ts 118 lines1/** One usage window of a login: percent used, and when it resets (ISO 8601). */
2export type UsageWindow = { pct: number; resetsAt?: string }
3
4/** A login's usage as last read, `at` in epoch milliseconds. */
5export type Reading = { fiveHour?: UsageWindow; sevenDay?: UsageWindow; at: number }
6
7/** Whether a login can serve requests, or why not. */
8export type Health =
9 | { kind: 'ok'; refreshExpiresAt?: number }
10 | { kind: 'login-needed'; why: string }
11 | { kind: 'logging-in'; since: number }
12
13/**
14 * One Claude login. `slot` is the credentials directory Claude Code reads it
15 * from: '' is the normal login, anything else an absolute directory.
16 */
17export type Account = {
18 id: string
19 slot: string
20 email?: string
21 /** One email can hold logins in several organizations (your Max plan, a Team seat). */
22 orgId?: string
23 orgName?: string
24 /** `subscriptionType` as `claude auth status` reports it: max, team, pro. */
25 plan?: string
26}
27
28/**
29 * Who a login's sign-in belongs to, as the profile endpoint answered for the
30 * token `token` digests; the plan as Claude Code reads it from the sign-in.
31 */
32export type Holder = { token: string; who: Pick<Account, 'email' | 'orgId' | 'orgName' | 'plan'> & { email: string } }
33
34/** How the footer draws one of its rows: a glyph per login, or not at all. */
35export type Glyphs = 'bars' | 'pie' | 'braille' | 'none'
36
37/** How the footer marks the login in use: a dark line down each side of its column, a tile behind it, or the rest dimmed. */
38export type Highlight = 'lines' | 'tile' | 'dim'
39
40/** What glyphs and bars fill with: the room a login has left, or what it has used. */
41export type Fill = 'left' | 'used'
42
43/**
44 * Which login the rotation moves to: the one whose 5-hour window resets
45 * soonest, the one with the most room right now, or the next in the list; or
46 * none, the rotation off: the session moves only when the person picks.
47 */
48export type RotateTo = 'reset' | 'room' | 'order' | 'off'
49
50/** The footer's look, picked in the pane and kept across sessions. */
51export type FooterStyle = {
52 session: Glyphs
53 week: Glyphs
54 /** Whether a row ends with the login in use's percent. */
55 sessionPercent: boolean
56 weekPercent: boolean
57 active: Highlight
58 /** Either way the colors go from green with all the room left to red with none. */
59 fill: Fill
60}
61
62/**
63 * Claude in Chrome in one session: the account its connection was made as,
64 * where known, and whether a browser answered there; `hasFailed` once a
65 * browser call found none, until one is answered again.
66 */
67export type ChromeLink = { as?: string; isPaired: boolean; hasFailed?: boolean }
68
69/** A run of the footer's text: its color, and the lighter one it takes while the pointer is over the footer. */
70export type FooterRun = { text: string; color?: string; lit?: string; backgroundColor?: string; dimColor?: boolean }
71
72/** Everything the footer, band and pane draw from. */
73export type View = {
74 accounts: Account[]
75 readings: Record<string, Reading>
76 health: Record<string, Health>
77 /** Who each login's sign-in belongs to: a /login in a session on a login signs in there, whoever it signs in. */
78 holders: Record<string, Holder>
79 /** The login this session sends its requests with. */
80 activeId: string
81 /** Set after a switch until a response shows the new login's usage. */
82 pending?: { id: string; from: string; since: number }
83 /** Account id whose removal waits for a second press. */
84 removing?: string
85 footer: FooterStyle
86 /** Which login the rotation moves to, picked in the pane and kept across sessions. */
87 rotateTo: RotateTo
88 /** This session only: Claude Code's security default refuses switching, as on a Team or Enterprise account. */
89 isSwitchBlocked?: boolean
90 /**
91 * The account the Chrome extension is signed in to, the only one it answers:
92 * picked in the pane, or learned when Claude in Chrome paired; kept across sessions.
93 */
94 chromeAccountId?: string
95 /** The accounts a Chrome extension has answered as, kept across sessions: the Chrome box lists them. */
96 chromeAccountIds?: string[]
97 /** This session only: the Chrome box also lists the accounts no Chrome extension has answered as yet. */
98 isChromeOthersShown?: boolean
99 /** This session only: whether it has Claude in Chrome, once a call to it told. */
100 hasChrome?: boolean
101 /** This session only: Claude in Chrome's connection, once made. */
102 chrome?: ChromeLink
103 /** This session only: Connect is under way, to this account. */
104 chromeConnecting?: string
105 /** This session's id, which `claude --resume` takes. */
106 sessionId?: string
107 /** This session only: the footer draws imitated usage, to judge its look. */
108 demo?: boolean
109 /** This session's terminal draws block characters from its font, short of the line, as Terminal.app does. */
110 hasFontBlocks: boolean
111}
112
113declare module 'claude-code' {
114 interface PluginState {
115 'account-rotator': { view: View }
116 }
117}
118