glaip-sdk 0.0.20__py3-none-any.whl → 0.7.7__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 (216) hide show
  1. glaip_sdk/__init__.py +44 -4
  2. glaip_sdk/_version.py +10 -3
  3. glaip_sdk/agents/__init__.py +27 -0
  4. glaip_sdk/agents/base.py +1250 -0
  5. glaip_sdk/branding.py +15 -6
  6. glaip_sdk/cli/account_store.py +540 -0
  7. glaip_sdk/cli/agent_config.py +2 -6
  8. glaip_sdk/cli/auth.py +271 -45
  9. glaip_sdk/cli/commands/__init__.py +2 -2
  10. glaip_sdk/cli/commands/accounts.py +746 -0
  11. glaip_sdk/cli/commands/agents/__init__.py +119 -0
  12. glaip_sdk/cli/commands/agents/_common.py +561 -0
  13. glaip_sdk/cli/commands/agents/create.py +151 -0
  14. glaip_sdk/cli/commands/agents/delete.py +64 -0
  15. glaip_sdk/cli/commands/agents/get.py +89 -0
  16. glaip_sdk/cli/commands/agents/list.py +129 -0
  17. glaip_sdk/cli/commands/agents/run.py +264 -0
  18. glaip_sdk/cli/commands/agents/sync_langflow.py +72 -0
  19. glaip_sdk/cli/commands/agents/update.py +112 -0
  20. glaip_sdk/cli/commands/common_config.py +104 -0
  21. glaip_sdk/cli/commands/configure.py +734 -143
  22. glaip_sdk/cli/commands/mcps/__init__.py +94 -0
  23. glaip_sdk/cli/commands/mcps/_common.py +459 -0
  24. glaip_sdk/cli/commands/mcps/connect.py +82 -0
  25. glaip_sdk/cli/commands/mcps/create.py +152 -0
  26. glaip_sdk/cli/commands/mcps/delete.py +73 -0
  27. glaip_sdk/cli/commands/mcps/get.py +212 -0
  28. glaip_sdk/cli/commands/mcps/list.py +69 -0
  29. glaip_sdk/cli/commands/mcps/tools.py +235 -0
  30. glaip_sdk/cli/commands/mcps/update.py +190 -0
  31. glaip_sdk/cli/commands/models.py +14 -12
  32. glaip_sdk/cli/commands/shared/__init__.py +21 -0
  33. glaip_sdk/cli/commands/shared/formatters.py +91 -0
  34. glaip_sdk/cli/commands/tools/__init__.py +69 -0
  35. glaip_sdk/cli/commands/tools/_common.py +80 -0
  36. glaip_sdk/cli/commands/tools/create.py +228 -0
  37. glaip_sdk/cli/commands/tools/delete.py +61 -0
  38. glaip_sdk/cli/commands/tools/get.py +103 -0
  39. glaip_sdk/cli/commands/tools/list.py +69 -0
  40. glaip_sdk/cli/commands/tools/script.py +49 -0
  41. glaip_sdk/cli/commands/tools/update.py +102 -0
  42. glaip_sdk/cli/commands/transcripts/__init__.py +90 -0
  43. glaip_sdk/cli/commands/transcripts/_common.py +9 -0
  44. glaip_sdk/cli/commands/transcripts/clear.py +5 -0
  45. glaip_sdk/cli/commands/transcripts/detail.py +5 -0
  46. glaip_sdk/cli/commands/transcripts_original.py +756 -0
  47. glaip_sdk/cli/commands/update.py +164 -23
  48. glaip_sdk/cli/config.py +49 -7
  49. glaip_sdk/cli/constants.py +38 -0
  50. glaip_sdk/cli/context.py +8 -0
  51. glaip_sdk/cli/core/__init__.py +79 -0
  52. glaip_sdk/cli/core/context.py +124 -0
  53. glaip_sdk/cli/core/output.py +851 -0
  54. glaip_sdk/cli/core/prompting.py +649 -0
  55. glaip_sdk/cli/core/rendering.py +187 -0
  56. glaip_sdk/cli/display.py +45 -32
  57. glaip_sdk/cli/entrypoint.py +20 -0
  58. glaip_sdk/cli/hints.py +57 -0
  59. glaip_sdk/cli/io.py +14 -17
  60. glaip_sdk/cli/main.py +344 -167
  61. glaip_sdk/cli/masking.py +21 -33
  62. glaip_sdk/cli/mcp_validators.py +5 -15
  63. glaip_sdk/cli/pager.py +15 -22
  64. glaip_sdk/cli/parsers/__init__.py +1 -3
  65. glaip_sdk/cli/parsers/json_input.py +11 -22
  66. glaip_sdk/cli/resolution.py +5 -10
  67. glaip_sdk/cli/rich_helpers.py +1 -3
  68. glaip_sdk/cli/slash/__init__.py +0 -9
  69. glaip_sdk/cli/slash/accounts_controller.py +580 -0
  70. glaip_sdk/cli/slash/accounts_shared.py +75 -0
  71. glaip_sdk/cli/slash/agent_session.py +65 -29
  72. glaip_sdk/cli/slash/prompt.py +24 -10
  73. glaip_sdk/cli/slash/remote_runs_controller.py +566 -0
  74. glaip_sdk/cli/slash/session.py +827 -232
  75. glaip_sdk/cli/slash/tui/__init__.py +34 -0
  76. glaip_sdk/cli/slash/tui/accounts.tcss +88 -0
  77. glaip_sdk/cli/slash/tui/accounts_app.py +933 -0
  78. glaip_sdk/cli/slash/tui/background_tasks.py +72 -0
  79. glaip_sdk/cli/slash/tui/clipboard.py +147 -0
  80. glaip_sdk/cli/slash/tui/context.py +59 -0
  81. glaip_sdk/cli/slash/tui/keybind_registry.py +235 -0
  82. glaip_sdk/cli/slash/tui/loading.py +58 -0
  83. glaip_sdk/cli/slash/tui/remote_runs_app.py +628 -0
  84. glaip_sdk/cli/slash/tui/terminal.py +402 -0
  85. glaip_sdk/cli/slash/tui/theme/__init__.py +15 -0
  86. glaip_sdk/cli/slash/tui/theme/catalog.py +79 -0
  87. glaip_sdk/cli/slash/tui/theme/manager.py +86 -0
  88. glaip_sdk/cli/slash/tui/theme/tokens.py +55 -0
  89. glaip_sdk/cli/slash/tui/toast.py +123 -0
  90. glaip_sdk/cli/transcript/__init__.py +12 -52
  91. glaip_sdk/cli/transcript/cache.py +258 -60
  92. glaip_sdk/cli/transcript/capture.py +72 -21
  93. glaip_sdk/cli/transcript/history.py +815 -0
  94. glaip_sdk/cli/transcript/launcher.py +1 -3
  95. glaip_sdk/cli/transcript/viewer.py +79 -329
  96. glaip_sdk/cli/update_notifier.py +385 -24
  97. glaip_sdk/cli/validators.py +16 -18
  98. glaip_sdk/client/__init__.py +3 -1
  99. glaip_sdk/client/_schedule_payloads.py +89 -0
  100. glaip_sdk/client/agent_runs.py +147 -0
  101. glaip_sdk/client/agents.py +370 -100
  102. glaip_sdk/client/base.py +78 -35
  103. glaip_sdk/client/hitl.py +136 -0
  104. glaip_sdk/client/main.py +25 -10
  105. glaip_sdk/client/mcps.py +166 -27
  106. glaip_sdk/client/payloads/agent/__init__.py +23 -0
  107. glaip_sdk/client/{_agent_payloads.py → payloads/agent/requests.py} +65 -74
  108. glaip_sdk/client/payloads/agent/responses.py +43 -0
  109. glaip_sdk/client/run_rendering.py +583 -79
  110. glaip_sdk/client/schedules.py +439 -0
  111. glaip_sdk/client/shared.py +21 -0
  112. glaip_sdk/client/tools.py +214 -56
  113. glaip_sdk/client/validators.py +20 -48
  114. glaip_sdk/config/constants.py +11 -0
  115. glaip_sdk/exceptions.py +1 -3
  116. glaip_sdk/hitl/__init__.py +48 -0
  117. glaip_sdk/hitl/base.py +64 -0
  118. glaip_sdk/hitl/callback.py +43 -0
  119. glaip_sdk/hitl/local.py +121 -0
  120. glaip_sdk/hitl/remote.py +523 -0
  121. glaip_sdk/icons.py +9 -3
  122. glaip_sdk/mcps/__init__.py +21 -0
  123. glaip_sdk/mcps/base.py +345 -0
  124. glaip_sdk/models/__init__.py +107 -0
  125. glaip_sdk/models/agent.py +47 -0
  126. glaip_sdk/models/agent_runs.py +117 -0
  127. glaip_sdk/models/common.py +42 -0
  128. glaip_sdk/models/mcp.py +33 -0
  129. glaip_sdk/models/schedule.py +224 -0
  130. glaip_sdk/models/tool.py +33 -0
  131. glaip_sdk/payload_schemas/__init__.py +1 -13
  132. glaip_sdk/payload_schemas/agent.py +1 -3
  133. glaip_sdk/registry/__init__.py +55 -0
  134. glaip_sdk/registry/agent.py +164 -0
  135. glaip_sdk/registry/base.py +139 -0
  136. glaip_sdk/registry/mcp.py +253 -0
  137. glaip_sdk/registry/tool.py +445 -0
  138. glaip_sdk/rich_components.py +58 -2
  139. glaip_sdk/runner/__init__.py +76 -0
  140. glaip_sdk/runner/base.py +84 -0
  141. glaip_sdk/runner/deps.py +112 -0
  142. glaip_sdk/runner/langgraph.py +872 -0
  143. glaip_sdk/runner/logging_config.py +77 -0
  144. glaip_sdk/runner/mcp_adapter/__init__.py +13 -0
  145. glaip_sdk/runner/mcp_adapter/base_mcp_adapter.py +43 -0
  146. glaip_sdk/runner/mcp_adapter/langchain_mcp_adapter.py +257 -0
  147. glaip_sdk/runner/mcp_adapter/mcp_config_builder.py +95 -0
  148. glaip_sdk/runner/tool_adapter/__init__.py +18 -0
  149. glaip_sdk/runner/tool_adapter/base_tool_adapter.py +44 -0
  150. glaip_sdk/runner/tool_adapter/langchain_tool_adapter.py +242 -0
  151. glaip_sdk/schedules/__init__.py +22 -0
  152. glaip_sdk/schedules/base.py +291 -0
  153. glaip_sdk/tools/__init__.py +22 -0
  154. glaip_sdk/tools/base.py +468 -0
  155. glaip_sdk/utils/__init__.py +59 -12
  156. glaip_sdk/utils/a2a/__init__.py +34 -0
  157. glaip_sdk/utils/a2a/event_processor.py +188 -0
  158. glaip_sdk/utils/agent_config.py +4 -14
  159. glaip_sdk/utils/bundler.py +403 -0
  160. glaip_sdk/utils/client.py +111 -0
  161. glaip_sdk/utils/client_utils.py +46 -28
  162. glaip_sdk/utils/datetime_helpers.py +58 -0
  163. glaip_sdk/utils/discovery.py +78 -0
  164. glaip_sdk/utils/display.py +25 -21
  165. glaip_sdk/utils/export.py +143 -0
  166. glaip_sdk/utils/general.py +1 -36
  167. glaip_sdk/utils/import_export.py +15 -16
  168. glaip_sdk/utils/import_resolver.py +524 -0
  169. glaip_sdk/utils/instructions.py +101 -0
  170. glaip_sdk/utils/rendering/__init__.py +115 -1
  171. glaip_sdk/utils/rendering/formatting.py +38 -23
  172. glaip_sdk/utils/rendering/layout/__init__.py +64 -0
  173. glaip_sdk/utils/rendering/{renderer → layout}/panels.py +10 -3
  174. glaip_sdk/utils/rendering/{renderer → layout}/progress.py +73 -12
  175. glaip_sdk/utils/rendering/layout/summary.py +74 -0
  176. glaip_sdk/utils/rendering/layout/transcript.py +606 -0
  177. glaip_sdk/utils/rendering/models.py +18 -8
  178. glaip_sdk/utils/rendering/renderer/__init__.py +9 -51
  179. glaip_sdk/utils/rendering/renderer/base.py +534 -882
  180. glaip_sdk/utils/rendering/renderer/config.py +4 -10
  181. glaip_sdk/utils/rendering/renderer/debug.py +30 -34
  182. glaip_sdk/utils/rendering/renderer/factory.py +138 -0
  183. glaip_sdk/utils/rendering/renderer/stream.py +13 -54
  184. glaip_sdk/utils/rendering/renderer/summary_window.py +79 -0
  185. glaip_sdk/utils/rendering/renderer/thinking.py +273 -0
  186. glaip_sdk/utils/rendering/renderer/toggle.py +182 -0
  187. glaip_sdk/utils/rendering/renderer/tool_panels.py +442 -0
  188. glaip_sdk/utils/rendering/renderer/transcript_mode.py +162 -0
  189. glaip_sdk/utils/rendering/state.py +204 -0
  190. glaip_sdk/utils/rendering/step_tree_state.py +100 -0
  191. glaip_sdk/utils/rendering/steps/__init__.py +34 -0
  192. glaip_sdk/utils/rendering/steps/event_processor.py +778 -0
  193. glaip_sdk/utils/rendering/steps/format.py +176 -0
  194. glaip_sdk/utils/rendering/{steps.py → steps/manager.py} +122 -26
  195. glaip_sdk/utils/rendering/timing.py +36 -0
  196. glaip_sdk/utils/rendering/viewer/__init__.py +21 -0
  197. glaip_sdk/utils/rendering/viewer/presenter.py +184 -0
  198. glaip_sdk/utils/resource_refs.py +29 -26
  199. glaip_sdk/utils/runtime_config.py +425 -0
  200. glaip_sdk/utils/serialization.py +32 -46
  201. glaip_sdk/utils/sync.py +162 -0
  202. glaip_sdk/utils/tool_detection.py +301 -0
  203. glaip_sdk/utils/tool_storage_provider.py +140 -0
  204. glaip_sdk/utils/validation.py +20 -28
  205. {glaip_sdk-0.0.20.dist-info → glaip_sdk-0.7.7.dist-info}/METADATA +78 -23
  206. glaip_sdk-0.7.7.dist-info/RECORD +213 -0
  207. {glaip_sdk-0.0.20.dist-info → glaip_sdk-0.7.7.dist-info}/WHEEL +2 -1
  208. glaip_sdk-0.7.7.dist-info/entry_points.txt +2 -0
  209. glaip_sdk-0.7.7.dist-info/top_level.txt +1 -0
  210. glaip_sdk/cli/commands/agents.py +0 -1412
  211. glaip_sdk/cli/commands/mcps.py +0 -1225
  212. glaip_sdk/cli/commands/tools.py +0 -597
  213. glaip_sdk/cli/utils.py +0 -1330
  214. glaip_sdk/models.py +0 -259
  215. glaip_sdk-0.0.20.dist-info/RECORD +0 -80
  216. glaip_sdk-0.0.20.dist-info/entry_points.txt +0 -3
@@ -0,0 +1,933 @@
1
+ """Textual UI for the /accounts command.
2
+
3
+ Provides a minimal interactive list with the same columns/order as the Rich
4
+ fallback (name, API URL, masked key, status) and keyboard navigation.
5
+
6
+ Authors:
7
+ Raymond Christopher (raymond.christopher@gdplabs.id)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import logging
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ from glaip_sdk.cli.account_store import AccountStore, AccountStoreError, get_account_store
19
+ from glaip_sdk.cli.commands.common_config import check_connection_with_reason
20
+ from glaip_sdk.cli.slash.accounts_shared import (
21
+ build_account_rows,
22
+ build_account_status_string,
23
+ env_credentials_present,
24
+ )
25
+ from glaip_sdk.cli.slash.tui.background_tasks import BackgroundTaskMixin
26
+ from glaip_sdk.cli.slash.tui.clipboard import ClipboardAdapter
27
+ from glaip_sdk.cli.slash.tui.context import TUIContext
28
+ from glaip_sdk.cli.slash.tui.loading import hide_loading_indicator, show_loading_indicator
29
+ from glaip_sdk.cli.slash.tui.theme.catalog import _BUILTIN_THEMES
30
+ from glaip_sdk.cli.validators import validate_api_key
31
+ from glaip_sdk.utils.validation import validate_url
32
+
33
+ try: # pragma: no cover - optional dependency
34
+ from textual import events
35
+ from textual.app import App, ComposeResult
36
+ from textual.binding import Binding
37
+ from textual.containers import Container, Horizontal, Vertical
38
+ from textual.screen import ModalScreen
39
+ from textual.widgets import Button, Checkbox, DataTable, Footer, Header, Input, LoadingIndicator, Static
40
+ except Exception: # pragma: no cover - optional dependency
41
+ events = None # type: ignore[assignment]
42
+ App = None # type: ignore[assignment]
43
+ ComposeResult = None # type: ignore[assignment]
44
+ Binding = None # type: ignore[assignment]
45
+ Container = None # type: ignore[assignment]
46
+ Horizontal = None # type: ignore[assignment]
47
+ Vertical = None # type: ignore[assignment]
48
+ Button = None # type: ignore[assignment]
49
+ Checkbox = None # type: ignore[assignment]
50
+ DataTable = None # type: ignore[assignment]
51
+ Footer = None # type: ignore[assignment]
52
+ Header = None # type: ignore[assignment]
53
+ Input = None # type: ignore[assignment]
54
+ LoadingIndicator = None # type: ignore[assignment]
55
+ ModalScreen = None # type: ignore[assignment]
56
+ Static = None # type: ignore[assignment]
57
+ Theme = None # type: ignore[assignment]
58
+
59
+ if App is not None:
60
+ try: # pragma: no cover - optional dependency
61
+ from textual.theme import Theme
62
+ except Exception: # pragma: no cover - optional dependency
63
+ Theme = None # type: ignore[assignment]
64
+
65
+ TEXTUAL_SUPPORTED = App is not None and DataTable is not None
66
+
67
+ # Use safe bases so the module remains importable without Textual installed.
68
+ if TEXTUAL_SUPPORTED:
69
+ _AccountFormBase = ModalScreen[dict[str, Any] | None]
70
+ _ConfirmDeleteBase = ModalScreen[str | None]
71
+ _AppBase = App[None]
72
+ else:
73
+ _AccountFormBase = object
74
+ _ConfirmDeleteBase = object
75
+ _AppBase = object
76
+
77
+ # Widget IDs for Textual UI
78
+ ACCOUNTS_TABLE_ID = "#accounts-table"
79
+ FILTER_INPUT_ID = "#filter-input"
80
+ STATUS_ID = "#status"
81
+ ACCOUNTS_LOADING_ID = "#accounts-loading"
82
+ FORM_KEY_ID = "#form-key"
83
+
84
+ # CSS file name
85
+ CSS_FILE_NAME = "accounts.tcss"
86
+
87
+
88
+ @dataclass
89
+ class AccountsTUICallbacks:
90
+ """Callbacks invoked by the Textual UI."""
91
+
92
+ switch_account: Callable[[str], tuple[bool, str]]
93
+
94
+
95
+ def _build_account_rows_from_store(
96
+ store: AccountStore,
97
+ env_lock: bool,
98
+ ) -> tuple[list[dict[str, str | bool]], str | None]:
99
+ """Load account rows with masking and active flag."""
100
+ accounts = store.list_accounts()
101
+ active = store.get_active_account()
102
+ rows = build_account_rows(accounts, active, env_lock)
103
+ return rows, active
104
+
105
+
106
+ def _prepare_account_payload(
107
+ *,
108
+ name: str,
109
+ api_url_input: str,
110
+ api_key_input: str,
111
+ existing_url: str | None,
112
+ existing_key: str | None,
113
+ existing_names: set[str],
114
+ mode: str,
115
+ should_test: bool,
116
+ validate_name: Callable[[str], None],
117
+ connection_tester: Callable[[str, str], tuple[bool, str]],
118
+ ) -> tuple[dict[str, Any] | None, str | None]:
119
+ """Validate and build payload for add/edit operations."""
120
+ name = name.strip()
121
+ api_url_raw = api_url_input.strip()
122
+ api_key_raw = api_key_input.strip()
123
+
124
+ error = _validate_account_name(name, existing_names, mode, validate_name)
125
+ if error:
126
+ return None, error
127
+
128
+ api_url_candidate = api_url_raw or (existing_url or "")
129
+ api_key_candidate = api_key_raw or (existing_key or "")
130
+
131
+ api_url_validated, error = _validate_and_prepare_url(api_url_candidate)
132
+ if error:
133
+ return None, error
134
+
135
+ api_key_validated, error = _validate_and_prepare_key(api_key_candidate)
136
+ if error:
137
+ return None, error
138
+
139
+ if should_test:
140
+ error = _test_connection(api_url_validated, api_key_validated, connection_tester)
141
+ if error:
142
+ return None, error
143
+
144
+ payload: dict[str, Any] = {
145
+ "name": name,
146
+ "api_url": api_url_validated,
147
+ "api_key": api_key_validated,
148
+ "should_test": should_test,
149
+ "mode": mode,
150
+ }
151
+ return payload, None
152
+
153
+
154
+ def _validate_account_name(
155
+ name: str,
156
+ existing_names: set[str],
157
+ mode: str,
158
+ validate_name: Callable[[str], None],
159
+ ) -> str | None:
160
+ """Validate account name."""
161
+ if not name:
162
+ return "Account name cannot be empty."
163
+
164
+ try:
165
+ validate_name(name)
166
+ except Exception as exc:
167
+ return str(exc)
168
+
169
+ if mode == "add" and name in existing_names:
170
+ return f"Account '{name}' already exists. Choose a unique name."
171
+
172
+ return None
173
+
174
+
175
+ def _validate_and_prepare_url(api_url_candidate: str) -> tuple[str, str | None]:
176
+ """Validate and prepare API URL."""
177
+ if not api_url_candidate:
178
+ return "", "API URL is required."
179
+ try:
180
+ return validate_url(api_url_candidate), None
181
+ except Exception as exc:
182
+ return "", str(exc)
183
+
184
+
185
+ def _validate_and_prepare_key(api_key_candidate: str) -> tuple[str, str | None]:
186
+ """Validate and prepare API key."""
187
+ if not api_key_candidate:
188
+ return "", "API key is required."
189
+ try:
190
+ return validate_api_key(api_key_candidate), None
191
+ except Exception as exc:
192
+ return "", str(exc)
193
+
194
+
195
+ def _test_connection(
196
+ api_url: str,
197
+ api_key: str,
198
+ connection_tester: Callable[[str, str], tuple[bool, str]],
199
+ ) -> str | None:
200
+ """Test API connection."""
201
+ ok, reason = connection_tester(api_url, api_key)
202
+ if not ok:
203
+ detail = reason or "connection_failed"
204
+ return f"Connection test failed: {detail}"
205
+ return None
206
+
207
+
208
+ def run_accounts_textual(
209
+ rows: list[dict[str, str | bool]],
210
+ *,
211
+ active_account: str | None,
212
+ env_lock: bool,
213
+ callbacks: AccountsTUICallbacks,
214
+ ctx: TUIContext | None = None,
215
+ ) -> None:
216
+ """Launch the Textual accounts browser if dependencies are available."""
217
+ if not TEXTUAL_SUPPORTED:
218
+ return
219
+ app = AccountsTextualApp(rows, active_account, env_lock, callbacks, ctx=ctx)
220
+ app.run()
221
+
222
+
223
+ class AccountFormModal(_AccountFormBase): # pragma: no cover - interactive
224
+ """Modal form for add/edit account."""
225
+
226
+ CSS_PATH = CSS_FILE_NAME
227
+
228
+ def __init__(
229
+ self,
230
+ *,
231
+ mode: str,
232
+ existing: dict[str, str] | None,
233
+ existing_names: set[str],
234
+ connection_tester: Callable[[str, str], tuple[bool, str]],
235
+ validate_name: Callable[[str], None],
236
+ ) -> None:
237
+ """Initialize the account form modal.
238
+
239
+ Args:
240
+ mode: Form mode, either "add" or "edit".
241
+ existing: Existing account data for edit mode.
242
+ existing_names: Set of existing account names for validation.
243
+ connection_tester: Callable to test API connection.
244
+ validate_name: Callable to validate account name.
245
+ """
246
+ super().__init__()
247
+ self._mode = mode
248
+ self._existing = existing or {}
249
+ self._existing_names = existing_names
250
+ self._connection_tester = connection_tester
251
+ self._validate_name = validate_name
252
+
253
+ def compose(self) -> ComposeResult:
254
+ """Render the form controls."""
255
+ title = "Add account" if self._mode == "add" else "Edit account"
256
+ name_input = Input(
257
+ value=self._existing.get("name", ""),
258
+ placeholder="account-name",
259
+ id="form-name",
260
+ disabled=self._mode == "edit",
261
+ )
262
+ url_input = Input(value=self._existing.get("api_url", ""), placeholder="https://api.example.com", id="form-url")
263
+ key_input = Input(value="", placeholder="sk-...", password=True, id="form-key")
264
+ test_checkbox = Checkbox(
265
+ "Test connection before save",
266
+ value=True,
267
+ id="form-test",
268
+ )
269
+ status = Static("", id="form-status")
270
+
271
+ yield Static(title, id="form-title")
272
+ yield Static("Name", classes="form-label")
273
+ yield name_input
274
+ yield Static("API URL", classes="form-label")
275
+ yield url_input
276
+ yield Static("API Key", classes="form-label")
277
+ yield key_input
278
+ yield Horizontal(
279
+ Button("Show key", id="toggle-key"),
280
+ Button("Clear key", id="clear-key"),
281
+ id="form-key-actions",
282
+ )
283
+ yield test_checkbox
284
+ yield Horizontal(
285
+ Button("Save", id="form-save", variant="primary"),
286
+ Button("Cancel", id="form-cancel"),
287
+ id="form-actions",
288
+ )
289
+ yield status
290
+
291
+ def on_button_pressed(self, event: Button.Pressed) -> None:
292
+ """Handle button presses."""
293
+ btn_id = event.button.id or ""
294
+ if btn_id == "form-cancel":
295
+ self.dismiss(None)
296
+ return
297
+ if btn_id == "toggle-key":
298
+ key_input = self.query_one(FORM_KEY_ID, Input)
299
+ key_input.password = not key_input.password
300
+ key_input.focus()
301
+ return
302
+ if btn_id == "clear-key":
303
+ key_input = self.query_one(FORM_KEY_ID, Input)
304
+ key_input.value = ""
305
+ key_input.focus()
306
+ return
307
+ if btn_id == "form-save":
308
+ self._handle_submit()
309
+
310
+ def _handle_submit(self) -> None:
311
+ """Validate inputs and dismiss with payload on success."""
312
+ status = self.query_one("#form-status", Static)
313
+ name_input = self.query_one("#form-name", Input)
314
+ url_input = self.query_one("#form-url", Input)
315
+ key_input = self.query_one(FORM_KEY_ID, Input)
316
+ test_checkbox = self.query_one("#form-test", Checkbox)
317
+
318
+ payload, error = _prepare_account_payload(
319
+ name=name_input.value or "",
320
+ api_url_input=url_input.value or "",
321
+ api_key_input=key_input.value or "",
322
+ existing_url=self._existing.get("api_url"),
323
+ existing_key=self._existing.get("api_key"),
324
+ existing_names=self._existing_names,
325
+ mode=self._mode,
326
+ should_test=bool(test_checkbox.value),
327
+ validate_name=self._validate_name,
328
+ connection_tester=self._connection_tester,
329
+ )
330
+ if error:
331
+ status.update(f"[red]{error}[/]")
332
+ if error.startswith("Connection test failed") and hasattr(self.app, "_set_status"):
333
+ try:
334
+ # Surface a status-bar cue so errors remain visible after closing the modal.
335
+ self.app._set_status(error, "yellow") # type: ignore[attr-defined]
336
+ except Exception:
337
+ pass
338
+ return
339
+ status.update("[green]Saving...[/]")
340
+ self.dismiss(payload)
341
+
342
+
343
+ class ConfirmDeleteModal(_ConfirmDeleteBase): # pragma: no cover - interactive
344
+ """Modal requiring typed confirmation for delete."""
345
+
346
+ CSS_PATH = CSS_FILE_NAME
347
+
348
+ def __init__(self, name: str) -> None:
349
+ """Initialize the delete confirmation modal.
350
+
351
+ Args:
352
+ name: Name of the account to delete.
353
+ """
354
+ super().__init__()
355
+ self._name = name
356
+
357
+ def compose(self) -> ComposeResult:
358
+ """Render confirmation form."""
359
+ yield Static(f"Type '{self._name}' to confirm deletion. This cannot be undone.", id="confirm-text")
360
+ yield Input(placeholder=self._name, id="confirm-input")
361
+ yield Horizontal(
362
+ Button("Delete", id="confirm-delete", variant="error"),
363
+ Button("Cancel", id="confirm-cancel"),
364
+ id="confirm-actions",
365
+ )
366
+ yield Static("", id="confirm-status")
367
+
368
+ def on_button_pressed(self, event: Button.Pressed) -> None:
369
+ """Handle confirmation buttons."""
370
+ btn_id = event.button.id or ""
371
+ if btn_id == "confirm-cancel":
372
+ self.dismiss(None)
373
+ return
374
+ if btn_id == "confirm-delete":
375
+ self._handle_confirm()
376
+
377
+ def _handle_confirm(self) -> None:
378
+ """Dismiss with name when confirmation matches."""
379
+ status = self.query_one("#confirm-status", Static)
380
+ input_widget = self.query_one("#confirm-input", Input)
381
+ if (input_widget.value or "").strip() != self._name:
382
+ status.update(f"[yellow]Name does not match; type '{self._name}' to confirm.[/]")
383
+ input_widget.focus()
384
+ return
385
+ self.dismiss(self._name)
386
+
387
+
388
+ class AccountsTextualApp(BackgroundTaskMixin, _AppBase): # pragma: no cover - interactive
389
+ """Textual application for browsing accounts."""
390
+
391
+ CSS_PATH = CSS_FILE_NAME
392
+ BINDINGS = [
393
+ Binding("enter", "switch_row", "Switch", show=True) if Binding else None,
394
+ Binding("return", "switch_row", "Switch", show=False) if Binding else None,
395
+ Binding("/", "focus_filter", "Filter", show=True) if Binding else None,
396
+ Binding("a", "add_account", "Add", show=True) if Binding else None,
397
+ Binding("e", "edit_account", "Edit", show=True) if Binding else None,
398
+ Binding("d", "delete_account", "Delete", show=True) if Binding else None,
399
+ Binding("c", "copy_account", "Copy", show=True) if Binding else None,
400
+ # Esc clears filter when focused/non-empty; otherwise exits
401
+ Binding("escape", "clear_or_exit", "Close", priority=True) if Binding else None,
402
+ Binding("q", "app_exit", "Close", priority=True) if Binding else None,
403
+ ]
404
+ BINDINGS = [b for b in BINDINGS if b is not None]
405
+
406
+ def __init__(
407
+ self,
408
+ rows: list[dict[str, str | bool]],
409
+ active_account: str | None,
410
+ env_lock: bool,
411
+ callbacks: AccountsTUICallbacks,
412
+ ctx: TUIContext | None = None,
413
+ ) -> None:
414
+ """Initialize the Textual accounts app.
415
+
416
+ Args:
417
+ rows: Account data rows to display.
418
+ active_account: Name of the currently active account.
419
+ env_lock: Whether environment credentials are locking account switching.
420
+ callbacks: Callbacks for account switching operations.
421
+ ctx: Shared TUI context.
422
+ """
423
+ super().__init__()
424
+ self._store = get_account_store()
425
+ self._all_rows = rows
426
+ self._active_account = active_account
427
+ self._env_lock = env_lock
428
+ self._callbacks = callbacks
429
+ self._ctx = ctx
430
+ self._filter_text: str = ""
431
+ self._is_switching = False
432
+
433
+ def compose(self) -> ComposeResult:
434
+ """Build the Textual layout."""
435
+ header_text = self._header_text()
436
+ yield Static(header_text, id="header-info")
437
+ if self._env_lock:
438
+ yield Static(
439
+ "Env credentials detected (AIP_API_URL/AIP_API_KEY); add/edit/delete are disabled.",
440
+ id="env-lock",
441
+ )
442
+ clear_btn = Button("Clear", id="filter-clear")
443
+ clear_btn.display = False # hide until filter has content
444
+ filter_bar = Horizontal(
445
+ Static("Filter (/):", id="filter-label"),
446
+ Input(placeholder="Type to filter by name or host", id="filter-input"),
447
+ clear_btn,
448
+ id="filter-container",
449
+ )
450
+ filter_bar.styles.padding = (0, 0)
451
+ main = Vertical(
452
+ filter_bar,
453
+ DataTable(id=ACCOUNTS_TABLE_ID.lstrip("#")),
454
+ )
455
+ # Avoid large gaps; keep main content filling available space
456
+ main.styles.height = "1fr"
457
+ main.styles.padding = (0, 0)
458
+ yield main
459
+ yield Horizontal(
460
+ LoadingIndicator(id=ACCOUNTS_LOADING_ID.lstrip("#")),
461
+ Static("", id=STATUS_ID.lstrip("#")),
462
+ id="status-bar",
463
+ )
464
+ yield Footer()
465
+
466
+ def on_mount(self) -> None:
467
+ """Configure table columns and load rows."""
468
+ self._apply_theme()
469
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
470
+ table.add_column("Name", width=20)
471
+ table.add_column("API URL", width=40)
472
+ table.add_column("Key (masked)", width=20)
473
+ table.add_column("Status", width=14)
474
+ table.cursor_type = "row"
475
+ table.zebra_stripes = True
476
+ table.styles.height = "1fr" # Fill available space below the filter
477
+ table.styles.margin = 0
478
+ self._reload_rows()
479
+ table.focus()
480
+ # Keep the filter tight to the table
481
+ main = self.query_one(Vertical)
482
+ main.styles.gap = 0
483
+ self._update_filter_button_visibility()
484
+
485
+ def _header_text(self) -> str:
486
+ """Build header text with active account and host."""
487
+ host = self._get_active_host() or "Not configured"
488
+ lock_icon = " [yellow]🔒[/]" if self._env_lock else ""
489
+ active = self._active_account or "None"
490
+ return f"[green]Active:[/] [bold]{active}[/] ([cyan]{host}[/]){lock_icon}"
491
+
492
+ def _get_active_host(self) -> str | None:
493
+ """Return the API host for the active account (shortened)."""
494
+ return self._get_host_for_name(self._active_account)
495
+
496
+ def _get_host_for_name(self, name: str | None) -> str | None:
497
+ """Return shortened API URL for a given account name."""
498
+ if not name:
499
+ return None
500
+ for row in self._all_rows:
501
+ if row.get("name") == name:
502
+ url = str(row.get("api_url", ""))
503
+ return url if len(url) <= 40 else f"{url[:37]}..."
504
+ return None
505
+
506
+ def action_focus_filter(self) -> None:
507
+ """Focus the filter input and clear previous text."""
508
+ filter_input = self.query_one(FILTER_INPUT_ID, Input)
509
+ filter_input.value = self._filter_text
510
+ filter_input.focus()
511
+
512
+ def action_switch_row(self) -> None:
513
+ """Switch to the currently selected account."""
514
+ if self._env_lock:
515
+ self._set_status("Switching disabled: env credentials in use.", "yellow")
516
+ return
517
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
518
+ if table.cursor_row is None:
519
+ self._set_status("No account selected.", "yellow")
520
+ return
521
+ try:
522
+ row_key = table.get_row_at(table.cursor_row)[0]
523
+ except Exception:
524
+ self._set_status("Unable to read selected row.", "red")
525
+ return
526
+ name = str(row_key)
527
+ if self._is_switching:
528
+ self._set_status("Already switching...", "yellow")
529
+ return
530
+ self._is_switching = True
531
+ host = self._get_host_for_name(name)
532
+ if host:
533
+ self._show_loading(f"Connecting to '{name}' ({host})...")
534
+ else:
535
+ self._show_loading(f"Connecting to '{name}'...")
536
+ self._queue_switch(name)
537
+
538
+ def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None: # type: ignore[override]
539
+ """Handle mouse click selection by triggering switch."""
540
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
541
+ try:
542
+ # Move cursor to clicked row then switch
543
+ table.cursor_coordinate = (event.cursor_row, 0)
544
+ except Exception:
545
+ return
546
+ self.action_switch_row()
547
+
548
+ def on_input_submitted(self, event: Input.Submitted) -> None:
549
+ """Apply filter when user presses Enter inside filter input."""
550
+ self._filter_text = (event.value or "").strip()
551
+ self._reload_rows()
552
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
553
+ table.focus()
554
+ self._update_filter_button_visibility()
555
+
556
+ def on_input_changed(self, event: Input.Changed) -> None:
557
+ """Apply filter live as the user types."""
558
+ self._filter_text = (event.value or "").strip()
559
+ self._reload_rows()
560
+ self._update_filter_button_visibility()
561
+
562
+ def _reload_rows(self, preferred_name: str | None = None) -> None:
563
+ """Refresh table rows based on current filter/active state."""
564
+ # Work on a copy to avoid mutating the backing rows list
565
+ rows_copy = [dict(row) for row in self._all_rows]
566
+ for row in rows_copy:
567
+ row["active"] = row.get("name") == self._active_account
568
+
569
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
570
+ table.clear()
571
+ filtered = self._filtered_rows(rows_copy)
572
+ for row in filtered:
573
+ row_for_status = dict(row)
574
+ row_for_status["active"] = row_for_status.get("name") == self._active_account
575
+ # Use markup to align status colors with Rich fallback (green active badge).
576
+ status = build_account_status_string(row_for_status, use_markup=True)
577
+ # pylint: disable=duplicate-code
578
+ # Reuses shared status builder; columns mirror accounts_controller Rich table.
579
+ table.add_row(
580
+ str(row.get("name", "")),
581
+ str(row.get("api_url", "")),
582
+ str(row.get("masked_key", "")),
583
+ status,
584
+ )
585
+ # Move cursor to active or first row
586
+ cursor_idx = 0
587
+ target_name = preferred_name or self._active_account
588
+ for idx, row in enumerate(filtered):
589
+ if row.get("name") == target_name:
590
+ cursor_idx = idx
591
+ break
592
+ if filtered:
593
+ table.cursor_coordinate = (cursor_idx, 0)
594
+ else:
595
+ self._set_status("No accounts match the current filter.", "yellow")
596
+ return
597
+
598
+ # Update status to reflect filter state
599
+ if self._filter_text:
600
+ self._set_status(f"Filtered: {self._filter_text}", "cyan")
601
+ else:
602
+ self._set_status("", "white")
603
+
604
+ def _filtered_rows(self, rows: list[dict[str, str | bool]] | None = None) -> list[dict[str, str | bool]]:
605
+ """Return rows filtered by name or API URL substring."""
606
+ base_rows = rows if rows is not None else [dict(row) for row in self._all_rows]
607
+ if not self._filter_text:
608
+ return list(base_rows)
609
+ needle = self._filter_text.lower()
610
+ filtered = [
611
+ row
612
+ for row in base_rows
613
+ if needle in str(row.get("name", "")).lower() or needle in str(row.get("api_url", "")).lower()
614
+ ]
615
+
616
+ # Sort so name matches surface first, then URL matches, then alphabetically
617
+ def score(row: dict[str, str | bool]) -> tuple[int, str]:
618
+ name = str(row.get("name", "")).lower()
619
+ url = str(row.get("api_url", "")).lower()
620
+ name_hit = needle in name
621
+ url_hit = needle in url
622
+ # Extract nested conditional into clear statement
623
+ if name_hit:
624
+ priority = 0
625
+ elif url_hit:
626
+ priority = 1
627
+ else:
628
+ priority = 2
629
+ return (priority, name)
630
+
631
+ return sorted(filtered, key=score)
632
+
633
+ def _set_status(self, message: str, style: str) -> None:
634
+ """Update status line with message."""
635
+ status = self.query_one(STATUS_ID, Static)
636
+ status.update(f"[{style}]{message}[/]")
637
+
638
+ def _show_loading(self, message: str | None = None) -> None:
639
+ """Show the loading indicator and optional status message."""
640
+ show_loading_indicator(self, ACCOUNTS_LOADING_ID, message=message, set_status=self._set_status)
641
+
642
+ def _hide_loading(self) -> None:
643
+ """Hide the loading indicator."""
644
+ hide_loading_indicator(self, ACCOUNTS_LOADING_ID)
645
+
646
+ def _clear_filter(self) -> None:
647
+ """Clear the filter input and reset filter state."""
648
+ filter_input = self.query_one(FILTER_INPUT_ID, Input)
649
+ filter_input.value = ""
650
+ self._filter_text = ""
651
+ self._update_filter_button_visibility()
652
+
653
+ def _queue_switch(self, name: str) -> None:
654
+ """Run switch in background to keep UI responsive."""
655
+
656
+ async def perform() -> None:
657
+ try:
658
+ switched, message = await asyncio.to_thread(self._callbacks.switch_account, name)
659
+ except Exception as exc: # pragma: no cover - defensive
660
+ self._set_status(f"Switch failed: {exc}", "red")
661
+ return
662
+ finally:
663
+ self._hide_loading()
664
+ self._is_switching = False
665
+
666
+ if switched:
667
+ self._active_account = name
668
+ self._set_status(message or f"Switched to '{name}'.", "green")
669
+ self._update_header()
670
+ self._reload_rows()
671
+ else:
672
+ self._set_status(message or "Switch failed; kept previous account.", "yellow")
673
+
674
+ try:
675
+ self.track_task(perform(), logger=logging.getLogger(__name__))
676
+ except Exception as exc:
677
+ # If scheduling the task fails, clear loading/switching state and surface the error.
678
+ self._hide_loading()
679
+ self._is_switching = False
680
+ self._set_status(f"Switch failed to start: {exc}", "red")
681
+ logging.getLogger(__name__).debug("Failed to schedule switch task", exc_info=exc)
682
+
683
+ def _update_header(self) -> None:
684
+ """Refresh header text to reflect active/lock state."""
685
+ header = self.query_one("#header-info", Static)
686
+ header.update(self._header_text())
687
+
688
+ def action_clear_or_exit(self) -> None:
689
+ """Clear or exit filter when focused; otherwise exit app.
690
+
691
+ UX note: helps users reset the list without leaving the TUI.
692
+ """
693
+ filter_input = self.query_one(FILTER_INPUT_ID, Input)
694
+ if filter_input.has_focus:
695
+ # Clear when there is text; otherwise just move focus back to the table
696
+ if filter_input.value or self._filter_text:
697
+ self._clear_filter()
698
+ self._reload_rows()
699
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
700
+ table.focus()
701
+ return
702
+ self.exit()
703
+
704
+ def action_app_exit(self) -> None:
705
+ """Exit the application regardless of focus state."""
706
+ self.exit()
707
+
708
+ def on_button_pressed(self, event: Button.Pressed) -> None:
709
+ """Handle filter bar buttons."""
710
+ if event.button.id == "filter-clear":
711
+ self._clear_filter()
712
+ self._reload_rows()
713
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
714
+ table.focus()
715
+
716
+ def action_add_account(self) -> None:
717
+ """Open add account modal."""
718
+ if self._check_env_lock_hotkey():
719
+ return
720
+ if self._should_block_actions():
721
+ return
722
+ existing_names = {str(row.get("name", "")) for row in self._all_rows}
723
+ modal = AccountFormModal(
724
+ mode="add",
725
+ existing=None,
726
+ existing_names=existing_names,
727
+ connection_tester=lambda url, key: check_connection_with_reason(url, key, abort_on_error=False),
728
+ validate_name=self._store.validate_account_name,
729
+ )
730
+ self.push_screen(modal, self._on_form_result)
731
+
732
+ def action_edit_account(self) -> None:
733
+ """Open edit account modal for selected row."""
734
+ if self._check_env_lock_hotkey():
735
+ return
736
+ if self._should_block_actions():
737
+ return
738
+ name = self._get_selected_name()
739
+ if not name:
740
+ self._set_status("Select an account to edit.", "yellow")
741
+ return
742
+ account = self._store.get_account(name)
743
+ if not account:
744
+ self._set_status(f"Account '{name}' not found.", "red")
745
+ return
746
+ existing_names = {str(row.get("name", "")) for row in self._all_rows if str(row.get("name", "")) != name}
747
+ modal = AccountFormModal(
748
+ mode="edit",
749
+ existing={"name": name, "api_url": account.get("api_url", ""), "api_key": account.get("api_key", "")},
750
+ existing_names=existing_names,
751
+ connection_tester=lambda url, key: check_connection_with_reason(url, key, abort_on_error=False),
752
+ validate_name=self._store.validate_account_name,
753
+ )
754
+ self.push_screen(modal, self._on_form_result)
755
+
756
+ def action_delete_account(self) -> None:
757
+ """Open delete confirmation modal."""
758
+ if self._check_env_lock_hotkey():
759
+ return
760
+ if self._should_block_actions():
761
+ return
762
+ name = self._get_selected_name()
763
+ if not name:
764
+ self._set_status("Select an account to delete.", "yellow")
765
+ return
766
+ accounts = self._store.list_accounts()
767
+ if len(accounts) <= 1:
768
+ self._set_status("Cannot remove the last remaining account.", "red")
769
+ return
770
+ self.push_screen(ConfirmDeleteModal(name), self._on_delete_result)
771
+
772
+ def action_copy_account(self) -> None:
773
+ """Copy selected account name and URL to clipboard."""
774
+ name = self._get_selected_name()
775
+ if not name:
776
+ self._set_status("Select an account to copy.", "yellow")
777
+ return
778
+
779
+ account = self._store.get_account(name)
780
+ if not account:
781
+ return
782
+
783
+ text = f"Account: {name}\nURL: {account.get('api_url', '')}"
784
+ adapter = ClipboardAdapter()
785
+ result = adapter.copy(text)
786
+
787
+ if result.success:
788
+ self._set_status(f"Copied '{name}' to clipboard.", "green")
789
+ else:
790
+ self._set_status(f"Copy failed: {result.message}", "red")
791
+
792
+ def _check_env_lock_hotkey(self) -> bool:
793
+ """Prevent mutations when env credentials are present."""
794
+ if not self._is_env_locked():
795
+ return False
796
+ self._env_lock = True
797
+ self._set_status("Disabled by env-lock.", "yellow")
798
+ # Refresh UI to reflect env-lock state (header/banners/rows)
799
+ self._refresh_rows(preferred_name=self._active_account)
800
+ return True
801
+
802
+ def _on_form_result(self, payload: dict[str, Any] | None) -> None:
803
+ """Handle add/edit modal result."""
804
+ if payload is None:
805
+ self._set_status("Edit/add cancelled.", "yellow")
806
+ return
807
+ self._save_account(payload)
808
+
809
+ def _on_delete_result(self, confirmed_name: str | None) -> None:
810
+ """Handle delete confirmation result."""
811
+ if not confirmed_name:
812
+ self._set_status("Delete cancelled.", "yellow")
813
+ return
814
+ try:
815
+ self._store.remove_account(confirmed_name)
816
+ except AccountStoreError as exc:
817
+ self._set_status(f"Delete failed: {exc}", "red")
818
+ return
819
+ except Exception as exc: # pragma: no cover - defensive
820
+ self._set_status(f"Unexpected delete error: {exc}", "red")
821
+ return
822
+
823
+ self._set_status(f"Account '{confirmed_name}' deleted.", "green")
824
+ # Clear filter before refresh to show all accounts
825
+ self._clear_filter()
826
+ # Refresh rows without preferred name to show all accounts
827
+ # Active account will be cleared if the deleted account was active
828
+ self._refresh_rows(preferred_name=None)
829
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
830
+ table.focus()
831
+
832
+ def _save_account(self, payload: dict[str, Any]) -> None:
833
+ """Persist account data from modal payload."""
834
+ if self._is_env_locked():
835
+ self._set_status("Disabled by env-lock.", "yellow")
836
+ return
837
+
838
+ name = str(payload.get("name", ""))
839
+ api_url = str(payload.get("api_url", ""))
840
+ api_key = str(payload.get("api_key", ""))
841
+ set_active = bool(payload.get("set_active", payload.get("mode") == "add"))
842
+ is_edit = payload.get("mode") == "edit"
843
+
844
+ try:
845
+ self._store.add_account(name, api_url, api_key, overwrite=is_edit)
846
+ except AccountStoreError as exc:
847
+ self._set_status(f"Save failed: {exc}", "red")
848
+ return
849
+ except Exception as exc: # pragma: no cover - defensive
850
+ self._set_status(f"Unexpected save error: {exc}", "red")
851
+ return
852
+
853
+ if set_active:
854
+ try:
855
+ self._store.set_active_account(name)
856
+ self._active_account = name
857
+ except Exception as exc: # pragma: no cover - defensive
858
+ self._set_status(f"Saved but could not set active: {exc}", "yellow")
859
+ else:
860
+ self._announce_active_change(name)
861
+ self._update_header()
862
+
863
+ self._set_status(f"Account '{name}' saved.", "green")
864
+ # Clear filter before refresh to show all accounts
865
+ self._clear_filter()
866
+ # Refresh rows with preferred name to highlight the saved account
867
+ self._refresh_rows(preferred_name=name)
868
+ # Return focus to the table for immediate hotkey use
869
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
870
+ table.focus()
871
+
872
+ def _refresh_rows(self, preferred_name: str | None = None) -> None:
873
+ """Reload rows from store and preserve filter/cursor."""
874
+ self._env_lock = self._is_env_locked()
875
+ self._all_rows, self._active_account = _build_account_rows_from_store(self._store, self._env_lock)
876
+ self._reload_rows(preferred_name=preferred_name)
877
+ self._update_header()
878
+
879
+ def _get_selected_name(self) -> str | None:
880
+ """Return selected account name, if any."""
881
+ table = self.query_one(ACCOUNTS_TABLE_ID, DataTable)
882
+ if table.cursor_row is None:
883
+ return None
884
+ try:
885
+ row = table.get_row_at(table.cursor_row)
886
+ except Exception:
887
+ return None
888
+ return str(row[0]) if row else None
889
+
890
+ def _is_env_locked(self) -> bool:
891
+ """Return True when env credentials are set (even partially)."""
892
+ return env_credentials_present(partial=True)
893
+
894
+ def _announce_active_change(self, name: str) -> None:
895
+ """Surface active account change in status bar."""
896
+ account = self._store.get_account(name) or {}
897
+ host = account.get("api_url", "")
898
+ host_suffix = f" • {host}" if host else ""
899
+ self._set_status(f"Active account ➜ {name}{host_suffix}", "green")
900
+
901
+ def _should_block_actions(self) -> bool:
902
+ """Return True when mutating hotkeys are blocked by filter focus."""
903
+ filter_input = self.query_one(FILTER_INPUT_ID, Input)
904
+ if filter_input.has_focus:
905
+ self._set_status("Exit filter (Esc or Clear) to add/edit/delete.", "yellow")
906
+ return True
907
+ return False
908
+
909
+ def _update_filter_button_visibility(self) -> None:
910
+ """Show clear button only when filter has content."""
911
+ filter_input = self.query_one(FILTER_INPUT_ID, Input)
912
+ clear_btn = self.query_one("#filter-clear", Button)
913
+ clear_btn.display = bool(filter_input.value or self._filter_text)
914
+
915
+ def _apply_theme(self) -> None:
916
+ """Register built-in themes and set the active one from context."""
917
+ if not self._ctx or not self._ctx.theme or Theme is None:
918
+ return
919
+
920
+ for name, tokens in _BUILTIN_THEMES.items():
921
+ self.register_theme(
922
+ Theme(
923
+ name=name,
924
+ primary=tokens.primary,
925
+ secondary=tokens.secondary,
926
+ accent=tokens.accent,
927
+ warning=tokens.warning,
928
+ error=tokens.error,
929
+ success=tokens.success,
930
+ )
931
+ )
932
+
933
+ self.theme = self._ctx.theme.theme_name