diff --git a/app/.gitignore b/app/.gitignore index 123c9cf9..d42b848f 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -1,5 +1,6 @@ node_modules/ dist/ release/ +build/cli/ *.log .vite/ diff --git a/app/DISTRIBUTION.md b/app/DISTRIBUTION.md index e0e1e43e..45d7b348 100644 --- a/app/DISTRIBUTION.md +++ b/app/DISTRIBUTION.md @@ -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 diff --git a/app/README.md b/app/README.md index 05d473b5..c59af884 100644 --- a/app/README.md +++ b/app/README.md @@ -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. diff --git a/app/electron/cli.test.ts b/app/electron/cli.test.ts index ade98834..f71789d4 100644 --- a/app/electron/cli.test.ts +++ b/app/electron/cli.test.ts @@ -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 }))') diff --git a/app/electron/cli.ts b/app/electron/cli.ts index f0a52861..10696657 100644 --- a/app/electron/cli.ts +++ b/app/electron/cli.ts @@ -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 { +/** 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 { return new Promise((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 { 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 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 { - 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 { const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS return new Promise(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 = '' diff --git a/app/electron/main.ts b/app/electron/main.ts index 8572e9fc..d8980fb2 100644 --- a/app/electron/main.ts +++ b/app/electron/main.ts @@ -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() diff --git a/app/package.json b/app/package.json index b35d137a..b4ab6bea 100644 --- a/app/package.json +++ b/app/package.json @@ -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": [ { diff --git a/app/renderer/App.test.tsx b/app/renderer/App.test.tsx index c98b5d56..8aac9e0c 100644 --- a/app/renderer/App.test.tsx +++ b/app/renderer/App.test.tsx @@ -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() + 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() expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument() diff --git a/app/renderer/App.tsx b/app/renderer/App.tsx index aa9cbd1c..425fd2d7 100644 --- a/app/renderer/App.tsx +++ b/app/renderer/App.tsx @@ -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] diff --git a/app/renderer/assets/providers/antigravity.png b/app/renderer/assets/providers/antigravity.png new file mode 100644 index 00000000..9a0e29f8 Binary files /dev/null and b/app/renderer/assets/providers/antigravity.png differ diff --git a/app/renderer/assets/providers/cline.svg b/app/renderer/assets/providers/cline.svg new file mode 100644 index 00000000..d00094b4 --- /dev/null +++ b/app/renderer/assets/providers/cline.svg @@ -0,0 +1,4 @@ + + + + diff --git a/app/renderer/assets/providers/codewhale.svg b/app/renderer/assets/providers/codewhale.svg new file mode 100644 index 00000000..58d67344 --- /dev/null +++ b/app/renderer/assets/providers/codewhale.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/renderer/assets/providers/crush.png b/app/renderer/assets/providers/crush.png new file mode 100644 index 00000000..138a7ab6 Binary files /dev/null and b/app/renderer/assets/providers/crush.png differ diff --git a/app/renderer/assets/providers/devin.png b/app/renderer/assets/providers/devin.png new file mode 100644 index 00000000..c9a68730 Binary files /dev/null and b/app/renderer/assets/providers/devin.png differ diff --git a/app/renderer/assets/providers/droid.png b/app/renderer/assets/providers/droid.png new file mode 100644 index 00000000..0aab780f Binary files /dev/null and b/app/renderer/assets/providers/droid.png differ diff --git a/app/renderer/assets/providers/forge.png b/app/renderer/assets/providers/forge.png new file mode 100644 index 00000000..f2eba836 Binary files /dev/null and b/app/renderer/assets/providers/forge.png differ diff --git a/app/renderer/assets/providers/hermes.png b/app/renderer/assets/providers/hermes.png new file mode 100644 index 00000000..667d0d60 Binary files /dev/null and b/app/renderer/assets/providers/hermes.png differ diff --git a/app/renderer/assets/providers/ibm-bob.svg b/app/renderer/assets/providers/ibm-bob.svg new file mode 100644 index 00000000..ab76047e --- /dev/null +++ b/app/renderer/assets/providers/ibm-bob.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/renderer/assets/providers/kilo-code.png b/app/renderer/assets/providers/kilo-code.png new file mode 100644 index 00000000..2be60184 Binary files /dev/null and b/app/renderer/assets/providers/kilo-code.png differ diff --git a/app/renderer/assets/providers/kimi.svg b/app/renderer/assets/providers/kimi.svg new file mode 100644 index 00000000..c09b36fe --- /dev/null +++ b/app/renderer/assets/providers/kimi.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/app/renderer/assets/providers/kiro.png b/app/renderer/assets/providers/kiro.png new file mode 100644 index 00000000..f997c660 Binary files /dev/null and b/app/renderer/assets/providers/kiro.png differ diff --git a/app/renderer/assets/providers/mistral-vibe.svg b/app/renderer/assets/providers/mistral-vibe.svg new file mode 100644 index 00000000..f70841a7 --- /dev/null +++ b/app/renderer/assets/providers/mistral-vibe.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/app/renderer/assets/providers/mux.png b/app/renderer/assets/providers/mux.png new file mode 100644 index 00000000..d95a2cfa Binary files /dev/null and b/app/renderer/assets/providers/mux.png differ diff --git a/app/renderer/assets/providers/openclaw.jpg b/app/renderer/assets/providers/openclaw.jpg new file mode 100644 index 00000000..0394c6f4 Binary files /dev/null and b/app/renderer/assets/providers/openclaw.jpg differ diff --git a/app/renderer/assets/providers/roo-code.png b/app/renderer/assets/providers/roo-code.png new file mode 100644 index 00000000..776a1031 Binary files /dev/null and b/app/renderer/assets/providers/roo-code.png differ diff --git a/app/renderer/assets/providers/vercel-gateway.png b/app/renderer/assets/providers/vercel-gateway.png new file mode 100644 index 00000000..4cda755d Binary files /dev/null and b/app/renderer/assets/providers/vercel-gateway.png differ diff --git a/app/renderer/assets/providers/zcode.jpg b/app/renderer/assets/providers/zcode.jpg new file mode 100644 index 00000000..8dbcaaec Binary files /dev/null and b/app/renderer/assets/providers/zcode.jpg differ diff --git a/app/renderer/assets/providers/zed.jpg b/app/renderer/assets/providers/zed.jpg new file mode 100644 index 00000000..e50d3b05 Binary files /dev/null and b/app/renderer/assets/providers/zed.jpg differ diff --git a/app/renderer/assets/providers/zerostack.png b/app/renderer/assets/providers/zerostack.png new file mode 100644 index 00000000..6d835a59 Binary files /dev/null and b/app/renderer/assets/providers/zerostack.png differ diff --git a/app/renderer/components/ProviderLogo.test.tsx b/app/renderer/components/ProviderLogo.test.tsx new file mode 100644 index 00000000..e1f50158 --- /dev/null +++ b/app/renderer/components/ProviderLogo.test.tsx @@ -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() + 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() + 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() + 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() + expect(container.querySelector('span.provider-mono')).toHaveTextContent('G') + }) +}) diff --git a/app/renderer/components/ProviderLogo.tsx b/app/renderer/components/ProviderLogo.tsx index 6c8cb0ee..928490b4 100644 --- a/app/renderer/components/ProviderLogo.tsx +++ b/app/renderer/components/ProviderLogo.tsx @@ -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 = { + 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 = { @@ -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 <> + + + + } - return <> - - - + const initial = (provider.trim()[0] ?? '?').toUpperCase() + return ( + {initial} + ) } diff --git a/app/renderer/sections/Models.test.tsx b/app/renderer/sections/Models.test.tsx index 799807f6..b64fd1eb 100644 --- a/app/renderer/sections/Models.test.tsx +++ b/app/renderer/sections/Models.test.tsx @@ -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() + + // 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() + + 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]]) diff --git a/app/renderer/sections/Models.tsx b/app/renderer/sections/Models.tsx index f2483a79..67311025 100644 --- a/app/renderer/sections/Models.tsx +++ b/app/renderer/sections/Models.tsx @@ -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: ( ) : null} + {row.providerDisplayName} {fmtInt(row.calls)} {tokenValue(row.inputTokens)} @@ -298,7 +303,10 @@ function ModelGroupRow({ rows, onAddAlias }: { rows: ModelReportRow[]; onAddAlia className="mdot" style={{ background: seriesColorForModel(model.modelDisplayName || model.model) }} /> - {model.modelDisplayName} + + {model.modelDisplayName} + {model.providerDisplayName} + {unpriced ? : null} diff --git a/app/renderer/sections/Settings.test.tsx b/app/renderer/sections/Settings.test.tsx index ef9fce9e..c2d12827 100644 --- a/app/renderer/sections/Settings.test.tsx +++ b/app/renderer/sections/Settings.test.tsx @@ -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() + 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() diff --git a/app/renderer/sections/Settings.tsx b/app/renderer/sections/Settings.tsx index 341a0365..d08e8782 100644 --- a/app/renderer/sections/Settings.tsx +++ b/app/renderer/sections/Settings.tsx @@ -200,10 +200,16 @@ function GeneralPane({ period, refreshToken, claudeConfigs, claudeConfigSource } function ProvidersPane({ period, refreshToken }: { period: Period; refreshToken: number }) { const overview = usePolled(() => 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

Providers

codeburn auto-detects coding tools from local session files. No setup needed.

- {overview.error ? : !overview.data ?

Loading detected providers…

: providers.length === 0 ?

No providers detected.

: providers.map(([name, cost]) =>
{name.charAt(0).toUpperCase() + name.slice(1)}Detected · {formatUsd(cost)}
)} + {overview.error ? : !overview.data ?

Loading detected providers…

: providers.length === 0 ?

No providers detected.

: providers.map(entry =>
{entry.label}Detected · {formatUsd(entry.cost)}
)}
} diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index 6fc8f257..53822b8b 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -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) { diff --git a/app/scripts/after-pack.cjs b/app/scripts/after-pack.cjs new file mode 100644 index 00000000..c324daba --- /dev/null +++ b/app/scripts/after-pack.cjs @@ -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}`) +} diff --git a/app/scripts/stage-cli.mjs b/app/scripts/stage-cli.mjs new file mode 100644 index 00000000..827776e1 --- /dev/null +++ b/app/scripts/stage-cli.mjs @@ -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}`) diff --git a/package.json b/package.json index b3e4a402..224a1c82 100644 --- a/package.json +++ b/package.json @@ -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",