ai-battery 0.2.0 → 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.
Files changed (48) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-rail.applescript +227 -0
  3. package/bin/ai-battery-macos-status.applescript +5 -12
  4. package/bin/ai-battery-run +701 -31
  5. package/bin/ai-battery-tmux.js +17 -0
  6. package/bin/terminal-compositor.js +111 -0
  7. package/docs/REFERENCE.md +23 -3
  8. package/docs/RELEASING.md +30 -7
  9. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  10. package/docs/hud-preview.svg +75 -20
  11. package/docs/terminal-vertical-preview.svg +73 -0
  12. package/lib/cli.js +1148 -240
  13. package/lib/core/atomic-rename.js +18 -0
  14. package/lib/core/cli-help.js +57 -12
  15. package/lib/core/cli-messages.js +45 -1
  16. package/lib/core/cli-output.js +277 -72
  17. package/lib/core/cli-wrappers.js +410 -0
  18. package/lib/core/config-editor.js +194 -29
  19. package/lib/core/display-config.js +45 -0
  20. package/lib/core/integration-files.js +32 -3
  21. package/lib/core/shared-bar.js +603 -0
  22. package/lib/core/statusline-git.js +179 -15
  23. package/lib/core/terminal.js +25 -7
  24. package/lib/core/tmux-status.js +172 -0
  25. package/lib/core/uninstall.js +20 -7
  26. package/lib/core/usage-store.js +85 -0
  27. package/lib/hud/launcher.js +32 -33
  28. package/lib/platforms/linux/gnome-extension/extension.js +7 -6
  29. package/lib/platforms/linux/hud.js +157 -42
  30. package/lib/platforms/linux/panel.js +16 -3
  31. package/lib/platforms/linux/rail.js +412 -0
  32. package/lib/platforms/macos/hud.js +152 -44
  33. package/lib/platforms/process-scanner.js +77 -29
  34. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  35. package/lib/platforms/windows/codex-runner.js +178 -21
  36. package/lib/platforms/windows/hud/controls.ps1 +65 -15
  37. package/lib/platforms/windows/hud/main.ps1 +715 -54
  38. package/lib/platforms/windows/hud/rendering.ps1 +1284 -2
  39. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  40. package/lib/platforms/windows/hud-launcher.js +234 -81
  41. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  42. package/lib/platforms/windows/terminal-compositor.js +210 -25
  43. package/lib/platforms/windows/wt-bar.js +729 -0
  44. package/lib/platforms/windows/wt-fragment.js +665 -0
  45. package/lib/platforms/windows/wt-keybinding.js +300 -0
  46. package/lib/providers/antigravity.js +155 -8
  47. package/package.json +6 -2
  48. package/vendor/PaneContext.cs +875 -0
package/lib/cli.js CHANGED
@@ -6,7 +6,7 @@ import windowsLauncher from "../bin/codex-wrapper-win.cjs";
6
6
  import https from "node:https";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
9
- import { execFileSync, spawnSync } from "node:child_process";
9
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
10
10
  import { createRequire } from "node:module";
11
11
  import { fileURLToPath, pathToFileURL } from "node:url";
12
12
  import { isDeepStrictEqual } from "node:util";
@@ -19,12 +19,20 @@ import { cleanupBatteryArtifacts, isBatteryConfig } from "./core/uninstall.js";
19
19
  import { createIntegrationFiles } from "./core/integration-files.js";
20
20
  import { cliError, cliText, helpText, invalidChoice, requiredValue } from "./core/cli-help.js";
21
21
  import { errorText, messageText as cliMessageText } from "./core/cli-messages.js";
22
- import { formatClaudeResult, formatDoctorResult, formatResetResult, formatSetupResult, formatVisibilityResult } from "./core/cli-output.js";
22
+ import { formatClaudeResult, formatDoctorResult, formatResetResult, formatSetupResult, formatSplitBarModeResult, formatSplitBarStatus, formatVisibilityResult } from "./core/cli-output.js";
23
23
  import { codexTerminalDisplay, claudeTerminalDisplay } from "./core/diagnostics.js";
24
- import { PROVIDERS, STATUS_LINE_ITEMS, normalizeOrder, parseOrder, orderResults, providerId, providerLabel } from "./core/display-config.js";
24
+ import { BAR_POSITIONS, DEFAULT_SIDEBAR_WIDTH, PROVIDERS, SPLIT_BAR_MODES, STATUS_LINE_ITEMS, defaultDisplayConfig, isDisplayConfig, normalizeBarPosition, normalizeOrder, normalizeSidebarWidth, normalizeSplitBarMode, parseOrder, orderResults, providerId, providerLabel } from "./core/display-config.js";
25
25
  import { canEditConfig, editDisplayConfig } from "./core/config-editor.js";
26
- import { branchChanges } from "./core/statusline-git.js";
26
+ import { installCliPositionWrappers, posixCliWrapperDir, uninstallCliPositionWrappers } from "./core/cli-wrappers.js";
27
+ import { branchChanges, readGitBranchFast } from "./core/statusline-git.js";
27
28
  import { createAntigravityIntegration } from "./providers/antigravity.js";
29
+ import { cleanupPaneAiSession, createCrossOsSessionAlive, diagnosePaneContextHelper, isPaneSharedBarActive, isWslWtContext, paneUsageDecision, preparePaneContextHelper, readConfiguredBarPosition, readConfiguredSplitBarPosition, resolveSplitBarMode } from "./platforms/windows/shared-bar-platform.js";
30
+ import { listActiveAiSessions, sharedBarLeasePath, validBarContext } from "./core/shared-bar.js";
31
+ import { installWtFragment, removeWtFragment, diagnoseWtFragment, updateWtFragmentPosition } from "./platforms/windows/wt-fragment.js";
32
+ import { runSharedBar } from "./platforms/windows/wt-bar.js";
33
+ import { tmuxSocket } from "./core/tmux-status.js";
34
+ import { publishNewest, withFileLock } from "./core/usage-store.js";
35
+ import { atomicRename } from "./core/atomic-rename.js";
28
36
  import {
29
37
  cacheAgeSeconds,
30
38
  clamp,
@@ -59,14 +67,14 @@ const DEFAULT_TAIL_BYTES = 4 * 1024 * 1024;
59
67
  const DEFAULT_MAX_FILES = 40;
60
68
  const CLAUDE_LIMIT_HIT_TAIL_BYTES = 256 * 1024;
61
69
  const CLAUDE_LIMIT_HIT_MAX_FILES = 80;
62
- const CLAUDE_CODEX_CACHE_SECONDS = 60;
63
- const CLAUDE_CODEX_FALLBACK_CACHE_SECONDS = 15;
64
70
  const BACKGROUND_USAGE_RUNNING_SECONDS = 5 * 60;
65
71
  const DIVIDER = "│";
66
72
  const PROVIDER_DIVIDER = "┃";
67
73
  const DEFAULT_STATUSLINE_COLUMN_GUARD = 4;
68
74
  const COMMANDS = new Set([
69
75
  "setup",
76
+ "split",
77
+ "bar",
70
78
  "reset",
71
79
  "teardown",
72
80
  "uninstall",
@@ -80,7 +88,12 @@ const COMMANDS = new Set([
80
88
  "install-claude-statusline",
81
89
  "uninstall-claude-statusline"
82
90
  ]);
83
- const TEARDOWN_TARGETS = [...PROVIDERS, "hud", "tmux"];
91
+ const SPLIT_SUBCOMMANDS = ["status", "on", "auto", "manual", "off", "bottom", "top", "left", "right", "position"];
92
+ const TEARDOWN_TARGETS = [...PROVIDERS, "hud", "tmux", "split"];
93
+
94
+ function normalizeTarget(value) {
95
+ return providerId(value);
96
+ }
84
97
  const CODEX_WRAPPER_MARKER = "AI_BATTERY_MANAGED_CODEX_WRAPPER";
85
98
  const CODEX_WRAPPER_BRIDGE_MARKER = "AI_BATTERY_MANAGED_CODEX_BRIDGE";
86
99
  const CODEX_PATH_LOOKUP_MARKER = "AI_BATTERY_CODEX_PATH_LOOKUP=1";
@@ -89,7 +102,7 @@ const CODEX_PREFERRED_BACKUP_SUFFIX = ".ai-battery-original-link";
89
102
  const CODEX_TIMESTAMP_BACKUP_MARKER = ".ai-battery-backup-";
90
103
  const CODEX_STATUS_LINE = STATUS_LINE_ITEMS;
91
104
  const DEFAULT_STATUSLINE_HEADER_COLUMN_GUARD = 2;
92
- const CODEX_MENU_BAR_COLOR = "#000000";
105
+ const CODEX_MENU_BAR_COLOR = "#FFFFFF";
93
106
  const CLAUDE_MENU_BAR_COLOR = "#D97706";
94
107
  const MENU_BAR_WHITE = "#FFFFFF";
95
108
  const MENU_DETAIL_GREEN = "#30D158";
@@ -117,18 +130,32 @@ function parseArgs(argv) {
117
130
  menuBar: false,
118
131
  menuBarImage: false,
119
132
  menuDetailImage: false,
133
+ railImage: false,
134
+ railScale: 1,
135
+ railText: null,
136
+ panelText: null,
137
+ codexIcon: null,
120
138
  hudState: false,
121
139
  silent: false,
122
140
  force: false,
123
141
  wrapCodex: true,
124
142
  configureCodexStatusLine: true,
125
143
  providerOrder: null,
144
+ barPosition: null,
126
145
  attachHud: false,
146
+ refreshProcesses: false,
147
+ paneDecisionProvider: null,
148
+ paneCleanupProvider: null,
149
+ sharedBarState: null,
150
+ ownerPid: 0,
151
+ paneCols: 0,
152
+ paneRows: 0,
127
153
  header: true,
128
154
  usageRow: "auto",
129
155
  help: argv.length === 0,
130
156
  helpTopic: "",
131
157
  version: false,
158
+ subcommand: "",
132
159
  targets: [],
133
160
  rest: []
134
161
  };
@@ -148,6 +175,16 @@ function parseArgs(argv) {
148
175
  } else if (args.command === "reset" && !resetAliasSeen && !args.targets.length && ["settings", "config"].includes(arg)) {
149
176
  // Keep the previous reset settings/config syntax for existing scripts.
150
177
  resetAliasSeen = true;
178
+ } else if (!arg.startsWith("-") && args.command === "split") {
179
+ if (args.subcommand === "position" && !args.barPosition) {
180
+ const nextPos = normalizeBarPosition(arg, null);
181
+ if (!nextPos) throw invalidChoice("position", BAR_POSITIONS.join(", "), "split");
182
+ args.barPosition = nextPos;
183
+ } else if (args.subcommand) {
184
+ throw cliError(`Unexpected argument: ${arg}.`, `불필요한 인자: ${arg}.`, "split");
185
+ } else {
186
+ args.subcommand = arg;
187
+ }
151
188
  } else if (!arg.startsWith("-") && ["setup", "reset", "teardown", "uninstall", "on", "off"].includes(args.command)) {
152
189
  args.targets.push(arg);
153
190
  } else if (arg === "--provider" || arg === "-p") {
@@ -183,8 +220,37 @@ function parseArgs(argv) {
183
220
  try { args.providerOrder = parseOrder(value, PROVIDERS, "--provider-order"); }
184
221
  catch { throw cliError("--provider-order requires unique comma-separated tools: codex, claude, gemini.", "--provider-order에 codex, claude, gemini를 쉼표로 구분하고 중복 없이 입력하세요.", args.command); }
185
222
  i += 1;
223
+ } else if (arg === "--position") {
224
+ const value = requiredValue(argv, i, args.command);
225
+ const nextPos = normalizeBarPosition(value, null);
226
+ if (!nextPos) throw invalidChoice("--position", BAR_POSITIONS.join(", "), args.command);
227
+ args.barPosition = nextPos;
228
+ i += 1;
229
+ } else if (arg === "--interval") {
230
+ args.interval = Math.max(1, Number(requiredValue(argv, i, args.command)) || 2);
231
+ i += 1;
186
232
  } else if (arg === "--attach-hud") {
187
233
  args.attachHud = true;
234
+ } else if (arg === "--refresh-processes") {
235
+ args.refreshProcesses = true;
236
+ } else if (arg === "--pane-decision") {
237
+ args.paneDecisionProvider = requiredValue(argv, i, args.command);
238
+ i += 1;
239
+ } else if (arg === "--pane-cleanup") {
240
+ args.paneCleanupProvider = requiredValue(argv, i, args.command);
241
+ i += 1;
242
+ } else if (arg === "--shared-bar-state") {
243
+ args.sharedBarState = requiredValue(argv, i, args.command);
244
+ i += 1;
245
+ } else if (arg === "--owner-pid") {
246
+ args.ownerPid = Math.max(0, Math.trunc(Number(requiredValue(argv, i, args.command)) || 0));
247
+ i += 1;
248
+ } else if (arg === "--cols") {
249
+ args.paneCols = Math.max(0, Math.trunc(Number(requiredValue(argv, i, args.command)) || 0));
250
+ i += 1;
251
+ } else if (arg === "--rows") {
252
+ args.paneRows = Math.max(0, Math.trunc(Number(requiredValue(argv, i, args.command)) || 0));
253
+ i += 1;
188
254
  } else if (arg === "--watch" || arg === "-w") {
189
255
  args.watch = true;
190
256
  const maybeInterval = argv[i + 1];
@@ -217,6 +283,35 @@ function parseArgs(argv) {
217
283
  } else if (arg === "--menu-detail-image") {
218
284
  args.menuDetailImage = true;
219
285
  args.style = "plain";
286
+ } else if (arg === "--rail-image") {
287
+ args.railImage = true;
288
+ args.style = "plain";
289
+ } else if (arg === "--rail-scale") {
290
+ const value = Number(requiredValue(argv, i, args.command));
291
+ if (!Number.isFinite(value) || value < 0.5 || value > 3) {
292
+ throw cliError("--rail-scale must be between 0.5 and 3.0.", "--rail-scale은 0.5에서 3.0 사이여야 합니다.", args.helpTopic);
293
+ }
294
+ args.railScale = value;
295
+ i += 1;
296
+ } else if (arg === "--rail-text") {
297
+ const value = String(requiredValue(argv, i, args.command)).trim().toLowerCase();
298
+ if (!["white", "black"].includes(value)) throw invalidChoice(arg, "white, black", args.helpTopic);
299
+ args.railText = value;
300
+ i += 1;
301
+ } else if (arg === "--panel-text") {
302
+ const value = String(requiredValue(argv, i, args.command)).trim().toLowerCase();
303
+ if (!["white", "black"].includes(value)) throw invalidChoice(arg, "white, black", args.helpTopic);
304
+ args.panelText = value;
305
+ i += 1;
306
+ } else if (arg === "--codex-icon") {
307
+ const value = String(requiredValue(argv, i, args.command)).trim().toLowerCase();
308
+ if (!["white", "black"].includes(value)) throw invalidChoice(arg, "white, black", args.helpTopic);
309
+ args.codexIcon = value;
310
+ i += 1;
311
+ } else if (arg.startsWith("--codex-icon=")) {
312
+ const value = arg.slice(arg.indexOf("=") + 1).trim().toLowerCase();
313
+ if (!["white", "black"].includes(value)) throw invalidChoice("--codex-icon", "white, black", args.helpTopic);
314
+ args.codexIcon = value;
220
315
  } else if (arg === "--hud-state") {
221
316
  args.hudState = true;
222
317
  args.style = "plain";
@@ -238,7 +333,7 @@ function parseArgs(argv) {
238
333
  args.helpTopic = commandSeen ? args.command : "";
239
334
  args.provider = providerId(args.provider);
240
335
  args.activeProvider = providerId(args.activeProvider);
241
- args.targets = args.targets.map(providerId);
336
+ args.targets = args.targets.map(normalizeTarget);
242
337
  if (!["all", ...PROVIDERS].includes(args.provider)) {
243
338
  throw invalidChoice("--provider", "all, codex, claude, gemini", args.helpTopic);
244
339
  }
@@ -246,11 +341,24 @@ function parseArgs(argv) {
246
341
  throw invalidChoice("--active-provider", "codex, claude, gemini", args.helpTopic);
247
342
  }
248
343
  if (args.providerOrder && !["config", "setup"].includes(args.command)) throw cliError("--provider-order requires config or setup.", "--provider-order는 config 또는 setup에서 사용하세요.", args.helpTopic);
344
+ if (args.barPosition && !["config", "setup", "split"].includes(args.command)) throw cliError("--position requires config, setup, or split.", "--position은 config, setup 또는 split에서 사용하세요.", args.helpTopic);
345
+ if (args.command === "split") {
346
+ if (args.subcommand && !SPLIT_SUBCOMMANDS.includes(args.subcommand)) {
347
+ throw invalidChoice("subcommand", SPLIT_SUBCOMMANDS.join(", "), "split");
348
+ }
349
+ if (args.subcommand === "position" && !args.barPosition) {
350
+ throw invalidChoice("position", BAR_POSITIONS.join(", "), "split");
351
+ }
352
+ }
249
353
  if (args.targets.length) {
250
- const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "all"]
354
+ const choices = args.command === "setup" ? [...PROVIDERS, "tmux", "split", "all"]
251
355
  : ["on", "off"].includes(args.command) ? [...PROVIDERS, "all"] : [...TEARDOWN_TARGETS, "all"];
252
356
  if (args.targets.some((target) => !choices.includes(target))) {
253
- throw invalidChoice("target", choices.map(target => target === "antigravity" ? "gemini" : target).join(", "), args.command);
357
+ throw invalidChoice(
358
+ "target",
359
+ choices.map(target => (target === "antigravity" ? "gemini" : target)).join(", "),
360
+ args.command
361
+ );
254
362
  }
255
363
  }
256
364
 
@@ -306,6 +414,12 @@ function legacyStateDir() {
306
414
  return homePath(".local", "state", "claudex-battery");
307
415
  }
308
416
 
417
+ function hasCustomXdgStateHome() {
418
+ const xdg = String(process.env.XDG_STATE_HOME || "").trim();
419
+ if (!xdg) return false;
420
+ return path.resolve(xdg) !== path.resolve(userHome(), ".local", "state");
421
+ }
422
+
309
423
  let windowsStateDirForWslMemo;
310
424
  function windowsStateDirForWsl() {
311
425
  // Account usage is shared between native Windows and WSL without sharing the
@@ -315,7 +429,7 @@ function windowsStateDirForWsl() {
315
429
  if (override) return override;
316
430
  // An explicit state directory is an isolation boundary for tests, portable
317
431
  // installs, and users who do not want state written to the Windows profile.
318
- if (process.env.AI_BATTERY_STATE_DIR || process.env.CLAUDEX_BATTERY_STATE_DIR) return null;
432
+ if (process.env.AI_BATTERY_STATE_DIR || process.env.CLAUDEX_BATTERY_STATE_DIR || hasCustomXdgStateHome()) return null;
319
433
  if (windowsStateDirForWslMemo !== undefined) return windowsStateDirForWslMemo;
320
434
 
321
435
  // Cache the resolved path: the statusline can run every second (refreshInterval)
@@ -331,7 +445,8 @@ function windowsStateDirForWsl() {
331
445
 
332
446
  let resolved = null;
333
447
  try {
334
- const home = spawnSync("cmd.exe", ["/c", "echo %USERPROFILE%"], { encoding: "utf8", timeout: 2000 });
448
+ const cmdExe = fs.existsSync("/mnt/c/Windows/System32/cmd.exe") ? "/mnt/c/Windows/System32/cmd.exe" : "cmd.exe";
449
+ const home = spawnSync(cmdExe, ["/c", "echo %USERPROFILE%"], { encoding: "utf8", timeout: 2000 });
335
450
  const winHome = String(home.stdout || "").trim();
336
451
  if (home.status === 0 && /^[A-Za-z]:\\/.test(winHome)) {
337
452
  const conv = spawnSync("wslpath", ["-u", winHome], { encoding: "utf8", timeout: 2000 });
@@ -356,14 +471,22 @@ function windowsStateDirForWsl() {
356
471
  return resolved;
357
472
  }
358
473
 
359
- function claudeStateDir() {
474
+ function sharedStateDir() {
475
+ const override = String(process.env.AI_BATTERY_SHARED_USAGE_STATE_DIR || "").trim();
476
+ if (override) return override;
360
477
  return windowsStateDirForWsl() || stateDir();
361
478
  }
362
479
 
480
+ function claudeStateDir() {
481
+ return sharedStateDir();
482
+ }
483
+
363
484
  function codexUsageStateDir() {
364
- const override = String(process.env.AI_BATTERY_SHARED_USAGE_STATE_DIR || "").trim();
365
- if (override) return override;
366
- return windowsStateDirForWsl() || stateDir();
485
+ return sharedStateDir();
486
+ }
487
+
488
+ function displayConfigPath() {
489
+ return path.join(sharedStateDir(), "display-config.json");
367
490
  }
368
491
 
369
492
  function claudeCachePath() {
@@ -433,19 +556,149 @@ function writeConfig(config) {
433
556
  writeJsonAtomic(configPath(), config);
434
557
  }
435
558
 
559
+ function normalizeDisplayConfig(stored) {
560
+ const defaults = defaultDisplayConfig();
561
+ return {
562
+ version: 1,
563
+ providers: Object.fromEntries(PROVIDERS.map(provider => [provider, stored?.providers?.[provider] !== false])),
564
+ providerOrder: normalizeOrder(stored?.providerOrder, defaults.providerOrder),
565
+ splitBar: normalizeSplitBarMode(stored?.splitBar, defaults.splitBar),
566
+ barPosition: normalizeBarPosition(stored?.barPosition, defaults.barPosition),
567
+ splitBarPosition: stored?.splitBarPosition ? normalizeBarPosition(stored.splitBarPosition, null) : null,
568
+ sidebarWidth: normalizeSidebarWidth(stored?.sidebarWidth, defaults.sidebarWidth)
569
+ };
570
+ }
571
+
572
+ function readDisplayConfig(options = {}) {
573
+ const target = displayConfigPath();
574
+ if (fs.existsSync(target)) {
575
+ const parsed = readJson(target);
576
+ if (options.strict) {
577
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
578
+ throw new Error(`AI Battery display config is invalid and was left untouched: ${target}`);
579
+ }
580
+ if (!isDisplayConfig(parsed)) {
581
+ throw new Error(`AI Battery display config ownership could not be verified; file was left untouched: ${target}`);
582
+ }
583
+ if (parsed.providers !== undefined
584
+ && (!parsed.providers || typeof parsed.providers !== "object" || Array.isArray(parsed.providers))) {
585
+ throw new Error(`AI Battery display config providers must be a JSON object: ${target}`);
586
+ }
587
+ if (parsed.providerOrder !== undefined && !Array.isArray(parsed.providerOrder)) {
588
+ throw new Error(`AI Battery display config providerOrder must be a JSON array: ${target}`);
589
+ }
590
+ if (parsed.splitBar !== undefined && !SPLIT_BAR_MODES.includes(parsed.splitBar)) {
591
+ throw new Error(`AI Battery display config splitBar must be one of auto, manual, off: ${target}`);
592
+ }
593
+ }
594
+ if (isDisplayConfig(parsed)) return normalizeDisplayConfig(parsed);
595
+ return defaultDisplayConfig();
596
+ }
597
+
598
+ const localPath = configPath();
599
+ const sharedLocalPath = path.join(sharedStateDir(), "config.json");
600
+ if (!samePath(sharedLocalPath, localPath) && fs.existsSync(sharedLocalPath)) {
601
+ const sharedConfig = readJson(sharedLocalPath);
602
+ if (isBatteryConfig(sharedConfig)) return normalizeDisplayConfig(sharedConfig);
603
+ }
604
+ if (fs.existsSync(localPath)) {
605
+ return normalizeDisplayConfig(readConfig({ strict: Boolean(options.strict) }));
606
+ }
607
+ return defaultDisplayConfig();
608
+ }
609
+
610
+ function updateDisplayConfig({ providerOrder, providers, splitBar, barPosition, splitBarPosition, sidebarWidth } = {}) {
611
+ // Always validate local config ownership/syntax before mutating display config.
612
+ readConfig({ strict: true });
613
+ const target = displayConfigPath();
614
+ const merged = withFileLock(`${target}.lock`, () => {
615
+ const latest = readDisplayConfig({ strict: true });
616
+ const next = {
617
+ version: 1,
618
+ providers: {
619
+ ...latest.providers,
620
+ ...(providers && typeof providers === "object" ? providers : {})
621
+ },
622
+ providerOrder: providerOrder !== undefined
623
+ ? normalizeOrder(providerOrder, PROVIDERS)
624
+ : latest.providerOrder,
625
+ splitBar: splitBar !== undefined
626
+ ? normalizeSplitBarMode(splitBar, latest.splitBar)
627
+ : latest.splitBar,
628
+ barPosition: barPosition !== undefined
629
+ ? normalizeBarPosition(barPosition, latest.barPosition)
630
+ : latest.barPosition,
631
+ splitBarPosition: splitBarPosition !== undefined
632
+ ? (splitBarPosition === null ? null : normalizeBarPosition(splitBarPosition, latest.splitBarPosition || latest.barPosition))
633
+ : latest.splitBarPosition,
634
+ sidebarWidth: sidebarWidth !== undefined
635
+ ? normalizeSidebarWidth(sidebarWidth, latest.sidebarWidth)
636
+ : latest.sidebarWidth
637
+ };
638
+ writeJsonAtomic(target, next);
639
+ return next;
640
+ }, { timeoutMs: 3000 });
641
+
642
+ // Mirror only display fields into an existing local config.json so local
643
+ // recovery metadata and extra fields remain intact and compatible with tools/tests.
644
+ const localPath = configPath();
645
+ if (fs.existsSync(localPath)) {
646
+ withFileLock(`${localPath}.lock`, () => {
647
+ if (!fs.existsSync(localPath)) return;
648
+ const local = readConfig({ strict: true });
649
+ local.providerOrder = merged.providerOrder;
650
+ local.providers = { ...local.providers, ...merged.providers };
651
+ if (splitBar !== undefined || local.splitBar !== undefined) {
652
+ local.splitBar = merged.splitBar;
653
+ }
654
+ if (barPosition !== undefined || local.barPosition !== undefined) {
655
+ local.barPosition = merged.barPosition;
656
+ }
657
+ if (splitBarPosition !== undefined || local.splitBarPosition !== undefined) {
658
+ local.splitBarPosition = merged.splitBarPosition;
659
+ }
660
+ if (sidebarWidth !== undefined || local.sidebarWidth !== undefined) {
661
+ local.sidebarWidth = merged.sidebarWidth;
662
+ }
663
+ writeConfig(local);
664
+ }, { timeoutMs: 3000 });
665
+ }
666
+ return merged;
667
+ }
668
+
436
669
  const { installManagedText, removeManagedText, stripOwnedBlock } = createIntegrationFiles({ readConfig, writeConfig, writeTextAtomic });
437
670
 
438
671
  function providerVisible(provider) {
439
- const config = readConfig();
672
+ const config = readDisplayConfig();
440
673
  return config.providers?.[provider] !== false;
441
674
  }
442
675
 
443
676
  function configuredProviderOrder() {
444
- return normalizeOrder(readConfig().providerOrder, PROVIDERS);
677
+ return normalizeOrder(readDisplayConfig().providerOrder, PROVIDERS);
678
+ }
679
+
680
+ function diagnoseSharedBar() {
681
+ const fragment = diagnoseWtFragment();
682
+ const helper = diagnosePaneContextHelper();
683
+ const splitBar = resolveSplitBarMode(process.env, { configuredMode: readDisplayConfig().splitBar });
684
+ const backendOverride = String(process.env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
685
+ const usesWtPane = backendOverride !== "in-terminal";
686
+ return {
687
+ ...fragment,
688
+ backend: usesWtPane ? "wt-pane" : "in-terminal",
689
+ mode: splitBar.mode,
690
+ configuredMode: splitBar.configuredMode,
691
+ ...(splitBar.envOverride ? { envOverride: splitBar.envOverride } : {}),
692
+ triggerConfigured: Boolean(fragment.autoAttach),
693
+ helperReady: helper.ready,
694
+ helperPath: helper.path,
695
+ helperError: helper.ready ? null : helper.reason,
696
+ autoAttach: Boolean(splitBar.mode === "auto" && helper.ready && (!usesWtPane || fragment.autoAttach))
697
+ };
445
698
  }
446
699
 
447
700
  function antigravityAvailable() {
448
- return fs.existsSync(antigravity.cachePath()) || fs.existsSync(antigravity.settingsPath());
701
+ return antigravity.available();
449
702
  }
450
703
 
451
704
  function providerTargets(targets) {
@@ -457,14 +710,14 @@ function providerTargets(targets) {
457
710
  } else if (PROVIDERS.includes(target)) {
458
711
  providers.add(target);
459
712
  } else {
460
- throw new Error("target must be one of: codex, claude, all");
713
+ throw new Error("target must be one of: codex, claude, gemini, all");
461
714
  }
462
715
  }
463
716
  return [...providers];
464
717
  }
465
718
 
466
719
  function teardownTargets(targets) {
467
- const requested = targets.length ? targets : ["all"];
720
+ const requested = targets.length ? targets.map(normalizeTarget) : ["all"];
468
721
  const selected = new Set();
469
722
  for (const target of requested) {
470
723
  if (target === "all") {
@@ -472,7 +725,7 @@ function teardownTargets(targets) {
472
725
  } else if (TEARDOWN_TARGETS.includes(target)) {
473
726
  selected.add(target);
474
727
  } else {
475
- throw new Error("target must be one of: codex, claude, hud, tmux, all");
728
+ throw new Error("target must be one of: codex, claude, gemini, hud, tmux, split-bar, all");
476
729
  }
477
730
  }
478
731
  return [...selected];
@@ -480,13 +733,11 @@ function teardownTargets(targets) {
480
733
 
481
734
  function setProviderVisibility(targets, visible) {
482
735
  const providers = providerTargets(targets);
483
- const config = readConfig({ strict: true });
484
- for (const provider of providers) {
485
- config.providers[provider] = visible;
486
- }
487
- writeConfig(config);
736
+ const patch = Object.fromEntries(providers.map(provider => [provider, visible]));
737
+ updateDisplayConfig({ providers: patch });
488
738
  return {
489
739
  configPath: configPath(),
740
+ displayConfigPath: displayConfigPath(),
490
741
  providers,
491
742
  visible
492
743
  };
@@ -923,20 +1174,80 @@ function shellRcPath() {
923
1174
 
924
1175
  function shellPathBlock(shimDir) {
925
1176
  const shell = path.basename(process.env.SHELL || "");
1177
+ const cliDir = posixCliWrapperDir(userHome());
1178
+ const dirs = samePath(cliDir, shimDir) ? [shimDir] : [cliDir, shimDir];
926
1179
  if (shell === "fish") {
927
- return `\n# >>> ai-battery setup >>>\nfish_add_path -p ${shQuote(shimDir)}\n# <<< ai-battery setup <<<\n`;
1180
+ // fish_add_path -p prepends each call, so reverse order keeps cliDir first.
1181
+ return `\n# >>> ai-battery setup >>>\n${[...dirs].reverse().map(dir => `fish_add_path -p ${shQuote(dir)}`).join("\n")}\n# <<< ai-battery setup <<<\n`;
928
1182
  }
929
- return `\n# >>> ai-battery setup >>>\nexport PATH=${shQuote(shimDir)}:"$PATH"\n# <<< ai-battery setup <<<\n`;
1183
+ return `\n# >>> ai-battery setup >>>\nexport PATH=${dirs.map(shQuote).join(":")}` + ':"$PATH"\n# <<< ai-battery setup <<<\n';
1184
+ }
1185
+
1186
+ function updatePosixShellPathFile(rcPath, shimDir) {
1187
+ fs.mkdirSync(path.dirname(rcPath), { recursive: true });
1188
+ const existing = fs.existsSync(rcPath) ? fs.readFileSync(rcPath, "utf8") : "";
1189
+ const withoutAiBatteryBlock = stripOwnedBlock(rcPath, existing, removeAiBatteryShellPathBlock);
1190
+ const separator = withoutAiBatteryBlock && !withoutAiBatteryBlock.endsWith("\n") ? "\n" : "";
1191
+ const next = `${withoutAiBatteryBlock}${separator}${shellPathBlock(shimDir)}`;
1192
+ const changed = next !== existing;
1193
+ if (changed) installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1194
+ return { changed, existing, withoutAiBatteryBlock };
1195
+ }
1196
+
1197
+ function ensureCliPositionWrappers(targets = ["claude", "antigravity"], { updateShellPath = false } = {}) {
1198
+ const names = [];
1199
+ if (targets.includes("claude")) names.push("claude");
1200
+ if (targets.includes("antigravity")) names.push("agy");
1201
+ if (!names.length || !codexRunnerExists()) return null;
1202
+ const winShimDir = process.platform === "win32" ? defaultCodexShimDir() : null;
1203
+ const result = installCliPositionWrappers({
1204
+ names,
1205
+ runnerPath: codexRunnerPath(),
1206
+ homeDir: userHome(),
1207
+ platform: process.platform,
1208
+ nodePath: process.execPath,
1209
+ windowsDir: winShimDir,
1210
+ env: process.env
1211
+ });
1212
+ if (updateShellPath && process.platform === "win32" && winShimDir) {
1213
+ try {
1214
+ ensureWindowsShimPath(winShimDir, path.join(homePath(".local", "bin"), "claude.exe"));
1215
+ } catch { /* Best-effort Windows PATH update. */ }
1216
+ } else if (updateShellPath && process.platform !== "win32") {
1217
+ let existingCodexDir = null;
1218
+ try {
1219
+ const configuredWrapper = readConfig().codexWrapper?.wrapperPath;
1220
+ if (configuredWrapper) existingCodexDir = path.dirname(configuredWrapper);
1221
+ } catch {}
1222
+ const shimDir = existingCodexDir || homePath(".local", "bin");
1223
+ const rcTargets = [shellRcPath()];
1224
+ const profilePath = homePath(".profile");
1225
+ if (!process.env.AI_BATTERY_RC && path.basename(process.env.SHELL || "") === "bash" && fs.existsSync(profilePath) && !samePath(rcTargets[0], profilePath)) {
1226
+ rcTargets.push(profilePath);
1227
+ }
1228
+ for (const rcPath of rcTargets) {
1229
+ try {
1230
+ updatePosixShellPathFile(rcPath, shimDir);
1231
+ } catch { /* Best-effort PATH update. */ }
1232
+ }
1233
+ }
1234
+ return result;
930
1235
  }
931
1236
 
932
1237
  function tmuxStatusBarActive() {
933
1238
  const override = String(process.env.AI_BATTERY_TMUX || process.env.CLAUDEX_BATTERY_TMUX || "").toLowerCase();
934
1239
  if (override === "row") return false;
935
1240
  if (["status", "plain", "off"].includes(override)) return true;
936
- // AI_BATTERY_TMUX_STATUS=1 is set by "ai-battery setup tmux" via tmux set-environment -g.
937
- // Trust it even when TMUX socket path isn't propagated to Claude Code's statusline subprocess.
938
- if ((process.env.AI_BATTERY_TMUX_STATUS || process.env.CLAUDEX_BATTERY_TMUX_STATUS) === "1") return true;
939
- return false;
1241
+ if (process.env.TMUX) {
1242
+ const target = process.env.TMUX_PANE ? ["-t", process.env.TMUX_PANE] : [];
1243
+ const result = spawnSync("tmux", ["display-message", "-p", ...target, "#{AI_BATTERY_TMUX_STATUS}\t#{status}\t#{?@ai_battery_tmux_saved,1,0}\t#{?@ai_battery_tmux_paused,1,0}"], { encoding: "utf8", timeout: 1000 });
1244
+ if (result.status === 0) {
1245
+ const [enabled, height, managed, paused] = result.stdout.trim().split("\t");
1246
+ return enabled === "1" && paused !== "1" && height !== "off" && (height !== "5" || managed === "1");
1247
+ }
1248
+ }
1249
+ // Hooks may retain the integration flag while omitting the TMUX socket.
1250
+ return (process.env.AI_BATTERY_TMUX_STATUS || process.env.CLAUDEX_BATTERY_TMUX_STATUS) === "1";
940
1251
  }
941
1252
 
942
1253
  function booleanEnvValue(value) {
@@ -951,12 +1262,18 @@ function claudeUsageRowVisible(args) {
951
1262
  if (args.usageRow === true || args.usageRow === false) return args.usageRow;
952
1263
  const envValue = booleanEnvValue(process.env.AI_BATTERY_CLAUDE_USAGE_ROW ?? process.env.CLAUDEX_BATTERY_CLAUDE_USAGE_ROW);
953
1264
  if (envValue !== null) return envValue;
954
- if (process.platform === "win32") return false;
1265
+ if (process.platform === "win32" && args.attachHud) return false;
955
1266
  return !tmuxStatusBarActive();
956
1267
  }
957
1268
 
958
1269
  function tmuxConfPath() {
959
- return process.env.AI_BATTERY_TMUX_CONF || homePath(".tmux.conf");
1270
+ if (process.env.AI_BATTERY_TMUX_CONF) return process.env.AI_BATTERY_TMUX_CONF;
1271
+ const legacy = homePath(".tmux.conf");
1272
+ if (fs.existsSync(legacy)) return legacy;
1273
+ const xdgBase = process.env.XDG_CONFIG_HOME || homePath(".config");
1274
+ const xdg = path.join(xdgBase, "tmux", "tmux.conf");
1275
+ if (fs.existsSync(xdg)) return xdg;
1276
+ return legacy;
960
1277
  }
961
1278
 
962
1279
  function removeAiBatteryTmuxBlock(text) {
@@ -976,26 +1293,12 @@ function extractExistingStatusRight(confText) {
976
1293
  return last;
977
1294
  }
978
1295
 
979
- function tmuxStatusBlock(existingStatusRight = null) {
980
- // #{client_width} is expanded by tmux before running the shell command,
981
- // giving the responsive layout the actual terminal width to work with.
982
- const battery = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}`;
983
- const batteryPart = `#(${battery})`;
984
- // Put the battery on the far right so tmux left-clips the existing text before
985
- // the bar. When the block is uninstalled, the earlier set -g status-right wins.
986
- const statusRightValue = existingStatusRight
987
- ? `${existingStatusRight} ${batteryPart} `
988
- : `${batteryPart} `;
989
- const rightLength = 200;
1296
+ function tmuxStatusBlock(confPath = tmuxConfPath()) {
1297
+ const command = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery-tmux.js"))} start --socket #{q:socket_path} --config ${shQuote(confPath)}`;
990
1298
  return [
991
1299
  "\n# >>> ai-battery tmux >>>",
992
- "# AI Battery once per session in the tmux status bar; runners inside tmux",
993
- "# see AI_BATTERY_TMUX_STATUS and skip their per-pane bottom row.",
994
- "set-environment -g AI_BATTERY_TMUX_STATUS 1",
995
- "set -g status on",
996
- "set -g status-interval 10",
997
- `set-option -g status-right-length ${rightLength}`,
998
- `set -g status-right "${statusRightValue.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
1300
+ "# Keep the existing status row; append usage only while an AI runs in this session.",
1301
+ `run-shell -b "${command.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
999
1302
  "# <<< ai-battery tmux <<<",
1000
1303
  ""
1001
1304
  ].join("\n");
@@ -1011,19 +1314,24 @@ function installTmuxStatus({ confPath = tmuxConfPath() } = {}) {
1011
1314
  } catch (error) { if (error.code !== "ENOENT") throw error; }
1012
1315
  const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
1013
1316
  const existingStatusRight = extractExistingStatusRight(withoutBlock);
1014
- const next = `${withoutBlock}${tmuxStatusBlock(existingStatusRight)}`;
1317
+ const next = `${withoutBlock}${tmuxStatusBlock(confPath)}`;
1015
1318
  if (next !== existing) installManagedText(confPath, next, next.slice(withoutBlock.length));
1016
1319
  let active = false;
1017
1320
  let error = null;
1018
- if (process.env.TMUX && !process.env.AI_BATTERY_TMUX_CONF) {
1019
- const commands = [
1020
- "set-environment", "-g", "AI_BATTERY_TMUX_STATUS", "1", ";",
1021
- "set-option", "-g", "status", "on", ";",
1022
- "set-option", "-g", "status-interval", "10", ";",
1023
- "set-option", "-g", "status-right-length", "200", ";",
1024
- "set-option", "-g", "status-right", `${existingStatusRight ? `${existingStatusRight} ` : ""}#(${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}) `
1025
- ];
1026
- const result = spawnSync("tmux", commands, { encoding: "utf8", timeout: 4000 });
1321
+ const socket = !process.env.AI_BATTERY_TMUX_CONF ? tmuxSocket() : null;
1322
+ if (socket) {
1323
+ // Migrate only the old options we still recognize as our status-right block.
1324
+ const right = spawnSync("tmux", ["-S", socket, "show-options", "-gv", "status-right"], { encoding: "utf8", timeout: 1500 });
1325
+ if (right.stdout?.includes("ai-battery.js") && right.stdout.includes("--tmux")) {
1326
+ for (const option of ["status-right", "status-right-length", "status-interval", "status"]) {
1327
+ const pattern = new RegExp("^[ \\t]*set(?:-option)?(?:[ \\t]+-(?!t\\b|u\\b|w\\b|a\\b)\\w+)*[ \\t]+" + option + "[ \\t]+(?:\"((?:[^\"\\\\]|\\\\.)*)\"|'((?:[^'\\\\]|\\\\.)*)'|([^#\\r\\n]+?))(?:[ \\t]+#.*)?$", "gm");
1328
+ const match = [...withoutBlock.matchAll(pattern)].at(-1);
1329
+ const rawValue = match ? (match[1] ?? match[2] ?? match[3]?.trim()) : null;
1330
+ const value = option === "status-right" ? existingStatusRight : rawValue;
1331
+ spawnSync("tmux", ["-S", socket, "set-option", value == null ? "-gu" : "-g", option, ...(value == null ? [] : [value])], { timeout: 1500 });
1332
+ }
1333
+ }
1334
+ const result = spawnSync(process.execPath, [path.join(scriptDir(), "ai-battery-tmux.js"), "start", "--socket", socket, "--config", confPath], { encoding: "utf8", timeout: 8000 });
1027
1335
  active = !result.error && result.status === 0;
1028
1336
  if (!active) error = result.error?.message || result.stderr?.trim() || "Could not apply the tmux status bar";
1029
1337
  }
@@ -1043,6 +1351,8 @@ function uninstallTmuxStatus() {
1043
1351
  const confPath = tmuxConfPath();
1044
1352
  const records = readConfig({ strict: true }).integrationFiles || {};
1045
1353
  const paths = uniquePaths([confPath, ...Object.keys(records).filter(file => records[file]?.block?.includes("# >>> ai-battery tmux >>>"))]);
1354
+ const socket = tmuxSocket();
1355
+ if (socket) for (const file of paths) spawnSync(process.execPath, [path.join(scriptDir(), "ai-battery-tmux.js"), "stop", "--socket", socket, "--config", file], { timeout: 5000 });
1046
1356
  const changedPaths = paths.filter(file => removeManagedText(file, removeAiBatteryTmuxBlock));
1047
1357
  return { changed: changedPaths.length > 0, confPath, changedPaths };
1048
1358
  }
@@ -1667,12 +1977,15 @@ function removeManagedCodexBridge(wrapperPath) {
1667
1977
  return null;
1668
1978
  }
1669
1979
 
1670
- function uninstallCodexWrapper() {
1980
+ function uninstallCodexWrapper({ extraWindowsOwnedShimDirs = [] } = {}) {
1671
1981
  const config = readConfig({ strict: true });
1672
1982
  const statusLine = restoreCodexStatusLine(config);
1673
1983
  if (statusLine.clearedBackup) writeConfig(config);
1674
1984
  const candidates = codexWrapperCandidates(config);
1675
- const windowsOwnedShimDirs = windowsOwnedShimDirsForUninstall(config);
1985
+ const windowsOwnedShimDirs = [...new Set([
1986
+ ...windowsOwnedShimDirsForUninstall(config),
1987
+ ...(Array.isArray(extraWindowsOwnedShimDirs) ? extraWindowsOwnedShimDirs : [])
1988
+ ].filter(Boolean))];
1676
1989
  const unmanaged = [];
1677
1990
  const skippedWrappers = [];
1678
1991
  const removedWrappers = [];
@@ -2046,7 +2359,7 @@ function diagnoseClaudeStatusLine() {
2046
2359
  const managed = managedClaudeStatusLine(statusLine);
2047
2360
  const needsRefresh = process.platform === "win32"
2048
2361
  && managed
2049
- && (!command.includes("--attach-hud") || !command.includes("--no-usage-row"));
2362
+ && command.includes("--attach-hud");
2050
2363
  return {
2051
2364
  settingsPath,
2052
2365
  configured: Boolean(statusLine),
@@ -2079,6 +2392,7 @@ async function runDoctor() {
2079
2392
  },
2080
2393
  stateDir: stateDir(),
2081
2394
  configPath: configPath(),
2395
+ displayConfigPath: displayConfigPath(),
2082
2396
  recovery: {
2083
2397
  codexWrapper: Boolean(recoveryConfig.codexWrapper),
2084
2398
  codexStatusLine: Boolean(recoveryConfig.codexStatusLineBackup),
@@ -2089,6 +2403,7 @@ async function runDoctor() {
2089
2403
  : null
2090
2404
  }
2091
2405
  },
2406
+ ...((process.platform === "win32" || isWsl()) ? { split: diagnoseSharedBar() } : {}),
2092
2407
  codex: diagnoseCodex(),
2093
2408
  antigravity: antigravity.diagnose(),
2094
2409
  ...(process.platform !== "win32" ? { tmux: diagnoseTmux() } : {}),
@@ -2272,26 +2587,31 @@ function uninstallRowPtyHost() {
2272
2587
  }
2273
2588
 
2274
2589
  function setupTargets(targets) {
2275
- const requested = targets.length ? targets : ["all"];
2590
+ const requested = targets.length ? targets.map(normalizeTarget) : ["all"];
2276
2591
  const selected = new Set();
2277
2592
  for (const target of requested) {
2278
2593
  if (target === "all") {
2279
- // "all" keeps tmux opt-in: its block overrides the user's status-right.
2594
+ // Prepare native split integration where reachable. tmux remains opt-in.
2280
2595
  PROVIDERS.forEach((provider) => selected.add(provider));
2281
- } else if (PROVIDERS.includes(target) || target === "tmux") {
2596
+ if (process.platform === "win32" || isWslWtContext()) selected.add("split");
2597
+ } else if (PROVIDERS.includes(target) || ["tmux", "split"].includes(target)) {
2282
2598
  selected.add(target);
2283
2599
  } else {
2284
- throw new Error("target must be one of: codex, claude, gemini, tmux, all");
2600
+ throw new Error("target must be one of: codex, claude, gemini, tmux, split, all");
2285
2601
  }
2286
2602
  }
2287
2603
  return [...selected];
2288
2604
  }
2289
2605
 
2290
2606
  function runSetup(args) {
2291
- if (args.providerOrder) {
2292
- const config = readConfig({ strict: true });
2293
- config.providerOrder = args.providerOrder;
2294
- writeConfig(config);
2607
+ if (args.providerOrder || args.barPosition) {
2608
+ const updatedDisplay = updateDisplayConfig({
2609
+ ...(args.providerOrder ? { providerOrder: args.providerOrder } : {}),
2610
+ ...(args.barPosition ? { barPosition: args.barPosition } : {})
2611
+ });
2612
+ if (args.barPosition && !updatedDisplay.splitBarPosition && (process.platform === "win32" || isWsl())) {
2613
+ updateWtFragmentPosition({ position: updatedDisplay.barPosition, sidebarWidth: updatedDisplay.sidebarWidth });
2614
+ }
2295
2615
  }
2296
2616
  const targets = setupTargets(args.targets);
2297
2617
  const previous = readConfig({ strict: true });
@@ -2308,20 +2628,68 @@ function runSetup(args) {
2308
2628
  }
2309
2629
  }
2310
2630
  const results = {};
2311
- let windowsClaudeLauncher = null;
2312
2631
  if (targets.includes("claude")) {
2313
2632
  const statusLine = installClaudeStatusline(args);
2314
- if (process.platform === "win32") {
2315
- windowsClaudeLauncher = installRowPtyHost();
2316
- results.claude = { ...statusLine, launcher: windowsClaudeLauncher };
2317
- } else {
2318
- results.claude = statusLine;
2319
- }
2633
+ results.claude = statusLine;
2320
2634
  }
2321
2635
  if (targets.includes("antigravity")) results.antigravity = antigravity.install(args);
2636
+ if (targets.includes("claude") || targets.includes("antigravity")) {
2637
+ ensureCliPositionWrappers(targets, { updateShellPath: true });
2638
+ }
2322
2639
  if (targets.includes("tmux")) {
2323
2640
  results.tmux = installTmuxStatus(tmuxRefreshPath ? { confPath: tmuxRefreshPath } : {});
2324
2641
  }
2642
+ let paneContextHelper = null;
2643
+ if ((process.platform === "win32" || isWsl()) && targets.some(target => target === "split" || PROVIDERS.includes(target))) {
2644
+ paneContextHelper = preparePaneContextHelper();
2645
+ }
2646
+ if (targets.includes("split")) {
2647
+ if (process.platform === "win32") {
2648
+ const backendOverride = String(process.env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
2649
+ const splitPosition = readConfiguredSplitBarPosition();
2650
+ const usesWtPane = backendOverride !== "in-terminal";
2651
+ const fragment = installWtFragment({
2652
+ cliPath: path.join(scriptDir(), "ai-battery.js"),
2653
+ position: splitPosition,
2654
+ sidebarWidth: readDisplayConfig().sidebarWidth,
2655
+ bindAutoTrigger: usesWtPane
2656
+ });
2657
+ const helper = paneContextHelper || preparePaneContextHelper();
2658
+ results.split = (fragment.ok || !usesWtPane) ? {
2659
+ ...fragment,
2660
+ ok: usesWtPane ? fragment.ok : helper.ready,
2661
+ backend: usesWtPane ? "wt-pane" : "in-terminal",
2662
+ triggerConfigured: Boolean(fragment.autoAttach),
2663
+ helperReady: helper.ready,
2664
+ helperBuilt: helper.built,
2665
+ helperPath: helper.path,
2666
+ helperError: helper.ready ? null : helper.reason,
2667
+ autoAttach: Boolean(helper.ready && (!usesWtPane || fragment.autoAttach)),
2668
+ autoAttachNote: (usesWtPane && fragment.autoAttachNote) || (helper.ready ? null : helper.reason)
2669
+ } : fragment;
2670
+ } else {
2671
+ if (isWsl()) {
2672
+ const helper = paneContextHelper || preparePaneContextHelper();
2673
+ const backendOverride = String(process.env.AI_BATTERY_SPLIT_BACKEND || "").trim().toLowerCase();
2674
+ const usesWtPane = backendOverride !== "in-terminal";
2675
+ const fragment = diagnoseWtFragment();
2676
+ results.split = {
2677
+ ok: helper.ready,
2678
+ backend: usesWtPane ? "wt-pane" : "in-terminal",
2679
+ triggerConfigured: Boolean(fragment.autoAttach),
2680
+ helperReady: helper.ready,
2681
+ helperBuilt: helper.built,
2682
+ helperPath: helper.path,
2683
+ helperError: helper.ready ? null : helper.reason,
2684
+ autoAttach: Boolean(helper.ready && (!usesWtPane || fragment.autoAttach)),
2685
+ autoAttachNote: (usesWtPane && !fragment.autoAttach ? "Run Windows setup once to install the Windows Terminal bar fragment and shortcut." : null),
2686
+ ...(helper.ready ? {} : { reason: helper.reason })
2687
+ };
2688
+ } else {
2689
+ results.split = { ok: true, skipped: true, reason: "Run ai-battery setup split from Windows PowerShell." };
2690
+ }
2691
+ }
2692
+ }
2325
2693
  if (targets.includes("codex")) {
2326
2694
  const wrapCodex = args.wrapCodex;
2327
2695
  const statusLine = args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
@@ -2341,13 +2709,11 @@ function runSetup(args) {
2341
2709
  results.codex.providerEnabled = providerVisible("codex");
2342
2710
  if (process.platform === "win32" && wrapCodex) {
2343
2711
  results.codex.rowpty = windowsSetupNeedsRowPty()
2344
- ? (windowsClaudeLauncher || installRowPtyHost())
2712
+ ? installRowPtyHost()
2345
2713
  : {
2346
2714
  ok: true,
2347
2715
  skipped: true,
2348
- reason: windowsClaudeLauncher?.ok
2349
- ? "Installed with the Windows Claude HUD launcher; not required by the current Codex layout"
2350
- : "Not required by the default PTY compositor; set AI_BATTERY_WIN_LAYOUT=tui and run setup codex to install it"
2716
+ reason: "Not required by the default PTY compositor; set AI_BATTERY_WIN_LAYOUT=tui and run setup codex to install it"
2351
2717
  };
2352
2718
  }
2353
2719
  }
@@ -2366,6 +2732,7 @@ function setupResultFailed(result) {
2366
2732
  || result.codex?.statusLine?.error
2367
2733
  || result.codex?.rowpty?.error
2368
2734
  || (result.codex?.rowpty && result.codex.rowpty.ok === false)
2735
+ || (result.split && result.split.ok === false)
2369
2736
  || (result.tmux && result.tmux.ok === false && !result.tmux.skipped)
2370
2737
  );
2371
2738
  }
@@ -2437,16 +2804,42 @@ function runTeardown(args) {
2437
2804
  }
2438
2805
  };
2439
2806
 
2807
+ let removedWinCliWrappers = false;
2440
2808
  if (targets.includes("claude")) {
2441
- runStep("claude", () => uninstallClaudeStatusline({ strict: false }));
2809
+ runStep("claude", () => {
2810
+ const removed = uninstallCliPositionWrappers({ names: ["claude"], homeDir: userHome(), platform: process.platform, windowsDir: process.platform === "win32" ? defaultCodexShimDir() : null, env: process.env });
2811
+ if (process.platform === "win32" && removed.removed?.length) removedWinCliWrappers = true;
2812
+ return uninstallClaudeStatusline({ strict: false });
2813
+ });
2814
+ }
2815
+ if (targets.includes("antigravity")) {
2816
+ runStep("antigravity", () => {
2817
+ const removed = uninstallCliPositionWrappers({ names: ["agy"], homeDir: userHome(), platform: process.platform, windowsDir: process.platform === "win32" ? defaultCodexShimDir() : null, env: process.env });
2818
+ if (process.platform === "win32" && removed.removed?.length) removedWinCliWrappers = true;
2819
+ return antigravity.uninstall();
2820
+ });
2442
2821
  }
2443
- if (targets.includes("antigravity")) runStep("antigravity", antigravity.uninstall);
2444
2822
  if (targets.includes("codex")) {
2445
- runStep("codex", uninstallCodexWrapper);
2823
+ runStep("codex", () => uninstallCodexWrapper({
2824
+ extraWindowsOwnedShimDirs: removedWinCliWrappers ? [defaultCodexShimDir()] : []
2825
+ }));
2826
+ } else if (targets.includes("claude") || targets.includes("antigravity")) {
2827
+ try {
2828
+ const cfg = readConfig({ strict: true });
2829
+ const cliDir = process.platform === "win32" ? defaultCodexShimDir() : posixCliWrapperDir(userHome());
2830
+ const anyWrapperLeft = ["claude", "agy"].some(name => fs.existsSync(path.join(cliDir, process.platform === "win32" ? `${name}.cmd` : name)));
2831
+ if (!cfg.codexWrapper && !anyWrapperLeft) {
2832
+ removeShellPathBlocks([], { windowsOwnedShimDirs: process.platform === "win32" ? [defaultCodexShimDir()] : [] });
2833
+ }
2834
+ } catch { /* Best-effort PATH cleanup when no codex wrapper exists. */ }
2446
2835
  }
2447
2836
  if (targets.includes("tmux")) {
2448
2837
  runStep("tmux", uninstallTmuxStatus);
2449
2838
  }
2839
+ if (targets.includes("split")) {
2840
+ if (process.platform === "win32") runStep("split", removeWtFragment);
2841
+ else if (args.targets.includes("split")) results.split = { changed: false, skipped: true, reason: "Run ai-battery reset split from Windows PowerShell." };
2842
+ }
2450
2843
  if (targets.includes("hud")) {
2451
2844
  runStep("hud", uninstallHud);
2452
2845
  }
@@ -2459,7 +2852,10 @@ function runTeardown(args) {
2459
2852
  return { targets, fullReset, results };
2460
2853
  }
2461
2854
  const roots = [stateDir(), dataDir(), path.join(os.tmpdir(), "ai-battery")];
2462
- if (process.platform === "win32" && process.env.LOCALAPPDATA) roots.push(path.join(process.env.LOCALAPPDATA, "ai-battery"));
2855
+ if (process.platform === "win32" && process.env.LOCALAPPDATA
2856
+ && !process.env.AI_BATTERY_DATA_DIR && !process.env.AI_BATTERY_STATE_DIR && !process.env.CLAUDEX_BATTERY_STATE_DIR) {
2857
+ roots.push(path.join(process.env.LOCALAPPDATA, "ai-battery"));
2858
+ }
2463
2859
  results.artifacts = cleanupBatteryArtifacts({
2464
2860
  roots,
2465
2861
  home: userHome(),
@@ -2540,10 +2936,18 @@ function readHead(filePath, bytes = 32 * 1024) {
2540
2936
  }
2541
2937
  }
2542
2938
 
2543
- function latestMatchingJsonLine(files, predicate, acceptParsed = null) {
2939
+ function latestMatchingJsonLine(files, predicate, acceptParsed = null, newestTimestamp = false) {
2544
2940
  let fallback = null;
2941
+ let newest = null;
2942
+ let newestMs = 0;
2545
2943
 
2546
2944
  for (const file of files) {
2945
+ // Files are sorted by mtimeMs desc; once we have a newer event than this
2946
+ // file's last modification time (minus a small clock-skew margin), older
2947
+ // files cannot contain a newer event.
2948
+ if (newestTimestamp && newest && Number.isFinite(file.mtimeMs) && file.mtimeMs < newestMs - 5000) {
2949
+ break;
2950
+ }
2547
2951
  const text = readTail(file.path);
2548
2952
  const lines = text.split("\n");
2549
2953
 
@@ -2554,14 +2958,21 @@ function latestMatchingJsonLine(files, predicate, acceptParsed = null) {
2554
2958
  try {
2555
2959
  const json = JSON.parse(line);
2556
2960
  if (acceptParsed && !acceptParsed(json)) continue;
2557
- return { json, file: file.path };
2961
+ const result = { json, file: file.path };
2962
+ if (!newestTimestamp) return result;
2963
+ const ts = Date.parse(json.timestamp || "") || 0;
2964
+ if (!newest || ts > newestMs) {
2965
+ newest = result;
2966
+ newestMs = ts;
2967
+ }
2968
+ break;
2558
2969
  } catch {
2559
2970
  fallback = fallback || { error: "Found a matching line but could not parse it", file: file.path };
2560
2971
  }
2561
2972
  }
2562
2973
  }
2563
2974
 
2564
- return fallback;
2975
+ return newest || fallback;
2565
2976
  }
2566
2977
 
2567
2978
  function codexSessionMeta(filePath) {
@@ -2650,7 +3061,7 @@ function writeJsonAtomic(filePath, data, mode = 0o600) {
2650
3061
  const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2651
3062
  try {
2652
3063
  fs.writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, { mode });
2653
- fs.renameSync(tempPath, targetPath);
3064
+ atomicRename(tempPath, targetPath);
2654
3065
  } catch (error) {
2655
3066
  try {
2656
3067
  fs.rmSync(tempPath, { force: true });
@@ -2667,7 +3078,7 @@ function writeTextAtomic(filePath, text, mode = 0o600) {
2667
3078
  const tempPath = `${targetPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
2668
3079
  try {
2669
3080
  fs.writeFileSync(tempPath, text, { mode });
2670
- fs.renameSync(tempPath, targetPath);
3081
+ atomicRename(tempPath, targetPath);
2671
3082
  } catch (error) {
2672
3083
  try {
2673
3084
  fs.rmSync(tempPath, { force: true });
@@ -2689,7 +3100,9 @@ function readJson(filePath) {
2689
3100
  function teardownResultFailed(result) {
2690
3101
  return Object.values(result.results || {}).some((item) => Boolean(
2691
3102
  item?.error
3103
+ || item?.ok === false
2692
3104
  || item?.errors?.length
3105
+ || item?.retained === true
2693
3106
  || item?.retainedConfig
2694
3107
  || item?.retainedBackup
2695
3108
  || item?.skippedWrappers?.length
@@ -2791,8 +3204,8 @@ const {
2791
3204
  writeScanCache
2792
3205
  });
2793
3206
  const antigravity = createAntigravityIntegration({
2794
- homePath, stateDir, readJson, readUserJsonObject, readConfig, writeConfig,
2795
- writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning
3207
+ homePath, stateDir, usageStateDir: codexUsageStateDir, readJson, readUserJsonObject, readConfig, writeConfig,
3208
+ writeJsonAtomic, samePath, shellArg, scriptDir, isProviderRunning, providerVisible
2796
3209
  });
2797
3210
 
2798
3211
  function readStdin() {
@@ -2847,6 +3260,12 @@ function normalizeClaudeCachedLimit(limit, options = {}) {
2847
3260
  });
2848
3261
  }
2849
3262
 
3263
+ function isPlausibleResetEpoch(epochSec, windowMinutes = 10080) {
3264
+ if (!Number.isFinite(epochSec) || epochSec <= 0) return false;
3265
+ const maxFutureSec = (Date.now() / 1000) + Math.max((Number(windowMinutes) || 10080) * 60, 7 * 86400) + (7 * 86400);
3266
+ return epochSec <= maxFutureSec;
3267
+ }
3268
+
2850
3269
  function claudeCanonicalLimit(candidate, previous) {
2851
3270
  if (!candidate) return previous ?? null;
2852
3271
  if (!previous) return candidate;
@@ -2856,9 +3275,23 @@ function claudeCanonicalLimit(candidate, previous) {
2856
3275
  if (!candidateNorm) return previous;
2857
3276
  if (!previousNorm) return candidate;
2858
3277
 
3278
+ const winMin = candidateNorm.windowMinutes ?? previousNorm.windowMinutes ?? 10080;
2859
3279
  const candidateReset = resetEpochSeconds(candidate.resets_at ?? candidate.resetsAt ?? candidate.reset_at ?? candidate.resetAt);
2860
3280
  const previousReset = resetEpochSeconds(previous.resets_at ?? previous.resetsAt ?? previous.reset_at ?? previous.resetAt);
2861
- if (Number.isFinite(candidateReset) && Number.isFinite(previousReset) && Math.abs(candidateReset - previousReset) > 60) {
3281
+ const candidatePlausible = isPlausibleResetEpoch(candidateReset, winMin);
3282
+ const previousPlausible = isPlausibleResetEpoch(previousReset, winMin);
3283
+ if (candidatePlausible && !previousPlausible) return candidate;
3284
+ if (!candidatePlausible && previousPlausible) return previous;
3285
+ const nowSec = Date.now() / 1000;
3286
+ const candidateExpired = candidateReset > 0 && candidateReset <= nowSec;
3287
+ const previousExpired = previousReset > 0 && previousReset <= nowSec;
3288
+ if (previousExpired && !candidateExpired) return candidate;
3289
+ if (!previousExpired && candidateExpired) return previous;
3290
+ if (candidatePlausible && previousPlausible && Math.abs(candidateReset - previousReset) > 60) {
3291
+ const candidateUnused = candidateNorm.remainingPercent === 100 || candidateNorm.usedPercent === 0;
3292
+ const previousUnused = previousNorm.remainingPercent === 100 || previousNorm.usedPercent === 0;
3293
+ if (previousUnused && !candidateUnused) return candidate;
3294
+ if (!previousUnused && candidateUnused) return previous;
2862
3295
  return candidateReset > previousReset ? candidate : previous;
2863
3296
  }
2864
3297
 
@@ -3070,14 +3503,31 @@ function scanClaudeRateLimitHit() {
3070
3503
 
3071
3504
  let claudeRateLimitHitMemo = null;
3072
3505
 
3506
+ function sharedClaudeRateLimitHitPath() {
3507
+ return path.join(sharedStateDir(), "claude-rate-limit-hit.json");
3508
+ }
3509
+
3073
3510
  function latestClaudeRateLimitHit() {
3074
3511
  if (claudeRateLimitHitMemo && Date.now() - claudeRateLimitHitMemo.at < 5000) {
3075
3512
  return claudeRateLimitHitMemo.value;
3076
3513
  }
3077
3514
 
3078
- const cached = readScanCache("claude-rate-limit-hit", scanCacheSeconds(10));
3079
- const value = cached ? cached.value ?? null : scanClaudeRateLimitHit();
3080
- if (!cached) writeScanCache("claude-rate-limit-hit", value);
3515
+ const cached = readScanCache("claude-rate-limit-hit", scanCacheSeconds(30));
3516
+ let value = cached ? cached.value ?? null : scanClaudeRateLimitHit();
3517
+ if (!cached) {
3518
+ writeScanCache("claude-rate-limit-hit", value);
3519
+ if (value?.timestamp) {
3520
+ publishNewest(sharedClaudeRateLimitHitPath(), value, {
3521
+ read: readJson,
3522
+ write: writeJsonAtomic,
3523
+ timestamp: item => item?.timestamp
3524
+ });
3525
+ }
3526
+ }
3527
+ const sharedHit = readJson(sharedClaudeRateLimitHitPath());
3528
+ if (sharedHit?.timestamp && (!value?.timestamp || (Date.parse(sharedHit.timestamp) || 0) > (Date.parse(value.timestamp) || 0))) {
3529
+ value = sharedHit;
3530
+ }
3081
3531
  claudeRateLimitHitMemo = { at: Date.now(), value };
3082
3532
  return value;
3083
3533
  }
@@ -3108,11 +3558,11 @@ function applyClaudeRateLimitHit(limit, hit, window) {
3108
3558
  function captureClaudeStatusline(input) {
3109
3559
  const rateLimits = claudeRateLimitsFromStatusline(input);
3110
3560
  const sessionId = input.session_id ?? input.sessionId ?? null;
3111
- const previousGlobal = readJson(claudeCachePath());
3112
- const previous = (sessionId ? readJson(claudeSessionCachePath(sessionId)) : null) ?? previousGlobal;
3561
+ const globalPath = claudeCachePath();
3562
+ const previousSession = sessionId ? readJson(claudeSessionCachePath(sessionId)) : null;
3113
3563
  const sessionKind = claudeStatuslineSessionKind(input);
3114
3564
  const contextWindow = claudeContextWindowFromStatusline(input);
3115
- let snapshot = {
3565
+ const baseSnapshot = {
3116
3566
  version: 1,
3117
3567
  provider: "claude",
3118
3568
  sourceType: "statusline",
@@ -3138,26 +3588,66 @@ function captureClaudeStatusline(input) {
3138
3588
  contextWindow
3139
3589
  };
3140
3590
 
3141
- if (previous?.provider === "claude" && previous?.sourceType === "statusline") {
3142
- const sameSession = previous.sessionId && snapshot.sessionId && previous.sessionId === snapshot.sessionId;
3143
- if (!snapshot.rateLimits.fiveHour) {
3144
- snapshot.rateLimits.fiveHour = previous.rateLimits?.fiveHour ?? null;
3145
- }
3146
- if (!snapshot.rateLimits.sevenDay) {
3147
- snapshot.rateLimits.sevenDay = previous.rateLimits?.sevenDay ?? null;
3591
+ const mergeWithGlobal = (currentGlobal) => {
3592
+ const previous = previousSession ?? currentGlobal;
3593
+ const candidate = {
3594
+ ...baseSnapshot,
3595
+ rateLimits: { ...baseSnapshot.rateLimits }
3596
+ };
3597
+ if (previous?.provider === "claude" && previous?.sourceType === "statusline") {
3598
+ const sameSession = previous.sessionId && candidate.sessionId && previous.sessionId === candidate.sessionId;
3599
+ if (!candidate.rateLimits.fiveHour) {
3600
+ candidate.rateLimits.fiveHour = previous.rateLimits?.fiveHour ?? null;
3601
+ }
3602
+ if (!candidate.rateLimits.sevenDay) {
3603
+ candidate.rateLimits.sevenDay = previous.rateLimits?.sevenDay ?? null;
3604
+ }
3605
+ if (sameSession && !candidate.contextWindow) {
3606
+ candidate.contextWindow = previous.contextWindow ?? null;
3607
+ }
3148
3608
  }
3149
- if (sameSession && !snapshot.contextWindow) {
3150
- snapshot.contextWindow = previous.contextWindow ?? null;
3609
+ return claudeCanonicalStatuslineSnapshot(candidate, currentGlobal);
3610
+ };
3611
+
3612
+ const sameSemanticSnapshot = (left, right) => Boolean(
3613
+ left && right
3614
+ && left.sessionId === right.sessionId
3615
+ && left.sessionKind === right.sessionKind
3616
+ && isDeepStrictEqual(left.rateLimits, right.rateLimits)
3617
+ && isDeepStrictEqual(left.contextWindow, right.contextWindow)
3618
+ && isDeepStrictEqual(left.model, right.model)
3619
+ && isDeepStrictEqual(left.workspace, right.workspace)
3620
+ );
3621
+
3622
+ let snapshot;
3623
+ if (sessionKind !== "bg") {
3624
+ const existingGlobal = readJson(globalPath);
3625
+ const preview = mergeWithGlobal(existingGlobal);
3626
+ const globalAgeMs = existingGlobal?.capturedAt ? Date.now() - (Date.parse(existingGlobal.capturedAt) || 0) : Infinity;
3627
+ if (existingGlobal && sameSemanticSnapshot(preview, existingGlobal) && globalAgeMs >= 0 && globalAgeMs < 5000) {
3628
+ snapshot = existingGlobal;
3629
+ } else {
3630
+ try {
3631
+ snapshot = withFileLock(`${globalPath}.lock`, () => {
3632
+ const currentGlobal = readJson(globalPath);
3633
+ const canonical = mergeWithGlobal(currentGlobal);
3634
+ writeJsonAtomic(globalPath, canonical);
3635
+ return canonical;
3636
+ }, { timeoutMs: 1000 });
3637
+ } catch {
3638
+ // Lock unavailable or timed out: compute canonical snapshot in-memory without an unlocked write.
3639
+ snapshot = mergeWithGlobal(readJson(globalPath));
3640
+ }
3151
3641
  }
3642
+ } else {
3643
+ snapshot = mergeWithGlobal(readJson(globalPath));
3152
3644
  }
3153
3645
 
3154
- snapshot = claudeCanonicalStatuslineSnapshot(snapshot, previousGlobal);
3155
-
3156
3646
  if (snapshot.sessionId) {
3157
- writeJsonAtomic(claudeSessionCachePath(snapshot.sessionId), snapshot);
3158
- }
3159
- if (sessionKind !== "bg") {
3160
- writeJsonAtomic(claudeCachePath(), snapshot);
3647
+ const sessionAgeMs = previousSession?.capturedAt ? Date.now() - (Date.parse(previousSession.capturedAt) || 0) : Infinity;
3648
+ if (!previousSession || !sameSemanticSnapshot(snapshot, previousSession) || sessionAgeMs < 0 || sessionAgeMs >= 5000) {
3649
+ writeJsonAtomic(claudeSessionCachePath(snapshot.sessionId), snapshot);
3650
+ }
3161
3651
  }
3162
3652
  return snapshot;
3163
3653
  }
@@ -3236,19 +3726,35 @@ function readClaudeStatuslineCacheFrom(root) {
3236
3726
  return [globalCachePath, ...sessionCachePaths].some((cachePath) => fs.existsSync(cachePath)) ? null : undefined;
3237
3727
  }
3238
3728
 
3239
- function readClaudeStatuslineCache() {
3240
- const shared = readClaudeStatuslineCacheFrom(claudeStateDir());
3241
- if (shared !== undefined) return shared;
3242
-
3243
- // Under WSL the shared Windows cache may be empty on first use; fall back to
3244
- // the WSL-local state dir before the legacy directory.
3245
- if (path.resolve(claudeStateDir()) !== path.resolve(stateDir())) {
3246
- const local = readClaudeStatuslineCacheFrom(stateDir());
3247
- if (local !== undefined) return local;
3729
+ function claudeReadingCompare(a, b) {
3730
+ for (const key of ["primary", "secondary"]) {
3731
+ const left = a?.[key];
3732
+ const right = b?.[key];
3733
+ if (!left || !right) continue;
3734
+ const winMin = left.windowMinutes ?? right.windowMinutes ?? (key === "primary" ? 300 : 10080);
3735
+ const leftReset = resetEpochSeconds(left.resetsAt);
3736
+ const rightReset = resetEpochSeconds(right.resetsAt);
3737
+ const leftPlausible = isPlausibleResetEpoch(leftReset, winMin);
3738
+ const rightPlausible = isPlausibleResetEpoch(rightReset, winMin);
3739
+ if (leftPlausible && !rightPlausible) return -1;
3740
+ if (!leftPlausible && rightPlausible) return 1;
3741
+ if (leftPlausible && rightPlausible && Math.abs(leftReset - rightReset) > 60) {
3742
+ return rightReset - leftReset;
3743
+ }
3744
+ if (Number.isFinite(left.usedPercent) && Number.isFinite(right.usedPercent) && left.usedPercent !== right.usedPercent) {
3745
+ return right.usedPercent - left.usedPercent;
3746
+ }
3747
+ if (Number.isFinite(left.remainingPercent) && Number.isFinite(right.remainingPercent) && left.remainingPercent !== right.remainingPercent) {
3748
+ return left.remainingPercent - right.remainingPercent;
3749
+ }
3248
3750
  }
3751
+ return (Date.parse(b?.timestamp || "") || 0) - (Date.parse(a?.timestamp || "") || 0);
3752
+ }
3249
3753
 
3250
- if (path.resolve(legacyStateDir()) === path.resolve(stateDir())) return null;
3251
- return readClaudeStatuslineCacheFrom(legacyStateDir()) ?? null;
3754
+ function readClaudeStatuslineCache() {
3755
+ const readings = uniquePaths([claudeStateDir(), stateDir(), legacyStateDir()])
3756
+ .map(root => readClaudeStatuslineCacheFrom(root)).filter(Boolean);
3757
+ return readings.sort(claudeReadingCompare)[0] ?? null;
3252
3758
  }
3253
3759
 
3254
3760
  function claudeStatuslineRefreshInterval() {
@@ -3279,9 +3785,8 @@ function installClaudeStatusline(args) {
3279
3785
  "1"
3280
3786
  ];
3281
3787
  if (args.header === false) commandParts.push("--no-header");
3282
- if (args.usageRow === false || (process.platform === "win32" && args.usageRow !== true)) commandParts.push("--no-usage-row");
3788
+ if (args.usageRow === false) commandParts.push("--no-usage-row");
3283
3789
  if (args.usageRow === true) commandParts.push("--usage-row");
3284
- if (process.platform === "win32") commandParts.push("--attach-hud");
3285
3790
  const command = commandParts.join(" ");
3286
3791
  const installedByAiBattery = managedClaudeStatusLine(existing.statusLine);
3287
3792
  const config = readConfig({ strict: true });
@@ -3404,7 +3909,7 @@ function codexSharedLimit(limit) {
3404
3909
 
3405
3910
  function codexAccountUsageSnapshot(scan) {
3406
3911
  if (!scan?.ok || codexUsageTimestamp(scan) === null) return null;
3407
- if (![scan.percentRemaining, scan.primary?.percentRemaining, scan.secondary?.percentRemaining].some(Number.isFinite)) return null;
3912
+ if (![scan.percentRemaining, scan.primary?.remainingPercent, scan.secondary?.remainingPercent].some(Number.isFinite)) return null;
3408
3913
  return {
3409
3914
  timestamp: scan.timestamp,
3410
3915
  planType: scan.planType ?? null,
@@ -3426,33 +3931,33 @@ function readCodexAccountUsage() {
3426
3931
  function writeCodexAccountUsage(scan) {
3427
3932
  const usage = codexAccountUsageSnapshot(scan);
3428
3933
  if (!usage) return false;
3429
- const existing = readCodexAccountUsage();
3430
- const existingTimestamp = codexUsageTimestamp(existing);
3431
- const usageTimestamp = codexUsageTimestamp(usage);
3432
- if (existingTimestamp > usageTimestamp) return false;
3433
- if (existingTimestamp === usageTimestamp && isDeepStrictEqual(existing, usage)) return false;
3434
- try {
3435
- writeJsonAtomic(codexAccountUsagePath(), {
3934
+ return publishNewest(codexAccountUsagePath(), {
3436
3935
  version: CODEX_ACCOUNT_USAGE_VERSION,
3437
3936
  capturedAt: new Date().toISOString(),
3438
3937
  usage
3439
- });
3440
- return true;
3441
- } catch {
3442
- return false;
3443
- }
3938
+ }, { read: readJson, write: writeJsonAtomic, timestamp: value => value?.usage?.timestamp }).changed;
3939
+ }
3940
+
3941
+ function codexLimitWithResetsIn(limit) {
3942
+ if (!limit || typeof limit !== "object") return limit;
3943
+ const resetSec = resetEpochSeconds(limit.resetsAt);
3944
+ if (!Number.isFinite(resetSec) || resetSec <= 0) return limit;
3945
+ return { ...limit, resetsInSeconds: Math.max(0, Math.round(resetSec - Date.now() / 1000)) };
3444
3946
  }
3445
3947
 
3446
3948
  function mergeCodexAccountUsage(scan, sharedUsage) {
3447
3949
  if (!sharedUsage || codexUsageTimestamp(sharedUsage) === null) return scan;
3448
3950
  const localTimestamp = codexUsageTimestamp(scan);
3449
- if (scan?.ok && localTimestamp !== null && localTimestamp >= codexUsageTimestamp(sharedUsage)) return scan;
3951
+ if (scan?.ok && localTimestamp !== null && localTimestamp > codexUsageTimestamp(sharedUsage)) return scan;
3952
+ if (scan?.ok && localTimestamp === codexUsageTimestamp(sharedUsage) && isDeepStrictEqual(codexAccountUsageSnapshot(scan), sharedUsage)) return scan;
3450
3953
 
3451
3954
  const result = {
3452
3955
  ...(scan && typeof scan === "object" ? scan : {}),
3453
3956
  provider: "codex",
3454
3957
  ok: true,
3455
3958
  ...sharedUsage,
3959
+ primary: codexLimitWithResetsIn(sharedUsage.primary),
3960
+ secondary: codexLimitWithResetsIn(sharedUsage.secondary),
3456
3961
  sharedUsage: true,
3457
3962
  usageUpdate: {
3458
3963
  timestamp: sharedUsage.timestamp,
@@ -3609,17 +4114,20 @@ function readCodex(options = {}) {
3609
4114
  .digest("hex");
3610
4115
  // Changed usage logs must be visible on the next poll, even within the TTL.
3611
4116
  let scan = cached?.value;
3612
- if (cached?.inputFingerprint && cached.inputFingerprint !== inputFingerprint) scan = null;
3613
- if (!options.cachedOnly && cached?.inputFingerprint !== inputFingerprint) scan = null;
4117
+ // Backfill legacy scan caches (lacking usageEventOrder/inputFingerprint) into
4118
+ // shared account usage; publishNewest() keeps this a no-op when already current.
4119
+ if (scan?.ok) writeCodexAccountUsage(scan);
4120
+ if (cached?.usageEventOrder !== "timestamp") scan = null;
4121
+ if (cached?.inputFingerprint !== inputFingerprint) scan = null;
3614
4122
  if (!scan || typeof scan !== "object") {
3615
4123
  if (options.cachedOnly) return null;
3616
4124
  scan = scanCodexStatus(files, roots);
3617
- writeScanCache("codex-status", scan, { inputFingerprint });
4125
+ writeScanCache("codex-status", scan, { inputFingerprint, usageEventOrder: "timestamp" });
3618
4126
  }
3619
4127
  writeCodexAccountUsage(scan);
3620
4128
  scan = mergeCodexAccountUsage(scan, readCodexAccountUsage());
3621
4129
 
3622
- const processes = options.includeRunning === false ? null : scanProcessCommands();
4130
+ const processes = options.includeRunning === false ? null : scanProcessCommands(options.processOptions);
3623
4131
  const running = typeof options.runningOverride === "boolean"
3624
4132
  ? options.runningOverride
3625
4133
  : (
@@ -3631,22 +4139,48 @@ function readCodex(options = {}) {
3631
4139
  ? codexBackgroundReadyInProcesses(processes)
3632
4140
  : Boolean(scan.backgroundReady);
3633
4141
  const result = { ...scan, running, backgroundReady };
4142
+ for (const window of ["primary", "secondary"]) {
4143
+ const reset = resetEpochSeconds(result[window]?.resetsAt);
4144
+ if (reset > 0 && reset <= Date.now() / 1000) {
4145
+ result[window] = {
4146
+ ...result[window],
4147
+ remainingPercent: 100,
4148
+ usedPercent: 0,
4149
+ resetsInSeconds: 0,
4150
+ resetPassed: true
4151
+ };
4152
+ if (window === "primary") {
4153
+ result.ok = true;
4154
+ result.percentRemaining = 100;
4155
+ result.percentUsed = 0;
4156
+ result.error = null;
4157
+ }
4158
+ }
4159
+ }
3634
4160
  if (result.ok) result.ageSeconds = cacheAgeSeconds(result.timestamp ?? null);
3635
4161
  return result;
3636
4162
  }
3637
4163
 
3638
- function readCodexForClaudeCapture() {
3639
- if (process.platform !== "win32") return readCodex();
3640
-
3641
- const cached = readCodex({
3642
- cachedOnly: true,
3643
- maxAgeSeconds: CLAUDE_CODEX_CACHE_SECONDS
3644
- });
3645
- if (cached) return cached;
4164
+ function scheduleBackgroundProcessRefresh() {
4165
+ try {
4166
+ const marker = path.join(stateDir(), "process-refresh.stamp");
4167
+ const stat = safeStat(marker);
4168
+ if (stat && Date.now() - stat.mtimeMs < 5000) return;
4169
+ fs.mkdirSync(path.dirname(marker), { recursive: true });
4170
+ fs.writeFileSync(marker, `${process.pid}\n`);
4171
+ const child = spawn(process.execPath, [path.join(scriptDir(), "ai-battery.js"), "--refresh-processes"], {
4172
+ cwd: os.tmpdir(),
4173
+ stdio: "ignore",
4174
+ detached: true,
4175
+ windowsHide: true
4176
+ });
4177
+ child.on("error", () => {});
4178
+ child.unref();
4179
+ } catch { /* Best-effort background refresh. */ }
4180
+ }
3646
4181
 
3647
- return readCodex({
3648
- maxAgeSeconds: CLAUDE_CODEX_FALLBACK_CACHE_SECONDS
3649
- });
4182
+ function readCodexForClaudeCapture(options = {}) {
4183
+ return readCodex(options);
3650
4184
  }
3651
4185
 
3652
4186
  function codexSessionFiles(roots) {
@@ -3676,11 +4210,11 @@ function scanCodexStatus(files, roots) {
3676
4210
  const usageMatch = latestMatchingJsonLine(files, isRateLimitLine, (json) => {
3677
4211
  if (!isCodexRateLimit(json)) return false;
3678
4212
  const limits = json.payload.rate_limits;
3679
- return Boolean(normalizeLimit(limits.primary) || normalizeLimit(limits.secondary));
3680
- });
4213
+ return Boolean(normalizeLimit(limits.primary, { inferResetPassed: false }) || normalizeLimit(limits.secondary, { inferResetPassed: false }));
4214
+ }, true);
3681
4215
  // Preserve a metadata-only snapshot when percentages have never been seen;
3682
4216
  // the renderer will show an unknown value rather than inventing a number.
3683
- const match = usageMatch?.json ? usageMatch : latestMatchingJsonLine(files, isRateLimitLine, isCodexRateLimit);
4217
+ const match = usageMatch?.json ? usageMatch : latestMatchingJsonLine(files, isRateLimitLine, isCodexRateLimit, true);
3684
4218
  const rateLimits = match?.json?.payload?.rate_limits;
3685
4219
 
3686
4220
  if (!rateLimits) {
@@ -3692,16 +4226,15 @@ function scanCodexStatus(files, roots) {
3692
4226
  };
3693
4227
  }
3694
4228
 
3695
- // The approval mode lives in turn_context events of the same session, so
3696
- // only that file needs a second look.
3697
- const sessionFiles = files.filter((file) => file.path === match.file);
3698
- const contextMatch = latestMatchingJsonLine(sessionFiles, (line) => line.includes("\"turn_context\""));
4229
+ // Usage is account-wide; runtime mode still belongs to the locally
4230
+ // prioritized session, even when a background session reports newer usage.
4231
+ const contextMatch = latestMatchingJsonLine(files, (line) => line.includes("\"turn_context\""));
3699
4232
  const turnContext = contextMatch?.json?.payload ?? null;
3700
4233
  const approvalPolicy = turnContext?.approval_policy ?? null;
3701
4234
  const sandboxMode = turnContext?.sandbox_policy?.type ?? null;
3702
4235
  const collaborationMode = turnContext?.collaboration_mode?.mode ?? null;
3703
- const primary = normalizeLimit(rateLimits.primary);
3704
- const secondary = normalizeLimit(rateLimits.secondary);
4236
+ const primary = normalizeLimit(rateLimits.primary, { inferResetPassed: false });
4237
+ const secondary = normalizeLimit(rateLimits.secondary, { inferResetPassed: false });
3705
4238
  const sessionMeta = codexSessionMeta(match.file);
3706
4239
  const timestamp = match.json.timestamp ?? null;
3707
4240
 
@@ -4158,7 +4691,11 @@ function usageTotal(usage) {
4158
4691
  function readClaude(options = {}) {
4159
4692
  const running = typeof options.runningOverride === "boolean"
4160
4693
  ? options.runningOverride
4161
- : isProviderRunning("claude");
4694
+ : isProviderRunning("claude", options.processOptions);
4695
+ if (options.capturedSnapshot) {
4696
+ const inMemory = claudeStatuslineResultFromCache(options.capturedSnapshot, claudeCachePath());
4697
+ if (inMemory) return { ...inMemory, running };
4698
+ }
4162
4699
  const statuslineCache = readClaudeStatuslineCache();
4163
4700
  if (statuslineCache) return { ...statuslineCache, running };
4164
4701
 
@@ -4225,8 +4762,11 @@ function readClaude(options = {}) {
4225
4762
  };
4226
4763
  }
4227
4764
 
4765
+ let sttyColumnsMemo;
4766
+
4228
4767
  function sttyColumns() {
4229
4768
  if (process.platform === "win32") return null;
4769
+ if (sttyColumnsMemo !== undefined) return sttyColumnsMemo;
4230
4770
 
4231
4771
  let ttyFd = null;
4232
4772
  try {
@@ -4237,8 +4777,10 @@ function sttyColumns() {
4237
4777
  timeout: 100
4238
4778
  }).trim();
4239
4779
  const [, columns] = output.split(/\s+/).map((part) => Number(part));
4240
- return numericColumn(columns);
4780
+ sttyColumnsMemo = numericColumn(columns);
4781
+ return sttyColumnsMemo;
4241
4782
  } catch {
4783
+ sttyColumnsMemo = null;
4242
4784
  return null;
4243
4785
  } finally {
4244
4786
  if (ttyFd !== null) {
@@ -4255,12 +4797,12 @@ function runtimeTerminalColumns() {
4255
4797
  return numericColumn(process.stdout.columns) ?? sttyColumns();
4256
4798
  }
4257
4799
 
4258
- function statusLineColumns(input) {
4800
+ function statusLineColumns(input, observedColumns = null) {
4259
4801
  const explicitColumns = numericColumn(process.env.AI_BATTERY_COLUMNS)
4260
4802
  ?? numericColumn(process.env.CLAUDEX_BATTERY_COLUMNS);
4261
4803
  if (explicitColumns) return explicitColumns;
4262
4804
 
4263
- const runtimeColumns = runtimeTerminalColumns();
4805
+ const runtimeColumns = runtimeTerminalColumns() ?? numericColumn(observedColumns);
4264
4806
  const payloadCandidates = [
4265
4807
  input.terminal?.columns,
4266
4808
  input.terminal?.cols,
@@ -4289,18 +4831,18 @@ function statusLineColumns(input) {
4289
4831
  return 80;
4290
4832
  }
4291
4833
 
4292
- function statusLineHeaderColumns(input, args) {
4834
+ function statusLineHeaderColumns(input, args, observedColumns = null) {
4293
4835
  const guard = numericGuard(process.env.AI_BATTERY_HEADER_COLUMN_GUARD)
4294
4836
  ?? numericGuard(process.env.CLAUDEX_BATTERY_HEADER_COLUMN_GUARD)
4295
4837
  ?? DEFAULT_STATUSLINE_HEADER_COLUMN_GUARD;
4296
- return Math.max(20, statusLineColumns(input) - guard - (Number(args.leftPadding) || 0));
4838
+ return Math.max(20, statusLineColumns(input, observedColumns) - guard - (Number(args.leftPadding) || 0));
4297
4839
  }
4298
4840
 
4299
- function statusLineUsableColumns(input) {
4841
+ function statusLineUsableColumns(input, observedColumns = null) {
4300
4842
  const guard = numericGuard(process.env.AI_BATTERY_COLUMN_GUARD)
4301
4843
  ?? numericGuard(process.env.CLAUDEX_BATTERY_COLUMN_GUARD)
4302
4844
  ?? DEFAULT_STATUSLINE_COLUMN_GUARD;
4303
- return Math.max(20, statusLineColumns(input) - guard);
4845
+ return Math.max(20, statusLineColumns(input, observedColumns) - guard);
4304
4846
  }
4305
4847
 
4306
4848
  function contextRemainingPercent(input, fallbackContext = null) {
@@ -4329,11 +4871,14 @@ function displayPath(dir) {
4329
4871
 
4330
4872
  function gitBranchFromDir(dir) {
4331
4873
  if (!dir) return null;
4874
+ const fast = readGitBranchFast(dir);
4875
+ if (fast) return fast;
4332
4876
  try {
4333
4877
  const branch = execFileSync("git", ["-C", dir, "branch", "--show-current"], {
4334
4878
  encoding: "utf8",
4335
4879
  stdio: ["ignore", "pipe", "ignore"],
4336
- timeout: 500
4880
+ timeout: 500,
4881
+ windowsHide: true
4337
4882
  }).trim();
4338
4883
  return branch || null;
4339
4884
  } catch {
@@ -4352,7 +4897,7 @@ function statuslineGitBranch(input) {
4352
4897
  || null;
4353
4898
  if (explicit) return explicit;
4354
4899
 
4355
- const dirs = [
4900
+ const dirs = uniquePaths([
4356
4901
  input.workspace?.current_dir,
4357
4902
  input.workspace?.currentDir,
4358
4903
  input.cwd,
@@ -4360,7 +4905,7 @@ function statuslineGitBranch(input) {
4360
4905
  input.currentDir,
4361
4906
  input.workspace?.project_dir,
4362
4907
  input.workspace?.projectDir
4363
- ].filter(Boolean);
4908
+ ].filter(Boolean));
4364
4909
 
4365
4910
  for (const dir of dirs) {
4366
4911
  const branch = gitBranchFromDir(dir);
@@ -4369,7 +4914,7 @@ function statuslineGitBranch(input) {
4369
4914
  return null;
4370
4915
  }
4371
4916
 
4372
- function claudeHeader(input, args, capturedClaude = null) {
4917
+ function claudeHeader(input, args, capturedClaude = null, observedColumns = null) {
4373
4918
  const model = typeof input.model === "string"
4374
4919
  ? input.model
4375
4920
  : input.model?.display_name || input.model?.displayName || input.model?.id || (input.product === "antigravity" ? providerLabel("antigravity") : "Claude");
@@ -4395,7 +4940,7 @@ function claudeHeader(input, args, capturedClaude = null) {
4395
4940
  if (changes) parts.push("·", changes);
4396
4941
  const context = contextLeftText(input, capturedClaude?.contextWindow ?? null);
4397
4942
  if (context) parts.push("·", context);
4398
- const columns = statusLineHeaderColumns(input, args);
4943
+ const columns = statusLineHeaderColumns(input, args, observedColumns);
4399
4944
  const header = truncateMiddleVisible(parts.join(" "), columns);
4400
4945
  return statusColorize({ running: false }, header, args);
4401
4946
  }
@@ -4425,8 +4970,19 @@ function weekText(secondary) {
4425
4970
  }
4426
4971
 
4427
4972
  function formatCodex(data, args) {
4428
- if (!data.ok) return statusColorize(data, args.maxWidth && !args.showPaths
4429
- ? "Codex --%" : `Codex ? (${cliMessageText(data.error)})`, args);
4973
+ if (!data.ok) {
4974
+ if (args.maxWidth && !args.showPaths) {
4975
+ const hasValidSecondary = args.showSecondary !== false
4976
+ && data.secondary
4977
+ && Number.isFinite(data.secondary.remainingPercent)
4978
+ && !data.secondary.resetPassed;
4979
+ if (hasValidSecondary) {
4980
+ return `${statusColorize(data, "Codex --%", args)} ${divider(args)} ${statusColorize(data, weekText(data.secondary), args)}`;
4981
+ }
4982
+ return statusColorize(data, "Codex --%", args);
4983
+ }
4984
+ return statusColorize(data, `Codex ? (${cliMessageText(data.error)})`, args);
4985
+ }
4430
4986
 
4431
4987
  const batteryColor = remainingColor(data.percentRemaining);
4432
4988
  const primary = data.primary;
@@ -4465,7 +5021,7 @@ function formatClaude(data, args) {
4465
5021
  if (data.sourceType === "statusline") {
4466
5022
  const batteryColor = remainingColor(data.percentRemaining);
4467
5023
  const bits = [
4468
- `${statusColorize(data, "Claude ", args)}${bar(data.percentRemaining, args.barWidth, batteryColor, args.style)}${statusColorize(data, ` ${data.percentRemaining}%`, args)}`
5024
+ `${statusColorize(data, "Claude ", args)}${bar(data.percentRemaining, args.barWidth, batteryColor, args.style)}${statusColorize(data, ` ${Number.isFinite(data.percentRemaining) ? data.percentRemaining : "--"}%`, args)}`
4469
5025
  ];
4470
5026
  if (args.showPrimary !== false) {
4471
5027
  const primaryReset = limitResetText(data.primary);
@@ -4503,7 +5059,7 @@ function formatClaude(data, args) {
4503
5059
  function formatAntigravity(data, args) {
4504
5060
  const name = providerLabel("antigravity");
4505
5061
  if (!data.ok || typeof data.percentRemaining !== "number") {
4506
- const amounts = data.quotas?.filter(quota => quota.remainingAmount !== null)
5062
+ const amounts = data.quotas?.filter(quota => quota.remainingAmount != null)
4507
5063
  .map(quota => `${quota.id} ${quota.remainingAmount}`).join(" · ");
4508
5064
  return statusColorize(data, amounts && args.showSecondary !== false ? `${name} ${amounts}` : `${name} --%`, args);
4509
5065
  }
@@ -4525,17 +5081,23 @@ function compactNumber(value) {
4525
5081
  }
4526
5082
 
4527
5083
  function runningOverrideForProvider(args, provider) {
5084
+ if (args.runningProviders instanceof Set) return args.runningProviders.has(provider);
4528
5085
  if (args.activeProvider === provider) return true;
4529
5086
  return null;
4530
5087
  }
4531
5088
 
5089
+ function renderTmuxUsage(runningProviders, maxWidth) {
5090
+ const args = { provider: "all", runningProviders, style: "tmux", barWidth: 10, maxWidth, leftPadding: 0 };
5091
+ return render(collect(args), args);
5092
+ }
5093
+
4532
5094
  function collect(args) {
4533
5095
  const results = [];
4534
5096
  const includeHidden = args.provider !== "all";
4535
5097
  if ((args.provider === "all" || args.provider === "codex") && (includeHidden || providerVisible("codex"))) {
4536
5098
  results.push(readCodex({
4537
5099
  runningOverride: runningOverrideForProvider(args, "codex"),
4538
- includeRunning: args.activeProvider !== "codex"
5100
+ includeRunning: !(args.runningProviders instanceof Set) && args.activeProvider !== "codex"
4539
5101
  }));
4540
5102
  }
4541
5103
  if ((args.provider === "all" || args.provider === "claude") && (includeHidden || providerVisible("claude"))) {
@@ -4785,27 +5347,36 @@ function menuBatteryColor(percent, running = true) {
4785
5347
  return MENU_DETAIL_GREEN;
4786
5348
  }
4787
5349
 
4788
- function renderMenuBarSvgIcon(icon, x, y, height) {
5350
+ function resolveCodexMenuBarColor(codexIcon) {
5351
+ const mode = String(codexIcon || process.env.AI_BATTERY_CODEX_ICON_COLOR || "").trim().toLowerCase();
5352
+ if (mode === "black") return "#000000";
5353
+ if (mode === "white") return "#FFFFFF";
5354
+ return CODEX_MENU_BAR_COLOR;
5355
+ }
5356
+
5357
+ function renderMenuBarSvgIcon(icon, x, y, height, colorOverride = null) {
4789
5358
  const scale = height / icon.viewBox;
4790
5359
  const paths = icon.paths || [{ d: icon.path }];
5360
+ const fillColor = colorOverride || icon.color;
4791
5361
  const renderedPaths = paths.map((iconPath) => {
4792
5362
  const ruleAttrs = [
4793
5363
  iconPath.fillRule ? ` fill-rule="${iconPath.fillRule}"` : "",
4794
5364
  iconPath.clipRule ? ` clip-rule="${iconPath.clipRule}"` : ""
4795
5365
  ].join("");
4796
- return `<path d="${iconPath.d}" fill="${icon.color}"${ruleAttrs}/>`;
5366
+ return `<path d="${iconPath.d}" fill="${fillColor}"${ruleAttrs}/>`;
4797
5367
  }).join("");
4798
5368
  return `<g transform="translate(${x} ${y}) scale(${scale})">${renderedPaths}</g>`;
4799
5369
  }
4800
5370
 
4801
- function menuBarImageIcon(provider, x, y) {
5371
+ function menuBarImageIcon(provider, x, y, { codexIcon = null } = {}) {
4802
5372
  if (provider === "antigravity") {
4803
5373
  const svg = fs.readFileSync(path.join(scriptDir(), "..", "docs", "antigravity-icon.svg"), "utf8");
4804
5374
  return svg.replace(/<svg\b[^>]*>/, `<svg x="${x}" y="${y}" width="19" height="19" viewBox="0 0 180 180" fill="none" xmlns="http://www.w3.org/2000/svg">`);
4805
5375
  }
4806
5376
  const height = provider === "codex" ? 19 : 17;
4807
5377
  const iconY = provider === "codex" ? y - 0.5 : y;
4808
- if (provider === "codex") {
5378
+ const codexColor = resolveCodexMenuBarColor(codexIcon);
5379
+ if (provider === "codex" && codexColor !== "#000000") {
4809
5380
  const pngIconPath = codexMenuBarPngIconPath();
4810
5381
  if (pngIconPath) {
4811
5382
  return `<image x="${x}" y="${iconY}" width="${height}" height="${height}" href="${imageDataUri(pngIconPath)}"/>`;
@@ -4815,15 +5386,18 @@ function menuBarImageIcon(provider, x, y) {
4815
5386
  const icon = provider === "codex"
4816
5387
  ? (codexMenuBarSvgIcon() || MENU_BAR_BRAND_ICONS.codex)
4817
5388
  : (MENU_BAR_BRAND_ICONS[provider] || MENU_BAR_BRAND_ICONS.codex);
4818
- return renderMenuBarSvgIcon(icon, x, iconY, height);
5389
+ return renderMenuBarSvgIcon(icon, x, iconY, height, provider === "codex" ? codexColor : null);
4819
5390
  }
4820
5391
 
4821
- function renderMenuBarImage(snapshot) {
5392
+ function renderMenuBarImage(snapshot, { codexIcon = null, text = null } = {}) {
4822
5393
  const startX = 0;
4823
5394
  const endPadding = 0;
4824
5395
  const providerWidth = 56;
4825
5396
  const providerContentWidth = 48;
4826
5397
  const height = 24;
5398
+ const textMode = String(text || process.env.AI_BATTERY_PANEL_TEXT || "white").trim().toLowerCase();
5399
+ const darkText = textMode === "black" || textMode === "dark";
5400
+ const effectiveCodexIcon = codexIcon || (darkText ? "black" : null);
4827
5401
  const visibleResults = orderResults(snapshot.results.filter(Boolean), configuredProviderOrder());
4828
5402
  const width = visibleResults.length
4829
5403
  ? startX + ((visibleResults.length - 1) * providerWidth) + providerContentWidth + endPadding
@@ -4838,32 +5412,35 @@ function renderMenuBarImage(snapshot) {
4838
5412
  const meterY = 3;
4839
5413
  const meterWidth = 24;
4840
5414
  const meterHeight = 5;
4841
- const meterStroke = 1.1;
5415
+ const meterStroke = 1;
4842
5416
  const meterInnerX = meterX + 2;
4843
- const meterInnerY = meterY + 1.7;
5417
+ const meterInnerY = meterY + 2;
4844
5418
  const meterInnerWidth = meterWidth - 4;
4845
- const meterInnerHeight = meterHeight - 3.4;
5419
+ const meterInnerHeight = meterHeight - 3;
4846
5420
  const fillWidth = percent === null ? 0 : Math.max(percent > 0 ? 2 : 0, Math.round((percent / 100) * meterInnerWidth));
4847
- const fill = menuBatteryColor(percent, running);
5421
+ const fill = darkText && (!running || typeof percent !== "number") ? "#5C5C66" : menuBatteryColor(percent, running);
4848
5422
  const label = percent === null ? "--" : `${Math.round(percent)}%`;
4849
5423
  const labelX = meterX + (meterWidth / 2);
4850
- const textFill = running ? MENU_BAR_WHITE : MENU_DIM_TEXT;
5424
+ const textFill = darkText
5425
+ ? (running ? "#141418" : "#5C5C66")
5426
+ : (running ? MENU_BAR_WHITE : MENU_DIM_TEXT);
5427
+ const outlineStroke = darkText ? "#141418" : MENU_BAR_WHITE;
4851
5428
  const outlineOpacity = running ? MENU_BAR_OUTLINE_OPACITY : MENU_DIM_OUTLINE_OPACITY;
4852
5429
 
4853
- items.push(menuBarImageIcon(result.provider, x, 3));
4854
- items.push(`<rect x="${meterX}" y="${meterY}" width="${meterWidth}" height="${meterHeight}" rx="2.5" fill="none" stroke="${MENU_BAR_WHITE}" stroke-opacity="${outlineOpacity}" stroke-width="${meterStroke}"/>`);
5430
+ items.push(menuBarImageIcon(result.provider, x, 3, { codexIcon: effectiveCodexIcon }));
5431
+ items.push(`<rect x="${meterX + 0.5}" y="${meterY + 0.5}" width="${meterWidth - 1}" height="${meterHeight}" rx="2.5" fill="none" stroke="${outlineStroke}" stroke-opacity="${outlineOpacity}" stroke-width="${meterStroke}"/>`);
4855
5432
  if (fillWidth > 0) {
4856
- items.push(`<rect x="${meterInnerX}" y="${meterInnerY}" width="${fillWidth}" height="${meterInnerHeight}" rx="0.8" fill="${fill}"/>`);
5433
+ items.push(`<rect x="${meterInnerX}" y="${meterInnerY}" width="${fillWidth}" height="${meterInnerHeight}" rx="0.5" fill="${fill}"/>`);
4857
5434
  }
4858
- items.push(`<text x="${labelX}" y="21" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'SF Pro Text', sans-serif" font-size="9.5" font-weight="650" fill="${textFill}">${svgEscape(label)}</text>`);
5435
+ items.push(`<text x="${labelX}" y="21.5" text-anchor="middle" font-family="-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Ubuntu', 'Noto Sans', sans-serif" font-size="10.5" font-weight="700" fill="${textFill}">${svgEscape(label)}</text>`);
4859
5436
  });
4860
5437
 
4861
5438
  if (!items.length) {
4862
- items.push(`<text x="9" y="16" font-family="-apple-system, BlinkMacSystemFont, sans-serif" font-size="11" font-weight="650" fill="${MENU_BAR_WHITE}">AI --</text>`);
5439
+ items.push(`<text x="9" y="16" font-family="-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Ubuntu', 'Noto Sans', sans-serif" font-size="11" font-weight="650" fill="${darkText ? "#141418" : MENU_BAR_WHITE}">AI --</text>`);
4863
5440
  }
4864
5441
 
4865
5442
  const svg = [
4866
- `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`,
5443
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" text-rendering="geometricPrecision" shape-rendering="geometricPrecision">`,
4867
5444
  ...items,
4868
5445
  "</svg>",
4869
5446
  ""
@@ -4995,14 +5572,145 @@ function renderMenuDetailImage(snapshot) {
4995
5572
  throw new Error("Could not write macOS menu detail image");
4996
5573
  }
4997
5574
 
4998
- function desktopHudSnapshot(provider = "all") {
5575
+ function railProviderTag(provider) {
5576
+ if (provider === "codex") return "CDX";
5577
+ if (provider === "claude") return "CLD";
5578
+ if (provider === "antigravity") return "AGY";
5579
+ return "AI";
5580
+ }
5581
+
5582
+ function railProviderTagColor(provider, running, darkText = false) {
5583
+ if (provider === "antigravity") {
5584
+ if (darkText) return running ? "#2563EB" : "#4B76C8";
5585
+ return running ? "#60A5FA" : "#4C84CC";
5586
+ }
5587
+ if (provider === "claude") {
5588
+ if (darkText) return running ? "#D97706" : "#B47030";
5589
+ return running ? "#F97316" : "#CC6E2A";
5590
+ }
5591
+ if (darkText) return running ? "#141418" : "#5C5C66";
5592
+ return running ? "#FFFFFF" : "#CCCCD4";
5593
+ }
5594
+
5595
+ function railWindowParts(limit, fallbackLabel, fallbackValue, preferPercent = false) {
5596
+ if (!limit) return { label: fallbackLabel, value: fallbackValue };
5597
+ const label = limit.windowMinutes ? shortWindow(limit.windowMinutes) : (limit.id || fallbackLabel);
5598
+ const value = preferPercent
5599
+ ? (typeof limit.remainingPercent === "number" ? `${Math.round(limit.remainingPercent)}%` : resetClock(limit))
5600
+ : (label === "5h" ? resetClock(limit) : (typeof limit.remainingPercent === "number" ? `${Math.round(limit.remainingPercent)}%` : resetClock(limit)));
5601
+ return { label, value: value || fallbackValue };
5602
+ }
5603
+
5604
+ function renderRailImage(snapshot, { scale = 1, backdrop = false, text = null } = {}) {
5605
+ const safeScale = Number.isFinite(Number(scale)) ? clamp(Number(scale), 0.5, 3) : 1;
5606
+ const textMode = String(text || process.env.AI_BATTERY_RAIL_TEXT || "white").trim().toLowerCase();
5607
+ const darkText = textMode === "black" || textMode === "dark";
5608
+ const visibleResults = orderResults(snapshot.results.filter(Boolean), configuredProviderOrder());
5609
+ const width = 44;
5610
+ const padY = 8;
5611
+ const tagH = 14;
5612
+ const tagGap = 3;
5613
+ const batH = 30;
5614
+ const batGap = 3;
5615
+ const pctH = 14;
5616
+ const pctGap = 2;
5617
+ const lblH = 10;
5618
+ const valH = 12;
5619
+ const pairGap = 3;
5620
+ const divGap = 11;
5621
+ const blockH = (tagH + tagGap) + (batH + batGap) + (pctH + pctGap) + (lblH + valH + pairGap) + (lblH + valH);
5622
+ const count = Math.max(1, visibleResults.length);
5623
+ const height = (padY * 2) + (count * blockH) + (Math.max(0, count - 1) * divGap);
5624
+ const scaledWidth = Math.max(24, Math.round(width * safeScale));
5625
+ const scaledHeight = Math.max(32, Math.round(height * safeScale));
5626
+ const centerX = width / 2;
5627
+ const sansFont = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Ubuntu', 'Noto Sans', sans-serif";
5628
+ const monoFont = "'SF Mono', 'Cascadia Mono', 'JetBrains Mono', 'Ubuntu Mono', monospace";
5629
+ const items = backdrop
5630
+ ? [`<rect x="0.5" y="0.5" width="${width - 1}" height="${height - 1}" rx="8" fill="#1C1C20" fill-opacity="0.92" stroke="#44444A" stroke-width="1"/>`]
5631
+ : [];
5632
+
5633
+ if (!visibleResults.length) {
5634
+ items.push(`<text x="${centerX}" y="${Math.round(height / 2) + 4}" text-anchor="middle" font-family="${monoFont}" font-size="10.5" font-weight="700" fill="${darkText ? "#6C6C74" : "#9A9AA4"}">AI--</text>`);
5635
+ } else {
5636
+ let y = padY;
5637
+ visibleResults.forEach((result, index) => {
5638
+ if (index > 0) {
5639
+ const divY = y + Math.floor(divGap / 2) + 0.5;
5640
+ items.push(`<line x1="6" y1="${divY}" x2="${width - 6}" y2="${divY}" stroke="${darkText ? "#AAAAB4" : "#4A4A54"}" stroke-width="1"/>`);
5641
+ y += divGap;
5642
+ }
5643
+ const running = result.running === true;
5644
+ const percent = typeof result.percentRemaining === "number" ? clamp(result.percentRemaining, 0, 100) : null;
5645
+ const primaryColor = running
5646
+ ? (darkText ? "#141418" : "#F5F5F7")
5647
+ : (darkText ? "#6C6C74" : "#9A9AA4");
5648
+ const mutedColor = darkText ? "#787880" : "#80808A";
5649
+ const trackColor = darkText ? "#B4B4BC" : "#54545E";
5650
+ const tag = railProviderTag(result.provider);
5651
+ const tagColor = railProviderTagColor(result.provider, running, darkText);
5652
+
5653
+ items.push(`<text x="${centerX}" y="${y + 11}" text-anchor="middle" font-family="${monoFont}" font-size="11.5" font-weight="700" fill="${tagColor}">${svgEscape(tag)}</text>`);
5654
+ y += tagH + tagGap;
5655
+
5656
+ items.push(`<rect x="${centerX - 1}" y="${y}" width="2" height="${batH}" rx="1" fill="${trackColor}"/>`);
5657
+ if (percent !== null) {
5658
+ const fillH = percent > 0 ? Math.max(2, Math.round((percent / 100) * batH)) : 0;
5659
+ if (fillH > 0) {
5660
+ const fillColor = menuBatteryColor(percent, running);
5661
+ items.push(`<rect x="${centerX - 4}" y="${y + batH - fillH}" width="8" height="${fillH}" rx="1.5" fill="${fillColor}"/>`);
5662
+ }
5663
+ }
5664
+ y += batH + batGap;
5665
+
5666
+ const pctText = percent === null ? "--%" : `${Math.round(percent)}%`;
5667
+ const pctColor = running ? menuBatteryColor(percent, true) : primaryColor;
5668
+ items.push(`<text x="${centerX}" y="${y + 11}" text-anchor="middle" font-family="${sansFont}" font-size="10.5" font-weight="700" fill="${pctColor}">${svgEscape(pctText)}</text>`);
5669
+ y += pctH + pctGap;
5670
+
5671
+ const primary = railWindowParts(result.primary, "5h", "--:--", false);
5672
+ items.push(`<text x="${centerX}" y="${y + 8}" text-anchor="middle" font-family="${sansFont}" font-size="8.5" font-weight="500" fill="${mutedColor}">${svgEscape(primary.label)}</text>`);
5673
+ y += lblH;
5674
+ items.push(`<text x="${centerX}" y="${y + 10}" text-anchor="middle" font-family="${monoFont}" font-size="9.5" font-weight="500" fill="${primaryColor}">${svgEscape(primary.value)}</text>`);
5675
+ y += valH + pairGap;
5676
+
5677
+ const secondary = railWindowParts(result.secondary, "7d", "--%", true);
5678
+ items.push(`<text x="${centerX}" y="${y + 8}" text-anchor="middle" font-family="${sansFont}" font-size="8.5" font-weight="500" fill="${mutedColor}">${svgEscape(secondary.label)}</text>`);
5679
+ y += lblH;
5680
+ items.push(`<text x="${centerX}" y="${y + 10}" text-anchor="middle" font-family="${monoFont}" font-size="9.5" font-weight="500" fill="${primaryColor}">${svgEscape(secondary.value)}</text>`);
5681
+ y += valH;
5682
+ });
5683
+ }
5684
+
5685
+ const svg = [
5686
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${scaledWidth}" height="${scaledHeight}" viewBox="0 0 ${width} ${height}" text-rendering="geometricPrecision" shape-rendering="geometricPrecision">`,
5687
+ ...items,
5688
+ "</svg>",
5689
+ ""
5690
+ ].join("\n");
5691
+
5692
+ for (const root of [stateDir(), path.join(os.tmpdir(), "ai-battery")]) {
5693
+ const filePath = path.join(root, "hud-rail.svg");
5694
+ try {
5695
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
5696
+ fs.writeFileSync(filePath, svg, "utf8");
5697
+ return filePath;
5698
+ } catch {
5699
+ // Fall back to the next writable location.
5700
+ }
5701
+ }
5702
+ throw new Error("Could not write HUD rail image");
5703
+ }
5704
+
5705
+ function desktopHudSnapshot(provider = "all", { codexIcon = null } = {}) {
4999
5706
  const args = parseArgs(["--provider", provider]);
5000
5707
  const snapshot = collect(args);
5001
5708
  return {
5002
5709
  generatedAt: snapshot.generatedAt,
5003
5710
  state: renderHudState(snapshot),
5004
- panelImage: renderMenuBarImage(snapshot),
5711
+ panelImage: renderMenuBarImage(snapshot, { codexIcon }),
5005
5712
  detailImage: renderMenuDetailImage(snapshot),
5713
+ railImage: renderRailImage(snapshot),
5006
5714
  text: renderLine(snapshot, { ...args, style: "plain" }),
5007
5715
  rows: snapshot.results.filter(Boolean).map((result) => ({
5008
5716
  provider: result.provider,
@@ -5030,8 +5738,9 @@ function render(snapshot, args) {
5030
5738
  snapshot = { ...snapshot, results: orderResults(snapshot.results, configuredProviderOrder()) };
5031
5739
  if (args.json) return JSON.stringify(snapshot, null, 2);
5032
5740
  if (args.hudState) return renderHudState(snapshot);
5033
- if (args.menuBarImage) return renderMenuBarImage(snapshot);
5741
+ if (args.menuBarImage) return renderMenuBarImage(snapshot, { codexIcon: args.codexIcon, text: args.panelText });
5034
5742
  if (args.menuDetailImage) return renderMenuDetailImage(snapshot);
5743
+ if (args.railImage) return renderRailImage(snapshot, { scale: args.railScale, text: args.railText });
5035
5744
  if (args.menuBar) return renderMenuBar(snapshot);
5036
5745
 
5037
5746
  const maxWidth = args.maxWidth
@@ -5041,7 +5750,8 @@ function render(snapshot, args) {
5041
5750
  if (args.maxWidth) {
5042
5751
  // Use exact 10%, 20% or 25% steps. Keep 5h reset times after dropping
5043
5752
  // weekly detail, before spending the available space on longer bars.
5044
- const widths = [10, 5, 4].filter(width => width <= args.barWidth);
5753
+ const barWidth = Math.max(4, Number(args.barWidth) || 10);
5754
+ const widths = [10, 5, 4].filter(width => width <= barWidth);
5045
5755
  const fullWidth = widths[0];
5046
5756
  const shortWidth = widths.find(width => width <= 5);
5047
5757
  const candidates = [
@@ -5058,7 +5768,7 @@ function render(snapshot, args) {
5058
5768
  // names and readings rather than letting the one-row terminal wrap away
5059
5769
  // a provider. Detailed errors remain available in diagnostics.
5060
5770
  const readings = snapshot.results.map((result) => {
5061
- const percent = typeof result.percentRemaining === "number" ? `${result.percentRemaining}%` : "--%";
5771
+ const percent = result.ok && Number.isFinite(result.percentRemaining) ? `${result.percentRemaining}%` : "--%";
5062
5772
  const name = providerLabel(result.provider);
5063
5773
  return statusColorize(result, `${name} ${percent}`, args);
5064
5774
  }).join(` ${colorize(PROVIDER_DIVIDER, "gray", args.style)} `);
@@ -5103,31 +5813,69 @@ async function main() {
5103
5813
  }
5104
5814
 
5105
5815
  if (args.command === "config") {
5106
- const config = readConfig({ strict: true });
5107
- if (!args.providerOrder && !args.json && canEditConfig()) {
5108
- const edited = await editDisplayConfig(config, { color: args.style !== "plain" && !Object.hasOwn(process.env, "NO_COLOR") });
5816
+ const display = readDisplayConfig({ strict: true });
5817
+ if (!args.providerOrder && !args.barPosition && !args.json && canEditConfig()) {
5818
+ const edited = await editDisplayConfig(display, { color: args.style !== "plain" && !Object.hasOwn(process.env, "NO_COLOR") });
5109
5819
  if (!edited) {
5110
5820
  console.log(cliText("Configuration cancelled.", "설정을 취소했습니다."));
5111
5821
  return;
5112
5822
  }
5113
- // Merge with the latest settings so another process's changes survive the editor.
5114
- const latest = readConfig({ strict: true });
5115
- latest.providerOrder = edited.providerOrder;
5116
- Object.assign(latest.providers, edited.providerChanges);
5117
- writeConfig(latest);
5823
+ // Merge only changed fields inside the lock so concurrent edits survive.
5824
+ const saveBarPosition = edited.barPositionChanged || edited.positionTabVisited;
5825
+ const latest = updateDisplayConfig({
5826
+ ...(edited.orderChanged ? { providerOrder: edited.providerOrder } : {}),
5827
+ providers: edited.providerChanges,
5828
+ ...(saveBarPosition ? { barPosition: edited.barPosition } : {}),
5829
+ ...(edited.sidebarWidthChanged ? { sidebarWidth: edited.sidebarWidth } : {})
5830
+ });
5831
+ if ((saveBarPosition || edited.sidebarWidthChanged) && (process.platform === "win32" || isWsl())) {
5832
+ const effectiveWtPos = latest.splitBarPosition || latest.barPosition;
5833
+ if (!latest.splitBarPosition || edited.sidebarWidthChanged) {
5834
+ updateWtFragmentPosition({ position: effectiveWtPos, sidebarWidth: latest.sidebarWidth });
5835
+ }
5836
+ }
5837
+ if (latest.barPosition !== "bottom") {
5838
+ ensureCliPositionWrappers(["claude", "antigravity"], { updateShellPath: true });
5839
+ }
5118
5840
  const visible = latest.providerOrder.filter(provider => latest.providers[provider] !== false).map(providerLabel);
5119
5841
  console.log(`${cliText("Display settings saved", "표시 설정 저장")}: ${visible.join(" → ") || cliText("All hidden", "모두 숨김")}`);
5842
+ const posLabel = ({
5843
+ bottom: cliText("bottom", "하단 (bottom)"),
5844
+ top: cliText("top", "상단 (top)"),
5845
+ left: cliText("left", "좌측 (left)"),
5846
+ right: cliText("right", "우측 (right)")
5847
+ })[latest.barPosition] || latest.barPosition;
5848
+ console.log(`${cliText("Bar position", "상태바 위치")}: ${posLabel}${latest.splitBarPosition && latest.splitBarPosition !== latest.barPosition ? ` (${cliText("split", "통합 바")}: ${latest.splitBarPosition})` : ""}`);
5120
5849
  return;
5121
5850
  }
5122
- if (args.providerOrder) { config.providerOrder = args.providerOrder; writeConfig(config); }
5123
- const result = { configPath: configPath(), providerOrder: normalizeOrder(config.providerOrder, PROVIDERS),
5124
- providers: Object.fromEntries(PROVIDERS.map(provider => [provider, config.providers[provider] !== false])) };
5851
+ const current = (args.providerOrder || args.barPosition)
5852
+ ? updateDisplayConfig({
5853
+ ...(args.providerOrder ? { providerOrder: args.providerOrder } : {}),
5854
+ ...(args.barPosition ? { barPosition: args.barPosition } : {})
5855
+ })
5856
+ : display;
5857
+ if (args.barPosition && !current.splitBarPosition && (process.platform === "win32" || isWsl())) {
5858
+ updateWtFragmentPosition({ position: current.barPosition, sidebarWidth: current.sidebarWidth });
5859
+ }
5860
+ if (args.barPosition && current.barPosition !== "bottom") {
5861
+ ensureCliPositionWrappers(["claude", "antigravity"], { updateShellPath: true });
5862
+ }
5863
+ const result = {
5864
+ configPath: configPath(),
5865
+ displayConfigPath: displayConfigPath(),
5866
+ providerOrder: normalizeOrder(current.providerOrder, PROVIDERS),
5867
+ providers: Object.fromEntries(PROVIDERS.map(provider => [provider, current.providers[provider] !== false])),
5868
+ barPosition: current.barPosition,
5869
+ splitBarPosition: current.splitBarPosition || current.barPosition,
5870
+ sidebarWidth: current.sidebarWidth
5871
+ };
5125
5872
  if (args.json) console.log(JSON.stringify(result, null, 2));
5126
5873
  else {
5127
5874
  console.log(`${cliText("Display settings", "표시 설정")}: ${result.providerOrder.map(provider => `${providerLabel(provider)}${result.providers[provider] ? "" : cliText(" (hidden)", " (숨김)")}`).join(" → ")}`);
5128
- if (!args.providerOrder) {
5129
- console.log(cliText("Run ai-battery config in a terminal: arrows reorder, Space shows/hides, Enter saves, Esc cancels.", "터미널에서 ai-battery config를 실행하세요: 방향키 순서 이동 · Space 표시/숨김 · Enter 저장 · Esc 취소"));
5130
- console.log(`${cliText("Or use", "명령으로 변경")}: ai-battery config --provider-order ${result.providerOrder.map(provider => provider === "antigravity" ? "gemini" : provider).join(",")}`);
5875
+ console.log(`${cliText("Bar position", "상태바 위치")}: ${result.barPosition}${current.splitBarPosition && current.splitBarPosition !== result.barPosition ? ` (${cliText("split", "통합 바")}: ${current.splitBarPosition})` : ""}`);
5876
+ if (!args.providerOrder && !args.barPosition) {
5877
+ console.log(cliText("Run ai-battery config in a terminal: arrows reorder, Space shows/hides, Tab switches to bar position, Enter saves, Esc cancels.", "터미널에서 ai-battery config를 실행하세요: 방향키 순서 이동 · Space 표시/숨김 · Tab 상태바 위치 전환 · Enter 저장 · Esc 취소"));
5878
+ console.log(`${cliText("Or use", "명령으로 변경")}: ai-battery config --provider-order ${result.providerOrder.map(provider => provider === "antigravity" ? "gemini" : provider).join(",")} --position ${result.barPosition}`);
5131
5879
  }
5132
5880
  }
5133
5881
  return;
@@ -5158,6 +5906,146 @@ async function main() {
5158
5906
  process.exit(result.status ?? 0);
5159
5907
  }
5160
5908
 
5909
+ if (args.refreshProcesses) {
5910
+ scanProcessCommands({ forceRefresh: true });
5911
+ return;
5912
+ }
5913
+
5914
+ if (args.sharedBarState) {
5915
+ const { root, context } = JSON.parse(Buffer.from(args.sharedBarState, "base64").toString("utf8"));
5916
+ if (!root || !validBarContext(context)) throw new Error("Invalid shared bar context");
5917
+ const isAlive = createCrossOsSessionAlive({ root, context });
5918
+ const sessions = listActiveAiSessions({ root, context, isAlive });
5919
+ const runningProviders = new Set(sessions.map(session => session.provider));
5920
+ console.log(JSON.stringify({
5921
+ ...collect({ ...args, runningProviders }),
5922
+ sharedBar: {
5923
+ sessionCount: sessions.length,
5924
+ mode: resolveSplitBarMode().mode,
5925
+ position: readConfiguredSplitBarPosition()
5926
+ }
5927
+ }));
5928
+ return;
5929
+ }
5930
+
5931
+ if (args.paneDecisionProvider) {
5932
+ const provider = providerId(args.paneDecisionProvider) || "codex";
5933
+ const decision = paneUsageDecision(provider, {
5934
+ ownerPid: args.ownerPid,
5935
+ cols: args.paneCols,
5936
+ rows: args.paneRows
5937
+ });
5938
+ const effectiveShow = Boolean(decision.showUsage) && !decision.attaching;
5939
+ if (provider === "codex" && !effectiveShow) {
5940
+ // Keep shared Codex account usage fresh for the Windows shared bar even
5941
+ // while the WSL runner hides its own per-pane bottom row.
5942
+ try { readCodex({ includeRunning: false }); } catch {}
5943
+ }
5944
+ const leasePath = decision.root && decision.context?.window && decision.context?.tab
5945
+ ? sharedBarLeasePath(decision.root, decision.context)
5946
+ : null;
5947
+ console.log(JSON.stringify({
5948
+ showUsage: effectiveShow,
5949
+ sharedBar: Boolean(decision.sharedBar),
5950
+ attaching: Boolean(decision.attaching),
5951
+ barSlice: decision.barSlice || null,
5952
+ barLeasePath: leasePath,
5953
+ columns: decision.columns ?? null
5954
+ }));
5955
+ return;
5956
+ }
5957
+
5958
+ if (args.paneCleanupProvider) {
5959
+ const provider = providerId(args.paneCleanupProvider) || "codex";
5960
+ cleanupPaneAiSession(provider, { ownerPid: args.ownerPid });
5961
+ return;
5962
+ }
5963
+
5964
+ if (args.command === "bar") {
5965
+ if (process.platform !== "win32" || !process.stdout.isTTY) {
5966
+ throw cliError("Run the shared bar in a native Windows Terminal pane.", "통합 바는 Windows Terminal의 전용 pane에서 실행하세요.", "bar");
5967
+ }
5968
+ await runSharedBar({
5969
+ intervalSeconds: process.argv.includes("--interval") ? args.interval : 2,
5970
+ renderLine: (columns, opts = {}) => render(collect(args), {
5971
+ ...args,
5972
+ ...(opts.barWidth ? { barWidth: opts.barWidth } : {}),
5973
+ style: args.style === "plain" ? "muted" : args.style,
5974
+ maxWidth: Math.max(20, columns - 1)
5975
+ })
5976
+ });
5977
+ return;
5978
+ }
5979
+
5980
+ if (args.command === "split") {
5981
+ const action = args.subcommand || (args.barPosition ? "position" : "status");
5982
+ if (BAR_POSITIONS.includes(action) || action === "position") {
5983
+ const targetPos = action === "position" ? args.barPosition : normalizeBarPosition(action);
5984
+ const updated = updateDisplayConfig({ splitBarPosition: targetPos });
5985
+ const fragmentUpdate = (process.platform === "win32" || isWsl())
5986
+ ? updateWtFragmentPosition({ position: targetPos, sidebarWidth: updated.sidebarWidth })
5987
+ : { ok: false, updated: false };
5988
+ const result = {
5989
+ ok: true,
5990
+ action: "position",
5991
+ position: targetPos,
5992
+ barPosition: updated.barPosition,
5993
+ splitBarPosition: updated.splitBarPosition,
5994
+ fragmentUpdated: Boolean(fragmentUpdate.updated),
5995
+ displayConfigPath: displayConfigPath()
5996
+ };
5997
+ if (args.json) console.log(JSON.stringify(result, null, 2));
5998
+ else {
5999
+ console.log(`${cliText("Split bar position", "통합 바 위치")}: ${targetPos}`);
6000
+ if (fragmentUpdate.ok) {
6001
+ console.log(cliText("Windows Terminal fragment updated.", "Windows Terminal 설정을 반영했습니다."));
6002
+ }
6003
+ }
6004
+ return;
6005
+ }
6006
+ if (["on", "auto", "manual", "off"].includes(action)) {
6007
+ const targetMode = normalizeSplitBarMode(action);
6008
+ const updated = updateDisplayConfig({
6009
+ splitBar: targetMode,
6010
+ ...(args.barPosition ? { splitBarPosition: args.barPosition } : {})
6011
+ });
6012
+ if (args.barPosition && (process.platform === "win32" || isWsl())) {
6013
+ updateWtFragmentPosition({ position: args.barPosition, sidebarWidth: updated.sidebarWidth });
6014
+ }
6015
+ const resolved = resolveSplitBarMode(process.env, { configuredMode: updated.splitBar });
6016
+ const result = {
6017
+ ok: true,
6018
+ action,
6019
+ mode: resolved.mode,
6020
+ configuredMode: updated.splitBar,
6021
+ position: updated.splitBarPosition || updated.barPosition,
6022
+ envOverride: resolved.envOverride,
6023
+ displayConfigPath: displayConfigPath()
6024
+ };
6025
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatSplitBarModeResult(result));
6026
+ return;
6027
+ }
6028
+ if (action === "status") {
6029
+ const display = readDisplayConfig({ strict: true });
6030
+ const resolved = resolveSplitBarMode(process.env, { configuredMode: display.splitBar });
6031
+ const position = readConfiguredSplitBarPosition(process.env);
6032
+ const splitInfo = (process.platform === "win32" || isWsl()) ? diagnoseSharedBar() : null;
6033
+ const result = {
6034
+ ok: true,
6035
+ action: "status",
6036
+ mode: resolved.mode,
6037
+ configuredMode: resolved.configuredMode,
6038
+ position,
6039
+ envOverride: resolved.envOverride,
6040
+ displayConfigPath: displayConfigPath(),
6041
+ platform: process.platform,
6042
+ ...(splitInfo ? { split: splitInfo } : {})
6043
+ };
6044
+ console.log(args.json ? JSON.stringify(result, null, 2) : formatSplitBarStatus(result));
6045
+ return;
6046
+ }
6047
+ }
6048
+
5161
6049
  if (args.command === "on" || args.command === "off") {
5162
6050
  const visible = args.command === "on";
5163
6051
  const result = setProviderVisibility(args.targets, visible);
@@ -5198,42 +6086,59 @@ async function main() {
5198
6086
  );
5199
6087
  }
5200
6088
  if (!args.silent) {
5201
- const contentWidth = Math.max(20, statusLineUsableColumns(input) - (Number(args.leftPadding) || 0));
5202
- const header = args.header ? claudeHeader(activeProvider === "antigravity" ? { ...input, product: "antigravity" } : input, args, capturedClaude) : "";
5203
- const usageRowVisible = activeProvider === "antigravity"
6089
+ const usageRowRequested = activeProvider === "antigravity"
5204
6090
  ? (typeof args.usageRow === "boolean" ? args.usageRow : booleanEnvValue(process.env.AI_BATTERY_ANTIGRAVITY_USAGE_ROW) ?? !tmuxStatusBarActive())
5205
6091
  : claudeUsageRowVisible(args);
5206
- if (!usageRowVisible && header) {
5207
- console.log(applyLeftPadding(header, args));
6092
+ const externalBarActive = process.env.AI_BATTERY_EXTERNAL_BAR === "1";
6093
+ const participate = usageRowRequested && !args.attachHud && !externalBarActive;
6094
+ const sharingOptions = {
6095
+ ownerPid: participate && process.platform === "win32" && activeProvider === "claude"
6096
+ ? claudeNativeSessionOwnerPid(capturedClaude.sessionId, capturedClaude.workspace?.currentDir || "") : 0,
6097
+ participate
6098
+ };
6099
+ const sharing = capturedClaude.sessionKind === "bg" ? { showUsage: false, columns: null } : paneUsageDecision(activeProvider, sharingOptions);
6100
+ const contentWidth = Math.max(20, statusLineUsableColumns(input, sharing.columns) - (Number(args.leftPadding) || 0));
6101
+ const header = args.header ? claudeHeader(activeProvider === "antigravity" ? { ...input, product: "antigravity" } : input, args, capturedClaude, sharing.columns) : "";
6102
+ const usageRowVisible = usageRowRequested && sharing.showUsage && !externalBarActive;
6103
+ if (!usageRowVisible) {
6104
+ if (header) console.log(applyLeftPadding(header, args));
5208
6105
  return;
5209
6106
  }
6107
+ const hookProcessOptions = {
6108
+ nonBlocking: true,
6109
+ triggerBackgroundRefresh: scheduleBackgroundProcessRefresh
6110
+ };
5210
6111
  const results = [];
5211
6112
  if ((args.provider === "all" || args.provider === "codex") && providerVisible("codex")) {
5212
- const codexData = readCodexForClaudeCapture();
6113
+ const codexData = readCodexForClaudeCapture({ processOptions: hookProcessOptions });
5213
6114
  if (codexData) results.push(codexData);
5214
6115
  }
5215
6116
  if ((args.provider === "all" || args.provider === "claude") && providerVisible("claude")) {
5216
6117
  if (activeProvider === "claude") {
5217
- const capturedSource = capturedClaude.sessionKind === "bg" && capturedClaude.sessionId
5218
- ? claudeSessionCachePath(capturedClaude.sessionId)
5219
- : claudeCachePath();
5220
- const claudeData = claudeStatuslineResultFromCache(capturedClaude, capturedSource, { includeBackground: true }) ?? readClaude();
6118
+ const claudeData = readClaude({ runningOverride: true, capturedSnapshot: capturedClaude });
5221
6119
  results.push({ ...claudeData, running: true });
5222
- } else results.push(readClaude());
6120
+ } else results.push(readClaude({ processOptions: hookProcessOptions }));
5223
6121
  }
5224
6122
  if ((args.provider === "all" || args.provider === "antigravity") && providerVisible("antigravity") && (activeProvider === "antigravity" || antigravityAvailable())) {
5225
- results.push(antigravity.read({ runningOverride: activeProvider === "antigravity" ? true : null }));
6123
+ results.push(antigravity.read({
6124
+ runningOverride: activeProvider === "antigravity" ? true : null,
6125
+ processOptions: hookProcessOptions
6126
+ }));
5226
6127
  }
5227
6128
  const usage = render({
5228
6129
  generatedAt: new Date().toISOString(),
5229
6130
  results
5230
6131
  }, { ...args, activeProvider, leftPadding: 0, maxWidth: contentWidth });
6132
+ // A bar may become ready while quota/log collection runs. Recheck lease only
6133
+ // so an event-driven hook never leaves a stale duplicate usage row.
6134
+ if (isPaneSharedBarActive(sharing, { includePendingAttach: true })) {
6135
+ if (header) console.log(applyLeftPadding(header, args));
6136
+ return;
6137
+ }
5231
6138
  // Inside tmux with the status-bar integration, the battery already shows
5232
6139
  // in tmux's own bar; keep the statusline to the one line tmux can't show.
5233
- const text = !usageRowVisible
5234
- ? (header || usage)
5235
- : (header && usage ? `${header}\n${usage}` : (usage || header));
5236
- console.log(applyLeftPadding(text, args));
6140
+ const text = header && usage ? `${header}\n${usage}` : (usage || header);
6141
+ if (text) console.log(applyLeftPadding(text, args));
5237
6142
  }
5238
6143
  return;
5239
6144
  }
@@ -5310,11 +6215,14 @@ export {
5310
6215
  percentValue,
5311
6216
  providerRunningInProcesses,
5312
6217
  render,
6218
+ renderTmuxUsage,
5313
6219
  renderHudState,
5314
6220
  renderMenuBarImage,
5315
6221
  renderMenuDetailImage,
6222
+ renderRailImage,
5316
6223
  rowptyDiagnostic,
5317
6224
  sameFilePath,
6225
+ teardownResultFailed,
5318
6226
  visibleWidth,
5319
6227
  uninstallClaudeStatusline,
5320
6228
  uninstallCodexWrapper,