@domicile-desktop/system-battery 0.0.0-stage → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Connor Prussin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,60 @@
1
- # Temporary Holding Version
1
+ # @domicile-desktop/system-battery
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The battery for a Domicile shell, from UPower over the system bus.
4
+
5
+ - Reads UPower's DisplayDevice: the combined charge of every battery and
6
+ whether a charger is connected.
7
+ - Built on the desktop's `dbus` namespace
8
+ ([`@domicile-desktop/sdk`](../chrome-sdk/README.md)). See
9
+ [SHELL-SYSTEM-ACCESS.md](/docs/SHELL-SYSTEM-ACCESS.md).
10
+ - Needs `upower` running. Without it, calls fail with a `Dbus` error.
11
+
12
+ ## Usage
13
+
14
+ ```ts
15
+ import { watchBattery } from "@domicile-desktop/system-battery/battery";
16
+
17
+ const watched = await watchBattery(domicile);
18
+ watched.match({
19
+ Err: (error) => console.error(error.message),
20
+ Ok: async ({ items }) => {
21
+ for await (const battery of items) {
22
+ // `None()` without a battery; else `Some({ charge, charging })`.
23
+ }
24
+ },
25
+ });
26
+ ```
27
+
28
+ - `domicile` is the desktop, a `Domicile`; any object with its `dbus` works.
29
+ - `readBattery(domicile)`: the reading now, `Result<Option<Battery>, SystemError>`.
30
+ - `watchBattery(domicile)`: the reading now as the first item, then one per
31
+ UPower change. `stop()` ends it.
32
+ - `charge` is 0 through 1. `charging` is true unless the battery is draining
33
+ (discharging, empty or pending discharge), so a full battery on AC counts.
34
+ - **Lock:** both work while the desktop is locked, so a lock screen can show
35
+ the battery ([LOCK.md](/docs/LOCK.md)).
36
+
37
+ ## Dependencies
38
+
39
+ - `@domicile-desktop/sdk` for the system calls, `zod` to parse UPower's
40
+ replies, `@cprussin/option-result` for `Result` and `Option`.
41
+
42
+ ## React
43
+
44
+ `@domicile-desktop/system-battery/react`, for a shell on
45
+ [`@domicile-desktop/react`](../react/README.md):
46
+
47
+ - `useBattery()`: the reading, `undefined` until UPower answers.
48
+ - `useHasBattery()`: whether `/sys` lists a battery, looked at every 10s.
49
+ - `deskBattery(domicile)` and `deskBatteryHardware(domicile)`: the shared
50
+ watches behind them, one per desktop, for components that take a watch.
51
+ - `followBattery(domicile, onReading)` (`./follow-battery`): the watch as
52
+ callbacks, logging failures.
53
+
54
+ ## Test
55
+
56
+ ```sh
57
+ bun run turbo test --filter @domicile-desktop/system-battery
58
+ ```
59
+
60
+ Tests answer with recorded UPower replies through a fake `System`.
@@ -0,0 +1,28 @@
1
+ import type { Option, Result } from "@cprussin/option-result";
2
+ import type { Dbus } from "@domicile-desktop/sdk/desktop/dbus";
3
+ import type { Listening, SystemError } from "@domicile-desktop/sdk/system";
4
+ /** The D-Bus calls a reading makes. */
5
+ type BusDesktop<K extends keyof Dbus> = {
6
+ readonly dbus: Pick<Dbus, K>;
7
+ };
8
+ export type Battery = {
9
+ /** 0 through 1. */
10
+ charge: number;
11
+ /** Whether a charger is connected: true while charging, full or held. */
12
+ charging: boolean;
13
+ /** How long the charge lasts, while draining and once UPower estimates it. */
14
+ secondsLeft?: number;
15
+ };
16
+ /**
17
+ * The battery now, or `None` on a machine without one. Works while the
18
+ * desktop is locked.
19
+ */
20
+ export declare const readBattery: (domicile: BusDesktop<"call">) => Promise<Result<Option<Battery>, SystemError>>;
21
+ /**
22
+ * The battery now as the first item, then after each change.
23
+ *
24
+ * Listens before it reads, so no change is missed, and reads again after a
25
+ * compositor restart. Works while the desktop is locked.
26
+ */
27
+ export declare const watchBattery: (domicile: BusDesktop<"call" | "match">) => Promise<Result<Listening<Option<Battery>>, SystemError>>;
28
+ export {};
@@ -0,0 +1,114 @@
1
+ // The battery, from UPower's DisplayDevice over the system bus: the combined
2
+ // charge of every battery and whether a charger is connected.
3
+ import { Err, None, Ok, Some } from "@cprussin/option-result";
4
+ import { Bus, ListenedKind, SystemErrorKind, } from "@domicile-desktop/sdk/system";
5
+ import { z } from "zod";
6
+ const UPOWER = "org.freedesktop.UPower";
7
+ const DEVICE = "org.freedesktop.UPower.Device";
8
+ const DISPLAY_DEVICE = "/org/freedesktop/UPower/devices/DisplayDevice";
9
+ const PROPERTIES = "org.freedesktop.DBus.Properties";
10
+ /** UPower's `State`s in which the battery drains: discharging, empty, pending discharge. */
11
+ const DRAINING = [2, 3, 6];
12
+ /**
13
+ * The battery now, or `None` on a machine without one. Works while the
14
+ * desktop is locked.
15
+ */
16
+ export const readBattery = async (domicile) => (await readProperties(domicile)).map(batteryOf);
17
+ /**
18
+ * The battery now as the first item, then after each change.
19
+ *
20
+ * Listens before it reads, so no change is missed, and reads again after a
21
+ * compositor restart. Works while the desktop is locked.
22
+ */
23
+ export const watchBattery = async (domicile) => (await domicile.dbus.match({
24
+ bus: Bus.System,
25
+ interface: PROPERTIES,
26
+ member: "PropertiesChanged",
27
+ path: DISPLAY_DEVICE,
28
+ sender: UPOWER,
29
+ })).andThenAsync(async (changes) => (await readProperties(domicile)).match({
30
+ Err: (error) => {
31
+ changes.stop();
32
+ return Err(error);
33
+ },
34
+ Ok: (properties) => Ok({
35
+ ended: changes.ended,
36
+ items: changes.items.pipeThrough(readings(domicile, properties)),
37
+ stop: changes.stop,
38
+ }),
39
+ }));
40
+ const variantSchema = z.object({ signature: z.string(), value: z.unknown() });
41
+ const propertiesSchema = z.record(z.string(), variantSchema);
42
+ const getAllSchema = z.tuple([propertiesSchema]);
43
+ const propertiesChangedSchema = z.tuple([
44
+ z.string(),
45
+ propertiesSchema,
46
+ z.array(z.string()),
47
+ ]);
48
+ const deviceSchema = z.looseObject({
49
+ IsPresent: z.object({ value: z.boolean() }),
50
+ Percentage: z.object({ value: z.number() }),
51
+ State: z.object({ value: z.number().int() }),
52
+ // Not on every UPower; 0 until it has an estimate.
53
+ TimeToEmpty: z.object({ value: z.number() }).optional(),
54
+ });
55
+ const readProperties = async (domicile) => (await domicile.dbus.call({
56
+ body: [DEVICE],
57
+ bus: Bus.System,
58
+ destination: UPOWER,
59
+ interface: PROPERTIES,
60
+ member: "GetAll",
61
+ path: DISPLAY_DEVICE,
62
+ signature: "s",
63
+ })).map(({ body }) => getAllSchema.parse(body)[0]);
64
+ /**
65
+ * Each reading, starting from `properties` and folding in each change to the
66
+ * device's own interface. After a compositor restart, the properties are read
67
+ * again; a read the next restart ends waits for the restart after it.
68
+ */
69
+ const readings = (domicile, properties) => {
70
+ let current = properties;
71
+ return new TransformStream({
72
+ start: (controller) => {
73
+ controller.enqueue(batteryOf(current));
74
+ },
75
+ transform: async (heard, controller) => {
76
+ switch (heard.kind) {
77
+ case ListenedKind.Heard: {
78
+ const [iface, changed] = propertiesChangedSchema.parse(heard.item.body);
79
+ if (iface === DEVICE) {
80
+ current = { ...current, ...changed };
81
+ controller.enqueue(batteryOf(current));
82
+ }
83
+ break;
84
+ }
85
+ case ListenedKind.Missed: {
86
+ (await readProperties(domicile)).match({
87
+ Err: (error) => {
88
+ if (error.kind !== SystemErrorKind.CompositorGone) {
89
+ controller.error(error);
90
+ }
91
+ },
92
+ Ok: (read) => {
93
+ current = read;
94
+ controller.enqueue(batteryOf(current));
95
+ },
96
+ });
97
+ break;
98
+ }
99
+ }
100
+ },
101
+ });
102
+ };
103
+ const batteryOf = (properties) => {
104
+ const { IsPresent, Percentage, State, TimeToEmpty } = deviceSchema.parse(properties);
105
+ const draining = DRAINING.includes(State.value);
106
+ const secondsLeft = draining ? (TimeToEmpty?.value ?? 0) : 0;
107
+ return IsPresent.value
108
+ ? Some({
109
+ charge: Percentage.value / 100,
110
+ charging: !draining,
111
+ ...(secondsLeft > 0 && { secondsLeft }),
112
+ })
113
+ : None();
114
+ };
@@ -0,0 +1,15 @@
1
+ import type { Option } from "@cprussin/option-result";
2
+ import type { Domicile } from "@domicile-desktop/sdk/desktop/desktop";
3
+ import type { Battery } from "./battery";
4
+ import { watchBattery as watchUPower } from "./battery";
5
+ /** Injectable so tests can drive their own library and see failures. */
6
+ type Dependencies = {
7
+ fail?: (error: unknown) => void;
8
+ watch?: typeof watchUPower;
9
+ };
10
+ /**
11
+ * Watches the battery through UPower: calls `onReading` with the current
12
+ * reading and each change, and returns a function that stops watching.
13
+ */
14
+ export declare const followBattery: (domicile: Domicile, onReading: (reading: Option<Battery>) => void, { fail, watch }?: Dependencies) => (() => void);
15
+ export {};
@@ -0,0 +1,58 @@
1
+ import { watchBattery as watchUPower } from "./battery";
2
+ /**
3
+ * Watches the battery through UPower: calls `onReading` with the current
4
+ * reading and each change, and returns a function that stops watching.
5
+ */
6
+ export const followBattery = (domicile, onReading, { fail = logFailure, watch = watchUPower } = {}) => {
7
+ const now = {
8
+ stop: () => undefined,
9
+ stopped: false,
10
+ };
11
+ watch(domicile)
12
+ .then((result) => {
13
+ if (now.stopped) {
14
+ result.map(stopNow);
15
+ }
16
+ else {
17
+ now.stop = result.match({
18
+ Err: (error) => failed(fail, error),
19
+ Ok: (battery) => follow(battery, onReading, fail),
20
+ });
21
+ }
22
+ })
23
+ .catch(fail);
24
+ return () => {
25
+ now.stopped = true;
26
+ now.stop();
27
+ };
28
+ };
29
+ /** Hand each reading to `onReading`; returns what stops it. */
30
+ const follow = (battery, onReading, fail) => {
31
+ each(battery.items, onReading).catch(fail);
32
+ battery.ended
33
+ .then((ended) => {
34
+ ended.match({ Err: fail, Ok: () => undefined });
35
+ })
36
+ .catch(fail);
37
+ return battery.stop;
38
+ };
39
+ /** Calls `onItem` with each item until `items` closes. */
40
+ const each = async (items, onItem) => {
41
+ const reader = items.getReader();
42
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
43
+ onItem(next.value);
44
+ }
45
+ };
46
+ const stopNow = (battery) => {
47
+ battery.stop();
48
+ return battery;
49
+ };
50
+ /** Report `error`; there is nothing to stop. */
51
+ const failed = (fail, error) => {
52
+ fail(error);
53
+ return () => undefined;
54
+ };
55
+ const logFailure = (error) => {
56
+ // biome-ignore lint/suspicious/noConsole: the bar shows no battery, and this says why
57
+ console.error("system-battery: no battery reading", error);
58
+ };
@@ -0,0 +1,12 @@
1
+ import type { Result } from "@cprussin/option-result";
2
+ import type { Files } from "@domicile-desktop/sdk/desktop/files";
3
+ import type { SystemError } from "@domicile-desktop/sdk/system";
4
+ /** The calls the check makes. Each works while the desktop is locked. */
5
+ export type SysfsDesktop = {
6
+ readonly files: Pick<Files, "readDir" | "readText">;
7
+ };
8
+ /**
9
+ * Whether a power supply is the machine's battery. A peripheral's, such as a
10
+ * mouse's, has the scope `Device`.
11
+ */
12
+ export declare const hasBattery: (domicile: SysfsDesktop) => Promise<Result<boolean, SystemError>>;
@@ -0,0 +1,43 @@
1
+ // Whether the machine has a battery, from /sys, whether or not UPower runs.
2
+ import { Err, None, Ok, Some } from "@cprussin/option-result";
3
+ import { SystemErrorKind } from "@domicile-desktop/sdk/system";
4
+ const SUPPLIES = "/sys/class/power_supply";
5
+ /**
6
+ * Whether a power supply is the machine's battery. A peripheral's, such as a
7
+ * mouse's, has the scope `Device`.
8
+ */
9
+ export const hasBattery = async (domicile) => (await entriesOf(domicile, SUPPLIES)).match({
10
+ Err: (error) => Promise.resolve(Err(error)),
11
+ Ok: (supplies) => anyOf(supplies, async (name) => {
12
+ const type = await lineOf(domicile, `${SUPPLIES}/${name}/type`);
13
+ const scope = await lineOf(domicile, `${SUPPLIES}/${name}/scope`);
14
+ return type.andThen((kind) => scope.map((of) => kind.match({
15
+ None: () => false,
16
+ Some: (is) => is === "Battery",
17
+ }) &&
18
+ of.match({ None: () => true, Some: (is) => is !== "Device" })));
19
+ }),
20
+ });
21
+ /** The names in `dir`; none when it does not exist, as when no driver made it. */
22
+ const entriesOf = async (domicile, dir) => (await domicile.files.readDir(dir)).match({
23
+ Err: (error) => error.kind === SystemErrorKind.NotFound ? Ok([]) : Err(error),
24
+ Ok: (entries) => Ok(entries.map(({ name }) => name)),
25
+ });
26
+ /** Whether `test` holds for any of `names`, read one at a time. */
27
+ const anyOf = async (names, test) => {
28
+ const [first, ...rest] = names;
29
+ if (first === undefined) {
30
+ return Ok(false);
31
+ }
32
+ else {
33
+ return (await test(first)).match({
34
+ Err: (error) => Promise.resolve(Err(error)),
35
+ Ok: (found) => (found ? Promise.resolve(Ok(true)) : anyOf(rest, test)),
36
+ });
37
+ }
38
+ };
39
+ /** A one-line file under `/sys`, without its newline; `None` when missing. */
40
+ const lineOf = async (domicile, path) => (await domicile.files.readText(path)).match({
41
+ Err: (error) => error.kind === SystemErrorKind.NotFound ? Ok(None()) : Err(error),
42
+ Ok: (text) => Ok(Some(text.trim())),
43
+ });
@@ -0,0 +1,12 @@
1
+ import type { Option, Result } from "@cprussin/option-result";
2
+ import type { SharedWatch } from "@domicile-desktop/react/shared-watch";
3
+ import type { SystemError } from "@domicile-desktop/sdk/system";
4
+ import type { Battery } from "./battery";
5
+ /** The battery, watched once per desktop. */
6
+ export declare const deskBattery: (domicile: import("@domicile-desktop/sdk/desktop/desktop").Domicile) => SharedWatch<Option<Battery>>;
7
+ /** Whether the machine has a battery, looked for once per desktop. */
8
+ export declare const deskBatteryHardware: (domicile: import("@domicile-desktop/sdk/desktop/desktop").Domicile) => SharedWatch<Result<boolean, SystemError>>;
9
+ /** The battery's reading: `None()` without one, `undefined` before UPower says. */
10
+ export declare const useBattery: () => Option<Battery> | undefined;
11
+ /** Whether the machine has a battery, or `undefined` before it was looked for. */
12
+ export declare const useHasBattery: () => Result<boolean, SystemError> | undefined;
package/dist/react.js ADDED
@@ -0,0 +1,16 @@
1
+ // The battery for a React shell: one watch per desktop, however many parts
2
+ // read it.
3
+ import { perDesktop } from "@domicile-desktop/react/per-desktop";
4
+ import { sharedWatch } from "@domicile-desktop/react/shared-watch";
5
+ import { useDeskWatch } from "@domicile-desktop/react/use-shared-watch";
6
+ import { watchPresence } from "@domicile-desktop/react/watch-presence";
7
+ import { followBattery } from "./follow-battery";
8
+ import { hasBattery } from "./hardware";
9
+ /** The battery, watched once per desktop. */
10
+ export const deskBattery = perDesktop((domicile) => sharedWatch((onReading) => followBattery(domicile, onReading)));
11
+ /** Whether the machine has a battery, looked for once per desktop. */
12
+ export const deskBatteryHardware = perDesktop((domicile) => sharedWatch((onPresent) => watchPresence(() => hasBattery(domicile), onPresent)));
13
+ /** The battery's reading: `None()` without one, `undefined` before UPower says. */
14
+ export const useBattery = () => useDeskWatch(deskBattery);
15
+ /** Whether the machine has a battery, or `undefined` before it was looked for. */
16
+ export const useHasBattery = () => useDeskWatch(deskBatteryHardware);
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
+ "dependencies": {
3
+ "@cprussin/option-result": "^2.0.1",
4
+ "@domicile-desktop/react": "0.1.1",
5
+ "@domicile-desktop/sdk": "2.1.0",
6
+ "zod": "^4.5.4"
7
+ },
8
+ "description": "The battery for a Domicile shell: UPower's charge and charger state, over D-Bus.",
9
+ "devDependencies": {
10
+ "@cprussin/tsconfig": "^5.0.0",
11
+ "@domicile-desktop/test-support": "0.0.2",
12
+ "@types/bun": "^1.4.2",
13
+ "@types/react": "^19.2.18",
14
+ "react": "^19.2.8",
15
+ "typescript": "^7.0.2"
16
+ },
17
+ "engines": {
18
+ "bun": ">=1.4.2",
19
+ "node": ">=24"
20
+ },
21
+ "exports": {
22
+ "./battery": {
23
+ "types": "./dist/battery.d.ts",
24
+ "default": "./dist/battery.js"
25
+ },
26
+ "./hardware": {
27
+ "types": "./dist/hardware.d.ts",
28
+ "default": "./dist/hardware.js"
29
+ },
30
+ "./react": {
31
+ "types": "./dist/react.d.ts",
32
+ "default": "./dist/react.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist/**"
37
+ ],
38
+ "license": "MIT",
2
39
  "name": "@domicile-desktop/system-battery",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
40
+ "peerDependencies": {
41
+ "react": "^19.2.8"
42
+ },
43
+ "private": false,
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.build.json",
49
+ "test:types": "tsc --noEmit",
50
+ "test:unit": "bun test"
51
+ },
52
+ "type": "module",
53
+ "version": "1.1.1",
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/cprussin/domicile.git",
57
+ "directory": "packages/system-battery"
58
+ }
59
+ }