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.
@@ -10,8 +10,26 @@ function sleepSync(ms) {
10
10
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
11
11
  }
12
12
 
13
- export function createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote,
13
+ export function createMacHudPlatform({ macStatusPath, macRailPath, relevantEnvPrefix, scriptDir, shellQuote,
14
14
  home = os.homedir(), runLaunchctl = args => spawnSync("launchctl", args, { stdio: "ignore" }) }) {
15
+ const resolvedMacRailPath = macRailPath || (macStatusPath ? path.join(path.dirname(macStatusPath), "ai-battery-macos-rail.applescript") : "");
16
+ function parseMacScaleValue(raw, optionName) {
17
+ const named = { small: 0.85, medium: 1, default: 1, large: 1.25, xl: 1.5 };
18
+ const key = String(raw || "").trim().toLowerCase();
19
+ const value = Object.hasOwn(named, key) ? named[key] : Number(key);
20
+ if (!Number.isFinite(value) || value < 0.5 || value > 3) {
21
+ throw invalidChoice(optionName, "0.5..3.0 (or small, medium, large, xl)", "hud");
22
+ }
23
+ return Math.round(value * 100) / 100;
24
+ }
25
+
26
+ function parseMacRailText(raw) {
27
+ const v = String(raw || "").trim().toLowerCase();
28
+ if (["black", "dark", "ink"].includes(v)) return "black";
29
+ if (["white", "light", "bright"].includes(v)) return "white";
30
+ throw invalidChoice("--text", "black, white", "hud");
31
+ }
32
+
15
33
  function parseMacHudArgs(cliArgs) {
16
34
  const options = {
17
35
  foreground: false,
@@ -20,7 +38,12 @@ function parseMacHudArgs(cliArgs) {
20
38
  subcommand: null,
21
39
  autostartAction: "status",
22
40
  interval: 2,
23
- provider: "all"
41
+ provider: "all",
42
+ layout: "menu-bar",
43
+ layoutExplicit: false,
44
+ scale: 1,
45
+ codexIcon: "white",
46
+ railText: "white"
24
47
  };
25
48
 
26
49
  for (let i = 0; i < cliArgs.length; i += 1) {
@@ -33,6 +56,47 @@ function parseMacHudArgs(cliArgs) {
33
56
  options.stop = true;
34
57
  } else if (arg === "start") {
35
58
  // Starting is the default action.
59
+ } else if (arg === "rail" || arg === "--rail") {
60
+ options.layout = "rail";
61
+ options.layoutExplicit = true;
62
+ } else if (arg === "menu-bar" || arg === "--menu-bar") {
63
+ options.layout = "menu-bar";
64
+ options.layoutExplicit = true;
65
+ } else if (arg === "--layout") {
66
+ const next = String(requiredValue(cliArgs, i, "hud")).trim().toLowerCase();
67
+ if (!["menu-bar", "rail"].includes(next)) throw invalidChoice(arg, "menu-bar, rail", "hud");
68
+ options.layout = next;
69
+ options.layoutExplicit = true;
70
+ i += 1;
71
+ } else if (arg.startsWith("--layout=")) {
72
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
73
+ if (!["menu-bar", "rail"].includes(next)) throw invalidChoice("--layout", "menu-bar, rail", "hud");
74
+ options.layout = next;
75
+ options.layoutExplicit = true;
76
+ } else if (arg === "--scale" || arg === "--size") {
77
+ options.scale = parseMacScaleValue(requiredValue(cliArgs, i, "hud"), arg);
78
+ i += 1;
79
+ } else if (arg.startsWith("--scale=") || arg.startsWith("--size=")) {
80
+ const eq = arg.indexOf("=");
81
+ options.scale = parseMacScaleValue(arg.slice(eq + 1), arg.slice(0, eq));
82
+ } else if (arg === "--codex-icon") {
83
+ const next = String(requiredValue(cliArgs, i, "hud")).trim().toLowerCase();
84
+ if (!["white", "black"].includes(next)) throw invalidChoice(arg, "white, black", "hud");
85
+ options.codexIcon = next;
86
+ i += 1;
87
+ } else if (arg.startsWith("--codex-icon=")) {
88
+ const next = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
89
+ if (!["white", "black"].includes(next)) throw invalidChoice("--codex-icon", "white, black", "hud");
90
+ options.codexIcon = next;
91
+ } else if (arg === "black" || arg === "--black" || arg === "light" || arg === "--light") {
92
+ options.railText = "black";
93
+ } else if (arg === "white" || arg === "--white" || arg === "dark" || arg === "--dark") {
94
+ options.railText = "white";
95
+ } else if (arg === "--text" || arg === "--hud-text") {
96
+ options.railText = parseMacRailText(requiredValue(cliArgs, i, "hud"));
97
+ i += 1;
98
+ } else if (arg.startsWith("--text=") || arg.startsWith("--hud-text=")) {
99
+ options.railText = parseMacRailText(arg.slice(arg.indexOf("=") + 1));
36
100
  } else if (arg === "status") {
37
101
  options.subcommand = "status";
38
102
  } else if (arg === "autostart") {
@@ -66,32 +130,41 @@ function macCommands(options) {
66
130
  const node = shellQuote(process.execPath);
67
131
  const batteryJs = shellQuote(path.join(scriptDir, "ai-battery.js"));
68
132
  const providerArgs = macProviderArgs(options.provider);
133
+ const codexIconArgs = options.codexIcon === "black" ? " --codex-icon black" : "";
134
+ const panelTextArgs = options.railText === "black" ? " --panel-text black" : "";
135
+ const railTextArgs = options.railText === "black" ? " --rail-text black" : "";
69
136
  const envPrefix = relevantEnvPrefix();
70
137
  return {
71
- title: `${envPrefix} ${node} ${batteryJs} --menu-bar-image${providerArgs} 2>/dev/null`,
138
+ title: `${envPrefix} ${node} ${batteryJs} --menu-bar-image${providerArgs}${codexIconArgs}${panelTextArgs} 2>/dev/null`,
72
139
  detailImage: `${envPrefix} ${node} ${batteryJs} --menu-detail-image${providerArgs} 2>/dev/null`,
140
+ railImage: `${envPrefix} ${node} ${batteryJs} --rail-image${providerArgs}${railTextArgs} 2>/dev/null`,
73
141
  detail: `${envPrefix} ${node} ${batteryJs} --no-color${providerArgs} 2>/dev/null`,
74
142
  state: `${envPrefix} ${node} ${batteryJs} --hud-state${providerArgs} 2>/dev/null`
75
143
  };
76
144
  }
77
145
 
78
- function macHudPids() {
146
+ function macHudPids(layout = "all") {
79
147
  const result = spawnSync("ps", ["-axo", "pid=,args="], {
80
148
  encoding: "utf8",
81
149
  stdio: ["ignore", "pipe", "ignore"]
82
150
  });
83
151
  if (result.status !== 0) return [];
84
- return macHudPidsFromPsOutput(result.stdout, process.pid);
152
+ return macHudPidsFromPsOutput(result.stdout, process.pid, layout);
85
153
  }
86
154
 
87
- function macHudCommandMatches(cmdline) {
155
+ function macHudCommandMatches(cmdline, layout = "all") {
88
156
  const text = String(cmdline || "").trim();
89
- if (!text.includes("ai-battery-macos-status.applescript")) return false;
90
- if (!text.includes("--menu-bar-image") || !text.includes("--menu-detail-image")) return false;
91
- return path.basename(text.split(/\s+/, 1)[0] || "") === "osascript";
157
+ if (path.basename(text.split(/\s+/, 1)[0] || "") !== "osascript") return false;
158
+ if (layout !== "rail" && text.includes("ai-battery-macos-status.applescript")) {
159
+ return text.includes("--menu-bar-image") && text.includes("--menu-detail-image");
160
+ }
161
+ if (layout !== "menu-bar" && text.includes("ai-battery-macos-rail.applescript")) {
162
+ return text.includes("--rail-image");
163
+ }
164
+ return false;
92
165
  }
93
166
 
94
- function macHudPidsFromPsOutput(output, ownPid = process.pid) {
167
+ function macHudPidsFromPsOutput(output, ownPid = process.pid, layout = "all") {
95
168
  return String(output || "")
96
169
  .split(/\r?\n/)
97
170
  .map((line) => {
@@ -103,12 +176,16 @@ function macHudPidsFromPsOutput(output, ownPid = process.pid) {
103
176
  && Number.isInteger(proc.pid)
104
177
  && proc.pid > 0
105
178
  && proc.pid !== ownPid
106
- && macHudCommandMatches(proc.cmdline))
179
+ && macHudCommandMatches(proc.cmdline, layout))
107
180
  .map((proc) => proc.pid);
108
181
  }
109
182
 
110
- function macLaunchAgentPath() {
111
- return path.join(home, "Library", "LaunchAgents", "com.ai-battery.hud.plist");
183
+ function macLaunchAgentLabel(layout = "menu-bar") {
184
+ return layout === "rail" ? "com.ai-battery.hud.rail" : "com.ai-battery.hud";
185
+ }
186
+
187
+ function macLaunchAgentPath(layout = "menu-bar") {
188
+ return path.join(home, "Library", "LaunchAgents", `${macLaunchAgentLabel(layout)}.plist`);
112
189
  }
113
190
 
114
191
  function macLaunchctlDomain() {
@@ -128,14 +205,21 @@ function plistString(value) {
128
205
  }
129
206
 
130
207
  function macAutostartPlist(options) {
208
+ const layout = options.layout === "rail" ? "rail" : "menu-bar";
131
209
  const args = [process.execPath, path.join(scriptDir, "ai-battery-hud.js"), "start", "--interval", String(options.interval)];
132
210
  if (options.provider !== "all") args.push("--provider", options.provider);
211
+ if (options.codexIcon === "black") args.push("--codex-icon", "black");
212
+ if (options.railText === "black") args.push("--text", "black");
213
+ if (layout === "rail") {
214
+ args.push("--layout", "rail");
215
+ if (options.scale && options.scale !== 1) args.push("--scale", String(options.scale));
216
+ }
133
217
  return `<?xml version="1.0" encoding="UTF-8"?>
134
218
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
135
219
  <plist version="1.0">
136
220
  <dict>
137
221
  <key>Label</key>
138
- <string>com.ai-battery.hud</string>
222
+ <string>${macLaunchAgentLabel(layout)}</string>
139
223
  <key>ProgramArguments</key>
140
224
  <array>
141
225
  ${args.map(plistString).join("\n")}
@@ -147,18 +231,19 @@ ${args.map(plistString).join("\n")}
147
231
  `;
148
232
  }
149
233
 
150
- function macAutostartStatus() {
151
- const filePath = macLaunchAgentPath();
234
+ function macAutostartStatus(layout = "menu-bar") {
235
+ const filePath = macLaunchAgentPath(layout);
152
236
  return { enabled: fs.existsSync(filePath), filePath };
153
237
  }
154
238
 
155
- function verifyMacAutostartOwnership(filePath) {
239
+ function verifyMacAutostartOwnership(filePath, layout = "menu-bar") {
156
240
  let stat;
157
241
  try { stat = fs.lstatSync(filePath); } catch (error) { if (error.code === "ENOENT") return false; throw error; }
158
242
  const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(filePath, "utf8") : "";
159
243
  const args = text.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1];
160
244
  const values = [...(args || "").matchAll(/<string>([^<]*)<\/string>/g)].map(match => match[1]);
161
- if (!/<key>Label<\/key>\s*<string>com\.ai-battery\.hud<\/string>/.test(text)
245
+ const expectedLabel = macLaunchAgentLabel(layout).replace(/\./g, "\\.");
246
+ if (!new RegExp(`<key>Label<\\/key>\\s*<string>${expectedLabel}<\\/string>`).test(text)
162
247
  || !/[\\/]ai-battery-hud\.js$/.test(values[1] || "") || values[2] !== "start") {
163
248
  throw new Error(`LaunchAgent ownership could not be verified; left untouched: ${filePath}`);
164
249
  }
@@ -166,17 +251,18 @@ function verifyMacAutostartOwnership(filePath) {
166
251
  }
167
252
 
168
253
  function macAutostartEnable(options) {
169
- const filePath = macLaunchAgentPath();
170
- verifyMacAutostartOwnership(filePath);
254
+ const layout = options.layout === "rail" ? "rail" : "menu-bar";
255
+ const filePath = macLaunchAgentPath(layout);
256
+ verifyMacAutostartOwnership(filePath, layout);
171
257
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
172
258
  fs.writeFileSync(filePath, macAutostartPlist(options), "utf8");
173
259
  runLaunchctl(["bootstrap", macLaunchctlDomain(), filePath]);
174
260
  return filePath;
175
261
  }
176
262
 
177
- function macAutostartDisable() {
178
- const filePath = macLaunchAgentPath();
179
- if (!verifyMacAutostartOwnership(filePath)) return filePath;
263
+ function macAutostartDisable(layout = "menu-bar") {
264
+ const filePath = macLaunchAgentPath(layout);
265
+ if (!verifyMacAutostartOwnership(filePath, layout)) return filePath;
180
266
  runLaunchctl(["bootout", macLaunchctlDomain(), filePath]);
181
267
  fs.rmSync(filePath, { force: true });
182
268
  return filePath;
@@ -208,22 +294,32 @@ function runMacHud(cliArgs) {
208
294
  }
209
295
 
210
296
  if (options.subcommand === "status") {
211
- const pids = macHudPids();
212
- const auto = macAutostartStatus();
297
+ const pids = macHudPids("menu-bar");
298
+ const railPids = macHudPids("rail");
299
+ const auto = macAutostartStatus("menu-bar");
300
+ const railAuto = macAutostartStatus("rail");
213
301
  console.log(`HUD: ${pids.length ? `running (PID ${pids[0]})` : "stopped"}`);
302
+ if (railPids.length || (options.layoutExplicit && options.layout === "rail")) {
303
+ console.log(`HUD Rail: ${railPids.length ? `running (PID ${railPids[0]})` : "stopped"}`);
304
+ }
214
305
  console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
215
306
  if (auto.enabled) console.log(` ${auto.filePath}`);
307
+ if (railAuto.enabled) {
308
+ console.log("Autostart Rail: on");
309
+ console.log(` ${railAuto.filePath}`);
310
+ }
216
311
  process.exit(0);
217
312
  }
218
313
 
219
314
  if (options.subcommand === "autostart") {
315
+ const layout = options.layout === "rail" ? "rail" : "menu-bar";
220
316
  if (options.autostartAction === "on") {
221
317
  console.log(`Autostart: on · ${macAutostartEnable(options)}`);
222
318
  console.log(cliText("Starts at macOS login.", "macOS 로그인 시 실행합니다."));
223
319
  } else if (options.autostartAction === "off") {
224
- console.log(`Autostart: off · ${macAutostartDisable()}`);
320
+ console.log(`Autostart: off · ${macAutostartDisable(layout)}`);
225
321
  } else {
226
- const auto = macAutostartStatus();
322
+ const auto = macAutostartStatus(layout);
227
323
  console.log(`Autostart: ${auto.enabled ? "on" : "off"}`);
228
324
  if (auto.enabled) console.log(` ${auto.filePath}`);
229
325
  }
@@ -231,7 +327,7 @@ function runMacHud(cliArgs) {
231
327
  }
232
328
 
233
329
  if (options.stop) {
234
- const pids = macHudPids();
330
+ const pids = macHudPids(options.layoutExplicit ? options.layout : "all");
235
331
  if (!pids.length) {
236
332
  console.log("HUD: stopped");
237
333
  process.exit(0);
@@ -241,20 +337,30 @@ function runMacHud(cliArgs) {
241
337
  process.exit(result.error ? 1 : (result.status ?? 1));
242
338
  }
243
339
 
244
- const existingPids = macHudPids();
340
+ const existingPids = macHudPids(options.layout);
245
341
  if (existingPids.length) {
246
342
  spawnSync("kill", existingPids.map(String), { stdio: "ignore" });
247
343
  sleepSync(400);
248
344
  }
249
345
 
250
- const osascriptArgs = [
251
- macStatusPath,
252
- commands.title,
253
- commands.detailImage,
254
- commands.detail,
255
- String(options.interval),
256
- commands.state
257
- ];
346
+ const isRail = options.layout === "rail";
347
+ const osascriptArgs = isRail
348
+ ? [
349
+ resolvedMacRailPath,
350
+ commands.railImage,
351
+ commands.detail,
352
+ String(options.interval),
353
+ commands.state,
354
+ String(options.scale)
355
+ ]
356
+ : [
357
+ macStatusPath,
358
+ commands.title,
359
+ commands.detailImage,
360
+ commands.detail,
361
+ String(options.interval),
362
+ commands.state
363
+ ];
258
364
 
259
365
  if (options.foreground) {
260
366
  const result = spawnSync("osascript", osascriptArgs, { stdio: "inherit" });
@@ -266,8 +372,10 @@ function runMacHud(cliArgs) {
266
372
  stdio: "ignore"
267
373
  });
268
374
  child.unref();
269
- console.log(`HUD: ${existingPids.length ? "restarted" : "started"} · menu bar`);
270
- console.log(cliText("Click for details. Stop: ai-battery hud stop", "클릭하면 상세 정보가 표시됩니다. 종료: ai-battery hud stop"));
375
+ console.log(`HUD: ${existingPids.length ? "restarted" : "started"} · ${isRail ? "rail" : "menu bar"}`);
376
+ console.log(isRail
377
+ ? cliText("Drag to move, right-click to resize. Stop: ai-battery hud stop rail", "드래그로 이동하고 우클릭으로 크기를 조절합니다. 종료: ai-battery hud stop rail")
378
+ : cliText("Click for details. Stop: ai-battery hud stop", "클릭하면 상세 정보가 표시됩니다. 종료: ai-battery hud stop"));
271
379
  process.exit(0);
272
380
  }
273
381
 
@@ -267,11 +267,19 @@ function Resize-HudToContent {
267
267
  }
268
268
  if (($form.Width -ne $desiredWidth) -or ($form.Height -ne $desiredHeight)) {
269
269
  $form.Size = [System.Drawing.Size]::new($desiredWidth, $desiredHeight)
270
- $newX = if ($script:hudAnchorX -eq "right") { $oldRight - $form.Width } else { $form.Left }
271
- $newY = if ($script:hudAnchorY -eq "bottom") { $oldBottom - $form.Height } else { $form.Top }
272
- $form.Location = [System.Drawing.Point]::new([int]$newX, [int]$newY)
273
- Sync-HitFormBounds
274
- Save-HudPositionIfReady
270
+ if (-not $script:resizeDrag) {
271
+ $newX = if ($script:hudAnchorX -eq "right") { $oldRight - $form.Width } else { $form.Left }
272
+ $newY = if ($script:hudAnchorY -eq "bottom") { $oldBottom - $form.Height } else { $form.Top }
273
+ if ($script:positionSaveReady -and (Get-Command Get-OnScreenPoint -ErrorAction SilentlyContinue)) {
274
+ $form.Location = Get-OnScreenPoint ([int]$newX) ([int]$newY) ([int]$form.Width) ([int]$form.Height)
275
+ } else {
276
+ $form.Location = [System.Drawing.Point]::new([int]$newX, [int]$newY)
277
+ }
278
+ Sync-HitFormBounds
279
+ Save-HudPositionIfReady
280
+ } else {
281
+ Sync-HitFormBounds
282
+ }
275
283
  }
276
284
  if ($script:horizontalPaintPanel) { $script:horizontalPaintPanel.Invalidate() }
277
285
  if ($script:detailPopupForm -and -not $script:detailPopupForm.IsDisposed -and $script:detailPopupForm.Visible) {
@@ -296,16 +304,24 @@ function Resize-HudToContent {
296
304
 
297
305
  if (([math]::Abs($form.Width - $desiredWidth) -gt 1) -or ($form.Height -ne $desiredHeight)) {
298
306
  $form.Size = [System.Drawing.Size]::new($desiredWidth, $desiredHeight)
299
- $newX = if ($script:hudAnchorX -eq "right") { $oldRight - $form.Width } else { $form.Left }
300
- $newY = if ($script:hudAnchorY -eq "bottom") { $oldBottom - $form.Height } else { $form.Top }
301
- $form.Location = [System.Drawing.Point]::new([int]$newX, [int]$newY)
302
- Sync-HitFormBounds
303
- Save-HudPositionIfReady
307
+ if (-not $script:resizeDrag) {
308
+ $newX = if ($script:hudAnchorX -eq "right") { $oldRight - $form.Width } else { $form.Left }
309
+ $newY = if ($script:hudAnchorY -eq "bottom") { $oldBottom - $form.Height } else { $form.Top }
310
+ if ($script:positionSaveReady -and (Get-Command Get-OnScreenPoint -ErrorAction SilentlyContinue)) {
311
+ $form.Location = Get-OnScreenPoint ([int]$newX) ([int]$newY) ([int]$form.Width) ([int]$form.Height)
312
+ } else {
313
+ $form.Location = [System.Drawing.Point]::new([int]$newX, [int]$newY)
314
+ }
315
+ Sync-HitFormBounds
316
+ Save-HudPositionIfReady
317
+ } else {
318
+ Sync-HitFormBounds
319
+ }
304
320
  }
305
321
  }
306
322
 
307
323
  function Show-HudMessage([string]$Message) {
308
- $key = "message:$Message|$script:hudScale|$script:hudDarkText|$script:hudHorizontalPanel"
324
+ $key = "message:$Message|$script:hudScale|$script:hudDarkText|$script:hudContrastBackdrop|$script:hudCodexIconMode|$script:hudHorizontalPanel"
309
325
  if ($script:hudVisualKey -eq $key) { return }
310
326
  $script:hudVisualKey = $null
311
327
  $script:latestHudTexts = $null
@@ -367,7 +383,7 @@ function Update-HudFromSnapshot($Snapshot) {
367
383
  Running = $_.Parts.Running; Color = $_.Parts.TextColor.ToArgb();
368
384
  Reset = $_.Parts.ResetValue; Week = $_.Parts.WeekValue; Extra = $_.Parts.ExtraText }
369
385
  })
370
- $key = (@{ Rows = $visualRows; Scale = $script:hudScale; DarkText = $script:hudDarkText; Layout = $script:hudCustomLayout } | ConvertTo-Json -Depth 5 -Compress)
386
+ $key = (@{ Rows = $visualRows; Scale = $script:hudScale; DarkText = $script:hudDarkText; Backdrop = [bool]$script:hudContrastBackdrop; CodexIcon = [string]$script:hudCodexIconMode; Layout = $script:hudCustomLayout } | ConvertTo-Json -Depth 5 -Compress)
371
387
  if ($script:hudVisualKey -eq $key) {
372
388
  Invalidate-DockedTuiIfChanged $Snapshot
373
389
  Update-HudVisibilityForFullscreen