Skip to content

Energy Mode control in the popover - #27

Merged
EClinick merged 8 commits into
masterfrom
energy-mode
Aug 12, 2026
Merged

EClinick merged 8 commits into
masterfrom
energy-mode

Conversation

@EClinick

Copy link
Copy Markdown
Owner

What

Adds an Energy Mode (Low Power / Automatic / High Power) control to the popover so users can drop Apple's battery menu extra entirely, plus a redesign of the popover's top zone.

  • XPC protocol v4 with setPowerMode - the helper's first mutating operation. The helper validates mode and scope against whitelists, invokes /usr/bin/pmset with argv arrays (no shell), and replies with the state it reads back after the write, so a switch is never reported as applied unless it actually stuck. New error codes unsupportedPowerMode and powerSettingFailed; helper version 1.3.0.
  • Reads are unprivileged: the app parses pmset -g custom itself (shared PowerModeParser handles both the modern per-source powermode key and the legacy lowpowermode key). Only writes go through the root helper, so switching modes never prompts for a password.
  • New top zone: the three text rows and two dividers become a mode-tinted ring charge gauge (percent inside, charging bolt badge) beside the time-remaining headline and a combined draw/health/cycles caption. The Energy Mode control docks on the gauge ring as a badge; tapping it fans all modes out around the badge in a uniform-radius arc, with the active mode accent-filled. A caption names the active mode and the other power source's setting when they differ.
  • Capability aware: High Power hides on machines that don't support it (legacy lowpowermode machines, plus a cached flag when a High Power write is refused by hardware). Desktops without a battery get no control at all.
  • Degrades gracefully: against an installed v3 helper the control renders disabled with an update hint; scope is always the currently active power source.

Why

Switching energy modes previously required System Settings or Apple's battery menu extra. Juice already ships a root helper over XPC with client code-sign pinning, so the privileged write fits the existing security model; the read path needs no privileges at all.

Verification

  • 402 tests in 48 suites pass via make test, including new suites for the pmset parser, the root-side writer (via an injectable command seam - validation, scope flags, legacy-key handling, read-back mismatch), the app-side controller state machine, and popover layout/geometry (badge and fan clearances, pixel test for badge presence by state).
  • Exercised end to end on a Mac17,8: built Juice Dev.app, installed to /Applications, verified gauge tint, fan interaction, per-source footnote, and the helper-outdated path against the previous helper.
  • JuiceXPCProbe gained a set-powermode op for manual testing of the new XPC surface.

…op zone

The helper gains its first mutating operation (protocol v4): setPowerMode validates mode/scope whitelists, writes via pmset with argv arrays, and replies with the state read back after the write. The popover top zone is redesigned as a ring gauge tinted by the active mode plus three Control Center style mode buttons; reads are unprivileged pmset parses, writes go through the root helper.

Claude-Session: https://claude.ai/code/session_018mkxULoejU6mi9V73xmFG2
The Energy Mode control becomes a 22 pt badge seated on the gauge ring at bottom-trailing; tapping it fans the other modes out around the ring (staggered scale/blur entrance, reduce-motion aware). The footnote now always names the active mode since the labeled buttons are gone. Revert this commit to restore the three-button row.

Claude-Session: https://claude.ai/code/session_018mkxULoejU6mi9V73xmFG2
The fan now shows every available mode with the active one accent-filled, arcing from the badge's trailing side down past vertical (25-95 degrees) so nothing floats over the headline; re-picking the active mode dismisses without a write.

Claude-Session: https://claude.ai/code/session_018mkxULoejU6mi9V73xmFG2
Fan buttons were positioned on a circle around the gauge, leaving uneven 2-17 pt edge gaps from the badge; they now sit on a 30 pt circle around the badge itself so the open fan's padding reads uniform.

Claude-Session: https://claude.ai/code/session_018mkxULoejU6mi9V73xmFG2
Copilot AI lite review requested due to automatic review settings August 10, 2026 16:17
@vercel

vercel Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
website Ignored Ignored Preview Aug 12, 2026 1:56pm

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d373e6f020

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread Sources/JuiceXPCShared/PowerMode.swift Outdated
Comment on lines +104 to +105
let key = String(fields[0])
guard key == "powermode" || key == "lowpowermode" else { continue }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Parse the separate highpowermode setting

On supported High Power Macs whose pmset -g custom output uses separate lowpowermode and highpowermode booleans, such as earlier M1/M2 Max models, this guard ignores highpowermode and classifies the machine as legacy. Consequently an active High Power setting is reported as Automatic, and showsHighPower permanently removes the mode from the picker. The pmset(1) SETTINGS documentation defines highpowermode separately as an enable/disable 0/1 setting, so the parser needs to combine both legacy boolean keys instead of treating every lowpowermode host as incapable of High Power.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 625ddf0. PowerModeState now models the key layout explicitly (unified / dualBoolean / lowPowerOnly): the parser combines the two booleans per section (powermode takes precedence when present; highpowermode=1 wins over lowpowermode=1 as the more specific enabled state), so dual-boolean Macs report High Power correctly and keep the option visible. The helper's writer derives a per-layout plan - dual-boolean machines get both keys written with the clearing key first, inside the same bounded transaction - and lowpowermode-only machines still refuse High Power before writing anything.

Comment on lines +109 to +110
let refusedHighPower = mode == .highPower
&& (code == .unsupportedPowerMode || code == .powerSettingFailed)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Do not permanently cache generic write failures

When a High Power request encounters any .powerSettingFailed, including a transient nonzero pmset exit or a read-back race with another settings change, this marks High Power unsupported in persistent defaults. On a supported Mac, one temporary failure therefore hides the option across every future launch with no recovery path except manually clearing defaults; only a failure that specifically establishes hardware incompatibility should be persisted.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in ee3084d and c04dafe: only an accepted-then-dropped High Power write (helper read-back unchanged from the pre-write state, error code unsupportedPowerMode) is cached; a non-zero pmset exit or a read-back that moved to a different value is classified powerSettingFailed and surfaces as a transient, retryable error with nothing persisted. c04dafe additionally makes the cache self-healing: any later read or write that observes High Power actually set clears it.

Comment on lines +210 to +214
@Test("Reads the live machine's state through the real pmset")
func readsRealState() throws {
// pmset -g custom needs no privilege, so this must work in CI.
let state = try PowerModeWriter().readState()
#expect([PowerMode.automatic, .lowPower, .highPower].contains(state.battery))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Skip the live pmset test on battery-less hosts

On a Mac mini or other desktop, pmset -g custom has no Battery Power: section, while PowerModeParser.parse requires both battery and AC sections. This unconditional test therefore throws on hardware the project explicitly supports, causing make test—and consequently the guarded release publisher—to fail whenever it runs on a desktop Mac. Use fixture output here or skip the assertion when the host has no battery section.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in ee3084d: the parser now accepts single-section output (the missing source mirrors the present one and hasBatterySource records the difference), so pmset -g custom parses on battery-less Macs and this live test passes there. A present-but-keyless known section still throws.

…e machine

Helper: pmset transactions are serialized process-wide and bounded by a 10s deadline (shared BoundedProcess drains both pipes concurrently and reaps stalled commands). A High Power write that exits 0 but reads back unchanged now throws unsupportedPowerMode - only that gets cached as hardware refusal, so transient failures no longer permanently hide the option. Parser: a machine reporting only one power-source section mirrors it instead of failing (AC-only desktops), unknown sections are ignored rather than misattributed, and powermode beats lowpowermode deterministically. Controller: a stale in-flight refresh can no longer clobber a newer write, writes target the power source that is live at write time, reads are deadline-bounded, and the outdated-helper notice clears when the helper registration becomes ready. Popover: Refresh and power-source changes now re-read Energy Mode.
Round-2 review fixes: pipe draining now respects the process deadline even when a descendant holds the write ends open; helper transactions share one 10s budget including a bounded 2s lock wait; external pmset writes during a transaction are no longer misclassified as hardware refusal; a present-but-keyless pmset section is an error instead of silently mirroring the other source; no-op mode selection is decided against the live power source in the controller; failed writes invalidate older in-flight refreshes; the popover re-reads Energy Mode on each battery reading so external Automatic/High Power changes surface while open; the probe's local pmset read is bounded; the stale-refresh test synchronizes with an explicit handshake.
…d High Power cache

An exhausted transaction budget now throws before each spawn instead of launching the write with a zero deadline, so the machine can never change after the client already reported failure. The controller clears the cached High Power refusal whenever a read or write observes High Power actually set - an external pmset write racing the helper's read-back can poison that cache on a supported machine, and observed reality outranks the heuristic.
Earlier M1/M2 Max Macs expose separate lowpowermode and highpowermode booleans instead of the tri-state powermode key; the parser treated any lowpowermode host as incapable of High Power, misreading an active High Power as Automatic and hiding the option. PowerModeState now carries an explicit key layout (unified, dualBoolean, lowPowerOnly), the parser combines the booleans with powermode taking precedence, and the writer derives a per-layout write plan - dual-boolean machines get both keys written, clearing key first, within the same transaction budget. Old JSON payloads still decode via the legacy boolean.
@EClinick
EClinick merged commit 0b383cc into master Aug 12, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants