ai-battery 0.2.0 → 0.2.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.
Files changed (45) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +701 -31
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +23 -3
  7. package/docs/RELEASING.md +24 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/hud-preview.svg +43 -20
  10. package/docs/terminal-vertical-preview.svg +73 -0
  11. package/lib/cli.js +945 -219
  12. package/lib/core/atomic-rename.js +18 -0
  13. package/lib/core/cli-help.js +35 -7
  14. package/lib/core/cli-messages.js +45 -1
  15. package/lib/core/cli-output.js +277 -72
  16. package/lib/core/cli-wrappers.js +410 -0
  17. package/lib/core/config-editor.js +177 -29
  18. package/lib/core/display-config.js +45 -0
  19. package/lib/core/integration-files.js +32 -3
  20. package/lib/core/shared-bar.js +603 -0
  21. package/lib/core/statusline-git.js +179 -15
  22. package/lib/core/terminal.js +25 -7
  23. package/lib/core/tmux-status.js +172 -0
  24. package/lib/core/uninstall.js +20 -7
  25. package/lib/core/usage-store.js +85 -0
  26. package/lib/hud/launcher.js +29 -31
  27. package/lib/platforms/linux/hud.js +1 -1
  28. package/lib/platforms/linux/panel.js +1 -1
  29. package/lib/platforms/macos/hud.js +5 -5
  30. package/lib/platforms/process-scanner.js +77 -29
  31. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  32. package/lib/platforms/windows/codex-runner.js +178 -21
  33. package/lib/platforms/windows/hud/controls.ps1 +44 -10
  34. package/lib/platforms/windows/hud/main.ps1 +350 -43
  35. package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
  36. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  37. package/lib/platforms/windows/hud-launcher.js +153 -79
  38. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  39. package/lib/platforms/windows/terminal-compositor.js +210 -25
  40. package/lib/platforms/windows/wt-bar.js +729 -0
  41. package/lib/platforms/windows/wt-fragment.js +665 -0
  42. package/lib/platforms/windows/wt-keybinding.js +300 -0
  43. package/lib/providers/antigravity.js +155 -8
  44. package/package.json +5 -2
  45. package/vendor/PaneContext.cs +875 -0
@@ -1,9 +1,161 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
1
5
  import { execFileSync } from "node:child_process";
2
6
 
7
+ const branchChangesMemo = new Map();
8
+
9
+ export function findGitDir(dir) {
10
+ if (!dir) return null;
11
+ let current;
12
+ try {
13
+ current = path.resolve(String(dir));
14
+ if (!fs.statSync(current).isDirectory()) return null;
15
+ } catch {
16
+ return null;
17
+ }
18
+ for (let depth = 0; depth < 32; depth += 1) {
19
+ const candidate = path.join(current, ".git");
20
+ try {
21
+ const stat = fs.statSync(candidate);
22
+ if (stat.isDirectory()) return candidate;
23
+ if (stat.isFile()) {
24
+ const text = fs.readFileSync(candidate, "utf8");
25
+ const match = text.match(/^\s*gitdir:\s*(.+?)\s*$/m);
26
+ if (match) {
27
+ return path.resolve(current, match[1]);
28
+ }
29
+ }
30
+ } catch { /* Not here; walk up. */ }
31
+ const parent = path.dirname(current);
32
+ if (parent === current) break;
33
+ current = parent;
34
+ }
35
+ return null;
36
+ }
37
+
38
+ function commonGitDir(gitDir) {
39
+ try {
40
+ const commondir = fs.readFileSync(path.join(gitDir, "commondir"), "utf8").trim();
41
+ if (commondir) return path.resolve(gitDir, commondir);
42
+ } catch { /* Standard repo without worktree commondir. */ }
43
+ return gitDir;
44
+ }
45
+
46
+ function readLooseOrPackedRef(gitDir, refName) {
47
+ const dirs = [gitDir, commonGitDir(gitDir)];
48
+ for (const root of new Set(dirs)) {
49
+ try {
50
+ const text = fs.readFileSync(path.join(root, refName), "utf8").trim();
51
+ if (/^ref:\s+(.+)$/.test(text)) {
52
+ return readLooseOrPackedRef(gitDir, text.replace(/^ref:\s+/, "").trim());
53
+ }
54
+ if (/^[0-9a-f]{40,64}$/i.test(text)) return text.toLowerCase();
55
+ } catch { /* Try packed-refs. */ }
56
+ }
57
+ try {
58
+ const packed = fs.readFileSync(path.join(commonGitDir(gitDir), "packed-refs"), "utf8");
59
+ for (const line of packed.split(/\r?\n/)) {
60
+ if (!line || line.startsWith("#") || line.startsWith("^")) continue;
61
+ const space = line.indexOf(" ");
62
+ if (space > 0 && line.slice(space + 1).trim() === refName) {
63
+ return line.slice(0, space).trim().toLowerCase();
64
+ }
65
+ }
66
+ } catch { /* No packed-refs. */ }
67
+ return null;
68
+ }
69
+
70
+ function resolveFastBaseRef(gitDir) {
71
+ const common = commonGitDir(gitDir);
72
+ const remotesDir = path.join(common, "refs", "remotes");
73
+ let remotes = [];
74
+ try {
75
+ remotes = fs.readdirSync(remotesDir, { withFileTypes: true })
76
+ .filter(entry => entry.isDirectory())
77
+ .map(entry => entry.name);
78
+ } catch { /* No remotes dir. */ }
79
+ remotes.sort((a, b) => (a === "origin" ? -1 : b === "origin" ? 1 : a.localeCompare(b)));
80
+ for (const remote of remotes) {
81
+ try {
82
+ const sym = fs.readFileSync(path.join(remotesDir, remote, "HEAD"), "utf8").trim();
83
+ const match = sym.match(/^ref:\s+(refs\/remotes\/.+)$/);
84
+ if (match && match[1].startsWith(`refs/remotes/${remote}/`)) {
85
+ const sha = readLooseOrPackedRef(gitDir, match[1]);
86
+ if (sha) return { ref: match[1], sha };
87
+ }
88
+ } catch { /* No remote HEAD symref. */ }
89
+ }
90
+ for (const candidate of ["main", "master"]) {
91
+ const ref = `refs/heads/${candidate}`;
92
+ const sha = readLooseOrPackedRef(gitDir, ref);
93
+ if (sha) return { ref, sha };
94
+ }
95
+ return null;
96
+ }
97
+
98
+ export function readGitBranchFast(dir) {
99
+ const gitDir = findGitDir(dir);
100
+ if (!gitDir) return null;
101
+ try {
102
+ const head = fs.readFileSync(path.join(gitDir, "HEAD"), "utf8").trim();
103
+ const match = head.match(/^ref:\s+refs\/heads\/(.+)$/);
104
+ if (match) return match[1].trim() || null;
105
+ } catch { /* Fall back. */ }
106
+ return null;
107
+ }
108
+
109
+ function branchCacheFile(gitDir) {
110
+ const hash = crypto.createHash("sha256").update(gitDir).digest("hex").slice(0, 16);
111
+ return path.join(os.tmpdir(), `ai-battery-git-${hash}.json`);
112
+ }
113
+
114
+ function readBranchCache(gitDir, cacheKey) {
115
+ const mem = branchChangesMemo.get(gitDir);
116
+ if (mem && mem.key === cacheKey) return mem.value;
117
+ try {
118
+ const parsed = JSON.parse(fs.readFileSync(branchCacheFile(gitDir), "utf8"));
119
+ if (parsed && parsed.key === cacheKey && (typeof parsed.value === "string" || parsed.value === null)) {
120
+ branchChangesMemo.set(gitDir, parsed);
121
+ return parsed.value;
122
+ }
123
+ } catch { /* Cache miss. */ }
124
+ return undefined;
125
+ }
126
+
127
+ function writeBranchCache(gitDir, cacheKey, value) {
128
+ const record = { key: cacheKey, value };
129
+ branchChangesMemo.set(gitDir, record);
130
+ try {
131
+ const file = branchCacheFile(gitDir);
132
+ const tmp = `${file}.${process.pid}.tmp`;
133
+ fs.writeFileSync(tmp, JSON.stringify(record));
134
+ try { fs.renameSync(tmp, file); } finally { try { fs.unlinkSync(tmp); } catch {} }
135
+ } catch { /* Best-effort cache write. */ }
136
+ }
137
+
3
138
  // Match Codex's committed branch diff against the default branch merge base.
4
139
  // Only inspect local refs: status hooks must not block on network/auth prompts.
5
140
  export function branchChanges(dir) {
6
141
  if (!dir) return null;
142
+ const gitDir = findGitDir(dir);
143
+ if (!gitDir) return null;
144
+
145
+ let headSha = null;
146
+ try {
147
+ const head = fs.readFileSync(path.join(gitDir, "HEAD"), "utf8").trim();
148
+ if (head.startsWith("ref:")) headSha = readLooseOrPackedRef(gitDir, head.slice(4).trim());
149
+ else if (/^[0-9a-f]{40,64}$/i.test(head)) headSha = head.toLowerCase();
150
+ } catch { /* Fall through to git. */ }
151
+
152
+ const fastBase = resolveFastBaseRef(gitDir);
153
+ const cacheKey = headSha && fastBase ? `${headSha}:${fastBase.ref}:${fastBase.sha}` : null;
154
+ if (cacheKey) {
155
+ const cached = readBranchCache(gitDir, cacheKey);
156
+ if (cached !== undefined) return cached;
157
+ }
158
+
7
159
  const deadline = Date.now() + 900;
8
160
  const git = args => {
9
161
  const remaining = deadline - Date.now();
@@ -12,29 +164,39 @@ export function branchChanges(dir) {
12
164
  return execFileSync("git", ["-C", dir, ...args], {
13
165
  encoding: "utf8", stdio: ["ignore", "pipe", "ignore"],
14
166
  timeout: Math.min(250, remaining), maxBuffer: 4 * 1024 * 1024,
167
+ windowsHide: true,
15
168
  env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" }
16
169
  }).trim();
17
170
  } catch { return null; }
18
171
  };
19
- const remotes = (git(["remote"]) || "").split(/\r?\n/).filter(Boolean);
20
- remotes.sort((a, b) => (a === "origin" ? -1 : b === "origin" ? 1 : 0));
21
- let base = null;
22
- for (const remote of remotes) {
23
- const ref = git(["symbolic-ref", "--quiet", `refs/remotes/${remote}/HEAD`]);
24
- if (ref?.startsWith(`refs/remotes/${remote}/`) && git(["rev-parse", "--verify", "--quiet", ref])) {
25
- base = ref;
26
- break;
172
+
173
+ let base = fastBase?.ref || null;
174
+ if (!base) {
175
+ const remotes = (git(["remote"]) || "").split(/\r?\n/).filter(Boolean);
176
+ remotes.sort((a, b) => (a === "origin" ? -1 : b === "origin" ? 1 : 0));
177
+ for (const remote of remotes) {
178
+ const ref = git(["symbolic-ref", "--quiet", `refs/remotes/${remote}/HEAD`]);
179
+ if (ref?.startsWith(`refs/remotes/${remote}/`) && git(["rev-parse", "--verify", "--quiet", ref])) {
180
+ base = ref;
181
+ break;
182
+ }
183
+ }
184
+ if (!base) {
185
+ for (const candidate of ["main", "master"]) {
186
+ const ref = `refs/heads/${candidate}`;
187
+ if (git(["rev-parse", "--verify", "--quiet", ref])) { base = ref; break; }
188
+ }
27
189
  }
28
190
  }
29
191
  if (!base) {
30
- for (const candidate of ["main", "master"]) {
31
- const ref = `refs/heads/${candidate}`;
32
- if (git(["rev-parse", "--verify", "--quiet", ref])) { base = ref; break; }
33
- }
192
+ if (cacheKey) writeBranchCache(gitDir, cacheKey, null);
193
+ return null;
34
194
  }
35
- if (!base) return null;
36
195
  const mergeBase = git(["merge-base", "HEAD", base]);
37
- if (!mergeBase) return null;
196
+ if (!mergeBase) {
197
+ if (cacheKey) writeBranchCache(gitDir, cacheKey, null);
198
+ return null;
199
+ }
38
200
  const numstat = git(["diff", "--no-ext-diff", "--numstat", `${mergeBase}..HEAD`, "--"]);
39
201
  if (numstat === null) return null;
40
202
  let additions = 0, deletions = 0;
@@ -43,5 +205,7 @@ export function branchChanges(dir) {
43
205
  if (/^\d+$/.test(added)) additions += Number(added);
44
206
  if (/^\d+$/.test(removed)) deletions += Number(removed);
45
207
  }
46
- return `+${additions} -${deletions}`;
208
+ const value = `+${additions} -${deletions}`;
209
+ if (cacheKey) writeBranchCache(gitDir, cacheKey, value);
210
+ return value;
47
211
  }
@@ -144,11 +144,14 @@ function stripAnsi(text) {
144
144
  function charWidth(char) {
145
145
  const code = char.codePointAt(0);
146
146
  if (
147
- (code >= 0x0300 && code <= 0x036f)
147
+ code === 0x200d
148
+ || (code >= 0x0300 && code <= 0x036f)
148
149
  || (code >= 0x1ab0 && code <= 0x1aff)
149
150
  || (code >= 0x1dc0 && code <= 0x1dff)
150
151
  || (code >= 0x20d0 && code <= 0x20ff)
152
+ || (code >= 0xfe00 && code <= 0xfe0f)
151
153
  || (code >= 0xfe20 && code <= 0xfe2f)
154
+ || (code >= 0xe0100 && code <= 0xe01ef)
152
155
  ) {
153
156
  return 0;
154
157
  }
@@ -163,12 +166,27 @@ function charWidth(char) {
163
166
  || (code >= 0xfe30 && code <= 0xfe6f)
164
167
  || (code >= 0xff00 && code <= 0xff60)
165
168
  || (code >= 0xffe0 && code <= 0xffe6)
169
+ || (code >= 0x1f300 && code <= 0x1faff)
170
+ || (code >= 0x20000 && code <= 0x3fffd)
166
171
  ) {
167
172
  return 2;
168
173
  }
169
174
  return 1;
170
175
  }
171
176
 
177
+ function visibleClusters(text) {
178
+ const clusters = [];
179
+ for (const char of Array.from(text)) {
180
+ const width = charWidth(char);
181
+ if (width === 0 && clusters.length) {
182
+ clusters[clusters.length - 1].text += char;
183
+ } else {
184
+ clusters.push({ text: char, width });
185
+ }
186
+ }
187
+ return clusters;
188
+ }
189
+
172
190
  function visibleWidth(text) {
173
191
  return Array.from(stripAnsi(text)).reduce((width, char) => width + charWidth(char), 0);
174
192
  }
@@ -176,10 +194,10 @@ function visibleWidth(text) {
176
194
  function takeVisibleStart(text, maxWidth) {
177
195
  let width = 0;
178
196
  let output = "";
179
- for (const char of Array.from(text)) {
180
- const nextWidth = width + charWidth(char);
197
+ for (const cluster of visibleClusters(text)) {
198
+ const nextWidth = width + cluster.width;
181
199
  if (nextWidth > maxWidth) break;
182
- output += char;
200
+ output += cluster.text;
183
201
  width = nextWidth;
184
202
  }
185
203
  return output;
@@ -188,10 +206,10 @@ function takeVisibleStart(text, maxWidth) {
188
206
  function takeVisibleEnd(text, maxWidth) {
189
207
  let width = 0;
190
208
  let output = "";
191
- for (const char of Array.from(text).reverse()) {
192
- const nextWidth = width + charWidth(char);
209
+ for (const cluster of visibleClusters(text).reverse()) {
210
+ const nextWidth = width + cluster.width;
193
211
  if (nextWidth > maxWidth) break;
194
- output = char + output;
212
+ output = cluster.text + output;
195
213
  width = nextWidth;
196
214
  }
197
215
  return output;
@@ -0,0 +1,172 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+ import { spawnSync } from "node:child_process";
5
+ import { isDeepStrictEqual } from "node:util";
6
+
7
+ const TOKEN = "@ai_battery_tmux_token";
8
+ const SAVED = "@ai_battery_tmux_saved";
9
+ const PAUSED = "@ai_battery_tmux_paused";
10
+ const quote = text => "'" + String(text).replace(/'/g, "'\\''") + "'";
11
+ const rows = value => value === "off" ? 0 : value === "on" ? 1 : Number(value);
12
+
13
+ export function tmuxSocket() {
14
+ const result = spawnSync("tmux", ["display-message", "-p", "#{socket_path}"], { encoding: "utf8", timeout: 1500 });
15
+ return result.status === 0 ? result.stdout.trim() : null;
16
+ }
17
+
18
+ export function paneProviders(panes, processes, matches) {
19
+ const parents = new Map(processes.map(item => [item.pid, item]));
20
+ const roots = new Map();
21
+ for (const pane of panes.filter(item => !item.dead)) {
22
+ if (!roots.has(pane.pid)) roots.set(pane.pid, new Set());
23
+ roots.get(pane.pid).add(pane.session);
24
+ }
25
+ const result = new Map();
26
+ for (const process of processes) {
27
+ if (!process.hasTty) continue;
28
+ const providers = ["codex", "claude", "antigravity"].filter(provider => matches(process.cmdline, provider));
29
+ if (!providers.length) continue;
30
+ let pid = process.pid;
31
+ const seen = new Set();
32
+ while (pid && !seen.has(pid)) {
33
+ if (roots.has(pid)) {
34
+ for (const session of roots.get(pid)) {
35
+ if (!result.has(session)) result.set(session, new Set());
36
+ providers.forEach(provider => result.get(session).add(provider));
37
+ }
38
+ break;
39
+ }
40
+ seen.add(pid);
41
+ pid = parents.get(pid)?.ppid;
42
+ }
43
+ }
44
+ return result;
45
+ }
46
+
47
+ function processTree() {
48
+ if (process.platform !== "linux") {
49
+ const result = spawnSync("ps", ["-axo", "pid=,ppid=,tty=,args="], { encoding: "utf8", timeout: 1500, maxBuffer: 4 * 1024 * 1024 });
50
+ return String(result.stdout || "").split("\n").flatMap(line => {
51
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/);
52
+ return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), hasTty: !["??", "-"].includes(match[3]), cmdline: match[4] }] : [];
53
+ });
54
+ }
55
+ return fs.readdirSync("/proc").filter(name => /^\d+$/.test(name)).flatMap(name => {
56
+ try {
57
+ const stat = fs.readFileSync(path.join("/proc", name, "stat"), "utf8");
58
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
59
+ return [{ pid: Number(name), ppid: Number(fields[1]), hasTty: Number(fields[4]) !== 0,
60
+ cmdline: fs.readFileSync(path.join("/proc", name, "cmdline"), "utf8").replaceAll("\0", " ").trim() }];
61
+ } catch { return []; }
62
+ });
63
+ }
64
+
65
+ export function updateTmuxStatus({ socket, action = "tick", token, script, matches, renderUsage, config = "", position = "bottom" }) {
66
+ const run = (...args) => {
67
+ const result = spawnSync("tmux", ["-S", socket, ...args], { encoding: "utf8", timeout: 2000, maxBuffer: 2 * 1024 * 1024 });
68
+ if (result.status !== 0) throw new Error(result.stderr?.trim() || "tmux connection closed");
69
+ return result.stdout.replace(/\r?\n$/, "");
70
+ };
71
+ const get = (...args) => run("show-options", ...args);
72
+ const set = (...args) => run("set-option", ...args);
73
+ const currentToken = get("-gqv", TOKEN);
74
+ if (action === "start") {
75
+ const version = run("display-message", "-p", "#{version}").match(/^(\d+)\.(\d+)/);
76
+ if (version && Number(version[1]) <= 3 && (Number(version[1]) < 3 || Number(version[2]) < 2)) throw new Error("tmux 3.2 or newer is required");
77
+ token = crypto.randomBytes(12).toString("hex");
78
+ set("-g", TOKEN, token);
79
+ set("-g", "@ai_battery_tmux_config", config);
80
+ run("set-environment", "-g", "AI_BATTERY_TMUX_STATUS", "1");
81
+ } else if (!currentToken || (action === "tick" && token !== currentToken)) return;
82
+ if (action === "stop") {
83
+ if (config && get("-gqv", "@ai_battery_tmux_config") !== config) return;
84
+ set("-gu", TOKEN);
85
+ set("-gu", "@ai_battery_tmux_config");
86
+ run("set-environment", "-gu", "AI_BATTERY_TMUX_STATUS");
87
+ }
88
+
89
+ const sessionLines = run("list-sessions", "-F", "#{session_id}\t#{session_width}").split("\n").filter(Boolean);
90
+ const paneLines = run("list-panes", "-a", "-F", "#{session_id}\t#{pane_pid}\t#{pane_dead}").split("\n");
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);
93
+ const readFormats = (session, global = false) => {
94
+ const flags = global ? ["-g"] : ["-t", session];
95
+ const listing = get(...flags, "status-format");
96
+ return Object.fromEntries([...listing.matchAll(/^status-format\[(\d+)\]/gm)].map(match =>
97
+ [match[1], get("-v", ...flags, "status-format[" + match[1] + "]")]));
98
+ };
99
+ const writeFormats = (session, formats) => {
100
+ const commands = ["set-option", "-u", "-t", session, "status-format"];
101
+ for (const [index, value] of Object.entries(formats)) commands.push(";", "set-option", "-t", session, "status-format[" + index + "]", value);
102
+ run(...commands);
103
+ };
104
+ for (const line of sessionLines) {
105
+ const [session, sessionWidth] = line.split("\t");
106
+ if (action === "start" || action === "stop") set("-u", "-t", session, PAUSED);
107
+ if (action === "start") run("set-environment", "-t", session, "AI_BATTERY_TMUX_STATUS", "1");
108
+ if (action === "stop") run("set-environment", "-u", "-t", session, "AI_BATTERY_TMUX_STATUS");
109
+ let saved;
110
+ try { saved = JSON.parse(get("-qv", "-t", session, SAVED)); } catch { /* Not managed yet. */ }
111
+ const providers = active.get(session);
112
+ const currentFormats = saved ? readFormats(session) : null;
113
+ const manualChange = saved && Date.now() - (saved.updatedAt || 0) > 500 &&
114
+ (rows(get("-Av", "-t", session, "status")) !== saved.row + 1 || currentFormats[saved.row] !== saved.managed[saved.row]);
115
+ if (manualChange && action === "tick") set("-t", session, PAUSED, "1");
116
+ if (get("-qv", "-t", session, PAUSED) && !saved) continue;
117
+ if (providers?.size && !saved) {
118
+ const height = rows(get("-Av", "-t", session, "status"));
119
+ if (!Number.isInteger(height) || height < 1 || height >= 5) continue;
120
+ }
121
+ const widths = providers?.size ? run("list-clients", "-t", session, "-F", "#{client_width}").split("\n").map(Number).filter(value => value > 0) : [];
122
+ const text = providers?.size ? renderUsage(providers, widths.length ? Math.min(...widths) : (Number(sessionWidth) || 120)) : "";
123
+ if (!text || manualChange) {
124
+ if (!saved) continue;
125
+ const current = readFormats(session);
126
+ if (!saved.edited && isDeepStrictEqual(current, saved.managed)) writeFormats(session, saved.localFormats);
127
+ else if (current[saved.row] === saved.managed[saved.row]) {
128
+ if (saved.effective[saved.row] === undefined) set("-u", "-t", session, "status-format[" + saved.row + "]");
129
+ else set("-t", session, "status-format[" + saved.row + "]", saved.effective[saved.row]);
130
+ }
131
+ if (current[saved.row] === saved.managed[saved.row] && get("-Av", "-t", session, "status") === String(saved.row + 1).replace(/^1$/, "on")) {
132
+ if (saved.localStatus) set("-t", session, "status", saved.localStatus);
133
+ else set("-u", "-t", session, "status");
134
+ }
135
+ if (saved.managedPosition && get("-v", "-t", session, "status-position") === saved.managedPosition) {
136
+ if (saved.localStatusPosition) set("-t", session, "status-position", saved.localStatusPosition);
137
+ else set("-u", "-t", session, "status-position");
138
+ }
139
+ set("-u", "-t", session, SAVED);
140
+ continue;
141
+ }
142
+ const wasManaged = Boolean(saved);
143
+ if (!saved) {
144
+ const count = rows(get("-Av", "-t", session, "status"));
145
+ if (!Number.isInteger(count) || count < 1 || count >= 5) continue;
146
+ const localFormats = readFormats(session);
147
+ const effective = Object.keys(localFormats).length ? localFormats : readFormats(session, true);
148
+ const localStatusPosition = get("-v", "-t", session, "status-position") || null;
149
+ saved = { row: count, localStatus: get("-v", "-t", session, "status") || null, localStatusPosition, managedPosition: null, localFormats, effective, managed: effective };
150
+ }
151
+ const current = readFormats(session);
152
+ if (wasManaged && !isDeepStrictEqual(current, saved.managed)) saved.edited = true;
153
+ // Preserve edits made while the bar is active, including a replacement of
154
+ // the battery row itself. The first status row is otherwise unchanged.
155
+ if (current[saved.row] !== undefined && current[saved.row] !== saved.managed[saved.row] && get("-qv", "-t", session, SAVED)) continue;
156
+ const next = { ...(Object.keys(current).length ? current : saved.effective), [saved.row]: text };
157
+ if (!isDeepStrictEqual(current, next)) writeFormats(session, next);
158
+ const statusPosition = position === "top" ? "top" : "bottom";
159
+ if (get("-Av", "-t", session, "status-position") !== statusPosition) {
160
+ set("-t", session, "status-position", statusPosition);
161
+ saved.managedPosition = statusPosition;
162
+ }
163
+ saved.managed = next;
164
+ saved.updatedAt = Date.now();
165
+ set("-t", session, SAVED, JSON.stringify(saved));
166
+ if (rows(get("-Av", "-t", session, "status")) !== saved.row + 1) set("-t", session, "status", String(saved.row + 1));
167
+ }
168
+ if (action !== "stop" && get("-gqv", TOKEN) === token) {
169
+ const command = [process.execPath, script, "tick", "--socket", socket, "--token", token].map(quote).join(" ").replaceAll("#", "##");
170
+ run("run-shell", "-b", "-d", "2", command);
171
+ }
172
+ }
@@ -1,9 +1,10 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { isDisplayConfig } from "./display-config.js";
4
5
 
5
- const STATE_FILES = /^(?:(?:codex-status|windows-processes|wsl-windows-processes|claude-rate-limit-hit)-scan-cache\.json|(?:claude|antigravity)-statusline\.json|codex-account-usage\.json|windows-state-dir|hud-position\.json|hud-snapshot-[\w-]+\.json|linux-hud\.log|(?:tui|hud)-dock-(?:request|host)(?:-\d+)?\.json|macos-menu-(?:bar|detail)\.svg|codex-menu-bar-transparent\.png)(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$/;
6
- const HUD_FILES = new Set(["main.ps1", "controls.ps1", "dock.ps1", "native.ps1", "rendering.ps1", "snapshot.ps1", "windowing.ps1", "ai-battery-hud.ps1"]);
6
+ const STATE_FILES = /^(?:(?:codex-status|windows-processes|wsl-windows-processes|claude-rate-limit-hit)-scan-cache\.json|claude-rate-limit-hit\.json(?:\.lock)?|(?:claude|antigravity)-statusline\.json(?:\.lock)?|(?:codex|antigravity)-account-usage\.json(?:\.lock)?|display-config\.json\.lock|config\.json\.lock|windows-state-dir|windows-localappdata|process-refresh\.stamp|hud-position\.json|hud-snapshot(?:-[\w-]+)?\.json|linux-hud\.log|(?:tui|hud)-dock-(?:request|host)(?:-\d+)?\.json|macos-menu-(?:bar|detail)\.svg|codex-menu-bar-transparent\.png)(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$|^(?:config|display-config)\.json\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp$/;
7
+ const HUD_FILES = new Set(["main.ps1", "controls.ps1", "dock.ps1", "native.ps1", "rendering.ps1", "snapshot.ps1", "windowing.ps1", "ai-battery-hud.ps1", "shared-overlay.ps1"]);
7
8
 
8
9
  function lstat(file) {
9
10
  try { return fs.lstatSync(file); } catch (error) { if (error.code === "ENOENT") return null; throw error; }
@@ -43,9 +44,13 @@ export function cleanupBatteryArtifacts({ roots, home = os.homedir(), protectedR
43
44
  const file = path.join(directory, entry.name);
44
45
  if (entry.isSymbolicLink()) { result.retained.push(file); continue; }
45
46
  if (entry.isDirectory()) {
46
- const childKind = kind === "root" && ["bin", "hud", "linux-hud", "runtimes", "claude-statusline-sessions", "claude-hud-sessions"].includes(entry.name)
47
+ const childKind = kind === "root" && ["bin", "hud", "hud-cache", "linux-hud", "runtimes", "claude-statusline-sessions", "claude-hud-sessions", "pane-sharing", "shared-bars"].includes(entry.name)
47
48
  ? entry.name
48
- : kind === "runtimes" && /^(?:node-v\d+\.\d+\.\d+-win-(?:x64|arm64)|\.node-download-[\w-]+)$/.test(entry.name) ? "runtime" : null;
49
+ : kind === "runtimes" && /^(?:node-v\d+\.\d+\.\d+-win-(?:x64|arm64)|\.node-download-[\w-]+)$/.test(entry.name) ? "runtime"
50
+ : ["pane-sharing", "shared-bars"].includes(kind) && /^\d+$/.test(entry.name) ? "pane-window"
51
+ : kind === "pane-window" && /^(?:tab-[a-f0-9]{16}|window)$/.test(entry.name) ? "pane-tab"
52
+ : kind === "pane-tab" && entry.name === "sessions" ? "pane-sessions"
53
+ : ["pane-window", "pane-tab"].includes(kind) && ["election.lock", "trigger.lock"].includes(entry.name) ? "pane-lock" : null;
49
54
  if (childKind) { visit(file, childKind); prune(file); }
50
55
  else result.retained.push(file);
51
56
  continue;
@@ -55,12 +60,20 @@ export function cleanupBatteryArtifacts({ roots, home = os.homedir(), protectedR
55
60
  const config = readJson(file);
56
61
  owned = isBatteryConfig(config) && !config.codexWrapper && !config.codexStatusLineBackup && !config.claudeStatusLineBackup && !config.antigravityStatusLineBackup && !Object.keys(config.integrationFiles || {}).length;
57
62
  }
63
+ if (kind === "root" && entry.name === "display-config.json") {
64
+ owned = isDisplayConfig(readJson(file));
65
+ }
58
66
  if (["claude-statusline-sessions", "claude-hud-sessions"].includes(kind)) {
59
- owned = /^[\w-]+\.json(?:\.\d+\.tmp)?$/.test(entry.name)
67
+ owned = /^[\w.-]+\.json(?:\.\d+(?:\.\d+)?(?:\.[a-z0-9]+)?\.tmp)?$/.test(entry.name)
60
68
  && (entry.name.endsWith(".tmp") || readJson(file)?.provider === "claude" || kind === "claude-hud-sessions");
61
69
  }
62
- if (kind === "bin") owned = /^(?:rowpty\.exe|conpty\.dll|OpenConsole\.exe|rowpty\.src\.sha256)(?:\.old-[\w.-]+)?$/.test(entry.name);
63
- if (kind === "hud") owned = HUD_FILES.has(entry.name);
70
+ if (kind === "bin") owned = /^(?:(?:rowpty\.exe|conpty\.dll|OpenConsole\.exe|rowpty\.src\.sha256)(?:\.old(?:-[\w.-]+)?)?|rowpty\.build-\d+\.exe)$/.test(entry.name);
71
+ if (kind === "bin" && /^pane-context-(?:[a-f0-9]{16}|build-\d+)\.exe$/.test(entry.name)) owned = true;
72
+ if (kind === "bin" && /^pane-context-src-\d+\.cs$/.test(entry.name)) owned = true;
73
+ if (["pane-sharing", "shared-bars"].includes(kind)) owned = /^context-[a-f0-9]{24}\.json(?:\.\d+(?:\.[a-f0-9]+)?\.tmp)?$/.test(entry.name);
74
+ if (["pane-window", "pane-tab"].includes(kind)) owned = /^(?:owner|bar|trigger|dismissed)\.json(?:\.lock|\.\d+(?:\.[a-f0-9]+)?\.tmp)?$/.test(entry.name);
75
+ if (kind === "pane-sessions") owned = /^console-\d+\.json(?:\.\d+\.[a-f0-9]+\.tmp)?$/.test(entry.name);
76
+ if (kind === "hud" || kind === "hud-cache") owned = HUD_FILES.has(entry.name) || /^(?:shared-overlay|rendering)\.ps1\.\d+(?:\.[a-f0-9]+)?\.tmp$/.test(entry.name);
64
77
  if (kind === "linux-hud") owned = /^(?:icon|detail)-[a-f0-9]{64}\.svg$/.test(entry.name);
65
78
  if (kind === "runtimes") owned = /^\.node-\d+\.\d+\.\d+-(?:x64|arm64)\.lock$/.test(entry.name);
66
79
  if (kind === "runtime") owned = /^(?:node\.exe|extract\.ps1|SHASUMS256\.txt|node-v\d+\.\d+\.\d+-win-(?:x64|arm64)\.zip)$/.test(entry.name);
@@ -0,0 +1,85 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+
5
+ const SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
6
+ const RETRYABLE_LOCK_CODES = new Set(["EEXIST", "EPERM", "EACCES", "EBUSY"]);
7
+
8
+ // Exclusive lockfile helper safe across Windows and WSL/NTFS (DrvFs), where
9
+ // concurrent unlinks can transiently surface EPERM/EACCES/EBUSY alongside EEXIST.
10
+ export function withFileLock(lockFile, fn, { timeoutMs = 1500, staleMs = 10000, retryMs = 10 } = {}) {
11
+ const identity = crypto.randomBytes(8).toString("hex");
12
+ const deadline = Date.now() + Math.max(0, Number(timeoutMs) || 0);
13
+ const stepMs = Math.max(1, Number(retryMs) || 10);
14
+ let held = false;
15
+
16
+ fs.mkdirSync(path.dirname(lockFile), { recursive: true });
17
+ for (;;) {
18
+ try {
19
+ fs.writeFileSync(lockFile, identity, { flag: "wx", mode: 0o600 });
20
+ held = true;
21
+ break;
22
+ } catch (error) {
23
+ if (!RETRYABLE_LOCK_CODES.has(error?.code)) throw error;
24
+ let staleBroken = false;
25
+ if (error.code === "EEXIST") {
26
+ try {
27
+ const stat = fs.statSync(lockFile);
28
+ if (Date.now() - stat.mtimeMs > staleMs) {
29
+ const staleId = fs.readFileSync(lockFile, "utf8");
30
+ if (Date.now() - fs.statSync(lockFile).mtimeMs > staleMs && fs.readFileSync(lockFile, "utf8") === staleId) {
31
+ fs.unlinkSync(lockFile);
32
+ staleBroken = true;
33
+ }
34
+ }
35
+ } catch { /* Another writer released it. */ }
36
+ }
37
+ const remaining = deadline - Date.now();
38
+ if (staleBroken && remaining >= 0) continue;
39
+ if (remaining <= 0) break;
40
+ Atomics.wait(SLEEP_BUFFER, 0, 0, Math.min(stepMs, remaining));
41
+ }
42
+ }
43
+
44
+ if (!held) {
45
+ const error = new Error(`Timed out waiting for lock: ${lockFile}`);
46
+ error.code = "EBUSY";
47
+ throw error;
48
+ }
49
+
50
+ try {
51
+ return fn();
52
+ } finally {
53
+ for (let attempt = 0; attempt < 6; attempt += 1) {
54
+ try {
55
+ if (fs.readFileSync(lockFile, "utf8") === identity) fs.unlinkSync(lockFile);
56
+ break;
57
+ } catch (error) {
58
+ if (error?.code === "ENOENT" || !RETRYABLE_LOCK_CODES.has(error?.code) || attempt >= 5) break;
59
+ Atomics.wait(SLEEP_BUFFER, 0, 0, Math.min(20, 5 * (attempt + 1)));
60
+ }
61
+ }
62
+ }
63
+ }
64
+
65
+ // Windows and WSL publishers may update the same account snapshot at once.
66
+ // Serialize the compare/write so an older observation cannot win that race.
67
+ export function publishNewest(file, value, { read, write, timestamp }) {
68
+ const current = read(file);
69
+ const currentTime = Date.parse(timestamp(current) || "");
70
+ const nextTime = Date.parse(timestamp(value) || "");
71
+ if (!Number.isFinite(nextTime) || (Number.isFinite(currentTime) && currentTime >= nextTime)) {
72
+ return { value: current, changed: false };
73
+ }
74
+ try {
75
+ return withFileLock(`${file}.lock`, () => {
76
+ const previous = read(file);
77
+ const before = Date.parse(timestamp(previous) || "");
78
+ if (Number.isFinite(before) && before >= nextTime) return { value: previous, changed: false };
79
+ write(file, value);
80
+ return { value, changed: true };
81
+ });
82
+ } catch {
83
+ return { value: read(file), changed: false };
84
+ }
85
+ }