mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-24 13:57:02 +00:00
menubar: install and launch the Windows tray app from codeburn menubar
Shares the mac release resolution behind a per-platform spec (tag prefix, asset name, error text), so the Windows path reuses the pinned-version URL, the release-API fallback scan, the retrying download and the sha256 verify unchanged. Windows then runs msiexec out of %SystemRoot%\System32 with /i /passive /norestart, treats 3010 and 1602 as non-failures, and launches the exe named by the product's Uninstall registry key.
This commit is contained in:
parent
9905e8f8d0
commit
527e58078d
6 changed files with 538 additions and 34 deletions
|
|
@ -8,7 +8,8 @@
|
|||
- **Optimize findings say what to do with them and where their number came from.** Every finding now carries a class and a basis, and every surface groups by it: `Fix now (apply-able)` for findings `codeburn optimize --apply` can write itself, `Habits` for the behavioural ones, `FYI` for informational ones whose cost may be justified. A finding only counts as apply-able when a plan can actually be built for that instance, so an `mcp-deferral-off` caused by Vertex policy or a shell-profile override is grouped as a habit rather than promising a fix that does not exist. Alongside it, each finding is marked `measured` (summed from provider-counted usage) or `estimated` (a schema-size or recovery-fraction model), with the split reported in the header as `N measured · M estimated` in place of the blanket "Estimates only." footer. Sessions whose cost the provider never reported are kept out of the `cost-outliers` peer comparison, and a provider that only ever estimates gets the finding marked `estimated` rather than dropped. `--format json` gains `class` and `basis` per finding plus `summary.measuredSavingsUSD` (existing fields unchanged), and the new `docs/optimize.md` covers what is scanned, exactly what `--apply` may write, and how to read the health grade.
|
||||
|
||||
### Added (Windows)
|
||||
- **A menubar app for Windows.** `windows/` is a Tauri 2 tray app — Rust binary, React popover — that puts today's spend in the notification area and mirrors the macOS menubar screen for screen: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, CSV/JSON export, launch at login, currency, and theme. Windows has no menubar title, so the number lives in a second tray icon rendered from the system font at the panel's native icon size (Settings can turn it off; the tooltip always carries it). It reads everything through the CLI like the macOS and GNOME clients do, and gates on **codeburn 0.9.9 or newer** — the first release accepting `status --format menubar-json --no-optimize` — showing a setup screen with the install command until it finds one. Refresh follows popover visibility the way the macOS app does: 60 s with optimize findings while open, 2 minutes for today's total while closed, and immediately on open when what you are looking at has gone stale. The Claude quota view never spends Claude's single-use refresh token; on a 401 it re-reads Claude Code's own credential file for a token it has already rotated, matching the macOS client. Ships as an unsigned `.msi` from the `windows-v*` tag; `codeburn menubar` on Windows points at that release page. The same crate still builds and runs a tray on Linux, but that stays experimental and unreleased — `gnome/` is the supported Linux surface.
|
||||
- **`codeburn menubar` installs and launches the tray app on Windows.** The same command that installs the macOS menubar now does the Windows one, through the same pinned-release path: it resolves `windows-v<cliVersion>`, falls back to a scan of the newest `windows-v*` release carrying both assets when that tag has none, downloads the `.msi` with the same retry and backoff, and verifies its sha256 before anything executes it — a mismatch aborts without ever handing the file to the installer. It then runs `msiexec` out of `%SystemRoot%\System32` (never a bare name, so nothing dropped next to the CLI can impersonate it) with `/i <msi> /passive /norestart`, treats exit 3010 as installed-pending-restart and 1602 as a cancelled install rather than failures, and launches the exe named by the product's Uninstall registry key. An already-installed matching version skips the download and just launches; `--force` reinstalls.
|
||||
- **A menubar app for Windows.** `windows/` is a Tauri 2 tray app — Rust binary, React popover — that puts today's spend in the notification area and mirrors the macOS menubar screen for screen: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, CSV/JSON export, launch at login, currency, and theme. Windows has no menubar title, so the number lives in a second tray icon rendered from the system font at the panel's native icon size (Settings can turn it off; the tooltip always carries it). It reads everything through the CLI like the macOS and GNOME clients do, and gates on **codeburn 0.9.9 or newer** — the first release accepting `status --format menubar-json --no-optimize` — showing a setup screen with the install command until it finds one. Refresh follows popover visibility the way the macOS app does: 60 s with optimize findings while open, 2 minutes for today's total while closed, and immediately on open when what you are looking at has gone stale. The Claude quota view never spends Claude's single-use refresh token; on a 401 it re-reads Claude Code's own credential file for a token it has already rotated, matching the macOS client. Ships as an unsigned `.msi` from the `windows-v*` tag, which `codeburn menubar` now installs for you. The same crate still builds and runs a tray on Linux, but that stays experimental and unreleased — `gnome/` is the supported Linux surface.
|
||||
|
||||
### Added (CLI)
|
||||
- **DeepSeek Harness (`dsh`) is now a supported provider.** Reads DeepSeek's open-source agent harness from `~/.dsh/sessions` (`DSH_HOME` relocates the root), both the default zstd logs and the uncompressed `session.jsonl` variant. A `.zstd` log is a concatenation of independent zstd frames, one per write batch, so it is decoded frame by frame behind a structural frame scan and a torn trailing frame from a crashed writer is ignored rather than failing the file (needs Node 22.15+ for `zlib` zstd; below that dsh is skipped with a notice instead of counted as $0). One call per `(turn, step)`, with the step's final `assistant/message` usage superseding the streamed `assistant/chunk` sample of the same call rather than adding to it, the model taken from the message that served the step, and reasoning tokens billed at the output rate. DSH records tokens but no cost, so calls are priced from the shared tables. The events a forked session replays from its parent are skipped, since codeburn already counts the parent's own log. The session format is pinned at version 0 upstream with no compatibility implied, so a log stamped with any other version is skipped with a notice instead of read under today's assumptions.
|
||||
|
|
|
|||
10
README.md
10
README.md
|
|
@ -108,7 +108,7 @@ Also runs via `bunx codeburn` or `pnpm dlx codeburn`, or `brew install codeburn`
|
|||
codeburn menubar
|
||||
```
|
||||
|
||||
On Windows the same view is a tray app; see [Windows](#windows). On Linux, a GNOME Shell extension gives it in the top panel; see [Linux (GNOME)](#linux-gnome).
|
||||
The same command installs the tray app on Windows; see [Windows](#windows). On Linux, a GNOME Shell extension gives it in the top panel; see [Linux (GNOME)](#linux-gnome).
|
||||
|
||||
Requires **Node.js 22.13+** and at least one supported tool with session data on disk. For Cursor and OpenCode, `better-sqlite3` installs automatically.
|
||||
|
||||
|
|
@ -333,7 +333,13 @@ Allowed values are `terminal` (macOS Terminal.app, the default) and `iterm2`. An
|
|||
|
||||
### Windows
|
||||
|
||||
Windows gets the same ambient view from the system tray. Download the `.msi` from the [latest Windows Menubar release](https://github.com/getagentseal/codeburn/releases/tag/windows-v0.9.20) and run it; `codeburn menubar` on Windows just points you at that page.
|
||||
Windows gets the same ambient view from the system tray, from the same one command:
|
||||
|
||||
```powershell
|
||||
codeburn menubar
|
||||
```
|
||||
|
||||
It downloads the `.msi` for your CLI version, verifies its sha256, runs it through `msiexec /passive`, and launches the tray app. Re-run with `--force` to reinstall; an already-installed matching version is just launched. You can also download the `.msi` yourself from the [latest Windows Menubar release](https://github.com/getagentseal/codeburn/releases/tag/windows-v0.9.20).
|
||||
|
||||
Today's spend sits in the tray as a number beside the flame icon (turn it off in Settings, and the tooltip always carries it). Click for the same popover the macOS app shows: agent tabs, period switcher, Trend, Forecast, Pulse, Stats and Plan insights, activity and model breakdowns, optimize findings, and CSV/JSON export. Settings covers launch at login, the tray number, theme, and currency. It refreshes every 60 seconds while the popover is open and every 2 minutes while it is closed.
|
||||
|
||||
|
|
|
|||
|
|
@ -1311,12 +1311,13 @@ program
|
|||
|
||||
program
|
||||
.command('menubar')
|
||||
.description('Install and launch the macOS menubar app (one command, no clone)')
|
||||
.option('--force', 'Reinstall even if an older copy is already in ~/Applications')
|
||||
.description('Install and launch the menubar app on macOS and Windows (one command, no clone)')
|
||||
.option('--force', 'Reinstall even if a copy is already installed')
|
||||
.action(async (opts: { force?: boolean }) => {
|
||||
try {
|
||||
const result = await installMenubarApp({ force: opts.force, cliVersion: version })
|
||||
console.log(`\n Ready. ${result.installedPath}\n`)
|
||||
// A cancelled Windows installer leaves nothing to point at.
|
||||
if (result.installedPath) console.log(`\n Ready. ${result.installedPath}\n`)
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
console.error(`\n Menubar install failed: ${message}\n`)
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import { pipeline } from 'node:stream/promises'
|
|||
import { Readable } from 'node:stream'
|
||||
import { ProxyAgent, fetch as undiciFetch } from 'undici'
|
||||
|
||||
import { getCodeburnCacheDir } from './cache-dir.js'
|
||||
import {
|
||||
buildPersistentCodeburnLookupPath,
|
||||
resolvePersistentCodeburnPathFromWhichOutput,
|
||||
|
|
@ -22,9 +23,11 @@ const EXPECTED_BUNDLE_ID = 'org.agentseal.codeburn-menubar'
|
|||
const VERSIONED_ASSET_PATTERN = /^CodeBurnMenubar-v.+\.zip$/
|
||||
const APP_PROCESS_NAME = 'CodeBurnMenubar'
|
||||
const SUPPORTED_OS = 'darwin'
|
||||
/// The Windows tray app (windows/) is released as an .msi under its own tag, so this command
|
||||
/// points at it rather than pretending to install anything.
|
||||
const WINDOWS_RELEASE_PAGE = 'https://github.com/getagentseal/codeburn/releases?q=windows-v'
|
||||
/// The Windows tray app (windows/) ships as an .msi under its own `windows-v*` tag. GitHub
|
||||
/// rewrites the spaces in the bundle name to dots when it stores the asset, so both the asset
|
||||
/// name and its download URL carry `CodeBurn.Menubar_...`.
|
||||
const WINDOWS_PRODUCT_NAME = 'CodeBurn Menubar'
|
||||
const WINDOWS_ASSET_PATTERN = /^CodeBurn\.Menubar_.+_x64_en-US\.msi$/
|
||||
const MIN_MACOS_MAJOR = 14
|
||||
const PERSISTED_CLI_PATH = join(homedir(), 'Library', 'Application Support', 'CodeBurn', 'codeburn-cli-path.v1')
|
||||
const PERSISTENT_CLI_REQUIRED_MESSAGE =
|
||||
|
|
@ -34,8 +37,45 @@ export type InstallResult = { installedPath: string; launched: boolean }
|
|||
|
||||
export type ReleaseAsset = { name: string; browser_download_url: string }
|
||||
export type ReleaseResponse = { tag_name: string; assets: ReleaseAsset[] }
|
||||
/// `zip` is the platform's primary asset: the mac bundle zip, or the Windows .msi.
|
||||
export type ResolvedAssets = { release: ReleaseResponse; zip: ReleaseAsset; checksum: ReleaseAsset }
|
||||
export type InstallOptions = { force?: boolean; cliVersion?: string }
|
||||
export type InstallOptions = {
|
||||
force?: boolean
|
||||
cliVersion?: string
|
||||
platform?: string
|
||||
windows?: WindowsInstallHooks
|
||||
}
|
||||
|
||||
/// What differs per platform between the mac and Windows installs: which release tag holds the
|
||||
/// build, and which asset in it is the installable. Everything downstream - versioned URL first,
|
||||
/// release-API scan as fallback, retrying download, checksum verify - is shared.
|
||||
export type ReleaseSpec = {
|
||||
tagPrefix: string
|
||||
assetPattern: RegExp
|
||||
assetName: (version: string) => string
|
||||
missingAsset: (tag: string) => string
|
||||
noRelease: string
|
||||
}
|
||||
|
||||
const MAC_RELEASE: ReleaseSpec = {
|
||||
tagPrefix: 'mac-v',
|
||||
assetPattern: VERSIONED_ASSET_PATTERN,
|
||||
assetName: version => `CodeBurnMenubar-v${version}.zip`,
|
||||
missingAsset: tag =>
|
||||
`No ${APP_BUNDLE_NAME} versioned zip found in release ${tag}. ` +
|
||||
`Check https://github.com/getagentseal/codeburn/releases.`,
|
||||
noRelease: 'No mac-v* release with a CodeBurnMenubar-v*.zip and checksum was found.',
|
||||
}
|
||||
|
||||
export const WINDOWS_RELEASE: ReleaseSpec = {
|
||||
tagPrefix: 'windows-v',
|
||||
assetPattern: WINDOWS_ASSET_PATTERN,
|
||||
assetName: version => `CodeBurn.Menubar_${version}_x64_en-US.msi`,
|
||||
missingAsset: tag =>
|
||||
`No ${WINDOWS_PRODUCT_NAME} .msi found in release ${tag}. ` +
|
||||
`Check https://github.com/getagentseal/codeburn/releases.`,
|
||||
noRelease: 'No windows-v* release with a CodeBurn.Menubar_*.msi and checksum was found.',
|
||||
}
|
||||
type ProxyEnv = Partial<Record<'HTTPS_PROXY' | 'https_proxy' | 'HTTP_PROXY' | 'http_proxy' | 'NO_PROXY' | 'no_proxy', string>>
|
||||
type FetchOptions = Parameters<typeof undiciFetch>[1]
|
||||
type HeaderGetter = { get(name: string): string | null }
|
||||
|
|
@ -50,6 +90,10 @@ type FetchLikeResponse = {
|
|||
text(): Promise<string>
|
||||
}
|
||||
type FetchImpl = (url: string, options?: FetchOptions) => Promise<FetchLikeResponse>
|
||||
/// The release-API lookup reads JSON instead of streaming a body, so it takes its own narrow
|
||||
/// response shape rather than widening FetchLikeResponse for every asset download fake.
|
||||
export type ReleaseApiFetch = (url: string, options?: FetchOptions) =>
|
||||
Promise<{ ok: boolean; status: number; headers: HeaderGetter; json(): Promise<unknown> }>
|
||||
|
||||
/// Release-asset delivery (github.com -> Azure blob) occasionally returns a transient 5xx or
|
||||
/// drops the socket. Three attempts with a short exponential backoff (0.5s, then 1s) rides out
|
||||
|
|
@ -99,14 +143,9 @@ function fetchWithProxy(url: string, options: FetchOptions = {}) {
|
|||
return undiciFetch(url, dispatcher ? { ...options, dispatcher } : options)
|
||||
}
|
||||
|
||||
export function resolveMenubarReleaseAssets(release: ReleaseResponse): ResolvedAssets {
|
||||
const zip = release.assets.find(a => VERSIONED_ASSET_PATTERN.test(a.name))
|
||||
if (!zip) {
|
||||
throw new Error(
|
||||
`No ${APP_BUNDLE_NAME} versioned zip found in release ${release.tag_name}. ` +
|
||||
`Check https://github.com/getagentseal/codeburn/releases.`
|
||||
)
|
||||
}
|
||||
export function resolveMenubarReleaseAssets(release: ReleaseResponse, spec: ReleaseSpec = MAC_RELEASE): ResolvedAssets {
|
||||
const zip = release.assets.find(a => spec.assetPattern.test(a.name))
|
||||
if (!zip) throw new Error(spec.missingAsset(release.tag_name))
|
||||
const checksum = release.assets.find(a => a.name === `${zip.name}.sha256`)
|
||||
if (!checksum) {
|
||||
throw new Error(`Missing checksum asset ${zip.name}.sha256 in release ${release.tag_name}.`)
|
||||
|
|
@ -114,28 +153,28 @@ export function resolveMenubarReleaseAssets(release: ReleaseResponse): ResolvedA
|
|||
return { release, zip, checksum }
|
||||
}
|
||||
|
||||
export function resolveLatestMenubarReleaseAssets(releases: ReleaseResponse[]): ResolvedAssets {
|
||||
export function resolveLatestMenubarReleaseAssets(releases: ReleaseResponse[], spec: ReleaseSpec = MAC_RELEASE): ResolvedAssets {
|
||||
for (const release of releases) {
|
||||
if (!release.tag_name.startsWith('mac-v')) continue
|
||||
if (!release.tag_name.startsWith(spec.tagPrefix)) continue
|
||||
try {
|
||||
return resolveMenubarReleaseAssets(release)
|
||||
return resolveMenubarReleaseAssets(release, spec)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
throw new Error('No mac-v* release with a CodeBurnMenubar-v*.zip and checksum was found.')
|
||||
throw new Error(spec.noRelease)
|
||||
}
|
||||
|
||||
function normalizeCliVersion(cliVersion: string): string {
|
||||
return cliVersion.trim().replace(/^v/, '')
|
||||
}
|
||||
|
||||
export function resolveVersionedMenubarReleaseAssets(cliVersion: string): ResolvedAssets {
|
||||
export function resolveVersionedMenubarReleaseAssets(cliVersion: string, spec: ReleaseSpec = MAC_RELEASE): ResolvedAssets {
|
||||
const version = normalizeCliVersion(cliVersion)
|
||||
if (!version) throw new Error('Cannot resolve CodeBurn Menubar release without a CLI version.')
|
||||
|
||||
const tagName = `mac-v${version}`
|
||||
const zipName = `CodeBurnMenubar-v${version}.zip`
|
||||
const tagName = `${spec.tagPrefix}${version}`
|
||||
const zipName = spec.assetName(version)
|
||||
const checksumName = `${zipName}.sha256`
|
||||
const releaseBase = `${RELEASE_DOWNLOAD_BASE}/${tagName}`
|
||||
const zip = { name: zipName, browser_download_url: `${releaseBase}/${zipName}` }
|
||||
|
|
@ -187,12 +226,6 @@ async function exists(path: string): Promise<boolean> {
|
|||
}
|
||||
|
||||
async function ensureSupportedPlatform(): Promise<void> {
|
||||
if (platform() === 'win32') {
|
||||
throw new Error(
|
||||
'The Windows menubar ships as an installer, not through this command. ' +
|
||||
`Download the .msi from ${WINDOWS_RELEASE_PAGE} and run it.`,
|
||||
)
|
||||
}
|
||||
if (platform() !== SUPPORTED_OS) {
|
||||
throw new Error(`The menubar app is macOS only (detected: ${platform()}).`)
|
||||
}
|
||||
|
|
@ -216,8 +249,8 @@ async function sysProductVersion(): Promise<string> {
|
|||
})
|
||||
}
|
||||
|
||||
async function fetchLatestReleaseAssets(): Promise<ResolvedAssets> {
|
||||
const response = await fetchWithProxy(RELEASE_API, {
|
||||
async function fetchLatestReleaseAssets(spec: ReleaseSpec = MAC_RELEASE, fetchImpl?: ReleaseApiFetch): Promise<ResolvedAssets> {
|
||||
const response = await (fetchImpl ?? fetchWithProxy)(RELEASE_API, {
|
||||
headers: {
|
||||
'User-Agent': 'codeburn-menubar-installer',
|
||||
Accept: 'application/vnd.github+json',
|
||||
|
|
@ -227,7 +260,7 @@ async function fetchLatestReleaseAssets(): Promise<ResolvedAssets> {
|
|||
throw new HttpStatusError(formatGitHubReleaseLookupError(response.status, response.headers), response.status)
|
||||
}
|
||||
const body = await response.json() as ReleaseResponse[]
|
||||
return resolveLatestMenubarReleaseAssets(body)
|
||||
return resolveLatestMenubarReleaseAssets(body, spec)
|
||||
}
|
||||
|
||||
/// 5xx means "GitHub/the CDN is unhappy right now" and is worth another attempt. 4xx is not:
|
||||
|
|
@ -482,7 +515,165 @@ async function killRunningApp(): Promise<void> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Windows mirror of the mac install below: pin the release to the CLI's own version, fall back
|
||||
/// to the newest windows-v* release, verify the sha256 before anything executes the file, hand
|
||||
/// the .msi to msiexec, then launch what it installed.
|
||||
const WINDOWS_UNINSTALL_KEYS = [
|
||||
'HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
|
||||
'HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
|
||||
'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
|
||||
]
|
||||
/// 3010 is "installed, reboot to finish"; 1602 is the user closing the UAC/installer prompt.
|
||||
const MSI_EXIT_REBOOT_REQUIRED = 3010
|
||||
const MSI_EXIT_USER_CANCEL = 1602
|
||||
|
||||
export type WindowsInstallHooks = {
|
||||
fetchOptions?: AssetFetchOptions
|
||||
apiFetch?: ReleaseApiFetch
|
||||
runInstaller?: (exe: string, args: string[]) => Promise<number>
|
||||
queryRegistry?: () => Promise<string>
|
||||
launch?: (exePath: string) => void
|
||||
log?: (message: string) => void
|
||||
stagingDir?: string
|
||||
env?: NodeJS.ProcessEnv
|
||||
}
|
||||
|
||||
export type InstalledWindowsMenubar = { version: string; exePath: string }
|
||||
|
||||
/// Windows' `CreateProcess` searches the current directory before `PATH`, so spawning `msiexec`
|
||||
/// or `reg` by bare name lets anything dropped next to the CLI impersonate a system tool. Same
|
||||
/// rule the tray app follows (windows/src-tauri/src/cli.rs: system32_path).
|
||||
export function resolveSystem32Path(exe: string, env: NodeJS.ProcessEnv = process.env): string {
|
||||
const root = env.SystemRoot
|
||||
const base = root && /^[a-zA-Z]:[\\/]/.test(root) ? root.replace(/[\\/]+$/, '') : 'C:\\Windows'
|
||||
return `${base}\\System32\\${exe}`
|
||||
}
|
||||
|
||||
/// Reads `reg query ... /s` output, which prints one blank-line separated block per subkey.
|
||||
export function parseInstalledWindowsMenubar(regOutput: string): InstalledWindowsMenubar | undefined {
|
||||
for (const block of regOutput.split(/\r?\n\s*\r?\n/)) {
|
||||
const values = new Map<string, string>()
|
||||
for (const line of block.split(/\r?\n/)) {
|
||||
const match = /^\s+(.+?)\s{4}REG_\w+\s{4}(.*)$/.exec(line)
|
||||
if (match) values.set(match[1]!.trim(), match[2]!.trim())
|
||||
}
|
||||
if (values.get('DisplayName') !== WINDOWS_PRODUCT_NAME) continue
|
||||
const location = values.get('InstallLocation')
|
||||
// DisplayIcon is `<exe>[,<index>]` and points at the installed binary when there is no
|
||||
// InstallLocation to join onto.
|
||||
const icon = values.get('DisplayIcon')?.split(',')[0]?.trim()
|
||||
const exePath = location
|
||||
? `${location.replace(/[\\/]+$/, '')}\\${WINDOWS_PRODUCT_NAME}.exe`
|
||||
: icon
|
||||
if (!exePath) continue
|
||||
return { version: values.get('DisplayVersion') ?? '', exePath }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
async function queryWindowsUninstallRegistry(env: NodeJS.ProcessEnv): Promise<string> {
|
||||
const reg = resolveSystem32Path('reg.exe', env)
|
||||
// reg exits non-zero for a hive the machine does not have; an empty block is the right answer.
|
||||
const outputs = await Promise.all(
|
||||
WINDOWS_UNINSTALL_KEYS.map(key => captureCommand(reg, ['query', key, '/s']).catch(() => '')),
|
||||
)
|
||||
return outputs.join('\n\n')
|
||||
}
|
||||
|
||||
async function runMsiexec(exe: string, args: string[]): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn(exe, args, { stdio: 'inherit' })
|
||||
proc.on('error', reject)
|
||||
proc.on('close', code => resolve(code ?? 1))
|
||||
})
|
||||
}
|
||||
|
||||
function launchWindowsApp(exePath: string): void {
|
||||
const proc = spawn(exePath, [], { detached: true, stdio: 'ignore' })
|
||||
proc.on('error', err => console.error(`Could not launch ${exePath}: ${err.message}`))
|
||||
proc.unref()
|
||||
}
|
||||
|
||||
async function stageWindowsInstaller(
|
||||
assets: ResolvedAssets,
|
||||
stagingDir: string,
|
||||
hooks: WindowsInstallHooks,
|
||||
log: (message: string) => void,
|
||||
): Promise<string> {
|
||||
const { zip: msi, checksum } = assets
|
||||
const msiPath = join(stagingDir, msi.name)
|
||||
log(`Downloading ${msi.name}...`)
|
||||
await downloadToFile(msi.browser_download_url, msiPath, hooks.fetchOptions)
|
||||
log('Verifying checksum...')
|
||||
await verifyChecksum(msiPath, checksum.browser_download_url, hooks.fetchOptions)
|
||||
return msiPath
|
||||
}
|
||||
|
||||
async function installWindowsMenubarApp(options: InstallOptions): Promise<InstallResult> {
|
||||
const hooks = options.windows ?? {}
|
||||
const log = hooks.log ?? console.log
|
||||
const env = hooks.env ?? process.env
|
||||
const queryRegistry = hooks.queryRegistry ?? (() => queryWindowsUninstallRegistry(env))
|
||||
const launch = hooks.launch ?? launchWindowsApp
|
||||
const cliVersion = options.cliVersion ? normalizeCliVersion(options.cliVersion) : ''
|
||||
|
||||
const installed = parseInstalledWindowsMenubar(await queryRegistry())
|
||||
if (installed && !options.force && (!cliVersion || installed.version === cliVersion)) {
|
||||
launch(installed.exePath)
|
||||
log('Launched CodeBurn Menubar.')
|
||||
return { installedPath: installed.exePath, launched: true }
|
||||
}
|
||||
|
||||
let assets: ResolvedAssets
|
||||
if (cliVersion) {
|
||||
log(`Resolving CodeBurn Menubar v${cliVersion}...`)
|
||||
assets = resolveVersionedMenubarReleaseAssets(cliVersion, WINDOWS_RELEASE)
|
||||
} else {
|
||||
log('Looking up the latest CodeBurn Menubar release...')
|
||||
assets = await fetchLatestReleaseAssets(WINDOWS_RELEASE, hooks.apiFetch)
|
||||
}
|
||||
|
||||
const stagingDir = hooks.stagingDir ?? await (async () => {
|
||||
await mkdir(getCodeburnCacheDir(), { recursive: true })
|
||||
return mkdtemp(join(getCodeburnCacheDir(), 'menubar-'))
|
||||
})()
|
||||
try {
|
||||
let msiPath: string
|
||||
try {
|
||||
msiPath = await stageWindowsInstaller(assets, stagingDir, hooks, log)
|
||||
} catch (err) {
|
||||
if (!cliVersion || !isMissingDirectAssetError(err)) throw err
|
||||
log(`CodeBurn Menubar v${cliVersion} assets were not found. Looking up the latest CodeBurn Menubar release...`)
|
||||
assets = await fetchLatestReleaseAssets(WINDOWS_RELEASE, hooks.apiFetch)
|
||||
msiPath = await stageWindowsInstaller(assets, stagingDir, hooks, log)
|
||||
}
|
||||
|
||||
log('Installing...')
|
||||
const msiexec = resolveSystem32Path('msiexec.exe', env)
|
||||
const exitCode = await (hooks.runInstaller ?? runMsiexec)(msiexec, ['/i', msiPath, '/passive', '/norestart'])
|
||||
if (exitCode === MSI_EXIT_USER_CANCEL) {
|
||||
log('Installation was cancelled; nothing was installed.')
|
||||
return { installedPath: '', launched: false }
|
||||
}
|
||||
if (exitCode !== 0 && exitCode !== MSI_EXIT_REBOOT_REQUIRED) {
|
||||
throw new Error(`msiexec exited with ${exitCode} while installing ${assets.zip.name}.`)
|
||||
}
|
||||
if (exitCode === MSI_EXIT_REBOOT_REQUIRED) log('Windows wants a restart to finish the install.')
|
||||
|
||||
const nowInstalled = parseInstalledWindowsMenubar(await queryRegistry())
|
||||
if (!nowInstalled) {
|
||||
throw new Error('CodeBurn Menubar installed, but it was not found in the uninstall registry; start it from the Start menu.')
|
||||
}
|
||||
launch(nowInstalled.exePath)
|
||||
log('Launched CodeBurn Menubar.')
|
||||
return { installedPath: nowInstalled.exePath, launched: true }
|
||||
} finally {
|
||||
if (!hooks.stagingDir) await rm(stagingDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
export async function installMenubarApp(options: InstallOptions = {}): Promise<InstallResult> {
|
||||
if ((options.platform ?? platform()) === 'win32') return installWindowsMenubarApp(options)
|
||||
await ensureSupportedPlatform()
|
||||
await persistCodeburnPath()
|
||||
|
||||
|
|
|
|||
299
tests/menubar-installer-windows.test.ts
Normal file
299
tests/menubar-installer-windows.test.ts
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
import { createHash } from 'node:crypto'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
WINDOWS_RELEASE,
|
||||
installMenubarApp,
|
||||
parseInstalledWindowsMenubar,
|
||||
resolveLatestMenubarReleaseAssets,
|
||||
resolveSystem32Path,
|
||||
resolveVersionedMenubarReleaseAssets,
|
||||
type ReleaseResponse,
|
||||
} from '../src/menubar-installer.js'
|
||||
|
||||
function asset(name: string) {
|
||||
return { name, browser_download_url: `https://example.test/${name}` }
|
||||
}
|
||||
|
||||
const MSI_URL =
|
||||
'https://github.com/getagentseal/codeburn/releases/download/windows-v0.9.20/CodeBurn.Menubar_0.9.20_x64_en-US.msi'
|
||||
const MSI_BYTES = 'msi-bytes'
|
||||
|
||||
function sha256(text: string): string {
|
||||
return createHash('sha256').update(Buffer.from(text)).digest('hex')
|
||||
}
|
||||
|
||||
function httpResponse(status: number, body?: string) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: () => null },
|
||||
body: body === undefined ? null : new Response(body).body,
|
||||
text: async () => body ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
/** reg query /s output, one blank-line separated block per subkey. */
|
||||
function regBlock(values: Record<string, string>, key = '{9c1e2f0a-0000-0000-0000-000000000001}'): string {
|
||||
const lines = Object.entries(values).map(([name, value]) => ` ${name} REG_SZ ${value}`)
|
||||
return [
|
||||
'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{other}',
|
||||
' DisplayName REG_SZ Some Other App',
|
||||
'',
|
||||
`HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${key}`,
|
||||
...lines,
|
||||
'',
|
||||
].join('\r\n')
|
||||
}
|
||||
|
||||
const INSTALLED_0_9_20 = regBlock({
|
||||
DisplayName: 'CodeBurn Menubar',
|
||||
DisplayVersion: '0.9.20',
|
||||
InstallLocation: 'C:\\Program Files\\CodeBurn Menubar\\',
|
||||
Publisher: 'AgentSeal',
|
||||
})
|
||||
|
||||
describe('windows release asset resolution', () => {
|
||||
it('builds direct release asset URLs from the CLI version', () => {
|
||||
const resolved = resolveVersionedMenubarReleaseAssets('0.9.20', WINDOWS_RELEASE)
|
||||
|
||||
expect(resolved.release.tag_name).toBe('windows-v0.9.20')
|
||||
expect(resolved.zip.name).toBe('CodeBurn.Menubar_0.9.20_x64_en-US.msi')
|
||||
expect(resolved.zip.browser_download_url).toBe(MSI_URL)
|
||||
expect(resolved.checksum.browser_download_url).toBe(`${MSI_URL}.sha256`)
|
||||
})
|
||||
|
||||
it('normalizes a leading v', () => {
|
||||
expect(resolveVersionedMenubarReleaseAssets('v0.9.20', WINDOWS_RELEASE).release.tag_name).toBe('windows-v0.9.20')
|
||||
})
|
||||
|
||||
it('scans for the newest windows-v release that has both assets', () => {
|
||||
const releases: ReleaseResponse[] = [
|
||||
{ tag_name: 'mac-v0.9.20', assets: [asset('CodeBurnMenubar-v0.9.20.zip'), asset('CodeBurnMenubar-v0.9.20.zip.sha256')] },
|
||||
{ tag_name: 'windows-v0.9.21', assets: [asset('CodeBurn.Menubar_0.9.21_x64_en-US.msi')] },
|
||||
{
|
||||
tag_name: 'windows-v0.9.20',
|
||||
assets: [asset('CodeBurn.Menubar_0.9.20_x64_en-US.msi'), asset('CodeBurn.Menubar_0.9.20_x64_en-US.msi.sha256')],
|
||||
},
|
||||
]
|
||||
|
||||
const resolved = resolveLatestMenubarReleaseAssets(releases, WINDOWS_RELEASE)
|
||||
|
||||
expect(resolved.release.tag_name).toBe('windows-v0.9.20')
|
||||
expect(resolved.zip.name).toBe('CodeBurn.Menubar_0.9.20_x64_en-US.msi')
|
||||
})
|
||||
|
||||
it('reports when no windows release carries both assets', () => {
|
||||
expect(() => resolveLatestMenubarReleaseAssets([{ tag_name: 'v0.9.20', assets: [] }], WINDOWS_RELEASE))
|
||||
.toThrow(/No windows-v\* release/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveSystem32Path', () => {
|
||||
it('uses an absolute SystemRoot', () => {
|
||||
expect(resolveSystem32Path('msiexec.exe', { SystemRoot: 'D:\\Windows' })).toBe('D:\\Windows\\System32\\msiexec.exe')
|
||||
})
|
||||
|
||||
it('falls back to the documented default when SystemRoot is missing or relative', () => {
|
||||
expect(resolveSystem32Path('reg.exe', {})).toBe('C:\\Windows\\System32\\reg.exe')
|
||||
expect(resolveSystem32Path('reg.exe', { SystemRoot: 'Windows' })).toBe('C:\\Windows\\System32\\reg.exe')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseInstalledWindowsMenubar', () => {
|
||||
it('reads the version and joins the exe onto InstallLocation', () => {
|
||||
expect(parseInstalledWindowsMenubar(INSTALLED_0_9_20)).toEqual({
|
||||
version: '0.9.20',
|
||||
exePath: 'C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to DisplayIcon when there is no InstallLocation', () => {
|
||||
const output = regBlock({
|
||||
DisplayName: 'CodeBurn Menubar',
|
||||
DisplayVersion: '0.9.20',
|
||||
DisplayIcon: 'C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe,0',
|
||||
})
|
||||
|
||||
expect(parseInstalledWindowsMenubar(output)?.exePath).toBe('C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe')
|
||||
})
|
||||
|
||||
it('returns undefined when the product is not installed', () => {
|
||||
expect(parseInstalledWindowsMenubar(regBlock({ DisplayName: 'Something Else', DisplayVersion: '1.0' }))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('installMenubarApp on windows', () => {
|
||||
let sandbox: string
|
||||
let logs: string[]
|
||||
let launched: string[]
|
||||
let installerCalls: Array<{ exe: string; args: string[] }>
|
||||
|
||||
function hooks(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
stagingDir: sandbox,
|
||||
env: { SystemRoot: 'C:\\Windows' },
|
||||
log: (message: string) => { logs.push(message) },
|
||||
launch: (exePath: string) => { launched.push(exePath) },
|
||||
queryRegistry: async () => INSTALLED_0_9_20,
|
||||
runInstaller: async (exe: string, args: string[]) => { installerCalls.push({ exe, args }); return 0 },
|
||||
fetchOptions: {
|
||||
sleep: async () => {},
|
||||
log: (message: string) => { logs.push(message) },
|
||||
fetchImpl: async (url: string) => httpResponse(200, url.endsWith('.sha256')
|
||||
? `${sha256(MSI_BYTES)} CodeBurn.Menubar_0.9.20_x64_en-US.msi`
|
||||
: MSI_BYTES),
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
sandbox = await mkdtemp(join(tmpdir(), 'menubar-windows-'))
|
||||
logs = []
|
||||
launched = []
|
||||
installerCalls = []
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(sandbox, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('skips the download and just launches when the pinned version is already installed', async () => {
|
||||
let fetches = 0
|
||||
const result = await installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({ fetchOptions: { fetchImpl: async () => { fetches++; return httpResponse(500) } } }),
|
||||
})
|
||||
|
||||
expect(fetches).toBe(0)
|
||||
expect(installerCalls).toEqual([])
|
||||
expect(launched).toEqual(['C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe'])
|
||||
expect(result).toEqual({ installedPath: 'C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe', launched: true })
|
||||
})
|
||||
|
||||
it('downloads, verifies, runs msiexec from System32 and launches the installed app', async () => {
|
||||
let queries = 0
|
||||
const result = await installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({
|
||||
queryRegistry: async () => (queries++ === 0 ? '' : INSTALLED_0_9_20),
|
||||
}),
|
||||
})
|
||||
|
||||
expect(installerCalls).toEqual([{
|
||||
exe: 'C:\\Windows\\System32\\msiexec.exe',
|
||||
args: ['/i', join(sandbox, 'CodeBurn.Menubar_0.9.20_x64_en-US.msi'), '/passive', '/norestart'],
|
||||
}])
|
||||
expect(launched).toEqual(['C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe'])
|
||||
expect(result.launched).toBe(true)
|
||||
expect(logs).toContain('Downloading CodeBurn.Menubar_0.9.20_x64_en-US.msi...')
|
||||
expect(logs).toContain('Verifying checksum...')
|
||||
expect(logs).toContain('Installing...')
|
||||
expect(logs).toContain('Launched CodeBurn Menubar.')
|
||||
})
|
||||
|
||||
it('reinstalls the same version when --force is passed', async () => {
|
||||
await installMenubarApp({ platform: 'win32', cliVersion: '0.9.20', force: true, windows: hooks() })
|
||||
|
||||
expect(installerCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('aborts on a checksum mismatch without running the installer', async () => {
|
||||
await expect(installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({
|
||||
queryRegistry: async () => '',
|
||||
fetchOptions: {
|
||||
sleep: async () => {},
|
||||
log: () => {},
|
||||
fetchImpl: async (url: string) =>
|
||||
httpResponse(200, url.endsWith('.sha256') ? `${sha256('other-bytes')} x.msi` : MSI_BYTES),
|
||||
},
|
||||
}),
|
||||
})).rejects.toThrow(/Checksum mismatch/)
|
||||
|
||||
expect(installerCalls).toEqual([])
|
||||
expect(launched).toEqual([])
|
||||
})
|
||||
|
||||
it('treats 3010 as installed and says a restart is pending', async () => {
|
||||
let queries = 0
|
||||
const result = await installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({
|
||||
queryRegistry: async () => (queries++ === 0 ? '' : INSTALLED_0_9_20),
|
||||
runInstaller: async (exe: string, args: string[]) => { installerCalls.push({ exe, args }); return 3010 },
|
||||
}),
|
||||
})
|
||||
|
||||
expect(result.launched).toBe(true)
|
||||
expect(logs.some(line => line.includes('restart'))).toBe(true)
|
||||
})
|
||||
|
||||
it('treats 1602 as a cancelled install: no launch, no error', async () => {
|
||||
const result = await installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({
|
||||
queryRegistry: async () => '',
|
||||
runInstaller: async () => 1602,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(result).toEqual({ installedPath: '', launched: false })
|
||||
expect(launched).toEqual([])
|
||||
expect(logs.some(line => line.includes('cancelled'))).toBe(true)
|
||||
})
|
||||
|
||||
it('fails with the exit code for any other msiexec failure', async () => {
|
||||
await expect(installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({ queryRegistry: async () => '', runInstaller: async () => 1603 }),
|
||||
})).rejects.toThrow(/msiexec exited with 1603/)
|
||||
|
||||
expect(launched).toEqual([])
|
||||
})
|
||||
|
||||
it('falls back to the release API when the pinned assets are missing', async () => {
|
||||
let queries = 0
|
||||
const requested: string[] = []
|
||||
const latest: ReleaseResponse[] = [{
|
||||
tag_name: 'windows-v0.9.19',
|
||||
assets: [
|
||||
{ name: 'CodeBurn.Menubar_0.9.19_x64_en-US.msi', browser_download_url: 'https://example.test/msi' },
|
||||
{ name: 'CodeBurn.Menubar_0.9.19_x64_en-US.msi.sha256', browser_download_url: 'https://example.test/msi.sha256' },
|
||||
],
|
||||
}]
|
||||
|
||||
const result = await installMenubarApp({
|
||||
platform: 'win32',
|
||||
cliVersion: '0.9.20',
|
||||
windows: hooks({
|
||||
queryRegistry: async () => (queries++ === 0 ? '' : INSTALLED_0_9_20),
|
||||
apiFetch: async () => ({ ok: true, status: 200, headers: { get: () => null }, json: async () => latest }),
|
||||
fetchOptions: {
|
||||
sleep: async () => {},
|
||||
log: () => {},
|
||||
fetchImpl: async (url: string) => {
|
||||
requested.push(url)
|
||||
if (url.startsWith(MSI_URL)) return httpResponse(404)
|
||||
return httpResponse(200, url.endsWith('.sha256') ? `${sha256(MSI_BYTES)} msi` : MSI_BYTES)
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
expect(requested[0]).toBe(MSI_URL)
|
||||
expect(requested).toContain('https://example.test/msi')
|
||||
expect(installerCalls[0]?.args[1]).toBe(join(sandbox, 'CodeBurn.Menubar_0.9.19_x64_en-US.msi'))
|
||||
expect(result.launched).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -174,6 +174,12 @@ npm run tauri build
|
|||
`.github/workflows/release-menubar-windows.yml`; publishes the `.msi` (plus its sha256) to
|
||||
a "Windows Menubar vX" release. Unsigned for now, so Windows SmartScreen prompts on first run
|
||||
until a signing cert is in place.
|
||||
- `codeburn menubar` installs from those assets (`src/menubar-installer.ts`): it pins the tag to
|
||||
the CLI's own version (`windows-v<cliVersion>`), falls back to a scan of the newest `windows-v*`
|
||||
release carrying both assets, verifies the sha256 before anything executes the file, then runs
|
||||
`%SystemRoot%\System32\msiexec.exe /i <msi> /passive /norestart` and launches the exe named by
|
||||
the product's Uninstall registry key. Renaming the bundle or the MSI asset breaks that lookup —
|
||||
`WINDOWS_RELEASE` and `WINDOWS_PRODUCT_NAME` in the installer have to move with it.
|
||||
|
||||
## Pending work
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue