diff --git a/.agents/skills/verify-gbat/SKILL.md b/.agents/skills/verify-gbat/SKILL.md
index 92fe03e..a906b61 100644
--- a/.agents/skills/verify-gbat/SKILL.md
+++ b/.agents/skills/verify-gbat/SKILL.md
@@ -1,25 +1,21 @@
---
name: verify-gbat
-description: Verify gbat's real macOS/Linux battery CLI and macOS Raycast script with isolated PTY runs, version checks, hardware-aware feature journeys, and retained command evidence. Use after changing CLI output, HID behavior, or Raycast integration.
+description: Verify gbat's real macOS/Linux battery CLI and macOS Raycast script with isolated PTY runs and retained evidence. Use after changing CLI output, HID behavior, or Raycast integration.
---
# Verify gbat
-Read [the feature map](features/README.md), then the relevant journey. The primary
-surface is a one-shot Rust CLI; the secondary surface is the macOS Raycast Script
-Command `Logitech Mouse Battery`. No service, port, login, database, migrations,
-or seed data is involved. An empty working directory is sufficient for version
-checks; successful battery reads require a real awake Logitech mouse.
+Choose the journey that covers the change:
-## Launch
+- [Version identity](features/version.md) covers the checkout and installed executables.
+- [Battery and charging](features/battery.md) covers receiver, direct USB, and charging state.
+- [Failure and recovery](features/failure-recovery.md) covers absent devices, offline mice, Linux permissions, and recovery.
+- [Raycast integration](features/raycast.md) covers binary selection, missing executables, and the native Script Command.
-Run from this checkout using Rust/rustup (the version is pinned in
-`rust-toolchain.toml`) and `uv`. The helper uses Python 3.12, provisioned by `uv`
-if necessary; Python is a verification dependency, not an app dependency.
-On Linux the native hidraw backend needs a C compiler/linker, not `libudev-dev`
-or `libusb`. Build as your regular user.
+## Launch
-Keep these variables in one shell across launch, doctor, drive, and cleanup:
+Build as the regular user with the pinned Rust toolchain. The [PTY helper](scripts/capture.py)
+uses Python 3.12 through `uv`. Keep these variables in one shell:
```sh
REPO="$(git rev-parse --show-toplevel)"
@@ -30,28 +26,13 @@ HARNESS="$REPO/.agents/skills/verify-gbat/scripts/capture.py"
mkdir -p "$REPO/target/verification-evidence"
EVIDENCE="$(mktemp -d "$REPO/target/verification-evidence/run.XXXXXX")"
SCRATCH="$(mktemp -d "${TMPDIR:-/tmp}/gbat-verify.XXXXXX")"
-printf 'Evidence: %s\nScratch: %s\n' "$EVIDENCE" "$SCRATCH"
trap 'rmdir -- "$SCRATCH"' EXIT
```
-The build must succeed before driving. A successful doctor below establishes
-CLI readiness and the manifest version. It does not establish hardware
-readiness. There is no persistent app process: start each action with the helper
-in its own PTY, which exits and is reaped before the next action. Teardown is
-the Cleanup section; run it after failures too.
-
-Hardware queries cannot be isolated by working directory: interfaces are shared,
-requests use one software ID, and input reports are flushed. Never run two
-battery queries concurrently against the same receiver, including Raycast
-refreshes or another agent's run. If another driver is active, defer the query;
-do not kill or commandeer it. Version-only runs can coexist. There is no device
-selector: multiple Logitech devices can make the reading belong to another
-device. Establish the intended device/connection before claiming GPW2 proof.
-
## Doctor
-This is the read-only instance check. It invokes the exact local binary without
-opening HID, requires the version in `Cargo.toml`, and records its SHA-256:
+After a successful build, verify the exact executable against the manifest.
+Only `--version` as the first CLI argument skips HID initialization.
```sh
uv run --no-project --python 3.12 "$HARNESS" \
@@ -59,121 +40,55 @@ uv run --no-project --python 3.12 "$HARNESS" \
--feature version-local --expect version -- "$BINARY" --version
```
-Require helper exit `0`, `result.json` `passed: true`, exact version stdout,
-and empty stderr. The helper records a binary hash on every action: compare it
-with the doctor hash to detect a build replaced during verification. Version
-alone cannot establish freshness, so always build this checkout first. If
-anything looks off, repeat this check in a new evidence directory, retaining
-the failed attempt. On Linux this command needs no `sudo`.
+Require helper exit `0` and `passed: true` in `result.json`. Compare the binary
+SHA-256 in subsequent actions with the doctor's hash for the same executable.
## Drive
-The executable [PTY helper](scripts/capture.py) accepts exact commands after
-`--`; it never runs them through a shell. Every invocation requires a new
-evidence subdirectory and an existing, disposable scratch directory. Stdout and
-stdin use a private controlling PTY; stderr is redirected to its own proof file
-so channel assertions remain possible. It supplies no interactive input. The
-default deadline is 30 seconds, not the internal six-second discovery budget;
-use `--timeout 60` only for a justified slow host.
-
-For a real battery read on macOS:
-
-```sh
-uv run --no-project --python 3.12 "$HARNESS" \
- --evidence "$EVIDENCE/battery-terminal" --cwd "$SCRATCH" --binary "$BINARY" \
- --feature battery-terminal --expect battery -- "$BINARY"
-```
-
-For the corresponding Linux action, use `-- sudo -n "$BINARY"` instead.
-Build first as a regular user. If `sudo -n` needs authentication, use the
-environment's secret-delivery mechanism; do not put passwords into commands,
-artifacts, or this skill. A sudo error is a failed prerequisite, not a gbat
-failure-path pass. Do not change udev rules or device permissions for a run.
-
-Follow the map for charging, offline/recovery, and Raycast actions. A missing
-mouse or required charging state is a failed journey with its unmet precondition,
-not a successful substitute. Only the first CLI argument exactly equal to
-`--version` avoids HID. There is no `--help`, dry-run, or device-list mode;
-unknown arguments execute a battery query. The Raycast script does not forward
-arguments, so `mouse-battery.sh --version` also queries hardware.
+Run each relevant journey with a fresh evidence subdirectory per action. The
+helper launches the argv after `--` in a private PTY, captures stderr separately,
+and enforces a 30-second deadline by default. To inspect all options, run
+`uv run --no-project --python 3.12 "$HARNESS" --help`.
+
+For successful battery queries, identify the intended awake GPW2 and connection.
+The CLI can select any responding Logitech device. Serialize queries on the same
+receiver, including Raycast refreshes. They send HID++ requests using a shared
+software ID and flush input reports. On Linux, use `-- sudo -n "$BINARY"` in
+battery examples when elevated device access is needed. Handle authentication
+outside the capture. Keep device permissions unchanged.
+
+`--expect battery` checks the percentage and allows an optional charging suffix.
+Check the suffix against the observed charging state. `--expect error` checks a
+family of CLI errors. Inspect stderr for the specific failure in the selected
+journey. Record unavailable hardware or permissions as unmet preconditions.
+Native Raycast verification requires the visible Script Command invocation and
+result. The terminal wrapper ignores arguments, including `--version`.
## Evidence
-Keep proof in `$REPO/target/verification-evidence/run.XXXXXX`, outside scratch.
-`target/` is already ignored by Git. Copy evidence elsewhere before `cargo clean`
-or deleting the checkout. Each action contains:
-
-- `action.json`: feature/entry-point ID, exact argv, working directory, UTC time,
- platform, binary path/hash, manifest version, expected behavior, scratch before.
-- `terminal.bin` and `events.jsonl`: raw stdout PTY bytes and timed output chunks.
-- `stdout.txt` and `stderr.txt`: stdout with terminal CRLF normalized to LF and
- separately captured stderr.
-- `result.json`: actual app exit code, timeout/interruption/capture error,
- assertion result, scratch after,
- and whether scratch files stayed unchanged. Helper exit `0` means all its
- checks passed; app exit code is recorded separately.
-
-Record connection mode, intended device identity, wake/charging conditions,
-manual actions, and feature outcomes in `$EVIDENCE/notes.md`. Capture the action
-and resulting state through the real user entry point. For hardware queries,
-compare charging suffix with independently observed cable/charging conditions;
-do not require an exact historical battery percentage. A command that merely
-prints a plausible battery line cannot prove device identity or charging state.
-
-Observe relevant side effects alongside output: the helper compares scratch
-file contents; it does not audit the whole filesystem or network. gbat has no
-documented state files, network calls, or browser launches, but battery queries
-send real HID++ writes before reading replies. Do not call them pure device
-reads. `--version` returns before HID initialization. No mock battery provider,
-replacement executable, or internal test setter proves real hardware behavior.
-Existing protocol tests are useful supplementary checks, not CLI/hardware proof.
-
-For Raycast UI proof, retain the actual invocation and visible compact result
-using available native-app capture tooling; terminal execution of its script is
-a separate path. Do not reuse the historical README GIF/WebP as fresh evidence.
-Do not run `docs/record-demo.sh` for routine verification: it replaces
-`assets/demo.gif`.
-
-## Cleanup
+Keep evidence under the ignored `target/verification-evidence/` directory.
+Use a new directory for retries so earlier outcomes remain available.
-The helper waits for its child and closes its PTY. On timeout, SIGINT, or SIGTERM
-it kills only the process group it created and reaps the child. Never kill by
-process name. No server remains to stop. Close only UI windows opened by the
-run and restore any device state changed specifically for a journey.
+- `action.json` records argv, working directory, timestamp, platform, binary path
+ and hash, manifest version, expectation, and the initial scratch snapshot.
+- `terminal.bin` and `events.jsonl` hold raw PTY output and timed chunks.
+ `stdout.txt` normalizes terminal CRLF to LF. `stderr.txt` captures stderr.
+- `result.json` records the child exit code, timeout, interruption, capture
+ errors, assertion, and final scratch snapshot. A pass requires the expected
+ exit and output, a completed capture, and unchanged scratch entries.
+- Record the device identity, connection, wake/charging conditions, manual
+ actions, and feature outcomes in `$EVIDENCE/notes.md`.
-After every attempt, including a failed one, remove only that run's scratch:
-
-```sh
-rmdir -- "$SCRATCH"
-trap - EXIT
-test ! -e "$SCRATCH"
-test -s "$EVIDENCE/doctor/action.json"
-test -s "$EVIDENCE/doctor/result.json"
-test -s "$EVIDENCE/doctor/stdout.txt"
-printf 'Retained proof: %s\n' "$EVIDENCE"
-```
-
-Also confirm the driven feature's `action.json`, `result.json`, stdout/stderr,
-and terminal evidence survive. Never remove `$EVIDENCE` in cleanup. For a failed
-build before scratch exists, no instance was launched and there is nothing to
-terminate. Scratch should be empty: if `rmdir` fails, inspect it and remove only
-the run-created files before retrying; do not recursively delete an uninspected
-path. Do not erase failed evidence when retrying. SIGKILL or machine termination
-cannot be handled; such runs may retain partial evidence and need inspection.
-
-## Helpers
+## Cleanup
-All invocations above run `scripts/capture.py` through `uv`; it is also directly
-executable. Inspect its options without touching HID with:
+The helper reaps its child when it exits. After successes and failures, restore
+device state changed for the journey, close windows opened for the run, and
+remove the empty scratch directory:
```sh
-uv run --no-project --python 3.12 "$HARNESS" --help
+rmdir -- "$SCRATCH" && trap - EXIT
```
-`--expect version` requires the current manifest version; `battery` requires one
-valid `Battery: N%` line with an optional charging suffix; `error` requires app
-exit `1`, empty stdout, and a known gbat error prefix; `missing-binary` requires
-the Raycast wrapper's exact missing-executable message. Every expectation also
-requires no timeout and unchanged scratch file contents. `error` recognizes a
-family of failures: read stderr to assert the specific scenario in the map.
-The helper cannot certify hardware setup or native Raycast UI behavior.
+If scratch contains unexpected entries, inspect them against the captured
+snapshot before removal. Retain the action and result files, including failed
+runs. Copy evidence elsewhere before cleaning the Cargo target directory.
diff --git a/.agents/skills/verify-gbat/features/README.md b/.agents/skills/verify-gbat/features/README.md
deleted file mode 100644
index fc74360..0000000
--- a/.agents/skills/verify-gbat/features/README.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# gbat verification map
-
-This is the maintained map of gbat's user-facing behavior. Read the matching
-feature file before driving it. Every listed entry point needs its own outcome;
-a terminal script run does not cover the native Raycast entry point.
-
-## Baseline preconditions
-
-- Follow Launch and Doctor in [the skill](../SKILL.md) from a fresh scratch dir.
-- Use the absolute release binary built from this checkout with `--locked`.
-- Keep `$REPO`, `$BINARY`, `$HARNESS`, `$EVIDENCE`, and `$SCRATCH` in the shell.
-- Use macOS or Linux. Raycast and its zsh script are macOS-only product paths.
-- For battery journeys, connect a real awake GPW2 via LIGHTSPEED or USB, identify
- the device, and ensure no competing query is using its shared HID interface.
-- No fixture can seed hardware state. Missing connection, charging state,
- permission, or Raycast installation fails the dependent journey; record the
- reason and retain the attempt rather than substituting canned output.
-
-## Driving conventions
-
-- Use `capture.py` with a unique evidence subdirectory per action, serially.
-- Commands in features assume the Launch variables. On Linux only, replace
- battery `-- "$BINARY"` with `-- sudo -n "$BINARY"` after arranging access.
-- Match one stdout battery line and exit status, never README percentages.
-- Restore physical states changed during testing; preserve evidence in `target/`.
-
-## Proof and coverage
-
-Each action needs argv, stdout, stderr, exit code, binary identity, and its
-result. For battery/charging record the real device preconditions and observed
-physical actions too. Native UI proof needs the actual UI invocation/result.
-The initial generated-skill smoke run may prove only one feature; name every
-unexercised journey as unverified. Successful unit tests do not fill those gaps.
-
-## Features
-
-- [Version identity](version.md): local CLI and installed CLI version reporting.
-- [Battery and charging](battery.md): receiver, direct USB, charging suffix.
-- [Failure and recovery](failure-recovery.md): offline, absent device,
- permissions, recovery through the same CLI path.
-- [Raycast integration](raycast.md): explicit binary, automatic discovery,
- missing executable, native Script Command.
diff --git a/.agents/skills/verify-gbat/features/raycast.md b/.agents/skills/verify-gbat/features/raycast.md
index 7730ac9..046bf42 100644
--- a/.agents/skills/verify-gbat/features/raycast.md
+++ b/.agents/skills/verify-gbat/features/raycast.md
@@ -31,18 +31,19 @@ Preconditions:
Require valid battery stdout, empty stderr and app exit `0`.
- **Automatic discovery entry.** Run
`uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-discovery" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-discovery --expect battery -- env -u GBAT_BINARY PATH="$REPO/target/release:$PATH" "$REPO/raycast/mouse-battery.sh"`.
- This proves the PATH entry with this checkout's build. Search order after PATH
- is `/opt/homebrew/bin/gbat`, `/usr/local/bin/gbat`, `$HOME/.local/bin/gbat`, then
- the repository's `target/release/gbat`. When modifying fallback discovery,
- exercise each affected location on an appropriately configured host; do not
- overwrite installed binaries or claim all fallbacks from the PATH case.
+ This exercises the PATH entry with this checkout's build. When modifying
+ fallback discovery, exercise each affected location in the
+ [documented order](../../../../README.md#raycast) on an appropriately
+ configured host. Preserve the user's installed binaries.
- **Missing configured executable.** Confirm `test ! -e "$SCRATCH/no-gbat"`.
Run
`uv run --no-project --python 3.12 "$HARNESS" --evidence "$EVIDENCE/raycast-missing" --cwd "$SCRATCH" --binary "$BINARY" --feature raycast-missing --expect missing-binary -- env GBAT_BINARY="$SCRATCH/no-gbat" "$REPO/raycast/mouse-battery.sh"`.
Require app exit `1`, empty stdout and exact stderr
`gbat binary not found. Build it with: cargo build --release` plus a newline.
- A bad explicit override must not fall back to an installed binary. This case
- requires no hardware and invokes the real script without a fake executable.
+ Repeat with `GBAT_BINARY="$SCRATCH"` and `raycast-directory` as the evidence
+ directory and feature. A searchable directory also has its execute bit set.
+ Both cases should reach the same missing-executable diagnostic even when
+ a working gbat is on PATH.
- **Native UI entry.** Using available native-app control, open Raycast, search
the exact command `Logitech Mouse Battery`, and execute it. Capture the action
and visible compact battery result in `$EVIDENCE/raycast-ui/`, with connection
@@ -58,5 +59,3 @@ Preconditions:
- The script ignores its arguments, including `--version`; it queries hardware.
- Invalid `GBAT_BINARY` takes precedence even when a working gbat is on PATH.
-- Linux CLI support does not imply Raycast support; Linux cannot prove this map.
-- The original Raycast WebP is historical evidence, not proof of the current build.
diff --git a/.agents/skills/verify-gbat/scripts/capture.py b/.agents/skills/verify-gbat/scripts/capture.py
index c50042d..9de59c3 100755
--- a/.agents/skills/verify-gbat/scripts/capture.py
+++ b/.agents/skills/verify-gbat/scripts/capture.py
@@ -1,18 +1,18 @@
#!/usr/bin/env -S uv run --no-project --python 3.12
"""Capture a short-lived real command in a private PTY and retain its proof."""
-from __future__ import annotations
-
import argparse
import errno
import hashlib
import json
+import math
import os
import platform
import pty
import re
import select
import signal
+import stat
import sys
import time
import tomllib
@@ -22,17 +22,22 @@
def digest(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
def snapshot(directory: Path) -> dict[str, str]:
- return {
- str(path.relative_to(directory)): (
- f"symlink:{os.readlink(path)}" if path.is_symlink() else digest(path)
- )
- for path in sorted(directory.rglob("*"))
- if path.is_symlink() or path.is_file()
- }
+ entries: dict[str, str] = {}
+ for path in sorted(directory.rglob("*")):
+ mode = path.lstat().st_mode
+ if stat.S_ISLNK(mode):
+ value = f"symlink:{os.readlink(path)}"
+ elif stat.S_ISREG(mode):
+ value = digest(path)
+ else:
+ value = stat.filemode(mode)[0]
+ entries[str(path.relative_to(directory))] = value
+ return entries
def write_json(path: Path, data: object) -> None:
@@ -135,12 +140,14 @@ def main() -> int:
command: list[str] = args.command
if command[:1] == ["--"]:
command = command[1:]
- if not command or args.timeout <= 0:
- parser.error("Provide a command after -- and a positive timeout")
+ if not command or not math.isfinite(args.timeout) or args.timeout <= 0:
+ parser.error("Provide a command after -- and a finite positive timeout")
cwd = args.cwd.resolve(strict=True)
binary = args.binary.resolve(strict=True)
evidence = args.evidence.resolve()
- if evidence == cwd or cwd in evidence.parents:
+ if not cwd.is_dir() or not binary.is_file():
+ parser.error("--cwd must be a directory and --binary must be a file")
+ if evidence.is_relative_to(cwd):
parser.error("Evidence must be outside the scratch working directory")
repo = Path(__file__).resolve().parents[4]
version = tomllib.loads((repo / "Cargo.toml").read_text())["package"]["version"]
@@ -212,13 +219,14 @@ def main() -> int:
)
)
)
- after = snapshot(cwd)
- passed = bool(
+ after = snapshot(cwd) if cwd.is_dir() and not cwd.is_symlink() else None
+ scratch_unchanged = before == after
+ passed = (
matched
and not timed_out
and not interrupted
- and not capture_error
- and before == after
+ and capture_error is None
+ and scratch_unchanged
)
result = {
"feature": args.feature,
@@ -226,8 +234,8 @@ def main() -> int:
"timed_out": timed_out,
"interrupted": interrupted,
"capture_error": capture_error,
- "expectation_matched": bool(matched),
- "scratch_unchanged": before == after,
+ "expectation_matched": matched,
+ "scratch_unchanged": scratch_unchanged,
"scratch_after": after,
"passed": passed,
}
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index fe45601..9366fdc 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,10 +1,10 @@
version: 2
+# Give new releases a week to age before opening routine update PRs.
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
- # Let new releases age before adopting them, so a compromised version is likely yanked first.
cooldown:
default-days: 7
groups:
@@ -17,7 +17,6 @@ updates:
directory: /
schedule:
interval: monthly
- # Let new releases age before adopting them, so a compromised version is likely yanked first.
cooldown:
default-days: 7
groups:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index cc5e01f..c03dee2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -48,9 +48,9 @@ jobs:
run: |
set -euo pipefail
cargo build --release --locked
- version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' Cargo.toml | head -n 1)"
- test -n "$version"
- test "$(./target/release/gbat --version)" = "gbat $version"
+ version="$(cargo metadata --locked --no-deps --format-version 1 | jq -er '.packages[] | select(.name == "gbat") | .version')"
+ reported_version="$(./target/release/gbat --version)"
+ test "$reported_version" = "gbat $version"
check:
name: Check
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 2c6a626..674e0a8 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -22,6 +22,7 @@ concurrency:
env:
CARGO_TERM_COLOR: always
MACOSX_DEPLOYMENT_TARGET: "11.0"
+ TARGET: aarch64-apple-darwin
jobs:
build:
@@ -30,18 +31,13 @@ jobs:
# macos-15 is arm64; release archives remain macOS-only. Linux is built from source.
runs-on: macos-15
timeout-minutes: 30
- env:
- TARGET: aarch64-apple-darwin
outputs:
- tag: ${{ steps.version.outputs.tag }}
version: ${{ steps.version.outputs.version }}
sha256: ${{ steps.package.outputs.sha256 }}
steps:
- name: Check out source
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- # No step here uses git, and cargo build scripts are third-party code
- # that would otherwise be able to read the token out of .git/config.
persist-credentials: false
- name: Require the tag to point at a commit on main
@@ -61,17 +57,11 @@ jobs:
id: version
run: |
set -euo pipefail
- version="$(sed -n 's/^version = "\([^"]*\)"/\1/p' Cargo.toml | head -n 1)"
- test -n "$version"
- tag=""
- if [[ "$GITHUB_EVENT_NAME" == "push" ]]; then
- tag="$GITHUB_REF_NAME"
- test "$tag" = "v$version" || {
- echo "Tag $tag does not match Cargo version $version" >&2
- exit 1
- }
+ version="$(cargo metadata --locked --no-deps --format-version 1 | jq -er '.packages[] | select(.name == "gbat") | .version')"
+ if [[ "$GITHUB_EVENT_NAME" == "push" && "$GITHUB_REF_NAME" != "v$version" ]]; then
+ echo "Tag $GITHUB_REF_NAME does not match Cargo version $version" >&2
+ exit 1
fi
- echo "tag=$tag" >> "$GITHUB_OUTPUT"
echo "version=$version" >> "$GITHUB_OUTPUT"
# No tests here: the tag must point at main, and every commit on main passed "Check".
@@ -92,7 +82,8 @@ jobs:
echo "Expected minimum macOS $MACOSX_DEPLOYMENT_TARGET, got $minos" >&2
exit 1
}
- test "$("$binary" --version)" = "gbat $VERSION"
+ reported_version="$("$binary" --version)"
+ test "$reported_version" = "gbat $VERSION"
package_dir="$RUNNER_TEMP/package"
mkdir -p "$package_dir" dist
@@ -126,12 +117,13 @@ jobs:
- name: Download release files
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
- pattern: release-*
+ name: release-${{ env.TARGET }}
path: dist
- merge-multiple: true
- name: Attest release archives
- uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
+ uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
+ env:
+ NODE_OPTIONS: --max-http-header-size=32768
with:
subject-path: dist/*.tar.gz
@@ -141,7 +133,7 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
- TAG: ${{ needs.build.outputs.tag }}
+ TAG: ${{ github.ref_name }}
run: gh release create "$TAG" dist/* --verify-tag --generate-notes --title "$TAG"
formula-test:
@@ -159,8 +151,7 @@ jobs:
contents: read
attestations: read
env:
- TAG: ${{ needs.build.outputs.tag || inputs.formula_tag }}
- VERSION: ${{ needs.build.outputs.version }}
+ TAG: ${{ inputs.formula_tag || github.ref_name }}
SHA256: ${{ needs.build.outputs.sha256 }}
steps:
- name: Verify published release for formula retest
@@ -173,21 +164,19 @@ jobs:
echo "Invalid release tag: $TAG" >&2
exit 1
}
- version="${TAG#v}"
- archive="gbat-$TAG-aarch64-apple-darwin.tar.gz"
+ archive="gbat-$TAG-$TARGET.tar.gz"
release_dir="$RUNNER_TEMP/published-release"
gh release download "$TAG" --repo "$GITHUB_REPOSITORY" \
--pattern "$archive" --pattern "$archive.sha256" --dir "$release_dir"
(cd "$release_dir" && shasum -a 256 -c "$archive.sha256")
gh attestation verify "$release_dir/$archive" --repo "$GITHUB_REPOSITORY" \
--source-ref "refs/tags/$TAG"
- echo "VERSION=$version" >> "$GITHUB_ENV"
echo "SHA256=$(shasum -a 256 "$release_dir/$archive" | awk '{ print $1 }')" >> "$GITHUB_ENV"
- name: Generate formula
run: |
set -euo pipefail
- archive="gbat-v$VERSION-aarch64-apple-darwin.tar.gz"
+ archive="gbat-$TAG-$TARGET.tar.gz"
cat > "$RUNNER_TEMP/gbat.rb" <
-This terminal demo shows real battery readings from `gbat 0.0.1`. It is a
-historical recording, so its version may differ from the current release.
-See [recording details](docs/recording.md) for its source and update instructions.
+The demo shows a real battery reading. See the [recording details](docs/recording.md)
+for the captured version and instructions for recording a new demo.
## Raycast
@@ -147,12 +146,6 @@ On Linux, use `sudo "$HOME/.local/bin/gbat"`; `sudo` may use a different `PATH`.
### Linux and sudo
-Use `sudo` for battery queries on Linux:
-
-```sh
-sudo ./target/release/gbat
-```
-
Linux exposes the receiver and mouse through `/dev/hidraw*`. These device nodes
are normally accessible only to root. Reading battery status requires opening
the appropriate node for both reading and writing: `gbat` sends a HID++ battery
@@ -191,21 +184,19 @@ xattr -dr com.apple.quarantine "$(brew --prefix gbat)"
## How it works
-`gbat` opens Logitech HID++ interfaces in shared mode on macOS and through hidraw
-on Linux. It checks receiver device
-indices `1` through `6` and the direct USB index `0xFF`, trying `1` and `0xFF`
-first. It uses the first interface and device index that reports a supported
-battery feature. It filters only by Logitech's vendor ID, so with several
-Logitech HID++ devices connected it may read another mouse, keyboard, or
-headset. There is no device selector.
-
-It reads `UNIFIED_BATTERY` at `0x1004` and falls back to `BATTERY_STATUS` at
-`0x1000` when the unified feature is unavailable, does not answer, or returns an
-incomplete response. Once a battery feature is found, HID access errors stop the
-read. During discovery, an interface that fails is skipped; its error is
-reported only if no other interface finds the mouse or reports it offline.
-If neither feature yields a battery status, the command reports an error
-instead of inventing a `0%` reading.
+`gbat` selects interfaces with Logitech's vendor ID and HID++ usage page
+`0xFF00`. It opens them in shared mode on macOS and through hidraw on Linux.
+It probes each interface at receiver index `1`, then at direct USB index
+`0xFF`, then at receiver indices `2` through `6`. The first device that
+reports a supported battery feature supplies the reading. There is no device
+selector, so the reading can come from another mouse, keyboard, or headset.
+
+During discovery, a silent `UNIFIED_BATTERY` (`0x1004`) lookup skips that
+interface and index. If the device answers that the feature is unsupported,
+`gbat` looks up `BATTERY_STATUS` (`0x1000`). It also tries the legacy feature
+when a discovered unified feature yields no usable status. A HID access error
+during a status read ends the query. Discovery errors are reported only if
+no candidate exposes a battery feature or reports the mouse offline.
## License
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 0aecd84..878d24f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -9,8 +9,7 @@
简体中文
-`gbat` reads Logitech G Pro Wireless 2 battery status on macOS and Linux, prints
-one line, and exits.
+`gbat` 在 macOS 和 Linux 上读取 Logitech G Pro Wireless 2 的电量和充电状态,输出一行结果后退出。
```text
Battery: 78%
@@ -21,18 +20,13 @@ Battery: 42% (charging)
## 系统要求
-- macOS 11 Big Sur or later, or Linux with hidraw and udev
+- macOS 11 Big Sur 及以上版本,或支持 hidraw 和 sysfs 的 Linux
- 通过 LIGHTSPEED 接收器或 USB 连接的 Logitech G Pro Wireless 2
- 运行 `gbat` 时鼠标处于唤醒状态
## 安装
-On Linux, build the CLI from source and
-[run battery queries with sudo](README.md#linux-and-sudo).
-Linux builds do not require `libudev-dev` or a separately installed HIDAPI library.
-Homebrew packages, release archives, and Raycast integration remain macOS-only.
-
-Homebrew 软件包和 GitHub Release 归档仅提供 Apple Silicon 的 `arm64` 可执行文件。
+Homebrew 软件包和 GitHub Release 归档仅提供适用于 Apple Silicon 的 macOS `arm64` 可执行文件。Linux 用户请[从源码构建](#从源码构建),并[使用 sudo 查询电量](#linux-设备权限)。Raycast 集成仅适用于 macOS。
使用 Homebrew 安装:
@@ -68,13 +62,7 @@ gbat
sudo /path/to/gbat
```
-Linux normally restricts `/dev/hidraw*` to root. Battery reads require read/write
-access to send a HID++ query and receive its reply. Run the binary with `sudo`
-for each battery query; `gbat --version` works without `sudo`. The CLI does not
-install udev rules or change device permissions. See
-[Linux and sudo](README.md#linux-and-sudo) for details.
-
-成功时,命令向 stdout 输出一行电池状态,退出码为 `0`。失败时,命令向 stderr 输出错误,退出码为 `1`。运行 `gbat --version` 可查看已安装的版本,不会访问鼠标。
+成功时,命令向 stdout 输出一行电池状态,退出码为 `0`。失败时,命令向 stderr 输出错误,退出码为 `1`。在两个平台上,普通用户都可以运行 `gbat --version` 查看版本,无需访问鼠标。
鼠标闲置后,读取可能需要等待无线模块唤醒。如果接收器报告鼠标离线,打开鼠标电源或移动鼠标后重试。
@@ -82,7 +70,7 @@ install udev rules or change device permissions. See
-这段终端演示使用 `gbat 0.0.1` 读取真实鼠标电量。录屏保留了当时的版本,可能与当前 Release 不同。源码版本和更新方法见[录屏说明](docs/recording.md)。
+这段终端演示读取了真实鼠标的电量。录制时的版本和更新方法见[录屏说明](docs/recording.md)。
## Raycast
@@ -127,7 +115,13 @@ cp target/release/gbat "$HOME/.local/bin/gbat"
确认 `$HOME/.local/bin` 已加入 `PATH`,即可在任意目录运行 `gbat`。
-On Linux, run `sudo "$HOME/.local/bin/gbat"`; `sudo` may use a different `PATH`.
+在 Linux 上可运行 `sudo "$HOME/.local/bin/gbat"`,因为 `sudo` 使用的 `PATH` 可能与当前 Shell 不同。
+
+### Linux 设备权限
+
+查询电量时,`gbat` 需要读写对应的 `/dev/hidraw*` 节点,才能发送 HID++ 请求并接收回复。这些节点通常只有 root 能够读写。请使用普通用户构建,在查询电量时运行 `sudo ./target/release/gbat`。`gbat` 不会安装 udev 规则、更改设备权限或配置免密 sudo。
+
+Linux 版本使用原生 hidraw 后端,无需 `libudev-dev`、`libusb` 或单独安装的 HIDAPI 库。构建 Rust 依赖仍需 C 编译器和链接器,在 Ubuntu 或 Debian 上可通过 `sudo apt install build-essential` 安装。
## 故障排查
@@ -136,8 +130,8 @@ On Linux, run `sudo "$HOME/.local/bin/gbat"`; `sudo` may use a different `PATH`.
| `No responsive Logitech HID++ interface found` | 连接接收器或 USB 线,唤醒鼠标后重试。 |
| `The receiver reports no connected mouse` | 鼠标已离线。打开鼠标电源或移动鼠标后重试。 |
| `Could not read battery level` | 鼠标可能在读取时离线,或返回了无法使用的电池响应。移动鼠标后重试。 |
-| HID access errors on macOS | Run `gbat` from Terminal and approve any macOS permission prompt. `sudo` is not normally required on macOS. |
-| `Permission denied (os error 13)` on Linux | Run `sudo /path/to/gbat`; see [Linux and sudo](README.md#linux-and-sudo). |
+| macOS 提示 `Could not initialize HID access` 或 `Could not read battery level: HID access failed` | 从 Terminal 运行一次 `gbat`,若系统弹出权限请求,请允许访问。macOS 通常无需使用 `sudo`。 |
+| Linux 提示 `Permission denied (os error 13)` | 运行 `sudo /path/to/gbat`,详见 [Linux 设备权限](#linux-设备权限)。 |
| Raycast 提示 `gbat binary not found` | 安装或构建 `gbat`,或在脚本中将 `GBAT_BINARY` 设为它的可执行文件路径。 |
| `Battery: 100%` 但没有 `(charging)` | 鼠标充满后可能停止主动充电,这是正常现象。 |
| macOS 阻止运行 | 打开 System Settings > Privacy & Security,为 `gbat` 选择 Open Anyway。 |
@@ -150,9 +144,9 @@ xattr -dr com.apple.quarantine "$(brew --prefix gbat)"
## 工作原理
-`gbat` 以共享模式打开 Logitech HID++ 接口。它会检查接收器的设备索引 `1` 到 `6` 和 USB 直连索引 `0xFF`,先尝试 `1` 和 `0xFF`,再使用首个报告支持电池功能的接口及设备索引。它只按 Logitech 厂商 ID 筛选,连接多个 Logitech HID++ 设备时,可能读到另一只鼠标、键盘或耳机,且无法指定设备。
+`gbat` 按 Logitech 厂商 ID 和 HID++ 用途页 `0xFF00` 筛选接口,在 macOS 上以共享模式打开,在 Linux 上通过 hidraw 访问。它先在各接口上探测接收器索引 `1`,再尝试 USB 直连索引 `0xFF`,最后依次探测接收器索引 `2` 到 `6`。它会读取首个报告支持电池功能的设备。命令不支持指定设备,连接多个 Logitech 设备时,读数可能来自另一只鼠标、键盘或耳机。
-它优先读取 `0x1004` 的 `UNIFIED_BATTERY`。该功能不可用、未响应或返回不完整响应时,会回退到 `0x1000` 的 `BATTERY_STATUS`。找到电池功能后,HID 访问错误会直接终止读取。探测阶段某个接口出错时会跳过它,只有其他接口都没找到鼠标、也没有报告离线时,才返回该错误。如果两个功能都未返回电池状态,命令会报错,不会将读取失败显示为 `0%`。
+探测时,如果查询 `UNIFIED_BATTERY`(`0x1004`)没有收到回复,`gbat` 会跳过当前接口和索引。如果设备回复不支持该功能,它会继续查找 `BATTERY_STATUS`(`0x1000`)。已找到的 `UNIFIED_BATTERY` 未能返回可用状态时,它也会尝试后者。读取电池状态时遇到 HID 访问错误会结束查询。只有所有候选设备都未报告支持电池功能、也未报告鼠标离线时,才会返回探测阶段的错误。
## 许可证
diff --git a/docs/record-demo.sh b/docs/record-demo.sh
index 3002c75..61fd6fd 100755
--- a/docs/record-demo.sh
+++ b/docs/record-demo.sh
@@ -2,7 +2,7 @@
# Record the current build and connected mouse without replaying sample output.
set -eu
-project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P)
+project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd -P)
cd "$project_root"
for dependency in cargo vhs ffmpeg; do
@@ -12,6 +12,7 @@ for dependency in cargo vhs ffmpeg; do
fi
done
+export CARGO_TARGET_DIR="$project_root/target"
cargo build --release --locked
binary="$project_root/target/release/gbat"
version=$("$binary" --version)
@@ -19,26 +20,15 @@ printf 'Recording %s\n' "$version"
# Fail before recording if the mouse cannot provide a real battery reading.
"$binary"
-work_dir=$(mktemp -d "$project_root/target/record-demo.XXXXXX")
+work_dir=$(mktemp -d target/record-demo.XXXXXX)
trap 'rm -r "$work_dir"' EXIT
trap 'exit 1' HUP INT TERM
candidate="$work_dir/demo.gif"
# Render to a temporary file so a failed recording keeps the published GIF.
-awk -v output="$candidate" '
- /^[[:space:]]*Output[[:space:]]/ {
- if (!replaced) {
- print "Output \"" output "\""
- replaced = 1
- }
- next
- }
- { print }
- END { if (!replaced) exit 1 }
-' demo.tape > "$work_dir/demo.tape"
-vhs "$work_dir/demo.tape"
+vhs --output "$candidate" demo.tape
test -s "$candidate"
ffmpeg -hide_banner -loglevel error -xerror -i "$candidate" -f null -
-cp "$candidate" "$project_root/assets/demo.gif"
+mv "$candidate" "$project_root/assets/demo.gif"
printf 'Recorded %s in %s\n' "$version" "$project_root/assets/demo.gif"
diff --git a/docs/recording.md b/docs/recording.md
index e198b11..2902029 100644
--- a/docs/recording.md
+++ b/docs/recording.md
@@ -1,24 +1,13 @@
# README recordings
-The terminal animation was captured on October 13, 2026, on macOS 27.0.1 with a
-connected Logitech mouse. Its battery readings are live output.
-The Raycast animation is the original GitHub asset and is kept unchanged.
-
-| Asset | Captured version | Source |
+| Asset | Capture | Visible output |
| --- | --- | --- |
-| [`demo.gif`](../assets/demo.gif) | `gbat 0.0.1` | Local release build of `0.0.1` |
-| [`raycast-demo.webp`](../assets/raycast-demo.webp) | Original capture; software versions not recorded | Original GitHub asset, retained unchanged |
-
-The terminal demo shows the binary's own `--version` output and `Battery: 61%`.
-A later terminal recording may show a different level or charging state.
-The original Raycast animation shows the `Logitech Mouse Battery` command and
-`Battery: 86%`. It demonstrates the workflow without identifying a gbat release.
-
-The logo is static artwork. It contains no software version.
+| [`demo.gif`](../assets/demo.gif) | Local release build on macOS 27.0.1, October 13, 2026, with a connected Logitech mouse | `gbat 0.0.1` and `Battery: 61%` |
+| [`raycast-demo.webp`](../assets/raycast-demo.webp) | Original GitHub asset. Software versions were not recorded. | `Logitech Mouse Battery` and `Battery: 86%` |
## Record the terminal demo
-Install Rust and the recording tools, connect the mouse, and keep it awake:
+On macOS, install Rust and the recording tools, connect the mouse, and keep it awake:
```sh
brew install vhs ffmpeg ttyd
@@ -30,30 +19,20 @@ The script builds with `--locked`, verifies a real battery read, and records
sets `GBAT_BINARY` to that same build, so all four commands use it. There is no
sample-output wrapper.
-The recorder renders to a temporary GIF and checks that FFmpeg can decode it
-before replacing `assets/demo.gif`. Temporary files are removed on exit.
+The recorder passes a temporary output path to VHS and checks that FFmpeg can
+decode the entire GIF before moving it to `assets/demo.gif`.
Use VHS `0.12.1` or later: `0.12.0` can exit successfully without rendering,
which leaves the existing GIF untouched.
The checked-in capture used VHS `0.12.1`, ttyd `1.7.7`, and FFmpeg `9.0.2`.
-## Preserve the original Raycast animation
-
-Keep `assets/raycast-demo.webp` byte-for-byte identical to the original GitHub
-asset as it was committed. Do not re-record,
-re-encode, or replace it during gbat version updates or README drift checks.
-Only change it when the user explicitly requests a replacement.
-
-The terminal recorder updates only `assets/demo.gif`. Its release version and
-recording date do not apply to the Raycast animation.
-
## Check before updating the README
- Open the terminal animation and check its version, battery output, and
readability. A successful recorder exit alone is not enough.
-- Verify that the original Raycast animation remains unchanged.
+- Preserve the original Raycast animation byte-for-byte during terminal demo
+ and release updates. Replace it only when explicitly requested.
- Check every relative link and image reference in both README files.
-- Update the terminal capture's version and tool versions here and its captions
- in both README files together. Keep the binary version tied to `Cargo.toml`
- and the intended release; do not change it to match an older recording.
+- Record the capture date, CLI version, observed output, and tool versions here.
+ Both README captions link to this file.
diff --git a/raycast/mouse-battery.sh b/raycast/mouse-battery.sh
index 5d0e413..3053a07 100755
--- a/raycast/mouse-battery.sh
+++ b/raycast/mouse-battery.sh
@@ -9,30 +9,24 @@
set -euo pipefail
-script_dir="${0:A:h}"
-project_dir="${script_dir:h}"
-
if [[ -n "${GBAT_BINARY:-}" ]]; then
- binary_path="$GBAT_BINARY"
-elif binary_path="$(command -v gbat 2>/dev/null)" && [[ -x "$binary_path" ]]; then
- :
+ candidates=("$GBAT_BINARY")
else
- binary_path=""
- for candidate in \
- "/opt/homebrew/bin/gbat" \
- "/usr/local/bin/gbat" \
- "$HOME/.local/bin/gbat" \
- "$project_dir/target/release/gbat"; do
- if [[ -x "$candidate" ]]; then
- binary_path="$candidate"
- break
- fi
- done
+ candidates=(
+ "${commands[gbat]:-}"
+ /opt/homebrew/bin/gbat
+ /usr/local/bin/gbat
+ "$HOME/.local/bin/gbat"
+ "${0:A:h:h}/target/release/gbat"
+ )
fi
-if [[ -z "$binary_path" || ! -x "$binary_path" ]]; then
- print -u2 "gbat binary not found. Build it with: cargo build --release"
- exit 1
-fi
+for candidate in "${candidates[@]}"; do
+ if [[ -f "$candidate" && -x "$candidate" ]]; then
+ [[ "$candidate" == */* ]] || candidate="./$candidate"
+ exec "$candidate"
+ fi
+done
-exec "$binary_path"
+print -u2 "gbat binary not found. Build it with: cargo build --release"
+exit 1
diff --git a/src/hidpp.rs b/src/hidpp.rs
index 9711360..9f82c5b 100644
--- a/src/hidpp.rs
+++ b/src/hidpp.rs
@@ -28,12 +28,11 @@ const DEVICE_INDEX_CANDIDATES: [u8; 7] = [1, 0xFF, 2, 3, 4, 5, 6];
const REPORT_BUFFER_LEN: usize = 20;
const FLUSH_WINDOW: Duration = Duration::from_millis(200);
const RESPONSE_TIMEOUT: Duration = Duration::from_millis(1_500);
-/// Upper bound for probing every interface and device index. A paired but
-/// unavailable index answers with an error report instead of falling silent, so
-/// this budget only caps interfaces that never answer at all.
+/// Stop starting new probes after this budget. A probe already in progress can
+/// finish, and reading a discovered battery feature has its own timeout.
const DISCOVERY_BUDGET: Duration = Duration::from_secs(6);
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, PartialEq, Eq)]
pub struct BatteryStatus {
pub level: u8,
pub charging: bool,
@@ -92,7 +91,7 @@ fn permission_denied(error: &HidError) -> bool {
}
/// One report read from a HID interface.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, PartialEq, Eq)]
struct Report {
buffer: [u8; REPORT_BUFFER_LEN],
length: usize,
@@ -105,7 +104,7 @@ impl Report {
}
/// What a single HID++ request produced.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, PartialEq, Eq)]
enum Reply {
Response(Report),
/// The device index exists but rejected the request.
@@ -133,7 +132,7 @@ enum Discovery {
}
/// What reading the battery through every candidate HID interface found.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, PartialEq, Eq)]
pub enum Reading {
Status(BatteryStatus),
/// A device index exposed a battery feature, but reading it produced no
@@ -141,11 +140,10 @@ pub enum Reading {
NoStatus,
/// A receiver answered, but reported no connected mouse.
Offline,
- /// No HID interface answered at any device index.
+ /// No candidate reported a battery feature or an offline device.
NotFound,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BatteryFeature {
Unified(u8),
Legacy(u8),
@@ -189,12 +187,6 @@ fn ensure_length(response: &[u8], minimum: usize) -> Result<(), HidppError> {
Ok(())
}
-fn parse_feature_index(response: &[u8]) -> Result