ai-battery 0.1.25 → 0.1.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # AI Battery
2
2
 
3
+ 0.1.27: 한글 오류 메시지가 포함된 하단 사용량 줄이 갱신될 때 Codex 화면에 여러 줄로 누적되던 문제를 수정했습니다. 화면 칸 수를 기준으로 너비를 제한하고 불필요한 공백 채우기를 제거했습니다. 하단 바의 데이터 없음 표시는 `Claude --%`처럼 간결하게 표시합니다.
4
+
5
+ 0.1.26: `setup`이 기존 Codex 연동을 해제하던 문제를 수정했습니다. 기존 wrapper·PATH·Codex 상태줄과 tmux 연동을 유지·갱신하며, 실행 중인 셸이 기억하는 경로를 제거하지 않습니다. tmux 미실행 상태를 구분하고 HUD 메뉴의 밝은 테두리를 제거했습니다. 기본 예시는 `ai-battery setup tmux`입니다.
6
+
3
7
  0.1.25: Ubuntu/Linux 패널 HUD를 추가했습니다. macOS와 같은 로고·배터리 바·퍼센트를 표시합니다. 도움말·진단·설정 결과·오류 안내는 간결한 한국어/영어로 표시합니다. 명령 없이 실행하면 도움말을 표시하며 `show` 명령은 제거했습니다. 설정 복원은 `ai-battery reset`으로 실행하고, 이전 `reset settings`·`reset config`도 계속 지원합니다.
4
8
 
5
9
  [한국어](README.md) · [English](docs/i18n/en/) · [日本語](docs/i18n/ja/) · [中文](docs/i18n/zh/) · [Español](docs/i18n/es/)
@@ -55,7 +59,7 @@ Codex 86% │ 5h 18:09 │ 7d 82% ┃ Claude 4% │ 5h 18:10 │ 7d 71%
55
59
  | `ai-battery --watch` | 지원 | 지원 | 지원 | 지원 | 터미널 안에서 주기적으로 갱신합니다. |
56
60
  | Claude statusLine | 지원 | 지원 | 지원 | 지원 | Claude Code `statusLine`에 `node <script>` 명령을 저장합니다. |
57
61
  | Codex fullscreen | 지원 | 지원 | 지원 | 지원 | Windows 기본값은 Fullscreen PTY 화면과 터미널 배터리 행을 합성합니다. WSL/Linux/macOS는 POSIX PTY와 `python3`를 사용합니다. |
58
- | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | 기존 AI Battery wrapper를 해제합니다. 새 wrapper나 Codex 설정 변경은 명시적 옵션이 필요합니다. |
62
+ | `ai-battery setup codex` | 지원 | 지원 | 지원 | 지원 | 기존 연동을 유지·갱신합니다. 새 wrapper나 Codex 설정 변경은 명시적 옵션이 필요합니다. |
59
63
  | `ai-battery hud` | 지원 | 지원 | 지원 | 지원 | Ubuntu GNOME는 전용 패널 표시, 다른 Linux 데스크톱은 StatusNotifier 호스트를 사용합니다. |
60
64
 
61
65
  실행 중 감지는 Linux/WSL은 `/proc`, macOS는 `ps`, Windows는 PowerShell 프로세스 목록을 사용합니다. 텍스트 출력은 흰색/회색으로, macOS와 Linux HUD는 실행 중인 항목만 색상 배터리바로 강조하고 비실행 항목은 흐린 회색 계열로 표시합니다.
@@ -84,7 +88,7 @@ npx ai-battery
84
88
  npm install -g ai-battery
85
89
  ```
86
90
 
87
- 2. Claude statusLine을 설정하고, 기존 Codex wrapper가 있으면 해제합니다.
91
+ 2. 기존 연동을 갱신하고 Claude statusLine을 설정합니다. Codex wrapper와 tmux를 이미 쓰고 있다면 유지합니다.
88
92
 
89
93
  ```bash
90
94
  ai-battery setup
@@ -97,18 +101,22 @@ npx ai-battery
97
101
  codex
98
102
  ```
99
103
 
100
- 4. Codex 사용량은 별도 터미널의 `ai-battery --watch 2`, 또는 Windows/WSL/macOS HUD로 확인합니다.
104
+ 4. 터미널 공통 사용량 줄은 tmux에 연결한 뒤 tmux 세션에서 확인합니다. 기존 셸을 종료할 필요는 없습니다.
101
105
 
102
106
  ```bash
103
- ai-battery hud
107
+ ai-battery setup tmux
108
+ tmux
104
109
  ```
105
110
 
111
+ 일반 터미널에서 `codex`를 실행할 때도 사용량 행을 표시하려면 한 번 `ai-battery setup codex --wrap-codex`를 실행하고 안내된 `source` 명령을 현재 셸에 적용하세요. 이후 `setup`과 npm 업데이트에서도 이 선택을 유지합니다. 새로 열린 터미널에는 자동 적용됩니다. 데스크톱 표시는 `ai-battery hud`를 사용합니다.
112
+
106
113
  ## CLI
107
114
 
108
115
  `ai-battery`만 실행하면 도움말이 표시됩니다. 사용량은 연동된 상태 표시줄·HUD 또는 `--watch`로 계속 확인합니다.
109
116
 
110
117
  ```bash
111
118
  ai-battery setup
119
+ ai-battery setup tmux
112
120
  ai-battery hud
113
121
  ai-battery on codex
114
122
  ai-battery off codex
@@ -128,7 +136,7 @@ ai-battery --version
128
136
  | `--show-paths` | 로그 파일 경로와 데이터 관측 시각을 함께 표시합니다. |
129
137
  | `-v`, `--version` | 설치된 `ai-battery` 버전을 출력합니다. |
130
138
 
131
- `doctor`는 설치·연동 상태와 npm latest 버전을 간단히 표시합니다. 기본 설치에 필요 없는 Codex wrapper와 status_line은 오류로 안내하지 않습니다. 전체 경로·복구 기록 등 상세 정보는 `ai-battery doctor --json`으로 확인합니다. 네트워크가 막혀 있으면 버전 확인만 건너뛰고 나머지 진단은 계속 표시합니다.
139
+ `doctor`는 설치·연동 상태와 npm latest 버전을 간단히 표시합니다. tmux 설정 여부와 현재 세션 안/밖을 구분합니다. 기본 설치에 필요 없는 Codex wrapper와 status_line은 오류로 안내하지 않습니다. 전체 경로·복구 기록 등 상세 정보는 `ai-battery doctor --json`으로 확인합니다. 네트워크가 막혀 있으면 버전 확인만 건너뛰고 나머지 진단은 계속 표시합니다.
132
140
 
133
141
  <a id="uninstall"></a>
134
142
 
@@ -164,7 +172,7 @@ CLI는 npm 제거를 자동 실행하지 않습니다. `teardown`과 `uninstall`
164
172
 
165
173
  ## Setup
166
174
 
167
- `setup`은 Claude Code의 statusLine hook을 설정합니다. Codex는 기본적으로 독립 실행을 유지하며, 이전 버전의 AI Battery wrapper와 변경된 설정만 복원합니다. 원래 `codex` 실행 파일·PATH·설정에 새 변경을 추가하지 않습니다.
175
+ `setup`은 기존 Codex wrapper·PATH·상태줄과 tmux 연동을 유지·갱신하고 Claude statusLine을 설정합니다. 실행 중인 터미널의 경로와 복구용 백업을 제거하지 않습니다. 새 설치에는 Codex wrapper나 Codex 설정을 자동으로 추가하지 않습니다. 연동 해제는 `reset`으로 실행합니다.
168
176
 
169
177
  ```bash
170
178
  ai-battery setup
@@ -173,7 +181,7 @@ ai-battery setup
173
181
  일부만 설정할 수도 있습니다.
174
182
 
175
183
  ```bash
176
- ai-battery setup claude
184
+ ai-battery setup tmux
177
185
  ai-battery setup codex
178
186
  ```
179
187
 
@@ -185,7 +193,7 @@ tmux에서는 pane마다 하단 행을 예약하면 같은 전역 배터리가 p
185
193
  ai-battery setup tmux
186
194
  ```
187
195
 
188
- `~/.tmux.conf`에 관리 블록을 추가해 status-right에 배터리를 표시하고(10초 간격 갱신), 이 tmux 안에서 실행되는 `codex`는 pane별 배터리 행을 생략하고 pane 전체를 사용합니다. Claude statusLine도 같은 환경에서는 배터리 행을 접고 header(모델·디렉터리·브랜치) 1행만 표시합니다 — 배터리는 tmux bar에 이미 있기 때문입니다. 적용하려면 `tmux source-file ~/.tmux.conf` 후 새 pane을 여세요. 이 블록은 기존 `status-right` 설정을 덮어쓰므로 `setup all`에 포함되지 않는 opt-in입니다. 해제는 `ai-battery reset tmux`, tmux 안에서도 pane별 행을 유지하려면 `AI_BATTERY_TMUX=row`를 설정합니다.
196
+ `~/.tmux.conf`에 관리 블록을 추가해 status-right에 배터리를 표시하고(10초 간격 갱신), 이 tmux 안에서 실행되는 `codex`는 pane별 배터리 행을 생략하고 pane 전체를 사용합니다. Claude statusLine도 같은 환경에서는 배터리 행을 접고 header(모델·디렉터리·브랜치) 1행만 표시합니다 — 배터리는 tmux bar에 이미 있기 때문입니다. tmux 안에서 설정하면 실행 중인 서버에도 즉시 적용합니다. tmux 밖에서는 `실행: tmux`를 안내하며, tmux에 들어가야 줄이 표시됩니다. 기존 `status-right` 내용은 함께 표시합니다. 새 tmux 연동은 opt-in이며 이미 설정한 연동은 이후 `setup`과 `setup all`에서 갱신합니다. 해제는 `ai-battery reset tmux`, tmux 안에서도 pane별 행을 유지하려면 `AI_BATTERY_TMUX=row`를 설정합니다.
189
197
 
190
198
  Codex 하단 행이 보이지 않으면 진단을 실행합니다.
191
199
 
@@ -6,6 +6,7 @@ import signal
6
6
  import subprocess
7
7
  import sys
8
8
  import time
9
+ import unicodedata
9
10
 
10
11
  if os.name == "nt":
11
12
  print(
@@ -25,7 +26,12 @@ import tty
25
26
 
26
27
  SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
27
28
  BATTERY_BIN = os.environ.get("AI_BATTERY_BIN") or os.environ.get("CLAUDEX_BATTERY_BIN", os.path.join(SCRIPT_DIR, "ai-battery.js"))
28
- ANSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
29
+ ANSI_RE = re.compile(
30
+ r"(\x1b(?:\[[0-?]*[ -/]*[@-~]"
31
+ r"|\][^\x07\x1b]*(?:\x07|\x1b\\|$)"
32
+ r"|[PX^_][\s\S]*?(?:\x1b\\|$)|[ -/]*[@-~]))"
33
+ )
34
+ SGR_RE = re.compile(r"\x1b\[[0-9:;]*m")
29
35
 
30
36
 
31
37
  def battery_command_base():
@@ -164,12 +170,31 @@ def column_guard():
164
170
  return DEFAULT_COLUMN_GUARD
165
171
 
166
172
 
167
- def fit_ansi(text, width, pad=True):
168
- plain = strip_ansi(text)
169
- if len(plain) <= width:
170
- return text + (" " * (width - len(plain)) if pad else "")
171
- suffix = " " if pad else ""
172
- return plain[: max(0, width - len(suffix))] + suffix
173
+ def fit_ansi(text, width):
174
+ # Python len() counts code points, not terminal cells. Padding a Korean
175
+ # line using len() can wrap at the bottom and scroll a copy into the TUI
176
+ # on every refresh. EL clears the tail, so no padding is necessary.
177
+ output = []
178
+ cells = 0
179
+ for token in ANSI_RE.split(text):
180
+ if token.startswith("\x1b"):
181
+ # Status output may style text, but must never move the cursor,
182
+ # erase the child's screen or introduce another physical row.
183
+ if SGR_RE.fullmatch(token):
184
+ output.append(token)
185
+ continue
186
+ for char in token:
187
+ category = unicodedata.category(char)
188
+ if category in ("Cc", "Cs"):
189
+ continue
190
+ char_width = 0 if category in ("Mn", "Me", "Cf") else (
191
+ 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1
192
+ )
193
+ if cells + char_width > width:
194
+ return "".join(output)
195
+ output.append(char)
196
+ cells += char_width
197
+ return "".join(output)
173
198
 
174
199
 
175
200
  class StatusLine:
@@ -308,7 +333,7 @@ class StatusLine:
308
333
  def draw_cached(self):
309
334
  """Repaint cached text at the new terminal size without starting a poll."""
310
335
  paint_width = max(1, self.cols - 1)
311
- line = fit_ansi(self.text, paint_width, pad=True)
336
+ line = fit_ansi(self.text, paint_width)
312
337
  self.last_draw = time.monotonic()
313
338
  self.last_line = line
314
339
  self._write_row(line)
@@ -319,7 +344,7 @@ class StatusLine:
319
344
  return
320
345
  self.refresh(force)
321
346
  paint_width = max(1, self.cols - 1)
322
- line = fit_ansi(self.text, paint_width, pad=True)
347
+ line = fit_ansi(self.text, paint_width)
323
348
  if not force and not dirty and line == self.last_line:
324
349
  return
325
350
  self.last_draw = now
package/docs/RELEASING.md CHANGED
@@ -1,69 +1,69 @@
1
1
  # npm release
2
2
 
3
- The prepared version is **0.1.25**. The npm `latest` version was 0.1.24 when checked on 2026-11-05. Preparing or pushing this release does not publish it to npm.
3
+ The prepared version is **0.1.27**, following the published 0.1.26. Preparing or pushing this release does not publish it to npm.
4
4
 
5
- ## Changes in 0.1.25
5
+ ## Fixes in 0.1.27
6
6
 
7
- - Ubuntu/Linux HUD shares the macOS panel artwork. On GNOME 45–50 a bundled display extension renders the same full-size detail SVG inside its native popup, followed by Refresh and Quit. First installation requires one sign-out/sign-in for extension discovery. Other desktops retain the StatusNotifier menu. Extension disable/disconnect restores the standard tray without duplicate icons; reset removes only owned extension files and settings. Snapshots run asynchronously, failures keep the last artwork with a retry message, and the service reconnects after unlock. XDG autostart, stop/status/reset and isolated state roots are supported; WSL continues to use the Windows HUD.
8
- - Help, diagnostics, setup/reset results and errors use concise Korean or English messages. Locale selection follows `LANGUAGE`, `LC_ALL`, `LC_MESSAGES`, `LANG`, then Node's default locale. Unsupported languages fall back to English. Technical terms, paths, commands and external errors remain intact.
9
- - Main help lists `setup`, `hud` and `on / off` first, with command and option headings. Detailed help only advertises relevant options and examples; native Windows HUD options are shown on Windows.
10
- - **CLI behavior change:** running `ai-battery` without arguments opens help, and the `show` command is removed. Use an integrated status line, HUD or `--watch` for continuous usage display. Existing flag-based JSON, tmux, runner and macOS menu outputs remain available to integrations.
11
- - `ai-battery reset` restores integrations and cleans owned files; targets can follow directly, for example `ai-battery reset claude`. `reset settings`, `reset config`, `teardown` and `uninstall` remain compatibility forms. Reset preserves npm packages and unrelated provider settings.
12
- - `doctor` summarizes status without treating optional Codex wrappers/status lines as missing requirements. `doctor --json` retains full diagnostic data. JSON report keys and message values remain independent of the display locale.
7
+ - POSIX terminal rows measure Korean/full-width text in screen cells, retain colors while clipping, and clear the old tail without space padding. Repeated refreshes no longer wrap the bottom row and accumulate meter copies in the Codex screen or scrollback. Bounded rows show unavailable providers as `Codex --%` / `Claude --%`; detailed diagnostics retain localized errors.
13
8
 
14
- ## Validation
9
+ The active runner keeps its Python code until the next launch. Updating the CLI formatter also mitigates the reported Korean-error overflow in already-running sessions, since each status poll loads the formatter again. Existing Codex processes need not be terminated.
15
10
 
16
- Run checks from this checkout and save release artifacts under `.cache/releases/0.1.25/`:
11
+ ## Fixes in 0.1.26
12
+
13
+ - `setup` no longer invokes Codex teardown. It refreshes previously selected wrappers in place and preserves PATH blocks, built-in status lines, original-command backups and compatibility paths cached by existing shells. Wrapper replacement is atomic so an already-open script keeps its original bytes. Integration removal is explicit through `reset`.
14
+ - POSIX setup persists the shell PATH block even when the current process already has the shim on PATH. A session-only environment no longer makes setup report success while fresh shells lose the integration.
15
+ - A fresh install still leaves Codex independent until `--wrap-codex` or `--configure-codex-statusline` is requested. Setup explains how to enable terminal display instead of implying that standalone configuration creates a terminal row.
16
+ - Previously selected tmux integration is refreshed by default setup, including after npm updates. Fully removed managed blocks can be installed again without discarding current user configuration. Partial/edited blocks and retargeted symlinks remain protected. tmux commands use the stable bin entrypoint and quote paths for the config parser.
17
+ - Setup inside tmux applies owned status options to the running server without sourcing unrelated user configuration. Setup outside tmux reports `configured` and `Start: tmux`; doctor distinguishes configuration from being inside a tmux session.
18
+ - The GNOME HUD popup removes both the content border and box-pointer border. Korean and English main/setup examples use `ai-battery setup tmux`.
19
+
20
+ ## Validation and package preparation
17
21
 
18
22
  ```text
19
23
  npm run check
20
24
  npm run smoke:linux
25
+ mkdir -p .cache/releases/0.1.27
21
26
  npm pack --dry-run --json
22
- npm pack --pack-destination .cache/releases/0.1.25 --json
27
+ npm pack --pack-destination .cache/releases/0.1.27 --json
23
28
  ```
24
29
 
25
- The regression suite covers locale precedence, command help, no-argument help, removed commands, bare and targeted reset, compatibility forms, localized runtime messages, file preservation and locale-independent JSON reports. Linux HUD tests cover real GJS registration/menu export on a private session bus, snapshot refresh, provider visibility, stale-data recovery, reconnect, restart, stop/reset and literal desktop-entry argument handling. Native Linux tests require GJS and libdbusmenu; other platform tests are skipped where their runtime is unavailable. Native Windows, macOS and Windows ARM64 require their own runtime validation.
30
+ The regression suite includes real PTYs: an already-running wrapped Codex remains interactive during setup, the same Bash command cache launches it again, a fresh shell displays the usage row, and an attached tmux client displays the bar after live setup. An open wrapper reader retains its old bytes, compatibility command paths and recovery backups survive, and user Codex/shell/tmux settings are compared exactly.
26
31
 
27
- On Ubuntu GNOME 50.1 / Wayland, the Linux HUD registered with the real AppIndicators host. A separate headless GNOME Shell session verifies the actual popup and saves a screenshot, checks full-size shared artwork, provider visibility/resizing, extension disable/enable, tray fallback and service shutdown. Private-bus tests also cover presenter ownership and automatic tray restoration after a display client disappears, plus extension installation/removal and foreign-file/symlink preservation.
32
+ POSIX screen regressions replay actual output into a terminal emulator and inspect the rendered rows, cursor and scrollback. They cover repeated Korean error rows, narrow widths, wide/combining characters, control sequences, shorter replacement text, resize and keyboard input through a live PTY.
28
33
 
29
- Inspect the package manifest for the core CLI help/message/output modules, platform modules, stable bin entrypoints and required PowerShell files. Exclude tests, logs, credentials, node_modules and `.cache`. Install the exact tarball into an isolated npm prefix, with lifecycle scripts disabled for the smoke check, and verify:
34
+ Also install 0.1.26 into an isolated npm prefix, open the PTY fixture, upgrade that prefix to the exact 0.1.27 tarball, and run default setup while the original terminal remains open. Save the lifecycle report, package manifest, SHA256 checksum, installed-package smoke report and publish dry-run under `.cache/releases/0.1.27/`.
30
35
 
31
- - npm bin links and `--version` report 0.1.25;
32
- - Korean and English main/command help show the intended commands and headings;
33
- - setup, doctor, on/off and targeted reset work with temporary provider homes;
34
- - invalid commands/configuration produce localized errors without changing the source file;
35
- - JSON reports retain the same schema and values across locales.
36
+ The Linux GUI smoke test opens the actual popup in an isolated GNOME 50.1 Wayland session, verifies zero border width for the content and box pointer, and saves a screenshot. It also checks shared macOS SVG size, provider visibility, extension fallback/reconnect and shutdown. Native Windows/macOS runtime tests require their respective environments; platform-neutral regressions still run here.
36
37
 
37
- Keep the tarball, manifest, checksum, test log, installed-package smoke report and publish dry-run output together. Publish that tested tarball rather than rebuilding it after validation.
38
+ Inspect the tarball for runtime modules, stable bin entrypoints and required platform files. Exclude tests, logs, credentials, node_modules and `.cache`. Publish the exact tested tarball.
38
39
 
39
40
  ## Publish manually
40
41
 
41
- Publishing is a separate step. The current npm authentication check returned HTTP 401; authenticate before publishing:
42
-
43
42
  ```text
44
- npm login
45
43
  npm whoami
46
- npm publish .cache/releases/0.1.25/ai-battery-0.1.25.tgz --access public --tag latest
44
+ npm publish .cache/releases/0.1.27/ai-battery-0.1.27.tgz --access public --tag latest
47
45
  npm view ai-battery version dist-tags --json
48
46
  ```
49
47
 
50
- Complete npm authentication/2FA when requested. If 0.1.25 is already published by then, increment the version and rebuild and verify the package. After successful publication, tag the tested commit `v0.1.25`.
48
+ Authenticate with `npm login` if required, and complete npm 2FA when requested. If 0.1.27 is already published, increment the version and repeat verification. Tag the tested commit `v0.1.27` after publication.
51
49
 
52
- ## Update or remove an installation
53
-
54
- Run separately for Windows, WSL and each Node installation:
50
+ ## Update and enable terminal display
55
51
 
56
52
  ```text
57
- npm install -g ai-battery@0.1.25
53
+ npm install -g ai-battery@0.1.27
58
54
  ai-battery setup
55
+ ai-battery setup tmux
56
+ tmux
59
57
  ```
60
58
 
61
- Default Codex setup preserves independent execution. It does not install a wrapper or modify Codex settings unless explicitly requested with `--wrap-codex` or `--configure-codex-statusline`. Use a supported desktop HUD or `--watch` for usage display. There is no built-in `ai-battery update` command.
59
+ For a Codex usage row outside tmux, enable it once with `ai-battery setup codex --wrap-codex` and run the printed source command in existing shells. New shells load it automatically. Subsequent setup calls preserve that choice. Re-running setup does not require closing running Codex sessions.
60
+
61
+ GNOME caches loaded extension JavaScript. After its display code changes, sign out and back in when convenient, then start the HUD again. The terminal integration does not require a desktop restart.
62
62
 
63
- Restore integrations before removing the package:
63
+ Restore integrations before explicitly removing the npm package:
64
64
 
65
65
  ```text
66
66
  ai-battery reset && npm uninstall -g ai-battery
67
67
  ```
68
68
 
69
- For local installs use `npm uninstall ai-battery`. Reset keeps edited/unrecognized files and incomplete recovery records, and never invokes npm uninstall. Existing Bash terminals may need `hash -r` (zsh: `rehash`) after a legacy wrapper is removed; sessions already using a wrapper keep their terminal row until they exit.
69
+ Reset preserves edited/unrecognized files, incomplete recovery records and unrelated provider settings. It never invokes npm uninstall itself. Only explicit reset removes integrations; existing Bash terminals may then need `hash -r` (zsh: `rehash`).
package/lib/cli.js CHANGED
@@ -950,7 +950,7 @@ function extractExistingStatusRight(confText) {
950
950
  function tmuxStatusBlock(existingStatusRight = null) {
951
951
  // #{client_width} is expanded by tmux before running the shell command,
952
952
  // giving the responsive layout the actual terminal width to work with.
953
- const battery = `${shQuote(process.execPath)} ${shQuote(fileURLToPath(import.meta.url))} --tmux --bar-width 8 --max-width #{client_width}`;
953
+ const battery = `${shQuote(process.execPath)} ${shQuote(path.join(scriptDir(), "ai-battery.js"))} --tmux --bar-width 8 --max-width #{client_width}`;
954
954
  const batteryPart = `#(${battery})`;
955
955
  // Put the battery on the far right so tmux left-clips the existing text before
956
956
  // the bar. When the block is uninstalled, the earlier set -g status-right wins.
@@ -963,36 +963,49 @@ function tmuxStatusBlock(existingStatusRight = null) {
963
963
  "# AI Battery once per session in the tmux status bar; runners inside tmux",
964
964
  "# see AI_BATTERY_TMUX_STATUS and skip their per-pane bottom row.",
965
965
  "set-environment -g AI_BATTERY_TMUX_STATUS 1",
966
+ "set -g status on",
966
967
  "set -g status-interval 10",
967
968
  `set-option -g status-right-length ${rightLength}`,
968
- `set -g status-right "${statusRightValue}"`,
969
+ `set -g status-right "${statusRightValue.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`,
969
970
  "# <<< ai-battery tmux <<<",
970
971
  ""
971
972
  ].join("\n");
972
973
  }
973
974
 
974
- function installTmuxStatus() {
975
+ function installTmuxStatus({ confPath = tmuxConfPath() } = {}) {
975
976
  if (process.platform === "win32") {
976
977
  return { skipped: true, reason: "tmux status integration applies to WSL/Linux/macOS" };
977
978
  }
978
- const confPath = tmuxConfPath();
979
979
  let existing = "";
980
980
  try {
981
981
  existing = fs.readFileSync(confPath, "utf8");
982
- } catch {}
982
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
983
983
  const withoutBlock = stripOwnedBlock(confPath, existing, removeAiBatteryTmuxBlock);
984
984
  const existingStatusRight = extractExistingStatusRight(withoutBlock);
985
985
  const next = `${withoutBlock}${tmuxStatusBlock(existingStatusRight)}`;
986
- if (next === existing) {
987
- return { ok: true, confPath, changed: false };
986
+ if (next !== existing) installManagedText(confPath, next, next.slice(withoutBlock.length));
987
+ let active = false;
988
+ let error = null;
989
+ if (process.env.TMUX && !process.env.AI_BATTERY_TMUX_CONF) {
990
+ const commands = [
991
+ "set-environment", "-g", "AI_BATTERY_TMUX_STATUS", "1", ";",
992
+ "set-option", "-g", "status", "on", ";",
993
+ "set-option", "-g", "status-interval", "10", ";",
994
+ "set-option", "-g", "status-right-length", "200", ";",
995
+ "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}) `
996
+ ];
997
+ const result = spawnSync("tmux", commands, { encoding: "utf8", timeout: 4000 });
998
+ active = !result.error && result.status === 0;
999
+ if (!active) error = result.error?.message || result.stderr?.trim() || "Could not apply the tmux status bar";
988
1000
  }
989
- installManagedText(confPath, next, next.slice(withoutBlock.length));
990
1001
  return {
991
- ok: true,
1002
+ ok: !error,
992
1003
  confPath,
993
- changed: true,
1004
+ changed: next !== existing,
1005
+ active,
1006
+ error,
994
1007
  updated: existing !== withoutBlock,
995
- note: `Reload tmux to apply: tmux source-file ${confPath} (new panes then hide the per-pane battery row).`
1008
+ note: active ? null : "Start tmux to show the terminal usage bar."
996
1009
  };
997
1010
  }
998
1011
 
@@ -1067,25 +1080,19 @@ function ensureShimPath(shimDir, originalCommand) {
1067
1080
  const originalDir = path.dirname(originalCommand);
1068
1081
  const originalIndex = entries.findIndex((entry) => path.resolve(entry) === path.resolve(originalDir));
1069
1082
  const activeNow = shimIndex >= 0 && (originalIndex < 0 || shimIndex < originalIndex);
1070
- if (activeNow) {
1071
- return {
1072
- changed: false,
1073
- rcPath: null,
1074
- note: `${shimDir} is already before the original codex on PATH. Plain "codex" can use AI Battery in new command lookups. If this shell already cached codex, run "hash -r" once.`
1075
- };
1076
- }
1077
-
1078
1083
  const rcPath = shellRcPath();
1079
1084
  fs.mkdirSync(path.dirname(rcPath), { recursive: true });
1080
1085
  const existing = fs.existsSync(rcPath) ? fs.readFileSync(rcPath, "utf8") : "";
1081
1086
  const withoutAiBatteryBlock = stripOwnedBlock(rcPath, existing, removeAiBatteryShellPathBlock);
1082
1087
  const separator = withoutAiBatteryBlock && !withoutAiBatteryBlock.endsWith("\n") ? "\n" : "";
1083
1088
  const next = `${withoutAiBatteryBlock}${separator}${shellPathBlock(shimDir)}`;
1084
- installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1089
+ const changed = next !== existing;
1090
+ if (changed) installManagedText(rcPath, next, next.slice(withoutAiBatteryBlock.length));
1085
1091
 
1086
1092
  return {
1087
- changed: true,
1088
- rcPath,
1093
+ changed,
1094
+ persisted: true,
1095
+ rcPath: changed || !activeNow ? rcPath : null,
1089
1096
  note: `${existing === withoutAiBatteryBlock ? "Added" : "Updated"} ${shimDir} before PATH in ${rcPath}. Open a new terminal for plain "codex" to use AI Battery.`
1090
1097
  };
1091
1098
  }
@@ -1094,6 +1101,7 @@ function codexWrapperCandidates(config = readConfig()) {
1094
1101
  const activeCodex = findCommand("codex");
1095
1102
  return uniquePaths([
1096
1103
  config.codexWrapper?.wrapperPath,
1104
+ ...(config.codexWrapper?.compatibilityWrappers || []).map(item => item.wrapperPath),
1097
1105
  process.env.AI_BATTERY_SHIM_DIR ? codexWrapperPathInDir(process.env.AI_BATTERY_SHIM_DIR) : null,
1098
1106
  codexWrapperPathInDir(defaultCodexShimDir()),
1099
1107
  legacyCodexWrapperPath(),
@@ -1122,6 +1130,7 @@ function codexTimestampBackups(wrapperPath) {
1122
1130
  function codexWrapperBackupCandidates(wrapperPath, config = readConfig()) {
1123
1131
  return uniquePaths([
1124
1132
  config.codexWrapper?.wrapperPath === wrapperPath ? config.codexWrapper?.backupPath : null,
1133
+ ...(config.codexWrapper?.compatibilityWrappers || []).filter(item => samePath(item.wrapperPath, wrapperPath)).map(item => item.backupPath),
1125
1134
  `${wrapperPath}${CODEX_PREFERRED_BACKUP_SUFFIX}`,
1126
1135
  ...codexTimestampBackups(wrapperPath)
1127
1136
  ]);
@@ -1561,6 +1570,7 @@ function canRemoveCodexWrapperWithoutBackup(wrapperPath, config = readConfig())
1561
1570
  if (samePath(wrapperPath, legacyCodexWrapperPath())) return true;
1562
1571
  const configuredWrapper = config.codexWrapper?.wrapperPath;
1563
1572
  if (configuredWrapper && samePath(wrapperPath, configuredWrapper)) return true;
1573
+ if (config.codexWrapper?.compatibilityWrappers?.some(item => item.owned && samePath(item.wrapperPath, wrapperPath))) return true;
1564
1574
  return false;
1565
1575
  }
1566
1576
 
@@ -1657,13 +1667,9 @@ function uninstallCodexWrapper() {
1657
1667
  ? removeManagedCodexBridge(configuredWrapperPath)
1658
1668
  : null;
1659
1669
 
1660
- const configuredBlocked = Boolean(
1661
- configuredWrapperPath
1662
- && (
1663
- unmanaged.some((wrapperPath) => samePath(wrapperPath, configuredWrapperPath))
1664
- || skippedWrappers.some((item) => samePath(item.wrapperPath, configuredWrapperPath))
1665
- )
1666
- );
1670
+ const recordedWrappers = [configuredWrapperPath, ...(config.codexWrapper?.compatibilityWrappers || []).map(item => item.wrapperPath)].filter(Boolean);
1671
+ const configuredBlocked = recordedWrappers.some(file => unmanaged.some(wrapperPath => samePath(wrapperPath, file))
1672
+ || skippedWrappers.some(item => samePath(item.wrapperPath, file)));
1667
1673
  const hadConfig = Boolean(config.codexWrapper);
1668
1674
  const clearedWrapperConfig = hadConfig && !configuredBlocked;
1669
1675
  const rcPaths = configuredBlocked
@@ -1715,9 +1721,13 @@ function installCodexWrapper(args) {
1715
1721
  };
1716
1722
  }
1717
1723
 
1718
- const shimSelection = selectCodexShimDir(originalCommand, originalPathForPath);
1724
+ const configuredWrapper = config.codexWrapper?.wrapperPath;
1725
+ const shimSelection = configuredWrapper && !process.env.AI_BATTERY_SHIM_DIR
1726
+ ? { shimDir: path.dirname(configuredWrapper), immediate: pathDirPrecedesOriginal(path.dirname(configuredWrapper), originalPathForPath), reason: "Existing Codex integration" }
1727
+ : selectCodexShimDir(originalCommand, originalPathForPath);
1719
1728
  const shimDir = shimSelection.shimDir;
1720
1729
  const wrapperPath = codexWrapperPathInDir(shimDir);
1730
+ const newlyInstalled = !fs.existsSync(wrapperPath);
1721
1731
 
1722
1732
  if (samePath(wrapperPath, originalCommand)) {
1723
1733
  return {
@@ -1728,7 +1738,7 @@ function installCodexWrapper(args) {
1728
1738
  }
1729
1739
 
1730
1740
  fs.mkdirSync(shimDir, { recursive: true, mode: 0o755 });
1731
- let backupPath = null;
1741
+ const backupPath = existingCodexWrapperBackup(wrapperPath, config) || null;
1732
1742
  if (fs.existsSync(wrapperPath) && !managedCodexWrapper(wrapperPath)) {
1733
1743
  return {
1734
1744
  ok: false,
@@ -1739,13 +1749,16 @@ function installCodexWrapper(args) {
1739
1749
 
1740
1750
  const bridgePath = process.platform === "win32" ? codexWrapperBridgePath(wrapperPath) : null;
1741
1751
  if (bridgePath) writeTextAtomic(bridgePath, windowsCodexWrapperBridge());
1742
- fs.writeFileSync(wrapperPath, codexWrapperScriptForPlatform(originalCommand), { mode: 0o755 });
1752
+ writeTextAtomic(wrapperPath, codexWrapperScriptForPlatform(originalCommand), 0o755);
1743
1753
 
1744
- const wrapperCleanup = [];
1745
- for (const staleWrapperPath of codexInstallSkipPaths(config)) {
1754
+ const compatibilityWrappers = [];
1755
+ for (const staleWrapperPath of codexWrapperCandidates(config)) {
1746
1756
  if (samePath(staleWrapperPath, wrapperPath)) continue;
1747
1757
  if (!fs.existsSync(staleWrapperPath) || !managedCodexWrapper(staleWrapperPath)) continue;
1748
- wrapperCleanup.push(removeOrRestoreCodexWrapper(staleWrapperPath, config));
1758
+ const previousBackup = existingCodexWrapperBackup(staleWrapperPath, config) || null;
1759
+ if (process.platform === "win32") writeTextAtomic(codexWrapperBridgePath(staleWrapperPath), windowsCodexWrapperBridge());
1760
+ writeTextAtomic(staleWrapperPath, codexWrapperScriptForPlatform(originalCommand), 0o755);
1761
+ compatibilityWrappers.push({ wrapperPath: staleWrapperPath, backupPath: previousBackup, owned: canRemoveCodexWrapperWithoutBackup(staleWrapperPath, config) });
1749
1762
  }
1750
1763
 
1751
1764
  const pathResult = ensureShimPath(shimDir, originalPathForPath || originalCommand);
@@ -1756,6 +1769,7 @@ function installCodexWrapper(args) {
1756
1769
  originalCommand,
1757
1770
  backupPath,
1758
1771
  bridgePath,
1772
+ compatibilityWrappers,
1759
1773
  pathAddedByAiBattery: process.platform === "win32"
1760
1774
  ? (pathResult.changed
1761
1775
  ? shimDir
@@ -1768,11 +1782,11 @@ function installCodexWrapper(args) {
1768
1782
  return {
1769
1783
  ok: true,
1770
1784
  wrapperPath,
1785
+ newlyInstalled,
1771
1786
  originalCommand,
1772
1787
  backupPath,
1773
1788
  bridgePath,
1774
- legacyCleanup: wrapperCleanup,
1775
- wrapperCleanup,
1789
+ preservedWrappers: compatibilityWrappers.map(item => item.wrapperPath),
1776
1790
  shimSelection,
1777
1791
  path: pathResult
1778
1792
  };
@@ -2039,6 +2053,7 @@ async function runDoctor() {
2039
2053
  }
2040
2054
  },
2041
2055
  codex: diagnoseCodex(),
2056
+ ...(process.platform !== "win32" ? { tmux: diagnoseTmux() } : {}),
2042
2057
  claude: {
2043
2058
  providerEnabled: providerVisible("claude"),
2044
2059
  cachePath: claudeCachePath(),
@@ -2058,6 +2073,15 @@ async function runDoctor() {
2058
2073
  };
2059
2074
  }
2060
2075
 
2076
+ function diagnoseTmux() {
2077
+ const confPath = tmuxConfPath();
2078
+ let configured = false;
2079
+ let error = null;
2080
+ try { const text = fs.readFileSync(confPath, "utf8"); configured = removeAiBatteryTmuxBlock(text) !== text; }
2081
+ catch (cause) { if (cause.code !== "ENOENT") error = cause.message; }
2082
+ return { available: Boolean(findCommand("tmux")), confPath, configured, insideTmux: Boolean(process.env.TMUX), error };
2083
+ }
2084
+
2061
2085
  function windowsCscPath() {
2062
2086
  const windir = process.env.WINDIR || "C:\\Windows";
2063
2087
  const candidates = [
@@ -2226,6 +2250,19 @@ function setupTargets(targets) {
2226
2250
 
2227
2251
  function runSetup(args) {
2228
2252
  const targets = setupTargets(args.targets);
2253
+ const previous = readConfig({ strict: true });
2254
+ let tmuxRefreshPath = null;
2255
+ if ((!args.targets.length || args.targets.includes("all")) && process.platform !== "win32") {
2256
+ const confPath = tmuxConfPath();
2257
+ const recorded = Object.entries(previous.integrationFiles || {}).filter(([, record]) => record.block?.includes("# >>> ai-battery tmux >>>"));
2258
+ let configured = false;
2259
+ try { const text = fs.readFileSync(confPath, "utf8"); configured = removeAiBatteryTmuxBlock(text) !== text; }
2260
+ catch (error) { if (error.code !== "ENOENT") throw error; }
2261
+ if ((recorded.length || configured) && !targets.includes("tmux")) {
2262
+ targets.push("tmux");
2263
+ tmuxRefreshPath = configured || process.env.AI_BATTERY_TMUX_CONF ? confPath : recorded[0][0];
2264
+ }
2265
+ }
2229
2266
  const results = {};
2230
2267
  let windowsClaudeLauncher = null;
2231
2268
  if (targets.includes("claude")) {
@@ -2238,27 +2275,23 @@ function runSetup(args) {
2238
2275
  }
2239
2276
  }
2240
2277
  if (targets.includes("tmux")) {
2241
- results.tmux = installTmuxStatus();
2278
+ results.tmux = installTmuxStatus(tmuxRefreshPath ? { confPath: tmuxRefreshPath } : {});
2242
2279
  }
2243
2280
  if (targets.includes("codex")) {
2244
- const statusLine = args.wrapCodex && args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2245
- if (args.wrapCodex) {
2281
+ const wrapCodex = args.wrapCodex || Boolean(previous.codexWrapper)
2282
+ || codexWrapperCandidates(previous).some(file => managedCodexWrapper(file));
2283
+ const statusLine = args.configureCodexStatusLine ? installCodexStatusLine(args) : null;
2284
+ if (wrapCodex) {
2246
2285
  results.codex = { ...installCodexWrapper(args), statusLine };
2247
2286
  } else {
2248
- const legacyCleanup = uninstallCodexWrapper();
2249
- const failed = teardownResultFailed({ results: { codex: legacyCleanup } });
2250
2287
  results.codex = {
2251
- ok: !failed,
2252
- standalone: !failed,
2253
- skipped: failed,
2254
- legacyCleanup,
2255
- reason: failed ? "Could not safely detach the legacy Codex integration; kept recovery metadata. Run ai-battery reset codex for details."
2256
- : "Codex command and configuration are left under Codex's control. Use ai-battery hud or ai-battery-run -- codex for usage display."
2288
+ ok: true,
2289
+ standalone: true,
2290
+ reason: "Codex command and configuration are left under Codex's control.",
2291
+ statusLine
2257
2292
  };
2258
- // An explicit status-line request is applied after legacy restoration.
2259
- if (args.configureCodexStatusLine && !failed) results.codex.statusLine = installCodexStatusLine(args);
2260
2293
  }
2261
- if (process.platform === "win32" && args.wrapCodex) {
2294
+ if (process.platform === "win32" && wrapCodex) {
2262
2295
  results.codex.rowpty = windowsSetupNeedsRowPty()
2263
2296
  ? (windowsClaudeLauncher || installRowPtyHost())
2264
2297
  : {
@@ -4345,7 +4378,8 @@ function weekText(secondary) {
4345
4378
  }
4346
4379
 
4347
4380
  function formatCodex(data, args) {
4348
- if (!data.ok) return statusColorize(data, `Codex ? (${cliMessageText(data.error)})`, args);
4381
+ if (!data.ok) return statusColorize(data, args.maxWidth && !args.showPaths
4382
+ ? "Codex --%" : `Codex ? (${cliMessageText(data.error)})`, args);
4349
4383
 
4350
4384
  const batteryColor = remainingColor(data.percentRemaining);
4351
4385
  const primary = data.primary;
@@ -4380,7 +4414,8 @@ function formatCodex(data, args) {
4380
4414
  }
4381
4415
 
4382
4416
  function formatClaude(data, args) {
4383
- if (!data.ok) return statusColorize(data, `Claude ? (${cliMessageText(data.error)})`, args);
4417
+ if (!data.ok) return statusColorize(data, args.maxWidth && !args.showPaths
4418
+ ? "Claude --%" : `Claude ? (${cliMessageText(data.error)})`, args);
4384
4419
 
4385
4420
  if (data.sourceType === "statusline") {
4386
4421
  const batteryColor = remainingColor(data.percentRemaining);
@@ -4944,7 +4979,7 @@ function render(snapshot, args) {
4944
4979
  }
4945
4980
  // A split pane can be too narrow even for the minimum bars. Retain both
4946
4981
  // names and readings rather than letting the one-row terminal wrap away
4947
- // a provider. Error detail and bars remain available in wider panes.
4982
+ // a provider. Detailed errors remain available in diagnostics.
4948
4983
  const readings = snapshot.results.map((result) => {
4949
4984
  const percent = typeof result.percentRemaining === "number" ? `${result.percentRemaining}%` : "--%";
4950
4985
  const name = result.provider === "codex" ? "Codex" : result.provider === "claude" ? "Claude" : result.provider;
@@ -82,7 +82,7 @@ export function helpText(command = "", { env = process.env, platform = process.p
82
82
  return [
83
83
  usage(legacy ? `${command} [--force]` : "setup [codex|claude|tmux|all] [options]"),
84
84
  legacy ? t("Configure Claude Code's usage status line.", "Claude Code 상태 표시줄에 사용량을 연결합니다.")
85
- : t("Configure usage display integrations (default: codex and claude; tmux is opt-in).", "사용량 표시를 연동합니다. 기본 대상은 codex와 claude이며 tmux는 별도로 지정합니다."),
85
+ : t("Configure usage display. Existing integrations are preserved and refreshed; new tmux integration is opt-in.", "사용량 표시를 연동합니다. 기존 연동은 유지·갱신하며 새 tmux 연동은 별도로 지정합니다."),
86
86
  options([
87
87
  ["--force", "Replace an existing Claude statusLine", "기존 Claude 상태 표시줄 교체"],
88
88
  ...(!legacy ? [
@@ -93,7 +93,7 @@ export function helpText(command = "", { env = process.env, platform = process.p
93
93
  ]),
94
94
  legacy ? t("Restore settings: ai-battery reset claude", "설정 복원: ai-battery reset claude")
95
95
  : t("By default, Codex keeps its command, PATH and settings.\nRestore settings: ai-battery reset", "기본 Codex 설치는 실행 명령·PATH·설정을 유지합니다.\n설정 복원: ai-battery reset"),
96
- examples(legacy ? [`ai-battery ${command}`] : ["ai-battery setup claude", "ai-battery setup tmux"])
96
+ examples(legacy ? [`ai-battery ${command}`] : ["ai-battery setup tmux"])
97
97
  ].join("\n\n");
98
98
  }
99
99
  if (command === "uninstall-claude-statusline") {
@@ -157,7 +157,7 @@ export function helpText(command = "", { env = process.env, platform = process.p
157
157
  ])}`,
158
158
  options([["-w, --watch [seconds]", "Refresh periodically (default: 10s)", "주기적으로 갱신 (기본: 10초)"],
159
159
  ["-v, --version", "Show version", "버전 확인"], ["-h, --help", "Show help", "도움말 보기"]]),
160
- examples(["ai-battery setup claude", "ai-battery hud", "ai-battery on codex"]),
160
+ examples(["ai-battery setup tmux", "ai-battery hud", "ai-battery on codex"]),
161
161
  t("More help: ai-battery <command> --help", "상세 도움말: ai-battery <명령> --help")
162
162
  ].join("\n\n");
163
163
  }
@@ -38,6 +38,7 @@ export function formatSetupResult(result, { failed = false, platform = process.p
38
38
  o.add(`Original: ${codex.originalCommand}`);
39
39
  if (reloadCommand) o.add(`${o.t("Apply", "적용")}: ${reloadCommand}`);
40
40
  else if (platform === "win32") o.add(o.t("Open a new cmd/PowerShell to apply PATH changes.", "PATH 변경을 적용하려면 새 cmd/PowerShell을 여세요."));
41
+ else if (codex.newlyInstalled) o.add(o.t("Apply in existing shells: hash -r (zsh: rehash).", "기존 셸에 적용: hash -r (zsh: rehash)."));
41
42
  if (codex.path?.ok === false || codex.path?.error) {
42
43
  o.error("PATH", codex.path.error || o.t("Could not update PATH.", "PATH를 갱신하지 못했습니다."));
43
44
  }
@@ -46,7 +47,7 @@ export function formatSetupResult(result, { failed = false, platform = process.p
46
47
  o.add("Codex: skipped");
47
48
  o.note(codex.reason);
48
49
  }
49
- if (codex.legacyCleanup?.changed) o.add(o.t("Legacy Codex integration removed. Run: hash -r (zsh: rehash).", "이전 Codex 연동을 해제했습니다. 실행: hash -r (zsh: rehash)."));
50
+ if (codex.standalone && platform !== "win32" && !tmux) o.add(o.t("Terminal usage: ai-battery setup tmux", "터미널 사용량 표시: ai-battery setup tmux"));
50
51
  if (codex.statusLine) {
51
52
  const status = codex.statusLine;
52
53
  o.add(`Codex status_line: ${status.error ? "error" : status.alreadyConfigured ? "already configured" : "configured"} · ${status.configPath}`);
@@ -55,10 +56,10 @@ export function formatSetupResult(result, { failed = false, platform = process.p
55
56
  if (codex.retainedConfig) o.add(o.t("Codex recovery record preserved; restore is incomplete.", "Codex 복원이 끝나지 않아 복구 기록을 유지했습니다."));
56
57
  }
57
58
  if (tmux) {
58
- o.add(`tmux status-right: ${tmux.ok ? "ready" : tmux.skipped ? "skipped" : "error"}${tmux.confPath ? ` · ${tmux.confPath}` : ""}`);
59
+ o.add(`tmux status-right: ${tmux.ok ? tmux.active ? "active" : "configured" : tmux.skipped ? "skipped" : "error"}${tmux.confPath ? ` · ${tmux.confPath}` : ""}`);
59
60
  if (tmux.error) o.error("Error", tmux.error);
60
61
  else if (!tmux.ok) o.note(tmux.reason);
61
- else if (tmux.note) o.add(`${o.t("Apply", "적용")}: tmux source-file ${tmux.confPath}`);
62
+ else if (!tmux.active) o.add(o.t("Start: tmux", "실행: tmux"));
62
63
  }
63
64
  const rowpty = codex?.rowpty;
64
65
  if (rowpty && !rowpty.skipped) {
@@ -99,6 +100,13 @@ export function formatDoctorResult(result, { env = process.env } = {}) {
99
100
  o.add(` statusLine: ${claude.statusLine.error ? "error" : claude.statusLine.managed ? "ready" : claude.statusLine.configured ? "external" : "not configured"}`);
100
101
  o.add(` Cache: ${claude.statuslineCache ? "ready" : "waiting"}`);
101
102
  if (claude.statusLine.managed && !claude.statuslineCache) o.add(o.t(" Start Claude Code to receive usage data.", " Claude Code를 실행하면 사용량이 수집됩니다."));
103
+ if (result.tmux) {
104
+ o.lines.push("");
105
+ o.add(`tmux: ${result.tmux.error ? "error" : result.tmux.configured ? result.tmux.insideTmux ? "configured · in session" : "configured · outside session" : "not configured"}`);
106
+ o.error(" Error", result.tmux.error);
107
+ if (result.tmux.configured && !result.tmux.insideTmux) o.add(o.t(" Start: tmux", " 실행: tmux"));
108
+ else if (!result.tmux.configured && !codex.wrapperInstalled) o.add(o.t(" Terminal usage: ai-battery setup tmux", " 터미널 사용량 표시: ai-battery setup tmux"));
109
+ }
102
110
  const recovery = battery.recovery;
103
111
  const backups = [recovery.codexWrapper && "Codex wrapper", recovery.codexStatusLine && "Codex status_line", recovery.claudeStatusLine && "Claude statusLine"].filter(Boolean);
104
112
  if (backups.length) o.add(`Recovery: ${backups.join(", ")}`);
@@ -22,11 +22,18 @@ export function createIntegrationFiles({ readConfig, writeConfig, writeTextAtomi
22
22
  const separator = before && after && !before.endsWith("\n") && !after.startsWith("\n") ? "\n" : "";
23
23
  return before + separator + after;
24
24
  }
25
+ function setupBase(text, record, file) {
26
+ // An explicitly removed block can be installed again, preserving the whole
27
+ // current file. A partial or edited block still requires manual recovery.
28
+ const markers = record.block.match(/^# (?:>>>|<<<) ai-battery [^\r\n]+$/gm);
29
+ if (markers?.length === 2 && markers.every(marker => !text.includes(marker))) return text;
30
+ return stripRecorded(text, record, file);
31
+ }
25
32
  function stripOwnedBlock(file, text, fallback) {
26
33
  const record = recordFor(file);
27
34
  if (!record) return fallback(text);
28
35
  checkTarget(file, record);
29
- return stripRecorded(text, record, file);
36
+ return setupBase(text, record, file);
30
37
  }
31
38
  function installManagedText(file, next, block) {
32
39
  const config = readConfig({ strict: true });
@@ -35,13 +42,13 @@ export function createIntegrationFiles({ readConfig, writeConfig, writeTextAtomi
35
42
  const current = read(file);
36
43
  if (previous && current !== null) {
37
44
  checkTarget(file, previous);
38
- stripRecorded(current, previous, file);
45
+ setupBase(current, previous, file);
39
46
  }
40
47
  if (!block) throw new Error(`Cannot record an empty integration block: ${file}`);
41
48
  const mode = current === null ? 0o600 : fs.statSync(file).mode & 0o777;
42
49
  const record = {
43
50
  beforeText: previous && current !== null
44
- ? current === previous.installedText ? previous.beforeText : stripRecorded(current, previous, file)
51
+ ? current === previous.installedText ? previous.beforeText : setupBase(current, previous, file)
45
52
  : current,
46
53
  target: previous?.target || (current === null ? null : fs.realpathSync(file)),
47
54
  installedText: next,
@@ -82,7 +82,8 @@ export default class AiBattery extends Extension {
82
82
  const button = new PanelMenu.Button(1, "AI Battery");
83
83
  const icon = new St.Widget({ content_gravity: Clutter.ContentGravity.RESIZE_FILL, y_align: Clutter.ActorAlign.CENTER });
84
84
  button.add_child(icon);
85
- button.menu.box.set_style("background-color: #26262a; color: #f5f5f7; border-radius: 10px; padding: 6px 0;");
85
+ button.menu.actor.set_style("-arrow-border-width: 0; -arrow-border-color: transparent;");
86
+ button.menu.box.set_style("background-color: #26262a; color: #f5f5f7; border: 0; border-radius: 10px; padding: 6px 0;");
86
87
  const item = new PopupMenu.PopupBaseMenuItem({ reactive: false, can_focus: false });
87
88
  item.set_style("padding: 0;");
88
89
  const detail = new St.Widget({ content_gravity: Clutter.ContentGravity.RESIZE_FILL });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-battery",
3
- "version": "0.1.25",
3
+ "version": "0.1.27",
4
4
  "description": "Tiny terminal battery meter for local Codex and Claude Code usage.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -52,6 +52,8 @@ export async function run() {
52
52
  panel.button.menu.open();
53
53
  await Scripting.sleep(700);
54
54
  expect(panel.button.menu.isOpen && panel.detail.mapped, "The detail image must be visible inside the open menu");
55
+ expect(panel.button.menu.box.get_theme_node().get_border_width(0) === 0, "The popup must not have a bright border");
56
+ expect(panel.button.menu.actor.get_theme_node().get_length("-arrow-border-width") === 0, "The box pointer must not draw a border");
55
57
  const stream = Gio.File.new_for_path(`${root}/menu.png`).replace(null, false, Gio.FileCreateFlags.NONE, null);
56
58
  await new Shell.Screenshot().screenshot(false, stream);
57
59
  stream.close(null);