fleetdeck 0.3.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 (44) hide show
  1. fleetdeck/__init__.py +3 -0
  2. fleetdeck/__main__.py +232 -0
  3. fleetdeck/accounts.py +115 -0
  4. fleetdeck/adapters/__init__.py +0 -0
  5. fleetdeck/adapters/base.py +71 -0
  6. fleetdeck/adapters/claude_cli.py +187 -0
  7. fleetdeck/adapters/codex_cli.py +362 -0
  8. fleetdeck/adapters/demo.py +331 -0
  9. fleetdeck/config.py +323 -0
  10. fleetdeck/db.py +511 -0
  11. fleetdeck/gitinfo.py +169 -0
  12. fleetdeck/models.py +178 -0
  13. fleetdeck/paths.py +64 -0
  14. fleetdeck/proc.py +92 -0
  15. fleetdeck/redact.py +51 -0
  16. fleetdeck/services/__init__.py +0 -0
  17. fleetdeck/services/dispatcher.py +382 -0
  18. fleetdeck/services/fleet.py +65 -0
  19. fleetdeck/services/monitor.py +253 -0
  20. fleetdeck/services/notifier.py +71 -0
  21. fleetdeck/status.py +97 -0
  22. fleetdeck/terminal.py +235 -0
  23. fleetdeck/termrender.py +129 -0
  24. fleetdeck/ui/__init__.py +0 -0
  25. fleetdeck/ui/app.py +1295 -0
  26. fleetdeck/ui/app.tcss +263 -0
  27. fleetdeck/ui/commands.py +63 -0
  28. fleetdeck/ui/screens/__init__.py +0 -0
  29. fleetdeck/ui/screens/modals.py +623 -0
  30. fleetdeck/ui/style.py +150 -0
  31. fleetdeck/ui/views.py +230 -0
  32. fleetdeck/ui/widgets/__init__.py +0 -0
  33. fleetdeck/ui/widgets/agent_table.py +185 -0
  34. fleetdeck/ui/widgets/bottom.py +27 -0
  35. fleetdeck/ui/widgets/details.py +295 -0
  36. fleetdeck/ui/widgets/header.py +87 -0
  37. fleetdeck/ui/widgets/sidebar.py +227 -0
  38. fleetdeck/ui/widgets/splitter.py +66 -0
  39. fleetdeck/ui/widgets/terminal.py +119 -0
  40. fleetdeck-0.3.0.dist-info/METADATA +245 -0
  41. fleetdeck-0.3.0.dist-info/RECORD +44 -0
  42. fleetdeck-0.3.0.dist-info/WHEEL +4 -0
  43. fleetdeck-0.3.0.dist-info/entry_points.txt +2 -0
  44. fleetdeck-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,331 @@
1
+ """Simulated backend for `fleetdeck --demo`.
2
+
3
+ Produces records in the same documented shape as `claude agents --json --all`
4
+ so the whole pipeline (status mapping, project matching, dispatcher, UI) runs
5
+ unchanged. Nothing here talks to Claude Code.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import random
12
+ import subprocess
13
+ import time
14
+ import uuid
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from .base import CommandResult, LaunchSpec
20
+
21
+ DEMO_PROJECTS: list[tuple[str, str]] = [
22
+ ("acme-billing-api", "office"),
23
+ ("acme-web-console", "office"),
24
+ ("data-pipeline", "office"),
25
+ ("personal-blog", "personal"),
26
+ ("rust-raytracer", "personal"),
27
+ ]
28
+
29
+ _LOG_SCRIPT = [
30
+ "⏺ Reading CLAUDE.md and project structure",
31
+ "⏺ Read(src/{mod}/service.ts)",
32
+ "⏺ Grep(\"{sym}\") — 7 matches in 4 files",
33
+ "⏺ Planning: 1) add validation 2) update callers 3) extend tests",
34
+ "⏺ Edit(src/{mod}/service.ts) +24 −6",
35
+ "⏺ Edit(src/{mod}/controller.ts) +9 −2",
36
+ "⏺ Bash(npm run build) — exit 0",
37
+ "⏺ Bash(npm test -- {mod}) — 42 passed",
38
+ "⏺ Write(src/{mod}/__tests__/{mod}.spec.ts)",
39
+ "⏺ Bash(npm test) — 118 passed, 0 failed",
40
+ "⏺ Summary: implemented change, build and tests green",
41
+ ]
42
+
43
+ _SCENARIOS = ("ok", "ok", "ok", "permission", "input", "fail")
44
+
45
+ # (project index, scenario, session name, age seconds, task title, task prompt)
46
+ INITIAL_SESSIONS = [
47
+ (0, "ok", "refactor-invoice-service", 1240, "Refactor invoice service",
48
+ "Split InvoiceService into pricing and persistence; keep the public API stable."),
49
+ (0, "permission", "add-stripe-webhooks", 410, "Stripe webhooks",
50
+ "Add verified Stripe webhook handling for invoice.paid and invoice.failed."),
51
+ (1, "ok", "dark-mode-settings", 95, "Dark mode settings",
52
+ "Add a dark-mode toggle to the settings page, persisted per user."),
53
+ (2, "fail", "backfill-partitions", 1800, "Backfill partitions",
54
+ "Backfill monthly event partitions for 2024 and verify row counts."),
55
+ (3, "input", "draft-release-notes", 300, "Draft release notes",
56
+ "Draft release notes for v2.3 from merged PRs since the last tag."),
57
+ (4, "ok", "bvh-acceleration", 2600, "BVH acceleration",
58
+ "Implement a BVH for triangle meshes and benchmark against the naive path."),
59
+ ]
60
+
61
+
62
+ # Sessions for the demo's other accounts (same tuple shape as INITIAL_SESSIONS)
63
+ WORK_SESSIONS = [
64
+ (1, "permission", "migrate-auth-to-oidc", 820, "OIDC migration",
65
+ "Migrate the console's auth from sessions to OIDC; keep existing logins valid."),
66
+ ]
67
+ CODEX_SESSIONS = [
68
+ (1, "ok", "add-e2e-tests", 640, "Add e2e tests",
69
+ "Add Playwright e2e tests for the checkout flow."),
70
+ (4, "ok", "profile-render-loop", 1500, "Profile render loop",
71
+ "Profile the render loop and remove the top allocation hotspot."),
72
+ ]
73
+
74
+
75
+ def demo_fleet(workspace: list[tuple[str, str, str]], *, speed: float = 1.0,
76
+ seed: int | None = None):
77
+ """Three demo accounts: your Claude login, a second Claude login, ChatGPT."""
78
+ from ..config import Account
79
+ from ..services.fleet import Fleet, Member
80
+ return Fleet([
81
+ Member(Account("claude", "claude"), DemoBackend(workspace, speed=speed, seed=seed)),
82
+ Member(Account("work", "claude", "~/.claude-work"),
83
+ DemoBackend(workspace, speed=speed, seed=(seed or 0) + 1,
84
+ initial=WORK_SESSIONS, interactive=False)),
85
+ Member(Account("chatgpt", "codex"),
86
+ DemoBackend(workspace, speed=speed, seed=(seed or 0) + 2, provider="codex",
87
+ initial=CODEX_SESSIONS, interactive=False)),
88
+ ], active="claude")
89
+
90
+
91
+ def seed_demo_tasks(store, workspace: list[tuple[str, str, str]]) -> None:
92
+ """Give the pre-running demo sessions real task rows + launch records, so
93
+ the Task column and task queue go through the same code path as live use."""
94
+ import time as _time
95
+ from ..models import TaskStatus
96
+
97
+ import os
98
+ projects = {p.path: p for p in store.list_projects()} # stored as realpath
99
+ now = _time.time()
100
+ every = ([(s, "claude") for s in INITIAL_SESSIONS] + [(s, "work") for s in WORK_SESSIONS]
101
+ + [(s, "chatgpt") for s in CODEX_SESSIONS])
102
+ for (pidx, scenario, name, age, title, prompt), account in every:
103
+ project = projects.get(os.path.realpath(workspace[pidx][2]))
104
+ if project is None:
105
+ continue
106
+ task = store.add_task(project.id, title, prompt, priority=2, account=account)
107
+ store.update_task(task.id, status=TaskStatus.RUNNING, agent_name=name,
108
+ started_at=now - age - 1, attempts=1)
109
+ store.record_launch(name, project_id=project.id, task_id=task.id,
110
+ model=("gpt-5" if account == "chatgpt" else
111
+ "opus" if pidx % 2 == 0 else "sonnet"),
112
+ permission_mode="plan" if scenario == "input" else "default",
113
+ prompt=prompt)
114
+
115
+
116
+ @dataclass
117
+ class _Sim:
118
+ id: str
119
+ name: str
120
+ cwd: str
121
+ started: float
122
+ scenario: str
123
+ kind: str = "background"
124
+ state: str = "working"
125
+ status: str | None = "busy"
126
+ waiting_for: str | None = None
127
+ step: int = 0
128
+ log: list[str] = field(default_factory=list)
129
+ next_at: float = 0.0
130
+ mod: str = "billing"
131
+ session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
132
+ pid: int = field(default_factory=lambda: random.randint(20_000, 90_000))
133
+
134
+
135
+ def ensure_demo_workspace(root: Path) -> list[tuple[str, str, str]]:
136
+ """Create small real git repos with uncommitted changes (idempotent).
137
+
138
+ Returns (name, group, path) per demo project.
139
+ """
140
+ out = []
141
+ root.mkdir(parents=True, exist_ok=True)
142
+ for name, group in DEMO_PROJECTS:
143
+ repo = root / name
144
+ if not (repo / ".git").exists():
145
+ (repo / "src").mkdir(parents=True, exist_ok=True)
146
+ (repo / "README.md").write_text(f"# {name}\n\nDemo project for fleetdeck.\n")
147
+ (repo / "src" / "app.py").write_text("def main():\n return 'hello'\n")
148
+ git = ["git", "-C", str(repo), "-c", "user.name=demo",
149
+ "-c", "user.email=demo@example.invalid"]
150
+ try:
151
+ subprocess.run([*git[:3], "init", "-q", "-b", "main"], check=True,
152
+ capture_output=True)
153
+ subprocess.run([*git, "add", "."], check=True, capture_output=True)
154
+ subprocess.run([*git, "commit", "-qm", "initial"], check=True,
155
+ capture_output=True)
156
+ except (OSError, subprocess.CalledProcessError):
157
+ pass
158
+ (repo / "src" / "app.py").write_text(
159
+ "def main():\n return greet('world')\n\n\n"
160
+ "def greet(who: str) -> str:\n return f'hello {who}'\n"
161
+ )
162
+ (repo / "src" / "new_feature.py").write_text("FEATURE_FLAG = True\n")
163
+ out.append((name, group, str(repo)))
164
+ return out
165
+
166
+
167
+ class DemoBackend:
168
+ name = "demo"
169
+ is_demo = True
170
+
171
+ def __init__(self, workspace: list[tuple[str, str, str]], *, speed: float = 1.0,
172
+ seed: int | None = None, provider: str = "claude",
173
+ initial: list | None = None, interactive: bool = True) -> None:
174
+ self._rng = random.Random(seed)
175
+ self._speed = speed
176
+ self.provider = provider
177
+ self._sims: dict[str, _Sim] = {}
178
+ now = time.time()
179
+ mods = ["billing", "auth", "ingest", "posts", "render"]
180
+ sessions = INITIAL_SESSIONS if initial is None else initial
181
+ for i, (pidx, scenario, name, age, _title, _prompt) in enumerate(sessions):
182
+ _, _, path = workspace[pidx]
183
+ sim = self._new_sim(name, path, scenario, now - age, mods[pidx])
184
+ # fast-forward pre-existing sessions
185
+ for _ in range(self._rng.randint(2, 6)):
186
+ self._advance(sim, now)
187
+ self._sims[sim.id] = sim
188
+ if interactive: # one interactive session, like a terminal the user has open
189
+ _, _, path = workspace[1]
190
+ inter = _Sim(id="", name=f"{Path(path).name}-a1", cwd=path, started=now - 3600,
191
+ scenario="ok", kind="interactive", state="", status="idle")
192
+ self._sims["interactive-1"] = inter
193
+ self._last_tick = now
194
+
195
+ # ------------------------------------------------------------ helpers
196
+ def _new_sim(self, name: str, cwd: str, scenario: str, started: float, mod: str) -> _Sim:
197
+ sid = uuid.uuid4().hex[:8]
198
+ return _Sim(id=sid, name=name, cwd=cwd, started=started, scenario=scenario,
199
+ mod=mod, next_at=time.time() + self._delay())
200
+
201
+ def _delay(self) -> float:
202
+ return self._rng.uniform(1.5, 4.0) / self._speed
203
+
204
+ def _advance(self, sim: _Sim, now: float) -> None:
205
+ if sim.kind != "background" or sim.state in ("done", "failed", "stopped"):
206
+ return
207
+ if sim.state == "blocked":
208
+ return # waits for the user (attach is simulated by respawn)
209
+ line = _LOG_SCRIPT[min(sim.step, len(_LOG_SCRIPT) - 1)]
210
+ sim.log.append(line.format(mod=sim.mod, sym=f"{sim.mod.capitalize()}Service"))
211
+ sim.step += 1
212
+ if sim.scenario == "permission" and sim.step == 4:
213
+ sim.state, sim.status, sim.waiting_for = "blocked", "waiting", "permission prompt"
214
+ sim.log.append("⏺ Bash(rm -rf build && npm run migrate) — awaiting permission")
215
+ elif sim.scenario == "input" and sim.step == 3:
216
+ sim.state, sim.status, sim.waiting_for = "blocked", "waiting", "input needed"
217
+ sim.log.append("⏺ Question: should the changelog include internal refactors?")
218
+ elif sim.scenario == "fail" and sim.step == 5:
219
+ sim.state, sim.status = "failed", None
220
+ sim.log.append("✗ Error: migration 0042 failed: relation \"events_2024\" exists")
221
+ sim.log.append(" DATABASE_URL=postgres://app:hunter2secret@db:5432/app")
222
+ elif sim.step >= len(_LOG_SCRIPT):
223
+ sim.state, sim.status = "done", "idle"
224
+ sim.next_at = now + self._delay()
225
+
226
+ def _tick(self) -> None:
227
+ now = time.time()
228
+ for sim in self._sims.values():
229
+ if sim.next_at and now >= sim.next_at:
230
+ self._advance(sim, now)
231
+
232
+ def _record(self, s: _Sim) -> dict[str, Any]:
233
+ rec: dict[str, Any] = {
234
+ "cwd": s.cwd,
235
+ "kind": s.kind,
236
+ "startedAt": int(s.started * 1000),
237
+ "sessionId": s.session_id,
238
+ "name": s.name,
239
+ }
240
+ if s.kind == "background":
241
+ rec["id"] = s.id
242
+ rec["state"] = s.state
243
+ if self.provider == "codex": # Codex reports real token usage per turn
244
+ rec["provider"] = "codex"
245
+ rec["usage"] = {"input_tokens": 18_000 + 9_500 * s.step,
246
+ "output_tokens": 240 * s.step}
247
+ alive = s.kind == "interactive" or s.state in ("working", "blocked", "done")
248
+ if alive and s.status:
249
+ rec["pid"] = s.pid
250
+ rec["status"] = s.status
251
+ if s.status == "waiting" and s.waiting_for:
252
+ rec["waitingFor"] = s.waiting_for
253
+ return rec
254
+
255
+ # ------------------------------------------------------------ backend
256
+ async def version(self) -> str | None:
257
+ return "demo"
258
+
259
+ async def list_sessions(self, env: dict[str, str]) -> list[dict[str, Any]]:
260
+ await asyncio.sleep(0.02)
261
+ self._tick()
262
+ return [self._record(s) for s in self._sims.values()]
263
+
264
+ async def launch(self, spec: LaunchSpec) -> CommandResult:
265
+ await asyncio.sleep(0.1)
266
+ scenario = self._rng.choice(_SCENARIOS)
267
+ sim = self._new_sim(spec.name, spec.cwd, scenario, time.time(),
268
+ Path(spec.cwd).name.split("-")[0])
269
+ sim.log.append(f"⏺ Task: {spec.prompt[:120]}")
270
+ if spec.permission_mode == "plan":
271
+ sim.log.append("⏺ Plan mode: exploring before proposing changes")
272
+ self._sims[sim.id] = sim
273
+ return CommandResult(True, f"backgrounded · {sim.id} · {spec.name}", sim.id)
274
+
275
+ async def follow_up(self, session_id: str, prompt: str, *, cwd: str,
276
+ env: dict[str, str]) -> CommandResult:
277
+ await asyncio.sleep(0.1)
278
+ sim = next((s for s in self._sims.values() if s.session_id == session_id), None)
279
+ if sim is None:
280
+ return CommandResult(False, f"No conversation found with session ID: {session_id}")
281
+ if sim.state in ("working", "blocked"):
282
+ return CommandResult(False, "session is busy")
283
+ sim.state, sim.status, sim.waiting_for = "working", "busy", None
284
+ sim.scenario, sim.step = "ok", max(0, len(_LOG_SCRIPT) - 4)
285
+ sim.started = time.time() # like the real CLI, a woken session restarts its clock
286
+ sim.next_at = time.time() + self._delay()
287
+ sim.log.append(f"❯ {prompt[:120]}")
288
+ return CommandResult(True, f"note: woke session {sim.id}\nbackgrounded · {sim.id} · "
289
+ f"{sim.name}", sim.id)
290
+
291
+ def _find(self, agent_id: str) -> _Sim | None:
292
+ for s in self._sims.values():
293
+ if s.id == agent_id or s.name == agent_id:
294
+ return s
295
+ return None
296
+
297
+ async def logs(self, agent_id: str, env: dict[str, str]) -> CommandResult:
298
+ s = self._find(agent_id)
299
+ if not s:
300
+ return CommandResult(False, f"No session matching '{agent_id}'.")
301
+ header = f"Session {s.id} · {s.name} [DEMO — simulated output]"
302
+ return CommandResult(True, "\n".join([header, *s.log]))
303
+
304
+ async def stop(self, agent_id: str, env: dict[str, str]) -> CommandResult:
305
+ s = self._find(agent_id)
306
+ if not s:
307
+ return CommandResult(False, f"No session matching '{agent_id}'.")
308
+ s.state, s.status, s.waiting_for = "stopped", None, None
309
+ s.log.append("■ Stopped by user")
310
+ return CommandResult(True, f"stopped {s.id}")
311
+
312
+ async def respawn(self, agent_id: str, env: dict[str, str]) -> CommandResult:
313
+ s = self._find(agent_id)
314
+ if not s:
315
+ return CommandResult(False, f"No session matching '{agent_id}'.")
316
+ s.state, s.status, s.waiting_for = "working", "busy", None
317
+ s.scenario = "ok"
318
+ s.step = max(0, s.step - 2)
319
+ s.next_at = time.time() + self._delay()
320
+ s.log.append("↻ Respawned")
321
+ return CommandResult(True, f"respawned {s.id}")
322
+
323
+ async def remove(self, agent_id: str, env: dict[str, str]) -> CommandResult:
324
+ s = self._find(agent_id)
325
+ if not s:
326
+ return CommandResult(False, f"No session matching '{agent_id}'.")
327
+ self._sims = {k: v for k, v in self._sims.items() if v is not s}
328
+ return CommandResult(True, f"removed {s.id}")
329
+
330
+ def attach_argv(self, agent_id: str) -> list[str] | None:
331
+ return None
fleetdeck/config.py ADDED
@@ -0,0 +1,323 @@
1
+ """YAML settings with validated defaults."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import asdict, dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ from . import paths
13
+ from .models import SAFE_PERMISSION_MODES
14
+
15
+ # action id -> default keys (comma separated alternatives, Textual syntax).
16
+ # Ctrl+digit is only delivered by terminals with an extended keyboard
17
+ # protocol (kitty, WezTerm, Ghostty, recent iTerm2), so plain digits are
18
+ # bound as fallbacks.
19
+ DEFAULT_KEYBINDINGS: dict[str, str] = {
20
+ "new_agent": "n",
21
+ "add_project": "p",
22
+ "attach": "enter",
23
+ "preview": "space",
24
+ "logs": "l",
25
+ "diff": "d",
26
+ "stop": "s",
27
+ "restart": "r",
28
+ "search": "f,slash",
29
+ "pin": "t",
30
+ "new_task": "a",
31
+ "run_tests": "x",
32
+ "toggle_dispatch": "z",
33
+ "follow_up": "m",
34
+ "terminal": "ctrl+t",
35
+ "switch_account": "ctrl+a",
36
+ "details_wider": "right_square_bracket",
37
+ "details_narrower": "left_square_bracket",
38
+ "sidebar_wider": "right_curly_bracket",
39
+ "sidebar_narrower": "left_curly_bracket",
40
+ "zoom_details": "backslash",
41
+ "refresh": "ctrl+r",
42
+ "view_dashboard": "ctrl+1,1",
43
+ "view_projects": "ctrl+2,2",
44
+ "view_sessions": "ctrl+3,3",
45
+ "view_tasks": "ctrl+4,4",
46
+ "view_settings": "ctrl+5,5",
47
+ "help": "question_mark",
48
+ "quit": "q",
49
+ }
50
+
51
+ THEMES = (
52
+ "catppuccin-mocha",
53
+ "catppuccin-macchiato",
54
+ "catppuccin-frappe",
55
+ "catppuccin-latte",
56
+ "tokyo-night",
57
+ "nord",
58
+ "dracula",
59
+ "gruvbox",
60
+ "rose-pine",
61
+ )
62
+
63
+ WORKTREE_MODES = ("auto", "always", "never")
64
+
65
+
66
+ @dataclass
67
+ class Notifications:
68
+ toast: bool = True
69
+ bell: bool = False
70
+ desktop: bool = False # macOS osascript / notify-send
71
+
72
+
73
+ @dataclass
74
+ class Environment:
75
+ """Extra environment for `claude` invocations (e.g. CLAUDE_CONFIG_DIR to
76
+ keep an office account separate from a personal one)."""
77
+
78
+ env: dict[str, str] = field(default_factory=dict)
79
+
80
+
81
+ PROVIDERS = ("claude", "codex")
82
+
83
+
84
+ @dataclass
85
+ class Account:
86
+ """A signed-in CLI account. ``home`` is CLAUDE_CONFIG_DIR (claude) or
87
+ CODEX_HOME (codex); None means the CLI's default location."""
88
+
89
+ name: str
90
+ provider: str = "claude"
91
+ home: str | None = None
92
+ # macOS Keychain item holding a long-lived token from `claude setup-token`;
93
+ # read only at runtime, passed as CLAUDE_CODE_OAUTH_TOKEN, never stored.
94
+ token_keychain: str | None = None
95
+ extra_env: dict[str, str] = field(default_factory=dict)
96
+
97
+ @property
98
+ def env(self) -> dict[str, str]:
99
+ """Static environment (no secrets); see accounts.resolve_env for tokens."""
100
+ out = dict(self.extra_env)
101
+ if self.home:
102
+ out["CLAUDE_CONFIG_DIR" if self.provider == "claude" else "CODEX_HOME"] = self.home
103
+ return out
104
+
105
+ @property
106
+ def icon(self) -> str:
107
+ return "◆" if self.provider == "claude" else "◎"
108
+
109
+
110
+ def default_accounts(codex_available: bool) -> list[Account]:
111
+ out = [Account("claude", "claude", None)]
112
+ if codex_available:
113
+ out.append(Account("chatgpt", "codex", None))
114
+ return out
115
+
116
+
117
+ @dataclass
118
+ class Settings:
119
+ theme: str = "catppuccin-mocha"
120
+ refresh_interval: float = 2.0
121
+ # used while the terminal is unfocused or nothing is running / queued
122
+ idle_refresh_interval: float = 10.0
123
+ git_refresh_interval: float = 5.0
124
+ log_refresh_interval: float = 2.0
125
+ log_lines: int = 400
126
+ max_concurrent_agents: int = 4
127
+ dispatch_paused: bool = False
128
+ claude_binary: str = "claude"
129
+ codex_binary: str = "codex"
130
+ # empty = automatic (your default Claude login, plus ChatGPT via Codex if installed)
131
+ accounts: list[Account] = field(default_factory=list)
132
+ active_account: str | None = None # default account for new agents
133
+ command_timeout: float = 15.0
134
+ default_model: str | None = None
135
+ default_permission_mode: str = "default"
136
+ worktree_isolation: str = "auto"
137
+ show_interactive_sessions: bool = True
138
+ # panel widths in columns (None = automatic); set by dragging the dividers
139
+ sidebar_width: int | None = None
140
+ details_width: int | None = None
141
+ notifications: Notifications = field(default_factory=Notifications)
142
+ environments: dict[str, Environment] = field(
143
+ default_factory=lambda: {
144
+ "default": Environment(),
145
+ "office": Environment(),
146
+ "personal": Environment(),
147
+ }
148
+ )
149
+ keybindings: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_KEYBINDINGS))
150
+ # validation problems found while loading; never written back to disk
151
+ load_errors: list[str] = field(default_factory=list, repr=False, compare=False)
152
+
153
+ # ------------------------------------------------------------------ io
154
+ @classmethod
155
+ def from_dict(cls, data: dict[str, Any] | None) -> "Settings":
156
+ data = dict(data or {})
157
+ s = cls()
158
+ errors: list[str] = []
159
+
160
+ def num(key: str, lo: float, hi: float, cast=float) -> None:
161
+ if key in data:
162
+ try:
163
+ v = cast(data[key])
164
+ except (TypeError, ValueError):
165
+ errors.append(f"{key}: not a number")
166
+ return
167
+ setattr(s, key, min(hi, max(lo, v)))
168
+
169
+ num("refresh_interval", 0.5, 300)
170
+ num("idle_refresh_interval", 1, 600)
171
+ num("git_refresh_interval", 1, 600)
172
+ num("log_refresh_interval", 0.5, 300)
173
+ num("log_lines", 20, 10_000, int)
174
+ num("max_concurrent_agents", 1, 64, int)
175
+ num("command_timeout", 2, 300)
176
+ for key in ("sidebar_width", "details_width"):
177
+ if data.get(key) is not None:
178
+ num(key, 16, 400, int)
179
+
180
+ if "theme" in data:
181
+ s.theme = str(data["theme"])
182
+ if "dispatch_paused" in data:
183
+ s.dispatch_paused = bool(data["dispatch_paused"])
184
+ if "show_interactive_sessions" in data:
185
+ s.show_interactive_sessions = bool(data["show_interactive_sessions"])
186
+ if data.get("claude_binary"):
187
+ s.claude_binary = str(data["claude_binary"])
188
+ if data.get("codex_binary"):
189
+ s.codex_binary = str(data["codex_binary"])
190
+ accounts = data.get("accounts")
191
+ if isinstance(accounts, list):
192
+ seen: set[str] = set()
193
+ for i, spec in enumerate(accounts):
194
+ if not isinstance(spec, dict) or not spec.get("name"):
195
+ errors.append(f"accounts[{i}]: needs a name")
196
+ continue
197
+ name = str(spec["name"]).strip()
198
+ provider = str(spec.get("provider", "claude"))
199
+ if provider not in PROVIDERS:
200
+ errors.append(f"accounts.{name}: provider must be one of {PROVIDERS}")
201
+ continue
202
+ if name in seen:
203
+ errors.append(f"accounts.{name}: duplicate name")
204
+ continue
205
+ seen.add(name)
206
+ home = spec.get("home")
207
+ env = spec.get("env") or {}
208
+ if not isinstance(env, dict) or any(
209
+ "TOKEN" in str(k).upper() or "KEY" in str(k).upper() for k in env):
210
+ errors.append(f"accounts.{name}: put secrets in the Keychain "
211
+ "(token_keychain), not in env")
212
+ env = {k: v for k, v in (env if isinstance(env, dict) else {}).items()
213
+ if "TOKEN" not in str(k).upper() and "KEY" not in str(k).upper()}
214
+ s.accounts.append(Account(
215
+ name, provider, os.path.expanduser(str(home)) if home else None,
216
+ token_keychain=str(spec["token_keychain"]) if spec.get("token_keychain")
217
+ else None,
218
+ extra_env={str(k): os.path.expanduser(str(v)) for k, v in env.items()}))
219
+ if data.get("active_account"):
220
+ s.active_account = str(data["active_account"])
221
+ if data.get("default_model"):
222
+ s.default_model = str(data["default_model"])
223
+ if "default_permission_mode" in data:
224
+ mode = str(data["default_permission_mode"])
225
+ if mode in SAFE_PERMISSION_MODES:
226
+ s.default_permission_mode = mode
227
+ else:
228
+ errors.append(
229
+ f"default_permission_mode: {mode!r} not allowed "
230
+ f"(use one of {', '.join(SAFE_PERMISSION_MODES)})"
231
+ )
232
+ if "worktree_isolation" in data:
233
+ wt = str(data["worktree_isolation"])
234
+ if wt in WORKTREE_MODES:
235
+ s.worktree_isolation = wt
236
+ else:
237
+ errors.append(f"worktree_isolation: {wt!r} invalid")
238
+
239
+ n = data.get("notifications") or {}
240
+ if isinstance(n, dict):
241
+ s.notifications = Notifications(
242
+ toast=bool(n.get("toast", True)),
243
+ bell=bool(n.get("bell", False)),
244
+ desktop=bool(n.get("desktop", False)),
245
+ )
246
+
247
+ envs = data.get("environments")
248
+ if isinstance(envs, dict):
249
+ merged = dict(s.environments)
250
+ for name, spec in envs.items():
251
+ spec = spec or {}
252
+ env = spec.get("env", {}) if isinstance(spec, dict) else {}
253
+ merged[str(name)] = Environment(
254
+ env={str(k): os.path.expanduser(str(v)) for k, v in (env or {}).items()}
255
+ )
256
+ s.environments = merged
257
+
258
+ kb = data.get("keybindings")
259
+ if isinstance(kb, dict):
260
+ for action, keys in kb.items():
261
+ if action in DEFAULT_KEYBINDINGS and keys:
262
+ s.keybindings[action] = str(keys)
263
+ else:
264
+ errors.append(f"keybindings: unknown action {action!r}")
265
+
266
+ s.load_errors = errors
267
+ return s
268
+
269
+ def to_dict(self) -> dict[str, Any]:
270
+ d = asdict(self)
271
+ d.pop("load_errors", None)
272
+ return d
273
+
274
+ def effective_accounts(self, codex_available: bool | None = None) -> list[Account]:
275
+ if self.accounts:
276
+ return list(self.accounts)
277
+ if codex_available is None:
278
+ import shutil
279
+ codex_available = shutil.which(self.codex_binary) is not None
280
+ return default_accounts(codex_available)
281
+
282
+ def account(self, name: str | None, accounts: list[Account] | None = None) -> Account | None:
283
+ pool = accounts if accounts is not None else self.effective_accounts()
284
+ if name:
285
+ for a in pool:
286
+ if a.name == name:
287
+ return a
288
+ return None
289
+
290
+ def active(self, accounts: list[Account] | None = None) -> Account:
291
+ pool = accounts if accounts is not None else self.effective_accounts()
292
+ return self.account(self.active_account, pool) or pool[0]
293
+
294
+ def env_for(self, environment: str) -> dict[str, str]:
295
+ env = self.environments.get(environment) or self.environments.get("default")
296
+ return dict(env.env) if env else {}
297
+
298
+
299
+ def load_settings(path: Path | None = None) -> Settings:
300
+ path = path or paths.config_path()
301
+ if not path.exists():
302
+ return Settings()
303
+ try:
304
+ data = yaml.safe_load(path.read_text()) or {}
305
+ except yaml.YAMLError as exc:
306
+ s = Settings()
307
+ s.load_errors = [f"config.yaml is not valid YAML: {exc}"]
308
+ return s
309
+ if not isinstance(data, dict):
310
+ s = Settings()
311
+ s.load_errors = ["config.yaml must be a mapping"]
312
+ return s
313
+ return Settings.from_dict(data)
314
+
315
+
316
+ def save_settings(settings: Settings, path: Path | None = None) -> Path:
317
+ path = path or paths.config_path()
318
+ paths.ensure_private_dir(path.parent)
319
+ tmp = path.with_suffix(".yaml.tmp")
320
+ tmp.write_text(yaml.safe_dump(settings.to_dict(), sort_keys=False))
321
+ os.chmod(tmp, 0o600)
322
+ tmp.replace(path)
323
+ return path