Merge pull request #686 from getagentseal/fix/provider-visibility
Desktop: bundled CLI, provider logos, provider visibility
1
app/.gitignore
vendored
|
|
@ -1,5 +1,6 @@
|
|||
node_modules/
|
||||
dist/
|
||||
release/
|
||||
build/cli/
|
||||
*.log
|
||||
.vite/
|
||||
|
|
|
|||
|
|
@ -8,21 +8,48 @@ the CLI and menubar release processes in `../RELEASING.md`) — packaging is run
|
|||
by hand on a maintainer's machine. All three targets are produced by
|
||||
`electron-builder` and can be cross-built from a single macOS host.
|
||||
|
||||
## Prerequisite on the target machine: the codeburn CLI
|
||||
## The bundled CLI (no install prerequisite)
|
||||
|
||||
The desktop app does not bundle the CLI — every screen gets its data by
|
||||
spawning `codeburn`, resolved from the persisted path file, Homebrew/node
|
||||
version-manager locations, or `PATH` (`electron/cli.ts`). On a machine
|
||||
without it, the app launches into its "CLI not found" state until the user
|
||||
runs:
|
||||
The packaged app ships its own copy of the `codeburn` CLI and needs nothing
|
||||
installed on the target machine. Packaging stages a self-contained copy of the
|
||||
root repo's CLI into `app/build/cli` (see `scripts/stage-cli.mjs`) — the tsup
|
||||
bundle (`dist/main.js`), its Node-version launcher (`dist/cli.js`), the root
|
||||
`package.json` (the bundle reads its `version`), plus the CLI's production
|
||||
`node_modules` closure. An `afterPack` hook (`scripts/after-pack.cjs`) copies
|
||||
that tree into the app at `Contents/Resources/cli/` after packaging and before
|
||||
signing, so it lands inside the code signature.
|
||||
|
||||
```sh
|
||||
npm install -g codeburn
|
||||
```
|
||||
At runtime a packaged build spawns the bundled CLI with Electron's own binary
|
||||
acting as Node (`ELECTRON_RUN_AS_NODE=1`), so **no Node install is required** —
|
||||
the app is version-matched to itself. `main.ts` sets `CODEBURN_BUNDLED_CLI` to
|
||||
`Resources/cli/dist/launch.js` (a small shim that corrects `argv` for
|
||||
commander under Electron, then hands off to `main.js`), and `electron/cli.ts`
|
||||
resolves it ahead of any persisted path or `PATH` lookup.
|
||||
|
||||
Bundling `dist/cli.js` into the app (`extraResources` + spawning it with
|
||||
Electron's own binary via `ELECTRON_RUN_AS_NODE`) is the known path to a
|
||||
zero-dependency install; not implemented yet.
|
||||
A user-installed CLI is only consulted **outside** a packaged build (dev via the
|
||||
Vite dev server) or when explicitly overridden — `CODEBURN_BIN=/abs/path`, or a
|
||||
persisted path file (`Application Support/CodeBurn/codeburn-cli-path.v1`). The
|
||||
full resolution order in `electron/cli.ts` is: `CODEBURN_BIN` → dev repo CLI
|
||||
(Vite) → bundled CLI → persisted path → `PATH`/Homebrew/nvm/volta/asdf.
|
||||
|
||||
### Freshness
|
||||
|
||||
Packaging **always rebuilds the root CLI** before staging: the app `stage-cli`
|
||||
script runs the root `build:cli` (tsup only — no dashboard build, no network
|
||||
`bundle-litellm` fetch), so `dist/main.js` and `dist/cli.js` are regenerated
|
||||
from current `src/` on every `package*` run. A stale global `codeburn` can never
|
||||
ship, and the app can never be older than the JSON surfaces it calls. The
|
||||
bundled CLI's deps are pure JS (no native bindings), so the same staged tree is
|
||||
valid for every arch.
|
||||
|
||||
### Why `afterPack`, not `extraResources`
|
||||
|
||||
electron-builder routes every `node_modules` directory it copies through its
|
||||
production-dependency filter, which keeps only the *app's* own deps — so the
|
||||
bundled CLI's dependency tree gets stripped out of an `extraResources` copy
|
||||
(`filter: ["**/*"]` does not defeat this). `afterPack` copies the staged tree
|
||||
in verbatim, which is the electron-builder-recommended mechanism for adding
|
||||
unpacked files that must not be ASAR-archived.
|
||||
|
||||
## Versioning
|
||||
|
||||
|
|
@ -42,12 +69,14 @@ npm --prefix app run package:win # Windows NSIS installer, x64
|
|||
npm --prefix app run package:linux # Linux AppImage, x64
|
||||
```
|
||||
|
||||
`package` runs `npm run build` (compiles `electron/` with `tsc`, builds the
|
||||
renderer with `vite`) and then `electron-builder --mac`. `package:win` and
|
||||
`package:linux` mirror it exactly, swapping the final flag for
|
||||
`electron-builder --win` and `electron-builder --linux`. All three can run on
|
||||
the same macOS host — electron-builder downloads the NSIS and AppImage tooling
|
||||
on first use.
|
||||
`package` runs `npm run stage-cli` (rebuilds the root CLI and stages the
|
||||
self-contained bundle into `app/build/cli`; see "The bundled CLI" above), then
|
||||
`npm run build` (compiles `electron/` with `tsc`, builds the renderer with
|
||||
`vite`), then `electron-builder --mac` (whose `afterPack` hook copies the
|
||||
staged CLI into the app). `package:win` and `package:linux` mirror it exactly,
|
||||
swapping the final flag for `electron-builder --win` and `electron-builder
|
||||
--linux`. All three can run on the same macOS host — electron-builder downloads
|
||||
the NSIS and AppImage tooling on first use.
|
||||
|
||||
### Artifacts
|
||||
|
||||
|
|
@ -78,8 +107,12 @@ separate `electron-builder.yml`):
|
|||
- `files`: only `dist/electron/**/*`, `dist/renderer/**/*`, and `package.json`.
|
||||
The Electron main process has no npm runtime dependencies (only Node/Electron
|
||||
builtins — see `app/electron/cli.ts` and `app/electron/quota/*.ts`), and the
|
||||
renderer is a single Vite bundle, so `node_modules` does not need to ship at
|
||||
all.
|
||||
renderer is a single Vite bundle, so the app's own `node_modules` does not
|
||||
need to ship at all. (The *bundled CLI* has its own `node_modules`, added to
|
||||
`Resources/cli/` by the `afterPack` hook — see "The bundled CLI" above.)
|
||||
- `afterPack: "./scripts/after-pack.cjs"` — copies the staged CLI bundle
|
||||
(`app/build/cli`) into `Contents/Resources/cli` after packaging and before
|
||||
signing.
|
||||
- `mac.identity: "-"` — forces ad-hoc signing. **`identity: null` does NOT
|
||||
ad-hoc sign — it skips signing entirely**, which produces a bundle with a
|
||||
broken/absent seal (`codesign --verify --deep --strict` fails with
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ npm --prefix app run typecheck
|
|||
|
||||
## CLI Dependency
|
||||
|
||||
The app depends on a working `codeburn` CLI on the local machine. Electron resolves and spawns the CLI from the main process, then sends decoded JSON through the secure preload bridge into the renderer.
|
||||
Packaged builds ship their own version-matched copy of the `codeburn` CLI and require nothing installed — the app spawns the bundled CLI with Electron's own binary as Node (`ELECTRON_RUN_AS_NODE`). In development (Vite dev server) the app uses the repo's freshly-built CLI, and either can be overridden with `CODEBURN_BIN` or a persisted path file. See `DISTRIBUTION.md` for the bundling and resolution details. Electron resolves and spawns the CLI from the main process, then sends decoded JSON through the secure preload bridge into the renderer.
|
||||
|
||||
This follows the menubar pattern:
|
||||
|
||||
|
|
@ -55,12 +55,11 @@ Supported M1 periods are `today`, `week`, `30days`, `month`, and `all`. Provider
|
|||
|
||||
## Packaging
|
||||
|
||||
`npm run package` produces an ad-hoc-signed macOS `.dmg`/`.zip` (arm64 and x64) via `electron-builder`, no paid Apple Developer account required. See `DISTRIBUTION.md` for build instructions, artifact locations, and the Gatekeeper first-open story.
|
||||
`npm run package` produces an ad-hoc-signed macOS `.dmg`/`.zip` (arm64 and x64) via `electron-builder`, no paid Apple Developer account required. Packaging rebuilds the root CLI and bundles it into the app (`Resources/cli`), so installs need nothing on the target machine. See `DISTRIBUTION.md` for build instructions, the bundled-CLI mechanism, artifact locations, and the Gatekeeper first-open story.
|
||||
|
||||
## M2 Backlog
|
||||
|
||||
- Deliver a self-contained app that bundles the CodeBurn engine and auto-updates itself with Electron `autoUpdater`.
|
||||
- Ship end-user installs via `.dmg` and `install.sh`; end users should not need npm.
|
||||
- Add Electron `autoUpdater` (the app already bundles its own version-matched CLI, so end-user installs need nothing on the machine; auto-update is the remaining piece).
|
||||
- Keep npm as a separate CLI-user channel at the same version as the desktop app.
|
||||
- Add macOS code signing with a paid Developer ID and notarization (ad-hoc packaging exists today; see `DISTRIBUTION.md`).
|
||||
- Add a `codeburn desktop` launcher subcommand.
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, chmodSync
|
|||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import { spawnCli, spawnCliAction, spawnEnvFor, killAll, CliError, nodeManagerDirs, resolveCodeburnPath } from './cli'
|
||||
import { spawnCli, spawnCliAction, spawnEnvFor, spawnSpecFor, killAll, CliError, nodeManagerDirs, resolveCodeburnPath, resolveTarget } from './cli'
|
||||
|
||||
let dir: string
|
||||
const originalBin = process.env.CODEBURN_BIN
|
||||
const originalPathDirs = process.env.CODEBURN_PATH_DIRS
|
||||
const originalPathFile = process.env.CODEBURN_CLI_PATH_FILE
|
||||
const originalViteUrl = process.env.VITE_DEV_SERVER_URL
|
||||
const originalBundled = process.env.CODEBURN_BUNDLED_CLI
|
||||
|
||||
/** Writes an executable node script and points CODEBURN_BIN at it. */
|
||||
function fakeBin(name: string, body: string): string {
|
||||
|
|
@ -34,6 +35,8 @@ afterEach(() => {
|
|||
else process.env.CODEBURN_CLI_PATH_FILE = originalPathFile
|
||||
if (originalViteUrl === undefined) delete process.env.VITE_DEV_SERVER_URL
|
||||
else process.env.VITE_DEV_SERVER_URL = originalViteUrl
|
||||
if (originalBundled === undefined) delete process.env.CODEBURN_BUNDLED_CLI
|
||||
else process.env.CODEBURN_BUNDLED_CLI = originalBundled
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
|
|
@ -76,6 +79,104 @@ describe('resolveCodeburnPath (Vite development)', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('resolveTarget (bundled CLI in the packaged app)', () => {
|
||||
/** An existing (not necessarily executable) file to stand in for the bundle. */
|
||||
function bundledEntry(name = 'cli.js'): string {
|
||||
const p = join(dir, name)
|
||||
writeFileSync(p, '// bundled cli\n')
|
||||
return p
|
||||
}
|
||||
|
||||
it('resolves the bundled CLI, beating a persisted path and PATH', () => {
|
||||
delete process.env.CODEBURN_BIN
|
||||
delete process.env.VITE_DEV_SERVER_URL
|
||||
process.env.CODEBURN_PATH_DIRS = ''
|
||||
// A persisted global that should NOT win once a bundled CLI is present.
|
||||
const persistedTarget = join(dir, 'stale-global')
|
||||
writeFileSync(persistedTarget, '#!/usr/bin/env node\n', { mode: 0o755 })
|
||||
chmodSync(persistedTarget, 0o755)
|
||||
const persistedFile = join(dir, 'cli-path.v1')
|
||||
writeFileSync(persistedFile, persistedTarget)
|
||||
process.env.CODEBURN_CLI_PATH_FILE = persistedFile
|
||||
|
||||
const entry = bundledEntry()
|
||||
process.env.CODEBURN_BUNDLED_CLI = entry
|
||||
|
||||
expect(resolveTarget()).toEqual({ kind: 'bundled', entry })
|
||||
expect(resolveCodeburnPath()).toBe(entry)
|
||||
})
|
||||
|
||||
it('CODEBURN_BIN still overrides the bundled CLI', () => {
|
||||
const override = fakeBin('override.js', 'process.stdout.write("{}")') // sets CODEBURN_BIN
|
||||
process.env.CODEBURN_BUNDLED_CLI = bundledEntry('bundled.js')
|
||||
delete process.env.VITE_DEV_SERVER_URL
|
||||
|
||||
expect(resolveTarget()).toEqual({ kind: 'external', bin: override })
|
||||
})
|
||||
|
||||
it('the dev repo CLI beats the bundled CLI in Vite development', () => {
|
||||
delete process.env.CODEBURN_BIN
|
||||
process.env.CODEBURN_PATH_DIRS = ''
|
||||
process.env.CODEBURN_CLI_PATH_FILE = join(dir, 'no-persisted-path')
|
||||
process.env.CODEBURN_BUNDLED_CLI = bundledEntry('bundled.js')
|
||||
process.env.VITE_DEV_SERVER_URL = 'http://localhost:5173'
|
||||
|
||||
const target = resolveTarget()
|
||||
expect(target?.kind).toBe('external')
|
||||
expect(target && target.kind === 'external' ? target.bin : '').toMatch(/dist\/cli\.js$/)
|
||||
})
|
||||
|
||||
it('falls through when CODEBURN_BUNDLED_CLI points at a missing file', () => {
|
||||
delete process.env.CODEBURN_BIN
|
||||
delete process.env.VITE_DEV_SERVER_URL
|
||||
process.env.CODEBURN_PATH_DIRS = '' // force an empty PATH search space
|
||||
process.env.CODEBURN_CLI_PATH_FILE = join(dir, 'no-persisted-path')
|
||||
process.env.CODEBURN_BUNDLED_CLI = join(dir, 'does-not-exist', 'cli.js')
|
||||
|
||||
expect(resolveTarget()).toBeNull()
|
||||
expect(resolveCodeburnPath()).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('spawnSpecFor (bundled CLI runs via Electron-as-node)', () => {
|
||||
it('spawns process.execPath with the bundle as argv[0] and ELECTRON_RUN_AS_NODE set', () => {
|
||||
const spec = spawnSpecFor({ kind: 'bundled', entry: '/res/cli/dist/cli.js' }, ['status', '--period', 'today'])
|
||||
expect(spec.bin).toBe(process.execPath)
|
||||
expect(spec.args).toEqual(['/res/cli/dist/cli.js', 'status', '--period', 'today'])
|
||||
expect(spec.env.ELECTRON_RUN_AS_NODE).toBe('1')
|
||||
// PATH is still augmented (the bundle's own dir leads), harmless for a CLI
|
||||
// that itself shells out during pairing/sync.
|
||||
expect((spec.env.PATH ?? '').split(':')[0]).toBe('/res/cli/dist')
|
||||
})
|
||||
|
||||
it('spawns an external CLI directly, with no run-as-node flag', () => {
|
||||
const spec = spawnSpecFor({ kind: 'external', bin: '/some/bin/codeburn' }, ['status'])
|
||||
expect(spec.bin).toBe('/some/bin/codeburn')
|
||||
expect(spec.args).toEqual(['status'])
|
||||
expect(spec.env.ELECTRON_RUN_AS_NODE).toBeUndefined()
|
||||
expect((spec.env.PATH ?? '').split(':')[0]).toBe('/some/bin')
|
||||
})
|
||||
|
||||
it('spawnCli runs the bundled entry end-to-end as Node', async () => {
|
||||
delete process.env.CODEBURN_BIN
|
||||
delete process.env.VITE_DEV_SERVER_URL
|
||||
process.env.CODEBURN_PATH_DIRS = ''
|
||||
process.env.CODEBURN_CLI_PATH_FILE = join(dir, 'no-persisted-path')
|
||||
// process.execPath is the Node running vitest here; a real packaged app uses
|
||||
// Electron's binary, but the spawn shape (execPath + entry + args + env) is
|
||||
// identical, so this exercises the whole bundled path.
|
||||
const entry = join(dir, 'bundled-cli.js')
|
||||
writeFileSync(
|
||||
entry,
|
||||
'process.stdout.write(JSON.stringify({ ranAsNode: process.env.ELECTRON_RUN_AS_NODE === "1", firstArg: process.argv[2] }))\n',
|
||||
)
|
||||
process.env.CODEBURN_BUNDLED_CLI = entry
|
||||
|
||||
const result = (await spawnCli(['status'])) as { ranAsNode: boolean; firstArg: string }
|
||||
expect(result).toEqual({ ranAsNode: true, firstArg: 'status' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('spawnCli', () => {
|
||||
it('resolves parsed JSON on success', async () => {
|
||||
fakeBin('ok.js', 'process.stdout.write(JSON.stringify({ ok: 1 }))')
|
||||
|
|
|
|||
|
|
@ -9,6 +9,16 @@ import { delimiter, dirname, join } from 'node:path'
|
|||
export type CliErrorKind = 'not-found' | 'nonzero' | 'bad-json' | 'timeout' | 'too-large' | 'bad-args'
|
||||
export type ActionResult = { ok: boolean; stdout: string; stderr: string; code: number | null }
|
||||
|
||||
/**
|
||||
* A resolved CLI target. `external` is a standalone `codeburn` executable (the
|
||||
* dev repo build, a persisted path, or one found on PATH) spawned directly.
|
||||
* `bundled` is the copy shipped inside the packaged app under `resources/cli`;
|
||||
* it has no Node runner of its own, so it is spawned with Electron's own binary
|
||||
* acting as Node via `ELECTRON_RUN_AS_NODE`.
|
||||
*/
|
||||
export type CliTarget = { kind: 'external'; bin: string } | { kind: 'bundled'; entry: string }
|
||||
type SpawnSpec = { bin: string; args: string[]; env: NodeJS.ProcessEnv }
|
||||
|
||||
/** Structured failure so the renderer can pick the right empty/permission state. */
|
||||
export class CliError extends Error {
|
||||
readonly kind: CliErrorKind
|
||||
|
|
@ -92,6 +102,25 @@ export function spawnEnvFor(bin: string): NodeJS.ProcessEnv {
|
|||
return { ...process.env, PATH: path }
|
||||
}
|
||||
|
||||
/**
|
||||
* The concrete spawn (executable, argv, env) for a resolved target. An external
|
||||
* `codeburn` runs directly with the PATH augmentation above. The bundled copy
|
||||
* has no runner of its own, so it runs as `process.execPath` (Electron's binary)
|
||||
* with `ELECTRON_RUN_AS_NODE=1` turning it into plain Node and the bundle path
|
||||
* as the first argument. PATH is still augmented so anything the CLI itself
|
||||
* shells out to (pairing, sync) resolves the same way an external CLI would.
|
||||
*/
|
||||
export function spawnSpecFor(target: CliTarget, args: string[]): SpawnSpec {
|
||||
if (target.kind === 'bundled') {
|
||||
return {
|
||||
bin: process.execPath,
|
||||
args: [target.entry, ...args],
|
||||
env: { ...spawnEnvFor(target.entry), ELECTRON_RUN_AS_NODE: '1' },
|
||||
}
|
||||
}
|
||||
return { bin: target.bin, args, env: spawnEnvFor(target.bin) }
|
||||
}
|
||||
|
||||
function isExecutableFile(p: string): boolean {
|
||||
try {
|
||||
if (!statSync(p).isFile()) return false
|
||||
|
|
@ -102,6 +131,14 @@ function isExecutableFile(p: string): boolean {
|
|||
}
|
||||
}
|
||||
|
||||
function isFile(p: string): boolean {
|
||||
try {
|
||||
return statSync(p).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Persisted-path file written by the (future) first-run "locate CLI" flow,
|
||||
// mirroring the mac app's Application Support/CodeBurn/codeburn-cli-path.v1.
|
||||
function persistedPathFile(): string {
|
||||
|
|
@ -128,45 +165,61 @@ function readPersistedPath(): string | null {
|
|||
}
|
||||
|
||||
/**
|
||||
* Resolve the absolute path to the `codeburn` binary, or null if not found.
|
||||
* Resolve which `codeburn` to run, or null if none is available.
|
||||
* Order: dev override (`CODEBURN_BIN`) → repo CLI in Vite development →
|
||||
* bundled CLI shipped in the packaged app (`CODEBURN_BUNDLED_CLI`) →
|
||||
* persisted-path file → PATH / brew / nvm / volta / asdf → null.
|
||||
*
|
||||
* The dev repo CLI intentionally beats the persisted-path file: in `npm run
|
||||
* dev` the developer is iterating on this repo, so its freshly-built
|
||||
* `dist/cli.js` must win over a stale globally-installed/persisted binary
|
||||
* (which may lack newly-added commands). Setting `CODEBURN_BIN` still overrides
|
||||
* everything. In production `VITE_DEV_SERVER_URL` is unset, so the persisted
|
||||
* path behaves exactly as before.
|
||||
* The dev repo CLI intentionally beats both the bundled and persisted paths: in
|
||||
* `npm run dev` the developer is iterating on this repo, so its freshly-built
|
||||
* `dist/cli.js` must win over anything older (which may lack newly-added
|
||||
* commands). The bundled CLI beats the persisted/PATH ones so a packaged app is
|
||||
* version-matched to itself and never falls back to an older globally-installed
|
||||
* `codeburn`. `CODEBURN_BIN` still overrides everything. In an unpackaged
|
||||
* dev/test run `CODEBURN_BUNDLED_CLI` is unset, so resolution behaves exactly as
|
||||
* before.
|
||||
*/
|
||||
export function resolveCodeburnPath(): string | null {
|
||||
export function resolveTarget(): CliTarget | null {
|
||||
const override = process.env.CODEBURN_BIN
|
||||
if (override && override.startsWith('/') && isExecutableFile(override)) return override
|
||||
if (override && override.startsWith('/') && isExecutableFile(override)) return { kind: 'external', bin: override }
|
||||
|
||||
// Dev convenience: when launched by the Vite dev server, prefer the repo's own
|
||||
// freshly-built CLI over a stale globally-installed/persisted one, so
|
||||
// newly-added commands (sessions/compare/act JSON) work without CODEBURN_BIN.
|
||||
if (process.env.VITE_DEV_SERVER_URL) {
|
||||
const devBin = join(__dirname, '..', '..', '..', 'dist', 'cli.js')
|
||||
if (isExecutableFile(devBin)) return devBin
|
||||
if (isExecutableFile(devBin)) return { kind: 'external', bin: devBin }
|
||||
// Vitest loads this source module from app/electron rather than the emitted
|
||||
// app/dist/electron directory; keep the same repo CLI discoverable there.
|
||||
const sourceDevBin = join(__dirname, '..', '..', 'dist', 'cli.js')
|
||||
if (isExecutableFile(sourceDevBin)) return sourceDevBin
|
||||
if (isExecutableFile(sourceDevBin)) return { kind: 'external', bin: sourceDevBin }
|
||||
}
|
||||
|
||||
// Packaged app: main.ts sets CODEBURN_BUNDLED_CLI to resources/cli/dist/cli.js.
|
||||
// It is passed as an argument to Electron-as-node, so it only needs to be a
|
||||
// readable file — no exec bit or working shebang required.
|
||||
const bundled = process.env.CODEBURN_BUNDLED_CLI
|
||||
if (bundled && bundled.startsWith('/') && isFile(bundled)) return { kind: 'bundled', entry: bundled }
|
||||
|
||||
const persisted = readPersistedPath()
|
||||
if (persisted) return persisted
|
||||
if (persisted) return { kind: 'external', bin: persisted }
|
||||
|
||||
for (const bin of searchDirs().map(dir => join(dir, 'codeburn'))) {
|
||||
if (isExecutableFile(bin)) return bin
|
||||
if (isExecutableFile(bin)) return { kind: 'external', bin }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function runCli(bin: string, args: string[], timeoutMs: number): Promise<unknown> {
|
||||
/** The resolved CLI's path for display/status, or null. See {@link resolveTarget}. */
|
||||
export function resolveCodeburnPath(): string | null {
|
||||
const target = resolveTarget()
|
||||
if (!target) return null
|
||||
return target.kind === 'bundled' ? target.entry : target.bin
|
||||
}
|
||||
|
||||
function runCli(spec: SpawnSpec, cmdLabel: string, timeoutMs: number): Promise<unknown> {
|
||||
return new Promise<unknown>((resolve, reject) => {
|
||||
const child = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: spawnEnvFor(bin) })
|
||||
const child = spawn(spec.bin, spec.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: spec.env })
|
||||
activeChildren.add(child)
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
|
|
@ -184,7 +237,7 @@ function runCli(bin: string, args: string[], timeoutMs: number): Promise<unknown
|
|||
const timer = setTimeout(() => {
|
||||
finish(() => {
|
||||
child.kill('SIGKILL')
|
||||
reject(new CliError('timeout', `codeburn ${args[0] ?? ''} timed out after ${timeoutMs}ms`))
|
||||
reject(new CliError('timeout', `codeburn ${cmdLabel} timed out after ${timeoutMs}ms`))
|
||||
})
|
||||
}, timeoutMs)
|
||||
|
||||
|
|
@ -193,7 +246,7 @@ function runCli(bin: string, args: string[], timeoutMs: number): Promise<unknown
|
|||
if (total > MAX_OUTPUT_BYTES) {
|
||||
finish(() => {
|
||||
child.kill('SIGKILL')
|
||||
reject(new CliError('too-large', `codeburn ${args[0] ?? ''} produced more than ${MAX_OUTPUT_BYTES} bytes`))
|
||||
reject(new CliError('too-large', `codeburn ${cmdLabel} produced more than ${MAX_OUTPUT_BYTES} bytes`))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -234,16 +287,17 @@ function runCli(bin: string, args: string[], timeoutMs: number): Promise<unknown
|
|||
* absorbs same-cadence pollers. Never use this for config-mutating commands.
|
||||
*/
|
||||
export function spawnCli(args: string[], opts: { timeoutMs?: number } = {}): Promise<unknown> {
|
||||
const bin = resolveCodeburnPath()
|
||||
if (!bin) return Promise.reject(new CliError('not-found', 'codeburn CLI not found'))
|
||||
const target = resolveTarget()
|
||||
if (!target) return Promise.reject(new CliError('not-found', 'codeburn CLI not found'))
|
||||
const spec = spawnSpecFor(target, args)
|
||||
|
||||
const key = JSON.stringify([bin, ...args])
|
||||
const key = JSON.stringify([spec.bin, ...spec.args])
|
||||
const cached = readCache.get(key)
|
||||
if (cached && Date.now() - cached.at < COALESCE_TTL_MS) return Promise.resolve(cached.value)
|
||||
const existing = readInflight.get(key)
|
||||
if (existing) return existing
|
||||
|
||||
const flight = runCli(bin, args, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
||||
const flight = runCli(spec, args[0] ?? '', opts.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
||||
.then(value => { readCache.set(key, { at: Date.now(), value }); return value })
|
||||
.finally(() => { readInflight.delete(key) })
|
||||
readInflight.set(key, flight)
|
||||
|
|
@ -254,13 +308,14 @@ export function spawnCli(args: string[], opts: { timeoutMs?: number } = {}): Pro
|
|||
export function spawnCliAction(args: string[], opts: { timeoutMs?: number } = {}): Promise<ActionResult> {
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
||||
return new Promise<ActionResult>(resolve => {
|
||||
const bin = resolveCodeburnPath()
|
||||
if (!bin) {
|
||||
const target = resolveTarget()
|
||||
if (!target) {
|
||||
resolve({ ok: false, stdout: '', stderr: 'codeburn CLI not found', code: null })
|
||||
return
|
||||
}
|
||||
const spec = spawnSpecFor(target, args)
|
||||
|
||||
const child = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: spawnEnvFor(bin) })
|
||||
const child = spawn(spec.bin, spec.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: spec.env })
|
||||
activeChildren.add(child)
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
|
|
|
|||
|
|
@ -313,6 +313,15 @@ function bootstrap(): void {
|
|||
console.error('Unhandled promise rejection in main process:', reason)
|
||||
})
|
||||
|
||||
// Packaged builds ship their own version-matched CLI under resources/cli (the
|
||||
// afterPack hook copies it in). Point the resolver at the launch shim before
|
||||
// any handler spawns; cli.ts runs it with Electron-as-node. The shim, not
|
||||
// cli.js, is the entry — it corrects argv for commander under Electron. Unset
|
||||
// in dev, where the repo build is used instead.
|
||||
if (app.isPackaged) {
|
||||
process.env.CODEBURN_BUNDLED_CLI = path.join(process.resourcesPath, 'cli', 'dist', 'launch.js')
|
||||
}
|
||||
|
||||
// A second launch focuses the running window instead of opening a rival one.
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
|
|
|
|||
|
|
@ -11,11 +11,12 @@
|
|||
"dev": "npm run build:electron && concurrently -k -n vite,electron -c cyan,magenta \"vite\" \"wait-on tcp:127.0.0.1:5173 && cross-env VITE_DEV_SERVER_URL=http://127.0.0.1:5173 electron .\"",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"package": "npm run build && electron-builder --mac",
|
||||
"package:arm64": "npm run build && electron-builder --mac --arm64",
|
||||
"package:x64": "npm run build && electron-builder --mac --x64",
|
||||
"package:win": "npm run build && electron-builder --win",
|
||||
"package:linux": "npm run build && electron-builder --linux"
|
||||
"stage-cli": "npm --prefix .. run build:cli && node scripts/stage-cli.mjs",
|
||||
"package": "npm run stage-cli && npm run build && electron-builder --mac",
|
||||
"package:arm64": "npm run stage-cli && npm run build && electron-builder --mac --arm64",
|
||||
"package:x64": "npm run stage-cli && npm run build && electron-builder --mac --x64",
|
||||
"package:win": "npm run stage-cli && npm run build && electron-builder --win",
|
||||
"package:linux": "npm run stage-cli && npm run build && electron-builder --linux"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gsap/react": "^2.1.2",
|
||||
|
|
@ -53,6 +54,7 @@
|
|||
"dist/renderer/**/*",
|
||||
"package.json"
|
||||
],
|
||||
"afterPack": "./scripts/after-pack.cjs",
|
||||
"mac": {
|
||||
"target": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -261,6 +261,31 @@ describe('App shortcuts', () => {
|
|||
await waitFor(() => expect(mocks.getOverview).toHaveBeenCalledWith('30days', 'grok'))
|
||||
})
|
||||
|
||||
it('lists a detected provider with no spend this period and sorts it last', async () => {
|
||||
// Hermes has usage only outside the current period: the CLI still emits it
|
||||
// as a detected provider (cost 0), so the picker must show it, at the bottom.
|
||||
const payload = overviewPayload()
|
||||
payload.current.providers = { claude: 10, hermes: 0 }
|
||||
payload.current.providerDetails = [
|
||||
{ id: 'claude', label: 'Claude', cost: 10 },
|
||||
{ id: 'hermes', label: 'Hermes', cost: 0 },
|
||||
]
|
||||
mocks.getOverview.mockResolvedValue(payload)
|
||||
|
||||
render(<App />)
|
||||
expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('All providers'))
|
||||
const claudeOption = await screen.findByRole('option', { name: 'Claude' })
|
||||
const hermesOption = screen.getByRole('option', { name: 'Hermes' })
|
||||
const options = screen.getAllByRole('option')
|
||||
// Zero-cost Hermes appears, and sorts after the provider that has spend.
|
||||
expect(options.indexOf(hermesOption)).toBeGreaterThan(options.indexOf(claudeOption))
|
||||
|
||||
fireEvent.click(hermesOption)
|
||||
await waitFor(() => expect(mocks.getOverview).toHaveBeenCalledWith('30days', 'hermes'))
|
||||
})
|
||||
|
||||
it('hides the Claude config picker when the payload carries no claudeConfigs', async () => {
|
||||
render(<App />)
|
||||
expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument()
|
||||
|
|
|
|||
|
|
@ -123,14 +123,20 @@ export function App() {
|
|||
if (!overview.data) return
|
||||
const details = overview.data.current.providerDetails
|
||||
// Prefer providerDetails (internal id + display label); fall back to the
|
||||
// providers map keys (lowercased display names) for older CLIs.
|
||||
// providers map keys (lowercased display names) for older CLIs. The CLI
|
||||
// only emits detected providers, so keep every entry (including ones with
|
||||
// no spend this period) and sort by cost so zero-cost ones sit at the
|
||||
// bottom of the picker.
|
||||
const found = details
|
||||
? details.filter(entry => entry.cost > 0).map(entry => ({ id: entry.id, label: entry.label }))
|
||||
? [...details]
|
||||
.sort((a, b) => b.cost - a.cost)
|
||||
.map(entry => ({ id: entry.id, label: entry.label }))
|
||||
: Object.entries(overview.data.current.providers)
|
||||
// Fallback map keys are lowercased display names; ones with spaces
|
||||
// ("grok build") cannot round-trip as --provider, so exclude them
|
||||
// rather than offer a filter that is guaranteed to error.
|
||||
.filter(([key, value]) => value > 0 && /^[a-z0-9-]+$/.test(key))
|
||||
.filter(([key]) => /^[a-z0-9-]+$/.test(key))
|
||||
.sort(([, a], [, b]) => b - a)
|
||||
.map(([key]) => ({ id: key, label: providerName(key) }))
|
||||
setDetectedProviders(current => {
|
||||
const next = [...current]
|
||||
|
|
|
|||
BIN
app/renderer/assets/providers/antigravity.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
4
app/renderer/assets/providers/cline.svg
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Cline">
|
||||
<rect width="64" height="64" rx="14" fill="#0f2f2c"/>
|
||||
<path d="M45.5 42.2c-3.4 3.2-7.6 4.8-12.7 4.8-4.7 0-8.6-1.5-11.6-4.4-3-3-4.5-6.7-4.5-11.2s1.5-8.2 4.5-11.1c3-2.9 6.9-4.4 11.6-4.4 5.1 0 9.3 1.6 12.7 4.8l-5.2 5.8c-2-1.9-4.3-2.8-7-2.8-2.4 0-4.4.7-5.9 2.2-1.5 1.4-2.2 3.3-2.2 5.5 0 2.3.7 4.2 2.2 5.6 1.5 1.4 3.5 2.2 5.9 2.2 2.8 0 5.1-.9 7-2.8l5.2 5.8z" fill="#5eead4"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 473 B |
6
app/renderer/assets/providers/codewhale.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg width="128" height="128" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="CodeWhale">
|
||||
<rect width="128" height="128" rx="20" fill="#0f172a"/>
|
||||
<path d="M26 72c0-21 17-38 38-38h21c10 0 19 6 23 15 2 4 6 7 10 8-5 4-11 6-18 6h-2c-1 23-20 41-43 41H34c-7 0-12-5-12-12V80c0-4 3-8 8-8h-4z" fill="#38bdf8"/>
|
||||
<circle cx="82" cy="56" r="5" fill="#0f172a"/>
|
||||
<path d="M42 85h36M45 96h25" stroke="#0f172a" stroke-width="6" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 484 B |
BIN
app/renderer/assets/providers/crush.png
Normal file
|
After Width: | Height: | Size: 49 KiB |
BIN
app/renderer/assets/providers/devin.png
Normal file
|
After Width: | Height: | Size: 67 KiB |
BIN
app/renderer/assets/providers/droid.png
Normal file
|
After Width: | Height: | Size: 7.9 KiB |
BIN
app/renderer/assets/providers/forge.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
app/renderer/assets/providers/hermes.png
Normal file
|
After Width: | Height: | Size: 26 KiB |
6
app/renderer/assets/providers/ibm-bob.svg
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="IBM Bob">
|
||||
<rect width="64" height="64" rx="12" fill="#0F62FE"/>
|
||||
<path d="M14 19h36v5H14zm0 10h36v5H14zm0 10h36v5H14z" fill="#fff" opacity=".9"/>
|
||||
<circle cx="24" cy="32" r="4" fill="#0F62FE"/>
|
||||
<circle cx="40" cy="32" r="4" fill="#0F62FE"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 337 B |
BIN
app/renderer/assets/providers/kilo-code.png
Normal file
|
After Width: | Height: | Size: 774 B |
5
app/renderer/assets/providers/kimi.svg
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Kimi">
|
||||
<rect width="64" height="64" rx="14" fill="#101820"/>
|
||||
<path d="M18 46V18h7v11.2L36 18h9L33 30.3 46.5 46h-9.2L25 31.4V46h-7z" fill="#C8F35A"/>
|
||||
<circle cx="48" cy="16" r="5" fill="#7EE787"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 292 B |
BIN
app/renderer/assets/providers/kiro.png
Normal file
|
After Width: | Height: | Size: 1.2 KiB |
12
app/renderer/assets/providers/mistral-vibe.svg
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<svg width="28" height="28" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M8.8147 5.35803H5.35791V8.46914H8.8147V5.35803Z" fill="black"/>
|
||||
<path d="M22.6419 5.35803H19.1851V8.46914H22.6419V5.35803Z" fill="black"/>
|
||||
<path d="M15.7283 15.7284H12.2715V18.8395H15.7283V15.7284Z" fill="black"/>
|
||||
<path d="M8.8147 15.7284H5.35791V18.8395H8.8147V15.7284Z" fill="black"/>
|
||||
<path d="M22.6419 15.7284H19.1851V18.8395H22.6419V15.7284Z" fill="black"/>
|
||||
<path d="M12.2715 8.81482H5.35791V11.9259H12.2715V8.81482Z" fill="black"/>
|
||||
<path d="M12.2718 19.1852H1.90137V22.2963H12.2718V19.1852Z" fill="black"/>
|
||||
<path d="M26.0989 19.1852H15.7285V22.2963H26.0989V19.1852Z" fill="black"/>
|
||||
<path d="M22.6419 12.2716H5.35791V15.3827H22.6419V12.2716Z" fill="black"/>
|
||||
<path d="M22.6421 8.81482H15.7285V11.9259H22.6421V8.81482Z" fill="black"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 849 B |
BIN
app/renderer/assets/providers/mux.png
Normal file
|
After Width: | Height: | Size: 9.2 KiB |
BIN
app/renderer/assets/providers/openclaw.jpg
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
app/renderer/assets/providers/roo-code.png
Normal file
|
After Width: | Height: | Size: 1.5 KiB |
BIN
app/renderer/assets/providers/vercel-gateway.png
Normal file
|
After Width: | Height: | Size: 8.1 KiB |
BIN
app/renderer/assets/providers/zcode.jpg
Normal file
|
After Width: | Height: | Size: 6.8 KiB |
BIN
app/renderer/assets/providers/zed.jpg
Normal file
|
After Width: | Height: | Size: 4.8 KiB |
BIN
app/renderer/assets/providers/zerostack.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
34
app/renderer/components/ProviderLogo.test.tsx
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
// @vitest-environment jsdom
|
||||
import { render } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { ProviderLogo } from './ProviderLogo'
|
||||
|
||||
describe('ProviderLogo', () => {
|
||||
it('renders a single image mark for a known provider id', () => {
|
||||
const { container } = render(<ProviderLogo provider="hermes" />)
|
||||
const img = container.querySelector('img.provider-logo')
|
||||
expect(img).toBeInTheDocument()
|
||||
expect(img).toHaveAttribute('src')
|
||||
expect(container.querySelector('.provider-mono')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders themed light/dark marks for a themed provider id', () => {
|
||||
const { container } = render(<ProviderLogo provider="grok" />)
|
||||
expect(container.querySelector('img.provider-logo.pl-light')).toBeInTheDocument()
|
||||
expect(container.querySelector('img.provider-logo.pl-dark')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a monogram badge (never null) for an unknown provider id', () => {
|
||||
const { container } = render(<ProviderLogo provider="codebuff" />)
|
||||
const mono = container.querySelector('span.provider-mono')
|
||||
expect(mono).toBeInTheDocument()
|
||||
expect(mono).toHaveTextContent('C')
|
||||
expect(container.querySelector('img')).toBeNull()
|
||||
})
|
||||
|
||||
it('falls back to a monogram for a lowercased display-name key with spaces', () => {
|
||||
const { container } = render(<ProviderLogo provider="grok build" />)
|
||||
expect(container.querySelector('span.provider-mono')).toHaveTextContent('G')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,13 +1,28 @@
|
|||
import antigravity from '../assets/providers/antigravity.png'
|
||||
import claude from '../assets/providers/claude.svg'
|
||||
import cline from '../assets/providers/cline.svg'
|
||||
import codewhale from '../assets/providers/codewhale.svg'
|
||||
import copilotDark from '../assets/providers/copilot-dark.svg'
|
||||
import copilotLight from '../assets/providers/copilot-light.svg'
|
||||
import crush from '../assets/providers/crush.png'
|
||||
import cursorDark from '../assets/providers/cursor-dark.svg'
|
||||
import cursorLight from '../assets/providers/cursor-light.svg'
|
||||
import cursorAgent from '../assets/providers/cursor-agent.jpg'
|
||||
import devin from '../assets/providers/devin.png'
|
||||
import droid from '../assets/providers/droid.png'
|
||||
import forge from '../assets/providers/forge.png'
|
||||
import gemini from '../assets/providers/gemini.svg'
|
||||
import goose from '../assets/providers/goose.png'
|
||||
import grokDark from '../assets/providers/grok-dark.svg'
|
||||
import grokLight from '../assets/providers/grok-light.svg'
|
||||
import hermes from '../assets/providers/hermes.png'
|
||||
import ibmBob from '../assets/providers/ibm-bob.svg'
|
||||
import kiloCode from '../assets/providers/kilo-code.png'
|
||||
import kimi from '../assets/providers/kimi.svg'
|
||||
import kiro from '../assets/providers/kiro.png'
|
||||
import mistralVibe from '../assets/providers/mistral-vibe.svg'
|
||||
import mux from '../assets/providers/mux.png'
|
||||
import openclaw from '../assets/providers/openclaw.jpg'
|
||||
import opencodeDark from '../assets/providers/opencode-dark.svg'
|
||||
import opencodeLight from '../assets/providers/opencode-light.svg'
|
||||
import openaiDark from '../assets/providers/openai-dark.svg'
|
||||
|
|
@ -15,15 +30,40 @@ import openaiLight from '../assets/providers/openai-light.svg'
|
|||
import pi from '../assets/providers/pi.png'
|
||||
import qwenDark from '../assets/providers/qwen-dark.svg'
|
||||
import qwenLight from '../assets/providers/qwen-light.svg'
|
||||
import rooCode from '../assets/providers/roo-code.png'
|
||||
import vercelGateway from '../assets/providers/vercel-gateway.png'
|
||||
import warp from '../assets/providers/warp.jpg'
|
||||
import zcode from '../assets/providers/zcode.jpg'
|
||||
import zed from '../assets/providers/zed.jpg'
|
||||
import zerostack from '../assets/providers/zerostack.png'
|
||||
|
||||
const SINGLE_LOGOS: Record<string, string> = {
|
||||
antigravity,
|
||||
claude,
|
||||
cline,
|
||||
codewhale,
|
||||
crush,
|
||||
'cursor-agent': cursorAgent,
|
||||
devin,
|
||||
droid,
|
||||
forge,
|
||||
gemini,
|
||||
goose,
|
||||
hermes,
|
||||
'ibm-bob': ibmBob,
|
||||
'kilo-code': kiloCode,
|
||||
kimi,
|
||||
kiro,
|
||||
'mistral-vibe': mistralVibe,
|
||||
mux,
|
||||
openclaw,
|
||||
pi,
|
||||
'roo-code': rooCode,
|
||||
'vercel-gateway': vercelGateway,
|
||||
warp,
|
||||
zcode,
|
||||
zed,
|
||||
zerostack,
|
||||
}
|
||||
|
||||
const THEMED_LOGOS: Record<string, { light: string; dark: string }> = {
|
||||
|
|
@ -42,10 +82,19 @@ export function ProviderLogo({ provider, size = 16 }: { provider: string; size?:
|
|||
}
|
||||
|
||||
const logos = THEMED_LOGOS[provider]
|
||||
if (!logos) return null
|
||||
if (logos) {
|
||||
return <>
|
||||
<img src={logos.light} width={size} height={size} alt="" aria-hidden className="provider-logo pl-light" />
|
||||
<img src={logos.dark} width={size} height={size} alt="" aria-hidden className="provider-logo pl-dark" />
|
||||
</>
|
||||
}
|
||||
|
||||
return <>
|
||||
<img src={logos.light} width={size} height={size} alt="" aria-hidden className="provider-logo pl-light" />
|
||||
<img src={logos.dark} width={size} height={size} alt="" aria-hidden className="provider-logo pl-dark" />
|
||||
</>
|
||||
const initial = (provider.trim()[0] ?? '?').toUpperCase()
|
||||
return (
|
||||
<span
|
||||
className="provider-logo provider-mono"
|
||||
style={{ width: size, height: size, fontSize: Math.round(size * 0.58) }}
|
||||
aria-hidden
|
||||
>{initial}</span>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -168,6 +168,33 @@ describe('Models', () => {
|
|||
expect(dots[1]).toHaveAttribute('style', expect.stringContaining('var(--s-gpt)'))
|
||||
})
|
||||
|
||||
it('names the provider on each model row so duplicate model names stay distinguishable', async () => {
|
||||
const dupRows: ModelReportRow[] = [
|
||||
{ ...rows[0], provider: 'minimax', providerDisplayName: 'MiniMax', model: 'minimax-m3', modelDisplayName: 'MiniMax M3' },
|
||||
{ ...rows[1], provider: 'openrouter', providerDisplayName: 'OpenRouter', model: 'minimax-m3', modelDisplayName: 'MiniMax M3' },
|
||||
]
|
||||
getModels.mockResolvedValue(dupRows)
|
||||
|
||||
render(<Models period="30days" provider="all" />)
|
||||
|
||||
// Same display name, two rows — each tagged with its own provider.
|
||||
expect(await screen.findAllByText('MiniMax M3')).toHaveLength(2)
|
||||
expect(screen.getByText('MiniMax')).toBeInTheDocument()
|
||||
expect(screen.getByText('OpenRouter')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('names the provider on each by-task model group', async () => {
|
||||
getModels.mockResolvedValueOnce([rows[0]]).mockResolvedValueOnce(byTaskRows)
|
||||
|
||||
render(<Models period="week" provider="all" />)
|
||||
|
||||
expect(await screen.findByText('Claude Opus 4.8')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('tab', { name: 'By task' }))
|
||||
|
||||
expect(await screen.findByText('coding')).toBeInTheDocument()
|
||||
expect(screen.getByText('Anthropic')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders codex rows with credits and real cost as priced', async () => {
|
||||
getModels.mockResolvedValue([rows[1]])
|
||||
|
||||
|
|
|
|||
|
|
@ -26,6 +26,10 @@ function fmtInt(n: number): string {
|
|||
return n.toLocaleString('en-US')
|
||||
}
|
||||
|
||||
// Muted secondary tag naming a row's provider, so the same model name coming
|
||||
// from different providers reads as distinct rows.
|
||||
const providerTagStyle = { color: 'var(--mut)', fontSize: 'var(--fs-label)', fontWeight: 450 } as const
|
||||
|
||||
export function Models({
|
||||
period,
|
||||
provider,
|
||||
|
|
@ -272,6 +276,7 @@ function ModelTableRow({ row, onAddAlias }: { row: ModelReportRow; onAddAlias: (
|
|||
<button type="button" className="alias" onClick={onAddAlias}>add alias ›</button>
|
||||
</>
|
||||
) : null}
|
||||
<span style={{ ...providerTagStyle, display: 'block', marginTop: 2, paddingLeft: 16 }}>{row.providerDisplayName}</span>
|
||||
</td>
|
||||
<td className={cellClass}>{fmtInt(row.calls)}</td>
|
||||
<td className={cellClass}>{tokenValue(row.inputTokens)}</td>
|
||||
|
|
@ -298,7 +303,10 @@ function ModelGroupRow({ rows, onAddAlias }: { rows: ModelReportRow[]; onAddAlia
|
|||
className="mdot"
|
||||
style={{ background: seriesColorForModel(model.modelDisplayName || model.model) }}
|
||||
/>
|
||||
<span className="model-group-name">{model.modelDisplayName}</span>
|
||||
<span style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
|
||||
<span className="model-group-name">{model.modelDisplayName}</span>
|
||||
<span style={providerTagStyle}>{model.providerDisplayName}</span>
|
||||
</span>
|
||||
{unpriced ? <button type="button" className="alias" onClick={onAddAlias}>add alias ›</button> : null}
|
||||
</span>
|
||||
</td>
|
||||
|
|
|
|||
|
|
@ -155,6 +155,31 @@ describe('Settings', () => {
|
|||
expect(mocks.getOverview).toHaveBeenCalledWith('week', 'all')
|
||||
})
|
||||
|
||||
it('keys provider logos on the internal id from providerDetails', async () => {
|
||||
mocks.getOverview.mockResolvedValue({
|
||||
current: {
|
||||
providers: { 'grok build': 8.1, apex: 2.2 },
|
||||
providerDetails: [
|
||||
{ id: 'grok', label: 'Grok Build', cost: 8.1 },
|
||||
{ id: 'apex', label: 'Apex', cost: 2.2 },
|
||||
],
|
||||
},
|
||||
} as unknown as MenubarPayload)
|
||||
const user = userEvent.setup()
|
||||
const { container } = render(<Settings period="week" />)
|
||||
await user.click(screen.getByRole('button', { name: 'Providers' }))
|
||||
|
||||
// grok has a themed mark, keyed on the internal id, so a real image renders.
|
||||
const grokRow = (await screen.findByText('Grok Build')).closest('.set-prov-head')!
|
||||
expect(grokRow.querySelector('img.provider-logo')).toBeInTheDocument()
|
||||
expect(grokRow.querySelector('.provider-mono')).toBeNull()
|
||||
|
||||
// an unknown provider still renders a monogram badge, never nothing.
|
||||
const apexRow = screen.getByText('Apex').closest('.set-prov-head')!
|
||||
expect(apexRow.querySelector('span.provider-mono')).toHaveTextContent('A')
|
||||
expect(container.querySelector('.set-prov-head img[src="grok build"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('lists, adds, and removes model aliases through the action bridge', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Settings period="month" />)
|
||||
|
|
|
|||
|
|
@ -200,10 +200,16 @@ function GeneralPane({ period, refreshToken, claudeConfigs, claudeConfigSource }
|
|||
|
||||
function ProvidersPane({ period, refreshToken }: { period: Period; refreshToken: number }) {
|
||||
const overview = usePolled<MenubarPayload>(() => codeburn.getOverview(period, 'all'), [period, refreshToken])
|
||||
const providers = Object.entries(overview.data?.current.providers ?? {})
|
||||
const details = overview.data?.current.providerDetails
|
||||
// Prefer providerDetails (internal id + display label) so ProviderLogo keys on
|
||||
// the internal id. Fall back to the providers map keys (lowercased display
|
||||
// names) for older CLIs that omit providerDetails.
|
||||
const providers = details
|
||||
? details.filter(entry => entry.cost > 0).map(entry => ({ id: entry.id, label: entry.label, cost: entry.cost }))
|
||||
: Object.entries(overview.data?.current.providers ?? {}).map(([id, cost]) => ({ id, label: id.charAt(0).toUpperCase() + id.slice(1), cost }))
|
||||
return <section className="set-p on">
|
||||
<div><h3 className="set-h">Providers</h3><p className="set-sub">codeburn auto-detects coding tools from local session files. No setup needed.</p></div>
|
||||
{overview.error ? <SettingsErrorText error={overview.error} /> : !overview.data ? <p className="set-cap">Loading detected providers…</p> : providers.length === 0 ? <p className="set-cap">No providers detected.</p> : providers.map(([name, cost]) => <div className="card" key={name}><div className="set-prov-head"><ProviderLogo provider={name} /><span className="set-prov-name">{name.charAt(0).toUpperCase() + name.slice(1)}</span><span className="set-status"><span className="set-dot ok" />Detected · {formatUsd(cost)}</span></div></div>)}
|
||||
{overview.error ? <SettingsErrorText error={overview.error} /> : !overview.data ? <p className="set-cap">Loading detected providers…</p> : providers.length === 0 ? <p className="set-cap">No providers detected.</p> : providers.map(entry => <div className="card" key={entry.id}><div className="set-prov-head"><ProviderLogo provider={entry.id} /><span className="set-prov-name">{entry.label}</span><span className="set-status"><span className="set-dot ok" />Detected · {formatUsd(entry.cost)}</span></div></div>)}
|
||||
</section>
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@
|
|||
}
|
||||
|
||||
.provider-logo { display: inline-flex; object-fit: contain; flex: 0 0 auto; border-radius: 4px; }
|
||||
.provider-mono { align-items: center; justify-content: center; background: var(--fill); color: var(--mut); border: 1px solid var(--line); font-weight: 600; line-height: 1; text-transform: uppercase; }
|
||||
.pl-dark { display: none; }
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
|
|
|
|||
30
app/scripts/after-pack.cjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// Copy the staged self-contained CLI (app/build/cli, produced by stage-cli.mjs)
|
||||
// into the packaged app's resources/cli directory.
|
||||
//
|
||||
// This is done here rather than via `extraResources` because electron-builder
|
||||
// routes every `node_modules` directory it copies through its production-
|
||||
// dependency filter, which keeps only the *app's* own deps — so the bundled
|
||||
// CLI's dependency tree gets stripped out of an `extraResources` copy. afterPack
|
||||
// runs after packaging but before code signing, so the files we add land inside
|
||||
// the app's signature. The CLI's deps are pure JS (no native bindings), so the
|
||||
// same tree is valid for every arch.
|
||||
|
||||
const { join } = require('node:path')
|
||||
const { cpSync, existsSync } = require('node:fs')
|
||||
|
||||
exports.default = async function afterPack(context) {
|
||||
const { appOutDir, electronPlatformName, packager } = context
|
||||
const src = join(__dirname, '..', 'build', 'cli')
|
||||
if (!existsSync(join(src, 'node_modules'))) {
|
||||
throw new Error(`after-pack: ${src}/node_modules is missing — run "npm run stage-cli" first`)
|
||||
}
|
||||
|
||||
const resources =
|
||||
electronPlatformName === 'darwin'
|
||||
? join(appOutDir, `${packager.appInfo.productFilename}.app`, 'Contents', 'Resources')
|
||||
: join(appOutDir, 'resources')
|
||||
const dest = join(resources, 'cli')
|
||||
|
||||
cpSync(src, dest, { recursive: true, dereference: true })
|
||||
console.log(`after-pack: bundled CLI copied -> ${dest}`)
|
||||
}
|
||||
114
app/scripts/stage-cli.mjs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
// Stage a self-contained copy of the root codeburn CLI into app/build/cli so
|
||||
// electron-builder can ship it as `extraResources`. The packaged app spawns
|
||||
// this copy (via Electron-as-node) instead of a globally-installed `codeburn`,
|
||||
// guaranteeing the CLI matches the app's version with no install prerequisite.
|
||||
//
|
||||
// The tsup bundle (dist/main.js) is NOT self-contained: it keeps the runtime
|
||||
// dependencies external (chalk, react, ink, undici, zod, @modelcontextprotocol/
|
||||
// sdk, ...), and dist/main.js reads `../package.json` for its version string. So
|
||||
// the staged layout mirrors what `npm install` produces:
|
||||
//
|
||||
// build/cli/package.json (root package.json: {version}, type:module)
|
||||
// build/cli/dist/cli.js (Node-version-guard launcher → ./main.js)
|
||||
// build/cli/dist/main.js (the bundle)
|
||||
// build/cli/node_modules/ (production dependency closure)
|
||||
//
|
||||
// The production closure is copied out of the already-installed root
|
||||
// node_modules (offline, no reinstall). Run the root CLI build first so dist/ is
|
||||
// fresh — the app `stage-cli` script does exactly that.
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { cpSync, copyFileSync, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url)) // app/scripts
|
||||
const appDir = join(here, '..') // app
|
||||
const root = join(appDir, '..') // repo root
|
||||
const dist = join(root, 'dist')
|
||||
const rootModules = join(root, 'node_modules')
|
||||
const stage = join(appDir, 'build', 'cli')
|
||||
|
||||
for (const f of ['cli.js', 'main.js']) {
|
||||
if (!existsSync(join(dist, f))) {
|
||||
throw new Error(`stage-cli: ${join(dist, f)} is missing — build the root CLI first`)
|
||||
}
|
||||
}
|
||||
|
||||
rmSync(stage, { recursive: true, force: true })
|
||||
mkdirSync(join(stage, 'dist'), { recursive: true })
|
||||
|
||||
copyFileSync(join(root, 'package.json'), join(stage, 'package.json'))
|
||||
copyFileSync(join(dist, 'cli.js'), join(stage, 'dist', 'cli.js'))
|
||||
copyFileSync(join(dist, 'main.js'), join(stage, 'dist', 'main.js'))
|
||||
|
||||
// Desktop-app launch shim (the app spawns this, not cli.js). The packaged app
|
||||
// runs the CLI with Electron's own binary as Node (ELECTRON_RUN_AS_NODE=1).
|
||||
// Because process.versions.electron is then set, commander's argv auto-detection
|
||||
// treats a packaged (non-defaultApp) Electron as `from: 'electron'` and slices
|
||||
// argv by 1 instead of 2 — leaving this script's own path among the parsed args
|
||||
// and shifting every real argument. Drop that element before handing off so the
|
||||
// CLI's `program.parse()` sees the true args. Guarded so the shim also works if
|
||||
// ever run under plain Node. Kept in the app (not the shared CLI source) so the
|
||||
// published CLI is untouched.
|
||||
writeFileSync(
|
||||
join(stage, 'dist', 'launch.js'),
|
||||
[
|
||||
'// Generated by app/scripts/stage-cli.mjs — do not edit.',
|
||||
'if (process.versions.electron) process.argv.splice(1, 1)',
|
||||
"import('./main.js').catch(err => {",
|
||||
' process.stderr.write(String(err?.message ?? err) + \'\\n\')',
|
||||
' process.exit(1)',
|
||||
'})',
|
||||
'',
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
// `npm ls` prints the tree to stdout even when it exits non-zero on peer/
|
||||
// extraneous warnings, so capture stdout regardless of exit code.
|
||||
let listed = ''
|
||||
try {
|
||||
listed = execFileSync('npm', ['ls', '--omit=dev', '--all', '--parseable'], {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
})
|
||||
} catch (err) {
|
||||
listed = err.stdout ? String(err.stdout) : ''
|
||||
}
|
||||
|
||||
// Every parseable line is an absolute path to a production package instance.
|
||||
// Map each back to its top-level node_modules entry (`name` or `@scope/name`),
|
||||
// then copy those dirs whole — a package's own nested node_modules comes with
|
||||
// it, which is exactly the closure it needs at runtime.
|
||||
const prefix = rootModules + '/'
|
||||
const topLevel = new Set()
|
||||
for (const line of listed.split('\n')) {
|
||||
if (!line.startsWith(prefix)) continue
|
||||
const rest = line.slice(prefix.length)
|
||||
const match = rest.match(/^(@[^/]+\/[^/]+|[^/]+)/)
|
||||
if (match) topLevel.add(match[1])
|
||||
}
|
||||
if (topLevel.size === 0) {
|
||||
throw new Error('stage-cli: production dependency closure is empty — is the root `npm install`ed?')
|
||||
}
|
||||
|
||||
mkdirSync(join(stage, 'node_modules'), { recursive: true })
|
||||
for (const pkg of topLevel) {
|
||||
const src = join(rootModules, pkg)
|
||||
if (!existsSync(src) || !statSync(src).isDirectory()) continue
|
||||
cpSync(src, join(stage, 'node_modules', pkg), { recursive: true, dereference: true })
|
||||
}
|
||||
|
||||
// A partially-copied CLI that crashes on import is worse than none: fail the
|
||||
// build if any of the bundle's external runtime deps did not land.
|
||||
const required = [
|
||||
'chalk', 'react', 'ink', 'strip-ansi', 'zod', 'undici',
|
||||
'selfsigned', 'commander', 'bonjour-service', '@modelcontextprotocol/sdk',
|
||||
]
|
||||
const missing = required.filter(pkg => !existsSync(join(stage, 'node_modules', pkg)))
|
||||
if (missing.length) {
|
||||
throw new Error(`stage-cli: staged bundle is missing runtime deps: ${missing.join(', ')}`)
|
||||
}
|
||||
|
||||
console.log(`stage-cli: staged ${topLevel.size} production packages -> ${stage}`)
|
||||
|
|
@ -13,6 +13,7 @@
|
|||
"scripts": {
|
||||
"bundle-litellm": "node scripts/bundle-litellm.mjs",
|
||||
"build": "node scripts/bundle-litellm.mjs && tsup && node -e \"const fs=require('fs'); fs.copyFileSync('src/cli.ts','dist/cli.js'); fs.chmodSync('dist/cli.js',0o755)\" && npm run build:dash",
|
||||
"build:cli": "tsup && node -e \"const fs=require('fs'); fs.copyFileSync('src/cli.ts','dist/cli.js'); fs.chmodSync('dist/cli.js',0o755)\"",
|
||||
"build:dash": "cd dash && npm install --no-audit --no-fund --silent && npm run build",
|
||||
"dev": "NODE_OPTIONS=--no-deprecation tsx src/cli.ts",
|
||||
"test": "vitest",
|
||||
|
|
|
|||