ai-battery 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +30 -14
  2. package/bin/ai-battery-macos-status.applescript +5 -12
  3. package/bin/ai-battery-run +701 -31
  4. package/bin/ai-battery-tmux.js +17 -0
  5. package/bin/terminal-compositor.js +111 -0
  6. package/docs/REFERENCE.md +23 -3
  7. package/docs/RELEASING.md +24 -7
  8. package/docs/WINDOWS-TERMINAL-SHARED-BAR.md +74 -0
  9. package/docs/hud-preview.svg +43 -20
  10. package/docs/terminal-vertical-preview.svg +73 -0
  11. package/lib/cli.js +945 -219
  12. package/lib/core/atomic-rename.js +18 -0
  13. package/lib/core/cli-help.js +35 -7
  14. package/lib/core/cli-messages.js +45 -1
  15. package/lib/core/cli-output.js +277 -72
  16. package/lib/core/cli-wrappers.js +410 -0
  17. package/lib/core/config-editor.js +177 -29
  18. package/lib/core/display-config.js +45 -0
  19. package/lib/core/integration-files.js +32 -3
  20. package/lib/core/shared-bar.js +603 -0
  21. package/lib/core/statusline-git.js +179 -15
  22. package/lib/core/terminal.js +25 -7
  23. package/lib/core/tmux-status.js +172 -0
  24. package/lib/core/uninstall.js +20 -7
  25. package/lib/core/usage-store.js +85 -0
  26. package/lib/hud/launcher.js +29 -31
  27. package/lib/platforms/linux/hud.js +1 -1
  28. package/lib/platforms/linux/panel.js +1 -1
  29. package/lib/platforms/macos/hud.js +5 -5
  30. package/lib/platforms/process-scanner.js +77 -29
  31. package/lib/platforms/windows/autostart-cleanup.js +1 -1
  32. package/lib/platforms/windows/codex-runner.js +178 -21
  33. package/lib/platforms/windows/hud/controls.ps1 +44 -10
  34. package/lib/platforms/windows/hud/main.ps1 +350 -43
  35. package/lib/platforms/windows/hud/rendering.ps1 +1227 -1
  36. package/lib/platforms/windows/hud/snapshot.ps1 +26 -46
  37. package/lib/platforms/windows/hud-launcher.js +153 -79
  38. package/lib/platforms/windows/shared-bar-platform.js +972 -0
  39. package/lib/platforms/windows/terminal-compositor.js +210 -25
  40. package/lib/platforms/windows/wt-bar.js +729 -0
  41. package/lib/platforms/windows/wt-fragment.js +665 -0
  42. package/lib/platforms/windows/wt-keybinding.js +300 -0
  43. package/lib/providers/antigravity.js +155 -8
  44. package/package.json +5 -2
  45. package/vendor/PaneContext.cs +875 -0
@@ -0,0 +1,729 @@
1
+ import { spawn } from "node:child_process";
2
+ import { claimSharedBar, clearAutoAttachTrigger, clearTabAiSessions, heartbeatSharedBar, listActiveAiSessions, markSharedBarDismissed, releaseSharedBar } from "../../core/shared-bar.js";
3
+ import { createCrossOsSessionAlive, nativeTabState, readConfiguredSidebarWidth, readConfiguredSplitBarPosition, resolveCurrentPaneContext, scheduleNativeFocusRestore, sharedBarRoot } from "./shared-bar-platform.js";
4
+ import { readWtProfileColorMap } from "./wt-fragment.js";
5
+ import { charWidth, stripAnsi, visibleWidth } from "../../core/terminal.js";
6
+
7
+ const ESC = "\x1b";
8
+ const CSI = `${ESC}[`;
9
+
10
+ export const BAR_ENTER_SEQUENCE = `${CSI}?1049h${CSI}?2026h${CSI}?25l${CSI}?7l${CSI}2J${CSI}H${CSI}?1004h${CSI}?2026l`;
11
+ export const BAR_EXIT_SEQUENCE = `${CSI}?2026h${CSI}?1004l${CSI}0m${CSI}?7h${CSI}?25h${CSI}?1049l${CSI}?2026l`;
12
+
13
+ function clipAnsiLine(text, maxCells) {
14
+ let clean = "";
15
+ let width = 0;
16
+ for (const token of String(text || "").replace(/[\r\n]+/g, " ").match(/\x1b\[[0-?]*[ -/]*[@-~]|./gu) || []) {
17
+ if (token.startsWith(ESC)) { if (token.endsWith("m")) clean += token; continue; }
18
+ const next = charWidth(token);
19
+ if (width + next > Math.max(1, maxCells)) break;
20
+ clean += token;
21
+ width += next;
22
+ }
23
+ return clean;
24
+ }
25
+
26
+ export function formatBarFrame(text, columns = 80) {
27
+ const clean = clipAnsiLine(text, Math.max(1, columns - 1));
28
+ // Paint on Row 1 and clear Row 2 downward so any >=2-row buffer stays blank
29
+ // below the single usage row.
30
+ return `${CSI}?2026h${CSI}0m${CSI}?25l${CSI}1;1H${clean}${CSI}0m${CSI}K${CSI}2;1H${CSI}J${CSI}?2026l`;
31
+ }
32
+
33
+ function verticalBarColor(percent, running) {
34
+ if (!running) return `${CSI}90m`;
35
+ if (typeof percent !== "number") return `${CSI}90m`;
36
+ if (percent <= 20) return `${CSI}31m`;
37
+ if (percent <= 40) return `${CSI}33m`;
38
+ return `${CSI}32m`;
39
+ }
40
+
41
+ function placeAnsiAt(ansiText, width, startCol) {
42
+ const clipped = clipAnsiLine(ansiText, width);
43
+ const w = visibleWidth(clipped);
44
+ if (w >= width) return clipped;
45
+ const clampedStart = Math.max(0, Math.min(width - w, Math.trunc(startCol)));
46
+ return `${" ".repeat(clampedStart)}${clipped}`;
47
+ }
48
+
49
+ function centerAnsiCell(ansiText, width, alignBias = "left", axis = null) {
50
+ const clipped = clipAnsiLine(ansiText, width);
51
+ const w = visibleWidth(clipped);
52
+ if (w >= width) return clipped;
53
+ if (typeof axis === "number" && Number.isFinite(axis)) {
54
+ const start = axis - Math.floor(w / 2);
55
+ return placeAnsiAt(clipped, width, start);
56
+ }
57
+ const gap = width - w;
58
+ const left = alignBias === "right" ? Math.ceil(gap / 2) : Math.floor(gap / 2);
59
+ return `${" ".repeat(left)}${clipped}`;
60
+ }
61
+
62
+ function placePercentCell(ansiText, plainText, width, axis) {
63
+ const clipped = clipAnsiLine(ansiText, width);
64
+ const w = visibleWidth(clipped);
65
+ if (w >= width) return clipped;
66
+ // Anchor the units digit on `axis` (directly under the vertical battery bar)
67
+ // and `%` at `axis + 1`, so 100% (4ch) -> axis-2, 99% (3ch) -> axis-1,
68
+ // 9% (2ch) -> axis — every length change shifts smoothly around the center axis.
69
+ if (plainText.endsWith("%") && w >= 2 && w <= 4) {
70
+ return placeAnsiAt(clipped, width, axis + 2 - w);
71
+ }
72
+ return centerAnsiCell(clipped, width, "left", axis);
73
+ }
74
+
75
+ function shortVerticalProviderTag(name, width) {
76
+ const lower = String(name || "").toLowerCase();
77
+ const code = lower.startsWith("codex") ? "CDX"
78
+ : lower.startsWith("claude") ? "CLD"
79
+ : (lower.startsWith("gemini") || lower.startsWith("antigravity")) ? "AGY"
80
+ : String(name || "AI").slice(0, 3).toUpperCase();
81
+ return code.slice(0, Math.max(1, width));
82
+ }
83
+
84
+ function verticalProviderTagColor(name, running) {
85
+ const lower = String(name || "").toLowerCase();
86
+ const weight = running ? "1;" : "";
87
+ if (lower.startsWith("gemini") || lower.startsWith("antigravity")) {
88
+ return `${CSI}${weight}38;2;96;165;250m`;
89
+ }
90
+ if (lower.startsWith("claude")) {
91
+ return `${CSI}${weight}38;2;249;115;22m`;
92
+ }
93
+ if (lower.startsWith("codex")) {
94
+ return running ? `${CSI}1;97m` : `${CSI}37m`;
95
+ }
96
+ return running ? `${CSI}1;97m` : `${CSI}90m`;
97
+ }
98
+
99
+ const VERTICAL_PARTIAL_BLOCKS = ["", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
100
+
101
+ function renderVerticalBatteryRows(percent, barRows, width, running, alignBias = "left", axis = null) {
102
+ const rows = [];
103
+ if (barRows <= 0) return rows;
104
+ const clamped = typeof percent === "number" ? Math.max(0, Math.min(100, percent)) : null;
105
+ const totalEighths = clamped === null ? 0 : Math.round((clamped / 100) * barRows * 8);
106
+ const effectiveEighths = (clamped !== null && clamped > 0 && totalEighths === 0) ? 1 : totalEighths;
107
+ const fillColor = verticalBarColor(clamped, running);
108
+ // Fill bottom-to-top: empty segments show a slim centered rail │, partial uses ▁..▇, full uses █.
109
+ for (let r = barRows - 1; r >= 0; r -= 1) {
110
+ const rowEighths = Math.max(0, Math.min(8, effectiveEighths - (r * 8)));
111
+ const glyph = rowEighths <= 0
112
+ ? `${CSI}90m│${CSI}0m`
113
+ : `${fillColor}${VERTICAL_PARTIAL_BLOCKS[rowEighths]}${CSI}0m`;
114
+ rows.push(centerAnsiCell(glyph, width, alignBias, axis));
115
+ }
116
+ return rows;
117
+ }
118
+
119
+ // Convert a multi-provider ANSI line (separated by ┃) into a 5-column vertical
120
+ // battery rail (AGY/CDX/CLD, 3-row battery, %, 5hr / 00:00, 7dy / XX%).
121
+ export function formatVerticalStatusLines(text, columns = 5, rows = 30, options = {}) {
122
+ const fullWidth = Boolean(options?.fullWidth);
123
+ const alignBias = options?.alignBias === "right" ? "right" : "left";
124
+ const maxWidth = fullWidth ? Math.max(3, columns) : Math.max(3, columns - 1);
125
+ // Shared vertical center axis so AGY, battery bar, percentages, 5hr, 15:02 (:),
126
+ // 7dy, and 7d% all align to the exact same center column (no per-item drift).
127
+ const axis = maxWidth % 2 === 1
128
+ ? Math.floor(maxWidth / 2)
129
+ : (alignBias === "right" ? Math.ceil((maxWidth - 1) / 2) : Math.floor((maxWidth - 1) / 2));
130
+ const segments = String(text || "").split(/\s*(?:\x1b\[[0-?]*[ -/]*[@-~])*┃(?:\x1b\[[0-?]*[ -/]*[@-~])*\s*/u).filter(Boolean);
131
+ if (!segments.length) return [];
132
+
133
+ const providerCount = segments.length;
134
+ const dividersCount = Math.max(0, providerCount - 1);
135
+ const rowsPerProvider = Math.floor(Math.max(1, rows - dividersCount) / providerCount);
136
+ const showWeekLabel = rowsPerProvider >= 9;
137
+ const showWeek = rowsPerProvider >= 7;
138
+ const showResetLabel = rowsPerProvider >= 6;
139
+ const showReset = rowsPerProvider >= 4;
140
+ const fixedRows = 2
141
+ + (showReset ? 1 : 0) + (showResetLabel ? 1 : 0)
142
+ + (showWeek ? 1 : 0) + (showWeekLabel ? 1 : 0);
143
+ const barRows = Math.max(0, Math.min(3, rowsPerProvider - fixedRows));
144
+
145
+ const out = [];
146
+ const divider = `${CSI}90m${"─".repeat(Math.min(maxWidth, 5))}${CSI}0m`;
147
+
148
+ for (let i = 0; i < segments.length; i += 1) {
149
+ if (i > 0) out.push(centerAnsiCell(divider, maxWidth, alignBias, axis));
150
+ const rawSegment = segments[i];
151
+ const parts = rawSegment.split(/\s*(?:\x1b\[[0-?]*[ -/]*[@-~])*│(?:\x1b\[[0-?]*[ -/]*[@-~])*\s*/u).map(s => s.trim()).filter(Boolean);
152
+ if (!parts.length) continue;
153
+
154
+ const headPlain = stripAnsi(parts[0]).trim();
155
+ const running = !/^\s*\x1b\[(?:2|90|38;5;24[0-9])m/.test(parts[0]) && /\x1b\[(?:1|32|33|31|36|37|97|38;2)/.test(rawSegment);
156
+ const headMatch = headPlain.match(/^(Codex|Claude|Gemini|Antigravity)\b(.*)$/i);
157
+ if (!headMatch) {
158
+ out.push(centerAnsiCell(clipAnsiLine(headPlain, maxWidth), maxWidth, alignBias, axis));
159
+ continue;
160
+ }
161
+
162
+ const tag = shortVerticalProviderTag(headMatch[1], maxWidth);
163
+ const pctMatch = headMatch[2].match(/(\d{1,3})%/);
164
+ const percent = pctMatch ? Number(pctMatch[1]) : null;
165
+ const pctText = percent !== null ? `${percent}%` : "--%";
166
+
167
+ const tagAnsi = `${verticalProviderTagColor(headMatch[1], running)}${tag}${CSI}0m`;
168
+ const pctAnsi = running
169
+ ? `${CSI}1m${verticalBarColor(percent, true)}${pctText}${CSI}0m`
170
+ : `${CSI}90m${pctText}${CSI}0m`;
171
+
172
+ out.push(centerAnsiCell(tagAnsi, maxWidth, alignBias, axis));
173
+ for (const barRow of renderVerticalBatteryRows(percent, barRows, maxWidth, running, alignBias, axis)) {
174
+ out.push(barRow);
175
+ }
176
+ out.push(placePercentCell(pctAnsi, pctText, maxWidth, axis));
177
+
178
+ const metaColor = running ? `${CSI}37m` : `${CSI}90m`;
179
+ let resetText = null;
180
+ let weekText = null;
181
+ for (let p = 1; p < parts.length; p += 1) {
182
+ const plain = stripAnsi(parts[p]).trim();
183
+ const fiveMatch = plain.match(/^5h\s+(.+)$/i);
184
+ if (fiveMatch) { resetText = fiveMatch[1]; continue; }
185
+ const weekMatch = plain.match(/^7d\s+(\d{1,3})%$/i);
186
+ if (weekMatch) { weekText = `${weekMatch[1]}%`; }
187
+ }
188
+ if (showReset && resetText) {
189
+ if (showResetLabel) out.push(centerAnsiCell(`${CSI}90m5h${CSI}0m`, maxWidth, alignBias, axis));
190
+ out.push(centerAnsiCell(`${metaColor}${resetText}${CSI}0m`, maxWidth, alignBias, axis));
191
+ }
192
+ if (showWeek && weekText) {
193
+ if (showWeekLabel) out.push(centerAnsiCell(`${CSI}90m7d${CSI}0m`, maxWidth, alignBias, axis));
194
+ out.push(placePercentCell(`${metaColor}${weekText}${CSI}0m`, weekText, maxWidth, axis));
195
+ }
196
+ }
197
+ return out.slice(0, Math.max(1, rows));
198
+ }
199
+
200
+ export function formatVerticalBarFrame(textOrLines, columns = 24, rows = 20) {
201
+ const lines = Array.isArray(textOrLines)
202
+ ? textOrLines.slice(0, Math.max(1, rows)).map(line => clipAnsiLine(line, Math.max(1, columns)))
203
+ : formatVerticalStatusLines(textOrLines, columns, rows, { fullWidth: true });
204
+ let frame = `${CSI}?2026h${CSI}0m${CSI}?25l`;
205
+ for (let r = 0; r < lines.length; r += 1) {
206
+ frame += `${CSI}${r + 1};1H${lines[r]}${CSI}0m${CSI}K`;
207
+ }
208
+ if (lines.length < rows) {
209
+ frame += `${CSI}${lines.length + 1};1H${CSI}J`;
210
+ }
211
+ return `${frame}${CSI}?2026l`;
212
+ }
213
+
214
+ export function resolveTabThemeColors(sessions = [], colorMap = null) {
215
+ if (!colorMap) return null;
216
+ for (const session of sessions || []) {
217
+ const guid = String(session?.profileId || "").trim().toLowerCase();
218
+ if (guid && colorMap.byGuid?.has(guid)) return colorMap.byGuid.get(guid);
219
+ }
220
+ for (const session of sessions || []) {
221
+ if (String(session?.profileId || "").trim()) continue;
222
+ const distro = String(session?.wslDistro || "").trim().toLowerCase();
223
+ if (distro && colorMap.byDistro?.has(distro)) return colorMap.byDistro.get(distro);
224
+ if (distro.startsWith("ubuntu") && colorMap.byDistro?.has("ubuntu")) return colorMap.byDistro.get("ubuntu");
225
+ }
226
+ return colorMap.defaultColors || null;
227
+ }
228
+
229
+ export function oscThemeSequence(colors) {
230
+ if (!colors) return "";
231
+ let seq = "";
232
+ if (colors.background) seq += `${ESC}]11;${colors.background}\x07`;
233
+ if (colors.foreground) seq += `${ESC}]10;${colors.foreground}\x07`;
234
+ return seq;
235
+ }
236
+
237
+ // Detect when all upper work panes in the tab were closed and Windows Terminal
238
+ // expanded the remaining bottom/top/side bar pane to occupy the whole tab.
239
+ export function shouldAutoExitOnResize({
240
+ initialRows = 2,
241
+ currentRows = 2,
242
+ windowClientHeight = 0,
243
+ vertical = false,
244
+ initialColumns = 24,
245
+ currentColumns = 24
246
+ }) {
247
+ if (vertical) {
248
+ const cols = Number(currentColumns) || 0;
249
+ const startCols = Math.max(8, Number(initialColumns) || 24);
250
+ return cols >= Math.max(60, Math.round(startCols * 2.5));
251
+ }
252
+ const rows = Number(currentRows) || 0;
253
+ const start = Math.max(1, Number(initialRows) || 2);
254
+ if (rows < 8) return false;
255
+ if (Number(windowClientHeight) > 0) {
256
+ // At 10pt font (~14-16 DIPs/row), occupying >= 50% of window height means no
257
+ // sibling work panes remain above the bar.
258
+ return rows * 13 >= Number(windowClientHeight) * 0.5;
259
+ }
260
+ return rows >= Math.max(10, start * 3);
261
+ }
262
+
263
+ // Decide whether the shared bar should auto-close based on live tab pane count.
264
+ // Only evaluates when our tab is currently selected (so switching to another tab
265
+ // with fewer panes never closes this tab's bar).
266
+ export function evaluateSplitLifecycle({
267
+ myTab = "",
268
+ selectedTab = "",
269
+ paneCount = 0,
270
+ hadMultipleWorkPanes = false,
271
+ activeAiSessions = null,
272
+ hadMultipleAiSessions = false,
273
+ singlePaneBar = false,
274
+ hadAnyAiSession = false
275
+ }) {
276
+ const aiCount = activeAiSessions === null || activeAiSessions === undefined ? null : Number(activeAiSessions);
277
+ const nextHadMultiAi = hadMultipleAiSessions || (aiCount !== null && aiCount >= 2);
278
+ const nextHadAnyAi = hadAnyAiSession || (aiCount !== null && aiCount >= 1);
279
+ const onSameTab = Boolean(myTab && selectedTab && myTab === selectedTab);
280
+ const nextHadSplit = hadMultipleWorkPanes || (onSameTab && paneCount >= 3);
281
+
282
+ // When running as a non-bottom single-pane positioned bar (e.g. Claude/Gemini
283
+ // at top/left/right), keep the bar alive while >= 1 AI session is active and
284
+ // exit cleanly once all AI sessions close.
285
+ if (singlePaneBar) {
286
+ if (nextHadAnyAi && aiCount !== null && aiCount <= 0) {
287
+ return {
288
+ hadMultipleWorkPanes: nextHadSplit,
289
+ hadMultipleAiSessions: nextHadMultiAi,
290
+ hadAnyAiSession: nextHadAnyAi,
291
+ shouldExit: true,
292
+ reason: "ai-sessions-ended"
293
+ };
294
+ }
295
+ if (onSameTab && paneCount > 0 && paneCount <= 1) {
296
+ return {
297
+ hadMultipleWorkPanes: nextHadSplit,
298
+ hadMultipleAiSessions: nextHadMultiAi,
299
+ hadAnyAiSession: nextHadAnyAi,
300
+ shouldExit: true,
301
+ reason: "last-pane-closed"
302
+ };
303
+ }
304
+ return {
305
+ hadMultipleWorkPanes: nextHadSplit,
306
+ hadMultipleAiSessions: nextHadMultiAi,
307
+ hadAnyAiSession: nextHadAnyAi,
308
+ shouldExit: false,
309
+ reason: null
310
+ };
311
+ }
312
+
313
+ if (!onSameTab || !paneCount) {
314
+ return {
315
+ hadMultipleWorkPanes: nextHadSplit,
316
+ hadMultipleAiSessions: nextHadMultiAi,
317
+ hadAnyAiSession: nextHadAnyAi,
318
+ shouldExit: false,
319
+ reason: null
320
+ };
321
+ }
322
+
323
+ if (paneCount <= 1) {
324
+ return {
325
+ hadMultipleWorkPanes: nextHadSplit,
326
+ hadMultipleAiSessions: nextHadMultiAi,
327
+ hadAnyAiSession: nextHadAnyAi,
328
+ shouldExit: true,
329
+ reason: "last-pane-closed"
330
+ };
331
+ }
332
+ if (nextHadSplit && paneCount === 2) {
333
+ return {
334
+ hadMultipleWorkPanes: nextHadSplit,
335
+ hadMultipleAiSessions: nextHadMultiAi,
336
+ hadAnyAiSession: nextHadAnyAi,
337
+ shouldExit: true,
338
+ reason: "split-ended"
339
+ };
340
+ }
341
+ // Keep the unified bar open as long as the tab stays split (paneCount >= 3)
342
+ // AND at least one AI session (agy/codex/claude) is still running. Once ALL
343
+ // AI sessions in the tab exit (aiCount <= 0), close the bar cleanly even if
344
+ // plain shell panes remain split.
345
+ if (nextHadAnyAi && aiCount !== null && aiCount <= 0) {
346
+ return {
347
+ hadMultipleWorkPanes: nextHadSplit,
348
+ hadMultipleAiSessions: nextHadMultiAi,
349
+ hadAnyAiSession: nextHadAnyAi,
350
+ shouldExit: true,
351
+ reason: "ai-sessions-ended"
352
+ };
353
+ }
354
+ return {
355
+ hadMultipleWorkPanes: nextHadSplit,
356
+ hadMultipleAiSessions: nextHadMultiAi,
357
+ hadAnyAiSession: nextHadAnyAi,
358
+ shouldExit: false,
359
+ reason: null
360
+ };
361
+ }
362
+
363
+ export function handleBarInputChunk(chunk, { onFocusIn, onFocusOut, onQuit } = {}) {
364
+ const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk || "");
365
+ if (text.includes("\x03") || /(?:^|[^\x1b])q/i.test(text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""))) {
366
+ onQuit?.();
367
+ return "quit";
368
+ }
369
+ const lastIn = text.lastIndexOf(`${CSI}I`);
370
+ const lastOut = text.lastIndexOf(`${CSI}O`);
371
+ if (lastIn >= 0 && lastIn > lastOut) {
372
+ onFocusIn?.();
373
+ return "focus-in";
374
+ }
375
+ if (lastOut >= 0 && lastOut > lastIn) {
376
+ onFocusOut?.();
377
+ return "focus-out";
378
+ }
379
+ return "ignored";
380
+ }
381
+
382
+ function defaultBounceFocus() {
383
+ try {
384
+ const child = spawn("wt.exe", ["-w", "0", "move-focus", "previous"], {
385
+ stdio: "ignore",
386
+ detached: true,
387
+ windowsHide: true
388
+ });
389
+ child.on?.("error", () => {});
390
+ child.unref();
391
+ } catch { /* Best-effort focus bounce. */ }
392
+ }
393
+
394
+ const WAIT_ARRAY = new Int32Array(new SharedArrayBuffer(4));
395
+
396
+ export function runSharedBar({
397
+ intervalSeconds = 2,
398
+ renderLine,
399
+ stdout = process.stdout,
400
+ stdin = process.stdin,
401
+ env = process.env,
402
+ resolveContext = undefined,
403
+ resolveTabState = undefined,
404
+ bounceFocus = defaultBounceFocus,
405
+ autoExitEnabled = true,
406
+ focusBounceEnabled = true,
407
+ focusBounceGraceMs = 600,
408
+ startupTabRetryDelayMs = 80
409
+ }) {
410
+ const root = sharedBarRoot(env);
411
+ const customResolver = resolveContext !== undefined;
412
+ const getContext = resolveContext || (() => resolveCurrentPaneContext("direct", { ownerPid: process.pid, env, forceTab: true, includePaneCount: true }));
413
+ const barPosition = readConfiguredSplitBarPosition(env);
414
+ const initialSidebarWidth = readConfiguredSidebarWidth(env);
415
+ const isVerticalPosition = barPosition === "left" || barPosition === "right";
416
+ const colorMap = !customResolver ? readWtProfileColorMap(env) : null;
417
+ let lastThemeKey = "";
418
+ let enteredAltScreen = false;
419
+ let earlyFrame = null;
420
+
421
+ // Paint the live usage frame BEFORE spawning PaneContext.exe (~200-300ms UIA
422
+ // probe) so the newly opened root-split bar pane renders immediately instead
423
+ // of flashing an empty black box during startup.
424
+ if (process.platform === "win32" && !customResolver) {
425
+ try {
426
+ const cols = Math.max(5, Number(stdout.columns) || 80);
427
+ const rows = Math.max(1, Number(stdout.rows) || 2);
428
+ const vertical = (isVerticalPosition && rows >= 4) || (cols <= 48 && rows >= 8);
429
+ const barWidth = vertical ? Math.max(4, Math.min(10, cols - 7)) : undefined;
430
+ const defaultColors = colorMap?.defaultColors || null;
431
+ stdout.write(BAR_ENTER_SEQUENCE);
432
+ enteredAltScreen = true;
433
+ if (defaultColors) {
434
+ const seq = oscThemeSequence(defaultColors);
435
+ if (seq) {
436
+ lastThemeKey = `${defaultColors.background || ""}|${defaultColors.foreground || ""}`;
437
+ stdout.write(seq);
438
+ }
439
+ }
440
+ const text = renderLine(vertical ? 240 : cols, { barWidth });
441
+ earlyFrame = vertical ? formatVerticalBarFrame(text, cols, rows) : formatBarFrame(text, cols);
442
+ stdout.write(earlyFrame);
443
+ } catch {}
444
+ }
445
+
446
+ let context = null;
447
+ let leaseFile = null;
448
+ let ownerStartedAt = "";
449
+
450
+ if (process.platform === "win32" || customResolver) {
451
+ for (let attempt = 0; attempt < 3; attempt += 1) {
452
+ try {
453
+ context = getContext();
454
+ } catch {
455
+ context = null;
456
+ }
457
+ if (!context?.window || context.tab || attempt === 2) break;
458
+ if (startupTabRetryDelayMs > 0) Atomics.wait(WAIT_ARRAY, 0, 0, startupTabRetryDelayMs);
459
+ }
460
+ if (context?.window) {
461
+ ownerStartedAt = String(context.startedAt || "");
462
+ const claim = claimSharedBar({
463
+ root,
464
+ context,
465
+ pid: process.pid,
466
+ startedAt: ownerStartedAt
467
+ });
468
+ if (!claim.claimed) {
469
+ if (enteredAltScreen) {
470
+ try {
471
+ if (lastThemeKey) stdout.write(`${ESC}]111\x07${ESC}]110\x07`);
472
+ stdout.write(BAR_EXIT_SEQUENCE);
473
+ } catch {}
474
+ }
475
+ // Another live AI Battery Bar is already active in this tab.
476
+ return Promise.resolve({ exited: true, reason: claim.reason, existingPid: claim.existing?.pid });
477
+ }
478
+ if (claim.claimed) leaseFile = claim.leaseFile;
479
+ }
480
+ }
481
+
482
+ return new Promise((resolve) => {
483
+ let closed = false;
484
+ let lastFrame = earlyFrame;
485
+ const startedAtMs = Date.now();
486
+ let lastBounceAt = 0;
487
+ let heartbeatFailures = 0;
488
+ let autoExitTimer = null;
489
+ let startupFocusTimer = null;
490
+ let pollTimer = null;
491
+ let lifecycleTimer = null;
492
+ let barHasFocus = false;
493
+ let hadMultipleWorkPanes = Number(context?.paneCount || 0) >= 3;
494
+ const activeSessionsNow = () => context?.window
495
+ ? listActiveAiSessions({ root, context, isAlive: createCrossOsSessionAlive({ root, context, env }) })
496
+ : [];
497
+ const initialSessions = activeSessionsNow();
498
+ let hadMultipleAiSessions = initialSessions.length >= 2;
499
+ let hadAnyAiSession = initialSessions.length >= 1;
500
+ const myTab = String(context?.tab || "");
501
+ const singlePaneBar = false;
502
+ const initialRows = Math.max(1, Number(stdout.rows) || 2);
503
+ const initialColumns = Math.max(5, Number(stdout.columns) || 80);
504
+ const intervalMs = Math.max(500, Math.round((Number(intervalSeconds) || 2) * 1000));
505
+
506
+ const syncThemeColors = (sessions) => {
507
+ if (!colorMap || closed) return;
508
+ const colors = resolveTabThemeColors(sessions, colorMap);
509
+ const nextKey = colors ? `${colors.background || ""}|${colors.foreground || ""}` : "";
510
+ if (!nextKey || nextKey === lastThemeKey) return;
511
+ lastThemeKey = nextKey;
512
+ const seq = oscThemeSequence(colors);
513
+ if (seq) {
514
+ try { stdout.write(seq); } catch {}
515
+ }
516
+ };
517
+
518
+ const draw = (force = false) => {
519
+ if (closed) return;
520
+ const cols = Math.max(5, Number(stdout.columns) || 80);
521
+ const rows = Math.max(1, Number(stdout.rows) || 2);
522
+ const vertical = (isVerticalPosition && rows >= 4) || (cols <= 48 && rows >= 8);
523
+ let text;
524
+ try {
525
+ const barWidth = vertical ? Math.max(4, Math.min(10, cols - 7)) : undefined;
526
+ text = renderLine(vertical ? 240 : cols, { barWidth });
527
+ } catch {
528
+ return;
529
+ }
530
+ const frame = vertical
531
+ ? formatVerticalBarFrame(text, cols, rows)
532
+ : formatBarFrame(text, cols);
533
+ if (!force && frame === lastFrame) return;
534
+ lastFrame = frame;
535
+ try { stdout.write(frame); } catch { /* Stream closing. */ }
536
+ };
537
+
538
+ const stop = (reason = "exit") => {
539
+ if (closed) return;
540
+ closed = true;
541
+ clearInterval(pollTimer);
542
+ clearInterval(lifecycleTimer);
543
+ if (autoExitTimer) clearTimeout(autoExitTimer);
544
+ if (startupFocusTimer) clearTimeout(startupFocusTimer);
545
+ stdout.off?.("resize", onResize);
546
+ stdin.off?.("data", onData);
547
+ try { if (stdin.isTTY && oldRaw !== undefined) stdin.setRawMode?.(oldRaw); } catch {}
548
+ try { stdin.pause?.(); } catch {}
549
+ for (const [signal, handler] of signalHandlers) process.off(signal, handler);
550
+ try {
551
+ if (lastThemeKey) stdout.write(`${ESC}]111\x07${ESC}]110\x07`);
552
+ stdout.write(BAR_EXIT_SEQUENCE);
553
+ } catch {}
554
+ if (context?.window) {
555
+ if (reason === "user-quit") {
556
+ markSharedBarDismissed({ root, context, sessions: activeSessionsNow() });
557
+ } else if (["SIGINT", "SIGBREAK", "SIGHUP"].includes(reason)) {
558
+ const activeSessions = activeSessionsNow();
559
+ if (activeSessions.length >= 2) {
560
+ markSharedBarDismissed({ root, context, sessions: activeSessions });
561
+ }
562
+ }
563
+ }
564
+ if (["split-ended", "last-pane-closed"].includes(reason) && context?.window) clearTabAiSessions({ root, context });
565
+ const releaseHandles = () => {
566
+ if (["config-changed", "ai-sessions-ended", "split-ended"].includes(reason) && context?.window) {
567
+ clearAutoAttachTrigger({ root, context });
568
+ }
569
+ if (leaseFile) {
570
+ releaseSharedBar({ leaseFile, pid: process.pid, startedAt: ownerStartedAt });
571
+ leaseFile = null;
572
+ }
573
+ };
574
+ const focusRestoreArmed = !customResolver && context?.window && reason !== "last-pane-closed"
575
+ ? scheduleNativeFocusRestore(context.window, myTab, process.pid, env)
576
+ : false;
577
+ if (focusRestoreArmed) {
578
+ setTimeout(() => {
579
+ releaseHandles();
580
+ resolve({ exited: true, reason });
581
+ }, 120);
582
+ } else {
583
+ releaseHandles();
584
+ resolve({ exited: true, reason });
585
+ }
586
+ };
587
+
588
+ const onResize = () => {
589
+ if (closed) return;
590
+ const currentRows = Number(stdout.rows) || 2;
591
+ const currentColumns = Number(stdout.columns) || 80;
592
+ if (autoExitEnabled && !myTab && shouldAutoExitOnResize({
593
+ initialRows,
594
+ currentRows,
595
+ windowClientHeight: context?.clientHeight || 0,
596
+ vertical: isVerticalPosition,
597
+ initialColumns,
598
+ currentColumns
599
+ })) {
600
+ if (!autoExitTimer) {
601
+ autoExitTimer = setTimeout(() => {
602
+ autoExitTimer = null;
603
+ const settledRows = Number(stdout.rows) || 2;
604
+ const settledCols = Number(stdout.columns) || 80;
605
+ if (shouldAutoExitOnResize({
606
+ initialRows,
607
+ currentRows: settledRows,
608
+ windowClientHeight: context?.clientHeight || 0,
609
+ vertical: isVerticalPosition,
610
+ initialColumns,
611
+ currentColumns: settledCols
612
+ })) {
613
+ stop("last-pane-closed");
614
+ }
615
+ }, 250);
616
+ }
617
+ return;
618
+ }
619
+ if (autoExitTimer) {
620
+ clearTimeout(autoExitTimer);
621
+ autoExitTimer = null;
622
+ }
623
+ draw(true);
624
+ };
625
+
626
+ const onData = (chunk) => {
627
+ if (closed) return;
628
+ handleBarInputChunk(chunk, {
629
+ onQuit: () => stop("user-quit"),
630
+ onFocusOut: () => {
631
+ barHasFocus = false;
632
+ },
633
+ onFocusIn: () => {
634
+ barHasFocus = true;
635
+ if (!focusBounceEnabled) return;
636
+ const now = Date.now();
637
+ if (now - startedAtMs < focusBounceGraceMs) return;
638
+ if (now - lastBounceAt < 250) return;
639
+ lastBounceAt = now;
640
+ bounceFocus();
641
+ }
642
+ });
643
+ };
644
+ if (focusBounceEnabled) {
645
+ startupFocusTimer = setTimeout(() => {
646
+ startupFocusTimer = null;
647
+ if (closed || !barHasFocus) return;
648
+ const now = Date.now();
649
+ if (now - lastBounceAt < 250) return;
650
+ lastBounceAt = now;
651
+ bounceFocus();
652
+ }, focusBounceGraceMs + 150);
653
+ }
654
+
655
+ const signalHandlers = new Map();
656
+ for (const signal of ["SIGINT", "SIGTERM", "SIGBREAK", "SIGHUP"]) {
657
+ const handler = () => stop(signal);
658
+ try {
659
+ process.once(signal, handler);
660
+ signalHandlers.set(signal, handler);
661
+ } catch {}
662
+ }
663
+
664
+ const oldRaw = stdin.isTTY ? stdin.isRaw : undefined;
665
+ try {
666
+ if (stdin.isTTY) {
667
+ stdin.setRawMode?.(true);
668
+ stdin.resume?.();
669
+ stdin.on("data", onData);
670
+ }
671
+ } catch {}
672
+ stdout.on?.("resize", onResize);
673
+
674
+ if (!enteredAltScreen) {
675
+ try { stdout.write(BAR_ENTER_SEQUENCE); } catch {}
676
+ }
677
+ syncThemeColors(initialSessions);
678
+ draw(!enteredAltScreen);
679
+
680
+ lifecycleTimer = setInterval(() => {
681
+ if (closed || !autoExitEnabled || !context?.window) return;
682
+ try {
683
+ if (!customResolver) {
684
+ const nextPos = readConfiguredSplitBarPosition(env);
685
+ const nextSideW = readConfiguredSidebarWidth(env);
686
+ if (nextPos !== barPosition || (isVerticalPosition && nextSideW !== initialSidebarWidth)) {
687
+ stop("config-changed");
688
+ return;
689
+ }
690
+ }
691
+ // Use UIA-only --tab-state on cached window HWND (zero AttachConsole churn).
692
+ const live = resolveTabState
693
+ ? resolveTabState(context.window)
694
+ : (customResolver ? getContext() : nativeTabState(context.window, env));
695
+ const liveSessions = activeSessionsNow();
696
+ syncThemeColors(liveSessions);
697
+ const check = evaluateSplitLifecycle({ myTab, selectedTab: String(live?.tab || ""),
698
+ paneCount: Number(live?.paneCount || 0), hadMultipleWorkPanes, hadMultipleAiSessions,
699
+ activeAiSessions: liveSessions.length, singlePaneBar, hadAnyAiSession });
700
+ hadMultipleWorkPanes = check.hadMultipleWorkPanes;
701
+ hadMultipleAiSessions = check.hadMultipleAiSessions;
702
+ hadAnyAiSession = check.hadAnyAiSession ?? hadAnyAiSession;
703
+ if (check.shouldExit) stop(check.reason);
704
+ } catch { /* A transient probe failure must not close a working bar. */ }
705
+ }, 1000);
706
+
707
+ pollTimer = setInterval(() => {
708
+ if (closed) return;
709
+ if (leaseFile) {
710
+ let aliveLease = false;
711
+ try {
712
+ aliveLease = heartbeatSharedBar({ leaseFile, pid: process.pid, startedAt: ownerStartedAt });
713
+ } catch {
714
+ aliveLease = false;
715
+ }
716
+ if (aliveLease) {
717
+ heartbeatFailures = 0;
718
+ } else {
719
+ heartbeatFailures += 1;
720
+ if (heartbeatFailures >= 3) {
721
+ stop("lease-lost");
722
+ return;
723
+ }
724
+ }
725
+ }
726
+ draw(false);
727
+ }, intervalMs);
728
+ });
729
+ }