diff --git a/app/electron/menubar.test.ts b/app/electron/menubar.test.ts index 27620ff8..d6e07353 100644 --- a/app/electron/menubar.test.ts +++ b/app/electron/menubar.test.ts @@ -23,7 +23,7 @@ import { 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' +const TRAY_EXE = 'C:\\Program Files\\CodeBurn Menubar\\codeburn-menubar.exe' function result(overrides: Partial = {}): MenubarInstallResult { return { @@ -167,6 +167,16 @@ describe('companion settings', () => { writeFileSync(join(stateDir, 'companion.v1.json'), '{ broken') expect(readCompanionSettings(stateDir).menuBar).toBe(true) }) + + // Falling back to the defaults means seeding again, which reinstalls the tray app and + // re-enables the rail. A byte order mark, which anything editing this file by hand on + // Windows tends to leave, is not a good enough reason for that. + it('reads a file that was saved with a byte order mark', () => { + const settings = { menuBar: false, sidebar: false, trayExePath: TRAY_EXE, seeded: true } + writeFileSync(join(stateDir, 'companion.v1.json'), `${JSON.stringify(settings)}`) + + expect(readCompanionSettings(stateDir)).toEqual(settings) + }) }) describe('MenubarCompanion', () => { @@ -179,6 +189,8 @@ describe('MenubarCompanion', () => { let cliCalls: Array<{ args: string[]; env: NodeJS.ProcessEnv | undefined }> let installResult: MenubarInstallResult | null let existingRunKey: string | null + /** What is on disk, as far as the companion is concerned. TRAY_EXE is there by default. */ + let present: Set function deps(overrides: Record = {}) { return { @@ -191,6 +203,7 @@ describe('MenubarCompanion', () => { launch: (exe: string, args: string[]) => { launches.push({ exe, args }) }, runReg: async (args: string[]) => { regCalls.push(args) }, readRunKey: async () => existingRunKey, + exists: (path: string) => present.has(path), runCli: async (args: string[], opts: { extraEnv?: NodeJS.ProcessEnv }) => { cliCalls.push({ args, env: opts.extraEnv }) return { @@ -213,6 +226,7 @@ describe('MenubarCompanion', () => { mkdirSync(join(resources, 'menubar'), { recursive: true }) const exe = join(resources, 'menubar', 'codeburn-menubar.exe') writeFileSync(exe, 'exe') + present.add(exe) return exe } @@ -227,6 +241,7 @@ describe('MenubarCompanion', () => { cliCalls = [] installResult = result() existingRunKey = null + present = new Set([TRAY_EXE]) }) afterEach(() => { rmSync(sandbox, { recursive: true, force: true }) }) @@ -355,6 +370,69 @@ describe('MenubarCompanion', () => { error.mockRestore() }) + // A stored path can be wrong: written by a build that derived the binary name from the + // product name, or left behind by a tray app that has since been uninstalled. + const STALE_EXE = 'C:\\Program Files\\CodeBurn Menubar\\CodeBurn Menubar.exe' + + it('re-resolves a stored path that is not on disk rather than launching it', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: false, sidebar: true, trayExePath: STALE_EXE, seeded: true }) + + await new MenubarCompanion(deps()).setMenuBarEnabled(true) + + // The install re-reads the registry and installs nothing when the version matches. + expect(cliCalls).toHaveLength(1) + expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }]) + expect(readCompanionSettings(stateDir).trayExePath).toBe(TRAY_EXE) + }) + + it('does not send --quit into the void when the stored path is stale', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: STALE_EXE, seeded: true }) + + await new MenubarCompanion(deps()).setMenuBarEnabled(false) + + expect(launches).toEqual([]) + expect(regCalls).toEqual([runKeyArgs(false, STALE_EXE)]) + }) + + it('gives up rather than storing a path the installer reported but nothing is at', async () => { + stageMsi() + installResult = result({ exePath: STALE_EXE }) + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + + await new MenubarCompanion(deps()).bootstrap() + + expect(launches).toEqual([]) + expect(regCalls).toEqual([]) + expect(readCompanionSettings(stateDir).trayExePath).toBeNull() + expect(error).toHaveBeenCalled() + error.mockRestore() + }) + + it('repairs a Run value that points at a file which is not there', async () => { + stageMsi() + // Not a first run, so the seed rule would normally leave an existing value alone. + writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + existingRunKey = `"${STALE_EXE}"` + + await new MenubarCompanion(deps()).bootstrap() + + expect(regCalls).toEqual([runKeyArgs(true, TRAY_EXE)]) + }) + + it('still leaves a Run value alone when it points at something real', async () => { + stageMsi() + writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: TRAY_EXE, seeded: true }) + const other = 'C:\\Somewhere\\else.exe' + present.add(other) + existingRunKey = `"${other}"` + + await new MenubarCompanion(deps()).bootstrap() + + expect(regCalls).toEqual([]) + }) + 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 }) diff --git a/app/electron/menubar.ts b/app/electron/menubar.ts index 8dceb197..f68b798d 100644 --- a/app/electron/menubar.ts +++ b/app/electron/menubar.ts @@ -89,6 +89,8 @@ export type MenubarDeps = { runReg?: (args: string[]) => Promise /** The tray app's existing Run value, or null when there is none. */ readRunKey?: () => Promise + /** Whether a path is on disk. Injected so the stale-path handling is testable. */ + exists?: (path: string) => boolean home?: string } @@ -132,7 +134,11 @@ function companionSettingsPath(stateDir: string): string { export function readCompanionSettings(stateDir: string): CompanionSettings { try { - const raw = JSON.parse(readFileSync(companionSettingsPath(stateDir), 'utf8')) as Partial + // An unreadable file falls back to the defaults, which means seeding again: reinstalling + // the tray app and re-enabling the rail. A byte order mark is not a good enough reason + // for that, and anything that edits this file by hand on Windows tends to leave one. + const text = readFileSync(companionSettingsPath(stateDir), 'utf8').replace(/^/, '') + const raw = JSON.parse(text) as Partial return { menuBar: raw.menuBar ?? DEFAULT_COMPANION_SETTINGS.menuBar, sidebar: raw.sidebar ?? DEFAULT_COMPANION_SETTINGS.sidebar, @@ -209,6 +215,11 @@ export function parseRunKeyValue(regOutput: string): string | null { return value ? value : null } +/** The executable a Run value points at: it is stored quoted, and only the file matters. */ +export function runKeyTarget(value: string): string { + return value.trim().replace(/^"(.*)"$/, '$1') +} + /** 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 { @@ -322,26 +333,64 @@ export class MenubarCompanion { if (!this.settings.menuBar) return + // The install runs on every launch, not only when a path is missing: it is what carries a + // desktop-app update forward, and it costs nothing when the versions already match. const exePath = this.deps.store ? findPackagedTrayExe(menubarResourcesDir(this.deps)) : await this.install() if (!exePath) return + if (!this.exists(exePath)) { + // Storing a path to nothing is what made the switches send arguments into the void. + console.error(`the tray app was reported at ${exePath}, which is not there`) + return + } this.save({ trayExePath: exePath }) if (firstRun && existingDock === undefined && this.settings.sidebar) this.applyDockSetting(true) - // Same rule for launch at login: an existing Run value was written by the tray app's own - // toggle or by an earlier launch of this one, and either way it is not this launch's to - // rewrite. After the first run only the Menu bar switch touches it. - if (firstRun && await this.existingRunKey() === null) await this.setRunKey(true) + await this.reconcileRunKey(firstRun) this.launch(exePath, ['--reload-settings']) } + /** + * Launch at login, without overriding a choice. An existing Run value was written by the + * tray app's own toggle or by an earlier launch of this one, so it is left alone; only a + * first run seeds one. The exception is a value pointing at a file that is not there, which + * is not a preference but the old wrong path, and would fail silently at every login. + */ + private async reconcileRunKey(firstRun: boolean): Promise { + const existing = await this.existingRunKey() + if (existing === null) { + if (firstRun) await this.setRunKey(true) + return + } + if (!this.exists(runKeyTarget(existing))) await this.setRunKey(true) + } + private existingRunKey(): Promise { if (this.deps.readRunKey) return this.deps.readRunKey() // The Store route has no Run value at all, so there is nothing to ask about. return this.deps.store ? Promise.resolve(null) : regQueryRunValue(this.deps.env) } + private get exists(): (path: string) => boolean { + return this.deps.exists ?? existsSync + } + + /** + * Where the tray app actually is, checked rather than remembered. A stored path can be + * wrong: written by a build that derived the binary name from the product name, or left + * behind by a tray app that has since been uninstalled. Re-resolving costs one + * `codeburn menubar`, which re-reads the registry and installs nothing when the version + * already matches. + */ + private async resolveTrayExe(): Promise { + if (this.deps.store) return findPackagedTrayExe(menubarResourcesDir(this.deps)) + const stored = this.settings.trayExePath + if (stored && this.exists(stored)) return stored + const resolved = await this.install() + return resolved && this.exists(resolved) ? resolved : null + } + /** 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 { @@ -372,13 +421,11 @@ export class MenubarCompanion { if (!enabled) { await this.setRunKey(false) const exePath = this.settings.trayExePath - if (exePath) this.launch(exePath, ['--quit']) + if (exePath && this.exists(exePath)) this.launch(exePath, ['--quit']) return this.status() } - const exePath = this.deps.store - ? findPackagedTrayExe(menubarResourcesDir(this.deps)) - : (this.settings.trayExePath ?? await this.install()) + const exePath = await this.resolveTrayExe() if (!exePath) return this.status() this.save({ trayExePath: exePath }) await this.setRunKey(true) @@ -392,8 +439,15 @@ export class MenubarCompanion { 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']) + if (!this.settings.menuBar) return this.status() + // The file is written either way; this only decides whether a running rail hears about + // it now or at the next launch, so a tray app that cannot be found is not worth an + // install here. + const exePath = await this.resolveTrayExe() + if (exePath) { + this.save({ trayExePath: exePath }) + this.launch(exePath, ['--reload-settings']) + } return this.status() }