llmswap-cli 1.0.0__py3-none-any.whl

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 (78) hide show
  1. claude_swap/__init__.py +24 -0
  2. claude_swap/__main__.py +6 -0
  3. claude_swap/app_bundle.py +330 -0
  4. claude_swap/appearance.py +219 -0
  5. claude_swap/autoswitch.py +3065 -0
  6. claude_swap/cache.py +44 -0
  7. claude_swap/claude_locks.py +279 -0
  8. claude_swap/cli.py +2265 -0
  9. claude_swap/credentials.py +2156 -0
  10. claude_swap/exceptions.py +102 -0
  11. claude_swap/fsutil.py +409 -0
  12. claude_swap/json_output.py +455 -0
  13. claude_swap/launch_agent.py +862 -0
  14. claude_swap/lines.py +153 -0
  15. claude_swap/list_view.py +371 -0
  16. claude_swap/locking.py +87 -0
  17. claude_swap/logging_config.py +64 -0
  18. claude_swap/macos_keychain.py +240 -0
  19. claude_swap/mappings.py +127 -0
  20. claude_swap/menubar.py +1433 -0
  21. claude_swap/migrations.py +360 -0
  22. claude_swap/models.py +329 -0
  23. claude_swap/oauth.py +1628 -0
  24. claude_swap/pace.py +161 -0
  25. claude_swap/paths.py +250 -0
  26. claude_swap/poll_policy.py +337 -0
  27. claude_swap/printer.py +252 -0
  28. claude_swap/process_detection.py +370 -0
  29. claude_swap/session.py +2696 -0
  30. claude_swap/settings.py +827 -0
  31. claude_swap/signin.py +238 -0
  32. claude_swap/snapshot_source.py +121 -0
  33. claude_swap/spawn.py +135 -0
  34. claude_swap/subscription.py +349 -0
  35. claude_swap/switcher.py +9807 -0
  36. claude_swap/transfer.py +807 -0
  37. claude_swap/tui/__init__.py +43 -0
  38. claude_swap/tui/app.py +482 -0
  39. claude_swap/tui/autoview.py +381 -0
  40. claude_swap/tui/cswap.tcss +205 -0
  41. claude_swap/tui/dashboard.py +434 -0
  42. claude_swap/tui/data.py +194 -0
  43. claude_swap/tui/modals.py +159 -0
  44. claude_swap/tui/theme.py +88 -0
  45. claude_swap/tui/widgets.py +544 -0
  46. claude_swap/update_check.py +509 -0
  47. claude_swap/usage_bars.py +208 -0
  48. claude_swap/usage_rows.py +160 -0
  49. claude_swap/usage_store.py +1429 -0
  50. llmswap/AGENTS.md +11 -0
  51. llmswap/__init__.py +3 -0
  52. llmswap/__main__.py +4 -0
  53. llmswap/cli.py +535 -0
  54. llmswap/config.py +101 -0
  55. llmswap/httpjson.py +50 -0
  56. llmswap/jwt.py +20 -0
  57. llmswap/menubar.py +218 -0
  58. llmswap/model.py +172 -0
  59. llmswap/paths.py +41 -0
  60. llmswap/providers/AGENTS.md +12 -0
  61. llmswap/providers/base.py +619 -0
  62. llmswap/providers/claude.py +187 -0
  63. llmswap/providers/codex.py +274 -0
  64. llmswap/providers/gemini.py +80 -0
  65. llmswap/providers/registry.py +30 -0
  66. llmswap/render.py +127 -0
  67. llmswap/rotate.py +102 -0
  68. llmswap/store.py +138 -0
  69. llmswap/tui.py +182 -0
  70. llmswap/usage_cache.py +72 -0
  71. llmswap/warm/plan.py +118 -0
  72. llmswap/warm/runner.py +175 -0
  73. llmswap/warm/schedule.py +264 -0
  74. llmswap_cli-1.0.0.dist-info/METADATA +181 -0
  75. llmswap_cli-1.0.0.dist-info/RECORD +78 -0
  76. llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
  77. llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
  78. llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
claude_swap/menubar.py ADDED
@@ -0,0 +1,1433 @@
1
+ """macOS menu bar app for claude-swap (``cswap --menubar``).
2
+
3
+ A thin GUI shell over ``ClaudeAccountSwitcher`` and the core auto-switch engine
4
+ (``claude_swap.autoswitch``) — it never re-implements account, usage, or
5
+ auto-switch logic. Usage for display comes from ``switcher.accounts_snapshot()``
6
+ (backed by the shared usage store); auto-switching, when enabled, runs the same
7
+ ``AutoSwitchEngine`` the CLI's ``cswap auto`` drives, sharing
8
+ ``autoswitch_state.json`` and the ``autoswitch.*`` settings. The menu bar keeps
9
+ only its own display preferences.
10
+
11
+ Built on ``rumps`` (an optional extra, macOS only). The pure helpers below
12
+ (settings, formatting, log parsing) are import-safe without rumps so they can be
13
+ unit-tested in CI; ``rumps`` is imported lazily inside the app glue.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ import os
21
+ import platform
22
+ import plistlib
23
+ import re
24
+ import shlex
25
+ import sys
26
+ import threading
27
+ import time
28
+ from dataclasses import asdict, dataclass, fields
29
+ from datetime import datetime
30
+ from pathlib import Path
31
+ from typing import ClassVar
32
+
33
+ from claude_swap import launch_agent, oauth, pace
34
+ from claude_swap.exceptions import ClaudeSwitchError, CredentialReadError
35
+ from claude_swap.fsutil import atomic_write_text
36
+ from claude_swap.printer import warning
37
+ from claude_swap.switcher import SENTINEL_NOTES, USAGE_RELOGIN_REQUIRED, sentinel_note
38
+
39
+ ICON = "⇄"
40
+ REFRESH_CHOICES: tuple[int, ...] = (30, 60, 300)
41
+ AUTO_THRESHOLD_CHOICES: tuple[int, ...] = (80, 90, 95, 98)
42
+ TITLE_PCT_CHOICES: tuple[str, ...] = ("off", "5h", "7d", "both")
43
+ SWITCH_HISTORY_LIMIT = 10
44
+ # How long an identical engine error stays quiet after being surfaced. The
45
+ # engine retries every tick, so an unconditional notification is a storm; an
46
+ # unconditional drop is how a broken auto-switch looked healthy for two days.
47
+ ENGINE_ERROR_REPEAT_S = 3600.0
48
+ NOTIFICATION_BUNDLE_ID = "com.claude-swap.menubar"
49
+
50
+
51
+ def ensure_notification_identity(
52
+ executable: Path | None = None,
53
+ *,
54
+ platform: str = sys.platform,
55
+ ) -> Path | None:
56
+ """Ensure rumps can resolve a bundle identifier for notifications.
57
+
58
+ Fallback for runs outside the wrapper bundle (``claude_swap.app_bundle``),
59
+ whose Info.plist already carries the identifier: a bare command-line
60
+ interpreter has no app bundle, so rumps looks for an ``Info.plist`` beside
61
+ it. uv/pipx reinstalls can recreate that environment; repair the tiny
62
+ plist on every launch when needed.
63
+ """
64
+ if platform != "darwin":
65
+ return None
66
+ path = (executable or Path(sys.executable)).parent / "Info.plist"
67
+ data: dict = {}
68
+ try:
69
+ if path.exists():
70
+ try:
71
+ loaded = plistlib.loads(path.read_bytes())
72
+ except Exception:
73
+ loaded = None # unreadable/corrupt — rebuild from scratch
74
+ if isinstance(loaded, dict):
75
+ data = loaded
76
+ changed = False
77
+ if not data.get("CFBundleIdentifier"):
78
+ data["CFBundleIdentifier"] = NOTIFICATION_BUNDLE_ID
79
+ changed = True
80
+ if not data.get("CFBundleName"):
81
+ data["CFBundleName"] = "claude-swap"
82
+ changed = True
83
+ if changed or not path.exists():
84
+ # atomic: an interrupted write must not leave a half-written plist
85
+ tmp = path.with_name(path.name + ".tmp")
86
+ tmp.write_bytes(plistlib.dumps(data))
87
+ os.replace(tmp, path)
88
+ except (OSError, plistlib.InvalidFileException, ValueError) as exc:
89
+ logging.getLogger("claude-swap").warning(
90
+ "Could not prepare menu-bar notification identity: %s", exc
91
+ )
92
+ return None
93
+ return path
94
+
95
+
96
+ @dataclass
97
+ class MenuBarSettings:
98
+ """User-configurable menu bar display behavior, persisted as JSON.
99
+
100
+ Only display preferences and the auto-switch on/off toggle live here.
101
+ Auto-switch *policy* (threshold, cooldown, hysteresis, …) is core config,
102
+ read/written through ``claude_swap.settings`` (the ``autoswitch.*`` keys),
103
+ so the CLI and the menu bar share one source of truth.
104
+ """
105
+
106
+ show_account_name: bool = True
107
+ title_pct: str = "both" # one of TITLE_PCT_CHOICES
108
+ title_scoped: bool = False # append per-model weekly limits (e.g. Fable) to the title
109
+ refresh_interval: int = 60
110
+ auto_switch_enabled: bool = False
111
+
112
+ @classmethod
113
+ def load(cls, path: Path) -> "MenuBarSettings":
114
+ """Load settings, falling back to defaults on any problem.
115
+
116
+ Unknown keys are ignored; a value whose type doesn't match the field
117
+ default is dropped (that field keeps its default). A missing or
118
+ unparseable file yields all-defaults.
119
+ """
120
+ defaults = cls()
121
+ try:
122
+ raw = json.loads(path.read_text(encoding="utf-8"))
123
+ except (OSError, ValueError):
124
+ return defaults
125
+ if not isinstance(raw, dict):
126
+ return defaults
127
+ kwargs = {}
128
+ for f in fields(cls):
129
+ if f.name in raw and isinstance(raw[f.name], type(getattr(defaults, f.name))):
130
+ kwargs[f.name] = raw[f.name]
131
+ return cls(**kwargs)
132
+
133
+ def save(self, path: Path) -> None:
134
+ """Write settings as pretty JSON, creating parent directories.
135
+
136
+ Atomic, because the CLI and the running menu bar both write this file
137
+ and :meth:`load` reads a torn write as all-defaults, which would turn
138
+ auto-switch off without anyone touching the menu.
139
+ """
140
+ path.parent.mkdir(parents=True, exist_ok=True)
141
+ atomic_write_text(path, json.dumps(asdict(self), indent=2), mode=0o600)
142
+
143
+
144
+ # ---- pure display helpers (operate on the usage-window dict shape produced by
145
+ # ---- oauth.build_usage_result / stored in UsageEntry.last_good) --------------
146
+
147
+ def tightest_pct(usage: dict | str | None) -> float | None:
148
+ """Highest 5h/7d utilization percentage, or None if unknown.
149
+
150
+ Surfaces the binding window's utilization for display. Spend is excluded —
151
+ it isn't a rate-limit window.
152
+ """
153
+ if not isinstance(usage, dict):
154
+ return None
155
+ pcts = [
156
+ window["pct"]
157
+ for window in (usage.get("five_hour"), usage.get("seven_day"))
158
+ if isinstance(window, dict) and isinstance(window.get("pct"), (int, float))
159
+ ]
160
+ return max(pcts) if pcts else None
161
+
162
+
163
+ def _window_pct(usage: dict | str | None, key: str) -> float | None:
164
+ """Utilization pct for a usage window (``five_hour``/``seven_day``), or None."""
165
+ if isinstance(usage, dict):
166
+ window = usage.get(key)
167
+ if isinstance(window, dict) and isinstance(window.get("pct"), (int, float)):
168
+ return float(window["pct"])
169
+ return None
170
+
171
+
172
+ def _resets_at_ts(window: dict | str | None) -> float:
173
+ """POSIX timestamp of a usage window's ``resets_at``; inf if missing/bad."""
174
+ if isinstance(window, dict):
175
+ ra = window.get("resets_at")
176
+ if isinstance(ra, str):
177
+ try:
178
+ return datetime.fromisoformat(ra).timestamp()
179
+ except ValueError:
180
+ pass
181
+ return float("inf")
182
+
183
+
184
+ def _live_countdown(window: dict | str | None, now: float) -> str | None:
185
+ """Time until a usage window resets, computed live from ``resets_at``.
186
+
187
+ The cached usage dict's ``countdown`` string is frozen at fetch time, so a
188
+ stale (e.g. last-known-good) entry would show a wrong remaining time. Deriving
189
+ it from the absolute ``resets_at`` keeps it correct between/without refetches.
190
+ Returns ``None`` when there's no ``resets_at`` or it has already passed.
191
+ """
192
+ ts = _resets_at_ts(window)
193
+ if ts == float("inf"):
194
+ return None
195
+ remaining = int(ts - now)
196
+ if remaining <= 0:
197
+ return None
198
+ days, rem = divmod(remaining, 86400)
199
+ hours, rem = divmod(rem, 3600)
200
+ minutes = rem // 60
201
+ if days > 0:
202
+ return f"{days}d {hours}h"
203
+ if hours > 0:
204
+ return f"{hours}h {minutes}m"
205
+ return f"{minutes}m"
206
+
207
+
208
+ def _title_figure(window: dict | None, now: float) -> str | None:
209
+ """A window's figure for the title: ``"47%"``, or ``"?"`` once its
210
+ recorded reset has passed (``oauth.window_reset_passed``: the stored
211
+ figure describes the window that ended). The placeholder keeps the other
212
+ figures in place, since the title tells 5h from 7d by position alone.
213
+ None for a window the account lacks or one reported without a figure.
214
+ """
215
+ if oauth.window_reset_passed(window, now):
216
+ return "?"
217
+ if isinstance(window, dict) and isinstance(window.get("pct"), (int, float)):
218
+ return f"{window['pct']:.0f}%"
219
+ return None
220
+
221
+
222
+ MENU_NOTE_LIMIT = 40
223
+
224
+ # A reading older than this many display intervals is called stale in the
225
+ # health row, but never sooner than STALE_USAGE_FLOOR_S: while the engine
226
+ # runs, the display reads store-only and the engine polls the active account
227
+ # on its own cadence, so three short display intervals would be too strict.
228
+ STALE_REFRESH_INTERVALS = 3
229
+ STALE_USAGE_FLOOR_S = 15 * 60
230
+
231
+
232
+ @dataclass(frozen=True)
233
+ class EngineStoppedEvent:
234
+ """Queued by the menu bar's engine thread when its ``run_loop`` ends.
235
+
236
+ Carries the engine object, not just a flag: a restart starts the
237
+ replacement before the old thread has finished, so the old thread's exit
238
+ must be matched against the engine the app hosts *now* before anything is
239
+ cleared (see :func:`engine_exit_applies`). ``error`` is the exception that
240
+ ended the loop, or None when it returned on its own.
241
+ """
242
+
243
+ kind: ClassVar[str] = "engine-stopped"
244
+ engine: object
245
+ error: str | None = None
246
+
247
+ def human(self) -> str:
248
+ return self.error or "the engine loop ended on its own"
249
+
250
+
251
+ def engine_exit_applies(current, stopped) -> bool:
252
+ """Whether a stopped engine is the one the menu bar currently hosts.
253
+
254
+ False for a predecessor that finished after a restart, and for an engine
255
+ the app already let go of through its own stop.
256
+ """
257
+ return current is not None and current is stopped
258
+
259
+
260
+ def _age_text(seconds: float) -> str:
261
+ seconds = max(0, int(seconds))
262
+ if seconds < 60:
263
+ return "just now"
264
+ minutes, hours, days = seconds // 60, seconds // 3600, seconds // 86400
265
+ if hours < 1:
266
+ return f"{minutes}m ago"
267
+ if days < 1:
268
+ return f"{hours}h {minutes % 60}m ago"
269
+ return f"{days}d {hours % 24}h ago"
270
+
271
+
272
+ def active_usage_age(snapshot: dict, now: float | None = None) -> float | None:
273
+ """Seconds since the active account's usage was last read, or None.
274
+
275
+ The health row dates the measurement, not the display's last look at the
276
+ store: a store-only refresh (the engine paces all fetching while it runs)
277
+ would otherwise call a two-hour-old reading "just now".
278
+ """
279
+ now = time.time() if now is None else now
280
+ for row in snapshot.get("accounts") or []:
281
+ if row[2]: # is_active
282
+ fetched_at = row[7]
283
+ return max(0.0, now - fetched_at) if fetched_at else None
284
+ return None
285
+
286
+
287
+ def health_label(
288
+ *,
289
+ auto_enabled: bool,
290
+ engine_running: bool,
291
+ usage_age: float | None,
292
+ refresh_interval: int,
293
+ ) -> tuple[str, bool]:
294
+ """The menu's first row: ``(label, attention)``.
295
+
296
+ Four states hide behind "the icon is there": auto-switch off in settings,
297
+ enabled with the engine running, enabled with no engine (it failed to
298
+ start or its thread died), and usage that stopped being read. The row
299
+ names the first three and dates the fourth from the active account's last
300
+ reading (:func:`active_usage_age`); ``attention`` is True for the state
301
+ that needs a click, so the caller can wire a restart to the row and flag
302
+ the title.
303
+ """
304
+ if not auto_enabled:
305
+ status, attention = "Auto-switch off", False
306
+ elif engine_running:
307
+ status, attention = "Auto-switch running", False
308
+ else:
309
+ status, attention = "⚠ Auto-switch stopped, click to restart", True
310
+ stale_after = max(STALE_REFRESH_INTERVALS * refresh_interval, STALE_USAGE_FLOOR_S)
311
+ if usage_age is None:
312
+ usage = "no usage reading yet"
313
+ elif usage_age > stale_after:
314
+ usage = f"usage stale, read {_age_text(usage_age)}"
315
+ else:
316
+ usage = f"usage read {_age_text(usage_age)}"
317
+ return f"{status} · {usage}", attention
318
+
319
+
320
+ def menu_note(note: str, limit: int = MENU_NOTE_LIMIT) -> str:
321
+ """The state half of a sentinel note, sized for a menu row.
322
+
323
+ ``SENTINEL_NOTES`` carry a remedy after an em dash ("re-login needed —
324
+ refresh token dead; run: cswap login"), which
325
+ ``cswap list`` has the width for. A menu is as wide as its widest row, so
326
+ one expired account otherwise doubles the menu and pushes every other
327
+ row's numbers to the far edge. The row keeps the state; the full note
328
+ travels as the row's tooltip (see ``rebuild_menu``).
329
+ """
330
+ state = note.split(" — ", 1)[0].strip()
331
+ if len(state) > limit:
332
+ state = state[: limit - 1].rstrip() + "…"
333
+ return state
334
+
335
+
336
+ def _set_tooltip(item, text: str) -> None:
337
+ """Attach ``text`` as the row's hover tooltip; NSMenuItem carries one natively."""
338
+ ns_item = getattr(item, "_menuitem", None)
339
+ if ns_item is not None and hasattr(ns_item, "setToolTip_"):
340
+ ns_item.setToolTip_(text)
341
+
342
+
343
+ def usage_summary(
344
+ usage: dict | str | None, now: float | None = None, fetched_at: float | None = None
345
+ ) -> str:
346
+ """One-line usage summary for an account row (reset countdown computed live).
347
+
348
+ ``fetched_at`` is the underlying measurement's fetch time (may be older
349
+ than ``now`` when serving last-good data) — used only to flag a weekly
350
+ window that's meaningfully ahead of pace (issue #125), never the 5h one.
351
+ """
352
+ if isinstance(usage, str):
353
+ return menu_note(usage)
354
+ if usage is None:
355
+ return "usage unavailable"
356
+ if now is None:
357
+ now = time.time()
358
+ parts: list[str] = []
359
+ rejected = usage.get("rejected")
360
+ if isinstance(rejected, dict):
361
+ # A refused setup-token probe leads the row: the account is at its
362
+ # limit until the refusal ends, however low the windows below read.
363
+ seg = "rejected (!)"
364
+ countdown = _live_countdown(rejected, now)
365
+ if countdown:
366
+ seg += f" ({countdown})"
367
+ parts.append(seg)
368
+ for key, label in (("five_hour", "5h"), ("seven_day", "7d")):
369
+ window = usage.get(key)
370
+ if oauth.window_reset_passed(window, now):
371
+ # The stored figure describes the window that ended: no figure,
372
+ # and nothing to measure against pace.
373
+ parts.append(f"{label} ?")
374
+ continue
375
+ pace_result = None
376
+ if key == "seven_day":
377
+ pace_result = pace.compute_pace(window, fetched_at=fetched_at)
378
+ if isinstance(window, dict) and isinstance(window.get("pct"), (int, float)):
379
+ seg = f"{label} {window['pct']:.0f}%"
380
+ if key == "seven_day" and pace_result and pace_result.ahead:
381
+ seg += " (ahead)"
382
+ countdown = _live_countdown(window, now)
383
+ if countdown:
384
+ seg += f" ({countdown})" # time until this window resets
385
+ parts.append(seg)
386
+ # Per-model weekly limits (e.g. Fable), from the usage API's ``limits`` array.
387
+ for window in usage.get("scoped") or []:
388
+ if oauth.window_reset_passed(window, now):
389
+ if window.get("name"):
390
+ parts.append(f"{window['name']} ?") # as the 5h/7d rows above
391
+ continue
392
+ pace_result = pace.compute_pace(window, fetched_at=fetched_at)
393
+ if isinstance(window, dict) and isinstance(window.get("pct"), (int, float)) and window.get("name"):
394
+ seg = f"{window['name']} {window['pct']:.0f}%"
395
+ if window["pct"] >= 100:
396
+ seg += " (!)" # maxed model — the usual reason to switch
397
+ elif pace_result and pace_result.ahead:
398
+ seg += " (ahead)"
399
+ countdown = _live_countdown(window, now)
400
+ if countdown:
401
+ seg += f" ({countdown})"
402
+ parts.append(seg)
403
+ spend = usage.get("spend")
404
+ if isinstance(spend, dict) and isinstance(spend.get("pct"), (int, float)):
405
+ parts.append(f"$ {spend['pct']:.0f}%")
406
+ return " · ".join(parts) if parts else "usage unavailable"
407
+
408
+
409
+ def format_account_label(
410
+ num,
411
+ email: str,
412
+ usage: dict | str | None,
413
+ now: float | None = None,
414
+ alias: str | None = None,
415
+ disabled: bool = False,
416
+ fetched_at: float | None = None,
417
+ login_expires_at: float | None = None,
418
+ quarantined: bool = False,
419
+ ) -> str:
420
+ """Build one account row's menu label.
421
+
422
+ Ends with ``· re-login in 5d 12h`` while the slot's stored login is due
423
+ (:func:`oauth.format_login_expiry`, the same judgement the CLI/TUI views
424
+ use), last so its position is what stays constant in a proportional-font
425
+ NSMenu row.
426
+ """
427
+ label = f"{alias} ({email})" if alias else email
428
+ marker = " (disabled)" if disabled else ""
429
+ row = f"{num} {label}{marker} {usage_summary(usage, now, fetched_at)}"
430
+ note = oauth.format_login_expiry(login_expires_at, quarantined, now)
431
+ return f"{row} · {note}" if note else row
432
+
433
+
434
+ def _local_part(email: str, limit: int = 12) -> str:
435
+ """Email text before '@', truncated with a trailing '*' marker."""
436
+ local = email.split("@", 1)[0]
437
+ if len(local) > limit:
438
+ return local[: limit - 1] + "*"
439
+ return local
440
+
441
+
442
+ def format_title(
443
+ active_email: str | None,
444
+ active_usage: dict | str | None,
445
+ settings: MenuBarSettings,
446
+ now: float | None = None,
447
+ alias: str | None = None,
448
+ *,
449
+ attention: bool = False,
450
+ ) -> str:
451
+ """Build the menu-bar title from the active account and settings.
452
+
453
+ ``attention`` prefixes a warning sign: auto-switch is enabled but not
454
+ running, which the closed menu would otherwise never show.
455
+ """
456
+ icon = f"⚠ {ICON}" if attention else ICON
457
+ if active_email is None:
458
+ return icon
459
+ if now is None:
460
+ now = time.time()
461
+ segments: list[str] = []
462
+ if settings.show_account_name:
463
+ segments.append(alias if alias else _local_part(active_email))
464
+ if isinstance(active_usage, dict) and isinstance(active_usage.get("rejected"), dict):
465
+ segments.append("rejected (!)")
466
+ windows = active_usage if isinstance(active_usage, dict) else {}
467
+ for key, shown_in in (("five_hour", ("5h", "both")), ("seven_day", ("7d", "both"))):
468
+ if settings.title_pct in shown_in:
469
+ figure = _title_figure(windows.get(key), now)
470
+ if figure is not None:
471
+ segments.append(figure)
472
+ if settings.title_scoped:
473
+ # Per-model weekly limits (e.g. Fable), same shape as the dropdown
474
+ # rows; named so multiple scoped models stay distinguishable.
475
+ for window in windows.get("scoped") or []:
476
+ figure = _title_figure(window, now)
477
+ if figure is not None and window.get("name"):
478
+ segments.append(f"{window['name']} {figure}")
479
+ if not segments:
480
+ return icon
481
+ return f"{icon} " + " · ".join(segments)
482
+
483
+
484
+ def format_usage_log(email: str, usage: dict | str | None) -> str | None:
485
+ """A log line of an account's session (5h) and weekly (7d) limits.
486
+
487
+ Uses each window's absolute reset ``clock`` rather than a live countdown,
488
+ since log lines are already timestamped. Returns ``None`` when no numeric
489
+ window is available (sentinels, ``None``, or spend-only) so callers can skip
490
+ logging nothing.
491
+ """
492
+ parts: list[str] = []
493
+ for key, label in (("five_hour", "5h"), ("seven_day", "7d")):
494
+ pct = _window_pct(usage, key)
495
+ if pct is None:
496
+ continue
497
+ window = usage.get(key) # a dict — _window_pct found a numeric pct in it
498
+ clock = window.get("clock") if isinstance(window, dict) else None
499
+ seg = f"{label} {pct:.0f}%"
500
+ if clock:
501
+ seg += f" (resets {clock})"
502
+ parts.append(seg)
503
+ if not parts:
504
+ return None
505
+ return f"usage {email}: " + " · ".join(parts)
506
+
507
+
508
+ def _usage_log_key(usage: dict | str | None) -> tuple[float | None, float | None]:
509
+ """De-dupe key for usage logging: the (5h, 7d) percentages only.
510
+
511
+ Reset clocks change every refresh; keying on the percentages means an idle
512
+ account isn't re-logged every cycle.
513
+ """
514
+ return (_window_pct(usage, "five_hour"), _window_pct(usage, "seven_day"))
515
+
516
+
517
+ _SWITCH_LOG_RE = re.compile(r"Switched from account (\d+) to (\d+)")
518
+
519
+
520
+ def should_surface_engine_error(event, surfaced: dict, now: float) -> bool:
521
+ """Whether a hosted engine's error event should reach the log and the user.
522
+
523
+ ``surfaced`` maps each message to when it was last surfaced (monotonic
524
+ seconds) and is updated when this returns True. A message not seen within
525
+ ``ENGINE_ERROR_REPEAT_S`` is surfaced; otherwise it stays quiet — per
526
+ message, so two errors alternating tick by tick can't defeat the limit.
527
+ """
528
+ message = getattr(event, "message", None)
529
+ if not message:
530
+ return False
531
+ # Digits stripped so a message carrying a changing id, count or time is
532
+ # still one error, and stale entries pruned so the table stays bounded.
533
+ key = re.sub(r"\d+", "#", message)
534
+ for k in [k for k, t in surfaced.items() if now - t >= ENGINE_ERROR_REPEAT_S]:
535
+ del surfaced[k]
536
+ if key in surfaced:
537
+ return False
538
+ surfaced[key] = now
539
+ return True
540
+
541
+
542
+ def parse_switch_history(log_text: str, limit: int = SWITCH_HISTORY_LIMIT) -> list[str]:
543
+ """Recent account switches from the log, most-recent first.
544
+
545
+ Reads the ``Switched from account X to Y`` lines the switcher logs and pairs
546
+ each with its timestamp (trimmed to the minute). Returns at most ``limit``
547
+ entries like ``"3 → 1 2026-06-27 02:06"``. Any unparseable line is skipped.
548
+ """
549
+ out: list[str] = []
550
+ for line in log_text.splitlines():
551
+ m = _SWITCH_LOG_RE.search(line)
552
+ if not m:
553
+ continue
554
+ stamp = line.split(" - ", 1)[0].strip()[:16] # "YYYY-MM-DD HH:MM"
555
+ out.append(f"{m.group(1)} → {m.group(2)} {stamp}")
556
+ return out[-limit:][::-1]
557
+
558
+
559
+ LOGIN_COMMAND_NAME = "login.command"
560
+
561
+
562
+ def write_login_command(backup_dir: Path, program: list[str]) -> Path:
563
+ """Write the script that runs ``cswap login`` in a terminal window.
564
+
565
+ Claude Code's sign-in is a terminal prompt and the menu bar has no
566
+ terminal. macOS opens a ``.command`` file in the user's terminal app, so
567
+ the menu item hands the sign-in over through one. The file holds the
568
+ command line and nothing else.
569
+ """
570
+ path = backup_dir / LOGIN_COMMAND_NAME
571
+ atomic_write_text(path, f"#!/bin/sh\nexec {shlex.join([*program, 'login'])}\n")
572
+ path.chmod(0o700)
573
+ return path
574
+
575
+
576
+ def _account_display_usage(entry, account_num: str | int | None = None) -> dict | str | None:
577
+ """Menu-display usage for a ``UsageEntry``.
578
+
579
+ A human-readable note for a sentinel state (token expired / API key /
580
+ keychain unavailable), otherwise the last-good measurement dict, otherwise
581
+ ``None``.
582
+ """
583
+ if entry.sentinel:
584
+ return sentinel_note(entry.sentinel, account_num)
585
+ return entry.last_good
586
+
587
+
588
+ EMPTY_SNAPSHOT: dict = {
589
+ "accounts": [],
590
+ "active_email": None,
591
+ "active_usage": None,
592
+ "active_alias": None,
593
+ }
594
+
595
+
596
+ def _adapt_snapshot(snap) -> dict:
597
+ """Adapt an ``AccountsSnapshot`` to the menu bar's render dict.
598
+
599
+ Shape: ``{"accounts": [(num, email, is_active, display_usage, last_good, alias, disabled, fetched_at, login_expires_at, quarantined), ...],
600
+ "active_email": str | None, "active_usage": dict | str | None,
601
+ "active_alias": str | None}``. The snapshot itself is produced by
602
+ ``SnapshotSource`` (the paced read path), so this is a pure transform — no
603
+ fetching, no I/O. Per-account ``fetched_at`` is the underlying
604
+ measurement's fetch time, used only for the pace marker (issue #125).
605
+ ``login_expires_at``/``quarantined`` are the same fields the TUI's re-login
606
+ note reads (``AccountSnapshot.login_expires_at``, sentinel ==
607
+ ``USAGE_RELOGIN_REQUIRED``) — no extra credential read.
608
+ """
609
+ accounts = []
610
+ active_email = None
611
+ active_usage = None
612
+ active_alias = None
613
+ for acc in snap.accounts:
614
+ display = _account_display_usage(acc.usage, acc.number)
615
+ accounts.append(
616
+ (
617
+ acc.number, acc.email, acc.is_active, display, acc.usage.last_good,
618
+ acc.alias, acc.disabled, acc.usage.fetched_at,
619
+ acc.login_expires_at, acc.usage.sentinel == USAGE_RELOGIN_REQUIRED,
620
+ )
621
+ )
622
+ if acc.is_active:
623
+ active_email, active_usage, active_alias = acc.email, display, acc.alias
624
+ return {
625
+ "accounts": accounts,
626
+ "active_email": active_email,
627
+ "active_usage": active_usage,
628
+ "active_alias": active_alias,
629
+ }
630
+
631
+
632
+ def _take_worker_snapshot(
633
+ snapshot_source, *, full: bool, has_engine: bool
634
+ ) -> tuple[dict, bool]:
635
+ """Take and adapt one display snapshot; returns ``(snap, store_only)``.
636
+
637
+ Routine ticks read store-only while the hosted auto-switch engine is
638
+ running; an explicit Refresh now (``full=True``) still runs a store-governed
639
+ on-demand pass.
640
+ """
641
+ store_only = has_engine and not full
642
+ raw = snapshot_source.take(full=full, store_only=store_only)
643
+ return _adapt_snapshot(raw), store_only
644
+
645
+
646
+ # macOS 26 stopped drawing status items for processes launched through an
647
+ # exec trampoline, and a CPython *framework* build is exactly that: its
648
+ # ``bin/python3.x`` is a stub that posix_spawns into ``Python.app``
649
+ # (Mac/Tools/pythonw.c). Homebrew and python.org ship framework builds;
650
+ # uv-managed and most other interpreters do not.
651
+ #
652
+ # Measured on macOS 26.6.2 with rumps 0.4.0, same bare rumps app throughout:
653
+ #
654
+ # Homebrew 3.14.6 sys._framework 'Python' no status item
655
+ # Homebrew 3.10.21 sys._framework 'Python' no status item
656
+ # uv 3.14.7 sys._framework '' status item drawn
657
+ # uv 3.13.15 sys._framework '' status item drawn
658
+ #
659
+ # The interpreter version is not the variable; the build is.
660
+
661
+
662
+ MIN_AFFECTED_MACOS = 26
663
+
664
+
665
+ def _macos_major(mac_ver: str | None = None) -> int | None:
666
+ """Major version of the running macOS, or None if it cannot be read."""
667
+ raw = platform.mac_ver()[0] if mac_ver is None else mac_ver
668
+ head = raw.split(".")[0]
669
+ return int(head) if head.isdigit() else None
670
+
671
+
672
+ def framework_build_warning(
673
+ framework=None, install_method=None, mac_ver: str | None = None
674
+ ) -> str | None:
675
+ """Text to show when this interpreter cannot draw a status item.
676
+
677
+ Returns None wherever the menu bar is known to work. Both halves of the
678
+ condition matter: the evidence is a framework build *on macOS 26*, and
679
+ framework builds draw fine on earlier releases — gating on the build alone
680
+ would nag every Homebrew user on macOS 14 or 15, on every launch and in
681
+ the service log on every restart.
682
+
683
+ Nothing here can fix the incompatibility. The point is that it fails
684
+ silently, with a healthy process and empty logs, so it is worth one line.
685
+ """
686
+ fw = getattr(sys, "_framework", "") if framework is None else framework
687
+ if not fw:
688
+ return None
689
+
690
+ major = _macos_major(mac_ver)
691
+ if major is None or major < MIN_AFFECTED_MACOS:
692
+ return None
693
+
694
+ if install_method is None:
695
+ from claude_swap.update_check import _detect_install_method
696
+
697
+ install_method = _detect_install_method()
698
+
699
+ if install_method == "uv":
700
+ remedy = (
701
+ " uv tool install --managed-python --force 'claude-swap[menubar]'"
702
+ )
703
+ elif install_method == "pipx":
704
+ remedy = (
705
+ " Reinstall against a non-framework interpreter, e.g. one from "
706
+ "`uv python install 3.13`:\n"
707
+ " pipx install --force --python <that python> 'claude-swap[menubar]'"
708
+ )
709
+ else:
710
+ remedy = (
711
+ " Reinstall against a non-framework interpreter "
712
+ "(uv-managed ones are; Homebrew and python.org are not)."
713
+ )
714
+
715
+ return (
716
+ "This is a framework build of Python, which on macOS 26 has been "
717
+ "observed not to draw the menu bar icon: the process runs and logs "
718
+ "nothing, but no status item appears.\n" + remedy
719
+ )
720
+
721
+
722
+ def run(switcher) -> int:
723
+ """Entry point for ``cswap --menubar``. Blocks until the user quits."""
724
+ try:
725
+ import rumps # lazy: optional dependency, imported only when launching
726
+ import AppKit # ships with rumps (pyobjc-framework-Cocoa), never fails alone
727
+ except ImportError as e:
728
+ # This module is import-safe without rumps by design, so the CLI's
729
+ # guard around ``from claude_swap.menubar import run`` can never see a
730
+ # missing extra — the failure lands here at call time. Raise the
731
+ # error type the CLI already renders cleanly instead of a traceback.
732
+ raise ClaudeSwitchError(
733
+ "Menu bar mode requires 'rumps'. "
734
+ "Install with: pip install 'claude-swap[menubar]'"
735
+ ) from e
736
+
737
+ from claude_swap import app_bundle
738
+
739
+ # Hop into the wrapper .app before anything AppKit-side is set up, so the
740
+ # status item's owner has a bundle identifier that menu bar managers can
741
+ # key on. Returns only when staying in this interpreter (already bundled,
742
+ # opted out, framework build, or the bundle could not be built).
743
+ app_bundle.maybe_reexec(switcher.backup_dir)
744
+ if not app_bundle.in_bundle():
745
+ ensure_notification_identity()
746
+ try:
747
+ # Pid and build of this worker, so a later `cswap menubar` or
748
+ # `cswap upgrade` can tell an instance of an old build from the
749
+ # installed one. Never worth failing the start over.
750
+ launch_agent.write_worker_stamp(switcher.backup_dir)
751
+ except OSError:
752
+ switcher._logger.debug("could not write the menu bar worker stamp", exc_info=True)
753
+ _warn = framework_build_warning()
754
+ if _warn:
755
+ # stderr, not stdout: launchd sends stdout to the .log file where it
756
+ # would sit in a block buffer for the life of the process, and the
757
+ # install output points the user at the .err file anyway. stderr stays
758
+ # line-buffered even when redirected, so it lands immediately.
759
+ warning(_warn, file=sys.stderr)
760
+
761
+ # rumps never sets an activation policy, so under a framework Python the
762
+ # process launches as a regular app and parks a "Python" icon in the Dock
763
+ # for as long as the menu bar runs. Accessory keeps the status item and
764
+ # dialog windows but stays out of the Dock and the Cmd-Tab switcher.
765
+ AppKit.NSApplication.sharedApplication().setActivationPolicy_(
766
+ AppKit.NSApplicationActivationPolicyAccessory
767
+ )
768
+
769
+ from claude_swap.autoswitch import AutoSwitchEngine
770
+ from claude_swap.settings import load_settings, set_setting
771
+ from claude_swap.snapshot_source import SnapshotSource
772
+
773
+ settings_path = switcher.backup_dir / "menubar_settings.json"
774
+ log_path = switcher.backup_dir / "claude-swap.log"
775
+
776
+ class MenuBarApp(rumps.App):
777
+ def __init__(self):
778
+ super().__init__(ICON, quit_button=None)
779
+ self.switcher = switcher
780
+ self.settings = MenuBarSettings.load(settings_path)
781
+ # The supported paced read path: per refresh it fetches only the
782
+ # active account plus (at most once per freshness window) one stale
783
+ # alternate, so an open menu costs O(1) requests per window instead
784
+ # of a full pass per tick — which kept every token at its per-account
785
+ # rate-limit edge. Reused across refreshes to hold its pacing state.
786
+ self._snapshot_source = SnapshotSource(switcher)
787
+ self.snapshot = dict(EMPTY_SNAPSHOT)
788
+ self._dirty = False
789
+ self._snapshot_at = 0.0
790
+ self._refreshing = False
791
+ self._config_path = switcher._get_claude_config_path()
792
+ self._config_mtime = 0.0
793
+ self._config_email: str | None = None # the account the config last named
794
+ self._last_usage_log: dict = {} # account num -> last-logged (5h, 7d) key
795
+ # Auto-switch engine (the same one `cswap auto` runs), hosted in a
796
+ # background thread while enabled.
797
+ self._engine = None
798
+ # Why the engine is not running although auto-switch is enabled:
799
+ # a failed start or a thread that died. Shown in the health row.
800
+ self._engine_failure: str | None = None
801
+ self._engine_events: list = []
802
+ self._event_lock = threading.Lock()
803
+ self._engine_errors_surfaced: dict[str, float] = {}
804
+ self._health_item = None
805
+ self._health_attention = False
806
+ self.rebuild_menu()
807
+ # Background display refresh on the user's interval, plus a fast
808
+ # UI-sync tick that applies snapshots + engine events on the main thread.
809
+ self.refresh_timer = rumps.Timer(self.on_refresh_tick, self.settings.refresh_interval)
810
+ self.refresh_timer.start()
811
+ self.sync_timer = rumps.Timer(self.on_sync_tick, 1)
812
+ self.sync_timer.start()
813
+ self.refresh_async() # first display fetch
814
+ if self.settings.auto_switch_enabled:
815
+ self._start_engine()
816
+
817
+ # ---- display refresh plumbing ----------------------------------------
818
+ def refresh_async(self, full=False):
819
+ if self._refreshing:
820
+ return # in-flight guard: one worker at a time (SnapshotSource
821
+ # pacing state is only touched by this single worker)
822
+ self._refreshing = True
823
+ threading.Thread(target=self._worker, args=(full,), daemon=True).start()
824
+
825
+ def _worker(self, full):
826
+ # Lock-free handoff: worker only rebinds plain attributes (atomic in
827
+ # CPython); the main-thread sync tick reads them. While the engine
828
+ # runs it already paces all fetching, so routine display ticks read
829
+ # store-only; an explicit Refresh now (full=True) still runs a
830
+ # store-governed pass.
831
+ try:
832
+ try:
833
+ snap, store_only = _take_worker_snapshot(
834
+ self._snapshot_source,
835
+ full=full,
836
+ has_engine=self._engine is not None,
837
+ )
838
+ except Exception:
839
+ # Keep the last good snapshot rather than blanking the menu.
840
+ self.switcher._logger.debug("menubar snapshot failed", exc_info=True)
841
+ return
842
+ self._log_usage(snap)
843
+ self.snapshot = snap
844
+ self._snapshot_at = time.time()
845
+ self._dirty = True # picked up by on_sync_tick on the main thread
846
+ if store_only:
847
+ self._snapshot_source.refresh_plans()
848
+ finally:
849
+ self._refreshing = False
850
+
851
+ def _log_usage(self, snap):
852
+ """Log each account's session/weekly limits when they change.
853
+
854
+ Runs on every refresh (background thread; the logger is thread-safe)
855
+ but de-dupes per account on the (5h, 7d) percentages so an idle
856
+ machine doesn't churn the rotating log with identical lines.
857
+ """
858
+ for (
859
+ num, email, _is_active, _display, last_good, _alias, _disabled, _fetched_at,
860
+ _login_expires_at, _quarantined,
861
+ ) in snap["accounts"]:
862
+ key = _usage_log_key(last_good)
863
+ if key == (None, None) or self._last_usage_log.get(num) == key:
864
+ continue
865
+ line = format_usage_log(email, last_good)
866
+ if line:
867
+ self.switcher._logger.info(line)
868
+ self._last_usage_log[num] = key
869
+
870
+ def on_refresh_tick(self, _timer):
871
+ self.refresh_async()
872
+
873
+ def on_sync_tick(self, _timer):
874
+ if self._dirty:
875
+ self._dirty = False
876
+ self.rebuild_menu()
877
+ self._detect_active_change()
878
+ self._drain_engine_events()
879
+ self._refresh_health_row()
880
+
881
+ def _health(self):
882
+ return health_label(
883
+ auto_enabled=self.settings.auto_switch_enabled,
884
+ engine_running=self._engine is not None,
885
+ usage_age=active_usage_age(self.snapshot),
886
+ refresh_interval=self.settings.refresh_interval,
887
+ )
888
+
889
+ def _refresh_health_row(self):
890
+ """Keep the first row current between rebuilds.
891
+
892
+ Rebuilds follow successful refreshes; a refresh that keeps failing
893
+ never triggers one, so the row would say "read 2m ago" for hours,
894
+ which is the very state it exists to show. Text changes go in
895
+ place; a change of state (attention on or off) rebuilds, since the
896
+ row's action and the title change with it.
897
+ """
898
+ if self._health_item is None:
899
+ return
900
+ label, attention = self._health()
901
+ if attention != self._health_attention:
902
+ self.rebuild_menu()
903
+ elif label != self._health_item.title:
904
+ self._health_item.title = label
905
+
906
+ def _detect_active_change(self):
907
+ # Reflect account switches from any source (menu, CLI, auto engine)
908
+ # within ~1s. A switch rewrites the account ~/.claude.json names,
909
+ # and reading that is cheap -- no Keychain or usage API -- so we can
910
+ # do it on every tick. We gate the read on the file's mtime (a cheap
911
+ # stat) so a large config isn't parsed each second, and only kick a
912
+ # refresh when the named email actually changed (Claude Code rewrites
913
+ # this file often for unrelated reasons). The refresh then reads
914
+ # which account is active from the login. The name is compared
915
+ # with the last name seen, not with the active account: the two
916
+ # can differ for as long as another host's relabel stands, and
917
+ # every rewrite of the file would start a refresh.
918
+ if self._refreshing:
919
+ return # a worker is already in-flight; it refreshes the marker
920
+ try:
921
+ mtime = self._config_path.stat().st_mtime
922
+ except OSError:
923
+ return
924
+ if mtime == self._config_mtime:
925
+ return
926
+ self._config_mtime = mtime
927
+ current = self.switcher._get_current_account()
928
+ email = current[0] if current else None
929
+ if email and email != self._config_email:
930
+ self._config_email = email
931
+ self.refresh_async()
932
+
933
+ # ---- auto-switch engine ----------------------------------------------
934
+ def _start_engine(self):
935
+ """Run the core AutoSwitchEngine (live) in a background thread."""
936
+ if self._engine is not None:
937
+ return
938
+ try:
939
+ engine = AutoSwitchEngine(
940
+ self.switcher,
941
+ load_settings(self.switcher.backup_dir),
942
+ self._on_engine_event,
943
+ dry_run=False,
944
+ )
945
+ except Exception as e: # never let a bad start crash the menu bar
946
+ self.switcher._logger.warning("auto-switch engine failed to start: %s", e)
947
+ rumps.notification("claude-swap", "Auto-switch failed to start", str(e))
948
+ self._engine_failure = str(e)
949
+ self._dirty = True # the health row picks it up on the next tick
950
+ return
951
+ self._engine = engine
952
+ self._engine_failure = None
953
+ threading.Thread(target=self._run_engine, args=(engine,), daemon=True).start()
954
+
955
+ def _run_engine(self, engine):
956
+ # Engine thread. Whatever ends the loop, tell the main thread which
957
+ # engine ended; it decides whether that is still the hosted one.
958
+ error = None
959
+ try:
960
+ engine.run_loop()
961
+ except Exception as e:
962
+ error = f"{type(e).__name__}: {e}"
963
+ self.switcher._logger.debug("auto-switch engine crashed", exc_info=True)
964
+ finally:
965
+ self._on_engine_event(EngineStoppedEvent(engine, error))
966
+
967
+ def _stop_engine(self):
968
+ if self._engine is not None:
969
+ self._engine.stop()
970
+ self._engine = None
971
+ self._engine_failure = None
972
+
973
+ def _restart_engine(self):
974
+ """Apply changed core settings by restarting the running engine."""
975
+ if self._engine is not None:
976
+ self._stop_engine()
977
+ self._start_engine()
978
+
979
+ def _on_engine_event(self, event):
980
+ # Runs on the engine thread; must not raise. Queue for the main
981
+ # thread, which surfaces notifications and reacts on the sync tick.
982
+ with self._event_lock:
983
+ self._engine_events.append(event)
984
+
985
+ def _drain_engine_events(self):
986
+ with self._event_lock:
987
+ events, self._engine_events = self._engine_events, []
988
+ for ev in events:
989
+ if ev.kind == "switch" and not getattr(ev, "dry_run", False):
990
+ rumps.notification("claude-swap", "Auto-switched account", ev.human())
991
+ self.refresh_async() # reflect the switch promptly
992
+ elif ev.kind == "account-quarantined":
993
+ rumps.notification("claude-swap", "Account quarantined", ev.human())
994
+ elif ev.kind == "all-exhausted":
995
+ rumps.notification("claude-swap", "All accounts exhausted", ev.human())
996
+ elif ev.kind == "config-warning":
997
+ # e.g. an autoswitch.model name no account reports — the
998
+ # engine emits it once per run; dropping it would leave a
999
+ # menu-bar user with a silently inert filter.
1000
+ rumps.notification("claude-swap", "Configuration warning", ev.human())
1001
+ elif ev.kind == "error":
1002
+ # A failed tick. The engine retries by itself, so dropping
1003
+ # this hid a switch that could never succeed; say it once
1004
+ # per distinct message, then stay quiet for a while.
1005
+ if should_surface_engine_error(
1006
+ ev, self._engine_errors_surfaced, time.monotonic()
1007
+ ):
1008
+ self.switcher._logger.warning("auto-switch %s", ev.human())
1009
+ rumps.notification("claude-swap", "Auto-switch error", ev.human())
1010
+ elif ev.kind == "engine-stopped":
1011
+ # The thread behind the hosted engine ended without us
1012
+ # stopping it. Before this the reference stayed set: the
1013
+ # display kept reading store-only for an engine that no
1014
+ # longer fetched, and the menu kept looking enabled.
1015
+ if engine_exit_applies(self._engine, ev.engine):
1016
+ self._engine = None
1017
+ self._engine_failure = ev.human()
1018
+ self.switcher._logger.warning(
1019
+ "auto-switch stopped (%s); the menu bar keeps showing "
1020
+ "usage but will not switch until it is restarted",
1021
+ self._engine_failure,
1022
+ )
1023
+ rumps.notification(
1024
+ "claude-swap",
1025
+ "Auto-switch stopped",
1026
+ f"{self._engine_failure}. Open the menu to restart it.",
1027
+ )
1028
+ self.rebuild_menu()
1029
+ self.refresh_async() # display fetching resumes on its own
1030
+
1031
+ def _threshold(self) -> int:
1032
+ """Current auto-switch threshold from core settings (for the menu)."""
1033
+ try:
1034
+ return int(load_settings(self.switcher.backup_dir).threshold)
1035
+ except Exception:
1036
+ return 0
1037
+
1038
+ # ---- menu construction -----------------------------------------------
1039
+ def rebuild_menu(self):
1040
+ health, attention = self._health()
1041
+ self._health_attention = attention
1042
+ self.title = format_title(
1043
+ self.snapshot["active_email"],
1044
+ self.snapshot["active_usage"],
1045
+ self.settings,
1046
+ alias=self.snapshot.get("active_alias"),
1047
+ attention=attention,
1048
+ )
1049
+ # Stop a rumps memory leak: rumps registers each menu item's callback
1050
+ # in the process-global NSApp._ns_to_py_and_callback, but Menu.clear()
1051
+ # never removes them, so rebuilding the whole menu on every refresh
1052
+ # leaks every item forever (~1GB after days on a busy machine). Purge
1053
+ # this menu's entries before we tear it down. We walk the *native*
1054
+ # NSMenu tree (itemArray, recursing into submenus) rather than the
1055
+ # rumps Python dict: that dict is keyed by title and silently drops
1056
+ # same-title items, which would leave leaked entries behind.
1057
+ # Guard the private rumps attribute: if a future rumps release renames
1058
+ # it, degrade to "leaks again" rather than crashing on every rebuild.
1059
+ _reg = getattr(rumps.rumps.NSApp, "_ns_to_py_and_callback", None)
1060
+ if _reg is not None:
1061
+ def _purge(nsmenu):
1062
+ for _it in nsmenu.itemArray():
1063
+ _reg.pop(_it, None)
1064
+ _sub = _it.submenu()
1065
+ if _sub is not None:
1066
+ _purge(_sub)
1067
+ _purge(self.menu._menu)
1068
+ self.menu.clear()
1069
+ account_items = []
1070
+ for (
1071
+ num, email, is_active, display, _last_good, alias, disabled, fetched_at,
1072
+ login_expires_at, quarantined,
1073
+ ) in self.snapshot["accounts"]:
1074
+ item = rumps.MenuItem(
1075
+ format_account_label(
1076
+ num, email, display, alias=alias, disabled=disabled, fetched_at=fetched_at,
1077
+ login_expires_at=login_expires_at, quarantined=quarantined,
1078
+ ),
1079
+ callback=self._make_switch_to(num),
1080
+ )
1081
+ item.state = 1 if is_active else 0
1082
+ if isinstance(display, str) and display != menu_note(display):
1083
+ # The row shows the state; the remedy is a hover away.
1084
+ _set_tooltip(item, display)
1085
+ account_items.append(item)
1086
+ if not account_items:
1087
+ account_items.append(rumps.MenuItem("No managed accounts", callback=None))
1088
+
1089
+ health_item = rumps.MenuItem(
1090
+ health, callback=self.on_restart_engine if attention else None
1091
+ )
1092
+ if attention and self._engine_failure:
1093
+ _set_tooltip(health_item, self._engine_failure)
1094
+ self._health_item = health_item
1095
+
1096
+ self.menu = [
1097
+ health_item,
1098
+ None,
1099
+ *account_items,
1100
+ None,
1101
+ rumps.MenuItem("Rotate to next", callback=self._switch(None)),
1102
+ rumps.MenuItem("Switch to best", callback=self._switch("best")),
1103
+ rumps.MenuItem("Next available", callback=self._switch("next-available")),
1104
+ None,
1105
+ self._add_menu(rumps),
1106
+ self._disable_menu(rumps),
1107
+ self._remove_menu(rumps),
1108
+ rumps.MenuItem("Refresh current credentials", callback=self.on_refresh_creds),
1109
+ self._history_menu(rumps),
1110
+ None,
1111
+ self._settings_menu(rumps),
1112
+ rumps.MenuItem("Refresh now", callback=self.on_refresh_now),
1113
+ rumps.MenuItem("Quit", callback=self.on_quit),
1114
+ ]
1115
+
1116
+ def _add_menu(self, rumps):
1117
+ menu = rumps.MenuItem("Add account")
1118
+ menu.add(rumps.MenuItem(
1119
+ "Sign in to another account…", callback=self.on_add_signin
1120
+ ))
1121
+ menu.add(rumps.MenuItem("From current login", callback=self.on_add_login))
1122
+ if hasattr(self.switcher, "add_account_from_token"):
1123
+ menu.add(rumps.MenuItem("From setup-token…", callback=self.on_add_token))
1124
+ return menu
1125
+
1126
+ def _remove_menu(self, rumps):
1127
+ menu = rumps.MenuItem("Remove account")
1128
+ accounts = self.snapshot["accounts"]
1129
+ if not accounts:
1130
+ menu.add(rumps.MenuItem("No managed accounts", callback=None))
1131
+ for (
1132
+ num, email, _is_active, _display, _last_good, alias, _disabled, _fetched_at,
1133
+ _login_expires_at, _quarantined,
1134
+ ) in accounts:
1135
+ label = f"{num} {alias} ({email})" if alias else f"{num} {email}"
1136
+ menu.add(rumps.MenuItem(label, callback=self._make_remove(num)))
1137
+ return menu
1138
+
1139
+ def _disable_menu(self, rumps):
1140
+ menu = rumps.MenuItem("Disable / enable account")
1141
+ accounts = self.snapshot["accounts"]
1142
+ if not accounts:
1143
+ menu.add(rumps.MenuItem("No managed accounts", callback=None))
1144
+ for (
1145
+ num, email, _is_active, _display, _last_good, alias, disabled, _fetched_at,
1146
+ _login_expires_at, _quarantined,
1147
+ ) in accounts:
1148
+ name = f"{alias} ({email})" if alias else email
1149
+ item = rumps.MenuItem(
1150
+ f"{num} {name}", callback=self._make_toggle_disabled(num, disabled)
1151
+ )
1152
+ # A check-mark reads as "held out of rotation" — same glyph the
1153
+ # active row uses, but here it means disabled, not selected.
1154
+ item.state = 1 if disabled else 0
1155
+ menu.add(item)
1156
+ return menu
1157
+
1158
+ def _history_menu(self, rumps):
1159
+ menu = rumps.MenuItem("Switch history")
1160
+ try:
1161
+ text = log_path.read_text(encoding="utf-8")
1162
+ except OSError:
1163
+ text = ""
1164
+ entries = parse_switch_history(text)
1165
+ if entries:
1166
+ for line in entries:
1167
+ menu.add(rumps.MenuItem(line, callback=None))
1168
+ else:
1169
+ menu.add(rumps.MenuItem("No switches logged yet", callback=None))
1170
+ menu.add(None)
1171
+ menu.add(rumps.MenuItem("Open full log…", callback=self.on_open_log))
1172
+ return menu
1173
+
1174
+ def _settings_menu(self, rumps):
1175
+ menu = rumps.MenuItem("Settings")
1176
+ name_item = rumps.MenuItem("Show account name in menu bar", callback=self.on_toggle_name)
1177
+ name_item.state = 1 if self.settings.show_account_name else 0
1178
+ menu.add(name_item)
1179
+
1180
+ title_pct = rumps.MenuItem("Title percentage")
1181
+ tp_labels = {"off": "None", "5h": "Session (5h)",
1182
+ "7d": "Weekly (7d)", "both": "Both (5h · 7d)"}
1183
+ for mode in TITLE_PCT_CHOICES:
1184
+ ch = rumps.MenuItem(tp_labels[mode], callback=self._make_title_pct(mode))
1185
+ ch.state = 1 if self.settings.title_pct == mode else 0
1186
+ title_pct.add(ch)
1187
+ menu.add(title_pct)
1188
+
1189
+ scoped_item = rumps.MenuItem(
1190
+ "Show model limits in title", callback=self.on_toggle_scoped
1191
+ )
1192
+ scoped_item.state = 1 if self.settings.title_scoped else 0
1193
+ menu.add(scoped_item)
1194
+
1195
+ interval = rumps.MenuItem("Refresh interval")
1196
+ labels = {30: "30 seconds", 60: "60 seconds", 300: "5 minutes"}
1197
+ for secs in REFRESH_CHOICES:
1198
+ choice = rumps.MenuItem(labels[secs], callback=self._make_interval(secs))
1199
+ choice.state = 1 if self.settings.refresh_interval == secs else 0
1200
+ interval.add(choice)
1201
+ menu.add(interval)
1202
+
1203
+ auto_item = rumps.MenuItem("Auto-switch accounts", callback=self.on_toggle_autoswitch)
1204
+ auto_item.state = 1 if self.settings.auto_switch_enabled else 0
1205
+ menu.add(auto_item)
1206
+
1207
+ threshold_menu = rumps.MenuItem("Auto-switch threshold")
1208
+ current = self._threshold()
1209
+ for pct in AUTO_THRESHOLD_CHOICES:
1210
+ ch = rumps.MenuItem(f"{pct}%", callback=self._make_threshold(pct))
1211
+ ch.state = 1 if current == pct else 0
1212
+ threshold_menu.add(ch)
1213
+ menu.add(threshold_menu)
1214
+
1215
+ menu.add(None)
1216
+ # Checked = the plist sits in ~/Library/LaunchAgents, where launchd
1217
+ # scans at login. The state is read from disk on every rebuild so a
1218
+ # change made from the CLI shows up here too.
1219
+ login_item = rumps.MenuItem("Start at login", callback=self.on_toggle_login)
1220
+ login_item.state = 1 if launch_agent.start_at_login_enabled() else 0
1221
+ menu.add(login_item)
1222
+
1223
+ return menu
1224
+
1225
+ # ---- callbacks --------------------------------------------------------
1226
+ def _save_and_rebuild(self):
1227
+ self.settings.save(settings_path)
1228
+ self.rebuild_menu()
1229
+
1230
+ def _guard(self, fn):
1231
+ """Run a switcher action, surfacing ClaudeSwitchError via an alert."""
1232
+ try:
1233
+ fn()
1234
+ return True
1235
+ except ClaudeSwitchError as e:
1236
+ rumps.alert(title="claude-swap", message=str(e))
1237
+ return False
1238
+
1239
+ def _notify_switched(self):
1240
+ rumps.notification(
1241
+ "claude-swap",
1242
+ "Account switched",
1243
+ "Switch takes effect within ~30s — restart Claude Code to apply immediately.",
1244
+ )
1245
+
1246
+ def _make_switch_to(self, num):
1247
+ def cb(_sender):
1248
+ if self._guard(lambda: self.switcher.switch_to(str(num))):
1249
+ self._notify_switched()
1250
+ self.refresh_async()
1251
+ return cb
1252
+
1253
+ def _switch(self, strategy):
1254
+ def cb(_sender):
1255
+ if self._guard(lambda: self.switcher.switch(strategy=strategy)):
1256
+ self._notify_switched()
1257
+ self.refresh_async()
1258
+ return cb
1259
+
1260
+ def _make_remove(self, num):
1261
+ def cb(_sender):
1262
+ if rumps.alert(
1263
+ title="Remove account",
1264
+ message=f"Remove account {num}?",
1265
+ ok="Remove",
1266
+ cancel="Cancel",
1267
+ ) == 1: # 1 == OK
1268
+ if self._guard(lambda: self.switcher.remove_account(str(num), assume_yes=True)):
1269
+ self.refresh_async()
1270
+ return cb
1271
+
1272
+ def _make_toggle_disabled(self, num, disabled):
1273
+ # `disabled` is this row's current state; selecting it flips it.
1274
+ target = not disabled
1275
+ def cb(_sender):
1276
+ if self._guard(
1277
+ lambda: self.switcher.set_account_disabled(str(num), target)
1278
+ ):
1279
+ self.refresh_async()
1280
+ return cb
1281
+
1282
+ def on_add_signin(self, _sender):
1283
+ import subprocess
1284
+ try:
1285
+ script = write_login_command(
1286
+ self.switcher.backup_dir, launch_agent.resolve_program()
1287
+ )
1288
+ subprocess.run(["open", str(script)], check=True)
1289
+ except (OSError, subprocess.CalledProcessError) as e:
1290
+ rumps.alert(
1291
+ title="claude-swap",
1292
+ message=f"Couldn't open a terminal for the sign-in ({e}). "
1293
+ "Run `cswap login` in a terminal instead.",
1294
+ )
1295
+
1296
+ def on_add_login(self, _sender):
1297
+ if self._guard(self.switcher.add_account):
1298
+ self.refresh_async()
1299
+
1300
+ def on_add_token(self, _sender):
1301
+ # A menu-bar (accessory) app isn't the active app, so a modal
1302
+ # rumps.Window can render black/blank until we bring the app
1303
+ # forward. Activate before showing the input dialogs.
1304
+ import AppKit
1305
+ AppKit.NSApplication.sharedApplication().activateIgnoringOtherApps_(True)
1306
+ email_win = rumps.Window(
1307
+ title="Add account from setup-token",
1308
+ message="Email for this token:",
1309
+ ok="Next", cancel="Cancel", dimensions=(320, 24),
1310
+ )
1311
+ email_resp = email_win.run()
1312
+ if email_resp.clicked != 1 or not email_resp.text.strip():
1313
+ return
1314
+ token_win = rumps.Window(
1315
+ title="Add account from setup-token",
1316
+ message="Setup token (sk-ant-oat01-…):",
1317
+ ok="Add", cancel="Cancel", dimensions=(320, 24),
1318
+ )
1319
+ token_resp = token_win.run()
1320
+ if token_resp.clicked != 1 or not token_resp.text.strip():
1321
+ return
1322
+ if self._guard(lambda: self.switcher.add_account_from_token(
1323
+ token=token_resp.text.strip(), email=email_resp.text.strip(), slot=None,
1324
+ )):
1325
+ self.refresh_async()
1326
+
1327
+ def on_open_log(self, _sender):
1328
+ import subprocess
1329
+ # Reveal the log in Finder (-R); if it doesn't exist yet, open the dir.
1330
+ target = log_path if log_path.exists() else log_path.parent
1331
+ subprocess.run(["open", "-R", str(target)], check=False)
1332
+
1333
+ def on_refresh_creds(self, _sender):
1334
+ if self.switcher._get_current_account() is None:
1335
+ rumps.alert(title="claude-swap",
1336
+ message="No active Claude Code login detected. Log in first.")
1337
+ return
1338
+ try:
1339
+ self.switcher.add_account(slot=None)
1340
+ except CredentialReadError:
1341
+ # The Keychain did not answer (locked, or `security` timed out).
1342
+ # A launchd agent reads the Keychain like any other process of
1343
+ # the user's session, so relaunching from a Terminal is not a
1344
+ # fix; an earlier version of this alert claimed it was.
1345
+ rumps.alert(
1346
+ title="claude-swap",
1347
+ message="Couldn't read the active credential: the Keychain didn't "
1348
+ "answer (locked, or the security call timed out). Unlock it "
1349
+ "or try again in a moment; `cswap add` in a Terminal shows "
1350
+ "the full error.",
1351
+ )
1352
+ return
1353
+ except ClaudeSwitchError as e:
1354
+ rumps.alert(title="claude-swap", message=str(e))
1355
+ return
1356
+ self.refresh_async()
1357
+
1358
+ def on_refresh_now(self, _sender):
1359
+ self.refresh_async(full=True) # explicit user refresh → full pass
1360
+
1361
+ def on_quit(self, _sender):
1362
+ self._stop_engine()
1363
+ rumps.quit_application()
1364
+
1365
+ def on_toggle_name(self, _sender):
1366
+ self.settings.show_account_name = not self.settings.show_account_name
1367
+ self._save_and_rebuild()
1368
+
1369
+ def on_toggle_scoped(self, _sender):
1370
+ self.settings.title_scoped = not self.settings.title_scoped
1371
+ self._save_and_rebuild()
1372
+
1373
+ def _make_title_pct(self, mode):
1374
+ def cb(_sender):
1375
+ self.settings.title_pct = mode
1376
+ self._save_and_rebuild()
1377
+ return cb
1378
+
1379
+ def _make_interval(self, secs):
1380
+ def cb(_sender):
1381
+ self.settings.refresh_interval = secs
1382
+ # rumps 0.4.0's Timer.interval setter is a no-op while running
1383
+ # unless a full interval has elapsed; stop/start forces the new
1384
+ # cadence to take effect immediately.
1385
+ self.refresh_timer.stop()
1386
+ self.refresh_timer.interval = secs
1387
+ self.refresh_timer.start()
1388
+ self._save_and_rebuild()
1389
+ return cb
1390
+
1391
+ def on_toggle_login(self, _sender):
1392
+ # Moves the plist between its two homes; launchd is not touched, so
1393
+ # the app whose menu was just clicked keeps running either way.
1394
+ enabled = not launch_agent.start_at_login_enabled()
1395
+ try:
1396
+ launch_agent.set_start_at_login(
1397
+ enabled, backup_dir=self.switcher.backup_dir
1398
+ )
1399
+ except (ClaudeSwitchError, OSError) as e:
1400
+ rumps.alert(
1401
+ title="claude-swap", message=f"Couldn't change Start at login: {e}"
1402
+ )
1403
+ return
1404
+ self.rebuild_menu()
1405
+
1406
+ def on_toggle_autoswitch(self, _sender):
1407
+ self.settings.auto_switch_enabled = not self.settings.auto_switch_enabled
1408
+ self.settings.save(settings_path)
1409
+ if self.settings.auto_switch_enabled:
1410
+ self._start_engine()
1411
+ else:
1412
+ self._stop_engine()
1413
+ self.rebuild_menu()
1414
+
1415
+ def on_restart_engine(self, _sender):
1416
+ # The health row's click while auto-switch is enabled but not running.
1417
+ self._engine_failure = None
1418
+ self._start_engine()
1419
+ self.rebuild_menu()
1420
+
1421
+ def _make_threshold(self, pct):
1422
+ def cb(_sender):
1423
+ try:
1424
+ set_setting(self.switcher.backup_dir, "autoswitch.threshold", str(pct))
1425
+ except Exception as e:
1426
+ rumps.alert(title="claude-swap", message=f"Couldn't set threshold: {e}")
1427
+ return
1428
+ self._restart_engine() # apply immediately if running
1429
+ self.rebuild_menu()
1430
+ return cb
1431
+
1432
+ MenuBarApp().run()
1433
+ return 0