Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
19 changes: 17 additions & 2 deletions packages/electron/src/launch-main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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', {
Expand Down
11 changes: 8 additions & 3 deletions packages/electron/src/launch-main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down Expand Up @@ -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 = [
Expand All @@ -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 } : {}),
}),
Expand Down
173 changes: 173 additions & 0 deletions packages/electron/src/power-traces.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> = {}) {
const table = new Map<string, L[]>();
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<string, unknown> = {}, 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();
});
});
31 changes: 29 additions & 2 deletions packages/electron/src/system-telemetry.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down
Loading
Loading