Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's (forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b, cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/, schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread, Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron` (now a pointer), MCP run_cron_job / set_cron_job / browse cron, the scheduled-jobs core skill, guestDefaults.cronLimits. The core keeps thin contracts: - runs.guest bridge (runs/guestjob.py): a guest's job run as that guest, confined by the core from their record; the plugin only names it. - runs.start's cron stamp → meta.cron. - delivery of a guest job's result (push, mail, mailHtml) off the stamp. - « Discuter »: POST /api/cron-runs/discuss. - runs.cron provider readers (plugins/cron_bridge.py): budget, auto-archive, agents catalog, the agents page's Schedule. - core/cronexpr.py, agents/runconfig.py; context.write create for a new agent definition; ui.pages[].unless; setRoute keeps a Settings page under /settings/p/. - carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json, cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's decision, superseded). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
607 lines
26 KiB
Python
607 lines
26 KiB
Python
"""The conversation cards every list view reads, and the session-id lookups."""
|
|
|
|
import datetime
|
|
import json
|
|
import pathlib
|
|
import threading
|
|
import time
|
|
import zlib
|
|
|
|
from fastapi import HTTPException
|
|
|
|
import agents as agents_mod
|
|
import conversations
|
|
from conversations import ids, resource_view, spawned_live
|
|
from plugins import resources as plugin_resources
|
|
from conversations.cards import _conv_meta, _conv_title, _stopped_on, _subagent_activity
|
|
from conversations.tree import (
|
|
_conv_id,
|
|
_is_deploying,
|
|
_is_sidechain_path,
|
|
_rollup_children,
|
|
_root_path_of,
|
|
_running_agents,
|
|
_subagent_meta_cached,
|
|
)
|
|
from core import liveruns
|
|
from core.config import RUNNING_WINDOW_SECS, TRANSCRIPTS_DIR
|
|
from core.memo import _Memo
|
|
from core.state import AppState
|
|
from usage import calibrate
|
|
|
|
_skills_by_path_cache: tuple[int, dict[str, dict[str, int]]] | None = None
|
|
|
|
|
|
def _skills_by_path(deps: AppState) -> dict[str, dict[str, int]]:
|
|
"""transcript path → ``{skill: calls}``, decoded once per store version.
|
|
|
|
The indexer keeps a transcript's skill map in its **own column** (it feeds
|
|
the catalog rollup), not inside the summary blob — so a stored summary has
|
|
no `skills` key at all, and this is the join that puts it back.
|
|
"""
|
|
global _skills_by_path_cache
|
|
hit = _skills_by_path_cache
|
|
if hit and hit[0] == deps.store.summaries_version:
|
|
return hit[1]
|
|
out: dict[str, dict[str, int]] = {}
|
|
for path, raw in deps.store.all_transcript_skill_rows():
|
|
try:
|
|
contrib = json.loads(raw or "{}")
|
|
except ValueError:
|
|
continue
|
|
counts = {name: d.get("count") or 0 for name, d in contrib.items()}
|
|
if counts:
|
|
out[path] = counts
|
|
_skills_by_path_cache = (deps.store.summaries_version, out)
|
|
return out
|
|
|
|
|
|
def _skill_count(v) -> int:
|
|
return (v.get("count") or 0) if isinstance(v, dict) else (v or 0)
|
|
|
|
|
|
def _skills_map(deps: AppState) -> dict[str, dict]:
|
|
"""In-memory transcript path → skill map, preferring ``store.skills_by_path()``."""
|
|
fn = getattr(deps.store, "skills_by_path", None)
|
|
if fn is not None:
|
|
return fn()
|
|
return _skills_by_path(deps)
|
|
|
|
|
|
def _skills_used(deps: AppState, paths: list[str], extra: dict | None = None,
|
|
skills_map: dict[str, dict] | None = None) -> list[str]:
|
|
"""Skill names used across `paths`, busiest first.
|
|
|
|
Callers pass a conversation *and its subagent transcripts*: a `Skill(...)`
|
|
run by a spawned Explore is work this conversation caused, and the child is
|
|
never listed on its own — so hiding its skills would lose them entirely.
|
|
`extra` folds in a freshly parsed ``{skill: {count, …}}`` map for a
|
|
transcript the store may not have re-read yet (the detail view parses live).
|
|
"""
|
|
counts: dict[str, int] = {}
|
|
if skills_map is None:
|
|
fn = getattr(deps.store, "skills_by_path", None)
|
|
if fn is not None:
|
|
skills_map = fn()
|
|
if skills_map is not None:
|
|
for p in paths:
|
|
for name, v in (skills_map.get(p) or {}).items():
|
|
counts[name] = counts.get(name, 0) + _skill_count(v)
|
|
else:
|
|
for _path, raw in deps.store.transcript_skill_rows(paths):
|
|
try:
|
|
contrib = json.loads(raw or "{}")
|
|
except ValueError:
|
|
continue
|
|
for name, d in contrib.items():
|
|
counts[name] = counts.get(name, 0) + _skill_count(d)
|
|
for name, d in (extra or {}).items():
|
|
counts[name] = counts.get(name, 0) + _skill_count(d)
|
|
return sorted(counts, key=lambda n: (-counts[n], n))
|
|
|
|
|
|
def _build_agents_by_conversation(deps: AppState) -> dict[str, list[str]]:
|
|
"""The conversation ids of `_agent_runs`' runs, by agent — counted
|
|
straight off the store with the same rules (a subagent run is its root
|
|
conversation's, a cron / "Run now" session run is the conversation its
|
|
sessionId names), without building the run list: its per-run account,
|
|
profile and cost were most of a list rebuild after every write."""
|
|
counts: dict[str, dict[str, int]] = {}
|
|
|
|
def add(cid: str | None, name: str | None) -> None:
|
|
if cid and name:
|
|
c = counts.setdefault(cid, {})
|
|
c[name] = c.get(name, 0) + 1
|
|
|
|
sessions: dict[str, str] = {}
|
|
for path, s in deps.store.all_summaries():
|
|
if _is_sidechain_path(path):
|
|
name = _subagent_meta_cached(path).get("agentType")
|
|
if name:
|
|
parent = _root_path_of(path)
|
|
add(_conv_id(parent) if parent else None, name)
|
|
elif s.get("sessionId"):
|
|
sessions[s["sessionId"]] = path
|
|
|
|
def session_conv(sid: str) -> str | None:
|
|
path = sessions.get(sid)
|
|
return _conv_id(path) if path else None
|
|
|
|
by_file = _agent_by_file()
|
|
for job in _cron_jobs(deps):
|
|
name = by_file.get((job.get("promptFile") or "").lstrip("/"))
|
|
if not name:
|
|
continue # a job whose prompt file isn't an agent definition
|
|
for sid in (job.get("history") or {}).values():
|
|
if sid:
|
|
add(session_conv(sid), name)
|
|
for sid, m in deps.meta_store.items():
|
|
ar = m.get("agentRun") or {}
|
|
if ar.get("name"):
|
|
add(session_conv(sid), ar["name"])
|
|
return {cid: sorted(c, key=lambda n: (-c[n], n)) for cid, c in counts.items()}
|
|
|
|
|
|
_agents_by_conv_memo = _Memo(_build_agents_by_conversation)
|
|
|
|
|
|
_agent_by_file_cache: tuple[float, dict[str, str]] | None = None
|
|
|
|
|
|
def _agent_by_file() -> dict[str, str]:
|
|
"""prompt file → agent name, from the agents catalog (which parses every
|
|
agent file's frontmatter: ~25 ms) — held for a few seconds, since the
|
|
per-ping lookups below ask for it on every transcript write."""
|
|
global _agent_by_file_cache
|
|
now = time.monotonic()
|
|
if _agent_by_file_cache and now - _agent_by_file_cache[0] < 10:
|
|
return _agent_by_file_cache[1]
|
|
out = {a["path"]: a["name"] for a in agents_mod.catalog()}
|
|
_agent_by_file_cache = (now, out)
|
|
return out
|
|
|
|
|
|
def _agents_of_conversation(deps: AppState, cid: str, session_id: str | None,
|
|
child_paths: list[str]) -> list[str]:
|
|
"""`_agents_by_conversation(deps)[cid]` for one conversation, without the
|
|
whole-store run list: the same two origins `_build_agent_runs` unifies —
|
|
its subagent transcripts' recorded types, and the agent a cron job or
|
|
"Run now" spawned the session from. Busiest first, like the map.
|
|
|
|
The map rebuilds on every store version bump (= every transcript write,
|
|
~200 ms over 1 500 summaries) and a card or thread is asked for on each
|
|
of those — so the per-ping paths take this instead; the list keeps the
|
|
memoized map (one build for 50 cards)."""
|
|
counts: dict[str, int] = {}
|
|
for child in child_paths:
|
|
name = _subagent_meta_cached(pathlib.Path(child)).get("agentType")
|
|
if name:
|
|
counts[name] = counts.get(name, 0) + 1
|
|
if session_id:
|
|
by_file = _agent_by_file()
|
|
for job in _cron_jobs(deps):
|
|
name = by_file.get((job.get("promptFile") or "").lstrip("/"))
|
|
if name and session_id in (job.get("history") or {}).values():
|
|
counts[name] = counts.get(name, 0) + 1
|
|
ar = deps.meta_store.peek(session_id).get("agentRun") or {}
|
|
if ar.get("name"):
|
|
counts[ar["name"]] = counts.get(ar["name"], 0) + 1
|
|
return sorted(counts, key=lambda n: (-counts[n], n))
|
|
|
|
|
|
def _agents_by_conversation(deps: AppState) -> dict[str, list[str]]:
|
|
"""conversation id → the agent types that ran in it, busiest first.
|
|
|
|
Counted by the same rules as the run list the agents catalog counts
|
|
(`agents.runs._build_agent_runs`) — not from a second pass over the `Task`
|
|
calls — so a conversation card can never disagree with the agent page:
|
|
a subagent run is keyed to its *parent* conversation (where its Task card
|
|
lives), and a cron/manual agent session to the conversation it *is*.
|
|
"""
|
|
return _agents_by_conv_memo.get(
|
|
(deps.store.summaries_version, deps.meta_store.version), deps)
|
|
|
|
|
|
def _conv_card(deps: AppState, path: str, s: dict) -> dict:
|
|
"""Compact conversation reference used when cross-linking from a memory."""
|
|
return {
|
|
"id": _conv_id(path),
|
|
"sessionId": s.get("sessionId"),
|
|
"title": _conv_title(deps, s),
|
|
"model": s.get("model"),
|
|
"endedAt": s.get("endedAt"),
|
|
"cost": s.get("cost"),
|
|
"tokens": s.get("tokens"),
|
|
"meta": _conv_meta(deps, s),
|
|
}
|
|
|
|
|
|
# Card fields every list view needs. `usage`/`byToolSub`/`byModel` are heavy
|
|
# per-card and only analytics / guest stats read them — they ask with ``full=1``.
|
|
_CARD_KEYS = ("sessionId", "project", "gitBranch", "model", "models", "efforts",
|
|
"title", "userTurns", "assistantTurns", "messages", "startedAt", "endedAt",
|
|
"tokens", "cost", "byTool", "subagentCount",
|
|
"subagentTokens", "subagentCost", "tasks",
|
|
"planUnits", "subagentPlanUnits", "priceBook", "fastCalls",
|
|
"local")
|
|
_EXTRA_FULL_KEYS = ("usage", "byToolSub", "byModel")
|
|
_CARD_KEYS_FULL = _CARD_KEYS + _EXTRA_FULL_KEYS
|
|
|
|
|
|
def _dedup_by_session(summaries: list[tuple[str, dict]]) -> list[tuple[str, dict]]:
|
|
"""Collapse transcript files that share a ``sessionId`` into one.
|
|
|
|
Resuming a session in a different working directory (a worktree, or
|
|
``claude --resume`` from another dir) makes Claude Code write the
|
|
continuation to a *new* cwd-encoded folder under the SAME sessionId — so
|
|
one logical conversation lands on disk as several ``<cwd>/<sid>.jsonl``
|
|
files. Keyed on the file path, each became its own card and the
|
|
conversation showed up two (or more) times. Keep only the file with the
|
|
most recent activity (latest ``endedAt``, then most messages, then longest
|
|
path as a stable tiebreak) — that's the fully-resumed transcript. Files
|
|
without a sessionId are never collapsed (nothing links them)."""
|
|
best: dict[str, tuple[str, dict]] = {}
|
|
passthrough: list[tuple[str, dict]] = []
|
|
for path, s in summaries:
|
|
sid = s.get("sessionId")
|
|
if not sid:
|
|
passthrough.append((path, s))
|
|
continue
|
|
cur = best.get(sid)
|
|
if cur is None or (
|
|
(s.get("endedAt") or "", s.get("messages") or 0, path)
|
|
> (cur[1].get("endedAt") or "", cur[1].get("messages") or 0, cur[0])
|
|
):
|
|
best[sid] = (path, s)
|
|
return list(best.values()) + passthrough
|
|
|
|
|
|
# A card's `state` also depends on the clock (`_auto_state`'s recency window,
|
|
# 10 min), so the memo key carries a coarse time bucket too: an idle list flips
|
|
# a stale "running" badge within this many seconds even with no write.
|
|
_CARDS_TIME_BUCKET_S = 15
|
|
|
|
|
|
def _conversation_cards(deps: AppState, full: bool) -> list[dict]:
|
|
"""Every non-sidechain conversation as a card dict, unsorted — memoized per
|
|
(store, sidecar, live runs, time bucket) and shared across concurrent
|
|
requests.
|
|
|
|
The returned list and its cards are shared: callers must copy before
|
|
sorting/filtering in place, and never mutate a card."""
|
|
key = (deps.store.summaries_version, deps.meta_store.version,
|
|
deps.usage_store.version, deps.profile_store.version,
|
|
plugin_resources.registry(deps).version, liveruns.snapshot(),
|
|
liveruns.held_snapshot(),
|
|
int(time.time() // _CARDS_TIME_BUCKET_S))
|
|
return _cards_memo[bool(full)].get(key, deps, bool(full))
|
|
|
|
|
|
# ── the per-card cache behind the list ──────────────────────────────────────
|
|
# The list's memo key moves on every transcript write, and a rebuild used to
|
|
# remake all ~2 000 cards for the one that changed (~0.6 s, on every list
|
|
# refetch while anything runs). Each card is now kept with the inputs it was
|
|
# built from, and remade only when one of them moved:
|
|
#
|
|
# * its own summary, its subagents' summaries and its metadata entry — by
|
|
# identity: the summary store and the meta store replace a changed entry
|
|
# with a new object and never mutate one in place (their documented
|
|
# contracts; MetaStore keeps an unchanged entry's object across a reload);
|
|
# * what it reads from elsewhere, by value: its agents
|
|
# (`_agents_by_conversation`), when its subagents last wrote
|
|
# (`_subagent_activity`), whether its run's process is alive
|
|
# (`core.liveruns`), the calibration behind `planPct` — and, for a card
|
|
# with resources, the shared resource context, by identity
|
|
# (`resource_view.context` keeps the object while its content holds);
|
|
# * the clock: `state` follows the recency window, so a card active within it
|
|
# is remade every `_CARDS_TIME_BUCKET_S`, as the whole list used to be — and
|
|
# once it is past the window its state can't change any more;
|
|
# * the profile and look-colour versions (a change remakes every card), and
|
|
# an expiry every `_CARDS_FLUSH_S` for what a card reads that has no
|
|
# version of its own (the account registry) — staggered per card by a hash
|
|
# of its path, so the remakes trickle in rather than land on one request.
|
|
_CARDS_FLUSH_S = 300
|
|
|
|
|
|
class _CardEntry:
|
|
__slots__ = ("summary", "kids", "meta", "agents", "sub_at", "alive", "held", "live_kids", "ctx",
|
|
"account", "cal", "card", "built", "bucket", "settles", "epoch")
|
|
|
|
|
|
def _epoch(path: str, now: float) -> int:
|
|
"""The card's expiry period: `_CARDS_FLUSH_S` long, offset by its path."""
|
|
return int((now + zlib.crc32(path.encode()) % _CARDS_FLUSH_S) // _CARDS_FLUSH_S)
|
|
|
|
|
|
# full flag → (flush key, transcript path → entry). Only touched inside a
|
|
# `_cards_memo` build, which is single-flight per flag.
|
|
_card_cache: dict[bool, tuple[tuple | None, dict[str, _CardEntry]]] = {
|
|
False: (None, {}), True: (None, {})}
|
|
|
|
|
|
def _settles_at(s: dict, sub_at: str | None) -> float:
|
|
"""When the card's clock-driven fields stop moving: its last activity (or
|
|
its subagents') plus the recency window `_auto_state` applies."""
|
|
out = 0.0
|
|
for iso in (s.get("endedAt"), sub_at):
|
|
if not iso:
|
|
continue
|
|
try:
|
|
t = datetime.datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp()
|
|
except (ValueError, TypeError, AttributeError):
|
|
continue
|
|
out = max(out, t + RUNNING_WINDOW_SECS)
|
|
return out
|
|
|
|
|
|
def _card_entry(deps: AppState, path: str, s: dict, kids: list[dict],
|
|
kid_paths: list[str], keys: tuple, m: dict, agents: list[str],
|
|
sub_at: str | None, now: float, bucket: int,
|
|
skills_map: dict[str, dict] | None = None,
|
|
alive_set: frozenset[str] | None = None,
|
|
held_by_sid: dict[str, dict] | None = None) -> _CardEntry:
|
|
"""Build one conversation's card, with what it was built from.
|
|
|
|
The shared inputs are read *before* the build: one that moves while it
|
|
runs then just fails the next check, never passes it."""
|
|
e = _CardEntry()
|
|
e.summary, e.kids, e.meta, e.agents, e.sub_at = s, tuple(kids), m, agents, sub_at
|
|
sid = s.get("sessionId")
|
|
e.alive = (bool(sid) and sid in alive_set) if alive_set is not None else liveruns.alive(sid)
|
|
e.held = (held_by_sid.get(sid) if sid else None) if held_by_sid is not None else liveruns.held(sid)
|
|
# Its hub children at work (spawned_live.py): one starting or ending
|
|
# moves the card's state and running agents.
|
|
e.live_kids = tuple(spawned_live.active_sids(deps, sid))
|
|
skills_used = _skills_used(deps, [path, *kid_paths], skills_map=skills_map)
|
|
s = _rollup_children(s, kids)
|
|
# `resource_view.for_conversation`'s own test for needing the context.
|
|
e.ctx = (resource_view.context(deps)
|
|
if s.get("resourcesAuto") or m.get("resources") else None)
|
|
mm = _conv_meta(deps, s, slim=True, sub_at=sub_at)
|
|
e.account = mm.get("account") or "personal"
|
|
e.cal = calibrate.current(deps, e.account)
|
|
e.card = {"id": _conv_id(path), **{k: s.get(k) for k in keys},
|
|
"planPct": calibrate.plan_pct(deps, e.account, s.get("planUnits")),
|
|
"title": _conv_title(deps, s, mm),
|
|
"runningAgents": _running_agents(deps, s, mm.get("state")),
|
|
"deploying": _is_deploying(deps, s, mm.get("state")),
|
|
"stoppedOn": _stopped_on(s, mm.get("state")),
|
|
"skillsUsed": skills_used,
|
|
"agentsUsed": agents,
|
|
"meta": mm}
|
|
e.built, e.bucket, e.settles = now, bucket, _settles_at(s, sub_at)
|
|
e.epoch = _epoch(path, now)
|
|
return e
|
|
|
|
|
|
def _card_fresh(e: _CardEntry, path: str, s: dict, kids: list[dict], m: dict,
|
|
agents: list[str], sub_at: str | None, now: float, bucket: int,
|
|
ctx_now, cal_of,
|
|
alive_set: frozenset[str], held_by_sid: dict[str, dict],
|
|
live_by_parent: dict[str, list[dict]] | None = None) -> bool:
|
|
if e.summary is not s or e.agents != agents or e.sub_at != sub_at:
|
|
return False
|
|
sid = s.get("sessionId")
|
|
if live_by_parent is not None and e.live_kids != tuple(
|
|
a["toolUseId"][6:] for a in live_by_parent.get(sid or "", [])):
|
|
return False
|
|
if e.alive != (bool(sid) and sid in alive_set):
|
|
return False
|
|
if e.held != (held_by_sid.get(sid) if sid else None):
|
|
return False
|
|
if e.epoch != _epoch(path, now):
|
|
return False
|
|
if len(e.kids) != len(kids) or any(a is not b for a, b in zip(e.kids, kids)):
|
|
return False
|
|
if e.meta is not m and (e.meta or m): # peek hands out a fresh {} when absent
|
|
return False
|
|
if e.ctx is not None and e.ctx is not ctx_now():
|
|
return False
|
|
if e.cal != cal_of(e.account):
|
|
return False
|
|
return e.built >= e.settles or e.bucket == bucket
|
|
|
|
|
|
def _build_conversation_cards(deps: AppState, full: bool) -> list[dict]:
|
|
"""Every non-sidechain conversation as a card dict, unsorted — each from
|
|
the per-card cache unless one of its inputs moved (see above).
|
|
|
|
Only ``full=False`` is retained in ``_card_cache`` (avoiding a second
|
|
persistent 3,000-card cache in RAM); ``full=True`` attaches the heavy
|
|
analytics fields (``usage``/``byToolSub``/``byModel``) onto shallow copies
|
|
of the cached cards and is memoized by ``_cards_memo[True]``.
|
|
|
|
Summaries come from the store's shared decode cache and are **never
|
|
mutated** here — rollups copy, and per-card extras land on the card."""
|
|
summaries = deps.store.all_summaries()
|
|
# Group subagent summaries under their parent so we can roll their usage up,
|
|
# and collect per-session subagent activity in the same single pass.
|
|
children: dict[str, list[dict]] = {}
|
|
child_paths: dict[str, list[str]] = {}
|
|
sub_activity: dict[str, str] = {}
|
|
roots: list[tuple[str, dict]] = []
|
|
for path, s in summaries:
|
|
if "/subagents/" in path:
|
|
sid, ended = s.get("sessionId"), s.get("endedAt")
|
|
if sid and ended and ended > sub_activity.get(sid, ""):
|
|
sub_activity[sid] = ended
|
|
if s.get("isSidechain"):
|
|
pp = _root_path_of(path) # every depth rolls into the root card
|
|
if pp:
|
|
children.setdefault(pp, []).append(s)
|
|
child_paths.setdefault(pp, []).append(path)
|
|
else:
|
|
roots.append((path, s))
|
|
|
|
deduped = _dedup_by_session(roots)
|
|
|
|
if full:
|
|
base_cards = _conversation_cards(deps, False)
|
|
by_id = {_conv_id(p): (p, s) for p, s in deduped if s.get("messages")}
|
|
out_full = []
|
|
for card in base_cards:
|
|
hit = by_id.get(card["id"])
|
|
if hit is None:
|
|
out_full.append(dict(card))
|
|
continue
|
|
path, s = hit
|
|
rolled = _rollup_children(s, children.get(path, []))
|
|
out_full.append({
|
|
**card,
|
|
**{k: rolled.get(k) for k in _EXTRA_FULL_KEYS},
|
|
})
|
|
return out_full
|
|
|
|
skills_map = _skills_map(deps)
|
|
agents_by_conv = _agents_by_conversation(deps)
|
|
colors = getattr(deps, "look_colors", None)
|
|
flush = (deps.profile_store.version, getattr(colors, "version", 0))
|
|
prev_flush, prev = _card_cache[False]
|
|
if prev_flush != flush:
|
|
prev = {}
|
|
now = time.time()
|
|
bucket = int(now // _CARDS_TIME_BUCKET_S)
|
|
ctx_box: list = []
|
|
|
|
def ctx_now():
|
|
if not ctx_box:
|
|
ctx_box.append(resource_view.context(deps))
|
|
return ctx_box[0]
|
|
|
|
cals: dict[str, dict] = {}
|
|
|
|
def cal_of(account: str) -> dict:
|
|
if account not in cals:
|
|
cals[account] = calibrate.current(deps, account)
|
|
return cals[account]
|
|
|
|
alive_set = liveruns.snapshot()
|
|
held_by_sid = liveruns.held_map()
|
|
live_by_parent = spawned_live.by_parent(deps)
|
|
entries: dict[str, _CardEntry] = {}
|
|
out = []
|
|
# A session resumed across working dirs has one transcript file per cwd —
|
|
# collapse those so the conversation shows up once, not once per copy.
|
|
for path, s in deduped:
|
|
if not s.get("messages"):
|
|
continue # skip empty transcripts
|
|
kids = children.get(path, [])
|
|
m = deps.meta_store.peek(s.get("sessionId") or "")
|
|
agents = agents_by_conv.get(_conv_id(path), [])
|
|
sub_at = (sub_activity.get(s.get("sessionId") or "")
|
|
if s.get("runningAgents") else None)
|
|
e = prev.get(path)
|
|
if e is None or not _card_fresh(e, path, s, kids, m, agents, sub_at, now,
|
|
bucket, ctx_now, cal_of,
|
|
alive_set, held_by_sid, live_by_parent):
|
|
e = _card_entry(deps, path, s, kids, child_paths.get(path, []),
|
|
_CARD_KEYS, m, agents, sub_at, now, bucket,
|
|
skills_map=skills_map,
|
|
alive_set=alive_set, held_by_sid=held_by_sid)
|
|
entries[path] = e
|
|
out.append(e.card)
|
|
_card_cache[False] = (flush, entries)
|
|
return out
|
|
|
|
|
|
_cards_memo = {f: _Memo(_build_conversation_cards) for f in (False, True)}
|
|
|
|
|
|
# ── diff view: per-conversation commits + commit / conversation diffs ────────
|
|
def _resolve_transcript(id: str) -> pathlib.Path:
|
|
"""Validate a conversation id and return its archived transcript path."""
|
|
if not TRANSCRIPTS_DIR:
|
|
raise HTTPException(404, "transcripts not mounted")
|
|
# A UUIDv7 (conversations/ids.py), or a legacy path id from an old link.
|
|
rel_id = ids.rel_for(id)
|
|
if rel_id is None:
|
|
raise HTTPException(404 if ids.is_uid(id) else 400,
|
|
"not found" if ids.is_uid(id) else "invalid id")
|
|
rel = pathlib.PurePosixPath(rel_id)
|
|
if rel.is_absolute() or ".." in rel.parts or rel.suffix != ".jsonl":
|
|
raise HTTPException(400, "invalid id")
|
|
ap = (TRANSCRIPTS_DIR / rel_id).resolve()
|
|
try:
|
|
ap.relative_to(TRANSCRIPTS_DIR)
|
|
except ValueError:
|
|
raise HTTPException(400, "id escapes transcripts")
|
|
if not ap.is_file():
|
|
raise HTTPException(404, "not found")
|
|
return ap
|
|
|
|
|
|
def _summary_and_meta(deps: AppState, id: str) -> tuple[str, dict, dict]:
|
|
"""(sessionId, summary, meta sidecar) for a conversation id."""
|
|
ap = _resolve_transcript(id)
|
|
summary = deps.store.get_summary(str(ap)) or conversations.parse_conversation(ap, full=False)
|
|
sid = summary.get("sessionId") or ""
|
|
return sid, summary, deps.meta_store.get(sid)
|
|
|
|
|
|
def _meta_key(raw: str) -> str:
|
|
"""Accept a bare session id or a transcript id (a uid, or a legacy path);
|
|
store under the session id."""
|
|
if ids.is_uid(raw):
|
|
raw = ids.REGISTRY.rel(raw) or raw
|
|
name = pathlib.PurePosixPath(raw).name
|
|
return name[:-6] if name.endswith(".jsonl") else name
|
|
|
|
|
|
# ── cron jobs: scheduled agent sessions (see cron.py) ────────────────────────
|
|
# sessionId → conversation id, for linking a job's run history to the viewer.
|
|
# Single-flight memoized on the summaries version.
|
|
def _build_session_conv_map(deps: AppState) -> dict[str, str]:
|
|
m: dict[str, str] = {}
|
|
for path, s in deps.store.all_summaries():
|
|
sid = s.get("sessionId")
|
|
if sid and not _is_sidechain_path(path):
|
|
m[sid] = _conv_id(path)
|
|
return m
|
|
|
|
|
|
_sid_map_memo = _Memo(_build_session_conv_map)
|
|
|
|
|
|
def _session_conv_map(deps: AppState) -> dict:
|
|
return _sid_map_memo.get((id(deps.store), deps.store.summaries_version), deps)
|
|
|
|
|
|
_by_sid_cache: tuple[int, dict] | None = None
|
|
|
|
|
|
def _conv_ids_by_session(deps: AppState) -> dict[str, str]:
|
|
"""sessionId → transcript id (newest summary wins) for conversation links.
|
|
Memoized on the summaries version: the thread view asks on every load.
|
|
|
|
Subagent transcripts are left out: they carry the parent's sessionId, and
|
|
while a big workflow runs the parent sits idle as its subagents keep
|
|
writing — so a subagent would be the "newest" file and the parent's thread
|
|
(`continuedIn`), its pushes and its forms would all point into it."""
|
|
global _by_sid_cache
|
|
v = deps.store.summaries_version
|
|
cached = _by_sid_cache
|
|
if cached and cached[0] == v:
|
|
return cached[1]
|
|
best: dict[str, tuple[str, str]] = {}
|
|
for path, s in deps.store.all_summaries():
|
|
sid = s.get("sessionId")
|
|
if not sid or not s.get("messages"):
|
|
continue
|
|
if s.get("isSidechain") or _is_sidechain_path(path):
|
|
continue
|
|
ended = s.get("endedAt") or ""
|
|
prev = best.get(sid)
|
|
if prev is None or ended > prev[0]:
|
|
best[sid] = (ended, _conv_id(path))
|
|
out = {sid: cid for sid, (_, cid) in best.items()}
|
|
_by_sid_cache = (v, out)
|
|
return out
|
|
|
|
|
|
def _cron_jobs(deps) -> list[dict]:
|
|
"""The cron-jobs plugin's jobs (``plugins/cron_bridge.py`` ``index``,
|
|
cached — never a wait on a hot path): their ``promptFile`` and
|
|
``history`` tie an agent's session runs to it."""
|
|
from plugins import cron_bridge
|
|
return cron_bridge.index(deps)
|