mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-23 21:39:13 +00:00
feat(app): read and write the tray app's own settings
The tray app keeps its preferences in two files it reads from Rust before any of its windows exist, so those files are the interface rather than any running process: windows-settings.json for what only it cares about, windows-dock.json for the Capacity Dock. The desktop app can now read and write both, which is what lets its Settings carry the tray app's own panes. Every write is a merge. Both files hold keys this side has no business touching, the rail's placement above all, and a whole-file write would take them with it. And every value is checked against the same closed set the tray app parses it with: a value it cannot read collapses to a default there, so sending one would silently lose the setting rather than store it. The check is also what keeps a renderer from reaching a key it was not offered. Two rules come with the dock file. Writing the provider set latches manualSelection, because editing the set by hand is what stops the tray app seeding it from whatever is connected. And a set that no longer holds the resting provider moves it, since the rail can only rest on a row it is showing. Showing the rail is the Sidebar switch under another name, so it goes through that path rather than straight to the file, and keeps the rule that the rail cannot outlive the tray app. Launch at login is the one setting that is not in either file: it is the Run value, which this app already owns. After every write the running tray app is nudged with --reload-settings, which makes it re-read both files and broadcast to its own windows. With the tray app off there is nothing to tell and the files are enough.
This commit is contained in:
parent
451cc5115c
commit
4c4699952b
8 changed files with 626 additions and 1 deletions
|
|
@ -73,6 +73,10 @@ const CHANNELS = [
|
|||
'codeburn:companionStatus',
|
||||
'codeburn:setMenuBarEnabled',
|
||||
'codeburn:setSidebarEnabled',
|
||||
'codeburn:trayPrefs',
|
||||
'codeburn:setTrayAppPref',
|
||||
'codeburn:setTrayDockPref',
|
||||
'codeburn:setLaunchAtLogin',
|
||||
'codeburn:pluginList',
|
||||
'codeburn:pluginInfo',
|
||||
'codeburn:pluginAdd',
|
||||
|
|
|
|||
|
|
@ -238,7 +238,10 @@ type Deps = {
|
|||
/** Cached update-availability status; absent under tests unless injected. */
|
||||
getUpdateStatus?: () => Promise<UpdateStatus>
|
||||
/** The bundled tray app and Capacity Dock; absent off Windows and under tests. */
|
||||
companion?: Pick<MenubarCompanion, 'status' | 'setMenuBarEnabled' | 'setSidebarEnabled'> | null
|
||||
companion?: Pick<
|
||||
MenubarCompanion,
|
||||
'status' | 'setMenuBarEnabled' | 'setSidebarEnabled' | 'trayPrefs' | 'setTrayAppPref' | 'setTrayDockPref' | 'setLaunchAtLogin'
|
||||
> | null
|
||||
}
|
||||
|
||||
type Handler = (...args: any[]) => Promise<Envelope>
|
||||
|
|
@ -443,6 +446,15 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
({ 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 }),
|
||||
// The tray app's own settings, which live in the files it reads them from. Every setter
|
||||
// answers with the whole set, so the panes render what landed rather than what was sent.
|
||||
'codeburn:trayPrefs': async () => ({ ok: true, value: deps.companion ? await deps.companion.trayPrefs() : null }),
|
||||
'codeburn:setTrayAppPref': async (patch?: Record<string, unknown>) =>
|
||||
({ ok: true, value: deps.companion ? await deps.companion.setTrayAppPref(patch ?? {}) : null }),
|
||||
'codeburn:setTrayDockPref': async (patch?: Record<string, unknown>) =>
|
||||
({ ok: true, value: deps.companion ? await deps.companion.setTrayDockPref(patch ?? {}) : null }),
|
||||
'codeburn:setLaunchAtLogin': async (enabled?: boolean) =>
|
||||
({ ok: true, value: deps.companion ? await deps.companion.setLaunchAtLogin(Boolean(enabled)) : null }),
|
||||
// Plugin management reads (all return parsed JSON)
|
||||
'codeburn:pluginList': run(() => ['plugin', 'list', '--json']),
|
||||
'codeburn:pluginInfo': run((name: string) => ['plugin', 'info', vToken(name), '--json']),
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import {
|
|||
writeDockEnabled,
|
||||
type MenubarInstallResult,
|
||||
} from './menubar'
|
||||
import { readTrayFile } from './tray-settings'
|
||||
|
||||
const VERSION = '0.9.23'
|
||||
const MSI_NAME = `CodeBurn.Menubar_${VERSION}_x64_en-US.msi`
|
||||
|
|
@ -513,6 +514,95 @@ describe('MenubarCompanion', () => {
|
|||
expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }])
|
||||
})
|
||||
|
||||
// The tray app's own settings, which the two panes in the desktop app's Settings render.
|
||||
describe('tray preferences', () => {
|
||||
const settingsPath = () => join(home, '.config', 'codeburn', 'windows-settings.json')
|
||||
|
||||
function running(): MenubarCompanion {
|
||||
stageMsi()
|
||||
writeCompanionSettings(stateDir, { menuBar: true, sidebar: true, trayExePath: TRAY_EXE, seeded: true })
|
||||
return new MenubarCompanion(deps())
|
||||
}
|
||||
|
||||
it('reads both files and the Run value', async () => {
|
||||
const companion = running()
|
||||
mkdirSync(join(home, '.config', 'codeburn'), { recursive: true })
|
||||
writeFileSync(settingsPath(), JSON.stringify({ metric: 'tokens', accent: 'green' }))
|
||||
writeDockEnabled(true, home)
|
||||
existingRunKey = `"${TRAY_EXE}"`
|
||||
|
||||
const prefs = await companion.trayPrefs()
|
||||
|
||||
expect(prefs.app).toMatchObject({ metric: 'tokens', accent: 'green', terminal: 'windowsTerminal' })
|
||||
expect(prefs.dock).toMatchObject({ enabled: true, scale: 0.6 })
|
||||
expect(prefs.launchAtLogin).toBe(true)
|
||||
})
|
||||
|
||||
it('writes a setting and nudges the running tray app to re-read it', async () => {
|
||||
const companion = running()
|
||||
|
||||
const prefs = await companion.setTrayAppPref({ metric: 'iconOnly' })
|
||||
|
||||
expect(JSON.parse(readFileSync(settingsPath(), 'utf8'))).toEqual({ metric: 'iconOnly' })
|
||||
expect(prefs.app.metric).toBe('iconOnly')
|
||||
expect(launches).toEqual([{ exe: TRAY_EXE, args: ['--reload-settings'] }])
|
||||
})
|
||||
|
||||
it('writes nothing and nudges nobody for a patch it will not accept', async () => {
|
||||
const companion = running()
|
||||
|
||||
await companion.setTrayAppPref({ placement: { docked: 'left' } })
|
||||
|
||||
expect(launches).toEqual([])
|
||||
expect(readTrayFile('app', home)).toEqual({})
|
||||
})
|
||||
|
||||
it('keeps the rail placement while writing a dock setting', async () => {
|
||||
const companion = running()
|
||||
mkdirSync(join(home, '.config', 'codeburn'), { recursive: true })
|
||||
writeFileSync(dockPrefsPath(home), JSON.stringify({ enabled: true, placement: { docked: 'right' } }))
|
||||
|
||||
await companion.setTrayDockPref({ scale: 1.1, theme: 'glass' })
|
||||
|
||||
expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toEqual({
|
||||
enabled: true, placement: { docked: 'right' }, scale: 1.1, theme: 'glass',
|
||||
})
|
||||
})
|
||||
|
||||
it('moves the resting provider when it leaves the set', async () => {
|
||||
const companion = running()
|
||||
mkdirSync(join(home, '.config', 'codeburn'), { recursive: true })
|
||||
writeFileSync(dockPrefsPath(home), JSON.stringify({ enabled: true, preferred: 'gemini' }))
|
||||
|
||||
await companion.setTrayDockPref({ providers: ['claude', 'codex'] })
|
||||
|
||||
expect(JSON.parse(readFileSync(dockPrefsPath(home), 'utf8'))).toMatchObject({
|
||||
providers: ['claude', 'codex'], preferred: 'claude', manualSelection: true,
|
||||
})
|
||||
})
|
||||
|
||||
// Showing the rail is the Sidebar switch under another name, so it takes the same path
|
||||
// and keeps the rule that the rail cannot outlive the tray app.
|
||||
it('routes the show switch through the Sidebar rule', async () => {
|
||||
const companion = running()
|
||||
|
||||
const prefs = await companion.setTrayDockPref({ enabled: false })
|
||||
|
||||
expect(prefs.dock.enabled).toBe(false)
|
||||
expect(companion.status().sidebar).toBe(false)
|
||||
})
|
||||
|
||||
it('writes launch at login to the Run value this app owns', async () => {
|
||||
const companion = running()
|
||||
|
||||
await companion.setLaunchAtLogin(true)
|
||||
expect(regCalls).toEqual([runKeyArgs(true, TRAY_EXE)])
|
||||
|
||||
await companion.setLaunchAtLogin(false)
|
||||
expect(regCalls[1]).toEqual(runKeyArgs(false, TRAY_EXE))
|
||||
})
|
||||
})
|
||||
|
||||
it('Sidebar off with the tray app off writes the preference and tells nobody', async () => {
|
||||
stageMsi()
|
||||
writeCompanionSettings(stateDir, { menuBar: false, sidebar: true, trayExePath: TRAY_EXE, seeded: true })
|
||||
|
|
|
|||
|
|
@ -31,6 +31,10 @@ import { homedir } from 'node:os'
|
|||
import { join } from 'node:path'
|
||||
|
||||
import { spawnCliAction, type ActionResult } from './cli'
|
||||
import {
|
||||
normalizedPreferred, parseTrayAppPrefs, parseTrayDockPrefs, patchTrayFile, readTrayFile,
|
||||
sanitizeAppPatch, sanitizeDockPatch, type TrayAppPrefs, type TrayDockPrefs,
|
||||
} from './tray-settings'
|
||||
|
||||
/** 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'
|
||||
|
|
@ -267,6 +271,13 @@ function regQueryRunValue(env: NodeJS.ProcessEnv): Promise<string | null> {
|
|||
|
||||
// The controller ---------------------------------------------------------------------------------
|
||||
|
||||
/** What the two tray panes in the desktop app's Settings render from. */
|
||||
export type TrayPrefs = {
|
||||
app: TrayAppPrefs
|
||||
dock: TrayDockPrefs
|
||||
launchAtLogin: boolean
|
||||
}
|
||||
|
||||
export type CompanionStatus = {
|
||||
/** False on every platform but Windows, and on a Windows build with nothing staged. */
|
||||
supported: boolean
|
||||
|
|
@ -477,6 +488,74 @@ export class MenubarCompanion {
|
|||
return this.status()
|
||||
}
|
||||
|
||||
// The tray app's own settings ------------------------------------------------------------
|
||||
|
||||
/** Everything the two tray panes render from, read straight out of the files the tray app
|
||||
* reads them from, so the panes and the tray app can never be showing different answers. */
|
||||
async trayPrefs(): Promise<TrayPrefs> {
|
||||
return {
|
||||
app: parseTrayAppPrefs(readTrayFile('app', this.home)),
|
||||
dock: parseTrayDockPrefs(readTrayFile('dock', this.home)),
|
||||
launchAtLogin: (await this.existingRunKey()) !== null,
|
||||
}
|
||||
}
|
||||
|
||||
/** A setting the tray app keeps in `windows-settings.json`. Every other key in that file
|
||||
* is left alone, and the running tray app is told to re-read it. */
|
||||
async setTrayAppPref(patch: Record<string, unknown>): Promise<TrayPrefs> {
|
||||
const clean = sanitizeAppPatch(patch)
|
||||
if (Object.keys(clean).length > 0) {
|
||||
try {
|
||||
patchTrayFile('app', clean, this.home)
|
||||
await this.nudgeTray()
|
||||
} catch (err) {
|
||||
console.error('tray settings could not be saved:', err)
|
||||
}
|
||||
}
|
||||
return this.trayPrefs()
|
||||
}
|
||||
|
||||
/**
|
||||
* A Capacity Dock setting. `enabled` is the Sidebar switch under another name, so it goes
|
||||
* through the same path and keeps the rule that the rail cannot outlive the tray app.
|
||||
* A provider set that no longer holds the resting provider moves it, as the rail would.
|
||||
*/
|
||||
async setTrayDockPref(patch: Record<string, unknown>): Promise<TrayPrefs> {
|
||||
if ('enabled' in patch) {
|
||||
await this.setSidebarEnabled(patch.enabled === true)
|
||||
return this.trayPrefs()
|
||||
}
|
||||
const clean = sanitizeDockPatch(patch)
|
||||
if (Object.keys(clean).length > 0) {
|
||||
try {
|
||||
if (Array.isArray(clean.providers)) {
|
||||
const current = parseTrayDockPrefs(readTrayFile('dock', this.home))
|
||||
clean.preferred = normalizedPreferred(current.preferred, clean.providers as string[])
|
||||
}
|
||||
patchTrayFile('dock', clean, this.home)
|
||||
await this.nudgeTray()
|
||||
} catch (err) {
|
||||
console.error('Capacity Dock settings could not be saved:', err)
|
||||
}
|
||||
}
|
||||
return this.trayPrefs()
|
||||
}
|
||||
|
||||
/** Launch at login is the one tray setting that is not in a file: it is the Run value, and
|
||||
* this app owns it, so the pane writes it here rather than through the tray app. */
|
||||
async setLaunchAtLogin(enabled: boolean): Promise<TrayPrefs> {
|
||||
await this.setRunKey(enabled)
|
||||
return this.trayPrefs()
|
||||
}
|
||||
|
||||
/** Makes a running tray app re-read both preference files and repaint. Nothing to do when
|
||||
* the switch is off or the executable is not there; the files are read at the next start. */
|
||||
private async nudgeTray(): Promise<void> {
|
||||
if (!this.settings.menuBar) return
|
||||
const exePath = this.settings.trayExePath
|
||||
if (exePath && this.exists(exePath)) this.launch(exePath, ['--reload-settings'])
|
||||
}
|
||||
|
||||
private applyDockSetting(enabled: boolean): void {
|
||||
try {
|
||||
writeDockEnabled(enabled, this.home)
|
||||
|
|
|
|||
|
|
@ -74,6 +74,11 @@ const bridge = {
|
|||
companionStatus: () => invoke('codeburn:companionStatus'),
|
||||
setMenuBarEnabled: (enabled: boolean) => invoke('codeburn:setMenuBarEnabled', enabled),
|
||||
setSidebarEnabled: (enabled: boolean) => invoke('codeburn:setSidebarEnabled', enabled),
|
||||
// The tray app's own settings, in the two files it reads them from.
|
||||
trayPrefs: () => invoke('codeburn:trayPrefs'),
|
||||
setTrayAppPref: (patch: Record<string, unknown>) => invoke('codeburn:setTrayAppPref', patch),
|
||||
setTrayDockPref: (patch: Record<string, unknown>) => invoke('codeburn:setTrayDockPref', patch),
|
||||
setLaunchAtLogin: (enabled: boolean) => invoke('codeburn:setLaunchAtLogin', enabled),
|
||||
// Plugin management
|
||||
pluginList: () => invoke('codeburn:pluginList'),
|
||||
pluginInfo: (name: string) => invoke('codeburn:pluginInfo', name),
|
||||
|
|
|
|||
205
app/electron/tray-settings.test.ts
Normal file
205
app/electron/tray-settings.test.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
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 } from 'vitest'
|
||||
|
||||
import {
|
||||
DEFAULT_TRAY_APP_PREFS,
|
||||
canDeselect,
|
||||
normalizeScale,
|
||||
normalizedPreferred,
|
||||
parseTrayAppPrefs,
|
||||
parseTrayDockPrefs,
|
||||
patchTrayFile,
|
||||
readTrayFile,
|
||||
sanitizeAppPatch,
|
||||
sanitizeDockPatch,
|
||||
} from './tray-settings'
|
||||
|
||||
describe('reading the tray app files', () => {
|
||||
let home: string
|
||||
const settingsPath = () => join(home, '.config', 'codeburn', 'windows-settings.json')
|
||||
const dockPath = () => join(home, '.config', 'codeburn', 'windows-dock.json')
|
||||
|
||||
beforeEach(() => {
|
||||
home = mkdtempSync(join(tmpdir(), 'tray-settings-'))
|
||||
mkdirSync(join(home, '.config', 'codeburn'), { recursive: true })
|
||||
})
|
||||
afterEach(() => { rmSync(home, { recursive: true, force: true }) })
|
||||
|
||||
it('is empty for a machine where the tray app has never run', () => {
|
||||
expect(readTrayFile('app', home)).toEqual({})
|
||||
expect(readTrayFile('dock', home)).toEqual({})
|
||||
})
|
||||
|
||||
it('reads each file from the path the tray app reads it from', () => {
|
||||
writeFileSync(settingsPath(), JSON.stringify({ metric: 'tokens' }))
|
||||
writeFileSync(dockPath(), JSON.stringify({ enabled: true }))
|
||||
|
||||
expect(readTrayFile('app', home)).toEqual({ metric: 'tokens' })
|
||||
expect(readTrayFile('dock', home)).toEqual({ enabled: true })
|
||||
})
|
||||
|
||||
it('survives a byte order mark and refuses anything that is not an object', () => {
|
||||
writeFileSync(settingsPath(), `${JSON.stringify({ metric: 'tokens' })}`)
|
||||
expect(readTrayFile('app', home)).toEqual({ metric: 'tokens' })
|
||||
|
||||
writeFileSync(settingsPath(), '[1, 2]')
|
||||
expect(readTrayFile('app', home)).toEqual({})
|
||||
})
|
||||
|
||||
// Both files hold keys this side has no business touching: the rail's placement, the tray
|
||||
// app's own theme cache, the provider set it seeded for itself.
|
||||
it('merges into what is already there rather than replacing it', () => {
|
||||
writeFileSync(dockPath(), JSON.stringify({
|
||||
enabled: true,
|
||||
placement: { docked: 'right', x: 1, y: 0.37 },
|
||||
scale: 0.6,
|
||||
}))
|
||||
|
||||
patchTrayFile('dock', { scale: 1.1 }, home)
|
||||
|
||||
expect(JSON.parse(readFileSync(dockPath(), 'utf8'))).toEqual({
|
||||
enabled: true,
|
||||
placement: { docked: 'right', x: 1, y: 0.37 },
|
||||
scale: 1.1,
|
||||
})
|
||||
})
|
||||
|
||||
it('creates the directory when nothing has written there yet', () => {
|
||||
rmSync(join(home, '.config'), { recursive: true, force: true })
|
||||
|
||||
patchTrayFile('app', { metric: 'cost' }, home)
|
||||
|
||||
expect(JSON.parse(readFileSync(settingsPath(), 'utf8'))).toEqual({ metric: 'cost' })
|
||||
})
|
||||
})
|
||||
|
||||
// The tray app collapses a value it cannot read to a default, so sending one would silently
|
||||
// lose the setting. Everything is checked against the same closed set it parses with.
|
||||
describe('parseTrayAppPrefs', () => {
|
||||
it('reads every key the Menu bar pane shows', () => {
|
||||
expect(parseTrayAppPrefs({
|
||||
metric: 'totalTokens',
|
||||
menubarPeriod: 'week',
|
||||
accent: 'green',
|
||||
trayBadge: true,
|
||||
usageRefreshSeconds: 300,
|
||||
quotaCadenceSeconds: 900,
|
||||
terminal: 'powershell',
|
||||
})).toEqual({
|
||||
metric: 'totalTokens',
|
||||
menubarPeriod: 'week',
|
||||
accent: 'green',
|
||||
trayBadge: true,
|
||||
usageRefreshSeconds: 300,
|
||||
quotaCadenceSeconds: 900,
|
||||
terminal: 'powershell',
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to the tray app defaults for anything it would not understand', () => {
|
||||
expect(parseTrayAppPrefs({
|
||||
metric: 'credits',
|
||||
menubarPeriod: '30days',
|
||||
accent: 'chartreuse',
|
||||
trayBadge: 'yes',
|
||||
usageRefreshSeconds: 45,
|
||||
quotaCadenceSeconds: -5,
|
||||
terminal: 'bash',
|
||||
})).toEqual(DEFAULT_TRAY_APP_PREFS)
|
||||
expect(parseTrayAppPrefs({})).toEqual(DEFAULT_TRAY_APP_PREFS)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseTrayDockPrefs', () => {
|
||||
it('reads every key the Capacity Dock pane shows', () => {
|
||||
expect(parseTrayDockPrefs({
|
||||
enabled: true,
|
||||
preferred: 'claude',
|
||||
scale: 0.9,
|
||||
theme: 'glass',
|
||||
gaugeShape: 'squircle',
|
||||
providers: ['claude', 'codex'],
|
||||
manualSelection: true,
|
||||
})).toEqual({
|
||||
enabled: true,
|
||||
preferred: 'claude',
|
||||
scale: 0.9,
|
||||
theme: 'glass',
|
||||
gaugeShape: 'squircle',
|
||||
providers: ['claude', 'codex'],
|
||||
manualSelection: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('still understands the appearance by the name it used to have', () => {
|
||||
expect(parseTrayDockPrefs({ theme: 'acrylic' }).theme).toBe('glass')
|
||||
})
|
||||
|
||||
it('clamps and snaps the size to the steps the slider offers', () => {
|
||||
expect(normalizeScale(0.2)).toBe(0.6)
|
||||
expect(normalizeScale(9)).toBe(1.2)
|
||||
expect(normalizeScale(0.93)).toBe(0.95)
|
||||
expect(normalizeScale('big')).toBe(0.6)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeAppPatch', () => {
|
||||
it('passes each key through, one at a time', () => {
|
||||
expect(sanitizeAppPatch({ metric: 'iconOnly' })).toEqual({ metric: 'iconOnly' })
|
||||
expect(sanitizeAppPatch({ menubarPeriod: 'month' })).toEqual({ menubarPeriod: 'month' })
|
||||
expect(sanitizeAppPatch({ accent: 'purple' })).toEqual({ accent: 'purple' })
|
||||
expect(sanitizeAppPatch({ trayBadge: true })).toEqual({ trayBadge: true })
|
||||
expect(sanitizeAppPatch({ usageRefreshSeconds: 0 })).toEqual({ usageRefreshSeconds: 0 })
|
||||
expect(sanitizeAppPatch({ quotaCadenceSeconds: 60 })).toEqual({ quotaCadenceSeconds: 60 })
|
||||
expect(sanitizeAppPatch({ terminal: 'commandPrompt' })).toEqual({ terminal: 'commandPrompt' })
|
||||
})
|
||||
|
||||
// The renderer cannot reach a key the tray app owns, and cannot store a value it would
|
||||
// later fail to read.
|
||||
it('drops keys it is not allowed to write and repairs values it is', () => {
|
||||
expect(sanitizeAppPatch({ theme: 'dark', claudeConfigDirs: ['C:\\x'] })).toEqual({})
|
||||
expect(sanitizeAppPatch({ accent: 'not-a-colour' })).toEqual({ accent: 'ember' })
|
||||
expect(sanitizeAppPatch({ trayBadge: 'on' })).toEqual({ trayBadge: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeDockPatch', () => {
|
||||
it('passes each key through, one at a time', () => {
|
||||
expect(sanitizeDockPatch({ enabled: true })).toEqual({ enabled: true })
|
||||
expect(sanitizeDockPatch({ scale: 1.05 })).toEqual({ scale: 1.05 })
|
||||
expect(sanitizeDockPatch({ theme: 'glass' })).toEqual({ theme: 'glass' })
|
||||
expect(sanitizeDockPatch({ gaugeShape: 'squircle' })).toEqual({ gaugeShape: 'squircle' })
|
||||
expect(sanitizeDockPatch({ preferred: 'codex' })).toEqual({ preferred: 'codex' })
|
||||
})
|
||||
|
||||
// Editing the set by hand is what stops the tray app seeding it from whatever is connected.
|
||||
it('latches the manual selection whenever the provider set is written', () => {
|
||||
expect(sanitizeDockPatch({ providers: ['claude', 'codex'] }))
|
||||
.toEqual({ providers: ['claude', 'codex'], manualSelection: true })
|
||||
})
|
||||
|
||||
it('refuses anything that is not a provider id, and the rail placement', () => {
|
||||
expect(sanitizeDockPatch({ placement: { docked: 'left' } })).toEqual({})
|
||||
expect(sanitizeDockPatch({ preferred: '../../etc' })).toEqual({ preferred: null })
|
||||
expect(sanitizeDockPatch({ providers: ['claude', 'Bad Id', 42] }))
|
||||
.toEqual({ providers: ['claude'], manualSelection: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('the rail always has something to show', () => {
|
||||
it('moves the resting provider when it leaves the set', () => {
|
||||
expect(normalizedPreferred('claude', ['claude', 'codex'])).toBe('claude')
|
||||
expect(normalizedPreferred('gemini', ['claude', 'codex'])).toBe('claude')
|
||||
expect(normalizedPreferred('claude', [])).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the last connected provider switched on', () => {
|
||||
expect(canDeselect('claude', ['claude', 'codex'], ['claude', 'codex'])).toBe(true)
|
||||
expect(canDeselect('claude', ['claude'], ['claude'])).toBe(false)
|
||||
// One that is not connected is not what the rail is being kept alive by.
|
||||
expect(canDeselect('codex', ['claude', 'codex'], ['claude'])).toBe(true)
|
||||
expect(canDeselect('gemini', ['claude'], ['claude'])).toBe(true)
|
||||
})
|
||||
})
|
||||
201
app/electron/tray-settings.ts
Normal file
201
app/electron/tray-settings.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
// The tray app's own preferences, read and written from the desktop app.
|
||||
//
|
||||
// The tray app (windows/) keeps them in two files that it reads from Rust before any of its
|
||||
// windows exist, so those files are the interface rather than any running process:
|
||||
//
|
||||
// ~/.config/codeburn/windows-settings.json everything only the tray app cares about
|
||||
// ~/.config/codeburn/windows-dock.json the Capacity Dock, whose placement lives here too
|
||||
//
|
||||
// Both hold keys this side has no business touching (the rail's placement, the tray app's
|
||||
// theme cache), so every write is a merge of the named keys into whatever is already there.
|
||||
// And every value is checked against the same closed set the tray app parses it with
|
||||
// (windows/src/lib/appSettings.ts, windows/src/lib/dockPrefs.ts): a value it cannot
|
||||
// understand collapses to a default there, so sending one would silently lose the setting.
|
||||
//
|
||||
// After a write the tray app is nudged with `--reload-settings`, which makes it re-read both
|
||||
// files and broadcast to its own windows. That is done by the caller, which owns the process.
|
||||
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
export type TraySettingsFile = 'app' | 'dock'
|
||||
|
||||
function filePath(file: TraySettingsFile, home: string): string {
|
||||
return join(home, '.config', 'codeburn', file === 'app' ? 'windows-settings.json' : 'windows-dock.json')
|
||||
}
|
||||
|
||||
export function readTrayFile(file: TraySettingsFile, home = homedir()): Record<string, unknown> {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(filePath(file, home), 'utf8').replace(/^/, ''))
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
|
||||
return parsed as Record<string, unknown>
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
/** Merge the given keys into the file, leaving every other key the tray app owns alone. */
|
||||
export function patchTrayFile(
|
||||
file: TraySettingsFile,
|
||||
patch: Record<string, unknown>,
|
||||
home = homedir(),
|
||||
): Record<string, unknown> {
|
||||
const merged = { ...readTrayFile(file, home), ...patch }
|
||||
const path = filePath(file, home)
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, `${JSON.stringify(merged, null, 2)}\n`)
|
||||
return merged
|
||||
}
|
||||
|
||||
// What each setting may be -----------------------------------------------------------------
|
||||
|
||||
export const DISPLAY_METRICS = ['cost', 'tokens', 'totalTokens', 'iconOnly'] as const
|
||||
export const MENUBAR_PERIODS = ['today', 'week', 'month', 'all'] as const
|
||||
export const ACCENTS = ['ember', 'blue', 'purple', 'pink', 'red', 'orange', 'yellow', 'green', 'graphite'] as const
|
||||
export const USAGE_CADENCES = [-1, 0, 60, 300, 900] as const
|
||||
export const QUOTA_CADENCES = [0, 60, 120, 300, 900] as const
|
||||
export const TERMINALS = ['windowsTerminal', 'powershell', 'commandPrompt'] as const
|
||||
export const DOCK_THEMES = ['graphite', 'glass'] as const
|
||||
export const DOCK_GAUGE_SHAPES = ['circle', 'squircle'] as const
|
||||
export const DOCK_SCALE_MIN = 0.6
|
||||
export const DOCK_SCALE_MAX = 1.2
|
||||
export const DOCK_SCALE_STEP = 0.05
|
||||
|
||||
export type TrayAppPrefs = {
|
||||
metric: string
|
||||
menubarPeriod: string
|
||||
accent: string
|
||||
trayBadge: boolean
|
||||
usageRefreshSeconds: number
|
||||
quotaCadenceSeconds: number
|
||||
terminal: string
|
||||
}
|
||||
|
||||
export type TrayDockPrefs = {
|
||||
enabled: boolean
|
||||
preferred: string | null
|
||||
scale: number
|
||||
theme: string
|
||||
gaugeShape: string
|
||||
providers: string[]
|
||||
manualSelection: boolean
|
||||
}
|
||||
|
||||
export const DEFAULT_TRAY_APP_PREFS: TrayAppPrefs = {
|
||||
metric: 'cost',
|
||||
menubarPeriod: 'today',
|
||||
accent: 'ember',
|
||||
trayBadge: false,
|
||||
usageRefreshSeconds: -1,
|
||||
quotaCadenceSeconds: 120,
|
||||
terminal: 'windowsTerminal',
|
||||
}
|
||||
|
||||
export const DEFAULT_TRAY_DOCK_PREFS: TrayDockPrefs = {
|
||||
enabled: false,
|
||||
preferred: null,
|
||||
scale: DOCK_SCALE_MIN,
|
||||
theme: 'graphite',
|
||||
gaugeShape: 'circle',
|
||||
providers: [],
|
||||
manualSelection: false,
|
||||
}
|
||||
|
||||
function oneOf<T extends string | number>(value: unknown, allowed: readonly T[], fallback: T): T {
|
||||
return (allowed as readonly unknown[]).includes(value) ? (value as T) : fallback
|
||||
}
|
||||
|
||||
/** The same reading the tray app does, so what the pane shows is what the tray app sees. */
|
||||
export function parseTrayAppPrefs(raw: Record<string, unknown>): TrayAppPrefs {
|
||||
return {
|
||||
metric: oneOf(raw.metric, DISPLAY_METRICS, DEFAULT_TRAY_APP_PREFS.metric),
|
||||
menubarPeriod: oneOf(raw.menubarPeriod, MENUBAR_PERIODS, DEFAULT_TRAY_APP_PREFS.menubarPeriod),
|
||||
accent: oneOf(raw.accent, ACCENTS, DEFAULT_TRAY_APP_PREFS.accent),
|
||||
trayBadge: typeof raw.trayBadge === 'boolean' ? raw.trayBadge : DEFAULT_TRAY_APP_PREFS.trayBadge,
|
||||
usageRefreshSeconds: oneOf(raw.usageRefreshSeconds, USAGE_CADENCES, DEFAULT_TRAY_APP_PREFS.usageRefreshSeconds),
|
||||
quotaCadenceSeconds: oneOf(raw.quotaCadenceSeconds, QUOTA_CADENCES, DEFAULT_TRAY_APP_PREFS.quotaCadenceSeconds),
|
||||
terminal: oneOf(raw.terminal, TERMINALS, DEFAULT_TRAY_APP_PREFS.terminal),
|
||||
}
|
||||
}
|
||||
|
||||
/** The rail's scale is a slider, so it is clamped and snapped rather than picked from a set. */
|
||||
export function normalizeScale(value: unknown): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_TRAY_DOCK_PREFS.scale
|
||||
const clamped = Math.min(DOCK_SCALE_MAX, Math.max(DOCK_SCALE_MIN, value))
|
||||
const steps = Math.round((clamped - DOCK_SCALE_MIN) / DOCK_SCALE_STEP)
|
||||
return Number((DOCK_SCALE_MIN + steps * DOCK_SCALE_STEP).toFixed(2))
|
||||
}
|
||||
|
||||
export function parseTrayDockPrefs(raw: Record<string, unknown>): TrayDockPrefs {
|
||||
return {
|
||||
enabled: raw.enabled === true,
|
||||
preferred: typeof raw.preferred === 'string' ? raw.preferred : null,
|
||||
scale: normalizeScale(raw.scale),
|
||||
// `acrylic` is the spelling the setting had before the appearance was renamed Glass.
|
||||
theme: raw.theme === 'glass' || raw.theme === 'acrylic' ? 'glass' : 'graphite',
|
||||
gaugeShape: oneOf(raw.gaugeShape, DOCK_GAUGE_SHAPES, DEFAULT_TRAY_DOCK_PREFS.gaugeShape),
|
||||
providers: Array.isArray(raw.providers) ? raw.providers.filter((id): id is string => typeof id === 'string') : [],
|
||||
manualSelection: raw.manualSelection === true,
|
||||
}
|
||||
}
|
||||
|
||||
/** Provider ids are the CLI's own, and they end up in a file the tray app parses. */
|
||||
const PROVIDER_ID = /^[a-z0-9][a-z0-9-]{0,63}$/
|
||||
|
||||
/**
|
||||
* Keep only the keys this pane is allowed to write, each checked against what the tray app
|
||||
* can read back. Anything else in the patch is dropped rather than merged, so a renderer
|
||||
* cannot reach the rail's placement or any other key the tray app owns.
|
||||
*/
|
||||
export function sanitizeAppPatch(patch: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {}
|
||||
if ('metric' in patch) out.metric = oneOf(patch.metric, DISPLAY_METRICS, DEFAULT_TRAY_APP_PREFS.metric)
|
||||
if ('menubarPeriod' in patch) out.menubarPeriod = oneOf(patch.menubarPeriod, MENUBAR_PERIODS, DEFAULT_TRAY_APP_PREFS.menubarPeriod)
|
||||
if ('accent' in patch) out.accent = oneOf(patch.accent, ACCENTS, DEFAULT_TRAY_APP_PREFS.accent)
|
||||
if ('trayBadge' in patch) out.trayBadge = patch.trayBadge === true
|
||||
if ('usageRefreshSeconds' in patch) out.usageRefreshSeconds = oneOf(patch.usageRefreshSeconds, USAGE_CADENCES, DEFAULT_TRAY_APP_PREFS.usageRefreshSeconds)
|
||||
if ('quotaCadenceSeconds' in patch) out.quotaCadenceSeconds = oneOf(patch.quotaCadenceSeconds, QUOTA_CADENCES, DEFAULT_TRAY_APP_PREFS.quotaCadenceSeconds)
|
||||
if ('terminal' in patch) out.terminal = oneOf(patch.terminal, TERMINALS, DEFAULT_TRAY_APP_PREFS.terminal)
|
||||
return out
|
||||
}
|
||||
|
||||
export function sanitizeDockPatch(patch: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {}
|
||||
if ('enabled' in patch) out.enabled = patch.enabled === true
|
||||
if ('scale' in patch) out.scale = normalizeScale(patch.scale)
|
||||
if ('theme' in patch) out.theme = patch.theme === 'glass' ? 'glass' : 'graphite'
|
||||
if ('gaugeShape' in patch) out.gaugeShape = oneOf(patch.gaugeShape, DOCK_GAUGE_SHAPES, DEFAULT_TRAY_DOCK_PREFS.gaugeShape)
|
||||
if ('preferred' in patch) {
|
||||
out.preferred = typeof patch.preferred === 'string' && PROVIDER_ID.test(patch.preferred) ? patch.preferred : null
|
||||
}
|
||||
if ('providers' in patch) {
|
||||
const providers = Array.isArray(patch.providers)
|
||||
? patch.providers.filter((id): id is string => typeof id === 'string' && PROVIDER_ID.test(id))
|
||||
: []
|
||||
out.providers = providers
|
||||
// Editing the set by hand is what stops the tray app auto-seeding it from whatever is
|
||||
// connected, exactly as its own settings window latches it.
|
||||
out.manualSelection = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* The rail can only rest on a provider it is showing, so a resting provider that has left the
|
||||
* set gives way to the first one still in it. CapacityDockPreferences.normalizedPreferred.
|
||||
*/
|
||||
export function normalizedPreferred(preferred: string | null, selected: string[]): string | null {
|
||||
if (preferred !== null && selected.includes(preferred)) return preferred
|
||||
return selected[0] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* The rail must never end up with nothing to show, so the last connected provider in the set
|
||||
* cannot be switched off. CapacityDockProviderSelection.canDeselect.
|
||||
*/
|
||||
export function canDeselect(id: string, selected: string[], connected: readonly string[]): boolean {
|
||||
if (!selected.includes(id)) return true
|
||||
if (!connected.includes(id)) return true
|
||||
return selected.filter(entry => connected.includes(entry)).length > 1
|
||||
}
|
||||
|
|
@ -686,6 +686,30 @@ export type CompanionStatus = {
|
|||
store: boolean
|
||||
}
|
||||
|
||||
/** The tray app's own settings, from the two files it reads them from
|
||||
* (windows-settings.json, windows-dock.json) plus the HKCU Run value. */
|
||||
export type TrayPrefs = {
|
||||
app: {
|
||||
metric: string
|
||||
menubarPeriod: string
|
||||
accent: string
|
||||
trayBadge: boolean
|
||||
usageRefreshSeconds: number
|
||||
quotaCadenceSeconds: number
|
||||
terminal: string
|
||||
}
|
||||
dock: {
|
||||
enabled: boolean
|
||||
preferred: string | null
|
||||
scale: number
|
||||
theme: string
|
||||
gaugeShape: string
|
||||
providers: string[]
|
||||
manualSelection: boolean
|
||||
}
|
||||
launchAtLogin: boolean
|
||||
}
|
||||
|
||||
export interface CodeburnBridge {
|
||||
/** Subscribe to cold-start scan progress; returns an unsubscribe fn. */
|
||||
onProgress(cb: (event: ScanProgressEvent) => void): () => void
|
||||
|
|
@ -743,6 +767,11 @@ export interface CodeburnBridge {
|
|||
companionStatus?(): Promise<CompanionStatus>
|
||||
setMenuBarEnabled?(enabled: boolean): Promise<CompanionStatus>
|
||||
setSidebarEnabled?(enabled: boolean): Promise<CompanionStatus>
|
||||
/** The tray app's own settings. Null when there is no tray app to have any. */
|
||||
trayPrefs?(): Promise<TrayPrefs | null>
|
||||
setTrayAppPref?(patch: Record<string, unknown>): Promise<TrayPrefs | null>
|
||||
setTrayDockPref?(patch: Record<string, unknown>): Promise<TrayPrefs | null>
|
||||
setLaunchAtLogin?(enabled: boolean): Promise<TrayPrefs | null>
|
||||
// Plugin management
|
||||
pluginList(): Promise<unknown>
|
||||
pluginInfo(name: string): Promise<unknown>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue