Skip to content

RecentSessions

🛈 DocStrings

The recent sessions file.

Source code in src/acptui/recent.py
class RecentSessions:
    """The recent sessions file."""

    def __init__(self, path: Path | None = None) -> None:
        self.path = path or recent_path()

    def load(self) -> list[RecentSession]:
        """The sessions, newest first, one entry per session (the latest wins)."""
        try:
            lines = self.path.read_text(encoding="utf-8").splitlines()
        except OSError:
            return []
        latest: dict[tuple[str, str], RecentSession] = {}
        for line in lines:
            try:
                data = json.loads(line)
                session = RecentSession(
                    agent_id=str(data["agent_id"]),
                    agent_name=str(data["agent_name"]),
                    command=tuple(str(part) for part in data.get("command", ())),
                    url=data.get("url") if isinstance(data.get("url"), str) else None,
                    session_id=str(data["session_id"]),
                    cwd=str(data["cwd"]),
                    title=str(data.get("title", "")),
                    time=float(data.get("time", 0.0)),
                )
            except ValueError, KeyError, TypeError:
                continue
            key = (session.agent_id, session.session_id)
            if (old := latest.get(key)) is not None and not session.title:
                session = dataclasses.replace(session, title=old.title)
            latest.pop(key, None)
            latest[key] = session
        return list(reversed(latest.values()))

    def record(self, session: RecentSession) -> bool:
        """Add or update a session; whether it was written."""
        data = asdict(session) | {"command": list(session.command), "time": time.time()}
        try:
            self.path.parent.mkdir(parents=True, exist_ok=True)
            with self.path.open("a", encoding="utf-8") as file:
                file.write(json.dumps(data) + "\n")
            self._trim()
        except OSError:
            return False
        return True

    def _trim(self) -> None:
        lines = self.path.read_text(encoding="utf-8").splitlines()
        if len(lines) > 4 * MAX_SESSIONS:
            keep = list(reversed(self.load()[:MAX_SESSIONS]))
            text = "".join(
                json.dumps(asdict(s) | {"command": list(s.command)}) + "\n" for s in keep
            )
            self.path.write_text(text, encoding="utf-8")

load

load() -> list[RecentSession]

The sessions, newest first, one entry per session (the latest wins).

Source code in src/acptui/recent.py
def load(self) -> list[RecentSession]:
    """The sessions, newest first, one entry per session (the latest wins)."""
    try:
        lines = self.path.read_text(encoding="utf-8").splitlines()
    except OSError:
        return []
    latest: dict[tuple[str, str], RecentSession] = {}
    for line in lines:
        try:
            data = json.loads(line)
            session = RecentSession(
                agent_id=str(data["agent_id"]),
                agent_name=str(data["agent_name"]),
                command=tuple(str(part) for part in data.get("command", ())),
                url=data.get("url") if isinstance(data.get("url"), str) else None,
                session_id=str(data["session_id"]),
                cwd=str(data["cwd"]),
                title=str(data.get("title", "")),
                time=float(data.get("time", 0.0)),
            )
        except ValueError, KeyError, TypeError:
            continue
        key = (session.agent_id, session.session_id)
        if (old := latest.get(key)) is not None and not session.title:
            session = dataclasses.replace(session, title=old.title)
        latest.pop(key, None)
        latest[key] = session
    return list(reversed(latest.values()))

record

record(session: RecentSession) -> bool

Add or update a session; whether it was written.

Source code in src/acptui/recent.py
def record(self, session: RecentSession) -> bool:
    """Add or update a session; whether it was written."""
    data = asdict(session) | {"command": list(session.command), "time": time.time()}
    try:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with self.path.open("a", encoding="utf-8") as file:
            file.write(json.dumps(data) + "\n")
        self._trim()
    except OSError:
        return False
    return True

:fa-brands-github: Show source on GitHub