Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

39.2 KB
Raw Blame
import { usageDiagnosticLines } from '../lib/usageDiagnostic'
import { useEffect, useMemo, useRef, useState } from 'react'
import { UsageOrganization } from './UsageOrganization'
import { IconReload } from './icons'
import type { ClaudeUsage, ProviderUsage, RemoteAccountUsage, UsageLimit } from '@shared/types'
import { AGENT_CONFIG } from '@shared/agents/config'
import { useSettings } from '../state/settings'
import { useProjects } from '../state/projects'
import { useSshConn } from '../state/sshConn'
import {
  accountRowAction,
  dedupeProviderRows,
  providerRowKey,
  scopeFromKey,
  scopeUsage,
  usageScopeKey
} from '../lib/usageScope'
import {
  barFillPercent,
  formatResetCountdown,
  formatTimeAgo,
  heldUsageText,
  percentNumber,
  percentText,
  severityColor,
  usageFailureText
} from '../lib/usageFormat'
import {
  enabledProviders,
  hasAnyUsage,
  limitKey,
  limitLabel,
  limitShortLabel,
  primaryLimit,
  providerLabel,
  providerPillSegments
} from '@shared/usage-limits'
import { systemAccountDisplay } from '../state/workspace'
import { noteRemoteSystemEmails } from '../state/systemAccount'

/** Grace period before a hover-opened popover closes, so the pointer can cross the pill's own
 *  gap (or clip a corner en route elsewhere) without the panel flickering shut. */
const USAGE_HOVER_CLOSE_MS = 220

/** How often the collapsed pill re-asks for a MANAGED default account's snapshot. Only the system
 *  account is polled + pushed by the service; the service caches managed reads for its own
 *  debounce, so a re-ask inside that window is free. */
const DEFAULT_ACCOUNT_POLL_MS = 5 * 60 * 1000

/**
 * A single limit row in the popover: bar, "% left"/"% used", reset countdown. The bar's fill
 * honours the display mode (`barFillPercent`) so it tracks the same quantity as the number
 * beside it; its color stays keyed to the TRUE remaining percentage via `severityColor`, so
 * severity red/yellow/green never flips meaning when the mode does.
 */
function LimitRow({ limit, mode }: { limit: UsageLimit; mode: 'used' | 'remaining' | 'tokens' }) {
  const left = 100 - limit.usedPercent
  const fill = barFillPercent(limit.usedPercent, mode)
  return (
    <div className="usage-row">
      <div className="usage-row__title">
        {limitLabel(limit.kind, limit.scopeLabel)}
        {/* The server flags which window is actually gating the account right now. */}
        {limit.isActive && <span className="usage-row__active" title="Currently limiting">●</span>}
      </div>
      <div className="usage-bar">
        <div
          className="usage-bar__fill"
          style={{ width: `${fill}%`, background: severityColor(limit.severity, left) }}
        />
      </div>
      <div className="usage-row__meta">
        <span>{percentText(limit.usedPercent, mode)}</span>
        <span>{formatResetCountdown(limit.resetsAt)}</span>
      </div>
    </div>
  )
}

/**
 * The account-row affordance for issue #142 — the switch lives where the decision is made.
 * It writes `project.defaultAccountId` and nothing else: `data.accountId` is resolved once at
 * node creation and is immutable after, so the copy says "new sessions" and running sessions
 * never move. `isDefault` marks the row the project currently resolves to; `onUse` is absent
 * when there is nothing honest to offer (no active project, or a row whose account this
 * project cannot launch).
 */
function DefaultAccountMark({
  isDefault,
  onUse
}: {
  isDefault: boolean
  onUse?: () => void
}) {
  if (isDefault)
    return (
      <span
        className="usage-account__default"
        title="New Claude nodes in this project open under this account."
      >
        ✓ new sessions
      </span>
    )
  if (!onUse) return null
  return (
    <button
      type="button"
      className="usage-account__use"
      title="New Claude nodes in this project will open under this account. Running sessions keep theirs."
      onClick={onUse}
    >
      Use for new sessions
    </button>
  )
}

/** Why the bars above are old — only for numbers kept through a failed read. */
function HeldNote({ u }: { u: ClaudeUsage | ProviderUsage | null | undefined }) {
  const text = u ? heldUsageText(u) : null
  return text ? <div className="usage-popover__held">{text}</div> : null
}

/** Where a bulk move can send an account's sessions: another account on the same machine. */
export interface MoveTarget {
  id: string | undefined
  label: string
}

/** A bulk move in flight (Canvas `moveAccountSessions`): which account it empties, on which machine
 *  (`usageScopeKey`), and how many sessions it started. */
export interface AccountMoveProgress {
  from: string | undefined
  count: number
  scopeKey: string
}

/**
 * "⇄ Move N sessions" on an account row — the bulk version of a node's "Switch Claude account":
 * every Claude session on this canvas running on this account is quit, its conversation copied to
 * the picked account, and resumed there (Canvas `moveAccountSessions`). It sits where the limit is
 * read, because that is where the user learns an account is spent. Absent when there is nothing to
 * move or nowhere to move it.
 *
 * While a move runs (`moving`), the sessions it is moving still carry their OLD account until each
 * one lands, so the live count would offer them again — and a second bulk move is refused while one
 * runs. So the source row says "Moving N sessions…", and every other row's control is disabled.
 */
function MoveSessionsControl({
  count,
  targets,
  moving,
  onMove
}: {
  count: number
  targets: readonly MoveTarget[]
  /** null = no move running; 'this' = this row's account is being moved; 'other' = some other. */
  moving: null | { row: 'this' | 'other'; count: number }
  onMove: (to: MoveTarget) => void
}) {
  const [picking, setPicking] = useState(false)
  const plural = (n: number): string => `${n} ${n === 1 ? 'session' : 'sessions'}`
  if (moving?.row === 'this') {
    return (
      <span className="usage-account__move">
        <button type="button" className="usage-account__use" disabled>
          ⇄ Moving {plural(moving.count)}…
        </button>
      </span>
    )
  }
  if (count === 0 || targets.length === 0) return null
  return (
    <span className="usage-account__move">
      <button
        type="button"
        className="usage-account__use"
        aria-expanded={!moving && picking}
        disabled={!!moving}
        title={
          moving
            ? 'Another move is still running — wait for it to finish.'
            : 'Quit these sessions, move their conversations to another account and resume them there — no login needed. Busy sessions are skipped.'
        }
        onClick={() => setPicking((v) => !v)}
      >
        ⇄ Move {plural(count)}
      </button>
      {!moving && picking ? (
        <span className="usage-account__move-targets" role="group" aria-label="Move sessions to">
          {targets.map((t) => (
            <button
              key={t.id ?? 'system'}
              type="button"
              className="usage-account__use"
              onClick={() => {
                setPicking(false)
                onMove(t)
              }}
            >
              → {t.label}
            </button>
          ))}
        </span>
      ) : null}
    </span>
  )
}

/**
 * One account's limit bars under a label, for the multi-account popover. Reuses LimitRow's
 * markup — `u` is null while its on-demand fetch is in flight.
 */
function AccountUsageBlock({
  label,
  email,
  u,
  mode,
  isDefault = false,
  onUse,
  move,
  action
}: {
  label: string
  email?: string
  u: ClaudeUsage | null
  mode: 'used' | 'remaining' | 'tokens'
  isDefault?: boolean
  onUse?: () => void
  move?: React.ReactNode
  /** An action that belongs to THIS account (the system row's "Switch Claude account…"). */
  action?: React.ReactNode
}) {
  const shownEmail = u?.email ?? email
  return (
    <div className="usage-account">
      <div className="usage-account__label">
        {label}
        <DefaultAccountMark isDefault={isDefault} onUse={onUse} />
        {move}
      </div>
      {shownEmail && <div className="usage-account__email">{shownEmail}</div>}
      <UsageOrganization organization={u?.organization} email={shownEmail} />
      {u?.limits.map((l) => (
        <LimitRow key={limitKey(l)} limit={l} mode={mode} />
      ))}
      <HeldNote u={u} />
      {u && u.limits.length === 0 && (
        <div className="usage-popover__empty">
          {u.status === 'error' ? usageFailureText(u) : 'No usage data.'}
        </div>
      )}
      {!u && <div className="usage-popover__empty usage-pill__pulse">···</div>}
      {action}
    </div>
  )
}

/**
 * One SSH host's Claude identity. Carries the host explicitly: the same subscription can be
 * logged in on the desktop and on two servers, and a row that only said "Claude" would be
 * indistinguishable from the local one sitting right above it.
 *
 * An 'unavailable' row is dropped exactly like an unused provider — a host where nobody has run
 * `claude` has nothing to report, and listing it would turn "connect an SSH project" into "grow
 * a permanent empty section".
 */
function RemoteUsageBlock({
  row,
  mode,
  isDefault = false,
  onUse,
  move
}: {
  row: Extract<RemoteAccountUsage, { provider?: 'claude' }>
  mode: 'used' | 'remaining' | 'tokens'
  isDefault?: boolean
  onUse?: () => void
  move?: React.ReactNode
}) {
  if (row.usage.status === 'unavailable') return null
  const showHost = row.label !== row.hostKey
  return (
    <div className="usage-account">
      <div className="usage-account__label">
        {row.label}
        <span className="usage-account__host" title={`Read on ${row.hostKey} over SSH`}>
          {showHost ? row.hostKey : 'SSH'}
        </span>
        <DefaultAccountMark isDefault={isDefault} onUse={onUse} />
        {move}
      </div>
      {row.usage.email && <div className="usage-account__email">{row.usage.email}</div>}
      {row.usage.limits.map((l) => (
        <LimitRow key={limitKey(l)} limit={l} mode={mode} />
      ))}
      <HeldNote u={row.usage} />
      {row.usage.limits.length === 0 && (
        <div className="usage-popover__empty">
          {row.usage.status === 'error' ? usageFailureText(row.usage, 'on this host') : 'No usage data.'}
        </div>
      )}
    </div>
  )
}

/**
 * One non-Claude provider's section in the popover. Providers that aren't signed in report
 * 'unavailable' and are skipped entirely — showing an empty Codex row to someone who has never
 * run Codex is noise, not information. An 'error' provider IS shown, because that is a
 * configured provider failing and hiding it would make the popover flap between refreshes.
 */
/** AGENT_CONFIG is keyed by builtin ids; billing-only providers fall through to the shared table. */
function labelFor(provider: string): string {
  const agentLabel = (AGENT_CONFIG as Record<string, { label?: string } | undefined>)[provider]?.label
  return providerLabel(provider, agentLabel)
}

function ProviderBlock({ u, mode, hostKey }: { u: ProviderUsage; mode: 'used' | 'remaining' | 'tokens'; hostKey?: string }) {
  if (u.status === 'unavailable') return null
  const label = labelFor(u.provider)
  return (
    <div className="usage-account">
      <div className="usage-account__label">{label}
        {hostKey && <span className="usage-account__host" title={`Read on ${hostKey} over SSH`}>{hostKey} · SSH</span>}
      </div>
      {u.account && <div className="usage-account__email">{u.account}</div>}
      {u.limits.map((l) => (
        <LimitRow key={limitKey(l)} limit={l} mode={mode} />
      ))}
      {/* Numbers the service kept because the latest read failed (a Codex 429, issue #1168). */}
      <HeldNote u={u} />
      {/* One line per distinct reason (issue #912): two views failing the same way are one
          failure of this provider, not two paragraphs of the same sentence. */}
      {usageDiagnosticLines(label, u.diagnostics, u.provider).map((line) => (
        <div className="usage-popover__empty" key={line}>
          {line}
        </div>
      ))}
      {u.limits.length === 0 && !u.diagnostics?.length && (
        <div className="usage-popover__empty">
          {u.status === 'error' ? usageFailureText(u) : 'No usage data.'}
        </div>
      )}
    </div>
  )
}

/**
 * Bottom-left Claude usage pill + popover. Renders to the right of the React Flow Controls.
 * States: hidden when 'unavailable'; '···' while first-fetching; '⚠' on error w/o data;
 * last-known data shown on stale/error. Compact pill = mini-bar + one "N% label" per limit,
 * e.g. "93% 5h · 39% wk · 13% Fable" — the bar tracks whichever limit is closest to biting.
 */
export function UsageIndicator({
  overBoard = false,
  onSetDefaultAccount,
  countAccountSessions,
  onMoveSessions,
  accountMove = null
}: {
  overBoard?: boolean
  /** Writes `project.defaultAccountId` + persists (Canvas's own TabBar handler). When absent the
   *  popover is a pure readout, exactly as before issue #142. */
  onSetDefaultAccount?: (projectId: string, accountId: string | undefined) => void
  /** Claude sessions on this canvas running on an account (undefined = system), on the scoped
   *  machine. With `onMoveSessions`, turns on the rows' "Move N sessions". */
  countAccountSessions?: (accountId: string | undefined) => number
  /** Move every such session from one account to another (Canvas `moveAccountSessions`). */
  onMoveSessions?: (from: string | undefined, to: string | undefined, toLabel: string) => void
  /** The bulk move in flight, if any (Canvas owns it; see `MoveSessionsControl`). */
  accountMove?: AccountMoveProgress | null
}): JSX.Element | null {
  const [usage, setUsage] = useState<ClaudeUsage | null>(null)
  const [open, setOpen] = useState(false)
  const [refreshing, setRefreshing] = useState(false)
  const [acctUsage, setAcctUsage] = useState<Record<string, ClaudeUsage | null>>({})
  const [providers, setProviders] = useState<ProviderUsage[]>([])
  const [remote, setRemote] = useState<RemoteAccountUsage[]>([])
  const popRef = useRef<HTMLDivElement>(null)
  const closeTimerRef = useRef<number | null>(null)

  const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
  const systemLabelSetting = useSettings((s) => s.settings.systemAccountLabel)
  const hiddenProviders = useSettings((s) => s.settings.hiddenUsageProviders)
  const percentMode = useSettings((s) => s.settings.usagePercentMode)
  // Local logged-in accounts get their own popover row; skip pending logins + remote (host) ones.
  const accounts = useMemo(
    () => claudeAccounts.filter((a) => !a.pending && !a.host),
    [claudeAccounts]
  )

  // The indicator follows the ACTIVE project: on a local project it is this machine, on an SSH
  // project it is that host and nothing else. Showing every source at once is what made the panel
  // unreadable once remote hosts joined it.
  const activeProjectId = useProjects((s) => s.activeProjectId)
  const scopeHostKey = useProjects((s) =>
    usageScopeKey(s.projects.find((p) => p.id === s.activeProjectId))
  )
  const scope = useMemo(() => scopeFromKey(scopeHostKey), [scopeHostKey])

  // Issue #142 — "Use for new sessions" on the account rows. A PRIMITIVE selector on purpose
  // (see scopeHostKey above): selecting the project object would re-render the pill on every
  // canvas edit.
  const projectDefaultId = useProjects(
    (s) => s.projects.find((p) => p.id === s.activeProjectId)?.defaultAccountId
  )
  // The accounts THIS project can actually launch — the same host rule the whole panel follows
  // (local project: local accounts; SSH project: that host's). The persisted default is validated
  // against them, exactly as resolveNewNodeAccount does at node creation: a stale id (account
  // since removed) marks the System row, never a ghost.
  const eligibleAccounts = useMemo(
    () =>
      claudeAccounts.filter(
        (a) => !a.pending && (scopeHostKey ? a.host === scopeHostKey : !a.host)
      ),
    [claudeAccounts, scopeHostKey]
  )
  // The validated "Use for new sessions" account (undefined = system) — the identity the collapsed
  // pill describes. Same validation as the rows' ✓: a stale id falls back to the system account.
  const defaultAccountId =
    projectDefaultId && eligibleAccounts.some((a) => a.id === projectDefaultId)
      ? projectDefaultId
      : undefined
  const defaultAccountLabel = eligibleAccounts.find((a) => a.id === defaultAccountId)?.label

  // One rule for every row, local and remote alike — `accountRowAction` (pure, tested) decides
  // default/offer/none; this pair just turns its answer into props. Absent handler / no project =
  // pure readout, exactly as before. null = the System row (clears the override).
  const rowMark = (accountId: string | null): { isDefault: boolean; onUse?: () => void } => {
    const action = accountRowAction(accountId, eligibleAccounts, projectDefaultId)
    return {
      isDefault: action === 'default',
      onUse:
        action === 'offer' && onSetDefaultAccount && activeProjectId
          ? () => onSetDefaultAccount(activeProjectId, accountId ?? undefined)
          : undefined
    }
  }

  // The bulk move's control for one row. Targets are the OTHER accounts this project can launch on
  // this machine (the same `eligibleAccounts` rule) plus the machine's system login — never an
  // account on another machine, whose dir does not exist where these panes run.
  const moveFor = (accountId: string | null): React.ReactNode => {
    if (!countAccountSessions || !onMoveSessions) return null
    const from = accountId ?? undefined
    const systemTarget: MoveTarget = {
      id: undefined,
      label: scopeHostKey
        ? `System account (${scopeHostKey})`
        : systemAccountDisplay(systemLabelSetting, usage?.email)
    }
    const targets = [
      systemTarget,
      ...eligibleAccounts.map((a) => ({ id: a.id, label: a.label || a.email || 'Account' }))
    ].filter((t) => t.id !== from)
    return (
      <MoveSessionsControl
        count={countAccountSessions(from)}
        targets={targets}
        moving={
          accountMove
            ? {
                row:
                  accountMove.scopeKey === scopeHostKey &&
                  (accountMove.from || undefined) === (from || undefined)
                    ? 'this'
                    : 'other',
                count: accountMove.count
              }
            : null
        }
        onMove={(to) => {
          setOpen(false)
          onMoveSessions(from, to.id, to.label)
        }}
      />
    )
  }

  useEffect(() => {
    void window.nodeTerminal.usage.fetch().then(setUsage)
    return window.nodeTerminal.usage.onUpdate(setUsage)
  }, [])

  // Fetched once on mount and again whenever the popover opens (the service caches, so the
  // second call is usually free). On mount rather than popover-only because the pill itself
  // surfaces enabled providers now — and a provider the user has never signed into costs no
  // network call at all: every fetcher short-circuits to 'unavailable' on a missing credentials
  // file. So the price of asking is one failed read per unused provider, not five round-trips.
  useEffect(() => {
    let cancelled = false
    void window.nodeTerminal.usage.providers().then((ps) => {
      if (!cancelled) setProviders(ps)
    })
    return () => {
      cancelled = true
    }
  }, [open])

  // Remote (SSH host) Claude accounts, for THIS project's host only. Same cadence as
  // `providers` — mount, popover open — plus the moment the project's connection comes up
  // (`sshUp`: an SSH project is usually opened before its master is ready, and without this the
  // pill stays empty until you click it). Never polled: each row is an ssh exec plus an HTTPS
  // request made on the host, which is not a price to pay every 15 minutes for a pill nobody may
  // be looking at.
  const sshConnection = useSshConn((s) => s.byProject[activeProjectId])
  const sshUp = !!sshConnection
  const remoteScope = useRef({ activeProjectId, scopeHostKey, sshConnection })
  if (remoteScope.current.activeProjectId !== activeProjectId || remoteScope.current.scopeHostKey !== scopeHostKey ||
      remoteScope.current.sshConnection !== sshConnection) {
    remoteScope.current = { activeProjectId, scopeHostKey, sshConnection }
  }
  useEffect(() => {
    if (!scopeHostKey || !sshUp) {
      // Leaving the rows up after a switch would attribute one machine's numbers to another.
      setRemote((prev) => (prev.length ? [] : prev))
      return
    }
    let cancelled = false
    void window.nodeTerminal.usage.remote({ hostKey: scopeHostKey }).then((rows) => {
      if (cancelled) return
      setRemote(rows)
      noteRemoteSystemEmails(rows)
    })
    return () => {
      cancelled = true
    }
  }, [open, scopeHostKey, sshUp, sshConnection])

  // Fetch each account's usage on demand when the popover opens (system row uses `usage`).
  // Skipped entirely on an SSH project: those identities are not what this project spends.
  useEffect(() => {
    if (scope.kind !== 'local' || !open || accounts.length === 0) return
    let cancelled = false
    for (const a of accounts) {
      void window.nodeTerminal.usage.fetch(a.id).then((u) => {
        if (!cancelled) setAcctUsage((m) => ({ ...m, [a.id]: u }))
      })
    }
    return () => {
      cancelled = true
    }
  }, [open, accounts, scope.kind])

  // The LOCAL managed default's snapshot, kept fresh while the popover is CLOSED too — the pill
  // spells it out. (The popover's per-account fetch above only runs while open.)
  const localDefaultId = scope.kind === 'local' ? defaultAccountId : undefined
  useEffect(() => {
    if (!localDefaultId) return
    let cancelled = false
    const load = (): void => {
      void window.nodeTerminal.usage.fetch(localDefaultId).then((u) => {
        if (!cancelled) setAcctUsage((m) => ({ ...m, [localDefaultId]: u }))
      })
    }
    load()
    const timer = window.setInterval(load, DEFAULT_ACCOUNT_POLL_MS)
    return () => {
      cancelled = true
      window.clearInterval(timer)
    }
  }, [localDefaultId])

  // Close the popover on an outside click.
  useEffect(() => {
    if (!open) return
    const onDown = (e: MouseEvent): void => {
      if (popRef.current && !popRef.current.contains(e.target as Node)) setOpen(false)
    }
    window.addEventListener('mousedown', onDown)
    return () => window.removeEventListener('mousedown', onDown)
  }, [open])

  useEffect(() => () => { if (closeTimerRef.current) window.clearTimeout(closeTimerRef.current) }, [])

  // Hover opens it — the panel is a readout, so making the user click to see numbers they were
  // already looking at is a step for nothing. The popover renders INSIDE this container, so
  // travelling from the pill into it never leaves; only leaving the whole thing closes, and that
  // is delayed so a pointer clipping the corner on its way elsewhere doesn't snap it shut.
  const openNow = (): void => {
    if (closeTimerRef.current) window.clearTimeout(closeTimerRef.current)
    closeTimerRef.current = null
    setOpen(true)
  }
  const closeSoon = (): void => {
    if (closeTimerRef.current) window.clearTimeout(closeTimerRef.current)
    closeTimerRef.current = window.setTimeout(() => setOpen(false), USAGE_HOVER_CLOSE_MS)
  }

  // Settings → Usage toggles are a display choice, applied before any other rule — a hidden
  // provider is invisible here even when signed in and mid-limit. Scoping runs after them: the
  // toggles say what you never want to see, the scope says what belongs to where you are.
  const hidden = new Set(hiddenProviders)
  const scoped = scopeUsage({
    scope,
    claude: hidden.has('claude') ? null : usage,
    accounts,
    providers: providers.filter((p) => !hidden.has(p.provider)),
    // Its own switch, not Claude's: hiding the local rows must not silently take the SSH hosts
    // down with them, and vice versa.
    remote: remote.filter(r => !hidden.has(r.provider === 'codex' ? 'codex' : 'claude-remote')),
    defaultAccountId,
    defaultUsage: localDefaultId && !hidden.has('claude') ? (acctUsage[localDefaultId] ?? null) : null
  })
  const claudeUsage = scoped.claude
  const visibleProviders = scoped.providers
  const visibleRemote = scoped.remote

  // Only providers the user has actually enabled reach the pill; render whenever ANY of them
  // (Claude included) has something to say. Both rules are pure and pinned by tests — gating on
  // Claude alone, which is what this did, left a Codex-only user with no pill at all.
  const enabled = enabledProviders([...visibleProviders,
    ...visibleRemote.flatMap(r => r.provider === 'codex' ? [r.usage] : [])])
  if (!hasAnyUsage(claudeUsage, visibleProviders, visibleRemote) && scoped.pillLimits.length === 0)
    return null
  // Name the identity when the pill shows a managed account, so its numbers are never read as the
  // system account's. The system identity stays unlabelled — exactly the pill as it always was.
  const pillAccountLabel =
    scoped.pillAccountId === null
      ? null
      : scope.kind === 'local'
        ? defaultAccountLabel
        : visibleRemote.find((r) => r.provider !== 'codex' && r.accountId === scoped.pillAccountId)
            ?.label

  // On an SSH project these are the HOST's limits — same shape, same labels, read somewhere else.
  const limits = scoped.pillLimits
  const status = claudeUsage?.status ?? visibleRemote[0]?.usage.status ?? 'unavailable'
  const hasData = limits.length > 0 || enabled.length > 0
  const fetching = refreshing
  const providerError = visibleProviders.some((p) => p.status === 'error') ||
    visibleRemote.some(r => r.provider === 'codex' && r.usage.status === 'error')
  const claudeError = claudeUsage?.status === 'error' ||
    visibleRemote.some(r => r.provider !== 'codex' && r.usage.status === 'error')
  const isError = claudeError || providerError
  // The pill leads with whatever is closest to biting, so a scoped model cap that is nearly
  // exhausted can't hide behind a comfortable 5h window. Considers every enabled provider, not
  // just Claude, so an exhausted Codex window drives the bar too.
  const primary = primaryLimit([...limits, ...enabled.flatMap((p) => p.limits)])
  const updatedAt = claudeUsage?.updatedAt ?? visibleRemote[0]?.usage.updatedAt ?? null

  const refresh = async (e: React.MouseEvent): Promise<void> => {
    e.stopPropagation()
    if (refreshing) return
    setRefreshing(true)
    const requestedScope = remoteScope.current
    try {
      // ⟳ refreshes what is actually on screen. On an SSH project that is the host — forced past
      // its debounce, since this is the only way to make it re-read before the cache expires —
      // and the local snapshot is left alone rather than spending a request on rows nobody can see.
      if (scope.kind === 'ssh') {
        const rows = await window.nodeTerminal.usage
          .remote({ hostKey: scope.hostKey, force: true })
          .catch((): RemoteAccountUsage[] => [])
        if (remoteScope.current === requestedScope) setRemote(rows)
        noteRemoteSystemEmails(rows)
      } else {
        // The other providers sit behind the same debounce, so a stale failure (an expired token
        // the CLI has since renewed) would otherwise stay on screen until it runs out. Settled
        // separately: one read failing must not throw away the others' fresh answers.
        const [sys, def, ps] = await Promise.allSettled([
          window.nodeTerminal.usage.refresh(),
          localDefaultId ? window.nodeTerminal.usage.refresh(localDefaultId) : Promise.resolve(null),
          window.nodeTerminal.usage.providers(true)
        ])
        if (sys.status === 'fulfilled') setUsage(sys.value)
        if (localDefaultId && def.status === 'fulfilled' && def.value) {
          const fresh = def.value
          setAcctUsage((m) => ({ ...m, [localDefaultId]: fresh }))
        }
        if (ps.status === 'fulfilled') setProviders(ps.value)
      }
    } finally {
      setRefreshing(false)
    }
  }

  // Issue #420 — "Switch account" where the limit is displayed: opens a terminal running the
  // SYSTEM-scoped `claude /login` (createSystemLoginNode), so picking the other org is one click
  // from the panel that said you need to. Nothing changes until the user completes the login IN
  // that terminal — the CLI's own org picker + OAuth — which is why there is no confirm dialog in
  // front of it: the terminal is the confirmation surface, and the tooltip names what completing
  // it changes. LOCAL scope only: on an SSH project a system login would rewrite the HOST's
  // ~/.claude, and saying "switch account" while meaning another machine's identity is the kind of
  // ambiguity this popover exists to avoid. Hidden with the Claude provider — a switch button for
  // numbers the user chose not to see would be an orphan.
  // Issue #912: it is rendered INSIDE the block of the account it switches (the Claude block, or
  // the System row when managed accounts are listed). As a popover footer it sat under whichever
  // provider happened to be last, and read as that provider's action.
  const switchAction =
    scope.kind === 'local' && !hidden.has('claude') ? (
      <button
        type="button"
        className="usage-popover__switch"
        title={
          'Opens a terminal running `claude /login` for the system account (~/.claude). ' +
          'Completing it switches the org/account all system sessions use — running ' +
          'sessions carry on under the new one. Managed accounts keep their own logins.'
        }
        onClick={() => {
          setOpen(false)
          window.dispatchEvent(new CustomEvent('nodeterm:switch-system-account'))
        }}
      >
        ⇄ Switch Claude account…
      </button>
    ) : null
  // The single-account Claude block: its meters, its account and its action together. The
  // heading appears once another provider shares the panel, exactly as before.
  const claudeAccountShown = !!(claudeUsage?.email || claudeUsage?.organization)
  const claudeHasContent = limits.length > 0 || claudeError || claudeAccountShown

  let pillBody: JSX.Element
  if (!hasData && fetching) {
    pillBody = <span className="usage-pill__dim usage-pill__pulse">···</span>
  } else if (!hasData && isError) {
    pillBody = <span className="usage-pill__dim">⚠</span>
  } else {
    pillBody = (
      <>
        {pillAccountLabel && (
          <span
            className="usage-pill__account"
            title={
              scoped.pillAccountId === defaultAccountId
                ? 'Account used for new sessions in this project'
                : 'Account these limits belong to'
            }
          >
            {pillAccountLabel}
          </span>
        )}
        {primary && (
          <span className="usage-pill__minibar" aria-hidden>
            <span
              className="usage-pill__minibar-fill"
              style={{
                width: `${barFillPercent(primary.usedPercent, percentMode)}%`,
                background: severityColor(primary.severity, 100 - primary.usedPercent)
              }}
            />
          </span>
        )}
        {limits.map((l, i) => (
          <span key={limitKey(l)}>
            {i > 0 && <span className="usage-pill__sep">·</span>}
            <span className="usage-pill__num">
              {percentNumber(l.usedPercent, percentMode)}% {limitShortLabel(l.kind, l.scopeLabel)}
            </span>
          </span>
        ))}
        {/* One segment per enabled provider, carrying only its worst limit — a provider's full
            breakdown belongs in the popover, not in a pill that has to fit beside the canvas. */}
        {/* Cursor is the exception: all three buckets (providerPillSegments). */}
        {enabled.map((p, i) => {
          const segments = providerPillSegments(p, labelFor(p.provider))
          if (segments.length === 0) return null
          return (
            <span key={providerRowKey(p)} className="usage-pill__provider">
              {segments.map(({ limit: l, label }, j) => (
                <span key={limitKey(l)}>
                  {(limits.length > 0 || i > 0 || j > 0) && <span className="usage-pill__sep">·</span>}
                  <span className="usage-pill__num">
                    {percentNumber(l.usedPercent, percentMode)}% {label}
                  </span>
                </span>
              ))}
            </span>
          )
        })}
        {isError && hasData && <span className="usage-pill__dim">⚠</span>}
      </>
    )
  }

  return (
    <div
      className={`usage-indicator${overBoard ? ' usage-indicator--board' : ''}`}
      ref={popRef}
      onMouseEnter={openNow}
      onMouseLeave={closeSoon}
    >
      {open && (
        // `nowheel`: same reason as the session-memory panel — inside `.flow-wrap`, a plain wheel
        // would zoom the canvas ("Scroll wheel zooms") instead of scrolling the account list.
        <div className="usage-popover nowheel">
          <div className="usage-popover__head">
            <span className="usage-popover__title">✦ Usage</span>
            {/* Tracks whichever snapshot the panel is actually showing — the local poll's, or
                the host read's on an SSH project. Absent when neither has answered yet. */}
            {updatedAt !== null && (
              <span className="usage-popover__ago">Updated {formatTimeAgo(updatedAt)}</span>
            )}
          </div>
          {/* Issue #503: the account blocks SCROLL, the heading does not. Each account is a tall
              block (name + Session/Weekly/Opus meters), so past about four accounts the popover
              grew off the top of the window — the first account's header and meter were clipped
              with no way to reach them. Same rule as the session memory panel's row list: every
              row is rendered, the list scrolls. The switch action scrolls WITH its block since
              issue #912 — it belongs to the Claude/System block, which is always first. */}
          <div className="usage-popover__body">
            {/* The local Claude section belongs to a LOCAL project only. On an SSH project the
                remote blocks below carry the same limits, and rendering both would print the
                host's numbers twice under two different headings. */}
            {scope.kind === 'local' &&
              (scoped.accounts.length > 0 && claudeUsage ? (
                <>
                  <AccountUsageBlock
                    mode={percentMode}
                    label={systemAccountDisplay(systemLabelSetting, claudeUsage.email)}
                    // Avoid printing the email twice when it's already the display label.
                    email={systemLabelSetting.trim() ? (claudeUsage.email ?? undefined) : undefined}
                    u={claudeUsage}
                    {...rowMark(null)}
                    move={moveFor(null)}
                    action={switchAction}
                  />
                  {scoped.accounts.map((a) => (
                    <AccountUsageBlock
                      key={a.id}
                      mode={percentMode}
                      label={a.label}
                      email={a.email}
                      u={acctUsage[a.id] ?? null}
                      {...rowMark(a.id)}
                      move={moveFor(a.id)}
                    />
                  ))}
                </>
              ) : (
                <div className="usage-claude">
                  {/* Claude's rows are bare when it is the only provider; once others share the
                      panel they need a heading of their own to stay attributable. */}
                  {enabled.length > 0 && claudeHasContent && (
                    <div className="usage-account__label">Claude</div>
                  )}
                  {limits.map((l) => (
                    <LimitRow key={limitKey(l)} limit={l} mode={percentMode} />
                  ))}
                  <HeldNote u={claudeUsage} />
                  {/* Another provider's data must not hide a failed Claude read. Keep any
                      last-known Claude bars instead of replacing them with the empty state. */}
                  {((!hasData && !providerError) || (claudeError && limits.length === 0)) && (
                    <div className="usage-popover__empty">
                      {claudeError ? usageFailureText(claudeUsage) : 'No usage data.'}
                    </div>
                  )}
                  {/* Issue #912: the account is part of Claude's block, set like a meter row
                      under the provider heading — not a fourth peer section between Claude's
                      meters and the next provider. */}
                  {claudeAccountShown && (
                    <div className="usage-row usage-claude__account">
                      <div className="usage-row__title">Account</div>
                      {claudeUsage?.email && (
                        <div className="usage-account__email">{claudeUsage.email}</div>
                      )}
                      <UsageOrganization
                        organization={claudeUsage?.organization}
                        email={claudeUsage?.email}
                      />
                    </div>
                  )}
                  {switchAction}
                </div>
              ))}
            {/* On an SSH project these are the whole panel; the host badge is what says the numbers
                were read somewhere other than this machine. */}
            {/* The same offer on an SSH project's rows — scoped as ever: only the host's system
                identity and THIS host's managed accounts are actionable (accountRowAction). */}
            {visibleRemote.map((r) => r.provider === 'codex' ? (
              <ProviderBlock key={`codex:${r.hostKey}:${r.accountId ?? ''}`} u={r.usage} mode={percentMode} hostKey={r.hostKey} />
            ) : (
              <RemoteUsageBlock
                key={`${r.hostKey}#${r.accountId ?? ''}`}
                row={r}
                mode={percentMode}
                {...rowMark(r.accountId)}
                move={moveFor(r.accountId)}
              />
            ))}
            {scope.kind === 'ssh' && visibleRemote.length === 0 && (
              <div className="usage-popover__empty">
                No usage from this host yet — it is read once the project connects.
              </div>
            )}
            {/* U8 (owed from PR 7): Codex emits one row per account, all `provider: 'codex'`.
                Key on provider+accountId so each account renders distinctly, and reduce true
                duplicates (two settings entries → the same underlying account) to one row. */}
            {dedupeProviderRows(visibleProviders).map((p) => (
              <ProviderBlock key={providerRowKey(p)} u={p} mode={percentMode} />
            ))}
          </div>
        </div>
      )}
      {/* The SSH pill is visually identical to the local one — same labels, same bar — so the
          title is what answers "whose numbers are these?" without opening the popover. */}
      <button
        className="usage-pill"
        // Hover already opens it; the click stays for the pointer-less paths (keyboard focus,
        // touch) and as the way to dismiss it without moving the pointer away.
        onClick={() => setOpen((v) => !v)}
        onFocus={openNow}
        title={scope.kind === 'ssh' ? `Agent usage on ${scope.hostKey}` : 'Agent usage'}
      >
        <span className="usage-pill__icon">✦</span>
        <span className="usage-pill__summary">{pillBody}</span>
      </button>
      <button
        className={`usage-refresh${fetching ? ' spin' : ''}`}
        onClick={refresh}
        disabled={refreshing}
        title="Refresh usage"
      >
        <IconReload />
      </button>
    </div>
  )
}