ai-battery 0.2.1 → 0.2.3
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/README.md +6 -6
- package/bin/ai-battery-macos-rail.applescript +227 -0
- package/bin/ai-battery-run +6 -1
- package/docs/RELEASING.md +18 -7
- package/docs/hud-preview.svg +60 -28
- package/lib/cli.js +227 -41
- package/lib/core/cli-help.js +25 -8
- package/lib/core/config-editor.js +48 -8
- package/lib/core/display-config.js +12 -3
- package/lib/core/tmux-status.js +1 -1
- package/lib/hud/launcher.js +4 -3
- package/lib/platforms/linux/gnome-extension/extension.js +7 -6
- package/lib/platforms/linux/hud.js +157 -42
- package/lib/platforms/linux/panel.js +15 -2
- package/lib/platforms/linux/rail.js +412 -0
- package/lib/platforms/macos/hud.js +147 -39
- package/lib/platforms/windows/codex-runner.js +5 -1
- package/lib/platforms/windows/hud/controls.ps1 +28 -12
- package/lib/platforms/windows/hud/main.ps1 +372 -18
- package/lib/platforms/windows/hud/rendering.ps1 +107 -51
- package/lib/platforms/windows/hud-launcher.js +83 -4
- package/lib/platforms/windows/shared-bar-platform.js +7 -4
- package/lib/platforms/windows/terminal-compositor.js +4 -2
- package/lib/platforms/windows/wt-bar.js +8 -1
- package/lib/platforms/windows/wt-fragment.js +4 -4
- package/package.json +3 -2
|
@@ -22,6 +22,7 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
|
|
|
22
22
|
let positionTabVisited = false;
|
|
23
23
|
const t = (english, korean) => language === "ko" ? korean : english;
|
|
24
24
|
const positionLabel = pos => ({
|
|
25
|
+
off: t("Off", "표시 안 함 (off)"),
|
|
25
26
|
bottom: t("Bottom", "하단 (bottom)"),
|
|
26
27
|
top: t("Top", "상단 (top)"),
|
|
27
28
|
left: t("Left", "좌측 (left)"),
|
|
@@ -112,7 +113,6 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
|
|
|
112
113
|
lines = [fit(`${selected + 1}/${order.length} [${providers[order[selected]] ? "x" : " "}] ${providerLabel(order[selected])}`), help].slice(0, Math.max(1, height));
|
|
113
114
|
}
|
|
114
115
|
} else {
|
|
115
|
-
const isSidePosition = barPosition === "left" || barPosition === "right";
|
|
116
116
|
const fullHelp = t("↑↓ select · Enter save · Esc cancel · Tab switch", "↑↓ 선택 · Enter 저장 · Esc 취소 · Tab 전환");
|
|
117
117
|
const compactHelp = t("↑↓ select · Enter save · Esc cancel · Tab", "↑↓ 선택 · Enter 저장 · Esc 취소 · Tab");
|
|
118
118
|
const help = [fullHelp, compactHelp, "↑↓ · Enter · Esc · Tab"].find(text => visibleWidth(text) <= availableWidth)
|
|
@@ -124,15 +124,57 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
|
|
|
124
124
|
const line = width >= 24 && height >= 10 ? `│ ${padded} │` : text;
|
|
125
125
|
return index === positionSelected && color ? `\x1b[36m${line}\x1b[0m` : line;
|
|
126
126
|
});
|
|
127
|
-
const
|
|
128
|
-
if (
|
|
127
|
+
const buildPositionMockup = () => {
|
|
128
|
+
if (width < 28 || height < 16) return [];
|
|
129
129
|
const frameW = Math.min(availableWidth, width);
|
|
130
|
-
const sideW = 5;
|
|
131
|
-
const workW = Math.max(8, frameW - sideW - 3);
|
|
132
130
|
const padCell = (raw, w) => {
|
|
133
131
|
const clipped = truncateMiddleVisible(raw, w);
|
|
134
132
|
return clipped + " ".repeat(Math.max(0, w - visibleWidth(clipped)));
|
|
135
133
|
};
|
|
134
|
+
const border = s => color ? `\x1b[2m${s}\x1b[0m` : s;
|
|
135
|
+
const v = border("│");
|
|
136
|
+
if (barPosition === "off") {
|
|
137
|
+
const innerW = Math.max(12, frameW - 2);
|
|
138
|
+
const centerRow = (raw) => {
|
|
139
|
+
const clipped = truncateMiddleVisible(raw, innerW);
|
|
140
|
+
const len = visibleWidth(clipped);
|
|
141
|
+
const l = Math.floor(Math.max(0, innerW - len) / 2);
|
|
142
|
+
const r = Math.max(0, innerW - len - l);
|
|
143
|
+
return `${v}${" ".repeat(l)}${clipped}${" ".repeat(r)}${v}`;
|
|
144
|
+
};
|
|
145
|
+
const hiddenNote = t("Status bar hidden", "상태바 표시 안 함");
|
|
146
|
+
const top = border(`┌${"─".repeat(innerW)}┐`);
|
|
147
|
+
const bottom = border(`└${"─".repeat(innerW)}┘`);
|
|
148
|
+
return [
|
|
149
|
+
top,
|
|
150
|
+
`${v}${padCell(color ? "\x1b[2m $ codex\x1b[0m" : " $ codex", innerW)}${v}`,
|
|
151
|
+
`${v}${" ".repeat(innerW)}${v}`,
|
|
152
|
+
centerRow(color ? `\x1b[2m${hiddenNote}\x1b[0m` : hiddenNote),
|
|
153
|
+
`${v}${" ".repeat(innerW)}${v}`,
|
|
154
|
+
`${v}${" ".repeat(innerW)}${v}`,
|
|
155
|
+
bottom
|
|
156
|
+
];
|
|
157
|
+
}
|
|
158
|
+
if (barPosition === "top" || barPosition === "bottom") {
|
|
159
|
+
const innerW = Math.max(12, frameW - 2);
|
|
160
|
+
const barRaw = color
|
|
161
|
+
? " \x1b[32mGemini 50%\x1b[0m \x1b[2m│\x1b[0m 5h 18:34 \x1b[2m│\x1b[0m 7d 74%"
|
|
162
|
+
: " Gemini 50% │ 5h 18:34 │ 7d 74%";
|
|
163
|
+
const barRow = `${v}${padCell(barRaw, innerW)}${v}`;
|
|
164
|
+
const workRows = [
|
|
165
|
+
`${v}${padCell(color ? "\x1b[2m $ codex\x1b[0m" : " $ codex", innerW)}${v}`,
|
|
166
|
+
`${v}${" ".repeat(innerW)}${v}`,
|
|
167
|
+
`${v}${" ".repeat(innerW)}${v}`
|
|
168
|
+
];
|
|
169
|
+
const top = border(`┌${"─".repeat(innerW)}┐`);
|
|
170
|
+
const mid = border(`├${"─".repeat(innerW)}┤`);
|
|
171
|
+
const bottom = border(`└${"─".repeat(innerW)}┘`);
|
|
172
|
+
return barPosition === "top"
|
|
173
|
+
? [top, barRow, mid, ...workRows, bottom]
|
|
174
|
+
: [top, ...workRows, mid, barRow, bottom];
|
|
175
|
+
}
|
|
176
|
+
const sideW = 5;
|
|
177
|
+
const workW = Math.max(8, frameW - sideW - 3);
|
|
136
178
|
const centerCell = (raw, w) => {
|
|
137
179
|
const clipped = truncateMiddleVisible(raw, w);
|
|
138
180
|
const len = visibleWidth(clipped);
|
|
@@ -160,14 +202,12 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
|
|
|
160
202
|
: " ".repeat(workW)
|
|
161
203
|
));
|
|
162
204
|
const isLeft = barPosition === "left";
|
|
163
|
-
const border = s => color ? `\x1b[2m${s}\x1b[0m` : s;
|
|
164
205
|
const top = isLeft
|
|
165
206
|
? border(`┌${"─".repeat(sideW)}┬${"─".repeat(workW)}┐`)
|
|
166
207
|
: border(`┌${"─".repeat(workW)}┬${"─".repeat(sideW)}┐`);
|
|
167
208
|
const bottom = isLeft
|
|
168
209
|
? border(`└${"─".repeat(sideW)}┴${"─".repeat(workW)}┘`)
|
|
169
210
|
: border(`└${"─".repeat(workW)}┴${"─".repeat(sideW)}┘`);
|
|
170
|
-
const v = border("│");
|
|
171
211
|
const body = mockSideRows.map((sideCell, idx) => (
|
|
172
212
|
isLeft
|
|
173
213
|
? `${v}${sideCell}${v}${mockWorkRows[idx]}${v}`
|
|
@@ -181,7 +221,7 @@ export function editDisplayConfig(initialConfig, { input = process.stdin, output
|
|
|
181
221
|
`╭─${title}${"─".repeat(Math.max(0, width - 3 - visibleWidth(title)))}╮`,
|
|
182
222
|
...items,
|
|
183
223
|
`╰${"─".repeat(width - 2)}╯`,
|
|
184
|
-
...
|
|
224
|
+
...buildPositionMockup(),
|
|
185
225
|
help
|
|
186
226
|
];
|
|
187
227
|
} else if (height >= 8) {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export const PROVIDERS = ["codex", "claude", "antigravity"];
|
|
2
2
|
export const STATUS_LINE_ITEMS = ["model-with-reasoning", "current-dir", "git-branch", "branch-changes", "context-remaining"];
|
|
3
3
|
export const SPLIT_BAR_MODES = ["auto", "manual", "off"];
|
|
4
|
-
export const
|
|
4
|
+
export const SPLIT_BAR_POSITIONS = ["bottom", "top", "left", "right"];
|
|
5
|
+
export const BAR_POSITIONS = ["off", ...SPLIT_BAR_POSITIONS];
|
|
5
6
|
export const DEFAULT_SIDEBAR_WIDTH = 5;
|
|
6
7
|
export const MIN_SIDEBAR_WIDTH = 5;
|
|
7
8
|
export const MAX_SIDEBAR_WIDTH = 5;
|
|
@@ -19,14 +20,22 @@ export function normalizeSplitBarMode(value, fallback = "auto") {
|
|
|
19
20
|
return SPLIT_BAR_MODES.includes(normalized) ? normalized : fallback;
|
|
20
21
|
}
|
|
21
22
|
|
|
22
|
-
export function
|
|
23
|
+
export function normalizeSplitBarPosition(value, fallback = "bottom") {
|
|
23
24
|
if (typeof value !== "string") return fallback;
|
|
24
25
|
const normalized = value.trim().toLowerCase();
|
|
25
26
|
if (normalized === "down" || normalized === "b") return "bottom";
|
|
26
27
|
if (normalized === "up" || normalized === "t") return "top";
|
|
27
28
|
if (normalized === "l") return "left";
|
|
28
29
|
if (normalized === "r") return "right";
|
|
29
|
-
return
|
|
30
|
+
return SPLIT_BAR_POSITIONS.includes(normalized) ? normalized : fallback;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function normalizeBarPosition(value, fallback = "bottom") {
|
|
34
|
+
if (typeof value !== "string") return fallback;
|
|
35
|
+
const normalized = value.trim().toLowerCase();
|
|
36
|
+
if (normalized === "off" || normalized === "none" || normalized === "hidden" || normalized === "hide") return "off";
|
|
37
|
+
const edge = normalizeSplitBarPosition(normalized, null);
|
|
38
|
+
return edge || fallback;
|
|
30
39
|
}
|
|
31
40
|
|
|
32
41
|
export function providerId(value) {
|
package/lib/core/tmux-status.js
CHANGED
|
@@ -89,7 +89,7 @@ export function updateTmuxStatus({ socket, action = "tick", token, script, match
|
|
|
89
89
|
const sessionLines = run("list-sessions", "-F", "#{session_id}\t#{session_width}").split("\n").filter(Boolean);
|
|
90
90
|
const paneLines = run("list-panes", "-a", "-F", "#{session_id}\t#{pane_pid}\t#{pane_dead}").split("\n");
|
|
91
91
|
const panes = paneLines.map(line => { const [session, pid, dead] = line.split("\t"); return { session, pid: Number(pid), dead: dead === "1" }; });
|
|
92
|
-
const active = action === "stop" ? new Map() : paneProviders(panes, processTree(), matches);
|
|
92
|
+
const active = (action === "stop" || position === "off") ? new Map() : paneProviders(panes, processTree(), matches);
|
|
93
93
|
const readFormats = (session, global = false) => {
|
|
94
94
|
const flags = global ? ["-g"] : ["-t", session];
|
|
95
95
|
const listing = get(...flags, "status-format");
|
package/lib/hud/launcher.js
CHANGED
|
@@ -19,6 +19,7 @@ const ps1Path = path.join(scriptDir, "ai-battery-hud.ps1");
|
|
|
19
19
|
const windowsHudSourceDir = path.resolve(scriptDir, "../lib/platforms/windows/hud");
|
|
20
20
|
const windowsHudMainPath = path.join(windowsHudSourceDir, "main.ps1");
|
|
21
21
|
const macStatusPath = path.join(scriptDir, "ai-battery-macos-status.applescript");
|
|
22
|
+
const macRailPath = path.join(scriptDir, "ai-battery-macos-rail.applescript");
|
|
22
23
|
|
|
23
24
|
function commandExists(command) {
|
|
24
25
|
const result = spawnSync(command, ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.Major"], {
|
|
@@ -118,12 +119,12 @@ function isDirectRun() {
|
|
|
118
119
|
}
|
|
119
120
|
}
|
|
120
121
|
|
|
121
|
-
function prefetchInitialJson(command, useWslCommand, batteryModulePath = path.join(scriptDir, "ai-battery.js")) {
|
|
122
|
+
function prefetchInitialJson(command, useWslCommand, batteryModulePath = path.join(scriptDir, "ai-battery.js"), extraArgs = []) {
|
|
122
123
|
if (process.env.AI_BATTERY_HUD_NO_PREFETCH) return null;
|
|
123
124
|
|
|
124
125
|
const result = useWslCommand
|
|
125
126
|
? spawnSync("bash", ["-lc", command], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 6000 })
|
|
126
|
-
: spawnSync(process.execPath, [batteryModulePath, "--json"], {
|
|
127
|
+
: spawnSync(process.execPath, [batteryModulePath, "--json", ...extraArgs], {
|
|
127
128
|
encoding: "utf8",
|
|
128
129
|
stdio: ["ignore", "pipe", "ignore"],
|
|
129
130
|
timeout: 6000,
|
|
@@ -170,7 +171,7 @@ const {
|
|
|
170
171
|
macHudCommandMatches,
|
|
171
172
|
macHudPidsFromPsOutput,
|
|
172
173
|
runMacHud
|
|
173
|
-
} = createMacHudPlatform({ macStatusPath, relevantEnvPrefix, scriptDir, shellQuote });
|
|
174
|
+
} = createMacHudPlatform({ macStatusPath, macRailPath, relevantEnvPrefix, scriptDir, shellQuote });
|
|
174
175
|
const {
|
|
175
176
|
describeWindowsHudOptions,
|
|
176
177
|
parseWindowsHudArgs,
|
|
@@ -21,12 +21,13 @@ function call(name, method, cancellable = null) {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
function artwork(actor, file, description) {
|
|
24
|
-
const
|
|
25
|
-
|
|
24
|
+
const themeScale = St.ThemeContext.get_for_stage(global.stage).scale_factor;
|
|
25
|
+
const renderScale = Math.max(2, themeScale);
|
|
26
|
+
if (actor._artwork === `${file}:${renderScale}`) return;
|
|
26
27
|
let pixbuf = GdkPixbuf.Pixbuf.new_from_file(file);
|
|
27
28
|
const width = pixbuf.width;
|
|
28
29
|
const height = pixbuf.height;
|
|
29
|
-
|
|
30
|
+
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(file, width * renderScale, height * renderScale, false);
|
|
30
31
|
const content = St.ImageContent.new_with_preferred_size(width, height);
|
|
31
32
|
const format = pixbuf.has_alpha ? Cogl.PixelFormat.RGBA_8888 : Cogl.PixelFormat.RGB_888;
|
|
32
33
|
if (content.set_bytes) {
|
|
@@ -38,7 +39,7 @@ function artwork(actor, file, description) {
|
|
|
38
39
|
actor.set_content(content);
|
|
39
40
|
actor.set_size(width, height);
|
|
40
41
|
actor.accessible_name = description;
|
|
41
|
-
actor._artwork = `${file}:${
|
|
42
|
+
actor._artwork = `${file}:${renderScale}`;
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
export default class AiBattery extends Extension {
|
|
@@ -83,7 +84,7 @@ export default class AiBattery extends Extension {
|
|
|
83
84
|
const icon = new St.Widget({ content_gravity: Clutter.ContentGravity.RESIZE_FILL, y_align: Clutter.ActorAlign.CENTER });
|
|
84
85
|
button.add_child(icon);
|
|
85
86
|
button.menu.actor.set_style("-arrow-border-width: 0; -arrow-border-color: transparent;");
|
|
86
|
-
button.menu.box.set_style("
|
|
87
|
+
button.menu.box.set_style("padding: 6px 0;");
|
|
87
88
|
const item = new PopupMenu.PopupBaseMenuItem({ reactive: false, can_focus: false });
|
|
88
89
|
item.set_style("padding: 0;");
|
|
89
90
|
const detail = new St.Widget({ content_gravity: Clutter.ContentGravity.RESIZE_FILL });
|
|
@@ -95,7 +96,7 @@ export default class AiBattery extends Extension {
|
|
|
95
96
|
button.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
|
|
96
97
|
const refresh = button.menu.addAction("Refresh", () => call(name, "Refresh").catch(console.error));
|
|
97
98
|
const quit = button.menu.addAction("Quit AI Battery", () => call(name, "Quit").catch(console.error));
|
|
98
|
-
for (const action of [refresh, quit]) action.set_style("font-size: 13px;
|
|
99
|
+
for (const action of [refresh, quit]) action.set_style("font-size: 13px; padding: 4px 12px; margin: 0; min-height: 0;");
|
|
99
100
|
button.menu.connect("open-state-changed", (_menu, open) => {
|
|
100
101
|
if (open) call(name, "Refresh", this._cancellable).catch(() => {});
|
|
101
102
|
});
|
|
@@ -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
|
-
|
|
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
|
|
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
|
|
74
|
-
|
|
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(
|
|
85
|
-
const text = stat.isFile() && !stat.isSymbolicLink() ? fs.readFileSync(
|
|
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: ${
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
100
|
-
fs.writeFileSync(
|
|
101
|
-
return
|
|
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
|
-
|
|
106
|
-
|
|
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
|
|
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
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
|
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(
|
|
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
|
-
|
|
155
|
-
|
|
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",
|
|
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
|
-
|
|
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 =
|
|
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
|
|