Files
openworker/tests/test_context_snapshot.py
Rohit Prasad cf035e2d1d Background subagents and a smarter side panel (#850)
* engine: report window occupancy as a context snapshot

Estimated system/tools/conversation split + resolved window, on ready and
each assistant_message; provider-reported prompt total wins when present.

* gui: right rail glance layer — environment, context meter, header summaries

Environment block (machine/folder/sandbox) atop the rail; Context section with
proportional breakdown and compaction note; collapsed headers carry muted
summary values (amber only for attention); header actions show on hover.

* engine: async subagents — spawn_agent family, human-only approvals, expiry note

Background children (read_only/inherit) with parent-stream approvals and a
fail-closed spawn-time deadline whose tool result says the ask expired;
reports steer or wake the parent; child tokens fold via the agent_task notice.

* gui: Subagents section in the right rail

Active + done runs with seeded icon chips and ages, amber while one waits on
approval; fed by agent_task events + the sessions/tasks endpoint.

* engine: persist subagent runs in a supplemental store

agent_tasks.json beside the wake store, written on transitions: last 50
finished per session, 8KB report cap, live-at-restart runs marked lost.
Also fixes report delivery through call_soon_threadsafe (kwargs crash).

* gui: animal identity glyphs for subagents

Ten one-color silhouettes with punched-out eyes, eight color families per
theme; header chips on the collapsed section; done history compresses to a
glyph grid past ten runs.

* e2e: unshadow the compaction flow; align team/machine specs with the new rail

One compact-the-context handler (signal, divider, context stamp); team header
asserts the attention summary; machine-group locator scoped past the env block.
2026-11-07 10:27:00 -08:00

74 lines
2.5 KiB
Python

"""`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
@pytest.mark.asyncio
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"}