class SessionListScreen(ModalScreen[str | None]):
"""Lists the agent's sessions for the working directory; returns the one to resume.
``d`` deletes, ``a`` archives / unarchives (when the agent supports it), ``h`` shows
archived sessions too.
"""
DEFAULT_CSS = "SessionListScreen {" + DIALOG_CSS + "}"
BINDINGS: ClassVar = [
Binding("escape", "dismiss_none", "Close"),
Binding("d", "delete", "Delete"),
Binding("a", "archive", "Archive / unarchive"),
Binding("h", "toggle_archived", "Show archived"),
]
def __init__(self, connection: AgentConnection) -> None:
super().__init__()
self.connection = connection
self._cursor: str | None = None
self.sessions: dict[str, SessionInfo] = {}
self.show_archived = False
def compose(self) -> ComposeResult:
with Vertical(id="dialog"):
yield Static("Resume a session", id="dialog-title")
yield OptionList(id="sessions")
yield Static("Loading…", id="dialog-hint")
def on_mount(self) -> None:
self.load()
def _hint(self) -> str:
keys = ["enter: resume"]
if self.connection.supports_delete:
keys.append("d: delete")
if self.connection.supports_archive:
keys += [
"a: archive/unarchive",
"h: " + ("hide" if self.show_archived else "show") + " archived",
]
keys.append("escape: close")
return " · ".join(keys)
@work(exclusive=True)
async def load(self, *, reset: bool = False) -> None:
"""Load (the next page of) sessions."""
hint = self.query_one("#dialog-hint", Static)
options = self.query_one("#sessions", OptionList)
if reset:
self._cursor = None
self.sessions.clear()
options.clear_options()
archived = (
("include" if self.show_archived else None)
if self.connection.supports_archive
else None
)
try:
response = await self.connection.list_sessions(self._cursor, archived=archived)
except (RequestError, ConnectionError) as exc:
hint.update(Content(f"The agent cannot list sessions: {exc}"))
return
if (
options.option_count
and options.get_option_at_index(options.option_count - 1).id == "more"
):
options.remove_option("more")
for info in response.sessions:
self.sessions[info.session_id] = info
title = info.title if is_set(info.title) and info.title else info.session_id
updated = info.updated_at if is_set(info.updated_at) and info.updated_at else ""
flag = " [archived]" if is_set(info.archived) and info.archived else ""
label = Content.assemble(
(title, "bold"),
(flag, "$text-warning"),
("\n " + updated[:19].replace("T", " "), "$text-muted"),
)
options.add_option(Option(label, id=f"s:{info.session_id}"))
cursor = response.next_cursor if is_set(response.next_cursor) else None
self._cursor = cursor
if cursor is not None and response.sessions:
options.add_option(Option(Content("… load more").stylize("$text-muted"), id="more"))
hint.update(self._hint() if self.sessions else "No sessions for this directory.")
if options.highlighted is None and options.option_count:
options.highlighted = 0
options.focus()
def _highlighted(self) -> SessionInfo | None:
options = self.query_one("#sessions", OptionList)
if options.highlighted is None:
return None
option_id = options.get_option_at_index(options.highlighted).id or ""
return self.sessions.get(option_id[2:]) if option_id.startswith("s:") else None
def on_option_list_option_selected(self, event: OptionList.OptionSelected) -> None:
option_id = event.option_id or ""
if option_id == "more":
self.load()
elif option_id.startswith("s:"):
self.dismiss(option_id[2:])
def action_dismiss_none(self) -> None:
"""Close without choosing."""
self.dismiss(None)
def action_delete(self) -> None:
"""Delete the highlighted session (after confirming)."""
info = self._highlighted()
if info is None or not self.connection.supports_delete:
return
def confirmed(ok: bool | None) -> None:
if ok:
self._mutate(info.session_id, "delete")
title = info.title if is_set(info.title) and info.title else info.session_id
self.app.push_screen(ConfirmScreen(f"Delete session {title!r}?"), callback=confirmed)
def action_archive(self) -> None:
"""Archive or unarchive the highlighted session."""
info = self._highlighted()
if info is not None and self.connection.supports_archive:
archived = is_set(info.archived) and bool(info.archived)
self._mutate(info.session_id, "unarchive" if archived else "archive")
def action_toggle_archived(self) -> None:
"""Show or hide archived sessions."""
if self.connection.supports_archive:
self.show_archived = not self.show_archived
self.load(reset=True)
@work(group="mutate")
async def _mutate(self, session_id: str, action: str) -> None:
try:
if action == "delete":
await self.connection.delete_session(session_id)
else:
await self.connection.archive_session(session_id, archived=action == "archive")
except (RequestError, ConnectionError) as exc:
self.notify(f"Could not {action} the session: {exc}", severity="error")
return
self.notify(f"Session {action}d", timeout=2)
self.load(reset=True)