feat(app): Settings part 2 — Plans, Export, Devices actions, theme on boot

- Plans tab: add/remove budget presets via `plan set`/`plan reset`, lists
  configured plans, links to the full Plans screen
- Export tab: format + provider + native folder picker (electron dialog)
  → runs `codeburn export`, reports the result
- Devices: real Remove (`devices rm`) + Refresh; visibility is read-only
  from `share status`; pairing shows an honest "pair from terminal" note
  instead of a dead Approve button; combine row is read-only status
- Apply the persisted theme at app startup (not only when General mounts)
- Settings gets onNavigate for the "Open Plans" link

Only one-shot, non-interactive CLI commands are wired as buttons; the
interactive share daemon and pairing flow stay honestly read-only.
This commit is contained in:
iamtoruk 2026-07-11 17:31:32 -07:00
parent 55e9fa51f6
commit 1de907ac8b
9 changed files with 231 additions and 32 deletions

View file

@ -5,6 +5,7 @@ import { describe, it, expect, vi } from 'vitest'
vi.mock('electron', () => ({
app: { name: 'CodeBurn', whenReady: () => Promise.resolve(), on: () => {}, quit: () => {} },
BrowserWindow: class {},
dialog: { showOpenDialog: vi.fn() },
ipcMain: { handle: () => {} },
Menu: { buildFromTemplate: (template: unknown) => template, setApplicationMenu: () => {} },
}))
@ -47,6 +48,10 @@ const CHANNELS = [
'codeburn:resetCurrency',
'codeburn:addAlias',
'codeburn:removeAlias',
'codeburn:removeDevice',
'codeburn:setPlan',
'codeburn:resetPlan',
'codeburn:exportData',
'codeburn:cliStatus',
] as const
@ -77,6 +82,10 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> =
{ channel: 'codeburn:resetCurrency', args: [], argv: ['currency', '--reset'] },
{ channel: 'codeburn:addAlias', args: ['unknown-model', 'priced-model'], argv: ['model-alias', 'unknown-model', 'priced-model'] },
{ channel: 'codeburn:removeAlias', args: ['unknown-model'], argv: ['model-alias', '--remove', 'unknown-model'] },
{ channel: 'codeburn:removeDevice', args: ['studio-mac'], argv: ['devices', 'rm', 'studio-mac'] },
{ channel: 'codeburn:setPlan', args: ['claude-max', 'claude'], argv: ['plan', 'set', 'claude-max', '--provider', 'claude'] },
{ channel: 'codeburn:resetPlan', args: ['cursor'], argv: ['plan', 'reset', '--provider', 'cursor'] },
{ channel: 'codeburn:exportData', args: ['json', 'all', '/tmp/codeburn-export'], argv: ['export', '-f', 'json', '-o', '/tmp/codeburn-export', '--provider', 'all'] },
]
function flattenMenuItems(items: any[]): any[] {

View file

@ -1,4 +1,4 @@
import { app, BrowserWindow, ipcMain, Menu, nativeTheme, type MenuItemConstructorOptions } from 'electron'
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, type MenuItemConstructorOptions } from 'electron'
import path from 'node:path'
import { CliError, resolveCodeburnPath, spawnCli, spawnCliAction, type ActionResult } from './cli'
@ -85,6 +85,12 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
'codeburn:resetCurrency': runAction(() => ['currency', '--reset']),
'codeburn:addAlias': runAction((from: string, to: string) => ['model-alias', from, to]),
'codeburn:removeAlias': runAction((from: string) => ['model-alias', '--remove', from]),
'codeburn:removeDevice': runAction((name: string) => ['devices', 'rm', name]),
'codeburn:setPlan': runAction((id: string, provider: string) => ['plan', 'set', id, '--provider', provider]),
'codeburn:resetPlan': runAction((provider: string) => ['plan', 'reset', '--provider', provider]),
'codeburn:exportData': runAction((format: string, provider: string, outPath: string) => [
'export', '-f', format, '-o', outPath, '--provider', provider,
]),
'codeburn:cliStatus': async () => {
const p = deps.resolveCodeburnPath()
return { ok: true, value: { found: p !== null, path: p } }
@ -97,6 +103,10 @@ function registerHandlers(): void {
for (const [channel, handler] of Object.entries(handlers)) {
ipcMain.handle(channel, (_event, ...args) => handler(...args))
}
ipcMain.handle('codeburn:chooseDirectory', async () => {
const res = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] })
return { ok: true, value: res.canceled ? null : (res.filePaths[0] ?? null) }
})
}
export function createApplicationMenuTemplate(isDev = Boolean(process.env.VITE_DEV_SERVER_URL)): MenuItemConstructorOptions[] {

View file

@ -37,6 +37,11 @@ const bridge = {
resetCurrency: () => invoke('codeburn:resetCurrency'),
addAlias: (from: string, to: string) => invoke('codeburn:addAlias', from, to),
removeAlias: (from: string) => invoke('codeburn:removeAlias', from),
removeDevice: (name: string) => invoke('codeburn:removeDevice', name),
setPlan: (id: string, provider: string) => invoke('codeburn:setPlan', id, provider),
resetPlan: (provider: string) => invoke('codeburn:resetPlan', provider),
exportData: (format: string, provider: string, outPath: string) => invoke('codeburn:exportData', format, provider, outPath),
chooseDirectory: () => invoke('codeburn:chooseDirectory'),
cliStatus: () => invoke('codeburn:cliStatus'),
platform: process.platform,
}

View file

@ -5,6 +5,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { App } from './App'
import type { DateRange, MenubarPayload, SpendFlow } from './lib/types'
const stored = new Map<string, string>()
vi.stubGlobal('localStorage', {
getItem: (key: string) => stored.get(key) ?? null,
setItem: (key: string, value: string) => stored.set(key, value),
clear: () => stored.clear(),
})
const mocks = vi.hoisted(() => ({
getOverview: vi.fn<(period: string, provider: string, range?: DateRange) => Promise<MenubarPayload>>(),
getSpendFlow: vi.fn<(period: string, provider: string, range?: DateRange) => Promise<SpendFlow>>(),
@ -117,6 +124,15 @@ describe('App shortcuts', () => {
reachableCount: 1,
},
})
localStorage.clear()
document.documentElement.removeAttribute('data-theme')
})
it('applies the persisted theme on app boot before Settings mounts', async () => {
localStorage.setItem('codeburn.theme', 'dark')
render(<App />)
await waitFor(() => expect(document.documentElement).toHaveAttribute('data-theme', 'dark'))
expect(screen.queryByRole('heading', { name: 'General' })).not.toBeInTheDocument()
})
it('switches sections with command-number shortcuts', async () => {

View file

@ -80,6 +80,13 @@ export function App() {
)
const refreshOverview = overview.refresh
useEffect(() => {
let saved: string | null = null
try { saved = globalThis.localStorage?.getItem('codeburn.theme') ?? null } catch { /* storage can be unavailable */ }
if (saved === 'light' || saved === 'dark') document.documentElement.setAttribute('data-theme', saved)
else document.documentElement.removeAttribute('data-theme')
}, [])
useEffect(() => {
if (!overview.data) return
const found = Object.keys(overview.data.current.providers)
@ -143,7 +150,7 @@ export function App() {
{section === 'plans' ? (
<Plans period={period} refreshToken={refreshToken} />
) : section === 'settings' ? (
<Settings period={period} refreshToken={refreshToken} />
<Settings period={period} refreshToken={refreshToken} onNavigate={setSection} />
) : (
<>
<TopBar

View file

@ -455,5 +455,10 @@ export interface CodeburnBridge {
resetCurrency(): Promise<ActionResult>
addAlias(from: string, to: string): Promise<ActionResult>
removeAlias(from: string): Promise<ActionResult>
removeDevice(name: string): Promise<ActionResult>
setPlan(id: string, provider: string): Promise<ActionResult>
resetPlan(provider: string): Promise<ActionResult>
exportData(format: string, provider: string, outPath: string): Promise<ActionResult>
chooseDirectory(): Promise<string | null>
cliStatus(): Promise<{ found: boolean; path: string | null; error?: string }>
}

View file

@ -3,13 +3,14 @@ import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ActionResult, AliasRow, CombinedUsage, DeviceScanResult, Identity, MenubarPayload, StatusJson } from '../lib/types'
import type { ActionResult, AliasRow, CombinedUsage, DeviceScanResult, Identity, MenubarPayload, ShareStatus, StatusJson } from '../lib/types'
import { Settings } from './Settings'
const mocks = vi.hoisted(() => ({
getIdentity: vi.fn<() => Promise<Identity>>(),
getDevices: vi.fn<(period: string) => Promise<CombinedUsage>>(),
getDevicesScan: vi.fn<() => Promise<DeviceScanResult>>(),
getShareStatus: vi.fn<() => Promise<ShareStatus>>(),
getPlans: vi.fn<(period: string) => Promise<StatusJson>>(),
getOverview: vi.fn<(period: string, provider: string) => Promise<MenubarPayload>>(),
getAliases: vi.fn<() => Promise<AliasRow[]>>(),
@ -17,6 +18,11 @@ const mocks = vi.hoisted(() => ({
resetCurrency: vi.fn<() => Promise<ActionResult>>(),
addAlias: vi.fn<(from: string, to: string) => Promise<ActionResult>>(),
removeAlias: vi.fn<(from: string) => Promise<ActionResult>>(),
removeDevice: vi.fn<(name: string) => Promise<ActionResult>>(),
setPlan: vi.fn<(id: string, provider: string) => Promise<ActionResult>>(),
resetPlan: vi.fn<(provider: string) => Promise<ActionResult>>(),
chooseDirectory: vi.fn<() => Promise<string | null>>(),
exportData: vi.fn<(format: string, provider: string, path: string) => Promise<ActionResult>>(),
}))
vi.mock('../lib/ipc', async orig => {
const actual = await orig<typeof import('../lib/ipc')>()
@ -47,24 +53,30 @@ describe('Settings', () => {
mocks.getIdentity.mockResolvedValue(identity)
mocks.getDevices.mockResolvedValue(devices)
mocks.getDevicesScan.mockResolvedValue(scan)
mocks.getPlans.mockResolvedValue({ currency: 'EUR', today: { cost: 0, savings: 0, calls: 0 }, month: { cost: 0, savings: 0, calls: 0 } })
mocks.getShareStatus.mockResolvedValue({ sharing: true, name: 'Toruk MacBook Pro', port: 9732, always: false, peers: 1, pending: [] })
mocks.getPlans.mockResolvedValue({ currency: 'EUR', today: { cost: 0, savings: 0, calls: 0 }, month: { cost: 0, savings: 0, calls: 0 }, plans: { claude: { id: 'claude-max', provider: 'claude', budget: 200, spent: 48, percentUsed: 24, status: 'under', projectedMonthEnd: 120, daysUntilReset: 19, periodStart: '2026-07-01', periodEnd: '2026-08-01' } } })
mocks.getOverview.mockResolvedValue(overview)
mocks.getAliases.mockResolvedValue([{ from: 'proxy-opus', to: 'claude-opus-4-6' }])
mocks.setCurrency.mockResolvedValue(actionOk)
mocks.resetCurrency.mockResolvedValue(actionOk)
mocks.addAlias.mockResolvedValue(actionOk)
mocks.removeAlias.mockResolvedValue(actionOk)
mocks.removeDevice.mockResolvedValue(actionOk)
mocks.setPlan.mockResolvedValue(actionOk)
mocks.resetPlan.mockResolvedValue(actionOk)
mocks.chooseDirectory.mockResolvedValue('/Users/toruk/Exports')
mocks.exportData.mockResolvedValue(actionOk)
localStorage.clear()
document.documentElement.removeAttribute('data-theme')
})
it('switches panes from the rail and keeps minimal placeholders honest', async () => {
it('switches panes from the rail and renders the completed Plans pane', async () => {
const user = userEvent.setup()
render(<Settings period="month" />)
expect(screen.getByRole('heading', { name: 'General' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Plans' }))
expect(screen.getByRole('heading', { name: 'Plans' })).toBeInTheDocument()
expect(screen.getByText('Wired up in the next pass.')).toBeInTheDocument()
expect((await screen.findAllByText('Claude Max 20x')).length).toBeGreaterThan(0)
})
it('shows current currency and sends currency changes to the CLI', async () => {
@ -111,20 +123,52 @@ describe('Settings', () => {
expect(mocks.removeAlias).toHaveBeenCalledWith('proxy-opus')
})
it('renders device identity, scan results, paired devices, and Part 2 affordances', async () => {
it('lists, removes, and adds plans through the action bridge', async () => {
const user = userEvent.setup()
const { container } = render(<Settings period="month" />)
vi.spyOn(window, 'confirm').mockReturnValue(true)
render(<Settings period="month" />)
await user.click(screen.getByRole('button', { name: 'Plans' }))
expect((await screen.findAllByText('Claude Max 20x')).length).toBeGreaterThan(0)
expect(screen.getByText('$200/month · claude · 24% used')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Remove' }))
expect(mocks.resetPlan).toHaveBeenCalledWith('claude')
await user.selectOptions(screen.getByLabelText('Add a plan'), 'cursor-pro')
await user.click(screen.getByRole('button', { name: 'Add' }))
expect(mocks.setPlan).toHaveBeenCalledWith('cursor-pro', 'cursor')
})
it('chooses an export folder and exports the selected format and provider', async () => {
const user = userEvent.setup()
render(<Settings period="month" />)
await user.click(screen.getAllByRole('button', { name: 'Export' }).at(-1)!)
await user.click(screen.getByRole('button', { name: 'Choose folder…' }))
expect(mocks.chooseDirectory).toHaveBeenCalledOnce()
expect(await screen.findByText('/Users/toruk/Exports')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'JSON' }))
await user.selectOptions(screen.getByLabelText('Provider'), 'claude')
await user.click(screen.getAllByRole('button', { name: 'Export' }).at(-1)!)
expect(mocks.exportData).toHaveBeenCalledWith('json', 'claude', '/Users/toruk/Exports')
expect(await screen.findByText('Exported to /Users/toruk/Exports')).toBeInTheDocument()
})
it('renders real device status and removes paired devices without fake pairing controls', async () => {
const user = userEvent.setup()
vi.spyOn(window, 'confirm').mockReturnValue(true)
render(<Settings period="month" />)
await user.click(screen.getByRole('button', { name: 'Devices' }))
expect(await screen.findByText('Toruk MacBook Pro')).toBeInTheDocument()
expect(screen.getByText('Visible on the local network as Toruk MacBook Pro.local')).toBeInTheDocument()
expect(screen.getByText('Local device name: Toruk MacBook Pro')).toBeInTheDocument()
expect(await screen.findByText('Mac Studio')).toBeInTheDocument()
expect(screen.getByText('wants to pair · fingerprint 7F:2A:…:C4')).toBeInTheDocument()
expect(screen.getByText('fingerprint 7F:2A:…:C4')).toBeInTheDocument()
expect(await screen.findByText('toruk-mini')).toBeInTheDocument()
expect(screen.getByText('34 sessions · $41.20 this month')).toBeInTheDocument()
expect(screen.getByText('Visibility: on')).toBeInTheDocument()
expect(screen.getByText('Approve')).toBeInTheDocument()
expect(screen.getByText('Pull now')).toBeInTheDocument()
expect(container.querySelector('.tglon')).toBeInTheDocument()
expect(screen.getByText('Visible')).toBeInTheDocument()
expect(screen.getByText(/pairing is interactive/)).toBeInTheDocument()
expect(screen.queryByText('Approve')).not.toBeInTheDocument()
expect(screen.queryByText('Pull now')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Remove' }))
expect(mocks.removeDevice).toHaveBeenCalledWith('toruk-mini')
expect(screen.getByText('Combined view active · 2 devices')).toBeInTheDocument()
})
it('excludes already-paired scans and renders empty device states', async () => {

View file

@ -3,14 +3,26 @@ import { useEffect, useState } from 'react'
import { Hint } from '../components/Hint'
import { CliErrorText, cliErrorDisplay } from '../components/CliErrorPanel'
import { Panel } from '../components/Panel'
import type { Section } from '../components/Sidebar'
import { usePolled } from '../hooks/usePolled'
import { formatUsd } from '../lib/format'
import { codeburn } from '../lib/ipc'
import type { ActionResult, AliasRow, CliError, CombinedUsage, DeviceScanResult, Identity, MenubarPayload, Period, StatusJson } from '../lib/types'
import type { ActionResult, AliasRow, CliError, CombinedUsage, DeviceScanResult, Identity, JsonPlanSummary, MenubarPayload, Period, PlanId, PlanProvider, ShareStatus, StatusJson } from '../lib/types'
type Pane = 'general' | 'providers' | 'aliases' | 'plans' | 'devices' | 'export' | 'privacy'
type Theme = 'system' | 'light' | 'dark'
type PlanPreset = { id: Exclude<PlanId, 'custom' | 'none'>; label: string; provider: Exclude<PlanProvider, 'all' | 'codex'> }
const PLAN_PRESETS: PlanPreset[] = [
{ id: 'claude-pro', label: 'Claude Pro', provider: 'claude' },
{ id: 'claude-max', label: 'Claude Max 20x', provider: 'claude' },
{ id: 'claude-max-5x', label: 'Claude Max 5x', provider: 'claude' },
{ id: 'cursor-pro', label: 'Cursor Pro', provider: 'cursor' },
{ id: 'supergrok', label: 'SuperGrok', provider: 'grok' },
{ id: 'supergrok-heavy', label: 'SuperGrok Heavy', provider: 'grok' },
]
function readSetting(key: string): string | null {
try { return globalThis.localStorage?.getItem(key) ?? null } catch { return null }
}
@ -43,11 +55,8 @@ function shortFingerprint(fingerprint: string): string {
return `${parts[0]}:${parts[1]}:…:${parts[parts.length - 1]}`
}
export function Settings({ period, refreshToken = 0 }: { period: Period; refreshToken?: number }) {
export function Settings({ period, refreshToken = 0, onNavigate }: { period: Period; refreshToken?: number; onNavigate?: (section: Section) => void }) {
const [pane, setPane] = useState<Pane>('general')
const identity = usePolled<Identity>(() => codeburn.getIdentity(), [refreshToken])
const scan = usePolled<DeviceScanResult>(() => codeburn.getDevicesScan(), [refreshToken])
const devices = usePolled<CombinedUsage>(() => codeburn.getDevices(period), [period, refreshToken])
return (
<>
@ -64,9 +73,9 @@ export function Settings({ period, refreshToken = 0 }: { period: Period; refresh
{pane === 'general' && <GeneralPane period={period} refreshToken={refreshToken} />}
{pane === 'providers' && <ProvidersPane period={period} refreshToken={refreshToken} />}
{pane === 'aliases' && <AliasesPane refreshToken={refreshToken} />}
{pane === 'plans' && <PlaceholderPane title="Plans" subtitle="Set a monthly budget plan per provider." />}
{pane === 'devices' && <DevicesPane identity={identity} scan={scan} devices={devices} period={period} />}
{pane === 'export' && <PlaceholderPane title="Export" subtitle="Save your usage as CSV or JSON." />}
{pane === 'plans' && <PlansPane period={period} refreshToken={refreshToken} onNavigate={onNavigate} />}
{pane === 'devices' && <DevicesPane period={period} refreshToken={refreshToken} />}
{pane === 'export' && <ExportPane period={period} refreshToken={refreshToken} />}
{pane === 'privacy' && <PrivacyPane />}
</main>
</div>
@ -159,12 +168,93 @@ function AliasesPane({ refreshToken }: { refreshToken: number }) {
</section>
}
function PlaceholderPane({ title, subtitle }: { title: string; subtitle: string }) {
return <section className="set-p on"><div><h3 className="set-h">{title}</h3><p className="set-sub">{subtitle}</p></div><p className="set-cap">Wired up in the next pass.</p></section>
function planSummaries(status: StatusJson): JsonPlanSummary[] {
if (status.plans) return Object.values(status.plans).filter((plan): plan is JsonPlanSummary => Boolean(plan))
return status.plan ? [status.plan] : []
}
function DevicesPane({ identity, scan, devices, period }: { identity: ReturnType<typeof usePolled<Identity>>; scan: ReturnType<typeof usePolled<DeviceScanResult>>; devices: ReturnType<typeof usePolled<CombinedUsage>>; period: Period }) {
return <section className="set-p on"><div><h3 className="set-h">Devices</h3><p className="set-sub">Combine usage across your machines.</p></div><ThisDevicePanel identity={identity} /><DiscoveredPanel scan={scan} /><PairedPanel devices={devices} period={period} /></section>
function PlansPane({ period, refreshToken, onNavigate }: { period: Period; refreshToken: number; onNavigate?: (section: Section) => void }) {
const [nonce, setNonce] = useState(0)
const plans = usePolled<StatusJson>(() => codeburn.getPlans(period), [period, refreshToken, nonce])
const [presetId, setPresetId] = useState(PLAN_PRESETS[0]!.id)
const [message, setMessage] = useState<{ text: string; error: boolean } | null>(null)
const configured = plans.data ? planSummaries(plans.data) : []
const finish = (result: ActionResult) => {
setMessage({ text: result.ok ? (result.stdout.trim() || 'Plan updated') : (result.stderr || 'Plan action failed'), error: !result.ok })
if (result.ok) setNonce(value => value + 1)
}
const remove = (plan: JsonPlanSummary) => {
if (!window.confirm(`Remove the ${plan.provider} plan?`)) return
void codeburn.resetPlan(plan.provider).then(finish)
}
const add = () => {
const preset = PLAN_PRESETS.find(item => item.id === presetId)!
void codeburn.setPlan(preset.id, preset.provider).then(finish)
}
return <section className="set-p on">
<div><h3 className="set-h">Plans</h3><p className="set-sub">Set a monthly budget plan per provider. codeburn compares it to your API-equivalent spend.</p></div>
<div className="card">
<div className="about-sec">
{plans.error ? <SettingsErrorText error={plans.error} /> : !plans.data ? <p className="set-cap">Loading plans…</p> : configured.length === 0 ? <p className="set-cap">No plans configured.</p> : configured.map(plan => <div className="about-row" key={plan.provider}><span className="tx">{PLAN_PRESETS.find(item => item.id === plan.id)?.label ?? plan.id}<small>${plan.budget}/month · {plan.provider} · {plan.percentUsed}% used</small></span><span className="r"><button className="btnp" onClick={() => remove(plan)}>Remove</button></span></div>)}
</div>
<div className="about-sec set-last-sec">
<div className="about-row"><label className="tx" htmlFor="settings-plan-preset">Add a plan</label><span className="r"><select id="settings-plan-preset" className="set-input" value={presetId} onChange={event => setPresetId(event.target.value as PlanPreset['id'])}>{PLAN_PRESETS.map(preset => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select><button className="btnp btnp-primary" onClick={add}>Add</button></span></div>
{message && <p className={message.error ? 'set-action-msg error' : 'set-action-msg'}>{message.text}</p>}
</div>
</div>
<p className="set-cap">Presets: Claude Pro, Claude Max 20x, Claude Max 5x, Cursor Pro, SuperGrok, and SuperGrok Heavy. <button className="set-text-button" onClick={() => onNavigate?.('plans')}>Open Plans →</button></p>
</section>
}
function ExportPane({ period, refreshToken }: { period: Period; refreshToken: number }) {
const overview = usePolled<MenubarPayload>(() => codeburn.getOverview(period, 'all'), [period, refreshToken])
const [format, setFormat] = useState<'csv' | 'json'>('csv')
const [provider, setProvider] = useState('all')
const [destination, setDestination] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [message, setMessage] = useState<{ text: string; error: boolean } | null>(null)
const providers = Object.keys(overview.data?.current.providers ?? {})
const chooseDirectory = async () => {
const selected = await codeburn.chooseDirectory()
if (selected) setDestination(selected)
}
const exportNow = async () => {
if (!destination) return
setExporting(true)
setMessage(null)
try {
const result = await codeburn.exportData(format, provider, destination)
setMessage({ text: result.ok ? `Exported to ${destination}` : (result.stderr || 'Export failed'), error: !result.ok })
} finally {
setExporting(false)
}
}
return <section className="set-p on">
<div><h3 className="set-h">Export</h3><p className="set-sub">Save your usage as CSV or JSON. Everything stays on your machine.</p></div>
<div className="card">
<div className="about-sec">
<div className="about-row"><span className="tx">Format</span><span className="r"><span className="seg"><button className={format === 'csv' ? 'on' : undefined} onClick={() => setFormat('csv')}>CSV</button><button className={format === 'json' ? 'on' : undefined} onClick={() => setFormat('json')}>JSON</button></span></span></div>
<div className="about-row"><label className="tx" htmlFor="settings-export-provider">Provider</label><span className="r"><select id="settings-export-provider" className="set-input" value={provider} onChange={event => setProvider(event.target.value)}><option value="all">All providers</option>{providers.map(value => <option value={value} key={value}>{value.charAt(0).toUpperCase() + value.slice(1)}</option>)}</select></span></div>
<div className="about-row"><span className="tx">Destination</span><span className="r set-export-destination"><span className="set-mono">{destination ?? 'Choose a folder…'}</span><button className="btnp" onClick={() => void chooseDirectory()}>Choose folder…</button></span></div>
</div>
<div className="about-sec set-last-sec"><div className="about-row"><span className="tx" /><span className="r"><button className="btnp btnp-primary" disabled={!destination || exporting} onClick={() => void exportNow()}>{exporting ? 'Exporting…' : 'Export'}</button></span></div>{message && <p className={message.error ? 'set-action-msg error' : 'set-action-msg'}>{message.text}</p>}</div>
</div>
<p className="set-cap">CSV writes a folder (summary, daily, models, projects, sessions, tools, mcp). JSON writes one file (schema codeburn.export.v2).</p>
</section>
}
function DevicesPane({ period, refreshToken }: { period: Period; refreshToken: number }) {
const [nonce, setNonce] = useState(0)
const identity = usePolled<Identity>(() => codeburn.getIdentity(), [refreshToken])
const shareStatus = usePolled<ShareStatus>(() => codeburn.getShareStatus(), [refreshToken])
const scan = usePolled<DeviceScanResult>(() => codeburn.getDevicesScan(), [refreshToken, nonce])
const devices = usePolled<CombinedUsage>(() => codeburn.getDevices(period), [period, refreshToken, nonce])
const refresh = () => setNonce(value => value + 1)
return <section className="set-p on"><div><h3 className="set-h">Devices</h3><p className="set-sub">Combine usage across your machines.</p></div><ThisDevicePanel identity={identity} shareStatus={shareStatus} /><DiscoveredPanel scan={scan} /><PairedPanel devices={devices} period={period} onRefresh={refresh} /></section>
}
function PrivacyPane() {
@ -179,19 +269,28 @@ function PrivacyClaim({ title, detail, icon }: { title: string; detail: string;
return <div className="set-claim"><svg viewBox="0 0 24 24" aria-hidden="true">{icon}</svg><div><div className="set-claim-t">{title}</div><div className="set-claim-d">{detail}</div></div></div>
}
function ThisDevicePanel({ identity }: { identity: ReturnType<typeof usePolled<Identity>> }) {
return <Panel title="This device">{identity.data ? <div className="li"><div className="lx"><b>{identity.data.name}</b><span>Visible on the local network as {identity.data.name}.local</span><span>{identity.data.fingerprint}</span></div><span className="btn btn-s" aria-disabled="true">Visibility: on</span></div> : identity.error ? <SettingsErrorText error={identity.error} /> : <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>Reading this device identity…</p>}</Panel>
function ThisDevicePanel({ identity, shareStatus }: { identity: ReturnType<typeof usePolled<Identity>>; shareStatus: ReturnType<typeof usePolled<ShareStatus>> }) {
const status = shareStatus.data ? <span className="set-status"><span className={shareStatus.data.sharing ? 'set-dot ok' : 'set-dot'} />{shareStatus.data.sharing ? 'Visible' : 'Not sharing'}</span> : null
return <Panel title="This device" right={status}>{identity.data ? <div className="li"><div className="lx"><b>{identity.data.name}</b><span>Local device name: {identity.data.name}</span><span>{identity.data.fingerprint}</span></div></div> : identity.error ? <SettingsErrorText error={identity.error} /> : <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>Reading this device identity…</p>}{shareStatus.error && <SettingsErrorText error={shareStatus.error} />}</Panel>
}
function DiscoveredPanel({ scan }: { scan: ReturnType<typeof usePolled<DeviceScanResult>> }) {
const found = scan.data?.found.filter(device => !device.paired) ?? []
return <Panel title="Discovered nearby" right={scan.loading ? 'listening…' : undefined}>{!scan.data && scan.error ? <SettingsErrorText error={scan.error} /> : !scan.data ? <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>listening…</p> : found.length === 0 ? <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>No nearby devices found.</p> : found.map(device => <div className="li" key={`${device.host}:${device.port}:${device.fingerprint}`}><div className="lx"><b>{device.name}</b><span className="hot">wants to pair · fingerprint {shortFingerprint(device.fingerprint)}</span></div><span className="btn btn-p" aria-disabled="true">Approve</span></div>)}</Panel>
return <Panel title="Discovered nearby" right={scan.loading ? 'listening…' : undefined}>{!scan.data && scan.error ? <SettingsErrorText error={scan.error} /> : !scan.data ? <p className="set-cap">listening…</p> : found.length === 0 ? <p className="set-cap">No nearby devices found.</p> : found.map(device => <div className="li" key={`${device.host}:${device.port}:${device.fingerprint}`}><div className="lx"><b>{device.name}</b><span>fingerprint {shortFingerprint(device.fingerprint)}</span></div></div>)}<p className="set-cap set-device-caption">To pair a device, run <code>codeburn devices add</code> in a terminal — pairing is interactive (approve on the other device).</p></Panel>
}
function PairedPanel({ devices, period }: { devices: ReturnType<typeof usePolled<CombinedUsage>>; period: Period }) {
function PairedPanel({ devices, period, onRefresh }: { devices: ReturnType<typeof usePolled<CombinedUsage>>; period: Period; onRefresh: () => void }) {
const [error, setError] = useState('')
const paired = devices.data?.perDevice.filter(device => !device.local) ?? []
const deviceScope = devices.data ? `· ${devices.data.combined.deviceCount} devices` : '· paired devices'
return <Panel title="Paired">{!devices.data && devices.error ? <SettingsErrorText error={devices.error} /> : !devices.data ? <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>Loading paired devices…</p> : paired.length === 0 ? <p style={{ color: 'var(--t3)', margin: 0, fontSize: 12 }}>No paired devices yet.</p> : paired.map(device => <div className="li" key={device.id}><div className="lx"><b>{device.name}</b><span>{device.sessions.toLocaleString('en-US')} sessions · {formatUsd(device.cost)} {periodLabel(period)}</span></div><span className="btn btn-s" aria-disabled="true">Pull now</span></div>)}<div className="li"><div className="lx"><b>Combine usage from paired devices</b><span>scope captions gain “{deviceScope}” when on</span></div><span className="tglon" aria-disabled="true" /></div></Panel>
const remove = (name: string) => {
if (!window.confirm(`Remove paired device ${name}?`)) return
void codeburn.removeDevice(name).then(result => {
if (!result.ok) { setError(result.stderr || 'Unable to remove device'); return }
setError('')
onRefresh()
})
}
return <Panel title="Paired devices" right={<button className="set-text-button" onClick={onRefresh}>Refresh</button>}>{!devices.data && devices.error ? <SettingsErrorText error={devices.error} /> : !devices.data ? <p className="set-cap">Loading paired devices…</p> : paired.length === 0 ? <p className="set-cap">No paired devices yet.</p> : paired.map(device => <div className="li" key={device.id}><div className="lx"><b>{device.name}</b><span>{device.sessions.toLocaleString('en-US')} sessions · {formatUsd(device.cost)} {periodLabel(period)}</span></div><button className="btnp" onClick={() => remove(device.name)}>Remove</button></div>)}{devices.data && devices.data.combined.deviceCount > 1 && <div className="li"><div className="lx"><b>Combined view active · {devices.data.combined.deviceCount} devices</b></div></div>}{error && <p className="set-action-msg error">{error}</p>}</Panel>
}
function SettingsErrorText({ error }: { error: CliError }) {

View file

@ -232,6 +232,10 @@ body { overflow: hidden; background: var(--bg); color: var(--ink); }
.set-text-button { padding: 0; border: 0; background: transparent; color: var(--accent); font: inherit; font-size: 11.5px; cursor: pointer; }
.set-action-msg { margin: 6px 0 0; color: var(--ok); font-size: 11.5px; }
.set-action-msg.error { color: var(--bad); }
.set-export-destination { min-width: 0; }
.set-export-destination .set-mono { max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.set-device-caption { margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--line2); }
.set-device-caption code { color: var(--ink); font-family: var(--mono); }
.tgl { width: 30px; height: 18px; border-radius: 9px; background: var(--line); position: relative; flex: 0 0 auto; }
.tgl.on { background: var(--accent); }
.tgl::after { content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px; border-radius: 50%; background: #fff; }