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,43 @@
1
+ """Textual-based interactive TUI for claude-swap.
2
+
3
+ Entry point for ``cswap tui`` (and bare ``cswap`` in an interactive
4
+ terminal). Heavy imports (textual, rich) stay inside :func:`run` so the
5
+ plain CLI paths — ``cswap list``, cron's ``cswap auto --once`` — never pay
6
+ for them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING
12
+
13
+ if TYPE_CHECKING:
14
+ from claude_swap.switcher import ClaudeAccountSwitcher
15
+
16
+
17
+ def run(switcher: "ClaudeAccountSwitcher", start: str = "dashboard") -> int:
18
+ """Run the TUI over an existing switcher. Returns the process exit code.
19
+
20
+ ``start="watch"`` (the ``cswap watch`` command) opens directly on the
21
+ live watch page, stacked over the dashboard.
22
+ """
23
+ from claude_swap.appearance import detect_terminal_background, drain_stdin
24
+ from claude_swap.tui.app import CswapApp
25
+
26
+ # Sense the terminal background while we still own stdin in cooked mode
27
+ # (Textual's driver starts inside app.run()). Always detect so cycling to
28
+ # 'auto' works even when the initial theme is explicit. Both calls are
29
+ # meant to fail safe on their own, but they're wrapped here too: a
30
+ # detection bug must never crash the TUI launch.
31
+ try:
32
+ detected = detect_terminal_background()
33
+ except Exception:
34
+ detected = None
35
+ app = CswapApp(switcher, start=start, detected=detected)
36
+ # Drain any late OSC reply immediately before Textual's driver starts,
37
+ # so it isn't reissued as keystrokes once the app takes over the terminal.
38
+ try:
39
+ drain_stdin()
40
+ except Exception:
41
+ pass
42
+ app.run()
43
+ return app.return_code or 0
claude_swap/tui/app.py ADDED
@@ -0,0 +1,482 @@
1
+ """The claude-swap Textual application.
2
+
3
+ Owns the snapshot poll loop and every mutating action (switch/add/remove),
4
+ so the dashboard, the auto view, and the command palette all drive the same
5
+ code paths. Blocking switcher work always runs in thread workers — the UI
6
+ loop never touches file locks, keychain subprocesses, or the network.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from dataclasses import replace
13
+ from functools import partial
14
+
15
+ from textual.app import App, SuspendNotSupported
16
+ from textual.binding import Binding
17
+ from textual.reactive import reactive
18
+ from textual.worker import WorkerState
19
+
20
+ from claude_swap import printer
21
+ from claude_swap.models import AccountSnapshot, AccountsSnapshot, org_tag_shown
22
+ from claude_swap.snapshot_source import account_identity
23
+ from claude_swap.settings import load_settings, load_ui_settings, set_setting
24
+ from claude_swap.switcher import ClaudeAccountSwitcher
25
+ from claude_swap.tui.autoview import AutoScreen
26
+ from claude_swap.tui.dashboard import DashboardScreen, WatchScreen
27
+ from claude_swap.tui.data import ActionResult, SnapshotSource, format_duration, run_action
28
+ from claude_swap.tui.modals import AddTokenModal, ConfirmModal, OutputModal, TokenForm
29
+ from claude_swap.tui.theme import CSWAP_DARK, CSWAP_LIGHT
30
+
31
+
32
+ class CswapApp(App):
33
+ """claude-swap interactive dashboard."""
34
+
35
+ TITLE = "claude-swap"
36
+ CSS_PATH = "cswap.tcss"
37
+ # No command palette: actions live in the dashboard's nested menu, in
38
+ # their own context — not in a global searchable list.
39
+ ENABLE_COMMAND_PALETTE = False
40
+ BINDINGS = [Binding("ctrl+t", "toggle_theme", "Theme")]
41
+
42
+ POLL_INTERVAL_S = 3.0 # matches the old watch view's recapture cadence
43
+ # Snapshot age stays hidden while polling is healthy (age never exceeds
44
+ # ~POLL_INTERVAL_S); past this it surfaces as a staleness alarm. 60s also
45
+ # keeps format_duration in whole minutes, so the note never ticks per
46
+ # second.
47
+ SNAPSHOT_AGE_NOTE_S = 60.0
48
+
49
+ snapshot: reactive[AccountsSnapshot | None] = reactive(None)
50
+ refresh_status: reactive[str] = reactive("")
51
+ busy: reactive[bool] = reactive(False)
52
+
53
+ def __init__(
54
+ self,
55
+ switcher: ClaudeAccountSwitcher,
56
+ *,
57
+ start: str = "dashboard",
58
+ detected: str | None = None,
59
+ ) -> None:
60
+ super().__init__()
61
+ self.switcher = switcher
62
+ self._start = start # "dashboard" | "watch" (`cswap watch`)
63
+ self._detected = detected # terminal background sensed pre-driver, or None
64
+ self.source = SnapshotSource(switcher)
65
+ self._store_only = False
66
+ self._full_next = False
67
+ self._normal_refreshing = False
68
+ self._store_refreshing = False
69
+ self._normal_started_at: float | None = None
70
+ self._refresh_generation = 0
71
+ self._applied_generation = 0
72
+ self._last_refresh_error = ""
73
+ # The auto-switch lines, drawn as ticks on the status strip's bars
74
+ # everywhere: the threshold on the 5h row, the weekly line (when
75
+ # set) on the 7d and per-model rows. Missing/invalid settings fall
76
+ # back to the default.
77
+ try:
78
+ loaded = load_settings(switcher.backup_dir)
79
+ self.threshold_pct: float | None = loaded.threshold
80
+ self.weekly_threshold_pct: float | None = loaded.weekly_threshold
81
+ except Exception:
82
+ self.threshold_pct = None
83
+ self.weekly_threshold_pct = None
84
+ try:
85
+ ui = load_ui_settings(switcher.backup_dir)
86
+ self._theme_name, self.org_tag = ui.theme, ui.org_tag
87
+ except Exception:
88
+ self._theme_name, self.org_tag = "auto", "auto"
89
+
90
+ def on_mount(self) -> None:
91
+ self.register_theme(CSWAP_DARK)
92
+ self.register_theme(CSWAP_LIGHT)
93
+ resolved = self._resolved_theme()
94
+ # We own the theme; $TEXTUAL_THEME is intentionally not honoured.
95
+ self.theme = f"cswap-{resolved}"
96
+ printer.set_theme(resolved)
97
+ self.push_screen(DashboardScreen())
98
+ if self._start == "watch":
99
+ # Stacked over the dashboard so Esc lands there, not on exit.
100
+ self.push_screen(WatchScreen())
101
+ self.set_interval(self.POLL_INTERVAL_S, self._tick)
102
+ self.set_interval(1.0, self._update_refresh_status)
103
+ self._tick()
104
+
105
+ # -- snapshot poll loop ---------------------------------------------------
106
+
107
+ def _tick(self) -> None:
108
+ """Start one eligible refresh lane.
109
+
110
+ Normal mode prefers the fetch-enabled lane. When that lane is blocked,
111
+ the poll tick may still observe another process's store update through
112
+ one store-only lane. Auto mode already has an engine fetching, so it
113
+ launches only store-only snapshots.
114
+ """
115
+ if self._store_only:
116
+ self._start_store_refresh()
117
+ elif not self._normal_refreshing:
118
+ full, self._full_next = self._full_next, False
119
+ self._start_normal_refresh(full=full)
120
+ else:
121
+ self._start_store_refresh()
122
+
123
+ def _start_normal_refresh(self, *, full: bool) -> None:
124
+ if self._normal_refreshing:
125
+ return
126
+ self._normal_refreshing = True
127
+ self._normal_started_at = time.time()
128
+ generation = self._next_refresh_generation()
129
+ self._update_refresh_status()
130
+ self.run_worker(
131
+ partial(self._refresh_blocking, generation, "normal", full, False),
132
+ thread=True,
133
+ group="refresh-normal",
134
+ exit_on_error=False,
135
+ name="snapshot-refresh",
136
+ )
137
+
138
+ def _start_store_refresh(self) -> None:
139
+ if self._store_refreshing:
140
+ return
141
+ self._store_refreshing = True
142
+ generation = self._next_refresh_generation()
143
+ self._update_refresh_status()
144
+ self.run_worker(
145
+ partial(self._refresh_blocking, generation, "store", False, True),
146
+ thread=True,
147
+ group="refresh-store",
148
+ exit_on_error=False,
149
+ name="snapshot-store-refresh",
150
+ )
151
+
152
+ def _next_refresh_generation(self) -> int:
153
+ self._refresh_generation += 1
154
+ return self._refresh_generation
155
+
156
+ def _refresh_blocking(
157
+ self, generation: int, lane: str, full: bool, store_only: bool
158
+ ) -> None:
159
+ snap = self.source.take(full=full, store_only=store_only)
160
+ self.call_from_thread(self._apply_snapshot, generation, lane, snap)
161
+ if self._store_only:
162
+ self.source.refresh_plans()
163
+
164
+ def _apply_snapshot(
165
+ self, generation: int, lane: str, snap: AccountsSnapshot
166
+ ) -> None:
167
+ if lane == "normal":
168
+ self._normal_refreshing = False
169
+ self._normal_started_at = None
170
+ else:
171
+ self._store_refreshing = False
172
+ self._last_refresh_error = ""
173
+ if generation >= self._applied_generation:
174
+ self._applied_generation = generation
175
+ self.snapshot = snap
176
+ elif self.snapshot is not None:
177
+ # A later-started store repaint owns account metadata, but the
178
+ # older worker may have completed a genuinely newer provider fetch.
179
+ # SnapshotSource has already rejected per-account regressions, so
180
+ # merge its canonical usage rows without restoring stale metadata.
181
+ current = self.snapshot
182
+ incoming = {acc.number: acc for acc in snap.accounts}
183
+ accounts = tuple(
184
+ replace(acc, usage=other.usage)
185
+ if (
186
+ (other := incoming.get(acc.number)) is not None
187
+ and account_identity(acc) == account_identity(other)
188
+ )
189
+ else acc
190
+ for acc in current.accounts
191
+ )
192
+ self.snapshot = replace(
193
+ current,
194
+ accounts=accounts,
195
+ taken_at=max(current.taken_at, snap.taken_at),
196
+ )
197
+ self._update_refresh_status()
198
+
199
+ def _update_refresh_status(self) -> None:
200
+ parts: list[str] = []
201
+ now = time.time()
202
+ if self.snapshot is not None:
203
+ age = max(0.0, now - self.snapshot.taken_at)
204
+ if age >= self.SNAPSHOT_AGE_NOTE_S:
205
+ parts.append(f"snapshot {format_duration(age)} ago")
206
+ if self._normal_refreshing and self._normal_started_at is not None:
207
+ elapsed = now - self._normal_started_at
208
+ if elapsed >= self.POLL_INTERVAL_S:
209
+ parts.append(f"refreshing {format_duration(elapsed)}")
210
+ self.refresh_status = " · ".join(parts)
211
+
212
+ def request_refresh(self, *, full: bool = False) -> None:
213
+ if full:
214
+ self._full_next = True
215
+ self._tick()
216
+
217
+ def set_store_only(self, value: bool) -> None:
218
+ """Auto screen: the engine fetches, the poller only reads the store."""
219
+ self._store_only = value
220
+ self.request_refresh()
221
+
222
+ def on_worker_state_changed(self, event) -> None:
223
+ if event.state is not WorkerState.ERROR:
224
+ return
225
+ if event.worker.group in {"refresh-normal", "refresh-store"}:
226
+ if event.worker.group == "refresh-normal":
227
+ self._normal_refreshing = False
228
+ self._normal_started_at = None
229
+ else:
230
+ self._store_refreshing = False
231
+ self._update_refresh_status()
232
+ msg = str(event.worker.error)
233
+ if msg != self._last_refresh_error:
234
+ self._last_refresh_error = msg
235
+ lane = "store refresh" if event.worker.group == "refresh-store" else "refresh"
236
+ self.notify(
237
+ f"{lane.capitalize()} failed: {msg}", severity="warning", timeout=6
238
+ )
239
+ elif event.worker.group == "action":
240
+ self.busy = False
241
+ self.notify(f"Action failed: {event.worker.error}", severity="error")
242
+ elif event.worker.group == "engine":
243
+ self.notify(
244
+ f"Auto-switch engine stopped: {event.worker.error}",
245
+ severity="error",
246
+ )
247
+
248
+ # -- mutating actions (single-flight, captured, off-thread) ---------------
249
+
250
+ def _start_action(self, label: str, fn, *, show_output: bool = False) -> None:
251
+ if self.busy:
252
+ self.notify("Another action is still running", severity="warning")
253
+ return
254
+ self.busy = True
255
+ self.run_worker(
256
+ partial(self._action_blocking, label, fn, show_output),
257
+ thread=True,
258
+ group="action",
259
+ exit_on_error=False,
260
+ name=label,
261
+ )
262
+
263
+ def _action_blocking(self, label: str, fn, show_output: bool) -> None:
264
+ result = run_action(fn)
265
+ self.call_from_thread(self._action_done, label, result, show_output)
266
+
267
+ def _action_done(
268
+ self, label: str, result: ActionResult, show_output: bool
269
+ ) -> None:
270
+ self.busy = False
271
+ self.request_refresh()
272
+ if not result.ok:
273
+ self.push_screen(OutputModal(f"{label} — failed", result.output))
274
+ return
275
+ payload = result.payload or {}
276
+ if "switched" in payload:
277
+ if payload.get("switched"):
278
+ to = payload.get("to") or {}
279
+ target = to.get("email") or f"account {to.get('number')}"
280
+ self.notify(f"Switched to {target}", title="Switch")
281
+ else:
282
+ reason = str(payload.get("reason") or "no switch performed")
283
+ self.notify(reason, title="No switch", severity="warning")
284
+ return
285
+ if show_output and result.output.strip():
286
+ self.push_screen(OutputModal(label, result.output))
287
+ elif result.first_line:
288
+ self.notify(result.first_line)
289
+
290
+ # -- account operations ----------------------------------------------------
291
+
292
+ def do_switch(self, number: str) -> None:
293
+ self._start_action(
294
+ f"Switch to account {number}",
295
+ partial(self.switcher.switch_to, number, json_output=True),
296
+ )
297
+
298
+ def action_switch_best(self) -> None:
299
+ self._start_action(
300
+ "Switch (best)",
301
+ partial(self.switcher.switch, strategy="best", json_output=True),
302
+ )
303
+
304
+ def do_toggle_disabled(self, number: str) -> None:
305
+ """Hold the account out of auto-rotation, or return it — reads its
306
+ current state from the live snapshot to pick the direction."""
307
+ snap = self.snapshot
308
+ acc = next(
309
+ (a for a in (snap.accounts if snap else ()) if a.number == number), None
310
+ )
311
+ if acc is None:
312
+ return
313
+ target = not acc.disabled
314
+ verb = "Disable" if target else "Enable"
315
+ self._start_action(
316
+ f"{verb} account {number}",
317
+ partial(self.switcher.set_account_disabled, number, target),
318
+ )
319
+
320
+ def confirm_remove(self, number: str, email: str) -> None:
321
+ self.push_screen(
322
+ ConfirmModal(
323
+ f"Remove account {number} ({email})?\n\n"
324
+ "Its stored credentials and config backup are deleted.",
325
+ title="Remove account",
326
+ yes_label="Remove",
327
+ ),
328
+ partial(self._on_remove_confirm, number),
329
+ )
330
+
331
+ def _on_remove_confirm(self, number: str, confirmed: bool | None) -> None:
332
+ if confirmed:
333
+ self._start_action(
334
+ f"Remove account {number}",
335
+ partial(self.switcher.remove_account, number, assume_yes=True),
336
+ )
337
+
338
+ def action_add_current(self) -> None:
339
+ self.push_screen(
340
+ ConfirmModal(
341
+ "Back up the current Claude Code login as a managed account?\n\n"
342
+ "If this account is already managed, its stored credentials "
343
+ "are refreshed in place.",
344
+ title="Add account",
345
+ yes_label="Add",
346
+ ),
347
+ self._on_add_confirm,
348
+ )
349
+
350
+ def _on_add_confirm(self, confirmed: bool | None) -> None:
351
+ if confirmed:
352
+ self._start_action(
353
+ "Add current login",
354
+ partial(self.switcher.add_account),
355
+ show_output=True,
356
+ )
357
+
358
+ def action_add_signin(self) -> None:
359
+ self.push_screen(
360
+ ConfirmModal(
361
+ "Sign in to another account through Claude Code?\n\n"
362
+ "The dashboard steps aside and this terminal shows a sign-in "
363
+ "link: open it in a private window, sign in, and paste the "
364
+ "code back. The account you are using stays active.",
365
+ title="Add account",
366
+ yes_label="Sign in",
367
+ ),
368
+ self._on_signin_confirm,
369
+ )
370
+
371
+ def _on_signin_confirm(self, confirmed: bool | None) -> None:
372
+ """Hand the terminal to ``cswap login`` and show what it reported.
373
+
374
+ The one action that blocks the UI loop, on purpose: Claude Code's
375
+ sign-in is a terminal prompt, so the app is suspended until it
376
+ returns. ``run_action`` captures what cswap prints for the result
377
+ modal; the sign-in itself is a child process and writes to the
378
+ terminal directly.
379
+ """
380
+ if not confirmed:
381
+ return
382
+ if self.busy:
383
+ self.notify("Another action is still running", severity="warning")
384
+ return
385
+ try:
386
+ with self.suspend():
387
+ result = run_action(self.switcher.login_account)
388
+ except SuspendNotSupported:
389
+ self.notify(
390
+ "This terminal cannot be handed over. Run: cswap login",
391
+ severity="warning",
392
+ )
393
+ return
394
+ self._action_done("Sign in to another account", result, True)
395
+
396
+ def action_add_token(self) -> None:
397
+ self.push_screen(AddTokenModal(), self._on_token_form)
398
+
399
+ def _on_token_form(self, form: TokenForm | None) -> None:
400
+ if form is None:
401
+ return
402
+ run = partial(
403
+ self._start_action,
404
+ "Add account from token",
405
+ partial(
406
+ self.switcher.add_account_from_token,
407
+ token=form.token,
408
+ email=form.email,
409
+ slot=form.slot,
410
+ assume_yes=True,
411
+ ),
412
+ show_output=True,
413
+ )
414
+ occupant = self._slot_occupant(form.slot)
415
+ if occupant is not None:
416
+ self.push_screen(
417
+ ConfirmModal(
418
+ f"Slot {form.slot} is occupied by {occupant}. Overwrite?",
419
+ title="Overwrite slot",
420
+ yes_label="Overwrite",
421
+ ),
422
+ lambda confirmed: run() if confirmed else None,
423
+ )
424
+ else:
425
+ run()
426
+
427
+ def _slot_occupant(self, slot: int | None) -> str | None:
428
+ if slot is None or self.snapshot is None:
429
+ return None
430
+ for acc in self.snapshot.accounts:
431
+ if acc.number == str(slot):
432
+ return acc.email
433
+ return None
434
+
435
+ # -- navigation -------------------------------------------------------------
436
+
437
+ def action_refresh_full(self) -> None:
438
+ self.request_refresh(full=True)
439
+ self.notify("Refreshing usage…", timeout=2)
440
+
441
+ def action_open_auto(self) -> None:
442
+ if isinstance(self.screen, AutoScreen):
443
+ return
444
+ self.push_screen(AutoScreen())
445
+
446
+ def action_open_watch(self) -> None:
447
+ if isinstance(self.screen, WatchScreen):
448
+ return
449
+ self.push_screen(WatchScreen())
450
+
451
+ def tag_shown(self, acc: AccountSnapshot) -> bool:
452
+ """Whether ``ui.orgTag`` draws ``acc``'s org tag in any TUI account view."""
453
+ accounts = self.snapshot.accounts if self.snapshot else ()
454
+ return org_tag_shown(self.org_tag, acc.email, [a.email for a in accounts])
455
+
456
+ # -- theme --------------------------------------------------------------
457
+
458
+ def _resolved_theme(self) -> str:
459
+ """Concrete 'dark'/'light' for the current setting; auto → detected → dark."""
460
+ if self._theme_name == "auto":
461
+ return self._detected or "dark"
462
+ return self._theme_name
463
+
464
+ def apply_theme(self, name: str) -> None:
465
+ """Switch the live theme: TUI + captured printer output + persistence.
466
+
467
+ ``name`` is the setting; ``auto`` resolves against the pre-driver
468
+ detection (never re-probes mid-session)."""
469
+ self._theme_name = name
470
+ resolved = self._resolved_theme()
471
+ self.theme = f"cswap-{resolved}"
472
+ printer.set_theme(resolved)
473
+ try:
474
+ set_setting(self.switcher.backup_dir, "ui.theme", name)
475
+ except Exception as exc: # persistence is best-effort; never crash the UI
476
+ self.notify(f"Could not save theme: {exc}", severity="warning")
477
+
478
+ def action_toggle_theme(self) -> None:
479
+ order = ("dark", "light", "auto")
480
+ nxt = order[(order.index(self._theme_name) + 1) % len(order)]
481
+ self.apply_theme(nxt)
482
+ self.notify(f"Theme: {nxt}")