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
@@ -0,0 +1,544 @@
1
+ """Shared render widgets: usage bar rows, account cards, and the accounts panel.
2
+
3
+ The bar glyphs themselves come from ``claude_swap.usage_bars``, which the
4
+ plain CLI draws its bars with too.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from datetime import datetime, timezone
11
+ from typing import TYPE_CHECKING, Callable
12
+
13
+ from rich.cells import cell_len
14
+ from rich.text import Text
15
+ from textual.widgets import ListItem, Static
16
+
17
+ from claude_swap import oauth, pace, subscription
18
+ from claude_swap.json_output import USAGE_API_KEY, USAGE_RELOGIN_REQUIRED
19
+ from claude_swap.models import AccountSnapshot
20
+ from claude_swap.oauth import FIVE_HOUR_LABEL
21
+ from claude_swap.printer import format_age
22
+ from claude_swap.switcher import ERROR_NOTES
23
+ from claude_swap.usage_store import STALE_OK_S
24
+ from claude_swap.tui import data
25
+ from claude_swap.usage_bars import BAR_MAX, BAR_MIN, Palette, bar_cells, switch_line
26
+
27
+ if TYPE_CHECKING:
28
+ from claude_swap.tui.app import CswapApp
29
+
30
+ def usage_bar(
31
+ label: str,
32
+ pct: float | None,
33
+ suffix: str | None,
34
+ width: int,
35
+ *,
36
+ stale: bool = False,
37
+ threshold: float | None = None,
38
+ palette: Palette = Palette.DARK,
39
+ ) -> Text:
40
+ """One full bar line: ``5h ━━━━╸────┃── 47% resets 2h 13m · 20:39``."""
41
+ text = Text()
42
+ text.append(f"{label} ", style=palette.muted)
43
+ text.append(bar_cells(pct, width, stale=stale, threshold=threshold, palette=palette))
44
+ if pct is None:
45
+ text.append(" usage unknown", style=palette.muted)
46
+ else:
47
+ color = palette.severity(pct)
48
+ text.append(f" {pct:3.0f}%", style=f"{color} dim" if stale else color)
49
+ if suffix:
50
+ text.append(f" {suffix}", style=palette.muted)
51
+ return text
52
+
53
+
54
+ def _reset_parts(window: dict, now: float) -> tuple[str | None, str | None]:
55
+ """Countdown suffix and its clock-extended variant for one window.
56
+
57
+ ``("resets 2h 13m", "resets 2h 13m · 20:39")`` — the second form is what
58
+ a row shows when it has the width for it. Equal when no clock is known.
59
+ """
60
+ reset = data.reset_text(window, now)
61
+ if not reset:
62
+ return None, None
63
+ clock = data.reset_clock(window, now)
64
+ return reset, f"{reset} · {clock}" if clock else reset
65
+
66
+
67
+ def _passed_reset_parts(window: dict, now: float) -> tuple[str, str]:
68
+ """``_reset_parts`` for a window whose reset has passed
69
+ (``oauth.window_reset_passed``): how long ago, then when.
70
+
71
+ ``("reset 3h 5m ago", "reset 3h 5m ago · Nov 26 03:42")``.
72
+ """
73
+ reset_utc = datetime.fromisoformat(window["resets_at"])
74
+ ago = f"reset {data.format_duration(now - reset_utc.timestamp())} ago"
75
+ clock = oauth.reset_clock_string(
76
+ reset_utc, datetime.fromtimestamp(now, tz=timezone.utc)
77
+ )
78
+ return ago, f"{ago} · {clock}"
79
+
80
+
81
+ def _pace_suffix(window: dict, fetched_at: float | None) -> str:
82
+ """"(ahead of pace)" when a weekly window is meaningfully ahead, else ""."""
83
+ result = pace.compute_pace(window, fetched_at=fetched_at)
84
+ return "(ahead of pace)" if result and result.ahead else ""
85
+
86
+
87
+ def usage_rows(
88
+ last_good: dict | None, now: float, fetched_at: float | None = None
89
+ ) -> list[tuple[str, float | None, str, str]]:
90
+ """(label, pct, suffix, suffix_full) rows mirroring the CLI's
91
+ ``_format_usage_lines``. ``pct`` is None for a 5h/7d window reported
92
+ without a figure and for a 5h, 7d or per-model window whose reset has
93
+ passed (``oauth.window_reset_passed``), which then carries no marker and
94
+ says when it ended instead; ``usage_bar`` draws that row as ``usage
95
+ unknown``.
96
+
97
+ ``suffix_full`` extends the reset countdown with the absolute clock time
98
+ (``resets 2h 13m · 20:39``) for rows that have room; otherwise it equals
99
+ ``suffix``. Only windows the account actually has produce a row — an
100
+ annual plan without a 7-day window simply has no 7d line. Order matches
101
+ the CLI: spend, 5h, 7d, then per-model scoped windows (e.g. "Fable"),
102
+ the latter marked ``(!)`` at/over their limit. The weekly (7d) and scoped
103
+ rows also carry a "(ahead of pace)" marker when meaningfully ahead of the
104
+ week's expected usage (issue #125) — never the 5h row.
105
+ """
106
+ if not isinstance(last_good, dict):
107
+ return []
108
+ rows: list[tuple[str, float | None, str, str]] = []
109
+ spend = last_good.get("spend")
110
+ if spend:
111
+ amounts = f"${spend['used']:,.2f} / ${spend['limit']:,.2f}"
112
+ reset, reset_full = _reset_parts(spend, now)
113
+ suffix = f"{reset} {amounts}" if reset else amounts
114
+ suffix_full = f"{reset_full} {amounts}" if reset_full else amounts
115
+ rows.append(("$$", float(spend["pct"]), suffix, suffix_full))
116
+ for key, label in (("five_hour", FIVE_HOUR_LABEL), ("seven_day", "7d")):
117
+ window = last_good.get(key)
118
+ if window:
119
+ if oauth.window_reset_passed(window, now):
120
+ rows.append((label, None, *_passed_reset_parts(window, now)))
121
+ continue
122
+ reset, reset_full = _reset_parts(window, now)
123
+ suffix, suffix_full = reset or "", reset_full or ""
124
+ if key == "seven_day":
125
+ marker = _pace_suffix(window, fetched_at)
126
+ if marker:
127
+ suffix = f"{suffix} {marker}" if suffix else marker
128
+ suffix_full = f"{suffix_full} {marker}" if suffix_full else marker
129
+ pct = window.get("pct")
130
+ rows.append((
131
+ label,
132
+ float(pct) if isinstance(pct, (int, float)) else None,
133
+ suffix,
134
+ suffix_full,
135
+ ))
136
+ for window in last_good.get("scoped") or []:
137
+ if oauth.window_reset_passed(window, now):
138
+ rows.append((window["name"], None, *_passed_reset_parts(window, now)))
139
+ continue
140
+ pct = float(window["pct"])
141
+ suffix, suffix_full = _reset_parts(window, now)
142
+ suffix, suffix_full = suffix or "", suffix_full or ""
143
+ if pct >= 100:
144
+ suffix = f"{suffix} (!)" if suffix else "(!)"
145
+ suffix_full = f"{suffix_full} (!)" if suffix_full else "(!)"
146
+ else:
147
+ marker = _pace_suffix(window, fetched_at)
148
+ if marker:
149
+ suffix = f"{suffix} {marker}" if suffix else marker
150
+ suffix_full = f"{suffix_full} {marker}" if suffix_full else marker
151
+ rows.append((window["name"], pct, suffix, suffix_full))
152
+ rejected = last_good.get("rejected")
153
+ if isinstance(rejected, dict):
154
+ # A refused setup-token probe: at its limit until the refusal ends,
155
+ # whatever the windows above say (auto-switching excludes it).
156
+ reset, reset_full = _reset_parts(rejected, now)
157
+ suffix = f"rejected (!) {reset}" if reset else "rejected (!)"
158
+ suffix_full = f"rejected (!) {reset_full}" if reset_full else "rejected (!)"
159
+ rows.append(("probe", 100.0, suffix, suffix_full))
160
+ return rows
161
+
162
+
163
+ # Login-note forms, fullest first: "re-login in 5d 12h", "re-login in 5d",
164
+ # nothing. A row carries one only while its login is due
165
+ # (``oauth.login_time_left``), so most rows read as if there were no note.
166
+ LOGIN_FORMS = ("full", "short", None)
167
+
168
+
169
+ def login_segment(
170
+ acc: AccountSnapshot, form: str | None, now: float | None = None, gap: str = " "
171
+ ) -> str:
172
+ """The row's ``re-login in …`` note led by ``gap``, or ``""`` when
173
+ ``form`` is None or the slot's login is not due."""
174
+ if form is None:
175
+ return ""
176
+ quarantined = acc.usage.sentinel == USAGE_RELOGIN_REQUIRED
177
+ note = oauth.format_login_expiry(
178
+ acc.login_expires_at, quarantined, now, short=form == "short"
179
+ )
180
+ return f"{gap}{note}" if note else ""
181
+
182
+
183
+ def fit_login(build: Callable[[str | None], list[Text]], budget: int) -> list[Text]:
184
+ """``build(form)`` for the fullest login form in which every row's first
185
+ line fits ``budget`` columns; usage figures are never cut, so with no
186
+ fitting form the login goes."""
187
+ for form in LOGIN_FORMS:
188
+ rows = build(form)
189
+ if all(cell_len(row.plain.strip("\n").partition("\n")[0]) <= budget for row in rows):
190
+ break
191
+ return rows
192
+
193
+
194
+ def _append_plan(text: Text, acc: AccountSnapshot, gap: str, palette) -> None:
195
+ """``· Ultra`` after the header — the same marker ``cswap list`` prints:
196
+ a lapsed subscription is a highlighted ``Free`` rather than an appended
197
+ "expired", and the age follows once the plan has gone two TTLs without
198
+ refreshing."""
199
+ record = acc.subscription_plan
200
+ if not record:
201
+ return
202
+ plan = record["plan"]
203
+ text.append(f"{gap}· ", style=palette.muted)
204
+ text.append(
205
+ subscription.plan_label(plan),
206
+ style=palette.sev_warn if subscription.is_expired(plan) else palette.muted,
207
+ )
208
+ if time.time() - record["fetchedAt"] >= 2 * subscription.PLAN_TTL_S:
209
+ age = format_age(int(record["fetchedAt"] * 1000))
210
+ text.append(f" ({age})", style=palette.muted)
211
+
212
+
213
+ def _policy_badges(acc: AccountSnapshot, gap: str) -> list[str]:
214
+ """Badge strings for the account's per-account policy, in display order.
215
+
216
+ Returns an empty list for an account carrying no policy, which is every
217
+ account in a store that has never used the feature — that is what keeps
218
+ those rows byte-identical to their pre-policy render.
219
+
220
+ ``gap`` is the leading separator each render path already uses for its own
221
+ badges (three spaces on the card, two on the minimized row).
222
+ """
223
+ badges: list[str] = []
224
+ if acc.policy.threshold is not None:
225
+ # ``:g`` so 75.0 reads as "75%" and 82.5 keeps its fraction — the store
226
+ # accepts one decimal place and the row shows back exactly what was set.
227
+ badges.append(f"{gap}th {acc.policy.threshold:g}%")
228
+ return badges
229
+
230
+
231
+ def account_card_text(
232
+ acc: AccountSnapshot,
233
+ width: int,
234
+ *,
235
+ threshold: float | None = None,
236
+ weekly_threshold: float | None = None,
237
+ now: float | None = None,
238
+ palette: Palette = Palette.DARK,
239
+ show_tag: bool = True,
240
+ login: str | None = "full",
241
+ ) -> Text:
242
+ """The full account card: header line + per-window bar rows. Each row's
243
+ tick is the switch line that row is judged against: ``threshold`` on the
244
+ 5h (and spend) rows, ``weekly_threshold`` — when set — on the 7d and
245
+ per-model rows, which reset weekly. ``login`` is the form of the re-login
246
+ note that ends the header while the login is due (see ``LOGIN_FORMS``)."""
247
+ now = now if now is not None else time.time()
248
+
249
+ text = Text()
250
+ text.append(f"{acc.number:>2} ", style=f"bold {palette.foreground}")
251
+ if acc.alias:
252
+ text.append(acc.alias, style=f"bold {palette.accent}")
253
+ text.append(f" ({acc.email})", style=palette.foreground)
254
+ else:
255
+ text.append(acc.email, style=palette.foreground)
256
+ if show_tag:
257
+ text.append(f" [{acc.display_tag}]", style=palette.muted)
258
+ if acc.is_active:
259
+ text.append(" ● active", style=f"bold {palette.accent}")
260
+ if acc.disabled:
261
+ text.append(" (disabled)", style=palette.muted)
262
+ for badge in _policy_badges(acc, " "):
263
+ text.append(badge, style=palette.muted)
264
+ _append_plan(text, acc, " ", palette)
265
+ age = data.format_age(acc.usage.age_s)
266
+ if age:
267
+ text.append(f" {age}", style=palette.muted)
268
+ text.append(login_segment(acc, login, now, " "), style=palette.muted)
269
+
270
+ sentinel = acc.usage.sentinel
271
+ if sentinel is not None:
272
+ text.append("\n ")
273
+ style = palette.muted if sentinel == USAGE_API_KEY else palette.sev_warn
274
+ marker = "·" if sentinel == USAGE_API_KEY else "⚠"
275
+ text.append(
276
+ f"{marker} {data.sentinel_label(sentinel, acc.number)}", style=style
277
+ )
278
+ # Same supplementary line `cswap list` prints: the last good
279
+ # measurement behind the sentinel (API-key accounts have no quota to
280
+ # have "seen").
281
+ if sentinel != USAGE_API_KEY:
282
+ last_seen = data.last_seen_note(acc.usage)
283
+ if last_seen is not None:
284
+ text.append("\n ")
285
+ text.append(f"└ {last_seen}", style=palette.muted)
286
+ return text
287
+
288
+ rows = usage_rows(acc.usage.last_good, now, acc.usage.fetched_at)
289
+ if not rows:
290
+ text.append("\n ")
291
+ text.append("usage unavailable", style=palette.muted)
292
+ if acc.usage.last_error:
293
+ # Same wording as the CLI detail line: error KINDS with a
294
+ # friendly note render it, so both surfaces describe the state
295
+ # identically.
296
+ note = ERROR_NOTES.get(acc.usage.last_error, acc.usage.last_error)
297
+ text.append(f" · {note}", style=palette.muted)
298
+ return text
299
+
300
+ stale = acc.usage.age_s is not None and acc.usage.age_s > STALE_OK_S
301
+ label_width = max(len(label) for label, _pct, _suffix, _full in rows)
302
+ bar_width = max(BAR_MIN, min(BAR_MAX, width - 42 - label_width))
303
+ for label, pct, suffix, suffix_full in rows:
304
+ # everything on a row except the suffix: indent, label, bar, " NNN%"
305
+ # (or " usage unknown" on a row without a figure), gap
306
+ row_overhead = 4 + label_width + 1 + bar_width + (15 if pct is None else 5) + 2
307
+ # per-row: show the absolute clock only where it fits, so a long
308
+ # spend row degrading doesn't cost the 5h/7d rows their clocks
309
+ if suffix_full != suffix and row_overhead + len(suffix_full) <= width:
310
+ suffix = suffix_full
311
+ row_line = switch_line(label, threshold, weekly_threshold)
312
+ text.append("\n ")
313
+ text.append(
314
+ usage_bar(
315
+ f"{label:<{label_width}}",
316
+ pct,
317
+ suffix or None,
318
+ bar_width,
319
+ stale=stale,
320
+ threshold=row_line,
321
+ palette=palette,
322
+ )
323
+ )
324
+ return text
325
+
326
+
327
+ def fitted_card_text(acc: AccountSnapshot, width: int, budget: int, **kwargs) -> Text:
328
+ """``account_card_text`` with the login-note form its header has room for in ``budget`` columns."""
329
+ (card,) = fit_login(
330
+ lambda login: [account_card_text(acc, width, login=login, **kwargs)], budget
331
+ )
332
+ return card
333
+
334
+
335
+ def _end_mini(text: Text, acc: AccountSnapshot, form: str | None, now: float, palette: Palette) -> Text:
336
+ """Close a mini row with its ``re-login in …`` note, while the login is due."""
337
+ note = login_segment(acc, form, now, gap="")
338
+ if note:
339
+ text.append(" · ", style=palette.track)
340
+ text.append(note, style=palette.muted)
341
+ return text
342
+
343
+
344
+ def mini_account_text(
345
+ acc: AccountSnapshot,
346
+ now: float,
347
+ *,
348
+ palette: Palette = Palette.DARK,
349
+ login: str | None = "full",
350
+ show_tag: bool = True,
351
+ ) -> Text:
352
+ """One minimized line for an inactive account.
353
+
354
+ ``2 work@acme.dev [personal] 5h 92% · 7d 63%`` — pcts only, severity
355
+ colored; a window at/over 100% brings its reset countdown along, and a
356
+ maxed per-model window shows as ``Fable (!)``. Sentinel states show
357
+ their label instead. ``login`` is the form of the ``· re-login in …``
358
+ note that ends the row while the login is due (see ``LOGIN_FORMS``).
359
+ """
360
+ text = Text(no_wrap=True, overflow="ellipsis")
361
+ text.append(f"{acc.number:>2} ", style=f"bold {palette.muted}")
362
+ if acc.alias:
363
+ text.append(acc.alias, style=f"bold {palette.accent}")
364
+ text.append(f" ({acc.email})", style=palette.foreground)
365
+ else:
366
+ text.append(acc.email, style=palette.foreground)
367
+ if show_tag:
368
+ text.append(f" [{acc.display_tag}]", style=palette.muted)
369
+ if acc.disabled:
370
+ text.append(" (disabled)", style=palette.muted)
371
+ for badge in _policy_badges(acc, " "):
372
+ text.append(badge, style=palette.muted)
373
+ _append_plan(text, acc, " ", palette)
374
+ text.append(" ")
375
+
376
+ sentinel = acc.usage.sentinel
377
+ if sentinel is not None:
378
+ style = palette.muted if sentinel == USAGE_API_KEY else palette.sev_warn
379
+ text.append(data.sentinel_label(sentinel, acc.number), style=style)
380
+ return _end_mini(text, acc, login, now, palette)
381
+
382
+ last_good = acc.usage.last_good
383
+ fetched_at = acc.usage.fetched_at
384
+ stale = acc.usage.age_s is not None and acc.usage.age_s > STALE_OK_S
385
+ parts = 0
386
+ for key, label in (("five_hour", "5h"), ("seven_day", "7d")):
387
+ window = last_good.get(key) if isinstance(last_good, dict) else None
388
+ if not window:
389
+ continue
390
+ if parts:
391
+ text.append(" · ", style=palette.track)
392
+ if not isinstance(
393
+ window.get("pct"), (int, float)
394
+ ) or oauth.window_reset_passed(window, now):
395
+ # No figure, or one for a window that has ended: unknown, not 0%.
396
+ text.append(f"{label} ", style=palette.muted)
397
+ text.append("?", style=palette.muted)
398
+ parts += 1
399
+ continue
400
+ pct = float(window["pct"])
401
+ color = palette.severity(pct)
402
+ text.append(f"{label} ", style=palette.muted)
403
+ text.append(f"{pct:.0f}%", style=f"{color} dim" if stale else color)
404
+ if pct >= 100:
405
+ reset = data.reset_text(window, now)
406
+ if reset:
407
+ text.append(f" ({reset})", style=palette.muted)
408
+ elif key == "seven_day":
409
+ result = pace.compute_pace(window, fetched_at=fetched_at)
410
+ if result and result.ahead:
411
+ text.append(" (ahead)", style=palette.sev_warn)
412
+ parts += 1
413
+ maxed = [
414
+ w["name"]
415
+ for w in (last_good.get("scoped") or [] if isinstance(last_good, dict) else [])
416
+ if float(w["pct"]) >= 100 and not oauth.window_reset_passed(w, now)
417
+ ]
418
+ if isinstance(last_good, dict) and isinstance(last_good.get("rejected"), dict):
419
+ maxed.append("rejected") # a refused setup-token probe
420
+ for name in maxed:
421
+ if parts:
422
+ text.append(" · ", style=palette.track)
423
+ text.append(f"{name} (!)", style=palette.sev_crit)
424
+ parts += 1
425
+ if not parts:
426
+ text.append("usage unknown", style=palette.muted)
427
+ return _end_mini(text, acc, login, now, palette)
428
+
429
+
430
+ class AccountsPanel(Static):
431
+ """Static account overview: the active account full-size, others as
432
+ one-line minis (in slot order, expanded in place). The dashboard's — and
433
+ with ``show_minis=False`` the auto screen's — always-visible monitor."""
434
+
435
+ def __init__(self, *, show_minis: bool = True, id: str | None = None) -> None:
436
+ super().__init__(id=id)
437
+ self._show_minis = show_minis
438
+
439
+ def on_mount(self) -> None:
440
+ self.watch(self.app, "snapshot", lambda _snap: self.refresh(layout=True))
441
+ self.watch(self.app, "theme", lambda _t: self.refresh(layout=True))
442
+
443
+ def render(self) -> Text:
444
+ app: "CswapApp" = self.app # type: ignore[assignment]
445
+ palette = Palette.from_theme(app.current_theme)
446
+ snap = app.snapshot
447
+ if snap is None:
448
+ return Text("loading…", style=palette.muted)
449
+ if not snap.accounts:
450
+ return Text(
451
+ "No managed accounts yet.\n"
452
+ "Use the menu below: Add account — sign in to one, save your "
453
+ "current Claude Code login, or use a setup-token / API key.",
454
+ style=palette.muted,
455
+ )
456
+ now = time.time()
457
+ panel_width = self.size.width or 80
458
+ width = panel_width - 2
459
+ # One login-note form for all the minis, so the rows that carry one
460
+ # read alike; the card's header also carries the plan and age, so it
461
+ # fits its own.
462
+ inactive = [acc for acc in snap.accounts if not acc.is_active and self._show_minis]
463
+ minis = iter(
464
+ fit_login(
465
+ lambda login: [
466
+ mini_account_text(
467
+ acc, now, palette=palette, login=login,
468
+ show_tag=app.tag_shown(acc),
469
+ )
470
+ for acc in inactive
471
+ ],
472
+ panel_width,
473
+ )
474
+ )
475
+ blocks: list[Text] = []
476
+ for acc in snap.accounts:
477
+ if acc.is_active:
478
+ blocks.append(
479
+ fitted_card_text(
480
+ acc, width, panel_width, threshold=app.threshold_pct,
481
+ weekly_threshold=app.weekly_threshold_pct, now=now,
482
+ palette=palette, show_tag=app.tag_shown(acc),
483
+ )
484
+ )
485
+ elif self._show_minis:
486
+ blocks.append(next(minis))
487
+ if not blocks:
488
+ return Text("no active managed login", style=palette.muted)
489
+ text = Text()
490
+ previous_multiline = False
491
+ for i, block in enumerate(blocks):
492
+ multiline = "\n" in block.plain
493
+ if i:
494
+ # breathe around the expanded active card
495
+ text.append("\n\n" if (multiline or previous_multiline) else "\n")
496
+ text.append(block)
497
+ previous_multiline = multiline
498
+ return text
499
+
500
+
501
+ class AccountCard(Static):
502
+ """One account rendered full-size (used by the switch screen's list)."""
503
+
504
+ def __init__(self, acc: AccountSnapshot, *, threshold: float | None = None) -> None:
505
+ super().__init__()
506
+ self._acc = acc
507
+ self._threshold = threshold
508
+
509
+ def set_account(self, acc: AccountSnapshot) -> None:
510
+ self._acc = acc
511
+ self.refresh(layout=True)
512
+
513
+ def render(self) -> Text:
514
+ width = self.size.width or 80
515
+ return fitted_card_text(
516
+ self._acc, width, width, threshold=self._threshold,
517
+ palette=Palette.from_theme(self.app.current_theme),
518
+ show_tag=self.app.tag_shown(self._acc),
519
+ )
520
+
521
+
522
+ class AccountItem(ListItem):
523
+ """ListView row wrapping an :class:`AccountCard`; remembers its slot."""
524
+
525
+ def __init__(self, acc: AccountSnapshot) -> None:
526
+ super().__init__(AccountCard(acc))
527
+ self.number = acc.number
528
+ self.email = acc.email
529
+
530
+ def set_account(self, acc: AccountSnapshot) -> None:
531
+ self.number = acc.number
532
+ self.email = acc.email
533
+ self.query_one(AccountCard).set_account(acc)
534
+
535
+
536
+ class MenuItem(ListItem):
537
+ """One menu row: a label plus an action id the screen dispatches on."""
538
+
539
+ def __init__(self, label: str, action_id: str, *, muted: bool = False) -> None:
540
+ item = Static(label, markup=False)
541
+ if muted:
542
+ item.add_class("menu-item-muted")
543
+ super().__init__(item)
544
+ self.action_id = action_id