diff --git a/app/electron/cli.ts b/app/electron/cli.ts index 07b61b9c..a25749a6 100644 --- a/app/electron/cli.ts +++ b/app/electron/cli.ts @@ -948,12 +948,16 @@ export function spawnCli( /** Spawn a config-mutating CLI command and return its text output verbatim. * Mutations count as interactive, so they take a run slot ahead of any queued * background warm — a Settings save is never stuck behind speculative prefetch. */ -export function spawnCliAction(args: string[], opts: { timeoutMs?: number } = {}): Promise { +export function spawnCliAction(args: string[], opts: { timeoutMs?: number; extraEnv?: NodeJS.ProcessEnv } = {}): Promise { if (shuttingDown) return Promise.resolve({ ok: false, stdout: '', stderr: 'codeburn is shutting down', code: null }) const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS const target = resolveTarget() if (!target) return Promise.resolve({ ok: false, stdout: '', stderr: 'codeburn CLI not found', code: null }) const spec = spawnSpecFor(target, args) + // Actions never ride the resident `serve` child, so an extra variable simply joins the + // one-shot spawn's env. The bundled-menubar install is the only caller: it names the .msi + // the desktop app staged rather than putting a path on a command line. + if (opts.extraEnv) spec.env = { ...spec.env, ...opts.extraEnv } return (async () => { try { await acquireSlot('interactive') diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts index f217146c..f12c6ba0 100644 --- a/app/electron/main.test.ts +++ b/app/electron/main.test.ts @@ -70,6 +70,9 @@ const CHANNELS = [ 'codeburn:telemetryOnboarded', 'codeburn:telemetryTrack', 'codeburn:getUpdateStatus', + 'codeburn:companionStatus', + 'codeburn:setMenuBarEnabled', + 'codeburn:setSidebarEnabled', 'codeburn:pluginList', 'codeburn:pluginInfo', 'codeburn:pluginAdd', diff --git a/app/electron/main.ts b/app/electron/main.ts index df6c24f2..f9534c1b 100644 --- a/app/electron/main.ts +++ b/app/electron/main.ts @@ -2,6 +2,7 @@ import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, shell, type Men import path from 'node:path' import { CliError, DESKTOP_COLD_TIMEOUT_MS, PROGRESS_LINE_PREFIX, reapOrphanServe, resolveCodeburnPath, shutdownAll, spawnCli, spawnCliAction, startServe, type ActionResult, type SpawnPriority } from './cli' +import { MenubarCompanion, type CompanionStatus } from './menubar' import { getQuota, sanitizeError } from './quota' import { Telemetry } from './telemetry' import { createUpdateChecker, type UpdateChecker, type UpdateStatus } from './updates' @@ -10,6 +11,11 @@ import { createUpdateChecker, type UpdateChecker, type UpdateStatus } from './up let telemetryInstance: Telemetry | null = null // The once-per-launch + 24h update-availability checker. Null under tests. let updateChecker: UpdateChecker | null = null +// The bundled tray app and its Capacity Dock (Windows only). Null under tests. +let companion: MenubarCompanion | null = null + +/** What the sidebar switches read on a platform that has no tray app to bundle. */ +export const NO_COMPANION: CompanionStatus = { supported: false, menuBar: false, sidebar: false, store: false } /** The slice of Telemetry the bridge handlers use — injectable for tests. */ export type TelemetryBridge = Pick @@ -231,6 +237,8 @@ type Deps = { telemetry?: TelemetryBridge | null /** Cached update-availability status; absent under tests unless injected. */ getUpdateStatus?: () => Promise + /** The bundled tray app and Capacity Dock; absent off Windows and under tests. */ + companion?: Pick | null } type Handler = (...args: any[]) => Promise @@ -240,7 +248,7 @@ type Handler = (...args: any[]) => Promise * shell) and returns a result envelope. Pure + injectable so the wiring is * unit-testable without launching Electron. */ -export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, resolveCodeburnPath, getQuota, emitProgress: broadcastProgress, telemetry: telemetryInstance, getUpdateStatus: () => updateChecker ? updateChecker.getStatus() : Promise.resolve(NO_UPDATE_STATUS) }): Record { +export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, resolveCodeburnPath, getQuota, emitProgress: broadcastProgress, telemetry: telemetryInstance, getUpdateStatus: () => updateChecker ? updateChecker.getStatus() : Promise.resolve(NO_UPDATE_STATUS), companion: companion }): Record { const emitProgress = deps.emitProgress ?? (() => {}) const telemetry = deps.telemetry ?? null // Flips true after the first overview fetch succeeds. Until then, every @@ -427,6 +435,14 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re // One-shot read of the cached update-availability status. The check itself // runs in the background (launch + 24h); this returns whatever is known. 'codeburn:getUpdateStatus': async () => ({ ok: true, value: deps.getUpdateStatus ? await deps.getUpdateStatus() : NO_UPDATE_STATUS }), + // The bundled tray app and its Capacity Dock (Windows). Every setter answers with the + // whole status, so the sidebar renders the state that actually took rather than the one + // it asked for: an install that was cancelled leaves the switch where it was. + 'codeburn:companionStatus': async () => ({ ok: true, value: deps.companion ? deps.companion.status() : NO_COMPANION }), + 'codeburn:setMenuBarEnabled': async (enabled?: boolean) => + ({ ok: true, value: deps.companion ? await deps.companion.setMenuBarEnabled(Boolean(enabled)) : NO_COMPANION }), + 'codeburn:setSidebarEnabled': async (enabled?: boolean) => + ({ ok: true, value: deps.companion ? await deps.companion.setSidebarEnabled(Boolean(enabled)) : NO_COMPANION }), // Plugin management reads (all return parsed JSON) 'codeburn:pluginList': run(() => ['plugin', 'list', '--json']), 'codeburn:pluginInfo': run((name: string) => ['plugin', 'info', vToken(name), '--json']), @@ -651,6 +667,18 @@ function bootstrap(): void { } catch (err) { console.error('telemetry init failed (continuing without):', err) } + // The tray app and the Capacity Dock the desktop app carries on Windows. Constructed + // before the handlers so the sidebar's switches have something to read, and installed in + // the background so a `/passive` msiexec run never holds the first window back. + companion = new MenubarCompanion({ + resourcesPath: app.isPackaged ? process.resourcesPath : null, + stateDir: app.getPath('userData'), + // Electron sets this in an installed AppX package, which is the Store route. + store: (process as NodeJS.Process & { windowsStore?: boolean }).windowsStore === true, + platform: process.platform, + env: process.env, + }) + void companion.bootstrap().catch(err => console.error('menubar bootstrap failed:', err)) registerHandlers() installApplicationMenu() createWindow() diff --git a/app/electron/menubar.test.ts b/app/electron/menubar.test.ts new file mode 100644 index 00000000..f194b683 --- /dev/null +++ b/app/electron/menubar.test.ts @@ -0,0 +1,322 @@ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { + BUNDLED_MSI_ENV, + BUNDLED_RESULT_PREFIX, + MenubarCompanion, + dockPrefsPath, + findPackagedTrayExe, + findStagedMsi, + parseInstallResult, + readCompanionSettings, + runKeyArgs, + system32Path, + writeCompanionSettings, + writeDockEnabled, + type MenubarInstallResult, +} from './menubar' + +const VERSION = '0.9.23' +const MSI_NAME = `CodeBurn.Menubar_${VERSION}_x64_en-US.msi` +const TRAY_EXE = 'C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe' + +function result(overrides: Partial = {}): MenubarInstallResult { + return { + action: 'installed', + bundledVersion: VERSION, + previousVersion: null, + exePath: TRAY_EXE, + uninstallString: 'MsiExec.exe /X{guid}', + installedBy: 'desktop', + ...overrides, + } +} + +describe('staged tray app discovery', () => { + let sandbox: string + + beforeEach(() => { sandbox = mkdtempSync(join(tmpdir(), 'companion-')) }) + afterEach(() => { rmSync(sandbox, { recursive: true, force: true }) }) + + it('reads the version out of the staged asset name', () => { + writeFileSync(join(sandbox, MSI_NAME), 'msi') + expect(findStagedMsi(sandbox)).toEqual({ path: join(sandbox, MSI_NAME), version: VERSION }) + }) + + it('ignores anything that is not the release asset, and a directory that is not there', () => { + writeFileSync(join(sandbox, 'CodeBurn-Setup-0.9.23.exe'), 'nope') + expect(findStagedMsi(sandbox)).toBeNull() + expect(findStagedMsi(join(sandbox, 'missing'))).toBeNull() + }) + + it('finds the packaged tray executable only when it is there', () => { + expect(findPackagedTrayExe(sandbox)).toBeNull() + writeFileSync(join(sandbox, 'codeburn-menubar.exe'), 'exe') + expect(findPackagedTrayExe(sandbox)).toBe(join(sandbox, 'codeburn-menubar.exe')) + }) +}) + +describe('parseInstallResult', () => { + it('picks the one machine-readable line out of the installer prose', () => { + const stdout = [ + 'Verifying checksum...', + 'Installing...', + `${BUNDLED_RESULT_PREFIX}${JSON.stringify(result())}`, + 'Installed CodeBurn Menubar 0.9.23.', + ].join('\r\n') + + expect(parseInstallResult(stdout)).toEqual(result()) + }) + + it('is null when the installer said nothing machine-readable, or said it badly', () => { + expect(parseInstallResult('Installing...\n')).toBeNull() + expect(parseInstallResult(`${BUNDLED_RESULT_PREFIX}{not json`)).toBeNull() + }) +}) + +describe('runKeyArgs', () => { + it('writes and removes the same value the tray app\u2019s own toggle owns', () => { + expect(runKeyArgs(true, TRAY_EXE)).toEqual([ + 'add', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', + '/v', 'CodeBurn', '/t', 'REG_SZ', '/d', `"${TRAY_EXE}"`, '/f', + ]) + expect(runKeyArgs(false, TRAY_EXE)).toEqual([ + 'delete', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', 'CodeBurn', '/f', + ]) + }) +}) + +describe('system32Path', () => { + it('never resolves a system tool by bare name', () => { + expect(system32Path('reg.exe', { SystemRoot: 'D:\\Windows' })).toBe('D:\\Windows\\System32\\reg.exe') + expect(system32Path('reg.exe', {})).toBe('C:\\Windows\\System32\\reg.exe') + }) +}) + +describe('the dock preference file', () => { + let home: string + + beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'companion-home-')) }) + afterEach(() => { rmSync(home, { recursive: true, force: true }) }) + + it('creates the file the tray app reads before its page exists', () => { + writeDockEnabled(true, home) + expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toEqual({ enabled: true }) + }) + + it('keeps every key the tray app owns', () => { + mkdirSync(join(home, '.config', 'codeburn'), { recursive: true }) + writeFileSync(dockPrefsPath(home), JSON.stringify({ enabled: true, scale: 1.2, preferred: 'claude' })) + + writeDockEnabled(false, home) + + expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))) + .toEqual({ enabled: false, scale: 1.2, preferred: 'claude' }) + }) +}) + +describe('companion settings', () => { + let stateDir: string + + beforeEach(() => { stateDir = mkdtempSync(join(tmpdir(), 'companion-state-')) }) + afterEach(() => { rmSync(stateDir, { recursive: true, force: true }) }) + + it('defaults both switches on before anything has been written', () => { + expect(readCompanionSettings(stateDir)).toEqual({ menuBar: true, sidebar: true, trayExePath: null, seeded: false }) + }) + + it('round-trips, and falls back to the defaults on an unreadable file', () => { + writeCompanionSettings(stateDir, { menuBar: false, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + expect(readCompanionSettings(stateDir)).toEqual({ menuBar: false, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + + writeFileSync(join(stateDir, 'companion.v1.json'), '{ broken') + expect(readCompanionSettings(stateDir).menuBar).toBe(true) + }) +}) + +describe('MenubarCompanion', () => { + let sandbox: string + let resources: string + let stateDir: string + let home: string + let launches: Array<{ exe: string; args: string[] }> + let regCalls: string[][] + let cliCalls: Array<{ args: string[]; env: NodeJS.ProcessEnv | undefined }> + let installResult: MenubarInstallResult | null + + function deps(overrides: Record = {}) { + return { + resourcesPath: resources, + stateDir, + store: false, + platform: 'win32', + env: { SystemRoot: 'C:\\Windows' }, + home, + launch: (exe: string, args: string[]) => { launches.push({ exe, args }) }, + runReg: async (args: string[]) => { regCalls.push(args) }, + runCli: async (args: string[], opts: { extraEnv?: NodeJS.ProcessEnv }) => { + cliCalls.push({ args, env: opts.extraEnv }) + return { + ok: true, + stdout: installResult ? `Installing...\n${BUNDLED_RESULT_PREFIX}${JSON.stringify(installResult)}\n` : 'Installing...\n', + stderr: '', + code: 0, + } + }, + ...overrides, + } + } + + function stageMsi(): void { + mkdirSync(join(resources, 'menubar'), { recursive: true }) + writeFileSync(join(resources, 'menubar', MSI_NAME), 'msi') + } + + function stageExe(): string { + mkdirSync(join(resources, 'menubar'), { recursive: true }) + const exe = join(resources, 'menubar', 'codeburn-menubar.exe') + writeFileSync(exe, 'exe') + return exe + } + + beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), 'companion-app-')) + resources = join(sandbox, 'resources') + stateDir = join(sandbox, 'state') + home = join(sandbox, 'home') + mkdirSync(resources, { recursive: true }) + launches = [] + regCalls = [] + cliCalls = [] + installResult = result() + }) + + afterEach(() => { rmSync(sandbox, { recursive: true, force: true }) }) + + it('is unsupported off Windows and on a build with nothing staged', () => { + expect(new MenubarCompanion(deps()).status().supported).toBe(false) + stageMsi() + expect(new MenubarCompanion(deps({ platform: 'darwin' })).status().supported).toBe(false) + expect(new MenubarCompanion(deps()).status().supported).toBe(true) + // The Store route wants the executable itself; an .msi it cannot run is not support. + expect(new MenubarCompanion(deps({ store: true })).status().supported).toBe(false) + }) + + it('installs through the CLI, naming the staged file in the environment', async () => { + stageMsi() + await new MenubarCompanion(deps()).bootstrap() + + expect(cliCalls).toEqual([{ + args: ['menubar'], + env: { [BUNDLED_MSI_ENV]: join(resources, 'menubar', MSI_NAME) }, + }]) + expect(regCalls).toEqual([runKeyArgs(true, TRAY_EXE)]) + expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }]) + expect(readCompanionSettings(stateDir)).toMatchObject({ trayExePath: TRAY_EXE, seeded: true }) + }) + + it('seeds the Capacity Dock on first run only', async () => { + stageMsi() + await new MenubarCompanion(deps()).bootstrap() + expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toEqual({ enabled: true }) + + // A person turning the rail off in the tray app's own settings must not find it back on. + writeDockEnabled(false, home) + await new MenubarCompanion(deps()).bootstrap() + expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toEqual({ enabled: false }) + }) + + it('does nothing at all with the Menu bar switch off', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: false, sidebar: true, trayExePath: null, seeded: true }) + + await new MenubarCompanion(deps()).bootstrap() + + expect(cliCalls).toEqual([]) + expect(launches).toEqual([]) + expect(regCalls).toEqual([]) + }) + + it('launches the packaged executable and writes no Run value on the Store route', async () => { + const exe = stageExe() + await new MenubarCompanion(deps({ store: true })).bootstrap() + + expect(cliCalls).toEqual([]) + // Launch at login is the package manifest's own startup task there. + expect(regCalls).toEqual([]) + expect(launches).toEqual([{ exe, args: ['--reload-settings'] }]) + }) + + it('keeps the switch where it was when the install was cancelled', async () => { + stageMsi() + installResult = result({ action: 'cancelled', exePath: '', installedBy: null }) + + await new MenubarCompanion(deps()).bootstrap() + + expect(launches).toEqual([]) + expect(regCalls).toEqual([]) + expect(readCompanionSettings(stateDir).trayExePath).toBeNull() + }) + + it('keeps a working tray app when the installer reports nothing at all', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + installResult = null + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + + await new MenubarCompanion(deps()).bootstrap() + + expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }]) + error.mockRestore() + }) + + it('Menu bar off quits the tray app and drops the Run value', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + const companion = new MenubarCompanion(deps()) + + const status = await companion.setMenuBarEnabled(false) + + expect(status).toEqual({ supported: true, menuBar: false, sidebar: true, store: false }) + expect(regCalls).toEqual([runKeyArgs(false, TRAY_EXE)]) + expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--quit'] }]) + // The dock preference is untouched, so turning the tray back on restores the rail. + expect(() => readFileSync(dockPrefsPath(home), 'utf8')).toThrow() + }) + + it('Menu bar on installs if it has to, then starts the tray app again', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: false, sidebar: true, trayExePath: null, seeded: true }) + + const status = await new MenubarCompanion(deps()).setMenuBarEnabled(true) + + expect(status.menuBar).toBe(true) + expect(cliCalls).toHaveLength(1) + expect(regCalls).toEqual([runKeyArgs(true, TRAY_EXE)]) + expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }]) + }) + + it('Sidebar off writes the preference and asks a running tray app to notice', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + + const status = await new MenubarCompanion(deps()).setSidebarEnabled(false) + + expect(status.sidebar).toBe(false) + expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toEqual({ enabled: false }) + expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }]) + }) + + it('Sidebar with the tray app off writes the preference and tells nobody', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: false, sidebar: false, trayExePath: TRAY_EXE, seeded: true }) + + await new MenubarCompanion(deps()).setSidebarEnabled(true) + + expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toEqual({ enabled: true }) + expect(launches).toEqual([]) + }) +}) diff --git a/app/electron/menubar.ts b/app/electron/menubar.ts new file mode 100644 index 00000000..a0933ba0 --- /dev/null +++ b/app/electron/menubar.ts @@ -0,0 +1,360 @@ +// The tray app and the Capacity Dock, as the desktop app owns them on Windows. +// +// The desktop app ships the matching `windows-v*` build of the Tauri tray app +// (windows/) and puts it on the machine itself, so nobody has to know that +// `codeburn menubar` exists. Two switches in the sidebar turn each surface off: +// "Menu bar" is the tray process, "Sidebar" is the dock rail the tray app +// draws. Both default on. +// +// Two routes, and they share almost nothing: +// +// NSIS the staged `CodeBurn.Menubar__x64_en-US.msi` is installed +// through the CLI's own installer (src/menubar-installer.ts, reached +// with CODEBURN_MENUBAR_MSI). The MSI carries a fixed WiX upgrade +// code, so a manual `codeburn menubar` install is upgraded in place +// rather than duplicated, and a newer one is left alone. Launch at +// login is an HKCU Run value. +// +// AppX msiexec is not available to a packaged app and would fight the +// package manager anyway. The tray exe ships inside the package and +// is launched from there; launch at login is the manifest's +// windows.startupTask, so no Run value is written. +// +// The tray app is reached through its own argv: a second launch hands the +// running instance its arguments (windows/src-tauri/src/lib.rs), so `--quit` +// stops it and `--reload-settings` makes it re-read the dock preferences this +// module writes. + +import { spawn } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' +import { homedir } from 'node:os' +import { join } from 'node:path' + +import { spawnCliAction, type ActionResult } from './cli' + +/** Env var the CLI's Windows installer reads; the source of truth is src/menubar-installer.ts. */ +export const BUNDLED_MSI_ENV = 'CODEBURN_MENUBAR_MSI' +/** One machine-readable line the same installer prints, so this side need not read its prose. */ +export const BUNDLED_RESULT_PREFIX = 'CODEBURN_MENUBAR_RESULT ' +/** The release asset name, which is also the only version statement that cannot lie. */ +const MSI_PATTERN = /^CodeBurn\.Menubar_(.+)_x64_en-US\.msi$/ +/** What the Tauri bundle names its executable. */ +const TRAY_EXE = 'codeburn-menubar.exe' +/** The tray app's own Run value name, so the two never write a second copy of each other's. */ +const RUN_VALUE = 'CodeBurn' +const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' +/** A `/passive` msiexec run waits on a UAC prompt, which is a person, not a process. */ +const INSTALL_TIMEOUT_MS = 5 * 60_000 + +/** Mirrors BundledInstallResult in src/menubar-installer.ts. */ +export type MenubarInstallResult = { + action: 'installed' | 'up-to-date' | 'kept-newer' | 'cancelled' + bundledVersion: string + previousVersion: string | null + exePath: string + uninstallString: string | null + installedBy: 'desktop' | 'manual' | null +} + +/** The desktop app's own record of the two switches, in its userData directory. */ +export type CompanionSettings = { + menuBar: boolean + sidebar: boolean + /** Where the tray app ended up, so starting and stopping it costs no registry read. */ + trayExePath: string | null + /** False until the first launch has applied the defaults, which is what keeps a later + * manual "dock off" from being seeded back on at every launch. */ + seeded: boolean +} + +export const DEFAULT_COMPANION_SETTINGS: CompanionSettings = { + menuBar: true, + sidebar: true, + trayExePath: null, + seeded: false, +} + +export type MenubarDeps = { + /** Where the packaged app keeps its extraResources, or null in a build that has none. */ + resourcesPath: string | null + /** The desktop app's userData directory, which holds the companion settings file. */ + stateDir: string + /** True inside an AppX package: no msiexec, no Run value, the exe ships with the package. */ + store: boolean + platform: string + env: NodeJS.ProcessEnv + /** Injected so tests never spawn: the CLI action, a detached launch, and a `reg.exe` run. */ + runCli?: (args: string[], opts: { timeoutMs?: number; extraEnv?: NodeJS.ProcessEnv }) => Promise + launch?: (exePath: string, args: string[]) => void + runReg?: (args: string[]) => Promise + home?: string +} + +// Where things are ---------------------------------------------------------------------------- + +/** The staged tray app: `resources/menubar` in a packaged build, `build/menubar` in dev. */ +export function menubarResourcesDir(deps: Pick): string { + return deps.resourcesPath + ? join(deps.resourcesPath, 'menubar') + : join(__dirname, '..', '..', 'build', 'menubar') +} + +/** The staged .msi and the version its name declares, or null when nothing was staged. */ +export function findStagedMsi(dir: string): { path: string; version: string } | null { + let names: string[] + try { names = readdirSync(dir) } catch { return null } + for (const name of names) { + const version = MSI_PATTERN.exec(name)?.[1] + if (version) return { path: join(dir, name), version } + } + return null +} + +/** The tray executable shipped inside an AppX package, or null when it is not there. */ +export function findPackagedTrayExe(dir: string): string | null { + const exe = join(dir, TRAY_EXE) + return existsSync(exe) ? exe : null +} + +/** `~/.config/codeburn/windows-dock.json`, which is where the tray app's dock reads its + * preferences from before its page exists (windows/src-tauri/src/dock.rs). */ +export function dockPrefsPath(home = homedir()): string { + return join(home, '.config', 'codeburn', 'windows-dock.json') +} + +function companionSettingsPath(stateDir: string): string { + return join(stateDir, 'companion.v1.json') +} + +// Settings ------------------------------------------------------------------------------------- + +export function readCompanionSettings(stateDir: string): CompanionSettings { + try { + const raw = JSON.parse(readFileSync(companionSettingsPath(stateDir), 'utf8')) as Partial + return { + menuBar: raw.menuBar ?? DEFAULT_COMPANION_SETTINGS.menuBar, + sidebar: raw.sidebar ?? DEFAULT_COMPANION_SETTINGS.sidebar, + trayExePath: typeof raw.trayExePath === 'string' ? raw.trayExePath : null, + seeded: raw.seeded === true, + } + } catch { + return { ...DEFAULT_COMPANION_SETTINGS } + } +} + +export function writeCompanionSettings(stateDir: string, settings: CompanionSettings): void { + try { + mkdirSync(stateDir, { recursive: true }) + writeFileSync(companionSettingsPath(stateDir), `${JSON.stringify(settings, null, 2)}\n`) + } catch (err) { + console.error('companion settings could not be saved:', err) + } +} + +/** Read, change one key, write back. The tray app owns every other key in this file (the + * rail's placement, size and provider set), so the whole object is preserved. */ +export function writeDockEnabled(enabled: boolean, home = homedir()): void { + const path = dockPrefsPath(home) + let prefs: Record = {} + try { + const parsed: unknown = JSON.parse(readFileSync(path, 'utf8')) + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) prefs = parsed as Record + } catch { /* a missing or unreadable file simply starts from nothing */ } + prefs.enabled = enabled + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, `${JSON.stringify(prefs, null, 2)}\n`) +} + +// Talking to the tray app ---------------------------------------------------------------------- + +/** The CLI's install path prints one JSON line; everything else it says is for a person. */ +export function parseInstallResult(stdout: string): MenubarInstallResult | null { + for (const line of stdout.split(/\r?\n/)) { + if (!line.startsWith(BUNDLED_RESULT_PREFIX)) continue + try { return JSON.parse(line.slice(BUNDLED_RESULT_PREFIX.length)) as MenubarInstallResult } catch { return null } + } + return null +} + +/** `reg.exe` argv for the tray app's launch-at-login value. The tray app's own toggle writes + * the same value name (windows/src-tauri/src/autostart.rs), so the two agree by construction + * instead of leaving two entries behind. */ +export function runKeyArgs(enabled: boolean, exePath: string): string[] { + return enabled + ? ['add', RUN_KEY, '/v', RUN_VALUE, '/t', 'REG_SZ', '/d', `"${exePath}"`, '/f'] + : ['delete', RUN_KEY, '/v', RUN_VALUE, '/f'] +} + +/** Windows searches the current directory before PATH, so `reg` by bare name lets anything + * dropped beside the app impersonate it. Same rule as src/menubar-installer.ts. */ +export function system32Path(exe: string, env: NodeJS.ProcessEnv): string { + const root = env.SystemRoot + const base = root && /^[a-zA-Z]:[\\/]/.test(root) ? root.replace(/[\\/]+$/, '') : 'C:\\Windows' + return `${base}\\System32\\${exe}` +} + +function detachedLaunch(exePath: string, args: string[]): void { + try { + const child = spawn(exePath, args, { detached: true, stdio: 'ignore', windowsHide: true }) + child.on('error', err => console.error(`could not launch ${exePath}: ${err.message}`)) + child.unref() + } catch (err) { + console.error(`could not launch ${exePath}:`, err) + } +} + +function regRun(args: string[], env: NodeJS.ProcessEnv): Promise { + return new Promise(resolve => { + const child = spawn(system32Path('reg.exe', env), args, { stdio: 'ignore', windowsHide: true }) + // Deleting a value that is not there is the state we wanted anyway, so no exit code is + // read: a failure here must never stop a toggle the person just flipped. + child.on('error', () => resolve()) + child.on('close', () => resolve()) + }) +} + +// The controller --------------------------------------------------------------------------------- + +export type CompanionStatus = { + /** False on every platform but Windows, and on a Windows build with nothing staged. */ + supported: boolean + menuBar: boolean + sidebar: boolean + /** The Store route, where launch at login is the package's own startup task. */ + store: boolean +} + +export class MenubarCompanion { + private settings: CompanionSettings + + constructor(private readonly deps: MenubarDeps) { + this.settings = readCompanionSettings(deps.stateDir) + } + + private get home(): string { return this.deps.home ?? homedir() } + private get launch(): (exe: string, args: string[]) => void { return this.deps.launch ?? detachedLaunch } + private get runCli() { return this.deps.runCli ?? spawnCliAction } + private runReg(args: string[]): Promise { + return this.deps.runReg ? this.deps.runReg(args) : regRun(args, this.deps.env) + } + + /** Windows only, and only where a tray app was actually staged into the build. */ + supported(): boolean { + if (this.deps.platform !== 'win32') return false + const dir = menubarResourcesDir(this.deps) + return this.deps.store ? findPackagedTrayExe(dir) !== null : findStagedMsi(dir) !== null + } + + status(): CompanionStatus { + return { + supported: this.supported(), + menuBar: this.settings.menuBar, + sidebar: this.settings.sidebar, + store: this.deps.store, + } + } + + private save(patch: Partial): void { + this.settings = { ...this.settings, ...patch } + writeCompanionSettings(this.deps.stateDir, this.settings) + } + + /** + * Put the tray app on the machine and bring both surfaces in line with the switches. Runs + * at every launch, which is also what covers a desktop-app update: the staged .msi moves + * with the app, and the installer decides for itself whether it is newer than what is + * installed. + */ + async bootstrap(): Promise { + if (!this.supported()) return + + // The defaults are seeded once. A person who later turns the rail off in the tray app's + // own settings must not find it back on at the next launch of this one. + const firstRun = !this.settings.seeded + if (firstRun) this.save({ seeded: true }) + + if (!this.settings.menuBar) return + + const exePath = this.deps.store + ? findPackagedTrayExe(menubarResourcesDir(this.deps)) + : await this.install() + if (!exePath) return + this.save({ trayExePath: exePath }) + + if (firstRun && this.settings.sidebar) this.applyDockSetting(true) + await this.setRunKey(true) + this.launch(exePath, ['--reload-settings']) + } + + /** The install itself belongs to the CLI: it owns the registry read, the checksum, the + * msiexec call and the never-downgrade rule, and this side only stages the file. */ + private async install(): Promise { + const staged = findStagedMsi(menubarResourcesDir(this.deps)) + if (!staged) return null + + const result = await this.runCli(['menubar'], { + timeoutMs: INSTALL_TIMEOUT_MS, + extraEnv: { [BUNDLED_MSI_ENV]: staged.path }, + }) + const parsed = parseInstallResult(result.stdout) + if (!parsed) { + console.error(`menubar install did not report a result: ${result.stderr.trim() || `exit ${String(result.code)}`}`) + // A failed install must not orphan a working tray app that was already there. + return this.settings.trayExePath + } + if (parsed.action === 'cancelled') return null + return parsed.exePath || this.settings.trayExePath + } + + /** Menu bar off stops the process and drops the Run value; on installs if it has to, then + * starts it again. The dock preference is left exactly as it was, so turning the tray back + * on restores the rail the person had. */ + async setMenuBarEnabled(enabled: boolean): Promise { + this.save({ menuBar: enabled }) + if (!this.supported()) return this.status() + + if (!enabled) { + await this.setRunKey(false) + const exePath = this.settings.trayExePath + if (exePath) this.launch(exePath, ['--quit']) + return this.status() + } + + const exePath = this.deps.store + ? findPackagedTrayExe(menubarResourcesDir(this.deps)) + : (this.settings.trayExePath ?? await this.install()) + if (!exePath) return this.status() + this.save({ trayExePath: exePath }) + await this.setRunKey(true) + this.launch(exePath, ['--reload-settings']) + return this.status() + } + + /** The rail is the tray app's window, so this writes the preference and asks a running tray + * app to notice. With the tray off there is nothing to tell, and the file is enough. */ + async setSidebarEnabled(enabled: boolean): Promise { + this.save({ sidebar: enabled }) + if (!this.supported()) return this.status() + this.applyDockSetting(enabled) + const exePath = this.settings.trayExePath + if (this.settings.menuBar && exePath) this.launch(exePath, ['--reload-settings']) + return this.status() + } + + private applyDockSetting(enabled: boolean): void { + try { + writeDockEnabled(enabled, this.home) + } catch (err) { + console.error('Capacity Dock preference could not be saved:', err) + } + } + + /** One Run value for the tray app, owned here. The Store route has the manifest's own + * startup task instead, and writing a Run value beside it would start it twice. */ + private async setRunKey(enabled: boolean): Promise { + if (this.deps.store) return + const exePath = this.settings.trayExePath + if (enabled && !exePath) return + await this.runReg(runKeyArgs(enabled, exePath ?? '')) + } +} diff --git a/app/electron/preload.ts b/app/electron/preload.ts index 90200745..bd08568e 100644 --- a/app/electron/preload.ts +++ b/app/electron/preload.ts @@ -69,6 +69,11 @@ const bridge = { ipcRenderer.on('codeburn:update', listener) return () => { ipcRenderer.removeListener('codeburn:update', listener) } }, + // The bundled tray app and its Capacity Dock (Windows). Every setter answers with the + // whole status, so the sidebar renders what took rather than what it asked for. + companionStatus: () => invoke('codeburn:companionStatus'), + setMenuBarEnabled: (enabled: boolean) => invoke('codeburn:setMenuBarEnabled', enabled), + setSidebarEnabled: (enabled: boolean) => invoke('codeburn:setSidebarEnabled', enabled), // Plugin management pluginList: () => invoke('codeburn:pluginList'), pluginInfo: (name: string) => invoke('codeburn:pluginInfo', name), diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index f76807b7..a9fa5212 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -676,6 +676,16 @@ export type UpdateStatus = { tag: string | null } +/** The tray app and the Capacity Dock the Windows desktop app bundles (app/electron/menubar.ts). + * `supported` is false everywhere else, and on a Windows build with nothing staged. */ +export type CompanionStatus = { + supported: boolean + menuBar: boolean + sidebar: boolean + /** The Store route, where launch at login is the package's own startup task. */ + store: boolean +} + export interface CodeburnBridge { /** Subscribe to cold-start scan progress; returns an unsubscribe fn. */ onProgress(cb: (event: ScanProgressEvent) => void): () => void @@ -728,6 +738,11 @@ export interface CodeburnBridge { completeOnboarding(enabled: boolean): Promise telemetryTrack(name: string, props?: Record): Promise openExternal(url: string): Promise + /** The bundled tray app and Capacity Dock (Windows). Optional so a preload that + * predates them degrades to "not supported" rather than throwing. */ + companionStatus?(): Promise + setMenuBarEnabled?(enabled: boolean): Promise + setSidebarEnabled?(enabled: boolean): Promise // Plugin management pluginList(): Promise pluginInfo(name: string): Promise