Python
Background subagents and a smarter side panel (#850)
Rohit Prasadcf035e2d1d4b
diff --git a/coworker/agent.py b/coworker/agent.pyindex e9278f00..1384876f 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -455,6 +455,7 @@ def build_engine(provider = provider or ProviderRouter(secrets, default_provider="openai")# Repo-focused personas can fan broad research out to read-only explorer subagents, keeping# their own context for the actual change.+ agent_task_registry = Noneif agent.subagents and ws is not None:registry.register_all(explorer_tools(@@ -464,6 +465,18 @@ def build_engine(model_settings=model_settings,))+ # Async subagents (OPE-254): the background variant of explore, plus the+ # inherit mode whose approvals route through this session's own approver.+ # The registry is bound to the engine below, once it exists.+ from .tools.agent_tasks import agent_task_tools++ _agent_tools, agent_task_registry = agent_task_tools(+ workspace=ws,+ provider=provider,+ model=model,+ model_settings=model_settings,+ )+ registry.register_all(_agent_tools)# Scheduling: opted-in surfaces with a workspace can set up scheduled tasks (origin = this# session). Code stays out (it fans out to explorers instead).if task_store is not None and ws is not None and agent.scheduling:@@ -757,6 +770,11 @@ def build_engine(engine.compaction_settings = lambda: dict(_compaction_overrides)# OPE-237: in auto-approve, an approved plan's steps become reviewer evidence.engine.plan_approval = bool(config.auto_approve_plan_approval)+ # Async subagents: the registry the spawn tools and the server's tasks endpoint+ # share; bound late because the tools were registered before the engine existed.+ if agent_task_registry is not None:+ agent_task_registry.bind(engine)+ engine.agent_tasks = agent_task_registryengine.executor = executor # type: ignore[attr-defined]# OPE-232 / OPE-234: the read-only session grant and the auto-approve read-only tier# judge paths from the persistent shell's current folder, not the workspace folder itdiff --git a/coworker/engine.py b/coworker/engine.pyindex a27243cd..e21c79a8 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -354,6 +354,11 @@ class TurnEngine:# into the tool message's `_display` sidecar, so the quiet provenance chips# survive reload (owner ruling 2026-08-24) — display-only, never provider-visible.self._approval_origins: dict[str, dict[str, str]] = {}+ # Per-call override for the denied-tool-result text, keyed by tool_call id. An+ # approver that resolves a request itself (a subagent's expired approval wait)+ # sets this before returning DENY, so the model reads WHY instead of the+ # generic "denied by user" (OPE-255 ruling: the response must say it expired).+ self._deny_notes: dict[str, str] = {}# OPE-232: set once a shell command has been cleared in the batch being authorized.# The batch runs only after every call is cleared, and the shell persists, so a# later command's folder is unknown from then on (see `current_shell_cwd`).@@ -905,6 +910,8 @@ class TurnEngine:payload["reasoning_effort"] = effort_recordif turn.served_by:payload["served_by"] = turn.served_by+ # Context panel (FB-015): the window occupancy after this reply landed.+ payload["context"] = self.context_snapshot()yield Event(EventType.ASSISTANT_MESSAGE, payload)if not turn.tool_calls:@@ -1076,6 +1083,39 @@ class TurnEngine:state = self.compaction_statereturn state.as_dict() if state is not None else None+ def context_snapshot(self) -> dict[str, Any]:+ """What occupies the model's window right now (FB-015), for the GUI's Context+ panel: `used` is the provider-reported prompt-side total from the latest round+ trip when one exists (estimate fallback otherwise, flagged `estimated`); the+ category split — system prompt / tool schemas / conversation — is always the+ chars/4 estimate, so surfaces must present it as proportion, not ledger."""+ msgs = self._outbound_messages()+ system = _compaction.estimate_tokens(+ [m for m in msgs if m.get("role") == "system"]+ )+ convo = _compaction.estimate_tokens(+ [m for m in msgs if m.get("role") != "system"]+ )+ schemas = self.registry.schemas() or []+ tools = (+ len(json.dumps(schemas, ensure_ascii=False)) // 4 if schemas else 0+ )+ reported = int(self._last_context_tokens or 0)+ snapshot: dict[str, Any] = {+ "window": self._compaction_config().get("context_window"),+ "used": reported or (system + tools + convo),+ "estimated": not reported,+ "breakdown": {"system": system, "tools": tools, "messages": convo},+ }+ state = self.compaction_state+ if state is not None:+ snapshot["compaction"] = {+ "created_at": state.created_at,+ "messages": state.boundary_index,+ "trimmed": state.trimmed,+ }+ return snapshot+async def _compact_now(self, *, force: bool = False) -> Optional[str]:"""Run the compaction policy. Callers gate on `_compaction_due()` (or `force`,the overflow path). Returns the user-facing notice text when the outbound view@@ -2159,7 +2199,8 @@ class TurnEngine:if outcome is ApprovalOutcome.DENY:allowed, reason = (False,- "interrupted by user" if self._cancel.is_set() else "denied by user",+ self._deny_notes.pop(tool_call.id, None)+ or ("interrupted by user" if self._cancel.is_set() else "denied by user"),)self._approval_origins[tool_call.id] = {"origin": "user",diff --git a/coworker/server/app.py b/coworker/server/app.pyindex e2bb9a99..93025f1c 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -481,6 +481,19 @@ def create_app(manager: SessionManager) -> FastAPI:"attendance": manager.unattended.attendance(session_id),}+ @app.get("/v1/sessions/{session_id}/tasks")+ def get_session_tasks(session_id: str) -> dict[str, Any]:+ # Async subagents (OPE-257): the Subagents section's registry view. A live+ # engine answers from its registry; otherwise the supplemental record answers,+ # so history shows before the session's first turn after a restart.+ engine = manager._engines.get(session_id)+ reg = getattr(engine, "agent_tasks", None) if engine else None+ if reg is not None:+ return {"agents": reg.snapshot()}+ rows = manager.agent_task_store.load(session_id)+ rows.sort(key=lambda r: r.get("created") or 0, reverse=True)+ return {"agents": [{k: v for k, v in r.items() if k != "report"} for r in rows]}+@app.get("/v1/sessions/{session_id}/reviewer-stats")def get_reviewer_stats(session_id: str) -> dict[str, Any]:# Auto-Approve metering (§1.7): checks/verdicts/tokens from the durable audit rows.@@ -3187,6 +3200,9 @@ def create_app(manager: SessionManager) -> FastAPI:"command_trust": manager.workspace_command_trust(str(getattr(engine, "audit_context", {}).get("workspace", ""))),+ # Context panel (FB-015): occupancy on reconnect, so a reopened+ # session shows its meter before any new turn runs.+ "context": engine.context_snapshot(),},})diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex fad31df5..7b791995 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -498,6 +498,11 @@ class SessionManager:self.inbox_routing = InboxRouting(base / "inbox_routing.json")self.unattended = UnattendedRegistry(base / "unattended.json")self.wakes = WakeStore(base / "wakes.json")+ # Async subagents (OPE-253): the supplemental session record for subagent runs —+ # written on task transitions, so a run that ends between turn checkpoints survives.+ from ..tools.agent_tasks import AgentTaskStore++ self.agent_task_store = AgentTaskStore(base / "agent_tasks.json")# Channel subscriptions (inbound): persisted (session_id, channel) records + a ring buffer# of recently-seen channel messages for get_channel_messages.self.subscriptions = SubscriptionStore(base / "subscriptions.json")@@ -859,6 +864,7 @@ class SessionManager:engine.team_approver = team_approverif items_approver is not None:engine.items_approver = items_approver+ self._wire_agent_tasks(session_id, engine)return enginerecord = self.session_store.load(session_id)@@ -1024,10 +1030,45 @@ class SessionManager:engine.compaction_settings = self.compaction_settingsself._engines[session_id] = engineself.sync_worker_mode(session_id, engine) # §11.6: approvals follow the lead+ self._wire_agent_tasks(session_id, engine)if is_new_session:self._emit_session_created(session_id, agent_name)return engine+ def _wire_agent_tasks(self, session_id: str, engine: TurnEngine) -> None:+ """Hook a session's async-subagent registry (OPE-254) to the server: the loop+ its inherit children run on, report delivery through deliver_to_session (steer+ when busy, background turn when idle), live agent_task events for the rail,+ and expiry resolution for a parked card whose approval wait timed out."""+ reg = getattr(engine, "agent_tasks", None)+ if reg is None:+ return+ reg.loop = self._loop+ reg.attach_store(self.agent_task_store, session_id)++ def deliver(text: str, source: dict) -> None:+ if self._loop is None:+ raise RuntimeError("agent-task delivery needs the server loop")+ asyncio.run_coroutine_threadsafe(+ self.deliver_to_session(session_id, text, source=source), self._loop+ )++ def on_event(payload: dict) -> None:+ if self._loop is None:+ return+ asyncio.run_coroutine_threadsafe(+ self.broadcast_session(session_id, {"type": "agent_task", "data": payload}),+ self._loop,+ )++ def resolve_expired(tool_call_id: str) -> None:+ item = self.inbox.for_tool_call(session_id, tool_call_id)+ if item is not None:+ # First-responder-wins: a no-op if the human answered in the same instant.+ self.inbox.resolve(item.id, "expired", by="timeout")++ reg.deliver, reg.on_event, reg.resolve_expired = deliver, on_event, resolve_expired+def _emit_session_created(self, session_id: str, persona_id: str) -> None:"""Phase 5 telemetry, fired once per brand-new session on a background thread(never blocks session start). cloud.emit_session_created is a hard no-op when@@ -8648,6 +8689,8 @@ class SessionManager:# ...and closes its pending Inbox items — an orphaned approval/question can never be# meaningfully answered (owner call, 2026-07-03).self.inbox.resolve_session(session_id)+ # ...and its subagent-run history (the supplemental record dies with the session).+ self.agent_task_store.drop(session_id)# ...and its scratch dir. STRICTLY scoped: only a directory inside scratch_base is# removed — a real project folder the user picked is never touched.if ok and record and record.workspace:diff --git a/coworker/sessions.py b/coworker/sessions.pyindex 6724590b..3f6888f1 100644--- a/coworker/sessions.py+++ b/coworker/sessions.py@@ -65,12 +65,10 @@ def usage_totals(messages: list[dict[str, Any]]) -> dict[str, dict[str, int]]:"""Fold the assistant messages' `usage` sidecars into per-model totals (spec §5).Deterministic from the transcript, so a re-save never double counts."""out: dict[str, dict[str, int]] = {}- for m in messages or []:- if m.get("role") != "assistant":- continue- u = m.get("usage")++ def fold(u: Any, turns: int) -> None:if not isinstance(u, dict):- continue+ returnkey = str(u.get("model") or "unknown")row = out.setdefault(key, {f: 0 for f in USAGE_FIELDS} | {"turns": 0})for f in USAGE_FIELDS:@@ -78,5 +76,17 @@ def usage_totals(messages: list[dict[str, Any]]) -> dict[str, dict[str, int]]:row[f] += max(int(u.get(f) or 0), 0)except (TypeError, ValueError):pass- row["turns"] += 1+ row["turns"] += turns++ for m in messages or []:+ if m.get("role") == "assistant":+ fold(m.get("usage"), 1)+ elif m.get("role") == "notice":+ # A finished subagent's spend (OPE-258): the `agent_task` notice carries+ # the child's per-model totals, since its turns never join this transcript.+ au = m.get("agent_usage")+ if isinstance(au, dict):+ for model, u in au.items():+ fold({"model": model, **u} if isinstance(u, dict) else None,+ int(u.get("turns") or 0) if isinstance(u, dict) else 0)return outdiff --git a/coworker/tools/agent_tasks.py b/coworker/tools/agent_tasks.pynew file mode 100644index 00000000..42777ddd--- /dev/null+++ b/coworker/tools/agent_tasks.py@@ -0,0 +1,566 @@+"""Async subagents (OPE-253/254): background extra hands of the same coworker.++`spawn_agent` returns a task id immediately — the mirror of `run_shell`'s background+contract — and the child runs with its own fresh context while the parent keeps+working. The child is the SAME identity, not a new actor:++- `read_only` (default): the explorer toolset in plan mode — can never write or+ shell, so it never needs an approval and runs anywhere (own thread + loop, like+ the synchronous `explore`).+- `inherit`: the parent's tools (minus the spawn tools — no recursion), the parent's+ PermissionEngine (same mode, same session grants) and the parent's approver. The+ human stays the only approver (OPE-255): a child's ask parks in the parent+ session's one approval stream, labeled with the subagent's name, and its+ tool-call ids are prefixed with the task id so the Inbox's+ (session_id, tool_call_id) idempotency key can't collide with the parent's.+ Inherit children run on the server loop (`registry.loop`), where those approver+ closures are safe to await.++Approval deadline (OPE-255 ruling): no timeout by default — a child waits on its+card forever, like a main session. A parent may pass `approval_timeout` at spawn+(floor 60s); expiry resolves the ask as DECLINED, never approved, the card flips to+an expired state instead of vanishing, and the child's tool result says the request+expired so the model continues honestly without the step.++Delivery (OPE-256): on completion the registry's `deliver` hook (the manager wires+it to `deliver_to_session`) steers a busy parent at the next iteration boundary or+wakes an idle one with the report; without a manager the report is queued as+steering on the parent engine directly. Completion also appends an `agent_task`+notice carrying the child's per-model token usage, which `sessions.usage_totals`+folds into the session's totals (OPE-258).+"""++from __future__ import annotations++import asyncio+import functools+import json+import threading+import time+from dataclasses import dataclass, field, replace+from pathlib import Path+from typing import Any, Callable, Optional++import aisuite as ai++from ..engine import ApprovalOutcome, EventType, PermissionRequest, TurnEngine+from .subagent import build_explorer_engine++_MAX_ACTIVE = 3+_CHILD_MAX_ITERATIONS = 25+_MIN_APPROVAL_TIMEOUT = 60.0+# Supplemental record (owner ruling 2026-11-07): last N finished runs per session,+# reports truncated — the full text already reached the parent transcript at delivery.+_KEEP_FINISHED = 50+_REPORT_STORE_MAX = 8192+++class AgentTaskStore:+ """`agent_tasks.json` — the supplemental session record for subagent runs, beside+ the wake store. Written on every task transition (a subagent finishes BETWEEN turn+ checkpoints, so riding the session record would leave it undurable until the next+ save). One file, keyed by session id; atomic tmp-and-replace like WakeStore."""++ def __init__(self, path: Optional[str | Path] = None) -> None:+ self.path = Path(path) if path else None+ self._lock = threading.Lock()+ self._sessions: dict[str, list[dict[str, Any]]] = {}+ if self.path and self.path.is_file():+ try:+ saved = json.loads(self.path.read_text(encoding="utf-8"))+ self._sessions = {+ str(k): [dict(r) for r in v]+ for k, v in (saved.get("sessions") or {}).items()+ }+ except Exception:+ self._sessions = {}++ def _save(self) -> None: # caller holds the lock+ if not self.path:+ return+ self.path.parent.mkdir(parents=True, exist_ok=True)+ tmp = self.path.with_suffix(self.path.suffix + ".tmp")+ tmp.write_text(json.dumps({"sessions": self._sessions}, indent=2), encoding="utf-8")+ tmp.replace(self.path)++ def load(self, session_id: str) -> list[dict[str, Any]]:+ """This session's persisted runs. A run persisted as live is honestly lost —+ its engine died with the app — and is flipped to an error, not a phantom."""+ with self._lock:+ rows = [dict(r) for r in self._sessions.get(session_id, [])]+ changed = False+ for r in rows:+ if r.get("status") in ("running", "waiting"):+ r["status"] = "error"+ r["note"] = "lost when the app restarted"+ r.setdefault("finished", time.time())+ changed = True+ if changed:+ self.put(session_id, rows)+ return rows++ def put(self, session_id: str, rows: list[dict[str, Any]]) -> None:+ live = [r for r in rows if r.get("status") in ("running", "waiting")]+ done = [r for r in rows if r.get("status") not in ("running", "waiting")]+ done.sort(key=lambda r: r.get("finished") or r.get("created") or 0, reverse=True)+ keep = live + done[:_KEEP_FINISHED]+ for r in keep:+ rep = r.get("report") or ""+ if len(rep) > _REPORT_STORE_MAX:+ r["report"] = (+ rep[:_REPORT_STORE_MAX]+ + "\n… (truncated in the store — the full report was delivered in the session)"+ )+ with self._lock:+ self._sessions[session_id] = keep+ self._save()++ def drop(self, session_id: str) -> None:+ with self._lock:+ if session_id in self._sessions:+ del self._sessions[session_id]+ self._save()++INHERIT_INSTRUCTIONS = """You are a background subagent of the main coworker, working inside the same \+workspace with the same tools and the same permissions. The user sees your approval requests in the \+main session, labeled with your name — ask only for what the task truly needs. If an approval is \+declined or expires, do not retry it: continue without that step and note the gap.++Your final message is your report — it goes back to the main agent, not to the user. Make it \+self-contained: answer the task directly, reference code as path:line, list anything you changed, \+and note what you could not do and why."""+++@dataclass+class AgentTask:+ id: str+ label: str+ task: str+ mode: str # "read_only" | "inherit"+ status: str = "running" # running | waiting | done | error | canceled+ report: str = ""+ note: str = ""+ created: float = field(default_factory=time.time)+ finished: Optional[float] = None+ usage: dict[str, dict[str, int]] = field(default_factory=dict)+ icon_seed: int = 0+ approval_timeout: Optional[float] = None+ engine: Optional[TurnEngine] = None+ # The loop the child runs on (its own in read_only, the server's in inherit) —+ # how cancel and follow-ups reach it thread-safely.+ loop: Optional[asyncio.AbstractEventLoop] = None++ def snapshot(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "label": self.label,+ "task": self.task,+ "mode": self.mode,+ "status": self.status,+ "note": self.note,+ "created": self.created,+ "finished": self.finished,+ "usage": self.usage,+ "icon_seed": self.icon_seed,+ }+++class AgentTaskRegistry:+ """Per-session registry of background subagent runs (in-memory v1, like the+ background shells: it dies with the app, never with the turn)."""++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._tasks: dict[str, AgentTask] = {}+ self._counter = 0+ self.parent: Optional[TurnEngine] = None+ # Manager-wired hooks; every one is optional so the CLI still works.+ self.loop: Optional[asyncio.AbstractEventLoop] = None # the server loop+ self.deliver: Optional[Callable[[str, dict[str, Any]], None]] = None+ self.on_event: Optional[Callable[[dict[str, Any]], None]] = None+ # Resolves a parked Inbox card whose wait expired (prefixed tool_call_id).+ self.resolve_expired: Optional[Callable[[str], None]] = None+ # The supplemental record (AgentTaskStore), manager-attached.+ self.store: Optional[AgentTaskStore] = None+ self.session_id: str = ""++ def bind(self, parent: TurnEngine) -> None:+ self.parent = parent++ def attach_store(self, store: AgentTaskStore, session_id: str) -> None:+ """Rehydrate this session's history (done rows only — a live run's engine+ never survives a restart, and load() already marked those lost)."""+ if self.store is store and self.session_id == session_id:+ return+ self.store, self.session_id = store, session_id+ with self._lock:+ known = set(self._tasks)+ for row in store.load(session_id):+ tid = str(row.get("id") or "")+ if not tid or tid in known:+ continue+ self._tasks[tid] = AgentTask(+ id=tid,+ label=str(row.get("label") or tid),+ task=str(row.get("task") or ""),+ mode=str(row.get("mode") or "read_only"),+ status=str(row.get("status") or "error"),+ report=str(row.get("report") or ""),+ note=str(row.get("note") or ""),+ created=float(row.get("created") or 0),+ finished=row.get("finished"),+ usage=dict(row.get("usage") or {}),+ icon_seed=int(row.get("icon_seed") or 0),+ )+ # Fresh ids must never collide with rehydrated ones.+ try:+ self._counter = max(self._counter, int(tid.split("-")[-1]))+ except ValueError:+ pass++ def _persist(self) -> None:+ if self.store is None or not self.session_id:+ return+ with self._lock:+ rows = [{**t.snapshot(), "report": t.report} for t in self._tasks.values()]+ try:+ self.store.put(self.session_id, rows)+ except Exception:+ pass # a persistence hiccup must never take a child run down++ def new_task(self, label: str, task: str, mode: str, timeout: Optional[float]) -> AgentTask:+ with self._lock:+ self._counter += 1+ t = AgentTask(+ id=f"agent-{self._counter}",+ label=label,+ task=task,+ mode=mode,+ # Raw counter: the GUI derives shape (mod 10) and color family from it,+ # so the full 10×8 identity space is usable and stable per run.+ icon_seed=self._counter,+ approval_timeout=timeout,+ )+ self._tasks[t.id] = t+ return t++ def get(self, task_id: str) -> Optional[AgentTask]:+ with self._lock:+ return self._tasks.get(task_id)++ def active_count(self) -> int:+ with self._lock:+ return sum(1 for t in self._tasks.values() if t.status in ("running", "waiting"))++ def snapshot(self) -> list[dict[str, Any]]:+ with self._lock:+ return [t.snapshot() for t in sorted(self._tasks.values(), key=lambda t: t.created, reverse=True)]++ # -- internals ---------------------------------------------------------------++ def _emit(self, kind: str, task: AgentTask) -> None:+ # Every transition goes through here: persist first, then tell the GUI.+ self._persist()+ if self.on_event:+ try:+ self.on_event({"kind": kind, **task.snapshot()})+ except Exception:+ pass++ async def _consume(self, task: AgentTask, user_input: str) -> None:+ """Drive one child turn, folding usage and watching for approval waits."""+ engine = task.engine+ assert engine is not None+ task.loop = asyncio.get_running_loop()+ report, status = "", "unknown"+ try:+ async for event in engine.run(user_input):+ if event.type == EventType.PERMISSION_REQUIRED:+ task.status = "waiting"+ self._emit("agent_task_waiting", task)+ elif event.type == EventType.TOOL_FINISHED and task.status == "waiting":+ task.status = "running"+ self._emit("agent_task_running", task)+ elif event.type == EventType.ASSISTANT_MESSAGE:+ if event.data.get("text"):+ report = event.data["text"]+ u = event.data.get("usage")+ if isinstance(u, dict):+ key = str(u.get("model") or "unknown")+ row = task.usage.setdefault(+ key, {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0, "turns": 0}+ )+ for f in ("input", "output", "cache_read", "cache_write"):+ row[f] += int(u.get(f) or 0)+ row["turns"] += 1+ elif event.type == EventType.TURN_END:+ status = event.data.get("status", "unknown")+ elif event.type == EventType.INTERRUPTED:+ status = "canceled"+ elif event.type == EventType.ERROR:+ status = f"error: {event.data.get('error', '')}"+ except Exception as exc: # the child must never take the parent surface down+ status = f"error: {exc}"+ self._finish(task, report, status)++ def _finish(self, task: AgentTask, report: str, status: str) -> None:+ task.finished = time.time()+ task.report = report+ if status == "completed":+ task.status = "done"+ elif status == "canceled":+ task.status, task.note = "canceled", "stopped by request"+ elif status.startswith("error"):+ task.status, task.note = "error", status+ else:+ task.status, task.note = "done", f"stopped early ({status}); the report may be partial"+ self._emit("agent_task_finished", task)+ self._deliver_report(task)++ def _deliver_report(self, task: AgentTask) -> None:+ label = task.label or task.id+ if task.status == "canceled":+ return # the canceller knows; no wake for a run the user/parent stopped+ body = task.report or "(no report)"+ note = f" ({task.note})" if task.note else ""+ text = f"[Subagent '{label}' {task.status}{note}] {body}"+ # The usage notice first: it must be in the transcript before the delivery+ # turn saves, so usage_totals folds it exactly once (OPE-258).+ parent = self.parent+ if parent is not None:+ append = functools.partial(+ parent._append_notice,+ "agent_task",+ f"Subagent '{label}' {task.status}",+ agent_task=task.id,+ agent_usage=dict(task.usage),+ )+ try:+ # call_soon_threadsafe takes no callback kwargs — hence the partial.+ if self.loop is not None:+ self.loop.call_soon_threadsafe(append)+ else:+ append()+ except Exception:+ pass # the usage notice must never block the report delivery below+ source = {"connector": "subagent", "title": label, "task_id": task.id}+ if self.deliver is not None:+ try:+ self.deliver(text, source)+ return+ except Exception:+ pass+ # No manager (CLI/tests): queue as steering; the next parent turn picks it up.+ if parent is not None:+ parent.queue_steering(text, source=source)++ def _wrap_approver(self, task: AgentTask, child: TurnEngine):+ async def approver(req: PermissionRequest) -> ApprovalOutcome:+ # Resolved at CALL time: the manager overwrites the parent's approver on+ # every reconnect, and the child must always ask through the live one.+ parent_approver = getattr(self.parent, "approver", None)+ if parent_approver is None:+ return ApprovalOutcome.DENY+ # Prefix the id (Inbox idempotency is (session_id, tool_call_id)) and name+ # the asker so the card says which subagent wants what.+ prefixed = f"{task.id}:{req.tool_call_id or ''}"+ labeled = replace(+ req,+ tool_call_id=prefixed,+ reason=f"[subagent: {task.label}] {req.reason or ''}".strip(),+ )+ if not task.approval_timeout:+ return await parent_approver(labeled)+ try:+ return await asyncio.wait_for(parent_approver(labeled), task.approval_timeout)+ except asyncio.TimeoutError:+ secs = int(task.approval_timeout)+ if req.tool_call_id:+ child._deny_notes[req.tool_call_id] = (+ f"approval request expired after {secs}s and was treated as NOT "+ "approved — continue without this step and note the gap in your report"+ )+ if self.resolve_expired:+ try:+ self.resolve_expired(prefixed)+ except Exception:+ pass+ return ApprovalOutcome.DENY++ return approver+++def agent_task_tools(+ *,+ workspace: str | Path,+ provider: Any,+ model: str,+ model_settings: Optional[dict[str, Any]] = None,+) -> tuple[list, AgentTaskRegistry]:+ """The four background-subagent tools plus the registry the server reads.+ `registry.bind(engine)` must be called once the parent engine exists."""+ registry = AgentTaskRegistry()+ ws = str(Path(workspace).resolve())++ def _build_child(task: AgentTask) -> TurnEngine:+ if task.mode == "inherit":+ parent = registry.parent+ assert parent is not None+ child_registry = parent.registry.clone(+ exclude={"spawn_agent", "agent_task_output", "agent_send", "agent_task_cancel", "explore"}+ )+ child = TurnEngine(+ provider=provider,+ registry=child_registry,+ permissions=parent.permissions, # same mode, same session grants+ model=model,+ instructions=INHERIT_INSTRUCTIONS,+ max_iterations=_CHILD_MAX_ITERATIONS,+ model_settings=model_settings,+ )+ wrapped = registry._wrap_approver(task, child)+ if wrapped is not None:+ child.approver = wrapped+ # Attendance follows the parent: in auto mode the child auto-answers the+ # same way; in ask mode its cards reach the same person.+ for attr in ("is_attended", "attendance", "cards_reach_person"):+ val = getattr(parent, attr, None)+ if val is not None:+ setattr(child, attr, val)+ return child+ return build_explorer_engine(+ workspace=ws,+ provider=provider,+ model=model,+ model_settings=model_settings,+ max_iterations=_CHILD_MAX_ITERATIONS,+ )++ def _launch(task: AgentTask, user_input: str) -> None:+ if task.mode == "inherit" and registry.loop is not None:+ asyncio.run_coroutine_threadsafe(registry._consume(task, user_input), registry.loop)+ else:+ threading.Thread(+ target=lambda: asyncio.run(registry._consume(task, user_input)),+ name=f"subagent-{task.id}",+ daemon=True,+ ).start()++ def spawn_agent(+ task: str,+ label: str = "",+ mode: str = "read_only",+ approval_timeout: Optional[float] = None,+ ) -> dict:+ """Spawn a background subagent with its own fresh context and keep working —+ you get the report automatically when it finishes, so do NOT poll for it.+ `mode="read_only"` (default) researches the workspace and can never write;+ `mode="inherit"` gets your tools and permissions, and its approval requests go+ to the user labeled with this subagent's name. Use read_only unless the task+ must change something. State the task precisely and say what the report+ should include.++ Args:+ task (str): The full task, with constraints and the expected report shape.+ label (str): A short human-readable name for the run (2-4 words), shown in+ the side panel and on approval cards.+ mode (str): "read_only" (default) or "inherit".+ approval_timeout (float): Optional, inherit mode only — seconds an approval+ request may wait before it expires as NOT approved (minimum 60). Omit+ to wait indefinitely, like the main session.+ """+ if mode not in ("read_only", "inherit"):+ return {"error": f"unknown mode: {mode!r} (use 'read_only' or 'inherit')"}+ if mode == "inherit" and registry.loop is None:+ return {"error": "inherit mode is only available under the desktop app session; use read_only"}+ if registry.active_count() >= _MAX_ACTIVE:+ return {"error": f"already {_MAX_ACTIVE} subagents running — wait for one to finish"}+ timeout = None+ if approval_timeout:+ timeout = max(float(approval_timeout), _MIN_APPROVAL_TIMEOUT)+ t = registry.new_task(label.strip() or task.strip()[:40], task, mode, timeout)+ t.engine = _build_child(t)+ registry._emit("agent_task_started", t)+ _launch(t, task)+ return {+ "task_id": t.id,+ "label": t.label,+ "mode": mode,+ "note": "running in the background — the report arrives on its own when it finishes; continue your work",+ }++ def agent_task_output(task_id: str) -> dict:+ """Peek at a background subagent: status, token usage, and the report once it+ finished. The report is also delivered to you automatically — only use this to+ check on a run you suspect is stuck, not to poll.++ Args:+ task_id (str): The id spawn_agent returned (e.g. "agent-1").+ """+ t = registry.get(task_id)+ if t is None:+ return {"error": f"no such subagent task: {task_id}"}+ out = t.snapshot()+ if t.status in ("done", "error"):+ out["report"] = t.report+ return out++ def agent_send(task_id: str, message: str) -> dict:+ """Send a follow-up message to a subagent. A running one sees it at its next+ step; a finished one starts a new turn with its context intact and reports+ again when done.++ Args:+ task_id (str): The id spawn_agent returned.+ message (str): The follow-up or steering instruction.+ """+ t = registry.get(task_id)+ if t is None:+ return {"error": f"no such subagent task: {task_id}"}+ if t.engine is None:+ return {"error": "this subagent's context did not survive an app restart — spawn a new one"}+ framed = f"[Main agent] {message}"+ if t.status in ("running", "waiting"):+ if t.loop is not None:+ t.loop.call_soon_threadsafe(t.engine.queue_steering, framed)+ else:+ t.engine.queue_steering(framed)+ return {"task_id": t.id, "status": t.status, "note": "delivered — it is picked up at the next step"}+ if t.status == "canceled":+ return {"error": "this subagent was canceled; spawn a new one"}+ t.status, t.finished, t.note = "running", None, ""+ registry._emit("agent_task_started", t)+ _launch(t, framed)+ return {"task_id": t.id, "status": "running", "note": "continuing with its earlier context"}++ def agent_task_cancel(task_id: str) -> dict:+ """Stop a background subagent. Already-finished work is kept; its report (if+ any) stays readable via agent_task_output.++ Args:+ task_id (str): The id spawn_agent returned.+ """+ t = registry.get(task_id)+ if t is None:+ return {"error": f"no such subagent task: {task_id}"}+ if t.engine is None or t.status not in ("running", "waiting"):+ return {"task_id": t.id, "status": t.status, "note": "already finished"}+ if t.loop is not None:+ t.loop.call_soon_threadsafe(t.engine.request_interrupt)+ else:+ t.engine.request_interrupt()+ return {"task_id": t.id, "status": "canceling"}++ meta = lambda risk, caps, approval: ai.ToolMetadata( # noqa: E731+ category="agent", risk_level=risk, capabilities=caps, requires_approval=approval+ )+ tools = [+ # spawn itself never writes; what the CHILD does is gated by the child's own+ # calls (read_only can't write at all; inherit asks through the parent's+ # approver). So the spawn family stays approval-free, like explore.+ ai.tool(spawn_agent, metadata=meta("low", ["search"], False)),+ ai.tool(agent_task_output, metadata=meta("low", ["search"], False)),+ ai.tool(agent_send, metadata=meta("low", ["search"], False)),+ ai.tool(agent_task_cancel, metadata=meta("low", ["search"], False)),+ ]+ return tools, registrydiff --git a/coworker/tools/registry.py b/coworker/tools/registry.pyindex 047ab7b6..f3ffaa8f 100644--- a/coworker/tools/registry.py+++ b/coworker/tools/registry.py@@ -53,6 +53,16 @@ class ToolRegistry:def names(self) -> list[str]:return list(self._tools)+ def clone(self, *, exclude: Optional[set[str]] = None) -> "ToolRegistry":+ """A new registry over the same ToolSpecs, minus `exclude` — how a subagent+ inherits its parent's tools without the spawn tools themselves (no recursion)."""+ out = ToolRegistry()+ for name, spec in self._tools.items():+ if exclude and name in exclude:+ continue+ out._tools[name] = spec+ return out+def get(self, name: str) -> Optional[ToolSpec]:return self._tools.get(name)diff --git a/surfaces/gui/e2e/fixtures.ts b/surfaces/gui/e2e/fixtures.tsindex 40ecedbf..bbb486d4 100644--- a/surfaces/gui/e2e/fixtures.ts+++ b/surfaces/gui/e2e/fixtures.ts@@ -614,6 +614,8 @@ export async function mockApi(page: import("@playwright/test").Page) {// Session roots — the primary (writable, non-removable) scratch plus any added folders. Mutable so// the RO/RW add/toggle round-trips through the real UI. POST upserts by path (a toggle re-adds).const roots: any[] = [{ ...PRIMARY_ROOT }];+ // Async subagents: starts empty; the scripted spawn turn fills it and fires events.+ const agentTasks: any[] = [];// Session connections — PER-TEST copy so the Access section's mute toggle (POST) can flip// `enabled` without leaking into sibling tests.const connections = {@@ -703,7 +705,18 @@ export async function mockApi(page: import("@playwright/test").Page) {// The page's session id, from the socket URL — team approval stamps THIS session// as the lead (the active conversation IS the lead; workers hang off it).const sid = ws.url().split("/ws/session/")[1]?.split("?")[0] || "sess-lead";- send("ready", sid === "resume-live-1" ? { running: true } : {});+ // Context occupancy (FB-015) rides `ready` like the real server's, so the rail's+ // Context section has a value before any turn runs: 68k of 200k = 34%.+ const contextPayload = {+ window: 200_000,+ used: 68_000,+ estimated: false,+ breakdown: { system: 10_000, tools: 8_000, messages: 50_000 },+ };+ send("ready", {+ context: contextPayload,+ ...(sid === "resume-live-1" ? { running: true } : {}),+ });let pendingTool = "run_shell"; // which proposal the next approval decision resolveslet epicTimer: ReturnType<typeof setInterval> | null = null; // the slow stream, stoppable via interruptlet hadTurn = false; // a user_message landed — set_model is now a mid-session switch@@ -793,6 +806,46 @@ export async function mockApi(page: import("@playwright/test").Page) {return;}// A deliverable turn ending in an artifact chip (§34) — for the chip-open flow.+ // Async subagents (OPE-257): spawn → the registry row + started event arrive+ // while the parent carries on; the finish event lands after the turn, like a+ // real background run.+ if (/spawn a subagent/i.test(msg.text)) {+ const t: any = {+ id: "agent-1", label: "repo survey", task: "survey the repo layout",+ mode: "read_only", status: "running", created: Date.now() / 1000, icon_seed: 1,+ };+ agentTasks.unshift(t);+ send("agent_task", { kind: "agent_task_started", ...t });+ send("assistant_message", { text: "Spawned a subagent; carrying on." });+ send("turn_done");+ setTimeout(() => {+ t.status = "done";+ t.finished = Date.now() / 1000;+ send("agent_task", { kind: "agent_task_finished", ...t });+ }, 400);+ return;+ }+ // Auto-compaction (OPE-27) + the rail's Context panel in ONE flow, like the+ // real server: the transient `compacting` signal, then the divider marker,+ // then an assistant_message whose fresh `context` carries the compaction+ // stamp. (Two separate handlers once shadowed each other — owner-visible+ // breakage caught 2026-11-07.)+ if (/compact the context/i.test(msg.text)) {+ send("compacting", {});+ setTimeout(() => {+ send("compacted", { text: "Context compacted — earlier turns were summarized" });+ send("assistant_message", {+ text: "Still on it — continuing where I left off.",+ context: {+ ...contextPayload,+ used: 41_000,+ compaction: { created_at: 1724200000, messages: 12, trimmed: false },+ },+ });+ send("turn_done");+ }, 400);+ return;+ }if (/show the report/i.test(msg.text)) {send("assistant_message", {text: "Done — [Security review](artifact:reports/security-review.html)",@@ -869,18 +922,6 @@ export async function mockApi(page: import("@playwright/test").Page) {}, 120);return;}- // Auto-compaction (OPE-27): the server signals `compacting` (the transient- // spinner label), summarizes for a beat, then emits the marker and the turn- // continues normally — the divider must render inline.- if (/compact the context/i.test(msg.text)) {- send("compacting", {});- setTimeout(() => {- send("compacted", { text: "Context compacted — earlier turns were summarized" });- send("assistant_message", { text: "Still on it — continuing where I left off." });- send("turn_done");- }, 400);- return;- }// A turn that dies on a provider error; the follow-up {type:"retry"} recovers.if (/fail the turn/i.test(msg.text)) {send("error", { error: "model unreachable" });@@ -1206,6 +1247,11 @@ export async function mockApi(page: import("@playwright/test").Page) {(projectNames[b.kind] ||= []).unshift({ name: b.name, key: "/Users/u/fleet/ro4d/demo-universe/notes" });return json({ ok: true, kind: b.kind, name: b.name });}+ // Async subagents (OPE-257): the Subagents section's registry view. Mutated by+ // the "spawn a subagent" scripted turn below.+ if (/\/v1\/sessions\/[^/]+\/tasks$/.test(p)) {+ return json({ agents: agentTasks });+ }if (/\/v1\/sessions\/[^/]+\/roots$/.test(p)) {if (m === "POST") {const b = req.postDataJSON();diff --git a/surfaces/gui/e2e/rail-glance.spec.ts b/surfaces/gui/e2e/rail-glance.spec.tsnew file mode 100644index 00000000..1eaf0942--- /dev/null+++ b/surfaces/gui/e2e/rail-glance.spec.ts@@ -0,0 +1,58 @@+// The rail's glance layer: the Environment block names where the session runs, the+// Context section carries its value on the collapsed header (FB-015), and a fresh+// context payload on assistant_message updates it — including the compaction stamp.+import { expect } from "@playwright/test";+import { test } from "./fixtures";++test("environment block names the machine and folder; context reads from `ready`", async ({ page }) => {+ await page.goto("/");++ const env = page.getByTestId("rail-env");+ await expect(env).toContainText("This machine");+ await expect(env).toContainText("Temporary folder");++ // Collapsed header already carries the value: 68k of a 200k window = 34%.+ await expect(page.getByTestId("ctx-summary")).toContainText("34%");++ // Expanded: the proportional breakdown plus the free remainder.+ await page.getByTestId("rail-toggle-context").click();+ const panel = page.getByTestId("ctx-panel");+ await expect(panel).toContainText("68k of 200k");+ await expect(panel).toContainText("System prompt");+ await expect(panel).toContainText("Tools");+ await expect(panel).toContainText("Conversation");+ await expect(panel).toContainText("Free");+});++test("a turn's context payload updates the meter and surfaces the compaction note", async ({ page }) => {+ await page.goto("/");+ await page.getByPlaceholder(/Ask the coworker/).fill("compact the context");+ await page.getByRole("button", { name: "Send" }).click();++ // 41k of 200k after the fold — the header value moved with the turn.+ await expect(page.getByTestId("ctx-summary")).toContainText("21%");+ await page.getByTestId("rail-toggle-context").click();+ await expect(page.getByTestId("ctx-compacted")).toContainText("12");+});++test("a spawned subagent appears in the Subagents section and settles to done", async ({ page }) => {+ await page.goto("/");+ await page.getByPlaceholder(/Ask the coworker/).fill("spawn a subagent");+ await page.getByRole("button", { name: "Send" }).click();++ const head = page.getByTestId("rail-toggle-subagents");+ // The row appears with the start event and settles to done when the background+ // finish event lands (asserting the transient "running" state would race it).+ await expect(head).toContainText("1 done");+ await head.click();+ const list = page.getByTestId("agent-tasks");+ await expect(list).toContainText("repo survey");+});++test("collapsed section headers still answer with a summary value", async ({ page }) => {+ await page.goto("/");+ // Progress reports the live turn while it runs.+ await page.getByPlaceholder(/Ask the coworker/).fill("run a tool");+ await page.getByRole("button", { name: "Send" }).click();+ await expect(page.getByTestId("rail-toggle-progress")).toContainText("Working…");+});diff --git a/surfaces/gui/e2e/team.spec.ts b/surfaces/gui/e2e/team.spec.tsindex 80c59032..5320be0a 100644--- a/surfaces/gui/e2e/team.spec.ts+++ b/surfaces/gui/e2e/team.spec.ts@@ -189,11 +189,12 @@ test("approval creates the team; members live in the drawer, RECENT keeps one enawait page.getByTestId("teamreq-approve").click();await expect(page.getByText(/Team created/)).toBeVisible();- // The drawer grows a collapsed Team section with a member-count chip.+ // The drawer grows a collapsed Team section whose header summary (2026-11-06 rail+ // redesign) leads with attention: one of the three members is waiting.// (Sessions poll every 5s, so allow one full cycle.)const teamToggle = page.getByTestId("rail-toggle-team");await expect(teamToggle).toBeVisible({ timeout: 12_000 });- await expect(teamToggle).toContainText("3");+ await expect(teamToggle).toContainText("1 waiting");await expect(page.getByTestId("team-panel")).toHaveCount(0); // collapsed by default// The lead is the SESSION — Progress yields its slot (the board is the lead'sdiff --git a/surfaces/gui/e2e/union-v15.spec.ts b/surfaces/gui/e2e/union-v15.spec.tsindex 3112e3d9..016be215 100644--- a/surfaces/gui/e2e/union-v15.spec.ts+++ b/surfaces/gui/e2e/union-v15.spec.ts@@ -67,8 +67,9 @@ test("sidebar lists a cloud machine's sessions; Machine grouping shows its groupawait page.getByRole("button", { name: "Group and filter conversations" }).click();await page.getByRole("menu").getByText("Machine", { exact: true }).click();- // UX-048: group headers are the machine name, sentence case, no glyph.- await expect(page.locator("div").filter({ hasText: /^cloud-vm$/ })).toBeVisible();+ // UX-048: group headers are the machine name, sentence case, no glyph. `.first()`+ // because the rail's Environment block (2026-11-06) also names the machine.+ await expect(page.locator("div").filter({ hasText: /^cloud-vm$/ }).first()).toBeVisible();});test("Inbox aggregates a cloud box's parked approval; resolve routes via the proxy", async ({diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex 6f65ed01..8ec5d7cf 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -58,6 +58,7 @@ import type {Item,SessionInfo,SessionUsage,+ ContextInfo,TodoItem,WsEvent,} from "./types";@@ -262,6 +263,11 @@ export function App() {const [preparingSandbox, setPreparingSandbox] = useState<string | null>(null);// OPE-218: which walls this session runs behind, for the header chip. From `ready`.const [sandboxInfo, setSandboxInfo] = useState<SessionSandbox | null>(null);+ // Window occupancy for the rail's Context section (FB-015): from `ready` (so a+ // reopened session has it before any turn) and refreshed by each assistant_message.+ const [contextInfo, setContextInfo] = useState<ContextInfo | null>(null);+ // Async subagents (OPE-257): bumped by agent_task events; the rail refetches its list.+ const [agentTaskKey, setAgentTaskKey] = useState(0);// The server refused to build this session (its sandbox cannot be used) and closed the// socket for good: no reconnect strip, the error notice in the transcript says why.const [sessionRefused, setSessionRefused] = useState(false);@@ -298,6 +304,8 @@ export function App() {const [sessions, setSessions] = useState<SessionInfo[]>([]);const [projects, setProjects] = useState<RecentWorkspace[]>([]);const [sessionId, setSessionId] = useState<string>(newId());+ // Context occupancy is session-owned: drop it on switch, before `ready` refills it.+ useEffect(() => setContextInfo(null), [sessionId]);// Remote homes (UX-045): which joined machine the CURRENT session runs on// (null = This Mac). Fixed at creation via the setup row's runs-on chip;// restored from the session row on select/resume. Routes the session socket@@ -907,9 +915,14 @@ export function App() {// intro screen. Which wall the session runs behind belongs in the header (OPE-207).setPreparingSandbox(null);break;+ case "agent_task":+ // A subagent started/finished/is waiting — the rail refetches the registry.+ setAgentTaskKey((k) => k + 1);+ break;case "ready":setPreparingSandbox(null);setSandboxInfo(d.sandbox || null);+ if (d.context) setContextInfo(d.context);setSessionRefused(false);setConnected(true);if (d.model) setModel(d.model);@@ -964,6 +977,7 @@ export function App() {break;case "assistant_message": {if (d.usage) setUsage((u) => addTurnUsage(u, d.usage));+ if (d.context) setContextInfo(d.context);// The event's reasoning is authoritative (covers background-delivered turns);// the local buffer is the fallback for older servers.const reasoning = d.reasoning || reasoningRef.current;@@ -2622,6 +2636,11 @@ export function App() {scratchPrimary={tempWorkspace || !isProjectScoped(personaOf(agent))}openAccessKey={accessKey}onOpenIntegrations={() => openSettings("connectors")}+ context={contextInfo}+ sessionUsage={usage}+ agentTaskKey={agentTaskKey}+ machineName={curSession?.machine_name}+ machineOffline={!!curSession?.machine_offline}sandbox={sandboxInfo}onSandbox={setSandboxInfo}onOpenSandboxSettings={() => openSettings("sandbox")}diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex a0af6c6f..d04f7bb7 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -623,6 +623,25 @@ export async function getRoots(sessionId: string): Promise<RootInfo[]> {return (await res.json()).roots ?? [];}+// -- async subagents (OPE-257): the Running section's registry view ----------+export interface AgentTaskInfo {+ id: string;+ label: string;+ task: string;+ mode: string; // "read_only" | "inherit"+ status: string; // running | waiting | done | error | canceled+ note?: string;+ created: number;+ finished?: number | null;+ usage?: Record<string, { input: number; output: number; cache_read: number; cache_write: number; turns: number }>;+ icon_seed?: number;+}++export async function getAgentTasks(sessionId: string): Promise<AgentTaskInfo[]> {+ const res = await fetch(`${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/tasks`);+ return (await res.json()).agents ?? [];+}+export async function addRoot(sessionId: string,path: string,diff --git a/surfaces/gui/src/components/AccessSection.tsx b/surfaces/gui/src/components/AccessSection.tsxindex b499147a..94241e39 100644--- a/surfaces/gui/src/components/AccessSection.tsx+++ b/surfaces/gui/src/components/AccessSection.tsx@@ -265,6 +265,12 @@ export function AccessSection({>{summary}</span>+ {/* Recommended-but-unconnected count: the header's one attention signal. */}+ {(conns?.attention ?? 0) > 0 && (+ <span className="rail-summary attention shrink-0" data-testid="access-attention">+ {t("access.summary_attention", { count: conns!.attention })}+ </span>+ )}</button></div>{open && (diff --git a/surfaces/gui/src/components/AgentGlyph.tsx b/surfaces/gui/src/components/AgentGlyph.tsxnew file mode 100644index 00000000..ac44579a--- /dev/null+++ b/surfaces/gui/src/components/AgentGlyph.tsx@@ -0,0 +1,48 @@+// Subagent identity glyphs (OPE-259, owner-approved sheet 2026-11-07): ten animal+// silhouettes × eight cool-color families = 80 stable identities. One color per mark;+// the eyes are punched out (evenodd holes), so the surface shows through and the same+// path works on light and dark. Shape = seed mod 10, family = seed ÷ 10 mod 8 — the+// seed is the task's spawn counter, persisted, so a run keeps its animal forever.+// No warm colors: amber stays the rail's one attention meaning.++const eye = (x: number, y: number, r = 1.1) =>+ `M${x - r} ${y} a${r} ${r} 0 1 0 ${2 * r} 0 a${r} ${r} 0 1 0 ${-2 * r} 0`;++// [name, svg inner markup]+const ANIMALS: [string, string][] = [+ ["cat", `<path fill-rule="evenodd" d="M10 5 C11 4.6 11.8 4.4 12.6 4.5 L15.6 1.6 L16.4 7.2 C17 8.2 17.3 9.6 17.3 11 C17.3 15.2 14 17.8 10 17.8 C6 17.8 2.7 15.2 2.7 11 C2.7 9.6 3 8.2 3.6 7.2 L4.4 1.6 L7.4 4.5 C8.2 4.4 9 4.6 10 5 Z ${eye(7.3, 11)} ${eye(12.7, 11)}"/>`],+ ["puppy", `<g fill-rule="evenodd"><path d="M10 4.2 C13.6 4.2 16 6.9 16 10.7 C16 14.7 13.4 17.4 10 17.4 C6.6 17.4 4 14.7 4 10.7 C4 6.9 6.4 4.2 10 4.2 Z ${eye(7.6, 10.3)} ${eye(12.4, 10.3)}"/><ellipse cx="4.1" cy="8.9" rx="1.95" ry="4.3" transform="rotate(16 4.1 8.9)"/><ellipse cx="15.9" cy="8.9" rx="1.95" ry="4.3" transform="rotate(-16 15.9 8.9)"/></g>`],+ ["bunny", `<path fill-rule="evenodd" d="M6.4 1.2 C8 1.2 8.7 4.2 8.8 7.6 C9.2 7.5 9.6 7.5 10 7.5 C10.4 7.5 10.8 7.5 11.2 7.6 C11.3 4.2 12 1.2 13.6 1.2 C15.3 1.2 15.6 5.2 14.5 8.5 C15.6 9.5 16.2 10.9 16.2 12.4 C16.2 15.6 13.4 17.8 10 17.8 C6.6 17.8 3.8 15.6 3.8 12.4 C3.8 10.9 4.4 9.5 5.5 8.5 C4.4 5.2 4.7 1.2 6.4 1.2 Z ${eye(7.6, 12.4)} ${eye(12.4, 12.4)}"/>`],+ ["fox", `<path fill-rule="evenodd" d="M2.6 2.6 C5 2.8 7 3.6 8.3 4.7 C8.9 4.6 9.4 4.5 10 4.5 C10.6 4.5 11.1 4.6 11.7 4.7 C13 3.6 15 2.8 17.4 2.6 C17.6 5.4 17.2 8 16.4 9.4 C16.4 9.9 16.5 10.3 16.5 10.8 C16.5 15 13.3 17.6 10 17.6 C6.7 17.6 3.5 15 3.5 10.8 C3.5 10.3 3.6 9.9 3.6 9.4 C2.8 8 2.4 5.4 2.6 2.6 Z ${eye(7.2, 10.6)} ${eye(12.8, 10.6)}"/>`],+ ["owl", `<path fill-rule="evenodd" d="M3.4 2.2 L7.2 4 C8.1 3.6 9 3.4 10 3.4 C11 3.4 11.9 3.6 12.8 4 L16.6 2.2 L15.7 6.3 C16.6 7.6 17.1 9.3 17.1 11 C17.1 15.3 14 18 10 18 C6 18 2.9 15.3 2.9 11 C2.9 9.3 3.4 7.6 4.3 6.3 Z ${eye(7.1, 9.8, 1.9)} ${eye(12.9, 9.8, 1.9)}"/><circle cx="7.1" cy="9.8" r="0.85"/><circle cx="12.9" cy="9.8" r="0.85"/>`],+ ["octopus", `<path fill-rule="evenodd" d="M3.6 13 L3.6 10 C3.6 5.8 6.3 3 10 3 C13.7 3 16.4 5.8 16.4 10 L16.4 13 A1.6 1.6 0 0 1 13.2 13 A1.6 1.6 0 0 1 10 13 A1.6 1.6 0 0 1 6.8 13 A1.6 1.6 0 0 1 3.6 13 Z ${eye(7.4, 9.2, 1.15)} ${eye(12.6, 9.2, 1.15)}"/>`],+ ["frog", `<path fill-rule="evenodd" d="M6.3 3.2 A2.9 2.9 0 0 1 9.2 6 C9.5 6 9.7 6 10 6 C10.3 6 10.5 6 10.8 6 A2.9 2.9 0 1 1 15.4 8.3 C16.5 9.4 17.2 10.9 17.2 12.4 C17.2 15.6 14 17.6 10 17.6 C6 17.6 2.8 15.6 2.8 12.4 C2.8 10.9 3.5 9.4 4.6 8.3 A2.9 2.9 0 0 1 6.3 3.2 Z ${eye(6.3, 6.1)} ${eye(13.7, 6.1)}"/>`],+ ["mouse", `<path fill-rule="evenodd" d="M5 2.4 A3.1 3.1 0 0 1 8.1 5.6 C8.7 5.4 9.3 5.3 10 5.3 C10.7 5.3 11.3 5.4 11.9 5.6 A3.1 3.1 0 1 1 15.9 8.2 C16.5 9.2 16.8 10.3 16.8 11.5 C16.8 15.4 13.8 17.8 10 17.8 C6.2 17.8 3.2 15.4 3.2 11.5 C3.2 10.3 3.5 9.2 4.1 8.2 A3.1 3.1 0 0 1 5 2.4 Z ${eye(7.7, 11.2, 1.0)} ${eye(12.3, 11.2, 1.0)}"/>`],+ ["chick", `<path fill-rule="evenodd" d="M10 2.8 C14.2 2.8 17 5.9 17 10.2 C17 14.5 14.2 17.4 10 17.4 C5.8 17.4 3 14.5 3 10.2 C3 5.9 5.8 2.8 10 2.8 Z ${eye(7.5, 8.8, 1.05)} ${eye(12.5, 8.8, 1.05)} M10 11.2 L12 12.8 L10 14.4 L8 12.8 Z"/>`],+ ["whale", `<path fill-rule="evenodd" d="M2.6 12.6 C2.6 7.4 5.8 4.8 9.8 4.8 C13 4.8 15.3 6.6 15.9 9.3 L18.2 7.2 C18.8 9.6 18 11.8 15.8 12.6 C14.8 15.6 12.6 17 9.8 17 C5.8 17 2.6 15.6 2.6 12.6 Z ${eye(6.6, 10.4, 1.0)}"/>`],+];++export const GLYPH_FAMILIES = 8;+export const GLYPH_SHAPES = ANIMALS.length;++export function glyphName(seed: number): string {+ return ANIMALS[Math.abs(seed) % GLYPH_SHAPES][0];+}++export function AgentGlyph({ seed, size = 18 }: { seed: number; size?: number }) {+ const s = Math.abs(seed);+ const [name, body] = ANIMALS[s % GLYPH_SHAPES];+ const family = Math.floor(s / GLYPH_SHAPES) % GLYPH_FAMILIES;+ return (+ <svg+ className={`aglyph aglyph-f${family}`}+ data-glyph={name}+ width={size}+ height={size}+ viewBox="0 0 20 20"+ fill="currentColor"+ aria-hidden+ dangerouslySetInnerHTML={{ __html: body }}+ />+ );+}diff --git a/surfaces/gui/src/components/ConnectorMessageCard.tsx b/surfaces/gui/src/components/ConnectorMessageCard.tsxindex 46d2af9b..e6a2c2ed 100644--- a/surfaces/gui/src/components/ConnectorMessageCard.tsx+++ b/surfaces/gui/src/components/ConnectorMessageCard.tsx@@ -20,7 +20,7 @@ import { ConnectorBadge, hexToRgba, NEUTRAL } from "../connectors/ConnectorIcon"import { resolveConnector } from "../connectors/registry";/** Coarse relative time from epoch seconds: "just now" / "5m ago" / "2h ago" / "3d ago" / a date. */-function relativeTime(tsSeconds: number, t: (key: string, opts?: any) => string): string {+export function relativeTime(tsSeconds: number, t: (key: string, opts?: any) => string): string {if (!tsSeconds || !isFinite(tsSeconds)) return "";const then = tsSeconds * 1000;const diff = Date.now() - then;diff --git a/surfaces/gui/src/components/RailContext.tsx b/surfaces/gui/src/components/RailContext.tsxnew file mode 100644index 00000000..bafc6216--- /dev/null+++ b/surfaces/gui/src/components/RailContext.tsx@@ -0,0 +1,100 @@+import { useTranslation } from "react-i18next";+import type { ContextInfo, SessionUsage } from "../types";+import { formatTokens } from "../usage";++// The Context section (FB-015): how full the model's window is and what fills it.+// The composer's ring (UX-048) stays the glanceable signal; this is the expanded truth.+// The category split is a server-side estimate, so segments are drawn as PROPORTION of+// the reported total, never presented as an exact ledger (the body says "estimated").++export function contextPct(info: ContextInfo): number | null {+ if (!info.window || info.window <= 0) return null;+ return Math.min(100, Math.round((info.used / info.window) * 100));+}++// Collapsed-header value: "34%" plus a micro meter (or the token count when the+// model's window is unknown — same contract as the composer ring).+export function ContextSummary({ info }: { info: ContextInfo }) {+ const pct = contextPct(info);+ if (pct === null) return <>{formatTokens(info.used)}</>;+ return (+ <span className="ctx-sum" data-testid="ctx-summary">+ <span>{pct}%</span>+ <span className={"ctx-meter" + (pct >= 80 ? " warn" : "")}>+ <span className="ctx-meter-fill" style={{ width: `${pct}%` }} />+ </span>+ </span>+ );+}++const CATS = ["system", "tools", "messages"] as const;++export function ContextPanel({ info, usage }: { info: ContextInfo; usage?: SessionUsage }) {+ const { t } = useTranslation();+ const pct = contextPct(info);+ // Scale the estimated categories to the reported total so the bar never lies about+ // the whole even when the parts are approximate.+ const estSum = CATS.reduce((n, c) => n + (info.breakdown[c] || 0), 0) || 1;+ const share = (c: (typeof CATS)[number]) =>+ Math.round(((info.breakdown[c] || 0) / estSum) * info.used);+ const models = Object.entries(usage?.byModel || {});+ return (+ <div className="ctx-panel" data-testid="ctx-panel">+ <div className="ctx-head">+ <span className="ctx-used">+ {info.window+ ? t("rail.ctx_used", { used: formatTokens(info.used), window: formatTokens(info.window) })+ : t("rail.ctx_used_no_window", { used: formatTokens(info.used) })}+ </span>+ {pct !== null && <span className="ctx-pct">{t("rail.ctx_free", { pct: 100 - pct })}</span>}+ </div>+ {info.window ? (+ <div className="ctx-bar" role="img" aria-label={t("rail.ctx_bar_label")}>+ {CATS.map((c) => (+ <span+ key={c}+ className={`ctx-seg ctx-seg-${c}`}+ style={{ width: `${Math.min(100, (share(c) / info.window!) * 100)}%` }}+ />+ ))}+ </div>+ ) : null}+ <div className="ctx-rows">+ {CATS.map((c) => (+ <div className="ctx-row" key={c}>+ <span className={`ctx-dot ctx-seg-${c}`} />+ <span className="ctx-label">{t(`rail.ctx_${c}`)}</span>+ <span className="ctx-val">{t("rail.ctx_approx", { tokens: formatTokens(share(c)) })}</span>+ </div>+ ))}+ {info.window ? (+ <div className="ctx-row">+ <span className="ctx-dot ctx-seg-free" />+ <span className="ctx-label">{t("rail.ctx_free_label")}</span>+ <span className="ctx-val">{formatTokens(Math.max(0, info.window - info.used))}</span>+ </div>+ ) : null}+ </div>+ {models.length > 0 && (+ <div className="ctx-models">+ {models.map(([model, u]) => (+ <div className="ctx-row" key={model}>+ <span className="ctx-label ctx-model" title={model}>{model}</span>+ <span className="ctx-val">+ {t("rail.ctx_model_io", {+ in: formatTokens(u.input + u.cache_read + u.cache_write),+ out: formatTokens(u.output),+ })}+ </span>+ </div>+ ))}+ </div>+ )}+ {info.compaction && (+ <div className="ctx-note" data-testid="ctx-compacted">+ {t("rail.ctx_compacted", { count: info.compaction.messages || 0 })}+ </div>+ )}+ </div>+ );+}diff --git a/surfaces/gui/src/components/RightRail.glance.test.tsx b/surfaces/gui/src/components/RightRail.glance.test.tsxnew file mode 100644index 00000000..cb4f7cb8--- /dev/null+++ b/surfaces/gui/src/components/RightRail.glance.test.tsx@@ -0,0 +1,164 @@+// The rail's glance layer: the Environment block, the Context section, and the+// right-aligned header summaries that make collapsed sections still answer+// "what's in here?" (seventeenth-pass rule: nothing shouts louder than this).+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ContextInfo } from "../types";+import { RightRail } from "./RightRail";++vi.mock("../api", () => ({+ getAgentTasks: vi.fn().mockResolvedValue([]),+ getArtifacts: vi.fn().mockResolvedValue([]),+ getJournalCases: vi.fn().mockResolvedValue([]),+ getRoots: vi.fn().mockResolvedValue([]),+ readArtifact: vi.fn(),+ revealArtifact: vi.fn(),+}));++vi.mock("./AccessSection", () => ({ AccessSection: () => null }));++const baseProps = {+ active: true,+ sessionId: "session-a",+ refreshKey: 0,+ toolNames: [],+ todo: [],+ running: false,+};++const ctx = (over: Partial<ContextInfo> = {}): ContextInfo => ({+ window: 200_000,+ used: 68_000,+ estimated: false,+ breakdown: { system: 10_000, tools: 8_000, messages: 50_000 },+ ...over,+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("environment block", () => {+ it("names the machine, the folder with its branch, and the sandbox state", () => {+ render(+ <RightRail+ {...baseProps}+ machineName="ro4d"+ workspace="/Users/x/code/openworker"+ branch="rp/right-panel"+ sandbox={{ state: "sandboxed", provider: "openshell", network: "", sites: [], session_sites: [], folders: [], logins: [], started: true } as any}+ />,+ );+ const env = screen.getByTestId("rail-env");+ expect(env.textContent).toContain("ro4d");+ expect(env.textContent).toContain("openworker");+ expect(env.textContent).toContain("rp/right-panel");+ expect(screen.getByTestId("rail-env-sandbox").textContent).toContain("openshell");+ });++ it("falls back to this machine + temporary folder, and hides a sandbox that is off", () => {+ render(<RightRail {...baseProps} scratchPrimary sandbox={{ state: "off" } as any} />);+ const env = screen.getByTestId("rail-env");+ expect(env.textContent).toContain("This machine");+ expect(env.textContent).toContain("Temporary folder");+ expect(screen.queryByTestId("rail-env-sandbox")).toBeNull();+ });+});++describe("context section", () => {+ it("shows the percentage on the collapsed header and the breakdown when expanded", () => {+ render(<RightRail {...baseProps} context={ctx()} />);+ expect(screen.getByTestId("ctx-summary").textContent).toContain("34%");+ fireEvent.click(screen.getByTestId("rail-toggle-context"));+ const panel = screen.getByTestId("ctx-panel");+ expect(panel.textContent).toContain("System prompt");+ expect(panel.textContent).toContain("Tools");+ expect(panel.textContent).toContain("Conversation");+ expect(panel.textContent).toContain("68k of 200k");+ });++ it("says the window is unknown instead of inventing a percentage", () => {+ render(<RightRail {...baseProps} context={ctx({ window: null })} />);+ expect(screen.queryByTestId("ctx-summary")).toBeNull(); // token count, no meter+ fireEvent.click(screen.getByTestId("rail-toggle-context"));+ expect(screen.getByTestId("ctx-panel").textContent).toContain("window unknown");+ });++ it("notes a compaction once one happened", () => {+ render(<RightRail {...baseProps} context={ctx({ compaction: { messages: 12 } })} />);+ fireEvent.click(screen.getByTestId("rail-toggle-context"));+ expect(screen.getByTestId("ctx-compacted").textContent).toContain("12");+ });++ it("renders no section at all before the server has reported", () => {+ render(<RightRail {...baseProps} />);+ expect(screen.queryByTestId("rail-toggle-context")).toBeNull();+ });+});++describe("subagents section", () => {+ it("lists runs, amber while one waits on an approval, ages for the done", async () => {+ const { getAgentTasks } = await import("../api");+ (getAgentTasks as any).mockResolvedValue([+ { id: "agent-1", label: "repo map", task: "t", mode: "read_only", status: "done", created: 1, finished: Date.now() / 1000 - 7200, icon_seed: 1 },+ { id: "agent-2", label: "marker run", task: "t", mode: "inherit", status: "waiting", created: 2, icon_seed: 2 },+ ]);+ render(<RightRail {...baseProps} />);+ const head = await screen.findByTestId("rail-toggle-subagents");+ expect(head.textContent).toContain("1 waiting");+ expect(head.textContent).toContain("1 done");+ expect(head.querySelector(".rail-summary.attention")).not.toBeNull();+ // Header chips: one animal glyph per run, derived from the stable seed.+ expect(head.querySelectorAll(".agent-chips svg[data-glyph]").length).toBe(2);+ fireEvent.click(head);+ const list = screen.getByTestId("agent-tasks");+ expect(list.querySelector('svg[data-glyph="puppy"]')).not.toBeNull(); // seed 1+ expect(list.querySelector('svg[data-glyph="bunny"]')).not.toBeNull(); // seed 2+ expect(list.textContent).toContain("repo map");+ expect(list.textContent).toContain("marker run");+ expect(list.textContent).toContain("waiting on approval");+ (getAgentTasks as any).mockResolvedValue([]);+ });+});++describe("header summaries", () => {+ it("progress says how much of the plan is done while collapsed", () => {+ render(+ <RightRail+ {...baseProps}+ todo={[+ { content: "a", status: "done" },+ { content: "b", status: "done" },+ { content: "c", status: "pending" },+ ]}+ />,+ );+ const head = screen.getByTestId("rail-toggle-progress");+ expect(head.textContent).toContain("2 of 3 done");+ });++ it("progress says it is working during a live turn", () => {+ render(<RightRail {...baseProps} running />);+ expect(screen.getByTestId("rail-toggle-progress").textContent).toContain("Working…");+ });++ it("the board summary turns to attention counts when items are blocked", () => {+ render(+ <RightRail+ {...baseProps}+ board={{+ space: "s",+ name: "Board",+ items: [+ { id: 1, state: "blocked" } as any,+ { id: 2, state: "open" } as any,+ ],+ }}+ />,+ );+ const head = screen.getByTestId("rail-toggle-board");+ expect(head.textContent).toContain("1 needs attention");+ expect(head.querySelector(".rail-summary.attention")).not.toBeNull();+ });+});diff --git a/surfaces/gui/src/components/RightRail.requests.test.tsx b/surfaces/gui/src/components/RightRail.requests.test.tsxindex 55a869c0..649436bc 100644--- a/surfaces/gui/src/components/RightRail.requests.test.tsx+++ b/surfaces/gui/src/components/RightRail.requests.test.tsx@@ -6,6 +6,7 @@ import { getArtifacts, readArtifact } from "../api";import { RightRail } from "./RightRail";vi.mock("../api", () => ({+ getAgentTasks: vi.fn().mockResolvedValue([]),getArtifacts: vi.fn(),getJournalCases: vi.fn().mockResolvedValue([]),getRoots: vi.fn().mockResolvedValue([]),diff --git a/surfaces/gui/src/components/RightRail.tsx b/surfaces/gui/src/components/RightRail.tsxindex 1154ec50..2aa004fe 100644--- a/surfaces/gui/src/components/RightRail.tsx+++ b/surfaces/gui/src/components/RightRail.tsx@@ -4,19 +4,24 @@ import { useTranslation } from "react-i18next";// Emits the asset URL only; the worker itself loads lazily with the pdfjs chunk.import pdfWorkerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";import {+ getAgentTasks,getArtifacts,getJournalCases,getRoots,readArtifact,revealArtifact,+ type AgentTaskInfo,type ArtifactContent,type ArtifactInfo,type Board,type JournalCase,type RootInfo,} from "../api";-import type { SessionInfo, TodoItem } from "../types";+import { relativeTime } from "./ConnectorMessageCard";+import { AgentGlyph } from "./AgentGlyph";+import type { ContextInfo, SessionInfo, TodoItem } from "../types";import { AccessSection } from "./AccessSection";+import { ContextPanel, ContextSummary } from "./RailContext";import { BoardSection } from "./BoardPanel";import { TeamRail } from "./TeamRail";import type { TeamSummary } from "../teamView";@@ -25,8 +30,9 @@ import type { WorkerFilter } from "../teamRoster";import { Icon } from "./Icon";import type { SessionUsage } from "../types";import { Markdown, OPEN_ARTIFACT_EVENT } from "./Markdown";+// (ContextInfo/SessionUsage power the Context section; see RailContext.tsx.)-type Panel = "progress" | "artifacts" | "board" | "journal" | "team" | "files";+type Panel = "context" | "progress" | "agents" | "artifacts" | "board" | "journal" | "team" | "files";// Quiet file-type icons for the artifact list (the colored kind pills read as noisy).function kindIcon(kind: string): "file" | "fileCode" | "image" | "table" {@@ -70,6 +76,15 @@ interface Props {scratchPrimary?: boolean;openAccessKey?: number;onOpenIntegrations?: () => void;+ // FB-015: window occupancy for the Context section (from `ready`/assistant_message).+ context?: ContextInfo | null;+ // Per-model token totals for the Context section's model rows.+ sessionUsage?: SessionUsage;+ // Bumped by agent_task events; the Subagents section refetches its registry.+ agentTaskKey?: number;+ // Environment block: where this session runs. Absent machineName = this machine.+ machineName?: string;+ machineOffline?: boolean;// OPE-219: the session's sandbox, for the Access section's Sites group.sandbox?: SessionSandbox | null;onSandbox?: (next: SessionSandbox) => void;@@ -115,6 +130,11 @@ export function RightRail({scratchPrimary,openAccessKey = 0,onOpenIntegrations,+ context = null,+ sessionUsage,+ agentTaskKey = 0,+ machineName,+ machineOffline = false,sandbox = null,onSandbox,onOpenSandboxSettings,@@ -139,7 +159,9 @@ export function RightRail({// chip is the maximum signal. One exception survives (solo sessions only): Progress// still auto-opens the first time a live turn has todos.const [open, setOpen] = useState<Record<Panel, boolean>>({+ context: false,progress: false,+ agents: false,artifacts: false,board: false,journal: false,@@ -230,6 +252,14 @@ export function RightRail({getRoots(sessionId).then(setRootDirs).catch(() => setRootDirs([]));}, [active, sessionId, refreshKey]);+ // Async subagents (OPE-257): the registry view, refetched on every agent_task event.+ const [agentTasks, setAgentTasks] = useState<AgentTaskInfo[]>([]);+ useEffect(() => setAgentTasks([]), [sessionId]);+ useEffect(() => {+ if (!active) return;+ getAgentTasks(sessionId).then(setAgentTasks).catch(() => setAgentTasks([]));+ }, [active, sessionId, refreshKey, agentTaskKey]);+// Journal cases surface only when a board exists — same visibility rule as the// Board section, so plain sessions carry zero team chrome.useEffect(() => {@@ -343,20 +373,163 @@ export function RightRail({/>) : (<>+ {/* Environment: where this session runs — machine, folder+branch, sandbox.+ Identity at a glance, not config: Access stays the config surface (§32). */}+ <div className="rail-env" data-testid="rail-env">+ <div className="rail-env-row">+ <Icon name="monitor" size={15} />+ <span className="rail-env-main">{machineName || t("rail.env_this_machine")}</span>+ {machineOffline && <span className="rail-env-tag">{t("rail.env_offline")}</span>}+ </div>+ <div className="rail-env-row" title={scratchPrimary ? undefined : workspace}>+ <Icon name="folder" size={15} />+ <span className="rail-env-main">+ {scratchPrimary || !workspace+ ? t("root.temporary_space")+ : workspace.split("/").pop() || workspace}+ </span>+ {!scratchPrimary && branch && (+ <span className="rail-env-sub">+ <Icon name="branch" size={12} /> {branch}+ </span>+ )}+ </div>+ {sandbox && sandbox.state !== "off" && (+ <button+ className="rail-env-row rail-env-btn"+ data-testid="rail-env-sandbox"+ onClick={onOpenSandboxSettings}+ title={t("rail.env_sandbox_open")}+ >+ <Icon name="shield" size={15} />+ <span className="rail-env-main">+ {sandbox.state !== "sandboxed"+ ? t("rail.env_not_sandboxed")+ : sandbox.provider+ ? t("rail.env_sandboxed", { provider: sandbox.provider })+ : t("rail.env_sandboxed_plain")}+ </span>+ <span className={"rail-env-dot " + (sandbox.state === "sandboxed" ? "ok" : "warn")} />+ </button>+ )}+ </div>++ {/* Context (FB-015): how full the window is. The header carries the value;+ the composer's ring (UX-048) stays the always-on glance. */}+ {context && (+ <RailSection+ title={t("rail.context_title")}+ summary={<ContextSummary info={context} />}+ open={open.context}+ onToggle={() => setOpen({ ...open, context: !open.context })}+ >+ <ContextPanel info={context} usage={sessionUsage} />+ </RailSection>+ )}+{/* Leads carry no Progress panel — the board IS the lead's progress surface. */}{!isLead && (- <RailSection title={t("rail.progress_title")} open={open.progress} onToggle={() => setOpen({ ...open, progress: !open.progress })}>+ <RailSection+ title={t("rail.progress_title")}+ summary={+ running+ ? t("rail.sum_working")+ : todo.length+ ? t("rail.sum_done_of", { done: todo.filter((i) => i.status === "done").length, total: todo.length })+ : undefined+ }+ open={open.progress}+ onToggle={() => setOpen({ ...open, progress: !open.progress })}+ ><ProgressSummary running={running} toolNames={toolNames} todo={todo} /></RailSection>)}+ {/* Async subagents (OPE-257): active runs + done history, zero chrome when+ none ever ran. Amber only while one waits on an approval. */}+ {agentTasks.length > 0 && (() => {+ const act = agentTasks.filter((a) => a.status === "running").length;+ const waiting = agentTasks.filter((a) => a.status === "waiting").length;+ const rest = agentTasks.length - act - waiting;+ const parts = [+ waiting ? t("rail.agents_waiting", { count: waiting }) : "",+ act ? t("rail.agents_running", { count: act }) : "",+ rest ? t("rail.agents_done", { count: rest }) : "",+ ].filter(Boolean);+ // Owner ruling 2026-11-07: ten or fewer = a row each; past ten the LIVE+ // runs keep full rows (those you need to read) and only the done history+ // compresses into the glyph grid, labels on hover.+ const live = agentTasks.filter((a) => a.status === "running" || a.status === "waiting");+ const compress = agentTasks.length > 10;+ const rows = compress ? live : agentTasks;+ const grid = compress ? agentTasks.filter((a) => !live.includes(a)) : [];+ const statusLine = (a: AgentTaskInfo) =>+ a.status === "waiting"+ ? t("rail.agent_waiting")+ : a.status === "running"+ ? t("rail.agent_running")+ : a.status === "error"+ ? t("rail.agent_error")+ : a.status === "canceled"+ ? t("rail.agent_canceled")+ : relativeTime(a.finished || a.created, t);+ return (+ <RailSection+ title={t("rail.agents_title")}+ summary={+ <>+ <span className="agent-chips" data-testid="agent-chips">+ {agentTasks.slice(0, 5).map((a) => (+ <AgentGlyph key={a.id} seed={a.icon_seed ?? 0} size={14} />+ ))}+ </span>+ {parts.join(" · ")}+ </>+ }+ summaryAttention={waiting > 0}+ open={open.agents}+ onToggle={() => setOpen({ ...open, agents: !open.agents })}+ >+ <div className="agent-list" data-testid="agent-tasks">+ {rows.map((a) => (+ <div className="agent-row" key={a.id} title={a.task}>+ <AgentGlyph seed={a.icon_seed ?? 0} size={18} />+ <span className="agent-label">+ <span className="agent-name">{a.label}</span>+ <span className={"agent-sub" + (a.status === "waiting" ? " attention" : "")}>+ {statusLine(a)}+ </span>+ </span>+ <span className={"agent-dot " + a.status} />+ </div>+ ))}+ {grid.length > 0 && (+ <div className="agent-grid" data-testid="agent-grid">+ {grid.map((a) => (+ <span key={a.id} className="agent-grid-item" title={`${a.label} · ${statusLine(a)}`}>+ <AgentGlyph seed={a.icon_seed ?? 0} size={17} />+ </span>+ ))}+ </div>+ )}+ </div>+ </RailSection>+ );+ })()}+{/* Standalone boards have no team icon. Keep their existing entry point;staffed leads use the quick look and Team View instead. */}- {!isLead && board?.space && <RailSection title={t("rail.board_title")} open={open.board}- onToggle={() => setOpen({ ...open, board: !open.board })}- action={<button className="rail-mini-btn" data-testid="board-expand" onClick={onExpandBoard} title={t("rail.board_expand")}><Icon name="panelOpen" size={13} /></button>}>- <BoardSection board={board} onExpand={() => onExpandBoard?.()} onOpenItem={onOpenBoardItem} />- </RailSection>}+ {!isLead && board?.space && (() => {+ const attention = board.items.filter((i) => i.state === "blocked" || i.state === "review").length;+ const active = board.items.filter((i) => i.state === "open" || i.state === "in_progress").length;+ return <RailSection title={t("rail.board_title")} open={open.board}+ summary={attention ? t("rail.sum_board_attention", { count: attention }) : active ? t("rail.sum_board_open", { count: active }) : undefined}+ summaryAttention={attention > 0}+ onToggle={() => setOpen({ ...open, board: !open.board })}+ action={<button className="rail-mini-btn" data-testid="board-expand" onClick={onExpandBoard} title={t("rail.board_expand")}><Icon name="panelOpen" size={13} /></button>}>+ <BoardSection board={board} onExpand={() => onExpandBoard?.()} onOpenItem={onOpenBoardItem} />+ </RailSection>;+ })()}{/* The team panel: who's working, on what, and the way into their sessions —the altitude-3 escape hatch, moved here from the sidebar (RECENT keeps ONE@@ -369,7 +542,7 @@ export function RightRail({{showArtifacts && (<RailSectiontitle={t("rail.artifacts_title")}- count={artifacts.length ? String(artifacts.length) : undefined}+ summary={artifacts.length ? String(artifacts.length) : undefined}open={open.artifacts}onToggle={() => setOpen({ ...open, artifacts: !open.artifacts })}action={@@ -414,7 +587,7 @@ export function RightRail({{board?.space && journal.length > 0 && (<RailSectiontitle={t("rail.journal_title")}- count={String(journal.length)}+ summary={String(journal.length)}open={open.journal}onToggle={() => setOpen({ ...open, journal: !open.journal })}>@@ -435,7 +608,7 @@ export function RightRail({{rootDirs.length > 0 && (<RailSectiontitle={t("rail.crumb_files")}- count={String(rootDirs.length)}+ summary={String(rootDirs.length)}open={open.files}onToggle={() => setOpen({ ...open, files: !open.files })}>@@ -540,18 +713,19 @@ function RailSection({onToggle,children,action,- count,- countAttention,+ summary,+ summaryAttention,}: {title: string;open: boolean;onToggle: () => void;children: ReactNode;action?: ReactNode;- // The header's maximum signal: a small count chip; amber when it carries attention- // states (blocked/review). Panels never shout louder than this.- count?: string;- countAttention?: boolean;+ // The header's maximum signal: a right-aligned, muted summary value — the collapsed+ // header still answers "what's in here?". Amber only for attention states+ // (blocked/review). Panels never shout louder than this.+ summary?: ReactNode;+ summaryAttention?: boolean;}) {return (<section className="rail-section">@@ -563,8 +737,8 @@ function RailSection({><Icon name={open ? "chevronDown" : "chevronRight"} size={14} className="rail-chev" /><span>{title}</span>- {count && (- <span className={"rail-count" + (countAttention ? " attention" : "")}>{count}</span>+ {summary != null && (+ <span className={"rail-summary" + (summaryAttention ? " attention" : "")}>{summary}</span>)}</button>{action}diff --git a/surfaces/gui/src/components/TeamRail.tsx b/surfaces/gui/src/components/TeamRail.tsxindex 5ab91c97..4cef3205 100644--- a/surfaces/gui/src/components/TeamRail.tsx+++ b/surfaces/gui/src/components/TeamRail.tsx@@ -122,7 +122,14 @@ export function TeamRail({className="rail-chev"/><span>{t("rail.team_title")}</span>- <span className="team-roster-count">{entries.length}</span>+ {/* Header summary, like every other section: attention first, else activity. */}+ <span className={"rail-summary" + (waiting.length ? " attention" : "")}>+ {waiting.length+ ? t("rail.sum_team_waiting", { count: waiting.length })+ : entries.filter((w) => w.working).length+ ? t("rail.sum_team_working", { count: entries.filter((w) => w.working).length })+ : String(entries.length)}+ </span></button><div className="team-rail-actions"><buttondiff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 595455f0..bdfbdfd4 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -323,6 +323,46 @@},"rail": {"progress_title": "Progress",+ "context_title": "Context",+ "env_this_machine": "This machine",+ "env_offline": "offline",+ "env_sandboxed": "Sandboxed · {{provider}}",+ "env_sandboxed_plain": "Sandboxed",+ "env_not_sandboxed": "Not sandboxed",+ "env_sandbox_open": "Open sandbox settings",+ "sum_working": "Working…",+ "sum_done_of": "{{done}} of {{total}} done",+ "sum_board_attention_one": "{{count}} needs attention",+ "sum_board_attention_other": "{{count}} need attention",+ "sum_board_open_one": "{{count}} open",+ "sum_board_open_other": "{{count}} open",+ "sum_team_waiting_one": "{{count}} waiting",+ "sum_team_waiting_other": "{{count}} waiting",+ "sum_team_working_one": "{{count}} working",+ "sum_team_working_other": "{{count}} working",+ "ctx_used": "{{used}} of {{window}}",+ "ctx_used_no_window": "{{used}} in context · window unknown",+ "ctx_free": "{{pct}}% free",+ "ctx_bar_label": "What fills the context window",+ "ctx_system": "System prompt",+ "ctx_tools": "Tools",+ "ctx_messages": "Conversation",+ "ctx_free_label": "Free",+ "ctx_approx": "~{{tokens}}",+ "ctx_model_io": "{{in}} in · {{out}} out",+ "ctx_compacted_one": "Compacted — {{count}} earlier message summarized",+ "ctx_compacted_other": "Compacted — {{count}} earlier messages summarized",+ "agents_title": "Subagents",+ "agents_running_one": "{{count}} running",+ "agents_running_other": "{{count}} running",+ "agents_waiting_one": "{{count}} waiting",+ "agents_waiting_other": "{{count}} waiting",+ "agents_done_one": "{{count}} done",+ "agents_done_other": "{{count}} done",+ "agent_running": "running",+ "agent_waiting": "waiting on approval",+ "agent_error": "failed",+ "agent_canceled": "stopped","artifacts_title": "Artifacts","artifacts_empty": "No previewable files yet.","open": "Open",@@ -840,6 +880,8 @@"channel_add_error": "Couldn't add that channel.","summary_folder_count_one": "{{count}} folder","summary_folder_count_other": "{{count}} folders",+ "summary_attention_one": "{{count}} to set up",+ "summary_attention_other": "{{count}} to set up","sites": {"title": "Sites","session_only": "Session only",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 143d652f..9e2abb1f 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -316,6 +316,38 @@},"rail": {"progress_title": "进度",+ "context_title": "上下文",+ "env_this_machine": "本机",+ "env_offline": "离线",+ "env_sandboxed": "沙盒中 · {{provider}}",+ "env_sandboxed_plain": "沙盒中",+ "env_not_sandboxed": "未启用沙盒",+ "env_sandbox_open": "打开沙盒设置",+ "sum_working": "处理中…",+ "sum_done_of": "已完成 {{done}}/{{total}}",+ "sum_board_attention_other": "{{count}} 项需关注",+ "sum_board_open_other": "{{count}} 项进行中",+ "sum_team_waiting_other": "{{count}} 人等待中",+ "sum_team_working_other": "{{count}} 人工作中",+ "ctx_used": "{{used}} / {{window}}",+ "ctx_used_no_window": "上下文中 {{used}} · 窗口大小未知",+ "ctx_free": "剩余 {{pct}}%",+ "ctx_bar_label": "上下文窗口的构成",+ "ctx_system": "系统提示",+ "ctx_tools": "工具",+ "ctx_messages": "对话",+ "ctx_free_label": "可用",+ "ctx_approx": "约 {{tokens}}",+ "ctx_model_io": "输入 {{in}} · 输出 {{out}}",+ "ctx_compacted_other": "已压缩 — {{count}} 条较早消息已被摘要",+ "agents_title": "子智能体",+ "agents_running_other": "{{count}} 个运行中",+ "agents_waiting_other": "{{count}} 个等待中",+ "agents_done_other": "{{count}} 个已完成",+ "agent_running": "运行中",+ "agent_waiting": "等待批准",+ "agent_error": "失败",+ "agent_canceled": "已停止","artifacts_title": "产出文件","artifacts_empty": "还没有可预览的文件。","open": "打开",@@ -824,6 +856,7 @@"choose_location": "选择位置","channel_add_error": "无法添加该频道。","summary_folder_count_other": "{{count}} 个文件夹",+ "summary_attention_other": "{{count}} 项待设置","sites": {"title": "网站","session_only": "仅本次会话",diff --git a/surfaces/gui/src/styles.css b/surfaces/gui/src/styles.cssindex e89ed5d5..0e7f47be 100644--- a/surfaces/gui/src/styles.css+++ b/surfaces/gui/src/styles.css@@ -723,17 +723,91 @@ button.btn.danger { color: var(--accent); }.main.rail-open:has(.right-rail.artifact-mode) .main-chat { margin-right: var(--artifact-rail-w); }.main.rail-open:has(.right-rail.artifact-mode) .main-topbar { right: var(--artifact-rail-w); }.artifact-head { display: flex; justify-content: space-between; gap: 14px; align-items: center; }-.rail-section { border-bottom: 1px solid var(--line); padding: 11px 0; }+.rail-section { border-bottom: 1px solid var(--line); padding: 14px 0; }.rail-section-head { display: flex; justify-content: space-between; gap: 8px; align-items: center; min-height: 24px; }.rail-section-toggle { flex: 1; display: flex; gap: 8px; align-items: center; cursor: pointer; font: inherit; font-size: var(--fs-ui); font-weight: 600; color: var(--ink); user-select: none; border: 0; background: transparent; padding: 0; text-align: left; }.rail-chev { color: var(--faint); flex: none; }.rail-mini-btn { width: 24px; height: 24px; display: grid; place-items: center; color: var(--muted); border: 0; border-radius: 7px; background: transparent; cursor: pointer; }.rail-mini-btn:hover { color: var(--ink); background: var(--chrome-hover); }-.rail-section-body { padding-top: 10px; }-/* Seventeenth pass: a section header's maximum signal — a small count chip, amber only- when it carries attention states (blocked/review). */-.rail-count { margin-left: auto; font-size: var(--fs-label); font-weight: 500; color: var(--muted); background: var(--paper); border: 1px solid var(--line); border-radius: 999px; padding: 1px 7px; flex: none; }-.rail-count.attention { background: var(--warn-soft); border-color: transparent; color: var(--warn-ink); }+/* Header actions are quiet until the head is hovered or focused — the summary value is+ the resting signal, not a button cluster. */+.rail-section-head .rail-mini-btn { opacity: 0; transition: opacity 0.12s ease; }+.rail-section-head:hover .rail-mini-btn,+.rail-section-head:focus-within .rail-mini-btn { opacity: 1; }+.rail-section-body { padding-top: 12px; }+/* A section header's maximum signal: the right-aligned, muted summary value — the+ collapsed header still answers "what's in here?". Amber only for attention states+ (blocked/review); nothing in the rail shouts louder than this. */+.rail-summary { margin-left: auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-label); font-weight: 400; color: var(--muted); }+.rail-summary.attention { color: var(--warn-ink); }+/* Environment: where this session runs — identity at a glance above the sections. */+.rail-env { display: flex; flex-direction: column; gap: 9px; padding: 2px 0 16px; border-bottom: 1px solid var(--line); }+.rail-env-row { display: flex; gap: 10px; align-items: center; min-height: 20px; color: var(--muted); font-size: var(--fs-ui); }+.rail-env-main { color: var(--ink); font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.rail-env-sub { display: inline-flex; gap: 4px; align-items: center; color: var(--faint); font-size: var(--fs-label); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.rail-env-tag { font-size: var(--fs-label); color: var(--warn-ink); }+.rail-env-btn { border: 0; background: transparent; padding: 0; cursor: pointer; font: inherit; text-align: left; border-radius: 6px; }+.rail-env-btn:hover .rail-env-main { text-decoration: underline; text-decoration-color: var(--line-strong); text-underline-offset: 3px; }+.rail-env-dot { width: 7px; height: 7px; border-radius: 999px; margin-left: auto; flex: none; }+.rail-env-dot.ok { background: var(--ok-ink); }+.rail-env-dot.warn { background: var(--warn-ink); }+/* Context section (FB-015): the collapsed header carries % + a micro meter; the body is+ the proportional breakdown. Quiet grays — color never means category, only attention. */+.ctx-sum { display: inline-flex; gap: 7px; align-items: center; }+.ctx-meter { width: 40px; height: 4px; border-radius: 999px; background: var(--paper); overflow: hidden; flex: none; }+.ctx-meter-fill { display: block; height: 100%; border-radius: 999px; background: var(--muted); }+.ctx-meter.warn .ctx-meter-fill { background: var(--warn-ink); }+.ctx-panel { display: flex; flex-direction: column; gap: 10px; }+.ctx-head { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; }+.ctx-used { font-size: var(--fs-ui); font-weight: 550; color: var(--ink); }+.ctx-pct { font-size: var(--fs-label); color: var(--faint); }+.ctx-bar { display: flex; height: 6px; border-radius: 999px; background: var(--paper); overflow: hidden; }+.ctx-seg { display: block; height: 100%; }+.ctx-seg-system { background: var(--ink); opacity: 0.55; }+.ctx-seg-tools { background: var(--ink); opacity: 0.32; }+.ctx-seg-messages { background: var(--ink); opacity: 0.16; }+.ctx-dot.ctx-seg-free { background: var(--paper); opacity: 1; }+.ctx-rows, .ctx-models { display: flex; flex-direction: column; gap: 5px; }+.ctx-models { border-top: 1px solid var(--line); padding-top: 8px; }+.ctx-row { display: flex; gap: 8px; align-items: center; font-size: var(--fs-meta); }+.ctx-dot { width: 8px; height: 8px; border-radius: 3px; flex: none; }+.ctx-label { color: var(--muted); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.ctx-model { font-size: var(--fs-label); }+.ctx-val { margin-left: auto; color: var(--faint); flex: none; }+.ctx-note { font-size: var(--fs-label); color: var(--faint); }+/* Subagents (OPE-257/259): active runs + done history, animal identity glyphs.+ Bare one-color marks, eyes punched out so the surface shows through; each family+ carries a light ink and a lifted dark ink. No warm colors — amber keeps its one+ attention meaning. */+.aglyph { flex: none; }+.aglyph-f0 { color: #7c5fc0; } .aglyph-f1 { color: #b55a99; }+.aglyph-f2 { color: #3f74b3; } .aglyph-f3 { color: #2f87a0; }+.aglyph-f4 { color: #2f8f77; } .aglyph-f5 { color: #4f9456; }+.aglyph-f6 { color: #5a66c7; } .aglyph-f7 { color: #64707f; }+html[data-theme="dark"] .aglyph-f0 { color: #a98fe8; }+html[data-theme="dark"] .aglyph-f1 { color: #dd8cc4; }+html[data-theme="dark"] .aglyph-f2 { color: #7aa8dd; }+html[data-theme="dark"] .aglyph-f3 { color: #6cc2d8; }+html[data-theme="dark"] .aglyph-f4 { color: #67c2a8; }+html[data-theme="dark"] .aglyph-f5 { color: #85c48b; }+html[data-theme="dark"] .aglyph-f6 { color: #939ce8; }+html[data-theme="dark"] .aglyph-f7 { color: #9aa5b3; }+.agent-list { display: flex; flex-direction: column; gap: 2px; }+.agent-row { display: flex; gap: 9px; align-items: center; padding: 5px 2px; border-radius: 8px; }+/* Collapsed-header chips: the five most recent runs, lined up before the count. */+.agent-chips { display: inline-flex; gap: 3px; align-items: center; margin-right: 7px; vertical-align: -2px; }+/* Done-history grid (more than ten runs): compressed glyphs, label on hover. */+.agent-grid { display: flex; flex-wrap: wrap; gap: 7px 9px; padding: 8px 2px 2px; margin-top: 6px; border-top: 1px solid var(--line); }+.agent-grid-item { opacity: 0.75; display: inline-flex; }+.agent-grid-item:hover { opacity: 1; }+.agent-label { display: flex; align-items: baseline; gap: 8px; min-width: 0; font-size: var(--fs-ui); font-weight: 500; color: var(--ink); overflow: hidden; }+.agent-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.agent-sub { font-size: var(--fs-label); color: var(--faint); flex: none; }+.agent-sub.attention { color: var(--warn-ink); }+.agent-dot { width: 7px; height: 7px; border-radius: 999px; margin-left: auto; flex: none; background: var(--line-strong); }+.agent-dot.running { background: var(--accent); }+.agent-dot.waiting { background: var(--warn-ink); }+.agent-dot.error { background: var(--danger-ink, #c33); }/* Journal + Access fold behind this quiet row (three primary sections max). */.rail-more-row { display: flex; gap: 8px; align-items: center; width: 100%; padding: 11px 0; border: 0; border-bottom: 1px solid var(--line); background: transparent; cursor: pointer; font: inherit; font-size: var(--fs-meta); color: var(--faint); text-align: left; }.rail-more-row:hover { color: var(--muted); }diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.tsindex 1c257b2e..60266275 100644--- a/surfaces/gui/src/types.ts+++ b/surfaces/gui/src/types.ts@@ -25,6 +25,7 @@ export type EventType =| "model_changed"| "mode_notice"| "memory_saved"+ | "agent_task"| "compacting"| "compacted"| "continuation"@@ -94,6 +95,18 @@ export interface SessionUsage {context: number;}+// Window occupancy for the rail's Context section (FB-015), from the `ready` event and+// each `assistant_message`. The category split is a server-side chars/4 estimate, so it+// is rendered as proportion of `used`, never as a ledger. `window` is null when the+// model isn't in the matrix ("window unknown", same contract as the composer ring).+export interface ContextInfo {+ window: number | null;+ used: number;+ estimated: boolean;+ breakdown: { system: number; tools: number; messages: number };+ compaction?: { created_at?: number; messages?: number; trimmed?: boolean };+}+export interface SessionInfo {session_id: string;title?: string;diff --git a/tests/test_agent_tasks.py b/tests/test_agent_tasks.pynew file mode 100644index 00000000..e34d5c82--- /dev/null+++ b/tests/test_agent_tasks.py@@ -0,0 +1,254 @@+"""Async subagents (OPE-254/255/258): spawn in the background, report back, and keep+the human the only approver — an expired approval wait resolves as declined and SAYS so+in the child's tool result.+"""++from __future__ import annotations++import asyncio+import time++import aisuite as ai+import pytest++from coworker.engine import TurnEngine+from coworker.permissions import Mode, PermissionEngine+from coworker.providers import AssistantTurn, ModelCapabilities, ProviderClient, ToolCall+from coworker.providers.base import TokenUsage+from coworker.sessions import usage_totals+from coworker.tools import ToolRegistry+from coworker.tools.agent_tasks import INHERIT_INSTRUCTIONS, agent_task_tools+++class DualRoleProvider(ProviderClient):+ """Scripts BOTH the parent and its children, told apart by the system prompt:+ a child carries the inherit/explorer instructions, the parent does not."""++ def __init__(self, spawn_args: dict):+ self.spawn_args = spawn_args++ def _is_child(self, messages) -> bool:+ head = messages[0] if messages else {}+ content = str(head.get("content", ""))+ return head.get("role") == "system" and (+ "background subagent" in content or "read-only code explorer" in content+ )++ def complete(self, *, model, messages, tools=None, **settings):+ if self._is_child(messages):+ if any(m.get("role") == "tool" for m in messages):+ return AssistantTurn(text="child report: finished without the blocked step")+ tool_names = [t["function"]["name"] for t in (tools or [])]+ if "write_marker" in tool_names:+ return AssistantTurn(+ text="",+ tool_calls=[ToolCall(id="c1", name="write_marker", arguments={})],+ )+ return AssistantTurn(+ text="child report: all clear",+ usage=TokenUsage(input=100, output=20, cache_read=0, cache_write=0),+ )+ # Parent: one spawn, then a plain reply.+ if not any(m.get("role") == "tool" for m in messages):+ return AssistantTurn(+ text="", tool_calls=[ToolCall(id="p1", name="spawn_agent", arguments=self.spawn_args)]+ )+ return AssistantTurn(text="spawned, moving on")++ def capabilities(self, model):+ return ModelCapabilities(tools=True)+++def _parent(tmp_path, provider, extra_tools=None):+ tools, registry = agent_task_tools(+ workspace=tmp_path, provider=provider, model="m"+ )+ reg = ToolRegistry()+ reg.register_all(tools)+ for t in extra_tools or []:+ reg.register(t)+ engine = TurnEngine(+ provider=provider,+ registry=reg,+ permissions=PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE),+ model="m",+ )+ registry.bind(engine)+ engine.agent_tasks = registry+ return engine, registry+++async def _wait_for(predicate, timeout=10.0):+ deadline = time.time() + timeout+ while time.time() < deadline:+ if predicate():+ return True+ await asyncio.sleep(0.05)+ return False+++async def test_read_only_spawn_reports_back_and_counts_tokens(tmp_path):+ provider = DualRoleProvider({"task": "map the repo", "label": "repo map"})+ engine, registry = _parent(tmp_path, provider)++ events = [e async for e in engine.run("go research")]+ assert any(e.data.get("text") == "spawned, moving on" for e in events if e.data)++ assert await _wait_for(lambda: registry.snapshot() and registry.snapshot()[0]["status"] == "done")+ snap = registry.snapshot()[0]+ assert snap["label"] == "repo map"+ assert snap["usage"]["m"]["input"] == 100 and snap["usage"]["m"]["turns"] == 1++ # No manager wired: the report reaches the parent as steering — consumed into the+ # transcript when the child beat the turn's end, queued otherwise. The usage+ # notice lands in the transcript where usage_totals folds it (OPE-258).+ delivered = [s[0] for s in engine._steering] + [+ str(m.get("content", "")) for m in engine.messages if m.get("role") == "user"+ ]+ assert any("child report: all clear" in d for d in delivered)+ totals = usage_totals(engine.messages)+ assert totals["m"]["input"] >= 100 # the child's spend is visible now++ # agent_task_output can still peek at the finished run.+ out = engine.registry.execute("agent_task_output", {"task_id": snap["id"]})+ assert out["status"] == "done" and "all clear" in out["report"]+++async def test_expired_approval_is_declined_and_says_so(tmp_path, monkeypatch):+ """OPE-255 ruling: expiry = declined, never approved, and the child's tool result+ must say the request expired — the honest-fallback contract."""+ from coworker.tools import agent_tasks as module++ monkeypatch.setattr(module, "_MIN_APPROVAL_TIMEOUT", 0.2)++ def write_marker() -> dict:+ """Writes a marker file (needs approval)."""+ return {"ok": True}++ marker_tool = ai.tool(+ write_marker,+ metadata=ai.ToolMetadata(+ category="files", risk_level="high", capabilities=["write"], requires_approval=True+ ),+ )++ provider = DualRoleProvider(+ {"task": "write the marker", "label": "marker run", "mode": "inherit", "approval_timeout": 0.2}+ )+ engine, registry = _parent(tmp_path, provider, extra_tools=[marker_tool])+ registry.loop = asyncio.get_running_loop()++ asked, expired_ids = asyncio.Event(), []++ async def never_answers(req):+ # The card carries the subagent's name and a prefixed id (no Inbox collision).+ assert req.reason and req.reason.startswith("[subagent: marker run]")+ assert req.tool_call_id.startswith("agent-")+ asked.set()+ await asyncio.Event().wait() # the human never responds++ engine.approver = never_answers+ registry.resolve_expired = expired_ids.append++ [e async for e in engine.run("go")]+ assert await _wait_for(lambda: registry.snapshot() and registry.snapshot()[0]["status"] == "done")+ assert asked.is_set()++ task = registry.get(registry.snapshot()[0]["id"])+ tool_msgs = [m for m in task.engine.messages if m.get("role") == "tool"]+ assert tool_msgs, "the denied call must leave an honest tool result"+ assert "expired" in str(tool_msgs[0].get("content", ""))+ assert "NOT approved" in str(tool_msgs[0].get("content", ""))+ assert expired_ids and expired_ids[0].startswith(task.id + ":")+ assert "without the blocked step" in task.report+++async def test_delivery_fires_through_the_server_hooks(tmp_path):+ """The production path the first live run broke: registry.loop SET (the manager+ wires it) and a deliver hook — the notice must land and the hook must fire."""+ provider = DualRoleProvider({"task": "map the repo", "label": "hooked run"})+ engine, registry = _parent(tmp_path, provider)+ registry.loop = asyncio.get_running_loop()+ delivered: list[tuple[str, dict]] = []+ registry.deliver = lambda text, source: delivered.append((text, source))++ [e async for e in engine.run("go")]+ assert await _wait_for(lambda: bool(delivered))+ text, source = delivered[0]+ assert "child report: all clear" in text and source["title"] == "hooked run"+ # The usage notice went through the loop (scheduled, so give it a beat).+ assert await _wait_for(+ lambda: any(m.get("role") == "notice" and m.get("kind") == "agent_task" for m in engine.messages)+ )+++def test_store_marks_live_runs_lost_truncates_and_caps(tmp_path):+ from coworker.tools.agent_tasks import AgentTaskStore, _KEEP_FINISHED++ path = tmp_path / "agent_tasks.json"+ store = AgentTaskStore(path)+ rows = [+ {"id": "agent-1", "label": "live one", "status": "running", "created": 1},+ {"id": "agent-2", "label": "big report", "status": "done", "created": 2, "finished": 99_999, "report": "x" * 20_000},+ ] + [+ {"id": f"agent-{i}", "status": "done", "created": i, "finished": i}+ for i in range(3, 3 + _KEEP_FINISHED + 10)+ ]+ store.put("s1", rows)++ # A fresh store (the restart) reads the same file: the live run is honestly lost,+ # the oversized report is truncated, and the finished list is capped at N.+ reopened = AgentTaskStore(path)+ out = reopened.load("s1")+ lost = next(r for r in out if r["id"] == "agent-1")+ assert lost["status"] == "error" and "restart" in lost["note"]+ big = next(r for r in out if r["id"] == "agent-2")+ assert len(big["report"]) < 9_000 and "truncated" in big["report"]+ assert sum(1 for r in out if r["status"] == "done") <= _KEEP_FINISHED++ reopened.drop("s1")+ assert AgentTaskStore(path).load("s1") == []+++async def test_registry_persists_runs_and_rehydrates_without_id_collisions(tmp_path):+ from coworker.tools.agent_tasks import AgentTaskStore++ store = AgentTaskStore(tmp_path / "agent_tasks.json")+ provider = DualRoleProvider({"task": "map the repo", "label": "first run"})+ engine, registry = _parent(tmp_path, provider)+ registry.attach_store(store, "sess-1")+ [e async for e in engine.run("go")]+ assert await _wait_for(lambda: store.load("sess-1") and store.load("sess-1")[0]["status"] == "done")++ # A new registry (the rebuilt engine) rehydrates the history and keeps counting+ # ABOVE it, so a fresh spawn never reuses agent-1.+ _, registry2 = _parent(tmp_path, provider)+ registry2.attach_store(store, "sess-1")+ snap = registry2.snapshot()+ assert snap and snap[0]["label"] == "first run" and snap[0]["status"] == "done"+ t = registry2.new_task("second", "t", "read_only", None)+ assert t.id != snap[0]["id"]+++async def test_cancel_stops_a_running_child(tmp_path):+ class SlowChildProvider(DualRoleProvider):+ def complete(self, *, model, messages, tools=None, **settings):+ if self._is_child(messages):+ time.sleep(0.3)+ return AssistantTurn(+ text="", tool_calls=[ToolCall(id="l1", name="grep", arguments={"pattern": "x"})]+ )+ return super().complete(model=model, messages=messages, tools=tools, **settings)++ provider = SlowChildProvider({"task": "loop forever", "label": "loopy"})+ engine, registry = _parent(tmp_path, provider)+ [e async for e in engine.run("go")]+ assert await _wait_for(lambda: bool(registry.snapshot()))+ task_id = registry.snapshot()[0]["id"]+ engine.registry.execute("agent_task_cancel", {"task_id": task_id})+ assert await _wait_for(lambda: registry.snapshot()[0]["status"] in ("canceled", "done"))diff --git a/tests/test_context_snapshot.py b/tests/test_context_snapshot.pynew file mode 100644index 00000000..6ff7fa8b--- /dev/null+++ b/tests/test_context_snapshot.py@@ -0,0 +1,73 @@+"""`context_snapshot` — the window-occupancy readout behind the GUI's Context panel (FB-015).++The split (system / tools / messages) is always a chars/4 estimate; `used` prefers the+provider-reported prompt-side total from the latest round trip and says when it had to+fall back to the estimate.+"""++from __future__ import annotations++import pytest++from coworker.engine import EventType, TurnEngine+from coworker.permissions import Mode, PermissionEngine+from coworker.providers import (+ AssistantTurn,+ ModelCapabilities,+ ProviderClient,+)+from coworker.providers.base import TokenUsage+from coworker.tools import ToolRegistry+++class OneReplyProvider(ProviderClient):+ def __init__(self, usage: TokenUsage | None = None):+ self.usage = usage++ def complete(self, *, model, messages, tools=None, **settings):+ return AssistantTurn(text="done", tool_calls=[], usage=self.usage)++ def capabilities(self, model):+ return ModelCapabilities(tools=True)+++def _engine(tmp_path, provider):+ return TurnEngine(+ provider=provider,+ registry=ToolRegistry(),+ permissions=PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE),+ model="m",+ )+++def test_estimate_fallback_splits_system_tools_and_messages(tmp_path):+ engine = _engine(tmp_path, OneReplyProvider())+ engine.messages.append({"role": "system", "content": "s" * 400})+ engine.messages.append({"role": "user", "content": "u" * 800})++ snap = engine.context_snapshot()++ assert snap["estimated"] is True+ b = snap["breakdown"]+ # chars/4 over the serialized message: at least the content's share, in each bucket.+ assert b["system"] >= 100+ assert b["messages"] >= 200+ assert b["tools"] == 0 # a bare registry carries no schemas+ assert snap["used"] == b["system"] + b["tools"] + b["messages"]+ # An unlisted model has no window; the GUI shows "window unknown" (UX-048).+ assert snap["window"] is None+ assert "compaction" not in snap # never compacted+++async def test_reported_usage_wins_and_rides_the_assistant_message(tmp_path):+ usage = TokenUsage(input=900, output=10, cache_read=2100, cache_write=0)+ engine = _engine(tmp_path, OneReplyProvider(usage))++ events = [e async for e in engine.run("hello")]++ replies = [e for e in events if e.type is EventType.ASSISTANT_MESSAGE]+ snap = replies[-1].data["context"]+ assert snap["used"] == usage.context_tokens # 900 + 2100+ assert snap["estimated"] is False+ assert set(snap["breakdown"]) == {"system", "tools", "messages"}