codeburn/app/renderer/lib/format.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

147 lines
6.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { localeTag, t } from '../i18n'
export type ActiveCurrency = { code: string; symbol: string; rate: number }
// Single source of truth for display currency. App.tsx sets it from the overview
// payload; every formatUsd/formatConverted call site then converts for free.
// Defaults to USD so the first render (before the payload arrives) is correct.
let activeCurrency: ActiveCurrency = { code: 'USD', symbol: '$', rate: 1 }
export function setActiveCurrency(currency: ActiveCurrency): void {
activeCurrency = currency
}
/** Raw-USD input: multiplies by the active FX rate, then prefixes the symbol. */
export function formatUsd(n: number): string {
return formatUsdWithCurrency(n, activeCurrency)
}
/** Same rule as the CLI (src/format.ts isEstimatedCost): a row is marked `~`
* once its estimated portion is at least 1% of its cost, unless the amount
* reads as zero in the active currency. */
export function isEstimatedCost(cost: number, estimatedCost: number | undefined): boolean {
const estimated = estimatedCost ?? 0
return estimated > 0 && estimated >= cost * 0.01 && /[1-9]/.test(formatUsd(cost))
}
/** Raw-USD input formatted against an explicit payload currency. This keeps a
* persisted exact snapshot correct on its very first paint, before App's
* global active-currency effect has had a chance to run. */
export function formatUsdWithCurrency(n: number, currency: ActiveCurrency): string {
return `${currency.symbol}${(n * currency.rate).toLocaleString(localeTag(), { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}
/** a − b as displayed: the difference of the two rounded figures, so shown numbers add up. */
export function formatUsdDifference(a: number, b: number): string {
const shown = (n: number) => Number((n * activeCurrency.rate).toFixed(2))
return formatConverted(shown(a) - shown(b))
}
/**
* Already-converted input (CLI-side convertCost values, e.g. plan budgets): only
* prefixes the active symbol and formats the magnitude — never re-applies the rate.
*/
export function formatConverted(n: number): string {
return `${activeCurrency.symbol}${n.toLocaleString(localeTag(), { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
}
/** Shorten filesystem and CLI-mangled project paths to their useful trailing segments. */
export function shortenProjectPath(value: string, maxSegments = 3): string {
const trimmed = value.trim()
const pathDelimited = /[\\/]/.test(trimmed)
const parts = trimmed.split(pathDelimited ? /[\\/]+/ : /-+/).filter(Boolean)
let displayParts = parts.slice(-Math.max(1, maxSegments))
// A tail rooted directly under a home directory starts with the user name,
// which adds noise rather than useful project context.
const precedingPart = parts.at(-(displayParts.length + 1))
if (displayParts.length > 1 && /^(users?|home)$/i.test(precedingPart ?? '')) {
displayParts = displayParts.slice(1)
}
if (/^(projects|src|config)$/i.test(displayParts[0] ?? '')) {
displayParts[0] = displayParts[0].toLowerCase()
}
return displayParts.join('/') || trimmed
}
/** "1 session" / "2,048 sessions" — one count label for every count site, so the
* separator and the noun form never drift between screens. */
export function formatCount(n: number, singular: string, plural = `${singular}s`): string {
const count = n.toLocaleString(localeTag())
const stem = singular.replace(/\s+/g, '_')
const template = t(`common.count.${stem}.${n === 1 ? 'one' : 'other'}`)
// Fall back to English when a noun has no catalog entry (templates carry {count}).
return template.includes('{count}') ? template.replace('{count}', count) : `${count} ${n === 1 ? singular : plural}`
}
/** Compact token/count formatting: 1_842 → "1.8K", 184_000 → "184K", 1_200_000 → "1.2M". */
export function formatCompact(n: number): string {
if (!Number.isFinite(n)) return '—'
if (n === 0) return '0'
const abs = Math.abs(n)
if (abs < 1_000) return String(Math.round(n))
if (abs < 1_000_000) return `${trim(n / 1_000)}K`
if (abs < 1_000_000_000) return `${trim(n / 1_000_000)}M`
return `${trim(n / 1_000_000_000)}B`
}
// One decimal, but drop a trailing ".0" (184.0K → "184K", 1.2K stays "1.2K").
function trim(v: number): string {
const s = v.toFixed(1)
return s.endsWith('.0') ? s.slice(0, -2) : s
}
/** "Jul 10" — short month + day, no year. */
export function formatDayShort(iso: string): string {
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString(localeTag(), { month: 'short', day: 'numeric' })
}
/** "Jul 10, 2026" — full date. */
export function formatDayLong(iso: string): string {
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString(localeTag(), { month: 'short', day: 'numeric', year: 'numeric' })
}
/** "12 days" / "2h 14m" / "47m" / "38s" from a duration in ms. */
export function formatDuration(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return '—'
const totalMin = Math.floor(ms / 60_000)
if (totalMin < 1) return `${Math.floor(ms / 1000)}s`
if (totalMin < 60) return `${totalMin}m`
if (totalMin >= 2_880) return t('common.duration.days', { count: Math.round(totalMin / 1_440) })
return `${Math.floor(totalMin / 60)}h ${totalMin % 60}m`
}
/**
* "as of HH:MM" for a figure that is NOT live — a stored or slowly-polled
* value. Never returns a bare time that could read as now: a value from another
* day carries its date. Null in, null out (nothing to date yet, so no label).
*/
export function asOfLabel(at: number | string | null | undefined): string | null {
if (at === null || at === undefined) return null
const when = new Date(at)
if (Number.isNaN(when.getTime())) return null
const time = when.toLocaleTimeString(localeTag(), { hour: 'numeric', minute: '2-digit' })
const sameDay = when.toDateString() === new Date().toDateString()
return sameDay
? t('common.asOf', { time })
: t('common.asOfDate', { date: when.toLocaleDateString(localeTag(), { month: 'short', day: 'numeric' }), time })
}
/** Time left until a quota window resets, or null when it is unknown. */
export function formatResetTime(resetsAt: string | null): string | null {
if (!resetsAt) return null
const reset = Date.parse(resetsAt)
if (!Number.isFinite(reset)) return null
const remainingMinutes = Math.floor((reset - Date.now()) / 60_000)
if (remainingMinutes <= 0) return t('plans.reset.now')
const days = Math.floor(remainingMinutes / (24 * 60))
const hours = Math.floor((remainingMinutes % (24 * 60)) / 60)
const minutes = remainingMinutes % 60
if (days > 0) return hours > 0 ? t('plans.reset.daysHours', { days, hours }) : t('plans.reset.days', { days })
if (hours > 0) return minutes > 0 ? t('plans.reset.hoursMinutes', { hours, minutes }) : t('plans.reset.hours', { hours })
return t('plans.reset.minutes', { minutes })
}