Skip to content

feat(trackers,electron): thermal_state and cpu_speed_limit traces from powerMonitor (C13) - #125

Merged
krassx merged 2 commits into
mainfrom
feat/electron-power-traces
Oct 27, 2026
Merged

krassx merged 2 commits into
mainfrom
feat/electron-power-traces

Conversation

@krassx

@krassx krassx commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

What

Closes spec gap C13 (Electron thermal and low-power signals) for Electron main.

  • ElectronPowerTracker (@bugsee/trackers/electron, the one Power-domain tracker; no per-signal trackers) gains two stages next to 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: an unrecognised thermal state is unknown; a speed limit outside 0-100 or not a number is dropped (otherwise rounded to an integer).
  • @bugsee/electron adds two producers to the Electron main trace set whenever powerMonitor is injected: thermal_state (live read at start, then every change; unknown writes nothing) and cpu_speed_limit (event-fed only, so no initial value). Both are sampled, never held, per the spec's "Electron main traces" rows.
  • The power events (power_suspend, power_resume, power_lock, power_unlock, power_ac, power_battery) already existed; there is no Electron low-power-mode API (the spec marks low_power_mode as not available for Electron), so nothing is added for it.

thermal_state wire form: one table

packages/electron/src/thermal-state-wire.ts is the single place that decides the value. Today it is the spec's current form, the iOS int (nominal 0, fair 1, serious 2, critical 3; unknown omitted). Switching to Android's strings (normal, light, severe, critical) is an edit to that table only; its header comment says so.

Open owner question (for the PR discussion)

  • bugsee-cocoa#288: the thermal_state value form. iOS writes an int, Android writes a string, and the spec currently picks the iOS int. This PR implements that and keeps the mapping in one table so it can change in one place. Needs an owner decision if the mobile SDKs converge on strings.
  • Spec says thermal_state and cpu_speed_limit are not held, so a rolling capture window that starts after the last change will not contain a thermal_state value (same trade-off the spec already makes for other event-driven traces). Flagging in case the owner prefers held for the thermal state.

Tests

Test-first. Tracker unit tests, producer unit tests, wire-table tests, launch-level composition tests (power producers present with a powerMonitor alone; absent under the legacy systemMetricsSampler) and a real-launch integration test that asserts thermal_state [1, 2, 3] and cpu_speed_limit [80, 100] in the uploaded traces.system, and that client.stop() releases every listener. Existing listener-count tests were updated (6 to 8 power listeners with both streams on; 2 with events off).

Mutator loop (restored from a saved copy each time, ~38 injected mutations across power-tracker.ts, system-traces.ts, thermal-state-wire.ts, launch-main.ts): all killed after removing one redundant Number.isFinite that the range test already implied.

pnpm ci:local passes locally (lint, typecheck, cycles, per-package coverage, unit). e2e job not run.

Not verified

Not run against a real Electron: the argument shape of the two events (implemented from the Electron docs: first argument is a details object with state / limit) and getCurrentThermalState() semantics on a real macOS machine.

🤖 Generated with Claude Code

…m powerMonitor (C13)

The Power tracker gains thermalState and speedLimit stages; @bugsee/electron adds the two
producers. The thermal_state wire form is a single table (thermal-state-wire.ts).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 50s —— View job


Review of PR #125 (C13 thermal_state / cpu_speed_limit traces)

I read the whole diff and its surrounding code (the stage tracker's bindAll, the launch-main.ts wiring, the producers and the tests). I did not run the test suite or any tools. This is a read-only review and I pushed nothing.

Overall risk: Low–Medium. The change is small, isolated and well covered. The one real risk is untested against actual Electron.

Merge recommendation: Merge after the event-argument shape is either confirmed on a real macOS Electron or handled in both forms (P2 below).

Findings

  1. P2: Event argument shape is unverified, and a wrong guess fails silently. See the inline comment on packages/trackers/src/electron/power-tracker.ts:63-74. thermalOf and speedLimitOf only read detail.state / detail.limit. If Electron passes the bare string or number to the listener, every thermal change becomes unknown and is dropped, and every speed limit is dropped. Every test emits an object, so none would catch it. Accepting both shapes is a few lines.
  2. P3: A transition to unknown leaves the old value as the last sample. See the inline comment on packages/electron/src/system-traces.ts:183-201. It is a spec question and probably intended, so I would just document it.

Checked and found fine

  • bindAll forwards listener arguments, so the new payload-function path receives detail.
  • Producers subscribe before the baseline read, so no change can fall between the two.
  • Teardown releases each producer's listener, and the integration test asserts powerMonitor.total() === 0 after stop().
  • The launch-main.ts gating on power and the legacy systemMetricsSampler exclusion are consistent with the existing trackers.
  • Dropping non-numbers, NaN, infinities and out-of-range limits in speedLimitOf is correct, and 0 is correctly kept.
  • The open bugsee-cocoa#288 wire-form question is isolated in thermal-state-wire.ts, so it can change in one place.

Positives

  • Test-first, with a mutator loop and real-launch integration coverage.
  • A single wire table, and only one Power-domain tracker.
  • The PR is honest about what was not verified.

@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bacb6d19-ea77-4c3d-ba84-3035f7965b24
Commits

Reviewing files that changed from the base of the PR and between 5538e89 and f9686b9.

Files selected for processing: 3
  • packages/electron/src/system-traces.ts
  • packages/trackers/src/electron/power-tracker.test.ts
  • packages/trackers/src/electron/power-tracker.ts
Files skipped from review as they are similar to previous changes: 1
  • packages/electron/src/system-traces.ts

Limit details: You’ve used all 10 included reviews currently available.

📝 Summary

Summary by CodeRabbit

  • New Features
    • System traces can capture device thermal state on macOS and CPU speed limits on macOS and Windows when supported.
    • Thermal traces report an initial state when available and subsequent changes; unknown states are omitted. CPU speed-limit traces report event values from 0 to 100, rounded to whole numbers.
    • These traces are available when system tracing uses the power monitor without the legacy system metrics sampler.

The Electron power tracker adds thermal-state and CPU-speed-limit stages. It normalizes thermal states, validates and rounds speed limits, and supports live thermal-state reads. Electron system trace producers publish recognized thermal states and reported speed limits when a power tracker is available. The thermal-state producer samples an initial value when available; the speed-limit producer has no initial value.

Sequence Diagram(s)

sequenceDiagram
  participant ElectronPowerMonitor
  participant ElectronPowerTracker
  participant ThermalStateProducer
  participant CpuSpeedLimitProducer
  ElectronPowerMonitor->>ElectronPowerTracker: emit thermal-state or speed-limit event
  ElectronPowerTracker->>ThermalStateProducer: provide normalized thermal state
  ElectronPowerTracker->>CpuSpeedLimitProducer: provide validated speed limit
  ThermalStateProducer->>SystemTraceOutput: publish recognized thermal-state value
  CpuSpeedLimitProducer->>SystemTraceOutput: publish reported speed limit
Loading

Possibly related PRs

Suggested labels: javascript

Priority: Low

Change: Feature

Merge Risk: Minimal · up to f9686

The new power traces appear ready to merge after normal checks; testing with real Electron remains advisable.

Architecture risk: Medium · up to f9686

The change affects 3 systems.

Changed systems: packages/trackers, packages/electron, docs

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — packages/trackers (library) was modified; 3 changed files map to changed impact.
  • observed — packages/electron (library) was modified; 7 changed files map to changed impact.
  • observed — docs (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in docs/PROGRESS.md: Adds a progress entry documenting the Electron thermal-state and CPU-speed-limit stages, their normalization, producer gating and sampling behavior, and the current thermal-state wire mapping.
  • observed — Modified behavior in packages/electron/src/launch-main.test.ts: Updated the power-monitor-only test to expect power trace producers, including process-memory, thermal_state, and cpu_speed_limit, and to exclude app-metrics and display producers; the prior expectation that no producer list was built was removed.
  • observed — Modified behavior in packages/electron/src/launch-main.test.ts: Added a test asserting that when a legacy systemMetricsSampler and only a powerMonitor are supplied, systemTraceProducers remains undefined.
  • observed — Modified behavior in packages/electron/src/launch-main.ts: The powerMonitor documentation now lists thermal_state and cpu_speed_limit as system traces, with their platform conditions.

Reliability and maintainability

  • inferred — Risk-relevant change factors for packages/trackers: blast_radius_2; direct_dependents_2
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: adding thermal-state and CPU speed-limit traces from Electron powerMonitor.
Description check Passed The description directly explains the tracker stages, trace producers, wire mapping, tests, and verification limits for the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 6 functions across 10 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Usage-based review receipt

  • Mode: Continue automatically
  • Reviewed files: 2
  • Waived: $0.50 (charged $0.00)
  • View usage details

Note

This review exceeded your plan’s limits and used usage-based reviews—free during trial, billed after paid activation unless disabled. Manage usage-based reviews.

Comment @coderabbitai help to get the list of available commands.

Comment on lines +63 to +74
const thermalOf = (detail: unknown): { state: ElectronThermalState } => ({
state: normaliseThermal((detail as { state?: unknown } | null | undefined)?.state),
});

const speedLimitOf = (detail: unknown): { limit: number } | undefined => {
const limit = (detail as { limit?: unknown } | null | undefined)?.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;
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P2 Medium

Problem: thermalOf and speedLimitOf read detail.state / detail.limit from the first listener argument only. If real Electron passes the value directly (listener(state) or listener(limit)) instead of a details object, both normalisers fail silently.

Impact: Every thermal-state-change becomes {state: 'unknown'}, which the producer drops. Every speed-limit-change becomes undefined and is dropped. Only the one-off baseline read of thermal_state at start would ever be written, and cpu_speed_limit would never be written. There is no error and nothing is reported.

Scenario: I could not verify the event's argument shape. There is no Electron typings package in the repo, and the PR says this was not run against a real Electron. The unit tests and the integration test all emit {state} / {limit} objects, so they would pass either way. The existing Emitter.emit helper in the integration test passes {} as the first argument, so the repo's own helpers are not a reliable guide here.

Fix: Accept both shapes, so the code is right whichever one Electron uses:

const field = (detail: unknown, key: 'state' | 'limit'): unknown =>
  typeof detail === 'object' && detail !== null ? (detail as Record<string, unknown>)[key] : detail;

Use field(detail, 'state') in thermalOf and field(detail, 'limit') in speedLimitOf, and add tests that fire the bare primitive. Alternatively, confirm the shape on a real macOS Electron before merging.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f9686b9. thermalOf and speedLimitOf now read the value from a details object ({state} / {limit}) or from a bare first argument (listener('fair'), listener(80)), so they are right whichever form Electron uses; anything else still normalises to unknown / is dropped. Tests cover both shapes (object, bare, garbage, null, undefined) and the mutator loop on detailValue killed all four mutations. The real event shape is still unverified on a real Electron (stated in the PR body).

Comment on lines +183 to +201
class ThermalStateProducer extends TraceProducerBase {
readonly name = 'thermal_state';
#off: (() => void) | undefined;
constructor(private readonly tracker: ElectronPowerTracker) {
super();
}
#publish(state: Parameters<typeof thermalStateWire>[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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Severity: P3 Low

Problem: thermal_state writes nothing for unknown. A real transition from a known state to unknown, for example serious to unknown, therefore leaves the previous value (2) as the last sample.

Impact: The trace is "sampled, never held" by the spec, but a viewer that draws the last point of a series would show the device as still serious after the OS stopped reporting.

Scenario: The state goes serious, then a thermal-state-change with an unrecognised state arrives, which normaliseThermal turns into unknown. Nothing is written and no later sample corrects the series.

Fix: This is mostly a spec question, since "omit, never zero" is deliberate. If it is intended, add a one-line note to the producer comment that a transition to unknown leaves the prior value as the last sample. The bare-primitive concern on power-tracker.ts:63 matters more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed it is intended (spec: sampled, never held, omit never zero). Documented in the producer comment in f9686b9: a transition from a known state to unknown leaves the previous value as the last sample. Left as is; flagging it for the owner alongside the #288 question.

…e the unknown-state gap (C13 review)

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Claude finished @krassx's task in 18s —— View job


Re-review of PR #125 after f9686b9

I re-read the new commit f9686b9a and its surrounding code. I did not run the test suite or any tools, and I pushed nothing. I have no new findings.

Earlier findings are addressed

  1. P2, event argument shape. detailValue in packages/trackers/src/electron/power-tracker.ts now reads {state} / {limit} from an object and uses a bare first argument as the value itself. thermalOf and speedLimitOf both use it, and anything unrecognised still becomes unknown or is dropped. The new tests fire the bare forms 'serious', 'bogus', 75, 'fast' and 250 and assert the output. One edge case is harmless: an object without the key reads as undefined, which gives unknown or a drop. The thermal state check is an exact string match against the four known values (THERMAL_STATES, line 37).
  2. P3, unknown leaves the old value as the last sample. The producer comment in packages/electron/src/system-traces.ts now documents it, so I treat it as resolved.

Still open (not a code defect)

  • The real shape of the two Electron events, and getCurrentThermalState() on real macOS, are still unverified. The bare-value support makes the code correct for either argument shape. The one-off baseline read at start is the only unverified runtime behaviour.
  • The thermal state value form (bugsee-cocoa#288) is an owner decision. It stays confined to thermal-state-wire.ts.

Summary

  1. Overall risk: Low.
  2. Merge recommendation: Merge once the usual CI checks pass. A smoke test on a real macOS Electron would still be useful, but it no longer blocks.
  3. Most important issues to fix: None.
  4. Positives:
    • The fix covers both argument shapes and has tests for each.
    • There is a single wire table for thermal_state.
    • Test-first approach with a mutator loop on the new normalisers.
    • The PR is honest about what was not verified.

@krassx
krassx merged commit 9462174 into main Oct 27, 2026
8 checks passed
@krassx
krassx deleted the feat/electron-power-traces branch October 27, 2026 14:04
krassx added a commit that referenced this pull request Oct 27, 2026
…SPEED_LIMIT

#125 landed the two Electron power traces with literals; the broadened scan caught them. They are
now registered (int, not held; cpu_speed_limit in percent) and out of NOT_YET.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
krassx added a commit that referenced this pull request Oct 27, 2026
…registry (C17, C24) (#131)

* test(protocol,instrumentation-tests): spec-conformance guard and a single system wire-name registry (C17, C24)

- @bugsee/protocol: TraceName / EventName registry with TRACE_SPEC (type, unit, held) and
  EVENT_PARAMS; every trace/event producer (browser, node, electron, capture, host-owned
  trace lists in browser/webview/electron renderer) now references it. TraceProducerBase.emit
  takes a TraceName; the electron power_${state} concatenation is a lookup over registered events.
- Vendored snapshot of the JavaScript platform spec's tables (with the bugsee/specs commit) at
  packages/protocol/spec; pnpm spec:refresh / spec:check read it from a specs checkout by git ref.
- spec-drift test: registry vs snapshot (names, type, unit, held, params), NOT_YET list with
  reasons, held style of every emit call, and an AST scan that fails on a wire name spelled as a
  literal in producer code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(protocol): make the wire-name registry string enums so the WebView bundle inlines it

A const object of ~90 names stays whole in the IIFE (every runtime's names, ~2 KB gzip) and
pushed the bundle over its 64 KB budget. As string enums esbuild inlines every use and the
registry disappears (191585 raw / 64310 gzip, identical to main); the type is stricter too.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix(spec-snapshot): atomic snapshot write, one params list per event, declare typescript (review feedback)

- refresh writes through a temporary file renamed over the snapshot
- event params: drop the unread per-family copy; a key optional in any family is one optional key
- instrumentation-tests declares its typescript devDependency

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* test(spec-drift): scan every product file, type event names, fix EVENT_PARAMS, fail-closed parser (review F1-F6)

- F1: the scan covers every packages/*/src file but protocol (found by location, not by keyword); the
  disk-pressure capture probe is built from TraceName.CAPTURE; a reasoned NOT_A_WIRE_NAME list that
  fails when stale.
- F2: flags + / join / shared-suffix template assembly, quoted names inside strings, computed
  TraceName[key], and every spec name (pending ones included). SystemEvent.name and the electron #send are
  typed EventName.
- F3: EVENT_PARAMS expands "the same keys, plus ...", marks omitted / no-params-at-all / one-runtime keys
  optional; eventParamProblems() checks real emitted events in the browser, node and electron source tests.
- F4: the parser throws on a renamed column, an inexact held cell, an unnamed or wildcard row, a typeless
  value, an unknown unit, a cell-count mismatch and families that disagree; indented tables are read.
- F5: refresh --specs/--ref/--out need a value, the temp file is removed when the write fails.
- F6: the spec tooling runs under a coverage gate; NOT_YET names the spec item and the tracking issue/PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* test(spec-drift): merge main (#125) and register THERMAL_STATE / CPU_SPEED_LIMIT

#125 landed the two Electron power traces with literals; the broadened scan caught them. They are
now registered (int, not held; cpu_speed_limit in percent) and out of NOT_YET.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* test(spec-drift): pin exemptions to exact strings, type TraceSink, key the turbo cache, fail-closed parser (review round 2)

- NOT_A_WIRE_NAME entries list the exact strings and counts they excuse; an appended leak, an extra or a
  vanished occurrence fails. this.emit('stage') in packages/trackers/src is exempt structurally.
- TraceSink.emit takes a TraceName (type test); PROGRESS states exactly what the compiler covers.
- instrumentation-tests test:unit hashes packages/*/src, the snapshot and scripts/spec-snapshot.
- parser: throws on a table under an unrecognised ### heading in an inventory, a numeric value followed
  by a bare unit word, and a held claim in the held-less Node table.
- tests for quoted-name boundaries, '%' units, the same-keys reset; EXPECTED_EVENTS of the three
  system-events tests must cover every registered event.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
krassx added a commit that referenced this pull request Oct 28, 2026
…, rounding test, comments) (#136)

* docs(electron),test(trackers): thermal/cpu-speed-limit README, rounding boundary test, stale comments

Follow-up to #125: README lists thermal_state/cpu_speed_limit and the details-object listener shape (no getCurrentCPUSpeedLimit in Electron); pin Math.round at 62.5/99.6/99.4 boundaries (floor/ceil mutants killed); relaunch comment lists the new traces; reword the subscribe-first comment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* docs(electron): note the systemMetricsSampler exception for the power traces

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

javascript Pull requests that update javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant