ai-battery 0.2.1 → 0.2.2

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.
@@ -12,18 +12,36 @@ import { providerId } from "../../core/display-config.js";
12
12
  const directory = path.dirname(fileURLToPath(import.meta.url));
13
13
  const marker = "X-AI-Battery-Managed=true";
14
14
  const busPrefix = "org.hnode.AiBattery.Hud";
15
+ const railBusPrefix = "org.hnode.AiBattery.HudRail";
15
16
 
16
17
  export function linuxHudStateDir(env = process.env, home = os.homedir()) {
17
18
  return env.AI_BATTERY_STATE_DIR || env.CLAUDEX_BATTERY_STATE_DIR
18
19
  || path.join(env.XDG_STATE_HOME || path.join(home, ".local", "state"), "ai-battery");
19
20
  }
20
21
 
21
- export function linuxHudBusName(root) {
22
- return `${busPrefix}.state_${crypto.createHash("sha256").update(path.resolve(root)).digest("hex").slice(0, 16)}`;
22
+ export function linuxHudBusName(root, layout = "panel") {
23
+ const prefix = layout === "rail" ? railBusPrefix : busPrefix;
24
+ return `${prefix}.state_${crypto.createHash("sha256").update(path.resolve(root)).digest("hex").slice(0, 16)}`;
25
+ }
26
+
27
+ function parseScaleValue(raw, optionName) {
28
+ const named = { small: 0.85, medium: 1, default: 1, large: 1.25, xl: 1.5 };
29
+ const key = String(raw || "").trim().toLowerCase();
30
+ const value = Object.hasOwn(named, key) ? named[key] : Number(key);
31
+ if (!Number.isFinite(value) || value < 0.5 || value > 3) {
32
+ throw invalidChoice(optionName, "0.5..3.0 (or small, medium, large, xl)", "hud");
33
+ }
34
+ return Math.round(value * 100) / 100;
23
35
  }
24
36
 
25
37
  export function parseLinuxHudArgs(argv) {
26
- const options = { action: "start", autostart: "status", interval: 2, provider: "all", foreground: false, once: false };
38
+ const options = { action: "start", autostart: "status", interval: 2, provider: "all", layout: "panel", scale: 1, codexIcon: "white", railText: "white", foreground: false, once: false };
39
+ const parseRailText = raw => {
40
+ const v = String(raw || "").trim().toLowerCase();
41
+ if (["black", "dark", "ink"].includes(v)) return "black";
42
+ if (["white", "light", "bright"].includes(v)) return "white";
43
+ throw invalidChoice("--text", "black, white", "hud");
44
+ };
27
45
  let actionSeen = false;
28
46
  for (let i = 0; i < argv.length; i += 1) {
29
47
  const arg = argv[i];
@@ -31,6 +49,43 @@ export function parseLinuxHudArgs(argv) {
31
49
  options.action = arg;
32
50
  actionSeen = true;
33
51
  if (arg === "autostart" && ["on", "off", "status"].includes(argv[i + 1])) options.autostart = argv[++i];
52
+ } else if (["rail", "--rail"].includes(arg)) {
53
+ options.layout = "rail";
54
+ } else if (["panel", "--panel"].includes(arg)) {
55
+ options.layout = "panel";
56
+ } else if (arg === "--layout") {
57
+ const next = String(requiredValue(argv, i, "hud")).trim().toLowerCase();
58
+ if (!["panel", "rail"].includes(next)) throw invalidChoice(arg, "panel, rail", "hud");
59
+ options.layout = next;
60
+ i += 1;
61
+ } else if (arg.startsWith("--layout=")) {
62
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
63
+ if (!["panel", "rail"].includes(next)) throw invalidChoice("--layout", "panel, rail", "hud");
64
+ options.layout = next;
65
+ } else if (arg === "--scale" || arg === "--size") {
66
+ options.scale = parseScaleValue(requiredValue(argv, i, "hud"), arg);
67
+ i += 1;
68
+ } else if (arg.startsWith("--scale=") || arg.startsWith("--size=")) {
69
+ const eq = arg.indexOf("=");
70
+ options.scale = parseScaleValue(arg.slice(eq + 1), arg.slice(0, eq));
71
+ } else if (arg === "--codex-icon") {
72
+ const next = String(requiredValue(argv, i, "hud")).trim().toLowerCase();
73
+ if (!["white", "black"].includes(next)) throw invalidChoice(arg, "white, black", "hud");
74
+ options.codexIcon = next;
75
+ i += 1;
76
+ } else if (arg.startsWith("--codex-icon=")) {
77
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
78
+ if (!["white", "black"].includes(next)) throw invalidChoice("--codex-icon", "white, black", "hud");
79
+ options.codexIcon = next;
80
+ } else if (arg === "black" || arg === "--black" || arg === "light" || arg === "--light") {
81
+ options.railText = "black";
82
+ } else if (arg === "white" || arg === "--white" || arg === "dark" || arg === "--dark") {
83
+ options.railText = "white";
84
+ } else if (arg === "--text" || arg === "--hud-text") {
85
+ options.railText = parseRailText(requiredValue(argv, i, "hud"));
86
+ i += 1;
87
+ } else if (arg.startsWith("--text=") || arg.startsWith("--hud-text=")) {
88
+ options.railText = parseRailText(arg.slice(arg.indexOf("=") + 1));
34
89
  } else if (["--interval", "-Interval"].includes(arg)) {
35
90
  const value = requiredValue(argv, i, "hud");
36
91
  options.interval = Number(value);
@@ -63,15 +118,27 @@ export function desktopExecArg(value) {
63
118
  export function createLinuxHudPlatform({ scriptDir, home = os.homedir(), env = process.env,
64
119
  run = spawnSync, launch = spawn, node = process.execPath } = {}) {
65
120
  const root = linuxHudStateDir(env, home);
66
- const bus = linuxHudBusName(root);
121
+ const bus = linuxHudBusName(root, "panel");
122
+ const railBus = linuxHudBusName(root, "rail");
67
123
  const native = path.join(directory, "panel.js");
124
+ const railNative = path.join(directory, "rail.js");
68
125
  const gjs = env.AI_BATTERY_GJS || (fs.existsSync("/usr/bin/gjs") ? "/usr/bin/gjs" : "gjs");
69
- const desktopFile = path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "autostart", "ai-battery-hud.desktop");
126
+ const autostartDir = path.join(env.XDG_CONFIG_HOME || path.join(home, ".config"), "autostart");
127
+ const desktopFile = path.join(autostartDir, "ai-battery-hud.desktop");
128
+ const railDesktopFile = path.join(autostartDir, "ai-battery-hud-rail.desktop");
70
129
  const hudEntry = path.join(scriptDir || path.resolve(directory, "../../../bin"), "ai-battery-hud.js");
71
130
  const gnome = createGnomeHudIntegration({ home, env, run });
72
131
 
73
- function control(action) {
74
- const result = run(gjs, ["-m", native, "--bus-name", bus, "--control", action], { env, encoding: "utf8", timeout: 4000 });
132
+ function busFor(layout = "panel") {
133
+ return layout === "rail" ? railBus : bus;
134
+ }
135
+
136
+ function desktopFor(layout = "panel") {
137
+ return layout === "rail" ? railDesktopFile : desktopFile;
138
+ }
139
+
140
+ function control(action, layout = "panel") {
141
+ const result = run(gjs, ["-m", native, "--bus-name", busFor(layout), "--control", action], { env, encoding: "utf8", timeout: 4000 });
75
142
  if (result.error || result.status !== 0) {
76
143
  if (action === "status") return { running: false, error: result.error?.message || result.stderr?.trim() };
77
144
  throw new Error(result.error?.message || result.stderr?.trim() || "Linux HUD control failed");
@@ -79,31 +146,37 @@ export function createLinuxHudPlatform({ scriptDir, home = os.homedir(), env = p
79
146
  return JSON.parse(result.stdout);
80
147
  }
81
148
 
82
- function verifyAutostart() {
149
+ function verifyAutostart(filePath = desktopFile) {
83
150
  let stat;
84
- try { stat = fs.lstatSync(desktopFile); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
85
- const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(desktopFile, "utf8") : "";
151
+ try { stat = fs.lstatSync(filePath); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
152
+ const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(filePath, "utf8") : "";
86
153
  if (!text.split(/\r?\n/).includes(marker) || !/^Exec=.*ai-battery-hud\.js/m.test(text)) {
87
- throw new Error(`Linux autostart ownership could not be verified; left untouched: ${desktopFile}`);
154
+ throw new Error(`Linux autostart ownership could not be verified; left untouched: ${filePath}`);
88
155
  }
89
156
  return true;
90
157
  }
91
158
 
92
159
  function linuxAutostartEnable(options) {
93
- verifyAutostart();
160
+ const targetDesktop = desktopFor(options.layout);
161
+ verifyAutostart(targetDesktop);
94
162
  const names = ["AI_BATTERY_STATE_DIR", "CLAUDEX_BATTERY_STATE_DIR", "AI_BATTERY_DATA_DIR", "AI_BATTERY_SHARED_USAGE_STATE_DIR", "XDG_STATE_HOME", "XDG_DATA_HOME", "CODEX_HOME", "LANGUAGE"];
95
163
  const vars = [`HOME=${home}`, ...names.filter(name => env[name]).map(name => `${name}=${env[name]}`)];
96
- const command = ["/usr/bin/env", ...vars, node, hudEntry, "start", "--interval", String(options.interval), "--provider", options.provider];
97
- const text = ["[Desktop Entry]", "Type=Application", "Version=1.0", "Name=AI Battery", "Comment=Codex and Claude usage in the panel",
164
+ const command = ["/usr/bin/env", ...vars, node, hudEntry, "start", "--interval", String(options.interval), "--provider", options.provider,
165
+ ...(options.codexIcon === "black" ? ["--codex-icon", "black"] : []),
166
+ ...(options.railText === "black" ? ["--text", "black"] : []),
167
+ ...(options.layout === "rail" ? ["--layout", "rail", ...(options.scale && options.scale !== 1 ? ["--scale", String(options.scale)] : [])] : [])];
168
+ const name = options.layout === "rail" ? "AI Battery Rail" : "AI Battery";
169
+ const text = ["[Desktop Entry]", "Type=Application", "Version=1.0", `Name=${name}`, "Comment=Codex and Claude usage in the panel",
98
170
  `Exec=${command.map(desktopExecArg).join(" ")}`, "Terminal=false", "X-GNOME-Autostart-enabled=true", marker, ""].join("\n");
99
- fs.mkdirSync(path.dirname(desktopFile), { recursive: true });
100
- fs.writeFileSync(desktopFile, text, { mode: 0o600 });
101
- return desktopFile;
171
+ fs.mkdirSync(path.dirname(targetDesktop), { recursive: true });
172
+ fs.writeFileSync(targetDesktop, text, { mode: 0o600 });
173
+ return targetDesktop;
102
174
  }
103
175
 
104
- function linuxAutostartDisable() {
105
- if (verifyAutostart()) fs.unlinkSync(desktopFile);
106
- return desktopFile;
176
+ function linuxAutostartDisable(layout = "panel") {
177
+ const targetDesktop = desktopFor(layout);
178
+ if (verifyAutostart(targetDesktop)) fs.unlinkSync(targetDesktop);
179
+ return targetDesktop;
107
180
  }
108
181
 
109
182
  function runLinuxHud(argv) {
@@ -116,12 +189,13 @@ export function createLinuxHudPlatform({ scriptDir, home = os.homedir(), env = p
116
189
  return;
117
190
  }
118
191
  const options = parseLinuxHudArgs(argv);
192
+ const explicitLayout = argv.some(arg => ["rail", "--rail", "panel", "--panel"].includes(arg) || arg.startsWith("--layout"));
119
193
  if (options.action === "autostart") {
120
194
  if (options.autostart === "on") {
121
195
  console.log(`Autostart: on · ${linuxAutostartEnable(options)}`);
122
196
  console.log(cliText("Starts at desktop login.", "데스크톱 로그인 시 실행합니다."));
123
- } else if (options.autostart === "off") console.log(`Autostart: off · ${linuxAutostartDisable()}`);
124
- else console.log(`Autostart: ${verifyAutostart() ? "on" : "off"}`);
197
+ } else if (options.autostart === "off") console.log(`Autostart: off · ${linuxAutostartDisable(options.layout)}`);
198
+ else console.log(`Autostart: ${verifyAutostart(desktopFor(options.layout)) ? "on" : "off"}`);
125
199
  return;
126
200
  }
127
201
  if (options.once) {
@@ -129,53 +203,94 @@ export function createLinuxHudPlatform({ scriptDir, home = os.homedir(), env = p
129
203
  process.exitCode = result.status ?? 1;
130
204
  return;
131
205
  }
132
- const status = control("status");
206
+ const stopLayout = layout => {
207
+ const current = control("status", layout);
208
+ if (current.running) control("quit", layout);
209
+ for (let i = 0; current.running && control("status", layout).running && i < 15; i += 1) {
210
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
211
+ }
212
+ if (current.running && control("status", layout).running) {
213
+ throw new Error(`Linux ${layout} HUD is still stopping; retry shortly`);
214
+ }
215
+ return current.running;
216
+ };
133
217
  if (options.action === "status") {
134
- console.log(`HUD: ${status.running ? `running (PID ${status.pid})` : "stopped"} · Linux panel`);
135
- if (status.presentation === "gnome") console.log("Menu: macOS SVG");
136
- if (status.running && !status.registered) console.log(cliText("Waiting for the desktop panel; reconnects automatically after unlock.", "데스크톱 패널 대기 중 · 잠금 해제 후 자동 연결됩니다."));
137
- console.log(`Autostart: ${verifyAutostart() ? "on" : "off"}`);
218
+ const panelStatus = control("status", "panel");
219
+ const railStatus = control("status", "rail");
220
+ console.log(`HUD: ${panelStatus.running ? `running (PID ${panelStatus.pid})` : "stopped"} · Linux panel`);
221
+ if (panelStatus.presentation === "gnome") console.log("Menu: macOS SVG");
222
+ if (panelStatus.running && !panelStatus.registered) console.log(cliText("Waiting for the desktop panel; reconnects automatically after unlock.", "데스크톱 패널 대기 중 · 잠금 해제 후 자동 연결됩니다."));
223
+ if (railStatus.running || explicitLayout && options.layout === "rail") {
224
+ console.log(`HUD Rail: ${railStatus.running ? `running (PID ${railStatus.pid})` : "stopped"} · Linux rail`);
225
+ }
226
+ console.log(`Autostart: ${verifyAutostart(desktopFile) ? "on" : "off"}`);
227
+ if (verifyAutostart(railDesktopFile)) console.log("Autostart Rail: on");
228
+ return;
229
+ }
230
+ if (options.action === "stop") {
231
+ if (explicitLayout) stopLayout(options.layout);
232
+ else {
233
+ stopLayout("panel");
234
+ stopLayout("rail");
235
+ }
236
+ console.log("HUD: stopped");
138
237
  return;
139
238
  }
140
- if (status.running) control("quit");
141
- for (let i = 0; status.running && control("status").running && i < 15; i += 1) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
142
- if (status.running && control("status").running) throw new Error("Linux HUD is still stopping; retry shortly");
143
- if (options.action === "stop") { console.log("HUD: stopped"); return; }
144
239
 
145
- const probe = run(gjs, ["-m", native, "--probe"], { env, encoding: "utf8", timeout: 4000 });
240
+ const isRail = options.layout === "rail";
241
+ const status = control("status", options.layout);
242
+ stopLayout(options.layout);
243
+ const entry = isRail ? railNative : native;
244
+ let launchEnv = isRail && env.DISPLAY && !env.GDK_BACKEND ? { ...env, GDK_BACKEND: "x11" } : { ...env };
245
+ if (options.codexIcon === "black") launchEnv.AI_BATTERY_CODEX_ICON_COLOR = "black";
246
+ if (options.railText === "black") {
247
+ if (isRail) launchEnv.AI_BATTERY_RAIL_TEXT = "black";
248
+ else launchEnv.AI_BATTERY_PANEL_TEXT = "black";
249
+ }
250
+ const probe = run(gjs, ["-m", entry, "--probe"], { env: launchEnv, encoding: "utf8", timeout: 4000 });
146
251
  if (probe.error || probe.status !== 0) {
147
- throw new Error(cliText("Linux panel dependencies are missing. Install: sudo apt install gjs gir1.2-dbusmenu-glib-0.4", "Linux 패널 구성 요소가 없습니다. 설치: sudo apt install gjs gir1.2-dbusmenu-glib-0.4"));
252
+ throw new Error(isRail
253
+ ? cliText("Linux rail HUD dependencies are missing. Install: sudo apt install gjs gir1.2-gtk-3.0", "Linux 레일 HUD 구성 요소가 없습니다. 설치: sudo apt install gjs gir1.2-gtk-3.0")
254
+ : cliText("Linux panel dependencies are missing. Install: sudo apt install gjs gir1.2-dbusmenu-glib-0.4", "Linux 패널 구성 요소가 없습니다. 설치: sudo apt install gjs gir1.2-dbusmenu-glib-0.4"));
148
255
  }
149
256
  const available = JSON.parse(probe.stdout);
150
- if (!available.sessionAvailable || (!available.hostAvailable && !env.DISPLAY && !env.WAYLAND_DISPLAY)) {
257
+ if (!available.sessionAvailable || (!available.hostAvailable && !available.displayAvailable && !env.DISPLAY && !env.WAYLAND_DISPLAY)) {
151
258
  throw new Error(cliText("Run the Linux HUD inside your graphical desktop session.", "Linux HUD는 그래픽 데스크톱 세션에서 실행하세요."));
152
259
  }
153
260
  let integration;
154
- try { integration = gnome.prepare(); }
155
- catch (error) { console.error(`ai-battery-hud: ${errorText(error)}`); }
261
+ if (!isRail) {
262
+ try { integration = gnome.prepare(); }
263
+ catch (error) { console.error(`ai-battery-hud: ${errorText(error)}`); }
264
+ }
156
265
  fs.mkdirSync(root, { recursive: true, mode: 0o700 });
157
266
  const ready = path.join(root, `hud-snapshot-linux-ready-${process.pid}-${Date.now()}.json`);
158
- const args = ["-m", native, "--bus-name", bus, "--node", node, "--snapshot", path.join(directory, "panel-snapshot.js"),
159
- "--interval", String(options.interval), "--provider", options.provider, "--state-dir", root, "--ready", ready];
267
+ const args = ["-m", entry, "--bus-name", busFor(options.layout), "--node", node, "--snapshot", path.join(directory, "panel-snapshot.js"),
268
+ "--interval", String(options.interval), "--provider", options.provider, "--state-dir", root, "--ready", ready,
269
+ ...(isRail ? ["--scale", String(options.scale)] : [])];
160
270
  if (options.foreground) {
161
- const result = run(gjs, args, { env, stdio: "inherit" });
271
+ const result = run(gjs, args, { env: launchEnv, stdio: "inherit" });
162
272
  process.exitCode = result.status ?? 1;
163
273
  return;
164
274
  }
165
- const logFile = path.join(root, "linux-hud.log");
275
+ const logFile = path.join(root, isRail ? "linux-rail.log" : "linux-hud.log");
166
276
  const fd = fs.openSync(logFile, "a", 0o600);
167
277
  let child;
168
- try { child = launch(gjs, args, { env, detached: true, stdio: ["ignore", fd, fd] }); }
278
+ try { child = launch(gjs, args, { env: launchEnv, detached: true, stdio: ["ignore", fd, fd] }); }
169
279
  finally { fs.closeSync(fd); }
170
280
  child.unref();
171
281
  const deadline = Date.now() + 6000;
172
282
  while (Date.now() < deadline && !fs.existsSync(ready)) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
173
283
  if (!fs.existsSync(ready)) {
174
- if (control("status").running) control("quit");
284
+ if (control("status", options.layout).running) control("quit", options.layout);
175
285
  throw new Error(cliText(`Linux HUD did not become ready. Log: ${logFile}`, `Linux HUD를 시작하지 못했습니다. 로그: ${logFile}`));
176
286
  }
177
287
  const readyState = JSON.parse(fs.readFileSync(ready, "utf8"));
178
288
  fs.unlinkSync(ready);
289
+ if (isRail) {
290
+ console.log(`HUD: ${status.running ? "restarted" : "started"} · Linux rail`);
291
+ console.log(cliText("Drag to move, scroll or right-click to resize. Stop: ai-battery hud stop rail", "드래그로 이동하고 스크롤·우클릭으로 크기를 조절합니다. 종료: ai-battery hud stop rail"));
292
+ return;
293
+ }
179
294
  console.log(`HUD: ${readyState.registered ? status.running ? "restarted" : "started" : "waiting"} · Linux panel`);
180
295
  console.log(readyState.registered
181
296
  ? cliText("Click for details. Stop: ai-battery hud stop", "클릭하면 상세 정보가 표시됩니다. 종료: ai-battery hud stop")
@@ -1,7 +1,20 @@
1
1
  // Native GJS process: the desktop owns the panel/menu, Node owns usage scans.
2
2
  import Gio from "gi://Gio";
3
3
  import GLib from "gi://GLib";
4
- import { cliLanguage } from "../../core/cli-help.js";
4
+
5
+ function panelLanguage(env) {
6
+ const explicit = Boolean(env.LANGUAGE?.trim());
7
+ const candidates = explicit
8
+ ? env.LANGUAGE.split(":")
9
+ : [env.LC_ALL || env.LC_MESSAGES || env.LANG || "", ...(GLib.get_language_names?.() || [])];
10
+ for (const candidate of candidates) {
11
+ const base = String(candidate || "").trim().toLowerCase().split(/[_@.\-]/)[0];
12
+ if (base === "ko") return "ko";
13
+ if (base === "en") return "en";
14
+ if (["c", "posix"].includes(base) && explicit) return "en";
15
+ }
16
+ return "en";
17
+ }
5
18
 
6
19
  const value = (name, fallback = "") => {
7
20
  const index = ARGV.indexOf(name);
@@ -11,7 +24,7 @@ const busName = value("--bus-name");
11
24
  const controlPath = "/org/hnode/AiBattery/Hud";
12
25
  const controlInterface = "org.hnode.AiBattery.Hud";
13
26
  const env = Object.fromEntries(["LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"].map(name => [name, GLib.getenv(name)]));
14
- const language = cliLanguage(env);
27
+ const language = panelLanguage(env);
15
28
  const t = (english, korean) => language === "ko" ? korean : english;
16
29
  const encode = text => new TextEncoder().encode(text);
17
30