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.
- claude_swap/__init__.py +24 -0
- claude_swap/__main__.py +6 -0
- claude_swap/app_bundle.py +330 -0
- claude_swap/appearance.py +219 -0
- claude_swap/autoswitch.py +3065 -0
- claude_swap/cache.py +44 -0
- claude_swap/claude_locks.py +279 -0
- claude_swap/cli.py +2265 -0
- claude_swap/credentials.py +2156 -0
- claude_swap/exceptions.py +102 -0
- claude_swap/fsutil.py +409 -0
- claude_swap/json_output.py +455 -0
- claude_swap/launch_agent.py +862 -0
- claude_swap/lines.py +153 -0
- claude_swap/list_view.py +371 -0
- claude_swap/locking.py +87 -0
- claude_swap/logging_config.py +64 -0
- claude_swap/macos_keychain.py +240 -0
- claude_swap/mappings.py +127 -0
- claude_swap/menubar.py +1433 -0
- claude_swap/migrations.py +360 -0
- claude_swap/models.py +329 -0
- claude_swap/oauth.py +1628 -0
- claude_swap/pace.py +161 -0
- claude_swap/paths.py +250 -0
- claude_swap/poll_policy.py +337 -0
- claude_swap/printer.py +252 -0
- claude_swap/process_detection.py +370 -0
- claude_swap/session.py +2696 -0
- claude_swap/settings.py +827 -0
- claude_swap/signin.py +238 -0
- claude_swap/snapshot_source.py +121 -0
- claude_swap/spawn.py +135 -0
- claude_swap/subscription.py +349 -0
- claude_swap/switcher.py +9807 -0
- claude_swap/transfer.py +807 -0
- claude_swap/tui/__init__.py +43 -0
- claude_swap/tui/app.py +482 -0
- claude_swap/tui/autoview.py +381 -0
- claude_swap/tui/cswap.tcss +205 -0
- claude_swap/tui/dashboard.py +434 -0
- claude_swap/tui/data.py +194 -0
- claude_swap/tui/modals.py +159 -0
- claude_swap/tui/theme.py +88 -0
- claude_swap/tui/widgets.py +544 -0
- claude_swap/update_check.py +509 -0
- claude_swap/usage_bars.py +208 -0
- claude_swap/usage_rows.py +160 -0
- claude_swap/usage_store.py +1429 -0
- llmswap/AGENTS.md +11 -0
- llmswap/__init__.py +3 -0
- llmswap/__main__.py +4 -0
- llmswap/cli.py +535 -0
- llmswap/config.py +101 -0
- llmswap/httpjson.py +50 -0
- llmswap/jwt.py +20 -0
- llmswap/menubar.py +218 -0
- llmswap/model.py +172 -0
- llmswap/paths.py +41 -0
- llmswap/providers/AGENTS.md +12 -0
- llmswap/providers/base.py +619 -0
- llmswap/providers/claude.py +187 -0
- llmswap/providers/codex.py +274 -0
- llmswap/providers/gemini.py +80 -0
- llmswap/providers/registry.py +30 -0
- llmswap/render.py +127 -0
- llmswap/rotate.py +102 -0
- llmswap/store.py +138 -0
- llmswap/tui.py +182 -0
- llmswap/usage_cache.py +72 -0
- llmswap/warm/plan.py +118 -0
- llmswap/warm/runner.py +175 -0
- llmswap/warm/schedule.py +264 -0
- llmswap_cli-1.0.0.dist-info/METADATA +181 -0
- llmswap_cli-1.0.0.dist-info/RECORD +78 -0
- llmswap_cli-1.0.0.dist-info/WHEEL +4 -0
- llmswap_cli-1.0.0.dist-info/entry_points.txt +5 -0
- llmswap_cli-1.0.0.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
"""Dashboard: static account overview on top, a nested action menu below.
|
|
2
|
+
|
|
3
|
+
The accounts panel is the monitor (active account full-size, others as
|
|
4
|
+
one-line minis); the arrow keys drive the *menu*, not the accounts. Anything
|
|
5
|
+
account-targeted opens a context of its own:
|
|
6
|
+
|
|
7
|
+
- ``s`` / menu "Switch account" → :class:`SwitchScreen` — every account
|
|
8
|
+
full-size, Enter switches, pops back.
|
|
9
|
+
- ``w`` / menu "Watch accounts" / ``cswap watch`` → :class:`WatchScreen` —
|
|
10
|
+
the same full cards but read-only: a live monitor. ``s`` arms selection
|
|
11
|
+
(cursor appears on the active account), Enter switches and *stays
|
|
12
|
+
watching*, Esc disarms.
|
|
13
|
+
- "Remove account" nests into a submenu listing the accounts.
|
|
14
|
+
|
|
15
|
+
No global command palette: actions live where their context is.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from functools import partial
|
|
21
|
+
from typing import TYPE_CHECKING, Callable
|
|
22
|
+
|
|
23
|
+
from textual.app import ComposeResult
|
|
24
|
+
from textual.binding import Binding
|
|
25
|
+
from textual.screen import Screen
|
|
26
|
+
from textual.widgets import Footer, ListView, Static
|
|
27
|
+
|
|
28
|
+
from claude_swap.models import AccountsSnapshot
|
|
29
|
+
from claude_swap.tui.widgets import AccountItem, AccountsPanel, MenuItem
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from claude_swap.tui.app import CswapApp
|
|
33
|
+
|
|
34
|
+
FLASH_S = 1.5 # how long a just-refreshed row stays highlighted
|
|
35
|
+
|
|
36
|
+
MenuEntries = list[tuple[str, str]] # (label, action_id)
|
|
37
|
+
|
|
38
|
+
_BACK = ("← back", "back")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class DashboardScreen(Screen):
|
|
42
|
+
BINDINGS = [
|
|
43
|
+
Binding("s", "open_switch", "Switch accounts"),
|
|
44
|
+
Binding("w", "app.open_watch", "Watch"),
|
|
45
|
+
Binding("escape,left", "menu_back", "Back", show=False),
|
|
46
|
+
Binding("q", "app.quit", "Quit"),
|
|
47
|
+
# Power shortcuts; the menu is the discoverable path.
|
|
48
|
+
Binding("g", "app.open_auto", "Auto view", show=False),
|
|
49
|
+
Binding("f", "app.refresh_full", "Refresh usage", show=False),
|
|
50
|
+
Binding("j", "cursor_down", show=False),
|
|
51
|
+
Binding("k", "cursor_up", show=False),
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
app: "CswapApp"
|
|
55
|
+
|
|
56
|
+
def __init__(self) -> None:
|
|
57
|
+
super().__init__()
|
|
58
|
+
# Stack of (title, entries); depth 1 = root menu.
|
|
59
|
+
self._menu_stack: list[tuple[str, MenuEntries]] = []
|
|
60
|
+
|
|
61
|
+
def compose(self) -> ComposeResult:
|
|
62
|
+
yield AccountsPanel(id="accounts-panel")
|
|
63
|
+
yield Static("", id="menu-title")
|
|
64
|
+
yield ListView(id="menu")
|
|
65
|
+
yield Footer()
|
|
66
|
+
|
|
67
|
+
async def on_mount(self) -> None:
|
|
68
|
+
self.query_one("#menu", ListView).focus()
|
|
69
|
+
await self._push_menu("menu", self._root_entries())
|
|
70
|
+
|
|
71
|
+
# -- menu plumbing --------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
def _root_entries(self) -> MenuEntries:
|
|
74
|
+
# No "Refresh" entry: every view auto-refreshes, so a menu item would
|
|
75
|
+
# wrongly imply the user has to. `f` stays as a hidden escape hatch.
|
|
76
|
+
return [
|
|
77
|
+
("Switch account…", "switch"),
|
|
78
|
+
("Watch accounts", "watch"),
|
|
79
|
+
("Auto-switch view", "auto"),
|
|
80
|
+
("Add account…", "add-menu"),
|
|
81
|
+
("Disable / enable account…", "disable-menu"),
|
|
82
|
+
("Remove account…", "remove-menu"),
|
|
83
|
+
("Theme…", "theme-menu"),
|
|
84
|
+
("Quit", "quit"),
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
def _add_entries(self) -> MenuEntries:
|
|
88
|
+
return [
|
|
89
|
+
("Sign in to another account…", "add-signin"),
|
|
90
|
+
("From current Claude Code login", "add-login"),
|
|
91
|
+
("From a setup-token / API key…", "add-token"),
|
|
92
|
+
_BACK,
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
def _remove_entries(self) -> MenuEntries:
|
|
96
|
+
snap = self.app.snapshot
|
|
97
|
+
entries: MenuEntries = [
|
|
98
|
+
(
|
|
99
|
+
f"{acc.number} {f'{acc.alias} ({acc.email})' if acc.alias else acc.email}"
|
|
100
|
+
+ (f" [{acc.display_tag}]" if self.app.tag_shown(acc) else ""),
|
|
101
|
+
f"remove:{acc.number}",
|
|
102
|
+
)
|
|
103
|
+
for acc in (snap.accounts if snap else ())
|
|
104
|
+
]
|
|
105
|
+
entries.append(_BACK)
|
|
106
|
+
return entries
|
|
107
|
+
|
|
108
|
+
def _disable_entries(self) -> MenuEntries:
|
|
109
|
+
"""One row per account, labelled with its current state and the action
|
|
110
|
+
selecting it will take (enable a disabled one, disable an active one)."""
|
|
111
|
+
snap = self.app.snapshot
|
|
112
|
+
entries: MenuEntries = []
|
|
113
|
+
for acc in (snap.accounts if snap else ()):
|
|
114
|
+
name = f"{acc.alias} ({acc.email})" if acc.alias else acc.email
|
|
115
|
+
action = "→ enable" if acc.disabled else "→ disable"
|
|
116
|
+
state = " (disabled)" if acc.disabled else ""
|
|
117
|
+
entries.append(
|
|
118
|
+
(f"{acc.number} {name}{state} {action}", f"disable:{acc.number}")
|
|
119
|
+
)
|
|
120
|
+
entries.append(_BACK)
|
|
121
|
+
return entries
|
|
122
|
+
|
|
123
|
+
def _theme_entries(self) -> MenuEntries:
|
|
124
|
+
"""dark / light / auto, with the active setting marked."""
|
|
125
|
+
current = self.app._theme_name
|
|
126
|
+
entries: MenuEntries = [
|
|
127
|
+
(f"{'●' if name == current else ' '} {name}", f"theme:{name}")
|
|
128
|
+
for name in ("dark", "light", "auto")
|
|
129
|
+
]
|
|
130
|
+
entries.append(_BACK)
|
|
131
|
+
return entries
|
|
132
|
+
|
|
133
|
+
async def _push_menu(self, title: str, entries: MenuEntries) -> None:
|
|
134
|
+
self._menu_stack.append((title, entries))
|
|
135
|
+
await self._render_menu()
|
|
136
|
+
|
|
137
|
+
async def _pop_menu(self) -> None:
|
|
138
|
+
if len(self._menu_stack) > 1:
|
|
139
|
+
self._menu_stack.pop()
|
|
140
|
+
await self._render_menu()
|
|
141
|
+
|
|
142
|
+
async def _render_menu(self) -> None:
|
|
143
|
+
title, entries = self._menu_stack[-1]
|
|
144
|
+
crumb = " › ".join(t for t, _ in self._menu_stack)
|
|
145
|
+
self.query_one("#menu-title", Static).update(crumb)
|
|
146
|
+
menu = self.query_one("#menu", ListView)
|
|
147
|
+
await menu.clear()
|
|
148
|
+
await menu.extend(
|
|
149
|
+
MenuItem(label, action_id, muted=(action_id == "back"))
|
|
150
|
+
for label, action_id in entries
|
|
151
|
+
)
|
|
152
|
+
menu.index = 0
|
|
153
|
+
|
|
154
|
+
async def on_list_view_selected(self, event: ListView.Selected) -> None:
|
|
155
|
+
item = event.item
|
|
156
|
+
if isinstance(item, MenuItem):
|
|
157
|
+
await self._dispatch(item.action_id)
|
|
158
|
+
|
|
159
|
+
async def _dispatch(self, action_id: str) -> None:
|
|
160
|
+
app = self.app
|
|
161
|
+
actions: dict[str, Callable[[], None]] = {
|
|
162
|
+
"switch": self.action_open_switch,
|
|
163
|
+
"watch": app.action_open_watch,
|
|
164
|
+
"auto": app.action_open_auto,
|
|
165
|
+
"add-signin": app.action_add_signin,
|
|
166
|
+
"add-login": app.action_add_current,
|
|
167
|
+
"add-token": app.action_add_token,
|
|
168
|
+
"quit": app.exit,
|
|
169
|
+
}
|
|
170
|
+
if action_id == "back":
|
|
171
|
+
await self._pop_menu()
|
|
172
|
+
elif action_id == "add-menu":
|
|
173
|
+
await self._push_menu("add account", self._add_entries())
|
|
174
|
+
elif action_id == "remove-menu":
|
|
175
|
+
await self._push_menu("remove account", self._remove_entries())
|
|
176
|
+
elif action_id.startswith("remove:"):
|
|
177
|
+
number = action_id.split(":", 1)[1]
|
|
178
|
+
snap = app.snapshot
|
|
179
|
+
email = next(
|
|
180
|
+
(a.email for a in (snap.accounts if snap else ()) if a.number == number),
|
|
181
|
+
"?",
|
|
182
|
+
)
|
|
183
|
+
app.confirm_remove(number, email)
|
|
184
|
+
elif action_id == "theme-menu":
|
|
185
|
+
await self._push_menu("theme", self._theme_entries())
|
|
186
|
+
elif action_id.startswith("theme:"):
|
|
187
|
+
name = action_id.split(":", 1)[1]
|
|
188
|
+
app.apply_theme(name)
|
|
189
|
+
app.notify(f"Theme: {name}")
|
|
190
|
+
await self._pop_menu()
|
|
191
|
+
elif action_id == "disable-menu":
|
|
192
|
+
await self._push_menu("disable / enable", self._disable_entries())
|
|
193
|
+
elif action_id.startswith("disable:"):
|
|
194
|
+
number = action_id.split(":", 1)[1]
|
|
195
|
+
app.do_toggle_disabled(number)
|
|
196
|
+
await self._pop_menu()
|
|
197
|
+
else:
|
|
198
|
+
actions[action_id]()
|
|
199
|
+
|
|
200
|
+
# -- actions ----------------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
def action_open_switch(self) -> None:
|
|
203
|
+
if not isinstance(self.app.screen, SwitchScreen):
|
|
204
|
+
self.app.push_screen(SwitchScreen())
|
|
205
|
+
|
|
206
|
+
async def action_menu_back(self) -> None:
|
|
207
|
+
await self._pop_menu()
|
|
208
|
+
|
|
209
|
+
def action_cursor_down(self) -> None:
|
|
210
|
+
self.query_one("#menu", ListView).action_cursor_down()
|
|
211
|
+
|
|
212
|
+
def action_cursor_up(self) -> None:
|
|
213
|
+
self.query_one("#menu", ListView).action_cursor_up()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class AccountListScreen(Screen):
|
|
217
|
+
"""Shared machinery: a live ListView of full account cards.
|
|
218
|
+
|
|
219
|
+
Subclasses decide what the cursor does — :class:`SwitchScreen` is
|
|
220
|
+
selection-first, :class:`WatchScreen` is a monitor that can arm
|
|
221
|
+
selection on demand.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
app: "CswapApp"
|
|
225
|
+
|
|
226
|
+
def __init__(self) -> None:
|
|
227
|
+
super().__init__()
|
|
228
|
+
self._numbers: list[str] = []
|
|
229
|
+
self._stamps: dict[str, float | None] = {}
|
|
230
|
+
|
|
231
|
+
def compose(self) -> ComposeResult:
|
|
232
|
+
yield Static("", id="list-title")
|
|
233
|
+
yield ListView(id="accounts")
|
|
234
|
+
yield Footer()
|
|
235
|
+
|
|
236
|
+
def on_mount(self) -> None:
|
|
237
|
+
self.watch(self.app, "snapshot", self._on_snapshot)
|
|
238
|
+
|
|
239
|
+
async def _on_snapshot(self, snap: AccountsSnapshot | None) -> None:
|
|
240
|
+
if snap is None:
|
|
241
|
+
return
|
|
242
|
+
listview = self.query_one("#accounts", ListView)
|
|
243
|
+
numbers = [acc.number for acc in snap.accounts]
|
|
244
|
+
if numbers != self._numbers:
|
|
245
|
+
first_build = not self._numbers
|
|
246
|
+
previous = listview.index
|
|
247
|
+
await listview.clear()
|
|
248
|
+
await listview.extend(AccountItem(acc) for acc in snap.accounts)
|
|
249
|
+
self._numbers = numbers
|
|
250
|
+
listview.index = (
|
|
251
|
+
self._index_after_build(snap, first_build, previous)
|
|
252
|
+
if numbers
|
|
253
|
+
else None
|
|
254
|
+
)
|
|
255
|
+
else:
|
|
256
|
+
for item, acc in zip(listview.query(AccountItem), snap.accounts):
|
|
257
|
+
item.set_account(acc)
|
|
258
|
+
self._flash_updated(snap, listview)
|
|
259
|
+
|
|
260
|
+
def _index_after_build(
|
|
261
|
+
self, snap: AccountsSnapshot, first_build: bool, previous: int | None
|
|
262
|
+
) -> int | None:
|
|
263
|
+
"""Where the cursor lands after the list is (re)built."""
|
|
264
|
+
if first_build:
|
|
265
|
+
return self._active_index(snap)
|
|
266
|
+
return min(previous or 0, len(snap.accounts) - 1)
|
|
267
|
+
|
|
268
|
+
def _active_index(self, snap: AccountsSnapshot) -> int:
|
|
269
|
+
return next(
|
|
270
|
+
(
|
|
271
|
+
i
|
|
272
|
+
for i, acc in enumerate(snap.accounts)
|
|
273
|
+
if acc.number == snap.active_number
|
|
274
|
+
),
|
|
275
|
+
0,
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
def _flash_updated(self, snap: AccountsSnapshot, listview: ListView) -> None:
|
|
279
|
+
"""Briefly highlight rows whose stored measurement just advanced."""
|
|
280
|
+
new_stamps = {acc.number: acc.usage.fetched_at for acc in snap.accounts}
|
|
281
|
+
if self._stamps:
|
|
282
|
+
changed = {
|
|
283
|
+
num
|
|
284
|
+
for num, ts in new_stamps.items()
|
|
285
|
+
if ts is not None and ts != self._stamps.get(num)
|
|
286
|
+
}
|
|
287
|
+
for item in listview.query(AccountItem):
|
|
288
|
+
if item.number in changed and not item.has_class("flash"):
|
|
289
|
+
item.add_class("flash")
|
|
290
|
+
self.set_timer(FLASH_S, partial(item.remove_class, "flash"))
|
|
291
|
+
self._stamps = new_stamps
|
|
292
|
+
|
|
293
|
+
def action_cursor_down(self) -> None:
|
|
294
|
+
self.query_one("#accounts", ListView).action_cursor_down()
|
|
295
|
+
|
|
296
|
+
def action_cursor_up(self) -> None:
|
|
297
|
+
self.query_one("#accounts", ListView).action_cursor_up()
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class SwitchScreen(AccountListScreen):
|
|
301
|
+
"""All accounts, full-size and alive: arrows pick, Enter switches."""
|
|
302
|
+
|
|
303
|
+
BINDINGS = [
|
|
304
|
+
# priority: outranks the focused ListView's own (hidden) enter binding
|
|
305
|
+
# so "Switch" is visible in the footer; the action delegates right back
|
|
306
|
+
# to the list cursor, so behavior is identical.
|
|
307
|
+
Binding("enter", "select_highlighted", "Switch", priority=True),
|
|
308
|
+
Binding("b", "app.switch_best", "Best pick"),
|
|
309
|
+
Binding("escape,q,s", "back", "Back"),
|
|
310
|
+
Binding("j", "cursor_down", show=False),
|
|
311
|
+
Binding("k", "cursor_up", show=False),
|
|
312
|
+
]
|
|
313
|
+
|
|
314
|
+
def on_mount(self) -> None:
|
|
315
|
+
self.query_one("#list-title", Static).update("switch to which account?")
|
|
316
|
+
self.query_one("#accounts", ListView).focus()
|
|
317
|
+
super().on_mount()
|
|
318
|
+
|
|
319
|
+
def on_list_view_selected(self, event: ListView.Selected) -> None:
|
|
320
|
+
item = event.item
|
|
321
|
+
if isinstance(item, AccountItem):
|
|
322
|
+
self.app.do_switch(item.number)
|
|
323
|
+
self.app.pop_screen()
|
|
324
|
+
|
|
325
|
+
def action_select_highlighted(self) -> None:
|
|
326
|
+
listview = self.query_one("#accounts", ListView)
|
|
327
|
+
if listview.display:
|
|
328
|
+
listview.action_select_cursor()
|
|
329
|
+
|
|
330
|
+
def action_back(self) -> None:
|
|
331
|
+
self.app.pop_screen()
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class WatchScreen(AccountListScreen):
|
|
335
|
+
"""Live monitor of every account, full detail, hands-off by default.
|
|
336
|
+
|
|
337
|
+
``s`` arms selection (cursor appears on the active account); Enter then
|
|
338
|
+
switches and stays here — you keep watching on the new account. Esc
|
|
339
|
+
disarms selection first, then leaves the screen.
|
|
340
|
+
"""
|
|
341
|
+
|
|
342
|
+
_WATCH_TITLE = "watching all accounts"
|
|
343
|
+
_SELECT_TITLE = "switch to which account? · enter confirm · esc cancel"
|
|
344
|
+
|
|
345
|
+
BINDINGS = [
|
|
346
|
+
Binding("s", "toggle_select", "Switch"),
|
|
347
|
+
Binding("enter", "select_highlighted", "Confirm", priority=True),
|
|
348
|
+
Binding("f", "app.refresh_full", "Refresh", show=False),
|
|
349
|
+
Binding("escape,q", "back", "Back"),
|
|
350
|
+
Binding("down,j", "nav_down", show=False),
|
|
351
|
+
Binding("up,k", "nav_up", show=False),
|
|
352
|
+
]
|
|
353
|
+
|
|
354
|
+
def __init__(self) -> None:
|
|
355
|
+
super().__init__()
|
|
356
|
+
self._selecting = False
|
|
357
|
+
|
|
358
|
+
def on_mount(self) -> None:
|
|
359
|
+
self.watch(self.app, "refresh_status", self._on_refresh_status)
|
|
360
|
+
self.query_one("#list-title", Static).update(self._title_text())
|
|
361
|
+
super().on_mount()
|
|
362
|
+
|
|
363
|
+
def _title_text(self) -> str:
|
|
364
|
+
if self._selecting:
|
|
365
|
+
return self._SELECT_TITLE
|
|
366
|
+
status = self.app.refresh_status
|
|
367
|
+
return f"{self._WATCH_TITLE} · {status}" if status else self._WATCH_TITLE
|
|
368
|
+
|
|
369
|
+
def _on_refresh_status(self, status: str) -> None:
|
|
370
|
+
if not self._selecting:
|
|
371
|
+
self.query_one("#list-title", Static).update(self._title_text())
|
|
372
|
+
|
|
373
|
+
def check_action(self, action: str, parameters: tuple) -> bool | None:
|
|
374
|
+
if action == "select_highlighted" and not self._selecting:
|
|
375
|
+
return False # hidden and inert until selection is armed
|
|
376
|
+
return True
|
|
377
|
+
|
|
378
|
+
def _index_after_build(
|
|
379
|
+
self, snap: AccountsSnapshot, first_build: bool, previous: int | None
|
|
380
|
+
) -> int | None:
|
|
381
|
+
if not self._selecting:
|
|
382
|
+
return None # monitor mode: no cursor at all
|
|
383
|
+
return super()._index_after_build(snap, first_build, previous)
|
|
384
|
+
|
|
385
|
+
def _set_selecting(self, on: bool) -> None:
|
|
386
|
+
self._selecting = on
|
|
387
|
+
listview = self.query_one("#accounts", ListView)
|
|
388
|
+
title = self.query_one("#list-title", Static)
|
|
389
|
+
if on:
|
|
390
|
+
snap = self.app.snapshot
|
|
391
|
+
if snap is not None and snap.accounts:
|
|
392
|
+
listview.index = self._active_index(snap)
|
|
393
|
+
listview.focus()
|
|
394
|
+
title.update(self._SELECT_TITLE)
|
|
395
|
+
else:
|
|
396
|
+
listview.index = None
|
|
397
|
+
self.set_focus(None)
|
|
398
|
+
title.update(self._title_text())
|
|
399
|
+
self.refresh_bindings()
|
|
400
|
+
|
|
401
|
+
def action_toggle_select(self) -> None:
|
|
402
|
+
self._set_selecting(not self._selecting)
|
|
403
|
+
|
|
404
|
+
def on_list_view_selected(self, event: ListView.Selected) -> None:
|
|
405
|
+
if not self._selecting:
|
|
406
|
+
return # e.g. a stray click while just watching
|
|
407
|
+
item = event.item
|
|
408
|
+
if isinstance(item, AccountItem):
|
|
409
|
+
self.app.do_switch(item.number)
|
|
410
|
+
self._set_selecting(False) # stay here, keep watching
|
|
411
|
+
|
|
412
|
+
def action_select_highlighted(self) -> None:
|
|
413
|
+
if self._selecting:
|
|
414
|
+
self.query_one("#accounts", ListView).action_select_cursor()
|
|
415
|
+
|
|
416
|
+
def action_back(self) -> None:
|
|
417
|
+
if self._selecting:
|
|
418
|
+
self._set_selecting(False)
|
|
419
|
+
else:
|
|
420
|
+
self.app.pop_screen()
|
|
421
|
+
|
|
422
|
+
def action_nav_down(self) -> None:
|
|
423
|
+
listview = self.query_one("#accounts", ListView)
|
|
424
|
+
if self._selecting:
|
|
425
|
+
listview.action_cursor_down()
|
|
426
|
+
else:
|
|
427
|
+
listview.scroll_down(animate=False)
|
|
428
|
+
|
|
429
|
+
def action_nav_up(self) -> None:
|
|
430
|
+
listview = self.query_one("#accounts", ListView)
|
|
431
|
+
if self._selecting:
|
|
432
|
+
listview.action_cursor_up()
|
|
433
|
+
else:
|
|
434
|
+
listview.scroll_up(animate=False)
|
claude_swap/tui/data.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Data service for the TUI: snapshots, blocking actions, display helpers.
|
|
2
|
+
|
|
3
|
+
The TUI never parses printed CLI output — it consumes
|
|
4
|
+
``ClaudeAccountSwitcher.accounts_snapshot`` (one collect pass, see
|
|
5
|
+
switcher.py) and renders structured data. Fetch pacing lives in
|
|
6
|
+
``claude_swap.snapshot_source.SnapshotSource`` (shared with any GUI shell);
|
|
7
|
+
this module re-exports it for the TUI's use.
|
|
8
|
+
|
|
9
|
+
Everything here is blocking (file locks, keychain subprocesses, network) and
|
|
10
|
+
must be called from a thread worker, never the UI event loop.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import io
|
|
17
|
+
import sys
|
|
18
|
+
import time
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import datetime, timezone
|
|
21
|
+
from typing import Callable
|
|
22
|
+
|
|
23
|
+
from claude_swap import oauth, printer, usage_store
|
|
24
|
+
from claude_swap.exceptions import ClaudeSwitchError
|
|
25
|
+
from claude_swap.snapshot_source import SnapshotSource
|
|
26
|
+
from claude_swap.switcher import last_seen_note, sentinel_note
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
# Blocking actions (switch/add/remove) run captured, off the UI thread
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class ActionResult:
|
|
36
|
+
"""Outcome of a captured switcher action."""
|
|
37
|
+
|
|
38
|
+
ok: bool
|
|
39
|
+
output: str # captured stdout+stderr, ANSI-colored (render with Text.from_ansi)
|
|
40
|
+
payload: dict | None = None # structured result for json-capable actions
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def first_line(self) -> str:
|
|
44
|
+
"""First non-empty output line, ANSI-stripped — notification material."""
|
|
45
|
+
from rich.text import Text
|
|
46
|
+
|
|
47
|
+
for line in self.output.splitlines():
|
|
48
|
+
plain = Text.from_ansi(line).plain.strip()
|
|
49
|
+
if plain:
|
|
50
|
+
return plain
|
|
51
|
+
return ""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def run_action(fn: Callable[[], dict | None]) -> ActionResult:
|
|
55
|
+
"""Run a switcher action capturing stdout+stderr (color forced on).
|
|
56
|
+
|
|
57
|
+
``sys.stdin`` is swapped for an empty stream so an unexpected ``input()``
|
|
58
|
+
raises ``EOFError`` instead of freezing the app (in-scope actions never
|
|
59
|
+
prompt once ``assume_yes``/explicit identifiers are used; this is
|
|
60
|
+
defensive). The redirect is process-global for the duration — fine here
|
|
61
|
+
because the TUI owns the terminal and nothing else prints while it runs.
|
|
62
|
+
"""
|
|
63
|
+
buf = io.StringIO()
|
|
64
|
+
payload: dict | None = None
|
|
65
|
+
saved_stdin = sys.stdin
|
|
66
|
+
sys.stdin = io.StringIO()
|
|
67
|
+
try:
|
|
68
|
+
with printer.force_color(), contextlib.redirect_stdout(
|
|
69
|
+
buf
|
|
70
|
+
), contextlib.redirect_stderr(buf):
|
|
71
|
+
try:
|
|
72
|
+
payload = fn()
|
|
73
|
+
except ClaudeSwitchError as e:
|
|
74
|
+
print(f"Error: {e}")
|
|
75
|
+
return ActionResult(False, buf.getvalue())
|
|
76
|
+
except EOFError:
|
|
77
|
+
print("Error: interactive input is not available here.")
|
|
78
|
+
return ActionResult(False, buf.getvalue())
|
|
79
|
+
finally:
|
|
80
|
+
sys.stdin = saved_stdin
|
|
81
|
+
return ActionResult(
|
|
82
|
+
True, buf.getvalue(), payload if isinstance(payload, dict) else None
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------------------
|
|
87
|
+
# Display helpers
|
|
88
|
+
# ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
def sentinel_label(sentinel: str, account_num: str | int | None = None) -> str:
|
|
91
|
+
"""The same wording ``cswap list`` prints for this sentinel state."""
|
|
92
|
+
return sentinel_note(sentinel, account_num)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def window_pct(last_good: dict | None, key: str) -> float | None:
|
|
96
|
+
"""Utilization pct of one window ("five_hour"/"seven_day"), if known."""
|
|
97
|
+
if not isinstance(last_good, dict):
|
|
98
|
+
return None
|
|
99
|
+
window = last_good.get(key)
|
|
100
|
+
if not isinstance(window, dict):
|
|
101
|
+
return None
|
|
102
|
+
pct = window.get("pct")
|
|
103
|
+
return float(pct) if isinstance(pct, (int, float)) else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def reset_text(window: dict | None, now: float) -> str | None:
|
|
107
|
+
"""Live countdown to one window's reset ("resets 2h 13m"), if known.
|
|
108
|
+
|
|
109
|
+
Computed from ``resets_at`` at render time — the countdown the API sent
|
|
110
|
+
was correct at *fetch* time and drifts as the measurement ages.
|
|
111
|
+
"""
|
|
112
|
+
if not isinstance(window, dict):
|
|
113
|
+
return None
|
|
114
|
+
resets_at = window.get("resets_at")
|
|
115
|
+
if not resets_at:
|
|
116
|
+
return None
|
|
117
|
+
try:
|
|
118
|
+
ts = datetime.fromisoformat(str(resets_at).replace("Z", "+00:00")).timestamp()
|
|
119
|
+
except ValueError:
|
|
120
|
+
return None
|
|
121
|
+
remaining = ts - now
|
|
122
|
+
if remaining <= 0:
|
|
123
|
+
return "resets now"
|
|
124
|
+
return f"resets {format_duration(remaining)}"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def reset_clock(window: dict | None, now: float) -> str | None:
|
|
128
|
+
"""Absolute local reset time ("20:39" / "Jul 14 09:00"), if known.
|
|
129
|
+
|
|
130
|
+
None once the reset has elapsed — "resets now" needs no clock.
|
|
131
|
+
"""
|
|
132
|
+
if not isinstance(window, dict):
|
|
133
|
+
return None
|
|
134
|
+
resets_at = window.get("resets_at")
|
|
135
|
+
if not resets_at:
|
|
136
|
+
return None
|
|
137
|
+
try:
|
|
138
|
+
reset_utc = datetime.fromisoformat(str(resets_at).replace("Z", "+00:00"))
|
|
139
|
+
except ValueError:
|
|
140
|
+
return None
|
|
141
|
+
if reset_utc.timestamp() - now <= 0:
|
|
142
|
+
return None
|
|
143
|
+
return oauth.reset_clock_string(
|
|
144
|
+
reset_utc, datetime.fromtimestamp(now, tz=timezone.utc)
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def window_reset_text(last_good: dict | None, key: str, now: float) -> str | None:
|
|
149
|
+
"""`reset_text` for one of the top-level 5h/7d windows."""
|
|
150
|
+
if not isinstance(last_good, dict):
|
|
151
|
+
return None
|
|
152
|
+
return reset_text(last_good.get(key), now)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def format_duration(seconds: float) -> str:
|
|
156
|
+
"""Compact duration: "45s", "12m", "2h 13m", "3d 4h"."""
|
|
157
|
+
s = int(seconds)
|
|
158
|
+
if s < 60:
|
|
159
|
+
return f"{s}s"
|
|
160
|
+
if s < 3600:
|
|
161
|
+
return f"{s // 60}m"
|
|
162
|
+
if s < 86400:
|
|
163
|
+
h, m = divmod(s // 60, 60)
|
|
164
|
+
return f"{h}h {m}m" if m else f"{h}h"
|
|
165
|
+
d, h = divmod(s // 3600, 24)
|
|
166
|
+
return f"{d}d {h}h" if h else f"{d}d"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def format_age(age_s: float | None) -> str | None:
|
|
170
|
+
"""Measurement age note ("· 2m ago"); None while comfortably fresh."""
|
|
171
|
+
if age_s is None or age_s < usage_store.SERVE_TTL_S:
|
|
172
|
+
return None
|
|
173
|
+
return f"· {format_duration(age_s)} ago"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def clock_stamp() -> str:
|
|
177
|
+
"""HH:MM:SS local-time stamp for the event log."""
|
|
178
|
+
return time.strftime("%H:%M:%S")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
__all__ = [
|
|
182
|
+
"ActionResult",
|
|
183
|
+
"SnapshotSource",
|
|
184
|
+
"format_age",
|
|
185
|
+
"format_duration",
|
|
186
|
+
"last_seen_note",
|
|
187
|
+
"reset_clock",
|
|
188
|
+
"reset_text",
|
|
189
|
+
"run_action",
|
|
190
|
+
"sentinel_label",
|
|
191
|
+
"clock_stamp",
|
|
192
|
+
"window_pct",
|
|
193
|
+
"window_reset_text",
|
|
194
|
+
]
|