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.
- fleetdeck/__init__.py +3 -0
- fleetdeck/__main__.py +232 -0
- fleetdeck/accounts.py +115 -0
- fleetdeck/adapters/__init__.py +0 -0
- fleetdeck/adapters/base.py +71 -0
- fleetdeck/adapters/claude_cli.py +187 -0
- fleetdeck/adapters/codex_cli.py +362 -0
- fleetdeck/adapters/demo.py +331 -0
- fleetdeck/config.py +323 -0
- fleetdeck/db.py +511 -0
- fleetdeck/gitinfo.py +169 -0
- fleetdeck/models.py +178 -0
- fleetdeck/paths.py +64 -0
- fleetdeck/proc.py +92 -0
- fleetdeck/redact.py +51 -0
- fleetdeck/services/__init__.py +0 -0
- fleetdeck/services/dispatcher.py +382 -0
- fleetdeck/services/fleet.py +65 -0
- fleetdeck/services/monitor.py +253 -0
- fleetdeck/services/notifier.py +71 -0
- fleetdeck/status.py +97 -0
- fleetdeck/terminal.py +235 -0
- fleetdeck/termrender.py +129 -0
- fleetdeck/ui/__init__.py +0 -0
- fleetdeck/ui/app.py +1295 -0
- fleetdeck/ui/app.tcss +263 -0
- fleetdeck/ui/commands.py +63 -0
- fleetdeck/ui/screens/__init__.py +0 -0
- fleetdeck/ui/screens/modals.py +623 -0
- fleetdeck/ui/style.py +150 -0
- fleetdeck/ui/views.py +230 -0
- fleetdeck/ui/widgets/__init__.py +0 -0
- fleetdeck/ui/widgets/agent_table.py +185 -0
- fleetdeck/ui/widgets/bottom.py +27 -0
- fleetdeck/ui/widgets/details.py +295 -0
- fleetdeck/ui/widgets/header.py +87 -0
- fleetdeck/ui/widgets/sidebar.py +227 -0
- fleetdeck/ui/widgets/splitter.py +66 -0
- fleetdeck/ui/widgets/terminal.py +119 -0
- fleetdeck-0.3.0.dist-info/METADATA +245 -0
- fleetdeck-0.3.0.dist-info/RECORD +44 -0
- fleetdeck-0.3.0.dist-info/WHEEL +4 -0
- fleetdeck-0.3.0.dist-info/entry_points.txt +2 -0
- fleetdeck-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Polls the backend, normalises sessions and attributes them to projects."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any, Callable
|
|
11
|
+
|
|
12
|
+
from ..adapters.base import Backend, BackendError
|
|
13
|
+
from ..gitinfo import GitCache
|
|
14
|
+
from ..models import Agent, AgentStatus, Project
|
|
15
|
+
from ..status import STATUS_PRIORITY, derive_status
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(slots=True)
|
|
19
|
+
class Transition:
|
|
20
|
+
agent: Agent
|
|
21
|
+
old: AgentStatus | None
|
|
22
|
+
new: AgentStatus
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(slots=True)
|
|
26
|
+
class Snapshot:
|
|
27
|
+
agents: list[Agent] = field(default_factory=list)
|
|
28
|
+
errors: list[str] = field(default_factory=list)
|
|
29
|
+
transitions: list[Transition] = field(default_factory=list)
|
|
30
|
+
taken_at: float = 0.0
|
|
31
|
+
# True only when every environment's `claude agents` call succeeded. Task
|
|
32
|
+
# sync and dispatch act only on complete snapshots, so one flaky
|
|
33
|
+
# environment can't make another environment's sessions look lost.
|
|
34
|
+
ok: bool = False
|
|
35
|
+
partial: bool = False
|
|
36
|
+
|
|
37
|
+
def by_key(self) -> dict[str, Agent]:
|
|
38
|
+
return {a.key: a for a in self.agents}
|
|
39
|
+
|
|
40
|
+
def find(self, agent_id: str | None = None, name: str | None = None) -> Agent | None:
|
|
41
|
+
for a in self.agents:
|
|
42
|
+
if agent_id and a.id == agent_id:
|
|
43
|
+
return a
|
|
44
|
+
for a in self.agents:
|
|
45
|
+
if name and a.name == name:
|
|
46
|
+
return a
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
def active_background(self) -> list[Agent]:
|
|
50
|
+
return [a for a in self.agents if a.kind == "background" and a.status.is_active]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def poll_due(now: float, last: float, *, base: float, idle_interval: float,
|
|
54
|
+
idle: bool) -> bool:
|
|
55
|
+
"""Adaptive polling: every ``base`` seconds normally, every
|
|
56
|
+
``idle_interval`` while idle (terminal unfocused, or nothing active/queued)."""
|
|
57
|
+
return now - last >= (max(base, idle_interval) if idle else base) - 0.05
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def agent_key(rec: dict[str, Any]) -> str:
|
|
61
|
+
# ids are only unique per account (each account has its own supervisor)
|
|
62
|
+
suffix = f"@{rec['account']}" if rec.get("account") else ""
|
|
63
|
+
if rec.get("id"):
|
|
64
|
+
return f"bg:{rec['id']}{suffix}"
|
|
65
|
+
if rec.get("sessionId"):
|
|
66
|
+
return f"s:{rec['sessionId']}{suffix}"
|
|
67
|
+
return f"pid:{rec.get('pid')}:{rec.get('startedAt')}{suffix}"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def match_project(cwd: str, projects: list[Project]) -> Project | None:
|
|
71
|
+
"""Longest registered path that contains ``cwd`` (worktrees created inside a
|
|
72
|
+
repo, e.g. <repo>/.claude/worktrees/x, resolve to that repo's project)."""
|
|
73
|
+
try:
|
|
74
|
+
real = os.path.realpath(cwd)
|
|
75
|
+
except (OSError, ValueError):
|
|
76
|
+
real = cwd
|
|
77
|
+
best: Project | None = None
|
|
78
|
+
for p in projects:
|
|
79
|
+
base = p.path.rstrip(os.sep)
|
|
80
|
+
if real == base or real.startswith(base + os.sep) or cwd == base or \
|
|
81
|
+
cwd.startswith(base + os.sep):
|
|
82
|
+
if best is None or len(base) > len(best.path):
|
|
83
|
+
best = p
|
|
84
|
+
return best
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def record_to_agent(rec: dict[str, Any], permission_mode: str | None = None) -> Agent:
|
|
88
|
+
kind = str(rec.get("kind") or "unknown")
|
|
89
|
+
started_ms = rec.get("startedAt")
|
|
90
|
+
try:
|
|
91
|
+
started = float(started_ms) / 1000.0 if started_ms is not None else time.time()
|
|
92
|
+
except (TypeError, ValueError):
|
|
93
|
+
started = time.time()
|
|
94
|
+
pid = rec.get("pid")
|
|
95
|
+
return Agent(
|
|
96
|
+
key=agent_key(rec),
|
|
97
|
+
kind=kind,
|
|
98
|
+
cwd=str(rec.get("cwd") or ""),
|
|
99
|
+
started_at=started,
|
|
100
|
+
status=derive_status(
|
|
101
|
+
kind=kind,
|
|
102
|
+
state=rec.get("state"),
|
|
103
|
+
status=rec.get("status"),
|
|
104
|
+
waiting_for=rec.get("waitingFor"),
|
|
105
|
+
permission_mode=permission_mode,
|
|
106
|
+
),
|
|
107
|
+
id=rec.get("id"),
|
|
108
|
+
name=rec.get("name"),
|
|
109
|
+
session_id=rec.get("sessionId"),
|
|
110
|
+
pid=pid if isinstance(pid, int) else None,
|
|
111
|
+
raw_state=rec.get("state"),
|
|
112
|
+
raw_status=rec.get("status"),
|
|
113
|
+
waiting_for=rec.get("waitingFor"),
|
|
114
|
+
permission_mode=permission_mode,
|
|
115
|
+
account=rec.get("account"),
|
|
116
|
+
provider=str(rec.get("provider") or "claude"),
|
|
117
|
+
usage=rec.get("usage") if isinstance(rec.get("usage"), dict) else None,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class Monitor:
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
backend: Backend,
|
|
125
|
+
*,
|
|
126
|
+
projects: Callable[[], list[Project]],
|
|
127
|
+
launches: Callable[[], dict[str, Any]],
|
|
128
|
+
environments: Callable[[], list[dict[str, str]]],
|
|
129
|
+
git: GitCache,
|
|
130
|
+
include_interactive: Callable[[], bool] = lambda: True,
|
|
131
|
+
members: Callable[[], list[Any]] | None = None,
|
|
132
|
+
) -> None:
|
|
133
|
+
self.backend = backend
|
|
134
|
+
# accounts to poll (services.fleet.Member); None = single backend over
|
|
135
|
+
# `environments` (the pre-accounts behaviour)
|
|
136
|
+
self._members = members
|
|
137
|
+
self._projects = projects
|
|
138
|
+
self._launches = launches
|
|
139
|
+
self._environments = environments
|
|
140
|
+
self._include_interactive = include_interactive
|
|
141
|
+
self.git = git
|
|
142
|
+
self._lock = asyncio.Lock()
|
|
143
|
+
self._seen: dict[str, tuple[AgentStatus, float, str]] = {}
|
|
144
|
+
self.last = Snapshot()
|
|
145
|
+
|
|
146
|
+
async def poll(self) -> Snapshot:
|
|
147
|
+
"""Single-flight: concurrent callers share one in-progress poll."""
|
|
148
|
+
if self._lock.locked():
|
|
149
|
+
async with self._lock:
|
|
150
|
+
return self.last
|
|
151
|
+
async with self._lock:
|
|
152
|
+
self.last = await self._poll()
|
|
153
|
+
return self.last
|
|
154
|
+
|
|
155
|
+
async def _poll(self) -> Snapshot:
|
|
156
|
+
jobs: list[tuple[str | None, str | None, Any, dict[str, str]]] = []
|
|
157
|
+
if self._members is not None:
|
|
158
|
+
for m in self._members():
|
|
159
|
+
jobs.append((m.name, m.provider, m.backend, m.env))
|
|
160
|
+
else:
|
|
161
|
+
envs = self._environments() or [{}]
|
|
162
|
+
# dedupe identical environments (most setups have just one)
|
|
163
|
+
uniq: dict[str, dict[str, str]] = {}
|
|
164
|
+
for e in envs:
|
|
165
|
+
uniq.setdefault(json.dumps(e, sort_keys=True), e)
|
|
166
|
+
jobs = [(None, None, self.backend, e) for e in uniq.values()]
|
|
167
|
+
results = await asyncio.gather(
|
|
168
|
+
*(backend.list_sessions(env) for _, _, backend, env in jobs),
|
|
169
|
+
return_exceptions=True,
|
|
170
|
+
)
|
|
171
|
+
records: dict[str, dict[str, Any]] = {}
|
|
172
|
+
errors: list[str] = []
|
|
173
|
+
succeeded = 0
|
|
174
|
+
for (account, provider, _, _), res in zip(jobs, results):
|
|
175
|
+
if isinstance(res, BaseException):
|
|
176
|
+
if isinstance(res, asyncio.CancelledError):
|
|
177
|
+
raise res
|
|
178
|
+
msg = str(res) if isinstance(res, BackendError) else repr(res)
|
|
179
|
+
errors.append(f"{account}: {msg}" if account else msg)
|
|
180
|
+
continue
|
|
181
|
+
succeeded += 1
|
|
182
|
+
for rec in res:
|
|
183
|
+
if account is not None:
|
|
184
|
+
rec = {**rec, "account": account,
|
|
185
|
+
"provider": rec.get("provider") or provider}
|
|
186
|
+
records.setdefault(agent_key(rec), rec)
|
|
187
|
+
|
|
188
|
+
ok = succeeded == len(results)
|
|
189
|
+
projects = self._projects()
|
|
190
|
+
launches = self._launches()
|
|
191
|
+
now = time.time()
|
|
192
|
+
agents: list[Agent] = []
|
|
193
|
+
transitions: list[Transition] = []
|
|
194
|
+
include_inter = self._include_interactive()
|
|
195
|
+
for key, rec in records.items():
|
|
196
|
+
if rec.get("kind") == "interactive" and not include_inter:
|
|
197
|
+
continue
|
|
198
|
+
launch = launches.get(rec.get("name") or "")
|
|
199
|
+
if launch is not None and rec.get("id") and launch["agent_id"] not in (None, rec["id"]):
|
|
200
|
+
launch = None # same name reused by an unrelated session
|
|
201
|
+
agent = record_to_agent(rec, launch["permission_mode"] if launch else None)
|
|
202
|
+
if launch is not None:
|
|
203
|
+
agent.model = launch["model"]
|
|
204
|
+
agent.task_id = launch["task_id"]
|
|
205
|
+
proj = match_project(agent.cwd, projects)
|
|
206
|
+
if proj is None and launch is not None and launch["project_id"]:
|
|
207
|
+
proj = next((p for p in projects if p.id == launch["project_id"]), None)
|
|
208
|
+
if proj is not None:
|
|
209
|
+
agent.project_id, agent.project_name = proj.id, proj.name
|
|
210
|
+
snap = self.git.peek(agent.cwd)
|
|
211
|
+
if snap and snap.is_repo:
|
|
212
|
+
agent.branch = snap.branch
|
|
213
|
+
|
|
214
|
+
fingerprint = f"{rec.get('state')}|{rec.get('status')}|{rec.get('waitingFor')}"
|
|
215
|
+
prev = self._seen.get(key)
|
|
216
|
+
if prev is None:
|
|
217
|
+
agent.last_activity = agent.started_at
|
|
218
|
+
transitions.append(Transition(agent, None, agent.status))
|
|
219
|
+
elif prev[2] != fingerprint:
|
|
220
|
+
agent.last_activity = now
|
|
221
|
+
if prev[0] != agent.status:
|
|
222
|
+
transitions.append(Transition(agent, prev[0], agent.status))
|
|
223
|
+
else:
|
|
224
|
+
agent.last_activity = prev[1]
|
|
225
|
+
self._seen[key] = (agent.status, agent.last_activity or now, fingerprint)
|
|
226
|
+
agents.append(agent)
|
|
227
|
+
|
|
228
|
+
if ok: # forget vanished sessions only when every environment answered
|
|
229
|
+
for key in list(self._seen):
|
|
230
|
+
if key not in records:
|
|
231
|
+
del self._seen[key]
|
|
232
|
+
|
|
233
|
+
agents.sort(key=lambda a: (STATUS_PRIORITY[a.status], -(a.last_activity or 0)))
|
|
234
|
+
return Snapshot(agents=agents, errors=errors, transitions=transitions,
|
|
235
|
+
taken_at=now, ok=ok, partial=0 < succeeded < len(results))
|
|
236
|
+
|
|
237
|
+
async def refresh_git(self, agents: list[Agent]) -> None:
|
|
238
|
+
"""Warm the git cache for every distinct cwd (bounded concurrency)."""
|
|
239
|
+
cwds = {a.cwd for a in agents if a.cwd and os.path.isdir(a.cwd)}
|
|
240
|
+
sem = asyncio.Semaphore(4)
|
|
241
|
+
|
|
242
|
+
async def one(cwd: str) -> None:
|
|
243
|
+
async with sem:
|
|
244
|
+
try:
|
|
245
|
+
await self.git.get(cwd)
|
|
246
|
+
except Exception: # noqa: BLE001 — git failures must not break polling
|
|
247
|
+
pass
|
|
248
|
+
|
|
249
|
+
await asyncio.gather(*(one(c) for c in cwds))
|
|
250
|
+
for a in agents:
|
|
251
|
+
snap = self.git.peek(a.cwd)
|
|
252
|
+
if snap and snap.is_repo:
|
|
253
|
+
a.branch = snap.branch
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Turns status transitions into notifications."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
from ..config import Notifications
|
|
11
|
+
from ..models import AgentStatus
|
|
12
|
+
from ..proc import run
|
|
13
|
+
from .monitor import Transition
|
|
14
|
+
|
|
15
|
+
_NOTIFY_ON = {
|
|
16
|
+
AgentStatus.PERMISSION: ("warning", "needs permission"),
|
|
17
|
+
AgentStatus.WAITING: ("warning", "is waiting for input"),
|
|
18
|
+
AgentStatus.COMPLETED: ("success", "completed"),
|
|
19
|
+
AgentStatus.FAILED: ("error", "failed"),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(slots=True)
|
|
24
|
+
class Notice:
|
|
25
|
+
level: str # info | success | warning | error
|
|
26
|
+
title: str
|
|
27
|
+
message: str
|
|
28
|
+
project_id: int | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def notices_for(transitions: list[Transition]) -> list[Notice]:
|
|
32
|
+
out: list[Notice] = []
|
|
33
|
+
for t in transitions:
|
|
34
|
+
if t.old is None: # first sighting at startup: not news
|
|
35
|
+
continue
|
|
36
|
+
spec = _NOTIFY_ON.get(t.new)
|
|
37
|
+
if spec is None:
|
|
38
|
+
continue
|
|
39
|
+
level, verb = spec
|
|
40
|
+
detail = f" ({t.agent.waiting_for})" if t.agent.waiting_for else ""
|
|
41
|
+
where = f" · {t.agent.project_name}" if t.agent.project_name else ""
|
|
42
|
+
out.append(Notice(level, t.agent.display_name, f"{verb}{detail}{where}",
|
|
43
|
+
t.agent.project_id))
|
|
44
|
+
return out
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def desktop_notify(title: str, message: str) -> None:
|
|
48
|
+
"""Fire-and-forget OS notification. Text goes via argv, never a shell."""
|
|
49
|
+
try:
|
|
50
|
+
if sys.platform == "darwin" and shutil.which("osascript"):
|
|
51
|
+
script = ("on run argv\n display notification (item 2 of argv) "
|
|
52
|
+
"with title (item 1 of argv)\nend run")
|
|
53
|
+
await run(["osascript", "-e", script, title, message], timeout=5)
|
|
54
|
+
elif shutil.which("notify-send"):
|
|
55
|
+
await run(["notify-send", "--", title, message], timeout=5)
|
|
56
|
+
except Exception: # noqa: BLE001 — notifications are best effort
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Notifier:
|
|
61
|
+
def __init__(self, prefs: Notifications) -> None:
|
|
62
|
+
self.prefs = prefs
|
|
63
|
+
|
|
64
|
+
def external(self, notices: list[Notice]) -> list[asyncio.Future]:
|
|
65
|
+
futures = []
|
|
66
|
+
if self.prefs.desktop:
|
|
67
|
+
for n in notices:
|
|
68
|
+
if n.level in ("warning", "error", "success"):
|
|
69
|
+
futures.append(asyncio.ensure_future(
|
|
70
|
+
desktop_notify(f"Claude · {n.title}", n.message)))
|
|
71
|
+
return futures
|
fleetdeck/status.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Map Claude Code's reported session fields onto dashboard statuses.
|
|
2
|
+
|
|
3
|
+
Source of truth (Claude Code docs, `claude agents --json`):
|
|
4
|
+
state (background): working | blocked | done | failed | stopped
|
|
5
|
+
status (process alive): busy | waiting | idle
|
|
6
|
+
waitingFor (status == waiting): permission prompt | input needed |
|
|
7
|
+
sandbox request | worker request | dialog open
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from .models import AgentStatus
|
|
13
|
+
|
|
14
|
+
PERMISSION_WAITS = {"permission prompt", "sandbox request", "worker request"}
|
|
15
|
+
INPUT_WAITS = {"input needed", "dialog open"}
|
|
16
|
+
|
|
17
|
+
# Catppuccin Mocha accents; the UI swaps these per theme flavour.
|
|
18
|
+
STATUS_COLORS: dict[AgentStatus, str] = {
|
|
19
|
+
AgentStatus.RUNNING: "#a6e3a1", # green
|
|
20
|
+
AgentStatus.WAITING: "#f9e2af", # yellow
|
|
21
|
+
AgentStatus.PERMISSION: "#fab387", # peach / orange
|
|
22
|
+
AgentStatus.PLANNING: "#cba6f7", # mauve / purple
|
|
23
|
+
AgentStatus.COMPLETED: "#89b4fa", # blue
|
|
24
|
+
AgentStatus.FAILED: "#f38ba8", # red
|
|
25
|
+
AgentStatus.IDLE: "#7f849c", # overlay1 / gray
|
|
26
|
+
AgentStatus.STOPPED: "#6c7086", # overlay0 / gray
|
|
27
|
+
AgentStatus.UNKNOWN: "#585b70",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
STATUS_ICONS: dict[AgentStatus, str] = {
|
|
31
|
+
AgentStatus.RUNNING: "●",
|
|
32
|
+
AgentStatus.WAITING: "◐",
|
|
33
|
+
AgentStatus.PERMISSION: "▲",
|
|
34
|
+
AgentStatus.PLANNING: "◆",
|
|
35
|
+
AgentStatus.COMPLETED: "✓",
|
|
36
|
+
AgentStatus.FAILED: "✗",
|
|
37
|
+
AgentStatus.IDLE: "○",
|
|
38
|
+
AgentStatus.STOPPED: "■",
|
|
39
|
+
AgentStatus.UNKNOWN: "?",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
# Sort order on the dashboard: things needing a human first.
|
|
43
|
+
STATUS_PRIORITY: dict[AgentStatus, int] = {
|
|
44
|
+
AgentStatus.PERMISSION: 0,
|
|
45
|
+
AgentStatus.WAITING: 1,
|
|
46
|
+
AgentStatus.FAILED: 2,
|
|
47
|
+
AgentStatus.RUNNING: 3,
|
|
48
|
+
AgentStatus.PLANNING: 4,
|
|
49
|
+
AgentStatus.IDLE: 5,
|
|
50
|
+
AgentStatus.COMPLETED: 6,
|
|
51
|
+
AgentStatus.STOPPED: 7,
|
|
52
|
+
AgentStatus.UNKNOWN: 8,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def derive_status(
|
|
57
|
+
*,
|
|
58
|
+
kind: str | None,
|
|
59
|
+
state: str | None,
|
|
60
|
+
status: str | None,
|
|
61
|
+
waiting_for: str | None,
|
|
62
|
+
permission_mode: str | None = None,
|
|
63
|
+
) -> AgentStatus:
|
|
64
|
+
"""Return the most specific status the reported fields justify.
|
|
65
|
+
|
|
66
|
+
``permission_mode`` is only known for sessions this app launched; a session
|
|
67
|
+
started with ``--permission-mode plan`` that is actively working is shown as
|
|
68
|
+
Planning. Nothing else is inferred.
|
|
69
|
+
"""
|
|
70
|
+
state = (state or "").strip().lower() or None
|
|
71
|
+
status = (status or "").strip().lower() or None
|
|
72
|
+
waiting = (waiting_for or "").strip().lower() or None
|
|
73
|
+
|
|
74
|
+
if state == "failed":
|
|
75
|
+
return AgentStatus.FAILED
|
|
76
|
+
if state == "stopped":
|
|
77
|
+
return AgentStatus.STOPPED
|
|
78
|
+
|
|
79
|
+
if status == "waiting" or state == "blocked":
|
|
80
|
+
if waiting in PERMISSION_WAITS:
|
|
81
|
+
return AgentStatus.PERMISSION
|
|
82
|
+
return AgentStatus.WAITING
|
|
83
|
+
|
|
84
|
+
if state == "done":
|
|
85
|
+
return AgentStatus.COMPLETED
|
|
86
|
+
|
|
87
|
+
if state == "working" or status == "busy":
|
|
88
|
+
if permission_mode == "plan":
|
|
89
|
+
return AgentStatus.PLANNING
|
|
90
|
+
return AgentStatus.RUNNING
|
|
91
|
+
|
|
92
|
+
if status == "idle":
|
|
93
|
+
return AgentStatus.IDLE
|
|
94
|
+
|
|
95
|
+
if kind == "background" and state is None and status is None:
|
|
96
|
+
return AgentStatus.STOPPED
|
|
97
|
+
return AgentStatus.UNKNOWN
|
fleetdeck/terminal.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Embedded interactive shells: a pty-backed process rendered through pyte.
|
|
2
|
+
|
|
3
|
+
A TerminalSession is UI-agnostic. It owns the shell process and a VT screen,
|
|
4
|
+
reads output on the asyncio event loop (no threads), and calls ``on_output``
|
|
5
|
+
whenever the screen changes. The Textual widget lives in
|
|
6
|
+
ui/widgets/terminal.py.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import fcntl
|
|
13
|
+
import os
|
|
14
|
+
import signal
|
|
15
|
+
import struct
|
|
16
|
+
import subprocess
|
|
17
|
+
import termios
|
|
18
|
+
from typing import Callable
|
|
19
|
+
|
|
20
|
+
import pyte
|
|
21
|
+
|
|
22
|
+
# Textual key name -> bytes for the shell (xterm sequences).
|
|
23
|
+
KEYS: dict[str, bytes] = {
|
|
24
|
+
"enter": b"\r",
|
|
25
|
+
"tab": b"\t",
|
|
26
|
+
"shift+tab": b"\x1b[Z",
|
|
27
|
+
"backspace": b"\x7f",
|
|
28
|
+
"ctrl+h": b"\x08",
|
|
29
|
+
"escape": b"\x1b",
|
|
30
|
+
"up": b"\x1b[A",
|
|
31
|
+
"down": b"\x1b[B",
|
|
32
|
+
"right": b"\x1b[C",
|
|
33
|
+
"left": b"\x1b[D",
|
|
34
|
+
"home": b"\x1b[H",
|
|
35
|
+
"end": b"\x1b[F",
|
|
36
|
+
"insert": b"\x1b[2~",
|
|
37
|
+
"delete": b"\x1b[3~",
|
|
38
|
+
"pageup": b"\x1b[5~",
|
|
39
|
+
"pagedown": b"\x1b[6~",
|
|
40
|
+
"ctrl+left": b"\x1b[1;5D",
|
|
41
|
+
"ctrl+right": b"\x1b[1;5C",
|
|
42
|
+
"f1": b"\x1bOP", "f2": b"\x1bOQ", "f3": b"\x1bOR", "f4": b"\x1bOS",
|
|
43
|
+
"f5": b"\x1b[15~", "f6": b"\x1b[17~", "f7": b"\x1b[18~", "f8": b"\x1b[19~",
|
|
44
|
+
"f9": b"\x1b[20~", "f10": b"\x1b[21~", "f11": b"\x1b[23~", "f12": b"\x1b[24~",
|
|
45
|
+
"ctrl+space": b"\x00",
|
|
46
|
+
"ctrl+at": b"\x00",
|
|
47
|
+
"ctrl+left_square_bracket": b"\x1b",
|
|
48
|
+
"ctrl+backslash": b"\x1c",
|
|
49
|
+
"ctrl+circumflex_accent": b"\x1e",
|
|
50
|
+
"ctrl+underscore": b"\x1f",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# Leaves the terminal (returns focus to the dashboard); never sent to the shell.
|
|
54
|
+
LEAVE_KEY = "ctrl+right_square_bracket"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def key_to_bytes(key: str, character: str | None) -> bytes | None:
|
|
58
|
+
"""Translate a Textual key event into what a real terminal would send."""
|
|
59
|
+
if key in KEYS:
|
|
60
|
+
return KEYS[key]
|
|
61
|
+
if key.startswith("ctrl+") and len(key) == 6 and key[5].isalpha():
|
|
62
|
+
return bytes([ord(key[5].lower()) - 96]) # ctrl+a .. ctrl+z
|
|
63
|
+
if key.startswith(("alt+", "meta+")) and character:
|
|
64
|
+
return b"\x1b" + character.encode()
|
|
65
|
+
if character:
|
|
66
|
+
return character.encode("utf-8", "replace")
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def default_shell() -> str:
|
|
71
|
+
shell = os.environ.get("SHELL", "")
|
|
72
|
+
return shell if shell and os.path.exists(shell) else "/bin/sh"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class _Screen(pyte.Screen):
|
|
76
|
+
"""pyte screen that answers the shell's queries (cursor position etc.)."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, cols: int, rows: int, reply: Callable[[str], None]) -> None:
|
|
79
|
+
super().__init__(cols, rows)
|
|
80
|
+
self._reply = reply
|
|
81
|
+
|
|
82
|
+
def write_process_input(self, data: str) -> None: # pyte hook
|
|
83
|
+
self._reply(data)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class TerminalSession:
|
|
87
|
+
def __init__(self, cwd: str, *, env: dict[str, str] | None = None,
|
|
88
|
+
cols: int = 80, rows: int = 24, shell: str | None = None,
|
|
89
|
+
on_output: Callable[[], None] | None = None) -> None:
|
|
90
|
+
self.cwd = cwd
|
|
91
|
+
self.shell = shell or default_shell()
|
|
92
|
+
self.on_output = on_output
|
|
93
|
+
self.cols, self.rows = max(2, cols), max(2, rows)
|
|
94
|
+
self.screen = _Screen(self.cols, self.rows, lambda s: self.write(s.encode()))
|
|
95
|
+
self.stream = pyte.ByteStream(self.screen)
|
|
96
|
+
self.exit_code: int | None = None
|
|
97
|
+
self._loop = asyncio.get_running_loop()
|
|
98
|
+
|
|
99
|
+
master, slave = os.openpty()
|
|
100
|
+
self._set_size(slave)
|
|
101
|
+
full_env = {**os.environ, **(env or {}), "TERM": "xterm-256color",
|
|
102
|
+
"COLORTERM": "truecolor", "FLEETDECK_TERMINAL": "1"}
|
|
103
|
+
full_env.pop("COLUMNS", None)
|
|
104
|
+
full_env.pop("LINES", None)
|
|
105
|
+
self.proc = subprocess.Popen(
|
|
106
|
+
[self.shell],
|
|
107
|
+
cwd=cwd, env=full_env,
|
|
108
|
+
stdin=slave, stdout=slave, stderr=slave,
|
|
109
|
+
start_new_session=True, # own session + process group
|
|
110
|
+
preexec_fn=_make_controlling_tty,
|
|
111
|
+
close_fds=True,
|
|
112
|
+
)
|
|
113
|
+
os.close(slave)
|
|
114
|
+
self.fd = master
|
|
115
|
+
os.set_blocking(master, False)
|
|
116
|
+
self._loop.add_reader(master, self._on_readable)
|
|
117
|
+
|
|
118
|
+
# ------------------------------------------------------------ io
|
|
119
|
+
@property
|
|
120
|
+
def alive(self) -> bool:
|
|
121
|
+
return self.fd >= 0 and self.proc.poll() is None
|
|
122
|
+
|
|
123
|
+
def _on_readable(self) -> None:
|
|
124
|
+
try:
|
|
125
|
+
data = os.read(self.fd, 65536)
|
|
126
|
+
except BlockingIOError:
|
|
127
|
+
return
|
|
128
|
+
except OSError:
|
|
129
|
+
data = b""
|
|
130
|
+
if not data: # EOF: the shell exited
|
|
131
|
+
self._detach()
|
|
132
|
+
self.exit_code = self.proc.poll()
|
|
133
|
+
else:
|
|
134
|
+
self.stream.feed(data)
|
|
135
|
+
if self.on_output:
|
|
136
|
+
self.on_output()
|
|
137
|
+
|
|
138
|
+
def write(self, data: bytes) -> None:
|
|
139
|
+
if self.fd < 0:
|
|
140
|
+
return
|
|
141
|
+
try:
|
|
142
|
+
os.write(self.fd, data)
|
|
143
|
+
except OSError:
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
def paste(self, text: str) -> None:
|
|
147
|
+
self.write(b"\x1b[200~" + text.encode() + b"\x1b[201~")
|
|
148
|
+
|
|
149
|
+
def resize(self, cols: int, rows: int) -> None:
|
|
150
|
+
cols, rows = max(2, cols), max(2, rows)
|
|
151
|
+
if (cols, rows) == (self.cols, self.rows):
|
|
152
|
+
return
|
|
153
|
+
self.cols, self.rows = cols, rows
|
|
154
|
+
self.screen.resize(rows, cols)
|
|
155
|
+
if self.fd >= 0:
|
|
156
|
+
self._set_size(self.fd) # the kernel sends SIGWINCH to the shell
|
|
157
|
+
|
|
158
|
+
def _set_size(self, fd: int) -> None:
|
|
159
|
+
try:
|
|
160
|
+
fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", self.rows, self.cols, 0, 0))
|
|
161
|
+
except OSError:
|
|
162
|
+
pass
|
|
163
|
+
|
|
164
|
+
# ------------------------------------------------------------ lifecycle
|
|
165
|
+
def _detach(self) -> None:
|
|
166
|
+
if self.fd >= 0:
|
|
167
|
+
try:
|
|
168
|
+
self._loop.remove_reader(self.fd)
|
|
169
|
+
except Exception: # noqa: BLE001 — loop may be closing
|
|
170
|
+
pass
|
|
171
|
+
try:
|
|
172
|
+
os.close(self.fd)
|
|
173
|
+
except OSError:
|
|
174
|
+
pass
|
|
175
|
+
self.fd = -1
|
|
176
|
+
|
|
177
|
+
def close(self) -> None:
|
|
178
|
+
"""Hang up the shell (and everything it started) and free the pty."""
|
|
179
|
+
if self.proc.poll() is None:
|
|
180
|
+
for sig in (signal.SIGHUP, signal.SIGTERM):
|
|
181
|
+
try:
|
|
182
|
+
os.killpg(self.proc.pid, sig)
|
|
183
|
+
except (ProcessLookupError, PermissionError):
|
|
184
|
+
break
|
|
185
|
+
try:
|
|
186
|
+
self.proc.wait(timeout=0.5)
|
|
187
|
+
break
|
|
188
|
+
except subprocess.TimeoutExpired:
|
|
189
|
+
continue
|
|
190
|
+
else:
|
|
191
|
+
try:
|
|
192
|
+
os.killpg(self.proc.pid, signal.SIGKILL)
|
|
193
|
+
except (ProcessLookupError, PermissionError):
|
|
194
|
+
pass
|
|
195
|
+
self._detach()
|
|
196
|
+
try:
|
|
197
|
+
self.proc.wait(timeout=0.5)
|
|
198
|
+
except subprocess.TimeoutExpired:
|
|
199
|
+
pass
|
|
200
|
+
self.exit_code = self.proc.poll()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _make_controlling_tty() -> None:
|
|
204
|
+
# Runs in the child after setsid(): make the pty (already on fd 0) the
|
|
205
|
+
# controlling terminal so job control and Ctrl+C work in the shell.
|
|
206
|
+
try:
|
|
207
|
+
fcntl.ioctl(0, termios.TIOCSCTTY, 0)
|
|
208
|
+
except OSError:
|
|
209
|
+
pass
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class TerminalManager:
|
|
213
|
+
"""One shell per directory, kept alive while the dashboard runs."""
|
|
214
|
+
|
|
215
|
+
def __init__(self) -> None:
|
|
216
|
+
self.sessions: dict[str, TerminalSession] = {}
|
|
217
|
+
|
|
218
|
+
def get(self, cwd: str) -> TerminalSession | None:
|
|
219
|
+
s = self.sessions.get(cwd)
|
|
220
|
+
return s
|
|
221
|
+
|
|
222
|
+
def open(self, cwd: str, **kw) -> TerminalSession:
|
|
223
|
+
old = self.sessions.get(cwd)
|
|
224
|
+
if old is not None and old.alive:
|
|
225
|
+
return old
|
|
226
|
+
if old is not None:
|
|
227
|
+
old.close()
|
|
228
|
+
s = TerminalSession(cwd, **kw)
|
|
229
|
+
self.sessions[cwd] = s
|
|
230
|
+
return s
|
|
231
|
+
|
|
232
|
+
def close_all(self) -> None:
|
|
233
|
+
for s in list(self.sessions.values()):
|
|
234
|
+
s.close()
|
|
235
|
+
self.sessions.clear()
|