-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession-picker.py
More file actions
247 lines (201 loc) · 8.87 KB
/
session-picker.py
File metadata and controls
247 lines (201 loc) · 8.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#!/usr/bin/env python3
"""AgentBox session picker — shown by ttyd on each browser connection.
Displays active tmux sessions (with copilot process status) and recent
Copilot CLI sessions (from workspace.yaml). Auto-attaches when there is
exactly one detached tmux session.
"""
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
# ── Colours (ANSI) ───────────────────────────────────────────────────────────
CYAN = "\033[96m"
DIM = "\033[2m"
BOLD = "\033[1m"
RESET = "\033[0m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
COPILOT_SESSION_DIR = Path.home() / ".copilot" / "session-state"
# ── Helpers ──────────────────────────────────────────────────────────────────
def run(cmd: list[str], fallback: str = "") -> str:
try:
return subprocess.check_output(cmd, stderr=subprocess.DEVNULL, text=True).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return fallback
def time_ago(iso_str: str) -> str:
"""Convert ISO timestamp to human-readable relative time."""
try:
dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00"))
delta = datetime.now(timezone.utc) - dt
secs = int(delta.total_seconds())
if secs < 60:
return "just now"
if secs < 3600:
return f"{secs // 60}m ago"
if secs < 86400:
return f"{secs // 3600}h ago"
return f"{secs // 86400}d ago"
except (ValueError, TypeError):
return ""
def parse_workspace_yaml(path: Path) -> dict:
"""Minimal YAML parser for workspace.yaml (key: value lines only)."""
data = {}
try:
for line in path.read_text().splitlines():
if ":" in line:
key, _, val = line.partition(":")
data[key.strip()] = val.strip()
except OSError:
pass
return data
# ── tmux session listing ─────────────────────────────────────────────────────
def get_tmux_sessions() -> list[dict]:
"""Return list of tmux sessions with metadata."""
raw = run(["tmux", "list-sessions", "-F",
"#{session_name}\t#{session_windows}\t#{session_created}\t#{session_attached}"])
if not raw:
return []
sessions = []
for line in raw.splitlines():
parts = line.split("\t")
if len(parts) < 4:
continue
name, windows, created_ts, attached = parts
# Check if copilot is running in any pane of this session
pane_cmds = run(["tmux", "list-panes", "-t", name, "-F", "#{pane_current_command}"])
copilot_running = "copilot" in pane_cmds.lower() if pane_cmds else False
try:
created = datetime.fromtimestamp(int(created_ts), tz=timezone.utc)
age = time_ago(created.isoformat())
except (ValueError, OSError):
age = ""
sessions.append({
"name": name,
"windows": windows,
"age": age,
"attached": attached != "0",
"copilot": copilot_running,
})
return sessions
# ── Copilot CLI session listing ──────────────────────────────────────────────
def get_copilot_sessions(limit: int = 5) -> list[dict]:
"""Return recent Copilot CLI sessions from workspace.yaml files."""
if not COPILOT_SESSION_DIR.is_dir():
return []
sessions = []
for d in COPILOT_SESSION_DIR.iterdir():
ws = d / "workspace.yaml"
if not ws.exists():
continue
data = parse_workspace_yaml(ws)
if not data.get("id"):
continue
sessions.append({
"id": data["id"],
"summary": data.get("summary", ""),
"repo": data.get("repository", ""),
"branch": data.get("branch", ""),
"updated": data.get("updated_at", data.get("created_at", "")),
})
# Sort by most recently updated
sessions.sort(key=lambda s: s["updated"], reverse=True)
return sessions[:limit]
# ── Display ──────────────────────────────────────────────────────────────────
def show_picker(tmux_sessions: list[dict], copilot_sessions: list[dict]):
print()
print(f" {CYAN}{BOLD}═══ AgentBox Sessions ═══{RESET}")
print()
if tmux_sessions:
print(f" {BOLD}Terminal sessions:{RESET}")
for i, s in enumerate(tmux_sessions, 1):
status = ""
if s["copilot"]:
status = f" {GREEN}🤖 copilot running{RESET}"
elif s["attached"]:
status = f" {DIM}(attached){RESET}"
print(f" [{CYAN}{i}{RESET}] {s['name']}"
f" {DIM}│ {s['windows']} win │ {s['age']}{RESET}{status}")
print()
if copilot_sessions:
print(f" {BOLD}Recent Copilot sessions (resumable):{RESET}")
for i, s in enumerate(copilot_sessions, 1):
label = s["summary"] or s["id"][:12]
context = ""
if s["repo"]:
context = f" ({s['repo']}"
if s["branch"]:
context += f", {s['branch']}"
context += ")"
age = time_ago(s["updated"])
print(f" [{CYAN}c{i}{RESET}] {label}{DIM}{context} — {age}{RESET}")
print()
print(f" {BOLD}Actions:{RESET}")
print(f" [{CYAN}n{RESET}] New terminal session")
print(f" [{CYAN}c{RESET}] New session + {YELLOW}copilot --continue{RESET}")
print(f" [{CYAN}r{RESET}] New session + {YELLOW}copilot --resume{RESET} (picker)")
print(f" [{CYAN}q{RESET}] Quit")
print()
def prompt_session_name() -> str:
"""Ask for optional session name, default to auto-generated."""
try:
name = input(f" Session name [{DIM}Enter for auto{RESET}]: ").strip()
except (EOFError, KeyboardInterrupt):
name = ""
if not name:
# Generate a short name based on count of existing sessions
existing = run(["tmux", "list-sessions", "-F", "#{session_name}"])
count = len(existing.splitlines()) + 1 if existing else 1
name = f"session-{count}"
return name
# ── Main ─────────────────────────────────────────────────────────────────────
def main():
tmux_sessions = get_tmux_sessions()
copilot_sessions = get_copilot_sessions()
# Auto-attach: exactly one detached tmux session → go straight in
detached = [s for s in tmux_sessions if not s["attached"]]
if len(detached) == 1 and len(tmux_sessions) == 1:
print(f" {DIM}Reconnecting to {detached[0]['name']}…{RESET}")
os.execvp("tmux", ["tmux", "attach-session", "-t", detached[0]["name"]])
return # unreachable
show_picker(tmux_sessions, copilot_sessions)
try:
choice = input(f" Select: ").strip().lower()
except (EOFError, KeyboardInterrupt):
print()
return
# ── Handle choice ────────────────────────────────────────────────────
if choice == "q":
return
if choice == "n":
name = prompt_session_name()
os.execvp("tmux", ["tmux", "new-session", "-s", name])
elif choice == "c":
name = prompt_session_name()
os.execvp("tmux", ["tmux", "new-session", "-s", name, "copilot", "--continue"])
elif choice == "r":
name = prompt_session_name()
os.execvp("tmux", ["tmux", "new-session", "-s", name, "copilot", "--resume"])
elif choice.startswith("c") and choice[1:].isdigit():
idx = int(choice[1:]) - 1
if 0 <= idx < len(copilot_sessions):
sid = copilot_sessions[idx]["id"]
name = prompt_session_name()
os.execvp("tmux", ["tmux", "new-session", "-s", name,
"copilot", "--resume", sid])
else:
print(f" Invalid selection.")
main()
elif choice.isdigit():
idx = int(choice) - 1
if 0 <= idx < len(tmux_sessions):
os.execvp("tmux", ["tmux", "attach-session", "-t",
tmux_sessions[idx]["name"]])
else:
print(f" Invalid selection.")
main()
else:
print(f" Invalid selection.")
main()
if __name__ == "__main__":
main()