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.

6.0 KB
Raw Blame
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { DEFAULT_SETTINGS, type ClaudeUsage, type ProviderUsage, type UsageLimit } from '@shared/types'
import { useSettings } from '../state/settings'
import { UsageIndicator } from './UsageIndicator'

const limit: UsageLimit = {
  kind: 'session', group: 'session', usedPercent: 37, severity: null,
  resetsAt: null, windowMinutes: 300, scopeLabel: null, isActive: false
}
const snapshot = (status: ClaudeUsage['status'], limits: UsageLimit[] = []): ClaudeUsage => ({
  status, limits, session: null, weekly: null, email: null, updatedAt: 0
})

let host: HTMLDivElement
let root: Root
let update: (u: ClaudeUsage) => void

beforeEach(() => {
  host = document.createElement('div')
  document.body.appendChild(host)
  root = createRoot(host)
  useSettings.setState({ settings: { ...DEFAULT_SETTINGS, usagePercentMode: 'remaining' } })
})

afterEach(() => {
  act(() => root.unmount())
  host.remove()
  useSettings.setState({ settings: DEFAULT_SETTINGS })
  vi.unstubAllGlobals()
})

async function open(system: ClaudeUsage, account?: ClaudeUsage | 'pending', providers: ProviderUsage[] = []) {
  if (account) useSettings.setState({ settings: {
    ...DEFAULT_SETTINGS, usagePercentMode: 'remaining',
    claudeAccounts: [{ id: 'work', label: 'Work', createdAt: 0 }]
  } })
  vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
  // No credentials, network, or running sessions: exercise the real component using bridge snapshots.
  vi.stubGlobal('nodeTerminal', { usage: {
    fetch: async (id?: string) => id
      ? account === 'pending' ? new Promise<ClaudeUsage>(() => {}) : account
      : system,
    providers: async () => providers,
    onUpdate: (listener: typeof update) => { update = listener; return () => {} }
  } })
  await act(async () => root.render(<UsageIndicator />))
  await act(async () => host.querySelector('.usage-indicator')!.dispatchEvent(
    new MouseEvent('mouseover', { bubbles: true })
  ))
}

describe('Claude usage failure readout', () => {
  it('distinguishes failed system and managed account reads from empty data', async () => {
    await open(snapshot('error'), snapshot('error'))
    expect(host.querySelectorAll('.usage-popover__empty')).toHaveLength(2)
    for (const row of host.querySelectorAll('.usage-popover__empty')) {
      expect(row.textContent).toBe('Could not read usage.')
    }
  })

  it.each(['ok', 'fetching', 'unavailable'] as const)('keeps the empty account wording for %s', async (status) => {
    await open(snapshot('ok', [limit]), snapshot(status))
    expect(host.querySelector('.usage-popover__empty')?.textContent).toBe('No usage data.')
  })

  it('keeps the loading pulse while the managed account has no snapshot', async () => {
    await open(snapshot('ok', [limit]), 'pending')
    expect(host.querySelector('.usage-popover__empty.usage-pill__pulse')?.textContent).toBe('···')
  })

  it('preserves stale limit bars for both system and managed accounts', async () => {
    await open(snapshot('ok', [limit]), snapshot('error', [limit]))
    await act(async () => update(snapshot('error', [limit])))
    expect(host.querySelectorAll('.usage-row')).toHaveLength(2)
    expect(host.querySelector('.usage-popover__empty')).toBeNull()
    for (const row of host.querySelectorAll('.usage-row')) expect(row.textContent).toContain('63%')
  })

  it('shows the failure without any managed accounts', async () => {
    await open(snapshot('error'))
    expect(host.querySelector('.usage-popover__empty')?.textContent).toBe('Could not read usage.')
  })

  it('still attributes the Claude failure when another provider has data', async () => {
    await open(snapshot('error'), undefined, [{ provider: 'codex', account: null, status: 'ok', limits: [limit], updatedAt: 0 }])
    expect(host.querySelector('.usage-popover__empty')?.textContent).toBe('Could not read usage.')
    expect(host.querySelector('.usage-claude > .usage-account__label')?.textContent).toBe('Claude')
    expect(host.querySelectorAll('.usage-row')).toHaveLength(1)
  })

  it('names a rate limit instead of the generic failure, for system and managed rows', async () => {
    await open({ ...snapshot('error'), rateLimited: true }, { ...snapshot('error'), rateLimited: true })
    const rows = host.querySelectorAll('.usage-popover__empty')
    expect(rows).toHaveLength(2)
    for (const row of rows) {
      expect(row.textContent).toBe('Rate limited by the usage endpoint (HTTP 429) — try again in a few minutes.')
    }
  })

  it('says why kept bars are old, and how old', async () => {
    const kept = { ...snapshot('error', [limit]), rateLimited: true, updatedAt: Date.now() - 12 * 60_000 }
    await open(kept, kept)
    expect(host.querySelectorAll('.usage-row')).toHaveLength(2)
    const notes = host.querySelectorAll('.usage-popover__held')
    expect(notes).toHaveLength(2)
    for (const note of notes) {
      expect(note.textContent).toBe('Latest read was rate limited (HTTP 429) — showing numbers from 12m ago.')
    }
  })

  it('carries no held note on a good read', async () => {
    await open(snapshot('ok', [limit]))
    expect(host.querySelector('.usage-popover__held')).toBeNull()
  })

  it('preserves stale bars in the single-account view', async () => {
    await open(snapshot('error', [limit]))
    expect(host.querySelectorAll('.usage-row')).toHaveLength(1)
    expect(host.querySelector('.usage-popover__empty')).toBeNull()
  })
})

describe('Usage popover wheel', () => {
  it('owns the wheel, so a plain wheel scrolls the account list instead of zooming the canvas', async () => {
    // Mounted inside `.flow-wrap`, whose capture-phase wheel listener (Canvas.tsx) zooms every
    // plain wheel when Settings → "Scroll wheel zooms" is on, unless the target is under `.nowheel`.
    await open(snapshot('ok', [limit]))
    expect(host.querySelector('.usage-popover')?.closest('.nowheel')).not.toBeNull()
    expect(host.querySelector('.usage-popover__body')?.closest('.nowheel')).not.toBeNull()
  })
})