mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 03:29:51 +00:00
feat(app): bundle the CLI inside the packaged app
The packaged app resolved whatever codeburn was on PATH — for real users the published npm release, which predates every JSON surface the app calls. The app now ships its own CLI copy under resources/cli (staged production node_modules tree; tsup output is not self-contained) and spawns it with Electron's own binary via ELECTRON_RUN_AS_NODE. No install prerequisite remains. - resolution order: CODEBURN_BIN, dev repo CLI, bundled, persisted path, PATH search - launch.js shim strips the extra argv element commander mis-slices under packaged Electron-as-node (process.versions.electron is set), which reproduced the 'too many arguments' class of error - afterPack hook copies the staged tree (extraResources runs node_modules through the production-dep filter and ships it empty); lands before signing, signature verified intact - packaging always restages from src via root build:cli (tsup only, no network); ~12MB compressed per artifact Verified on the built app: Electron-as-node CLI emits current JSON (providerDetails, currency), and a minimal-PATH GUI launch spawns the bundled CLI with zero external dependencies. 290/290.
This commit is contained in:
parent
61dddf57a0
commit
4a100d9d06
10 changed files with 399 additions and 54 deletions
1
app/.gitignore
vendored
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": [
|
||||
{
|
||||
|
|
|
|||
30
app/scripts/after-pack.cjs
Normal file
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
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",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue