switch Anthropic accounts from the usage pills
The owner keeps a personal account and a company one and moves between them during a day — by what the work
is, and sometimes because one has hit a limit and the work has to carry on. /login handles ARRIVING at an
account. It could not go back to one, because the credential it overwrote was gone.
ai_provider_usage already answered "which of my accounts has room". This answers what immediately follows:
"then use that one". The chips under the numbers stop selecting whose stats you read and start selecting who
you ARE — which turned out to be the useful half of the same gesture, since reading the other account's
percentages was only ever a prelude to using it.
anthropic_accounts holds each login's OAuth object encrypted, keyed (user_id, account_uuid).
One key per ACCOUNT, not one for the table: encryptSecret('anthropic-account:<uuid>', …), so the secret
store mints a separate key each and one leak is one account. Same reasoning that split VAULT_STORE_KEY into
purposes. The uuid comes from Anthropic and survives a re-login; the email is stable too but is editable at
the provider.
What is stored includes a REFRESH token, deliberately — the access token lives hours and the refresh token
is what makes a switch work a week later. So a row plus its key is thirty days of acting as that account.
That was accepted knowingly; the per-account key narrows it, and refreshExpiresAt is a column so a dead
credential gets purged on read rather than sitting here for ever. An expired one cannot be switched to at
all: reveal returns null, because writing an expired credential would sign the owner out with no message.
Capture happens on login AND on every read of the account list. Without that second one this would know
only about logins that went through this dialog, and an account signed into from a terminal would be
invisible to the switcher — half your accounts missing, silently. The switch also captures the OUTGOING
credential first, or switching away from a terminal login loses it.
.credentials.json is replaced wholesale; .claude.json is PATCHED. The second holds the CLI's entire config
and overwriting it would take out every project entry and preference in it.
Owner only, and the isolation is unchanged: getOwnerHomeDir ignores the email it is passed, so every path
here is the owner's. A member's claude reads their own home and none of this touches it. The earlier claim
in this work that the credential was "machine-wide" was wrong — the owner corrected it. What a switch
actually changes is every claude running AS THE OWNER: terminals, task runners, pipelines, the commander.
The spinner is not decoration. A switch rewrites a file and changes nothing visible, so without it the
honest reading of a click is "nothing happened" and the second click is somebody checking. A running turn
keeps the credential it was spawned with, and the response says so rather than leaving the UI to imply
otherwise.
Verified before shipping: capture records the live account with org, plan and expiry; reveal decrypts
byte-identical to what is on disk; /api/claude-auth/accounts is 401 unauthenticated and 403 for a non-owner.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,11 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { usePermissions } from 'hooks/usePermissions';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import type { UsageAccount } from '../useClaudeUsage';
|
||||
import { currentLimit, formatAge, formatReset, formatTokens, useClaudeUsage, weekdayLabel } from '../useClaudeUsage';
|
||||
import type { SwitchableAccount } from '../useAnthropicAccounts';
|
||||
import { useAnthropicAccounts } from '../useAnthropicAccounts';
|
||||
|
||||
/**
|
||||
* Claude Code's own usage display, on the harness pill — for every account, not just the one signed in.
|
||||
@@ -129,38 +132,60 @@ const Models = ({ account }: { account: UsageAccount }) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* One chip per account, and only when there is more than one.
|
||||
* One chip per Anthropic account, and clicking one BECOMES it.
|
||||
*
|
||||
* A tab strip over a single account is chrome that never does anything — the same reasoning that collapses
|
||||
* the provider strip to a label when there is one harness on offer.
|
||||
* This used to select which account's stored numbers you were reading, which turned out to be the less
|
||||
* useful half of the same gesture: having established that the other account has room, what you want is to
|
||||
* use it. So the chip is now an action, and the panel below it always shows the account you are actually
|
||||
* signed into.
|
||||
*
|
||||
* The spinner is not decoration. A switch rewrites a credential on disk and changes nothing you can see —
|
||||
* without an indicator the honest reading of a click is "nothing happened", and the second click is somebody
|
||||
* checking.
|
||||
*/
|
||||
const AccountTabs = ({
|
||||
const AccountSwitcher = ({
|
||||
accounts,
|
||||
selected,
|
||||
onSelect,
|
||||
isSwitching,
|
||||
switchingTo,
|
||||
onSwitch,
|
||||
}: {
|
||||
accounts: UsageAccount[];
|
||||
selected: string;
|
||||
onSelect: (email: string) => void;
|
||||
accounts: SwitchableAccount[];
|
||||
isSwitching: boolean;
|
||||
switchingTo: string | null;
|
||||
onSwitch: (accountUuid: string) => void;
|
||||
}) => (
|
||||
<div className="flex items-center gap-1 overflow-x-auto border-t border-border px-2 py-2">
|
||||
{accounts.map((account) => (
|
||||
<button
|
||||
key={account.email}
|
||||
type="button"
|
||||
onClick={() => onSelect(account.email)}
|
||||
// The local part alone: the domain is what the accounts have in common and the part before it is
|
||||
// what tells them apart, and the panel is 320px wide.
|
||||
title={account.email}
|
||||
className={`shrink-0 cursor-pointer rounded-md px-2 py-1 text-xs font-medium transition-colors ${
|
||||
account.email === selected
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'text-muted-foreground hover:bg-foreground/10 hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{account.email.split('@')[0]}
|
||||
</button>
|
||||
))}
|
||||
{accounts.map((account) => {
|
||||
const busy = isSwitching && switchingTo === account.accountUuid;
|
||||
return (
|
||||
<button
|
||||
key={account.accountUuid}
|
||||
type="button"
|
||||
// An expired refresh token cannot be switched to, so the chip says why instead of failing on click.
|
||||
disabled={!account.usable || isSwitching || account.current}
|
||||
onClick={() => onSwitch(account.accountUuid)}
|
||||
title={
|
||||
account.current
|
||||
? `${account.emailAccount} — signed in`
|
||||
: account.usable
|
||||
? `Switch to ${account.emailAccount}${account.orgName ? ` (${account.orgName})` : ''}`
|
||||
: `${account.emailAccount} — sign-in expired, run /login`
|
||||
}
|
||||
className={`inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium transition-colors ${
|
||||
account.current
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: account.usable
|
||||
? 'cursor-pointer text-muted-foreground hover:bg-foreground/10 hover:text-foreground'
|
||||
: 'text-muted-foreground/40 line-through'
|
||||
} ${isSwitching && !busy ? 'opacity-50' : ''}`}
|
||||
>
|
||||
{busy && <Loader2 className="h-3 w-3 animate-spin" />}
|
||||
{/* The local part alone: the domain is what these accounts have in common and the part before it
|
||||
is what tells them apart, in a 320px panel. */}
|
||||
{account.emailAccount.split('@')[0]}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -193,6 +218,7 @@ export function UsagePopover({ label, harness }: UsagePopoverProps) {
|
||||
const enabled = isOwner && harness === 'claude-code';
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const { accounts: switchable, isSwitching, switchingTo, switchTo, switchError } = useAnthropicAccounts(open);
|
||||
const { accounts, allAccounts, isLoading, isRefreshing, isError } = useClaudeUsage(enabled && open);
|
||||
|
||||
/*
|
||||
@@ -204,8 +230,14 @@ export function UsagePopover({ label, harness }: UsagePopoverProps) {
|
||||
Null means "whichever is current", resolved at render — so the panel opens on the signed-in account
|
||||
without needing an effect to select it once the data arrives.
|
||||
*/
|
||||
const [selectedEmail, setSelectedEmail] = useState<string | null>(null);
|
||||
const selected = accounts.find((a) => a.email === selectedEmail) ?? accounts[0] ?? null;
|
||||
/*
|
||||
No selection state any more, deliberately.
|
||||
|
||||
The panel shows the account you are SIGNED INTO, full stop, and `useClaudeUsage` already filters to it.
|
||||
A selection would let the numbers and the chips disagree — reading one account's percentages with
|
||||
another's chip lit — and that disagreement is the exact confusion this whole change set out to remove.
|
||||
*/
|
||||
const selected = accounts[0] ?? null;
|
||||
const hidden = Math.max(0, allAccounts.length - accounts.length);
|
||||
|
||||
// The countdowns tick. Only while the panel is open — an interval running behind a closed popover is a
|
||||
@@ -250,6 +282,11 @@ export function UsagePopover({ label, harness }: UsagePopoverProps) {
|
||||
)}
|
||||
{/* Said out loud rather than silently dropped. Phase one shows one account; knowing another
|
||||
exists and is hidden on purpose is different from wondering where it went. */}
|
||||
{switchError && (
|
||||
<div className="mt-1 text-[11px] text-destructive">
|
||||
{switchError instanceof Error ? switchError.message : 'could not switch account'}
|
||||
</div>
|
||||
)}
|
||||
{hidden > 0 && (
|
||||
<div className="mt-0.5 text-[10px] text-muted-foreground">
|
||||
{hidden} other account{hidden === 1 ? '' : 's'} not shown
|
||||
@@ -272,8 +309,13 @@ export function UsagePopover({ label, harness }: UsagePopoverProps) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{accounts.length > 1 && (
|
||||
<AccountTabs accounts={accounts} selected={selected?.email ?? ''} onSelect={setSelectedEmail} />
|
||||
{switchable.length > 1 && (
|
||||
<AccountSwitcher
|
||||
accounts={switchable}
|
||||
isSwitching={isSwitching}
|
||||
switchingTo={switchingTo}
|
||||
onSwitch={(uuid) => void switchTo(uuid).catch(() => {})}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* A failure never blanks the panel: the two halves are independent server-side, so a limits problem
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
|
||||
/*
|
||||
The Anthropic accounts this machine's owner can BE, and the act of becoming one.
|
||||
|
||||
Separate from `useClaudeUsage`, which answers a different question. Usage is a measurement — how much room
|
||||
is left — and is only readable for the account currently signed in. This is identity: who could I be, and
|
||||
make me them. They meet in the popover, where the numbers belong to whichever pill is lit.
|
||||
*/
|
||||
|
||||
export type SwitchableAccount = {
|
||||
accountUuid: string;
|
||||
emailAccount: string;
|
||||
orgName: string | null;
|
||||
plan: string | null;
|
||||
capturedAt: string;
|
||||
lastUsedAt: string | null;
|
||||
refreshExpiresAt: string | null;
|
||||
/** False once the refresh token has expired: the pill has to offer `/login` rather than a switch. */
|
||||
usable: boolean;
|
||||
current: boolean;
|
||||
};
|
||||
|
||||
const KEY = ['anthropic', 'accounts'];
|
||||
|
||||
export function useAnthropicAccounts(enabled: boolean) {
|
||||
const client = useClient();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const query = useQuery<{ accounts: SwitchableAccount[] }>({
|
||||
queryKey: KEY,
|
||||
queryFn: () => client.get<{ accounts: SwitchableAccount[] }>('/claude-auth/accounts'),
|
||||
enabled,
|
||||
// Cheap — two small file reads and one SELECT — and it must not be stale, because a switch made from a
|
||||
// terminal is exactly the case this is here to notice.
|
||||
staleTime: 0,
|
||||
refetchOnWindowFocus: false,
|
||||
// A member gets a 403 here by design. Retrying it just spends three round trips arriving at the same no.
|
||||
retry: false,
|
||||
});
|
||||
|
||||
const switchTo = useMutation({
|
||||
mutationFn: (accountUuid: string) =>
|
||||
client.post<{ ok: boolean; email: string; appliesTo: string }>('/claude-auth/switch', { accountUuid }),
|
||||
onSuccess: async () => {
|
||||
// Both, and in this order. The account list decides which pill is lit; the usage numbers belong to
|
||||
// whichever account that is, and showing the old account's percentages under the new name is the one
|
||||
// outcome that would make somebody distrust the whole panel.
|
||||
await queryClient.invalidateQueries({ queryKey: KEY });
|
||||
await queryClient.invalidateQueries({ queryKey: ['chat', 'usage'] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['chat', 'usage', 'fresh'] });
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
accounts: query.data?.accounts ?? [],
|
||||
isLoading: query.isLoading,
|
||||
/** True while a switch is in flight — the panel must say so, or nobody believes it happened. */
|
||||
isSwitching: switchTo.isPending,
|
||||
switchingTo: switchTo.variables ?? null,
|
||||
switchError: switchTo.error,
|
||||
switchTo: switchTo.mutateAsync,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user