codeburn/app/renderer/vscode/summary.ts
Resham Joshi f3f6c4c3b0
feat: CodeBurn for VS Code (#1670)
* refactor(app): move the bridge handlers out of main.ts

createBridgeHandlers and the argv builders now live in
app/electron/bridge-handlers.ts with no electron import, so a host other
than Electron can run the same channel to argv mapping. main.ts keeps its
default deps and re-exports, so the desktop app and its tests are unchanged.

Two additive hooks for that host: scopeProjectFilter narrows the saved
project filter before it becomes argv, and CODEBURN_NODE_BIN runs the
bundled CLI with a named Node instead of Electron-as-Node.

* feat(app): let the renderer run inside an editor

The bridge can now say it is the VS Code host. When it does, the chord
shortcuts and their hints step aside for the editor's own, Settings hands
theme, language, default period and refresh to the editor's settings,
the top bar shows a this workspace / all projects switch, and the editor
can send a section, a period or a refresh to an open dashboard.

formatResetTime moves to lib/format.ts so the status bar and the summary
use the Plans wording. New strings are in all six locales. Nothing
changes in the desktop app.

* feat(app): build the renderer for VS Code webviews

app/vite.vscode.config.ts builds two webview entries into
vscode/dist/webview: the whole dashboard and the activity bar summary.
renderer/vscode/bridge.ts implements window.codeburn over postMessage,
forwarding only the channels in channels.ts; telemetry, update checks and
the desktop companions are answered in the webview. localStorage is
prefixed per scope so one workspace's cached views never paint in
another's, and the theme follows the editor's light, dark and high
contrast kinds through its --vscode-* tokens.

* feat(vscode): CodeBurn extension for VS Code and its forks

A status bar item with today's spend (~ when estimated) and a tooltip
with the week, the month, this workspace, the top model and plan quotas;
an activity bar summary; the desktop dashboard in an editor tab, scoped
to the open workspace; eight commands and eight settings.

The bundled CLI runs as the desktop's resident serve child through the
shared client. Current VS Code, Cursor and Antigravity ship Node 24, so
it runs on the editor's own Node; an older editor gets a system Node
22.13+ or a degraded run that says what it cannot read. A workspace
folder maps to a rooted --project the way the CLI keys sessions,
worktrees folding into their main repository.

npm run package:vscode builds the .vsix. Unit tests cover the bridge
host, status bar formatting, workspace mapping, settings and runtime
choice; test:smoke drives a real VS Code against a fixture home.

* ci, docs: build, test and package the VS Code extension

A vscode job typechecks, unit tests, packages the .vsix, runs the smoke
test in VS Code under xvfb and uploads the .vsix. docs/vscode.md covers
the architecture, the measured editor runtimes and how to test.

* fix(vscode): keep the currency setting out of workspace settings

Changing codeburn.currency runs the CLI's own currency command, which
every CodeBurn app shares, so a repository's .vscode/settings.json must
not be able to set it: the setting is application scoped now.

The smoke test also checks that the dashboard's renderer booted inside
the webview and called the host, not only that its tab opened.

* feat(vscode): version the extension 1.0.0, apart from the CLI

The extension carried the CLI's 0.9.25. It now has its own version,
1.0.0. The host passes it to the webview, and the dashboard's nav
footer, About dialog and Settings show it there instead of the
renderer's package version; Settings adds "Bundled CLI 0.9.25" beneath
it. The desktop app is unchanged. Nothing in the build or packaging
writes the extension's version from the CLI.

* fix(vscode): run the smoke test in Cursor, keep the demo shim out

Cursor 3 opens its Agents window on a fresh profile, which starts no
extension host, so the smoke run against Cursor.app hung; it now passes
--classic for Cursor. The webview build no longer copies
renderer/public/demo-shim.js, a browser demo harness, into the .vsix.

* feat(vscode): a quiet star line in the summary, and a Star on GitHub command

From the third day of use, the activity bar summary ends with the
desktop's "Enjoying CodeBurn? Star us on GitHub" line, in the same six
languages, with a close button. Clicking it or closing it hides it for
good (kept in the extension's globalState). It is never a notification.
The new "CodeBurn: Star on GitHub" command opens the repository page.
No tracking parameters, no telemetry.

* docs(vscode): marketplace screenshots in the README

Five screenshots of the extension on real data (Overview in dark and
light, the why it cost view, the status bar hover and the activity bar
summary), 1600 px wide, each with a one-line caption. They live in
vscode/media/screenshots, stay out of the .vsix, and the package script
points vsce at the raw GitHub URLs on main.

* fix(vscode): review fixes for settings trust, serve lifecycle and the tooltip

- codeburn.provider and codeburn.quotaProviders are application scoped,
  like currency, so a repository's settings cannot turn quota requests
  back on, even in Restricted Mode.
- deactivate removes the serve pid file once the child is stopped, and
  changing codeburn.nodePath restarts the serve child on the new Node.
- codeburn.currency is applied at startup when the CLI's currency
  differs, not only when the setting changes.
- The dashboard's Settings no longer shows per-plan quota switches in the
  editor, where the editor setting rewrites them on every boot; it points
  to the editor settings instead.
- Workspace and model names are escaped in the status bar tooltip.
- The README lists the dashboard actions that reach the network.
- The staged CLI drops its dependencies' tests and TypeScript sources
  (466 files, 9.9 MB to 9.2 MB).
2026-10-07 16:46:23 +02:00

175 lines
8.2 KiB
TypeScript

import { t } from '../i18n'
import { formatCount, formatResetTime, formatUsd, isEstimatedCost, setActiveCurrency, type ActiveCurrency } from '../lib/format'
import { PROVIDER_NAMES } from '../lib/providers'
import type { MenubarPayload, ProviderName, QuotaProvider } from '../lib/types'
export type Figure = { cost: number; estimated: boolean }
export type Ranked = { name: string; cost: number; estimated: boolean }
export type QuotaLine = { provider: string; plan: string | null; label: string; percent: number; resetsAt: string | null }
/** Everything the status bar, its tooltip, the sidebar and Copy summary show.
* Small and plain so the last one is cached and painted at the next startup. */
export type Summary = {
at: number
currency: ActiveCurrency
today: Figure
week: Figure | null
month: Figure | null
topModels: Ranked[]
topProjects: Ranked[]
workspace: { label: string; today: Figure; week: Figure | null } | null
quota: QuotaLine[]
optimize: { findingCount: number; savingsUSD: number } | null
}
const USD: ActiveCurrency = { code: 'USD', symbol: '$', rate: 1 }
/** The estimated share of a payload's total: the provider split carries it on
* current CLIs; the model split is the fallback for a CLI that predates that. */
function estimatedPortion(current: MenubarPayload['current']): number {
const providers = current.providerDetails?.filter(row => !row.excludedFromTotal)
if (providers?.some(row => row.estimatedCostUSD !== undefined)) {
return providers.reduce((sum, row) => sum + (row.estimatedCostUSD ?? 0), 0)
}
return (current.topModels ?? []).reduce((sum, row) => sum + (row.estimatedCostUSD ?? 0), 0)
}
/** The #1657 rule, as every other surface applies it. Needs the payload's currency active. */
export function figureOf(payload: MenubarPayload): Figure {
return { cost: payload.current.cost, estimated: isEstimatedCost(payload.current.cost, estimatedPortion(payload.current)) }
}
export function buildSummary(input: {
today: MenubarPayload
week: MenubarPayload | null
month: MenubarPayload | null
workspace: { label: string; today: MenubarPayload; week: MenubarPayload | null } | null
quota: QuotaProvider[] | null
optimize: { findingCount: number; savingsUSD: number } | null
now?: number
}): Summary {
const currency = input.today.currency ?? USD
setActiveCurrency(currency)
const ranked = input.week ?? input.today
return {
at: input.now ?? Date.now(),
currency,
today: figureOf(input.today),
week: input.week ? figureOf(input.week) : null,
month: input.month ? figureOf(input.month) : null,
topModels: (ranked.current.topModels ?? []).slice(0, 5).map(row => ({ name: row.name, cost: row.cost, estimated: isEstimatedCost(row.cost, row.estimatedCostUSD) })),
topProjects: (ranked.current.topProjects ?? []).slice(0, 5).map(row => ({ name: row.name, cost: row.cost, estimated: false })),
workspace: input.workspace
? { label: input.workspace.label, today: figureOf(input.workspace.today), week: input.workspace.week ? figureOf(input.workspace.week) : null }
: null,
quota: quotaLines(input.quota ?? []),
optimize: input.optimize,
}
}
/** One line per connected provider: its most-used window, the one that runs out first. */
export function quotaLines(quota: QuotaProvider[]): QuotaLine[] {
const lines: QuotaLine[] = []
for (const provider of quota) {
if (provider.connection !== 'connected' && provider.connection !== 'stale') continue
const windows = [provider.primary, ...provider.details].filter((w): w is NonNullable<typeof w> => w !== null)
const top = windows.reduce<typeof windows[number] | null>((best, w) => (best === null || w.percent > best.percent ? w : best), null)
if (!top) continue
lines.push({ provider: provider.provider, plan: provider.planLabel, label: top.label, percent: top.percent, resetsAt: top.resetsAt })
}
return lines
}
export function money(figure: Figure): string {
return `${figure.estimated ? '~' : ''}${formatUsd(figure.cost)}`
}
function percent(value: number): string {
return `${Math.round(value * 100)}%`
}
export type StatusBarFormat = 'cost' | 'costAndQuota' | 'workspace' | 'hidden'
export function statusText(summary: Summary | null, format: StatusBarFormat): string {
if (!summary) return '$(flame)'
setActiveCurrency(summary.currency)
const today = money(summary.today)
if (format === 'costAndQuota' && summary.quota.length > 0) {
const top = Math.max(...summary.quota.map(line => line.percent))
return `$(flame) ${today} · ${percent(top)}`
}
if (format === 'workspace' && summary.workspace) return `$(flame) ${money(summary.workspace.today)} / ${today}`
return `$(flame) ${today}`
}
function providerName(line: QuotaLine): string {
const name = PROVIDER_NAMES[line.provider as ProviderName] ?? line.provider
return line.plan ? `${name} ${line.plan}` : name
}
export function quotaText(line: QuotaLine): string {
const reset = formatResetTime(line.resetsAt)
const used = reset
? t('plans.quota.usedWithReset', { percent: Math.round(line.percent * 100), reset })
: t('plans.quota.used', { percent: Math.round(line.percent * 100) })
return `${providerName(line)} · ${line.label} · ${used}`
}
/** Names reach the tooltip from repositories and logs: keep them literal text. */
function cell(text: string): string {
return text.replace(/[\\`*_[\]()|<>!$#~]/g, '\\$&')
}
/** The status bar tooltip: plain markdown, one command link, no HTML. */
export function tooltipMarkdown(summary: Summary): string {
setActiveCurrency(summary.currency)
const rows: Array<[string, string]> = [[t('common.period.today'), money(summary.today)]]
if (summary.week) rows.push([t('common.period.week'), money(summary.week)])
if (summary.month) rows.push([t('common.period.month'), money(summary.month)])
if (summary.workspace) rows.push([t('ide.status.workspaceToday', { name: summary.workspace.label }), money(summary.workspace.today)])
const out = ['**CodeBurn**', '', '| | |', '|:--|--:|', ...rows.map(([label, value]) => `| ${cell(label)} | ${value} |`), '']
const top = summary.topModels[0]
if (top) out.push(`${t('ide.status.topModel')}: ${cell(top.name)} · ${money(top)}`, '')
if (summary.quota.length > 0) {
out.push(`**${t('shell.nav.plans')}**`, '')
for (const line of summary.quota) out.push(`- ${quotaText(line)}`)
out.push('')
}
const estimated = [summary.today, summary.week, summary.month, summary.workspace?.today, top].some(figure => figure?.estimated)
if (estimated) out.push(`_${t('shared.usd.estimated')}_`, '')
out.push(`[${t('ide.status.open')}](command:codeburn.openDashboard)`)
return out.join('\n')
}
/** Copy summary: plain text a person pastes into a chat or a standup note. */
export function summaryText(summary: Summary): string {
setActiveCurrency(summary.currency)
const lines = [`CodeBurn · ${new Date(summary.at).toLocaleDateString()}`]
lines.push(`${t('common.period.today')}: ${money(summary.today)}`)
if (summary.week) lines.push(`${t('common.period.week')}: ${money(summary.week)}`)
if (summary.month) lines.push(`${t('common.period.month')}: ${money(summary.month)}`)
if (summary.workspace) {
lines.push(`${summary.workspace.label}: ${money(summary.workspace.today)}${summary.workspace.week ? ` · ${t('common.period.week')} ${money(summary.workspace.week)}` : ''}`)
}
if (summary.topModels.length > 0) {
lines.push(`${t('ide.sidebar.topModels')}: ${summary.topModels.slice(0, 3).map(row => `${row.name} ${money(row)}`).join(', ')}`)
}
for (const line of summary.quota) lines.push(quotaText(line))
if (summary.optimize && summary.optimize.findingCount > 0) {
lines.push(`${t('shell.nav.optimize')}: ${formatCount(summary.optimize.findingCount, 'finding')} · ${t('ide.sidebar.savings', { amount: formatUsd(summary.optimize.savingsUSD) })}`)
}
return lines.join('\n')
}
/** What the activity bar view renders. */
export type SidebarState = {
status: 'loading' | 'ok' | 'error'
error: { kind: string; message: string } | null
summary: Summary | null
/** The workspace's name, or null with no folder open. */
workspaceLabel: string | null
/** Set when the CLI runs on the editor's own, too-old Node. */
runtimeNote: string | null
/** The star line at the bottom, once the extension has seen real use. */
star?: boolean
}