diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index e5f15afe..18433ce1 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1314,3 +1314,7 @@ recorded" was false. - **Android parity reference** — `/Users/alexeykarimov/Projects/Bugsee/android/sdk` (API + architecture target; Sentry/Firebase are *internal design references only*, never migration sources). - **Adversarial review + remediation** — `docs/review/` (the per-package reports) and `docs/review/REMEDIATION-PLAN.md` (the wave plan, every status, and the reasoning behind each decision — including items closed as NOT-a-defect with the measurement behind them). - **Memory (cross-session, my notes)** — `~/.claude/projects/.../memory/` (notable: `node-build-state.md`, `launch-options-scheme.md`, `core-package-complete-feat-core.md`, `capture-shared-package.md`, `git-remote-is-gerrit.md`, `core-typecheck-gotcha.md`). + +### 2026-10-27 — Electron thermal state and CPU speed limit traces (C13) → `feat/electron-power-traces` + +`ElectronPowerTracker` (`@bugsee/trackers/electron`) gains two stages beside `suspendResume`/`lockScreen`/`powerSource`: `thermalState` (`thermal-state-change`, macOS) and `speedLimit` (`speed-limit-change`, macOS and Windows), plus a live `current('thermalState')` read of `getCurrentThermalState()`. The tracker only normalises (a state that is not one of Electron's four names is `unknown`; a speed limit that is not a number in 0-100 is dropped, otherwise rounded to an integer). `@bugsee/electron` adds two producers to the Electron main trace set whenever `powerMonitor` is injected (system traces on, no legacy `systemMetricsSampler`): `thermal_state` (written at start from the live read and on every change; `unknown` writes nothing) and `cpu_speed_limit` (event-fed only: no initial value). Both are sampled, never held (spec javascript.md "Electron main traces"). **The `thermal_state` value form is one table, `packages/electron/src/thermal-state-wire.ts`:** today the iOS int (`nominal` 0, `fair` 1, `serious` 2, `critical` 3), the spec's current form. **OPEN OWNER QUESTION (bugsee-cocoa#288):** if the mobile SDKs converge on Android's strings the table becomes `normal`/`light`/`severe`/`critical` and nothing else changes. Not verified on a real Electron: the argument shape of the two events (taken from the Electron docs: the first argument is a `details` object with `state` / `limit`). diff --git a/packages/electron/src/launch-main.test.ts b/packages/electron/src/launch-main.test.ts index ed273c54..37f155c6 100644 --- a/packages/electron/src/launch-main.test.ts +++ b/packages/electron/src/launch-main.test.ts @@ -1172,11 +1172,15 @@ describe('launchMain — Electron domain trackers: power, display, application w expect(optsOf(f).wrapSystemEventsSource).toBeUndefined(); }); - it('a powerMonitor alone is enough for the events mux (no app needed) and adds no trace producer', () => { + it('a powerMonitor alone is enough for the events mux (no app needed) and adds only the power trace producers', () => { const powerMonitor = new FakeEmitter(); const f = fakeLaunch(); launchMain('tok', { ipcMain: fakeIpcMain().ipcMain, launch: f.launch, powerMonitor }); - expect(optsOf(f).systemTraceProducers).toBeUndefined(); + expect(producersOf(f)).toContain('process-memory'); + expect(producersOf(f)).toContain('thermal_state'); + expect(producersOf(f)).toContain('cpu_speed_limit'); + expect(producersOf(f)).not.toContain('electron-app-metrics'); + expect(producersOf(f)).not.toContain('displays'); const mux = wrapOf(f)(new Inner()); expect(powerMonitor.total()).toBe(0); // lazy const seen = vi.fn(); @@ -1214,6 +1218,17 @@ describe('launchMain — Electron domain trackers: power, display, application w expect(optsOf(f).systemTraceProducers).toBeUndefined(); }); + it('a legacy systemMetricsSampler with only a powerMonitor builds no producer list (the power producers would never start)', () => { + const f = fakeLaunch(); + launchMain('tok', { + ipcMain: fakeIpcMain().ipcMain, + launch: f.launch, + powerMonitor: new FakeEmitter(), + systemMetricsSampler: () => [], + }); + expect(optsOf(f).systemTraceProducers).toBeUndefined(); + }); + it('NEVER forwards the Electron objects or captureWindowEvents to the node launch', () => { const f = fakeLaunch(); launchMain('tok', { diff --git a/packages/electron/src/launch-main.ts b/packages/electron/src/launch-main.ts index 8139e70f..e2cc808f 100644 --- a/packages/electron/src/launch-main.ts +++ b/packages/electron/src/launch-main.ts @@ -153,7 +153,8 @@ export interface LaunchMainOptions extends BugseeLaunchOptions { gpuInfoType?: GpuInfoType; /** * Electron's `powerMonitor` — optional. When present and system events are captured, `power_suspend`/`power_resume`/ - * `power_lock`/`power_unlock`/`power_ac`/`power_battery` are recorded on `events.system`. Absent: that domain is off. + * `power_lock`/`power_unlock`/`power_ac`/`power_battery` are recorded on `events.system`, and (system traces on) + * `thermal_state` (macOS) and `cpu_speed_limit` (macOS, Windows) are traced. Absent: that domain is off. */ powerMonitor?: PowerMonitorSource; /** @@ -352,10 +353,13 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee // Trace producers: `systemTraceProducers` REPLACES the node defaults when supplied, so pass the node set (the caller's, // else the default one wired to this launch's scheduler/onError) PLUS the Electron producers. The node producers keep // `process_memory_*`/`cpu_*`/`event_loop_*` for the process that owns the session; the Electron ones only add names the - // node set never emits (`app_metrics`, `displays`). Not built when the legacy `systemMetricsSampler` replaces + // node set never emits (`app_metrics`, `displays`, `thermal_state`, `cpu_speed_limit`). Not built when the legacy `systemMetricsSampler` replaces // the producer list (they would never start). if ( - (tracker !== undefined || display !== undefined || captureState !== undefined) && + (tracker !== undefined || + display !== undefined || + power !== undefined || + captureState !== undefined) && nodeOptions.systemMetricsSampler === undefined ) { nodeOptions.systemTraceProducers = [ @@ -367,6 +371,7 @@ export function launchMain(appToken: string, options: LaunchMainOptions): Bugsee ...createElectronSystemTraceProducers({ ...(tracker !== undefined ? { process: tracker } : {}), ...(display !== undefined ? { display } : {}), + ...(power !== undefined ? { power } : {}), ...(screen !== undefined && appTracker !== undefined ? { application: appTracker } : {}), ...(nodeOptions.scheduler !== undefined ? { scheduler: nodeOptions.scheduler } : {}), }), diff --git a/packages/electron/src/power-traces.test.ts b/packages/electron/src/power-traces.test.ts new file mode 100644 index 00000000..f125654a --- /dev/null +++ b/packages/electron/src/power-traces.test.ts @@ -0,0 +1,173 @@ +import type { TraceSink } from '@bugsee/capture'; +import { + ElectronPowerTracker, + electronPowerTrackerFor, + type PowerMonitorSource, + resetElectronPowerTracker, +} from '@bugsee/trackers/electron'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createElectronSystemTraceProducers } from './system-traces'; + +type L = (...a: unknown[]) => void; +function fakeMonitor(over: Record = {}) { + const table = new Map(); + const monitor = { + on: vi.fn((e: string, l: L) => { + table.set(e, [...(table.get(e) ?? []), l]); + }), + removeListener: vi.fn((e: string, l: L) => { + table.set( + e, + (table.get(e) ?? []).filter((x) => x !== l), + ); + }), + getCurrentThermalState: vi.fn((): unknown => 'nominal'), + ...over, + }; + return { + monitor: monitor as PowerMonitorSource & typeof monitor, + fire: (e: string, ...args: unknown[]) => { + for (const l of [...(table.get(e) ?? [])]) l(...args); + }, + total: () => [...table.values()].reduce((n, l) => n + l.length, 0), + }; +} + +const keys: object[] = []; +afterEach(() => { + for (const k of keys.splice(0)) resetElectronPowerTracker(k); +}); + +function setup(over: Record = {}, onError?: (e: unknown) => unknown) { + const m = fakeMonitor(over); + keys.push(m.monitor); + const power = electronPowerTrackerFor({ powerMonitor: m.monitor }, onError); + const emitted: Array<{ name: string; value: unknown; hold: boolean | undefined }> = []; + const sink: TraceSink = { + emit: (name, value, display, options) => { + expect(display).toBeUndefined(); // no JavaScript producer sets displayId + emitted.push({ name, value, hold: options?.hold }); + }, + }; + const producers = createElectronSystemTraceProducers({ power }); + return { m, power, emitted, sink, producers }; +} + +describe('power traces: thermal_state and cpu_speed_limit (C13)', () => { + it('builds the two producers for a power tracker, none without one', () => { + expect(setup().producers.map((p) => p.name)).toEqual(['thermal_state', 'cpu_speed_limit']); + expect(createElectronSystemTraceProducers({}).map((p) => p.name)).toEqual([]); + }); + + it('touches nothing until started', () => { + const { m, producers } = setup(); + expect(m.monitor.on).not.toHaveBeenCalled(); + expect(m.monitor.getCurrentThermalState).not.toHaveBeenCalled(); + expect(producers.length).toBe(2); + }); + + it('thermal_state: writes the current state at start (iOS int), then every change; sampled, never held', () => { + const { m, producers, emitted, sink } = setup({ getCurrentThermalState: () => 'fair' }); + producers[0]?.start(sink); + expect(emitted).toEqual([{ name: 'thermal_state', value: 1, hold: false }]); + m.fire('thermal-state-change', { state: 'serious' }); + m.fire('thermal-state-change', { state: 'critical' }); + m.fire('thermal-state-change', { state: 'nominal' }); + expect(emitted.map((e) => e.value)).toEqual([1, 2, 3, 0]); + expect(emitted.every((e) => e.name === 'thermal_state' && e.hold === false)).toBe(true); + }); + + it('thermal_state: `unknown` writes nothing (at start and on an event); a later known state still lands', () => { + const { m, producers, emitted, sink } = setup({ getCurrentThermalState: () => 'unknown' }); + producers[0]?.start(sink); + m.fire('thermal-state-change', { state: 'unknown' }); + m.fire('thermal-state-change', { state: 'bogus' }); + expect(emitted).toEqual([]); + m.fire('thermal-state-change', { state: 'fair' }); + expect(emitted.map((e) => e.value)).toEqual([1]); + }); + + it('thermal_state: no getCurrentThermalState (Windows/Linux) -> no baseline; listener still armed harmlessly', () => { + const { producers, emitted, sink } = setup({ getCurrentThermalState: undefined }); + producers[0]?.start(sink); + expect(emitted).toEqual([]); + }); + + it('thermal_state: stop releases the listener, a late event writes nothing, and a restart re-reads', () => { + let state = 'nominal'; + const { m, producers, emitted, sink } = setup({ getCurrentThermalState: () => state }); + producers[0]?.start(sink); + expect(m.total()).toBe(1); + producers[0]?.stop(); + expect(m.total()).toBe(0); + m.fire('thermal-state-change', { state: 'critical' }); + expect(emitted).toHaveLength(1); + state = 'serious'; + producers[0]?.start(sink); + expect(emitted.map((e) => e.value)).toEqual([0, 2]); + }); + + it('cpu_speed_limit: event-fed only (no baseline), integer percent, sampled, never held', () => { + const { m, producers, emitted, sink } = setup(); + producers[1]?.start(sink); + expect(emitted).toEqual([]); + m.fire('speed-limit-change', { limit: 75 }); + m.fire('speed-limit-change', { limit: 100 }); + m.fire('speed-limit-change', { limit: 0 }); // a genuine 0 is a measured value + expect(emitted).toEqual([ + { name: 'cpu_speed_limit', value: 75, hold: false }, + { name: 'cpu_speed_limit', value: 100, hold: false }, + { name: 'cpu_speed_limit', value: 0, hold: false }, + ]); + }); + + it('cpu_speed_limit: an unreadable limit writes nothing, and stop releases the listener', () => { + const { m, producers, emitted, sink } = setup(); + producers[1]?.start(sink); + m.fire('speed-limit-change', { limit: 'fast' }); + m.fire('speed-limit-change', {}); + expect(emitted).toEqual([]); + producers[1]?.stop(); + expect(m.total()).toBe(0); + m.fire('speed-limit-change', { limit: 50 }); + expect(emitted).toEqual([]); + }); + + it('the two producers are independent: each arms only its own Electron event', () => { + const { m, producers, sink } = setup(); + producers[0]?.start(sink); + expect(m.total()).toBe(1); + producers[1]?.start(sink); + expect(m.total()).toBe(2); + producers[0]?.stop(); + expect(m.total()).toBe(1); + }); + + it('a throwing getCurrentThermalState is reported through the tracker and the producer still starts', () => { + const onError = vi.fn(); + const { m, producers, emitted, sink } = setup( + { + getCurrentThermalState: () => { + throw new Error('thermal'); + }, + }, + onError, + ); + expect(() => producers[0]?.start(sink)).not.toThrow(); + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'thermal' }), + ); + m.fire('thermal-state-change', { state: 'fair' }); + expect(emitted.map((e) => e.value)).toEqual([1]); + }); + + it('works with a directly constructed tracker too (structural, no registry needed)', () => { + const m = fakeMonitor(); + const tracker = new ElectronPowerTracker({ powerMonitor: m.monitor }); + const producers = createElectronSystemTraceProducers({ power: tracker }); + const seen: unknown[] = []; + producers[0]?.start({ emit: (_n, v) => seen.push(v) }); + expect(seen).toEqual([0]); + tracker.reset(); + }); +}); diff --git a/packages/electron/src/system-telemetry.integration.test.ts b/packages/electron/src/system-telemetry.integration.test.ts index 1b9ff930..0736cf84 100644 --- a/packages/electron/src/system-telemetry.integration.test.ts +++ b/packages/electron/src/system-telemetry.integration.test.ts @@ -308,6 +308,10 @@ class Emitter { emit(e: string, ...a: unknown[]) { for (const l of [...(this.table.get(e) ?? [])]) l({}, ...a); } + /** Electron's own shape for the powerMonitor details events: the FIRST argument is the details object. */ + emitDetail(e: string, detail: unknown) { + for (const l of [...(this.table.get(e) ?? [])]) l(detail); + } count(e: string) { return this.table.get(e)?.length ?? 0; } @@ -428,10 +432,33 @@ describe('Electron domain trackers -> real node launch -> assembled report', () await client.stop(); }); + it('thermal_state (iOS int) and cpu_speed_limit land in the uploaded traces.system, in order, none held (C13)', async () => { + const w = domainWorld(); + let thermal = 'fair'; + Object.assign(w.powerMonitor, { getCurrentThermalState: () => thermal }); + const { client, puts } = launchDomains(w); + w.powerMonitor.emitDetail('thermal-state-change', { state: 'serious' }); + w.powerMonitor.emitDetail('speed-limit-change', { limit: 80 }); + thermal = 'unknown'; + w.powerMonitor.emitDetail('thermal-state-change', { state: 'unknown' }); // writes nothing + w.powerMonitor.emitDetail('thermal-state-change', { state: 'critical' }); + w.powerMonitor.emitDetail('speed-limit-change', { limit: 100 }); + await client.logException(new Error('x')); + const traces = fileOf<{ name: string; value: unknown }>( + puts[0] as Uint8Array, + 'traces.system.json', + ); + const of = (n: string) => traces.filter((t) => t.name === n).map((t) => t.value); + expect(of('thermal_state')).toEqual([1, 2, 3]); + expect(of('cpu_speed_limit')).toEqual([80, 100]); + await client.stop(); + expect(w.powerMonitor.total()).toBe(0); + }); + it('captureSystemEvents OFF: no power/window/display-event listeners (the displays TRACE keeps only its own); both off: none at all', async () => { const w = domainWorld([new Win(1)]); const { client } = launchDomains(w, { captureSystemEvents: false }); - expect(w.powerMonitor.total()).toBe(0); + expect(w.powerMonitor.total()).toBe(2); // only the thermal_state and cpu_speed_limit TRACES keep theirs // no window/renderer EVENTS, but the displays trace follows the key window: windowFocus + windowMoved only expect(w.app.count('browser-window-created')).toBe(2); expect(w.app.count('web-contents-created')).toBe(0); @@ -449,7 +476,7 @@ describe('Electron domain trackers -> real node launch -> assembled report', () const win = new Win(1); const w = domainWorld([win]); const { client } = launchDomains(w); - expect(w.powerMonitor.total()).toBe(6); + expect(w.powerMonitor.total()).toBe(8); // the events (6) + thermal_state and cpu_speed_limit expect(w.screen.total()).toBe(6); // events (3) + the displays trace (3) expect(w.app.count('browser-window-created')).toBe(3); // focus, visibility, moved (the displays trace's key window) expect(w.app.count('web-contents-created')).toBe(1); diff --git a/packages/electron/src/system-traces.ts b/packages/electron/src/system-traces.ts index 76e64271..1e729880 100644 --- a/packages/electron/src/system-traces.ts +++ b/packages/electron/src/system-traces.ts @@ -6,8 +6,10 @@ import type { DisplayInfo, ElectronApplicationTracker, ElectronDisplayTracker, + ElectronPowerTracker, ElectronProcessTracker, } from '@bugsee/trackers/electron'; +import { thermalStateWire } from './thermal-state-wire'; // Electron-main `traces.system` producers. COMPOSITION only: `launchMain` appends these to the node producer set (the // node set keeps `process_memory_*`/`cpu_*`/`event_loop_*` for the process that owns the session; nothing here emits a @@ -168,10 +170,62 @@ class DisplaysProducer extends TraceProducerBase { } } +// `thermal_state` and `cpu_speed_limit` (C13): both come from the Power domain tracker's `powerMonitor` stages and are +// SAMPLED / event-driven (never held, spec javascript.md "Electron main traces"): a state the OS stops reporting leaves +// a gap rather than a frozen line. +// +// thermal_state the wire value is decided by `thermal-state-wire.ts` (OPEN OWNER QUESTION, bugsee-cocoa#288; today the +// iOS int 0-3). Written at start (a live read of `getCurrentThermalState()`) and on every +// `thermal-state-change`. macOS only: elsewhere the method is absent / answers `unknown`, which writes +// nothing (omit, never zero). +// A transition from a known state to `unknown` therefore leaves the previous value as the last sample (the +// spec: sampled, never held, omit never zero): a consumer that draws the last point of the series should not +// read it as "still that hot". +// cpu_speed_limit int percent 0-100 from `speed-limit-change` ONLY (macOS and Windows): there is no initial value and no +// value until the OS reports a limit. A measured 0 is a real limit and is written. +class ThermalStateProducer extends TraceProducerBase { + readonly name = 'thermal_state'; + #off: (() => void) | undefined; + constructor(private readonly tracker: ElectronPowerTracker) { + super(); + } + #publish(state: Parameters[0]): void { + const wire = thermalStateWire(state); + if (wire !== undefined) this.emit('thermal_state', wire); + } + protected onStart(): void { + // subscribe FIRST (arming the listener), then the baseline read: no change can fall between the two + this.#off = this.tracker.on('thermalState', (e) => this.#publish(e.state)); + const current = this.tracker.current('thermalState'); + if (current !== undefined) this.#publish(current.state); + } + protected override onStop(): void { + this.#off?.(); + this.#off = undefined; + } +} + +class CpuSpeedLimitProducer extends TraceProducerBase { + readonly name = 'cpu_speed_limit'; + #off: (() => void) | undefined; + constructor(private readonly tracker: ElectronPowerTracker) { + super(); + } + protected onStart(): void { + this.#off = this.tracker.on('speedLimit', (e) => this.emit('cpu_speed_limit', e.limit)); + } + protected override onStop(): void { + this.#off?.(); + this.#off = undefined; + } +} + /** The trackers the Electron producers read; a domain whose tracker is absent is simply off. */ export interface ElectronTraceTrackers { process?: ElectronProcessTracker; display?: ElectronDisplayTracker; + /** Feeds `thermal_state` and `cpu_speed_limit` (the `powerMonitor` stages). */ + power?: ElectronPowerTracker; /** Resolves the key window; without it the `displays` list follows the primary display (and no focus changes). */ application?: ElectronApplicationTracker; /** Timer source for the window-move debounce (default: the global timers). */ @@ -187,5 +241,8 @@ export function createElectronSystemTraceProducers( ...(trackers.display !== undefined ? [new DisplaysProducer(trackers.display, trackers.application, trackers.scheduler)] : []), + ...(trackers.power !== undefined + ? [new ThermalStateProducer(trackers.power), new CpuSpeedLimitProducer(trackers.power)] + : []), ]; } diff --git a/packages/electron/src/thermal-state-wire.test.ts b/packages/electron/src/thermal-state-wire.test.ts new file mode 100644 index 00000000..c1b977d9 --- /dev/null +++ b/packages/electron/src/thermal-state-wire.test.ts @@ -0,0 +1,29 @@ +import type { ElectronThermalState } from '@bugsee/trackers/electron'; +import { describe, expect, it } from 'vitest'; +import { THERMAL_STATE_WIRE, thermalStateWire } from './thermal-state-wire'; + +describe('thermal_state wire table (OPEN OWNER QUESTION: bugsee-cocoa#288, int vs Android strings)', () => { + it('the table is the iOS int form (the spec value form today), and unknown has no wire value', () => { + expect(THERMAL_STATE_WIRE).toStrictEqual({ + unknown: undefined, + nominal: 0, + fair: 1, + serious: 2, + critical: 3, + }); + }); + + it('thermalStateWire reads ONLY the table (so changing the form is a one-place edit)', () => { + const states: ElectronThermalState[] = ['unknown', 'nominal', 'fair', 'serious', 'critical']; + expect(states.map(thermalStateWire)).toEqual([undefined, 0, 1, 2, 3]); + }); + + it('a state the table has no row for answers undefined (omit, never guess)', () => { + expect(thermalStateWire('meltdown' as ElectronThermalState)).toBeUndefined(); + }); + + it('does not resolve inherited Object.prototype keys as states', () => { + expect(thermalStateWire('toString' as ElectronThermalState)).toBeUndefined(); + expect(thermalStateWire('constructor' as ElectronThermalState)).toBeUndefined(); + }); +}); diff --git a/packages/electron/src/thermal-state-wire.ts b/packages/electron/src/thermal-state-wire.ts new file mode 100644 index 00000000..b9b52957 --- /dev/null +++ b/packages/electron/src/thermal-state-wire.ts @@ -0,0 +1,26 @@ +import type { ElectronThermalState } from '@bugsee/trackers/electron'; + +// The ONE place that decides what a thermal state looks like on the wire (`traces.system` `thermal_state`). +// +// OPEN OWNER QUESTION (bugsee-cocoa#288): the mobile SDKs disagree. iOS writes the int `0` nominal / `1` fair / +// `2` serious / `3` critical; Android writes a string. The spec's CURRENT form for JavaScript is the iOS int, because +// Electron's source on macOS is exactly Apple's `NSProcessInfoThermalState`, so the mapping is lossless. If the mobile +// SDKs converge on Android's strings, change ONLY this table: +// +// nominal -> 'normal', fair -> 'light', serious -> 'severe', critical -> 'critical' +// +// `unknown` has no wire value: it is OMITTED, never written as a number (omit, never zero). +export const THERMAL_STATE_WIRE: Readonly< + Record +> = { + unknown: undefined, + nominal: 0, + fair: 1, + serious: 2, + critical: 3, +}; + +/** The wire value of a thermal state, or undefined when it has none (a state this table has no row for included). */ +export function thermalStateWire(state: ElectronThermalState): number | string | undefined { + return Object.hasOwn(THERMAL_STATE_WIRE, state) ? THERMAL_STATE_WIRE[state] : undefined; +} diff --git a/packages/trackers/src/electron/index.ts b/packages/trackers/src/electron/index.ts index 247e4b32..cdffb8d0 100644 --- a/packages/trackers/src/electron/index.ts +++ b/packages/trackers/src/electron/index.ts @@ -29,6 +29,7 @@ export { type ElectronPowerEnv, type ElectronPowerEvents, ElectronPowerTracker, + type ElectronThermalState, electronPowerTrackerFor, type PowerMonitorSource, resetElectronPowerTracker, diff --git a/packages/trackers/src/electron/power-tracker.test.ts b/packages/trackers/src/electron/power-tracker.test.ts index f115fe29..8b8c0cfa 100644 --- a/packages/trackers/src/electron/power-tracker.test.ts +++ b/packages/trackers/src/electron/power-tracker.test.ts @@ -20,12 +20,13 @@ function fakeMonitor(over: Record = {}) { ); }), isOnBatteryPower: vi.fn((): unknown => false), + getCurrentThermalState: vi.fn((): unknown => 'nominal'), ...over, }; return { monitor: monitor as PowerMonitorSource & typeof monitor, - fire: (e: string) => { - for (const l of [...(table.get(e) ?? [])]) l(); + fire: (e: string, ...args: unknown[]) => { + for (const l of [...(table.get(e) ?? [])]) l(...args); }, count: (e: string) => table.get(e)?.length ?? 0, total: () => [...table.values()].reduce((n, l) => n + l.length, 0), @@ -176,6 +177,146 @@ describe('ElectronPowerTracker', () => { it('rejects an unknown stage name', () => { const t = track(fakeMonitor()); expect(t.current('other' as 'powerSource')).toBeUndefined(); + expect(t.current('other' as 'thermalState')).toBeUndefined(); + }); + }); + + describe('thermalState stage (macOS thermal-state-change)', () => { + it('maps the event detail to a known state, attaching only its own event and releasing on the last unsubscribe', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + const off = t.on('thermalState', seen); + expect(m.count('thermal-state-change')).toBe(1); + expect(m.total()).toBe(1); + for (const state of ['nominal', 'fair', 'serious', 'critical']) { + m.fire('thermal-state-change', { state }); + } + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { state: 'nominal' }, + { state: 'fair' }, + { state: 'serious' }, + { state: 'critical' }, + ]); + off(); + expect(m.total()).toBe(0); + }); + it('anything that is not one of the four known states is reported as unknown (never passed through)', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + t.on('thermalState', seen); + m.fire('thermal-state-change', { state: 'unknown' }); + m.fire('thermal-state-change', { state: 'meltdown' }); + m.fire('thermal-state-change', { state: 3 }); + m.fire('thermal-state-change', {}); + m.fire('thermal-state-change', null); + m.fire('thermal-state-change'); + expect(seen.mock.calls.map((c) => c[0])).toEqual(Array(6).fill({ state: 'unknown' })); + }); + it('a BARE state (the listener receives the string itself) is read too: right whichever shape Electron uses', () => { + const m = fakeMonitor(); + const seen = vi.fn(); + track(m).on('thermalState', seen); + m.fire('thermal-state-change', 'serious'); + m.fire('thermal-state-change', 'bogus'); + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { state: 'serious' }, + { state: 'unknown' }, + ]); + }); + + it('does not arm the other stages', () => { + const m = fakeMonitor(); + track(m).on('thermalState', () => {}); + expect(m.count('speed-limit-change')).toBe(0); + expect(m.count('on-ac')).toBe(0); + }); + }); + + describe('speedLimit stage (speed-limit-change)', () => { + it('maps the percent limit, attaching only its own event and releasing on the last unsubscribe', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + const off = t.on('speedLimit', seen); + expect(m.count('speed-limit-change')).toBe(1); + expect(m.total()).toBe(1); + m.fire('speed-limit-change', { limit: 100 }); + m.fire('speed-limit-change', { limit: 0 }); + m.fire('speed-limit-change', { limit: 62.4 }); + expect(seen.mock.calls.map((c) => c[0])).toEqual([ + { limit: 100 }, + { limit: 0 }, + { limit: 62 }, + ]); + off(); + expect(m.total()).toBe(0); + }); + it('a BARE limit (the listener receives the number itself) is read too', () => { + const m = fakeMonitor(); + const seen = vi.fn(); + track(m).on('speedLimit', seen); + m.fire('speed-limit-change', 75); + m.fire('speed-limit-change', 'fast'); + m.fire('speed-limit-change', 250); + expect(seen.mock.calls.map((c) => c[0])).toEqual([{ limit: 75 }]); + }); + + it('drops a limit that cannot be real: non-number, NaN/Infinity, outside 0-100, no detail (omit, never zero)', () => { + const m = fakeMonitor(); + const t = track(m); + const seen = vi.fn(); + t.on('speedLimit', seen); + for (const detail of [ + { limit: '50' }, + { limit: Number.NaN }, + { limit: Number.POSITIVE_INFINITY }, + { limit: -1 }, + { limit: 101 }, + { limit: 100.4 }, + {}, + null, + undefined, + ]) { + m.fire('speed-limit-change', detail); + } + expect(seen).not.toHaveBeenCalled(); + }); + }); + + describe("current('thermalState')", () => { + it('reads getCurrentThermalState live and validates it', () => { + const m = fakeMonitor(); + const t = track(m); + for (const state of ['nominal', 'fair', 'serious', 'critical', 'unknown']) { + m.monitor.getCurrentThermalState.mockReturnValue(state); + expect(t.current('thermalState')).toEqual({ state }); + } + m.monitor.getCurrentThermalState.mockReturnValue('nuclear'); + expect(t.current('thermalState')).toEqual({ state: 'unknown' }); + m.monitor.getCurrentThermalState.mockReturnValue(2); + expect(t.current('thermalState')).toEqual({ state: 'unknown' }); + }); + it('is undefined without the method (non-macOS Electron) and when it throws (reported)', () => { + const quiet = vi.fn(); + expect( + track(fakeMonitor({ getCurrentThermalState: undefined }), quiet).current('thermalState'), + ).toBeUndefined(); + expect(quiet).not.toHaveBeenCalled(); + const onError = vi.fn(); + const bad = fakeMonitor({ + getCurrentThermalState: () => { + throw new Error('thermal'); + }, + }); + expect(track(bad, onError).current('thermalState')).toBeUndefined(); + expect(onError).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'thermal' }), + ); + }); + it('is undefined for a tracker with no monitor', () => { + expect(new ElectronPowerTracker().current('thermalState')).toBeUndefined(); }); }); diff --git a/packages/trackers/src/electron/power-tracker.ts b/packages/trackers/src/electron/power-tracker.ts index 22f3fe1e..a38c41ef 100644 --- a/packages/trackers/src/electron/power-tracker.ts +++ b/packages/trackers/src/electron/power-tracker.ts @@ -2,16 +2,21 @@ import { createTrackerRegistry } from '../tracker-registry'; import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-tracker'; // Electron MAIN-process POWER tracker (domain tracker, design §15.2/§15.4 TR9; Android reference: BugseeTrackerPower). -// It owns what Electron's `powerMonitor` can say, as THREE stages, each arming its own pair of `powerMonitor` -// listeners only while it has a subscriber and releasing them when the last leaves: +// It owns what Electron's `powerMonitor` can say, as FIVE stages, each arming its own `powerMonitor` listeners only +// while it has a subscriber and releasing them when the last leaves: // // suspendResume 'suspend' / 'resume' -> { state: 'suspend' | 'resume' } // lockScreen 'lock-screen' / 'unlock-screen' -> { state: 'lock' | 'unlock' } (macOS/Windows; never fires on Linux) // powerSource 'on-ac' / 'on-battery' -> { source: 'ac' | 'battery' } +// thermalState 'thermal-state-change' -> { state: ThermalState } (macOS only; the Apple enum) +// speedLimit 'speed-limit-change' -> { limit: number } (macOS/Windows; percent 0-100) // // `current('powerSource')` is a LIVE read of `powerMonitor.isOnBatteryPower()`; it answers undefined when the monitor has -// no such method, it throws (reported) or returns a non-boolean: a source is never guessed. `thermal-state-change` and -// `speed-limit-change` are deliberately NOT mapped: they are macOS-only and the thermal state is not Android's int enum. +// no such method, it throws (reported) or returns a non-boolean: a source is never guessed. `current('thermalState')` is +// the same for `getCurrentThermalState()` (a string Electron documents for macOS; elsewhere the method answers +// 'unknown' or is absent). The tracker only NORMALISES: a thermal state that is not one of Electron's four named states is +// 'unknown' (never passed through) and a speed limit that is not a finite 0-100 number is dropped. WHICH wire value a state +// becomes is the producer's business (packages/electron/src/thermal-state-wire.ts), not this tracker's. // PLATFORM DEPENDENT: per Electron's typings `on-ac` is documented for macOS and Windows and `on-battery` for macOS // only, so on Linux (and `on-battery` on Windows) the event may simply never fire; `lock-screen`/`unlock-screen` are // macOS/Windows. Absence of an event is never evidence of a state: read `current('powerSource')` for the live value. @@ -22,12 +27,22 @@ import { bindAll, ElectronStageTracker, type EmitterSource } from './stage-track /** The slice of Electron's `powerMonitor` this tracker reads. Every member is optional: an absent one means the stage is absent. */ export interface PowerMonitorSource extends EmitterSource { isOnBatteryPower?(): unknown; + /** macOS only. */ + getCurrentThermalState?(): unknown; } +/** Electron's `powerMonitor` thermal states (NSProcessInfoThermalState), plus `unknown` for anything else. */ +export type ElectronThermalState = 'unknown' | 'nominal' | 'fair' | 'serious' | 'critical'; + +const THERMAL_STATES: ReadonlySet = new Set(['nominal', 'fair', 'serious', 'critical']); + export interface ElectronPowerEvents { suspendResume: { state: 'suspend' | 'resume' }; lockScreen: { state: 'lock' | 'unlock' }; powerSource: { source: 'ac' | 'battery' }; + thermalState: { state: ElectronThermalState }; + /** The operating system's advertised CPU speed limit, integer percent 0-100. */ + speedLimit: { limit: number }; } export interface ElectronPowerEnv { @@ -37,7 +52,35 @@ export interface ElectronPowerEnv { type PowerStage = keyof ElectronPowerEvents; -const STAGE_EVENTS: Record> = { +/** A stage's Electron events: the payload is fixed, or computed from the event's first argument (undefined = drop it). */ +type Payload = + | ElectronPowerEvents[PowerStage] + | ((detail: unknown) => ElectronPowerEvents[PowerStage] | undefined); + +const normaliseThermal = (state: unknown): ElectronThermalState => + THERMAL_STATES.has(state) ? (state as ElectronThermalState) : 'unknown'; + +/** + * The value of a `powerMonitor` details event. Electron documents `details` objects (`{state}`, `{limit}`), but the shape + * was not verified on a real Electron, so a BARE value (`listener('fair')`, `listener(80)`) is read as the value itself: + * right whichever form Electron uses, and an unknown shape still normalises to unknown / dropped. + */ +const detailValue = (detail: unknown, key: 'state' | 'limit'): unknown => + typeof detail === 'object' && detail !== null ? (detail as Record)[key] : detail; + +const thermalOf = (detail: unknown): { state: ElectronThermalState } => ({ + state: normaliseThermal(detailValue(detail, 'state')), +}); + +const speedLimitOf = (detail: unknown): { limit: number } | undefined => { + const limit = detailValue(detail, 'limit'); + // the range test also rejects NaN and the infinities (every comparison with them is false) + return typeof limit === 'number' && limit >= 0 && limit <= 100 + ? { limit: Math.round(limit) } + : undefined; +}; + +const STAGE_EVENTS: Record> = { suspendResume: [ ['suspend', { state: 'suspend' }], ['resume', { state: 'resume' }], @@ -50,11 +93,19 @@ const STAGE_EVENTS: Record { readonly name = 'electron-power'; - protected readonly stages: readonly PowerStage[] = ['suspendResume', 'lockScreen', 'powerSource']; + protected readonly stages: readonly PowerStage[] = [ + 'suspendResume', + 'lockScreen', + 'powerSource', + 'thermalState', + 'speedLimit', + ]; readonly #monitor: PowerMonitorSource | undefined; constructor(env: ElectronPowerEnv = {}, onError?: (error: unknown) => unknown) { @@ -68,11 +119,19 @@ export class ElectronPowerTracker extends ElectronStageTracker ({ src: monitor, event, - listener: () => this.emit(stage, { ...payload } as never), + listener: (detail) => { + const value = typeof payload === 'function' ? payload(detail) : { ...payload }; + if (value !== undefined) this.emit(stage, value as never); + }, })), this.report, );