Compare commits

...

4 Commits

Author SHA1 Message Date
vh 489cfee1f0 fix(tui): drop post-Done Markdown body re-render (v0.8.2)
Operator: "first turn double prints agent's turn."

Root cause: v0.8.1 wrote both the streamed Text lines AND the post-
Done `Markdown(event.response)` body into the transcript. Same
content rendered twice — once as plain streaming, once as a full
markdown re-render. The v0.8.1 commit message documented this as
"some duplication is acceptable" but the live UX read as a bug.

## Fix

Drop the post-Done `Rule + Markdown(response)` writes in non-raw
mode. The streamed text IS the response; whatever the model emitted
flows into the transcript line-by-line via coalesce-on-newline.
Markdown formatting (bold, lists, code blocks) renders as plain
text — a known regression from v0.8.1's polished output but the
right tradeoff vs the duplication bug.

## What this loses temporarily

Pre-v0.8.2 (after Done):
  [done] turn_id=... ───
  ─── (Rule separator) ───
  **Bold text** rendered bold, `code` highlighted, lists as bullets, etc.

v0.8.2 (after Done):
  [done] turn_id=... ───
  **Bold text** as plain asterisks, `code` as backticks, lists as plain dashes

## v0.9.0 plan

Restore markdown rendering via LIVE rendering during the stream
(not post-Done re-render). Replace `RichLog#transcript` with a
`VerticalScroll` container that mounts a fresh `Markdown` widget
per turn; Text deltas update the widget; markdown renders as
content arrives. No duplication, no snap, full formatting.
Operator-confirmed direction (2026-05-25 AskUserQuestion).

## Tests

287/287 GREEN; ruff clean. Two tests updated for the new shape:
- test_done_renders_markdown_after_label → renamed
  test_done_flushes_tail_and_writes_label; asserts NO Markdown, NO
  Rule (post-Done) in the writes.
- test_happy_text_done_renders_markdown → renamed
  test_happy_text_done_no_double_print; asserts NO Markdown in the
  spy.

Patch bump (v0.8.1 → v0.8.2): bug fix; no public API change.
2026-05-24 21:53:20 -07:00
vh 11ef6830ab fix(tui,sse): inline Text streaming + empty-id keepalive skip (v0.8.1)
Two related fixes for the same user-reported bug pattern from a
running session against ratatoskr:sindra (qwen3.6-35-a3b-heretic):

## 1. Streaming text overlapping the transcript

Operator: "new text comes at the bottom and overwrites the existing
pane information instead of pushing it up naturally."

Root cause: the v0.6.0 `#current-text` Static was `dock: bottom`
with `height: auto`, sitting between the transcript RichLog (1fr)
and the prompt Input (dock: bottom). As text streamed, the Static
grew UPWARD but Textual didn't dynamically resize the 1fr transcript
to accommodate — the growing Static visually OVERLAPPED the
transcript's bottom rows. On Done, `current_text.update("")` snapped
it to height 0 and the transcript re-laid-out — "boom, everything
updates."

Fix: remove `#current-text` Static entirely. Apply the same
coalesce-on-newline pattern v0.7.1 used for thinking — Text deltas
accumulate in `TuiPresenterState.text_chunk_buffer`, flushing whole
lines (each `\n` boundary) directly to `log` (transcript). On Done:
flush remaining tail, then [done] label + Rule + Markdown body.

Trade-off accepted: streamed lines + post-Done Markdown body are
both in the transcript (some content duplication). The Markdown
body re-renders the same content with proper formatting (lists,
bold, code blocks). Acceptable — operator gets both the live-progress
streaming AND the canonical rendered version.

## 2. MalformedSseId raw='' crashing every turn

Operator: "current session is erroring on every turn with
[malformed_sse_id] raw=''"

Worldtree's qwen3.6-35-a3b-heretic provider emits some events
without `id:` lines (observed 2026-05-25 mid-stream). When the FIRST
such event arrives before any prior id has been seen, httpx_sse's
`ServerSentEvent.id` is `""`. `_parse_sse_id('')` raised ValueError
→ MalformedSseId → turn worker bailed → operator saw the label
every turn.

Per SSE RFC, events without `id:` are legitimate (they just don't
update Last-Event-ID). Issue #7 already covered the empty-DATA
keepalive case with skip-silently semantics. Empty-id is the same
shape of wire weirdness; same fix shape:

  if sse.id == "":
      continue  # treat as keepalive

Ordered AFTER the empty-data branch so an empty-data + empty-id
event still gets skipped on the data check.

## Tests + smoke

287/287 GREEN (was 286, +1 for empty-id skip; +1 net Text-flow test
adjustments). Ruff clean.

Verified Worldtree alive when the user hit the empty-id bug
(/healthz returned ok in 18ms) — not a server-down issue, just
wire-format mid-stream.

## Caveats

The fix doesn't recover content from the dropped empty-id event.
If the event happened to carry meaningful data (not a true
keepalive), we silently lose it. Acceptable trade-off: pre-v0.8.1
EVERY turn died on the offending agent; post-v0.8.1 the turn
continues and any single dropped frame is recoverable from logs if
debugging. Worldtree-side fix (always emit ids) is the right
upstream answer; ratatoskr just stops panicking on wire weirdness.

Patch bump (v0.8.0 → v0.8.1) — both fixes are bug fixes; no public
API change. The `TuiPresenterState.render` signature loses the
`current_text` parameter (was added v0.6.0), but presenter is an
internal contract; no external callers.
2026-05-24 21:39:02 -07:00
vh 9fade55901 feat(local_agents): tier-3 index + picker merge (v0.8.0)
Worldtree's GET /agents doesn't return consumer-defined (tier-3)
agents — the public list excludes them by design. Confirmed live in
v0.7.0's smoke. Without server-side knowledge, ratatoskr's picker
couldn't show tier-3 agents the operator had defined; the workflow
was "remember the agent_id, pass --agent ratatoskr:<name>
explicitly." Friction grows with every tier-3 agent.

## Fix: client-side index, merged at picker time

New module `ratatoskr.local_agents` maintains a JSON-backed index at
$XDG_CONFIG_HOME/ratatoskr/local_agents.json (override via
$RATATOSKR_LOCAL_AGENTS). `tier3` CLI define / patch / delete update
the index as side-effects. `tui._resolve_then_run` loads the index
after `list_agents(client)` and appends entries not already in the
remote list (dedup by agent_id; remote wins on conflict).

Library-level `tier3.define_agent` / `patch_agent` / `delete_agent`
stay pure — local persistence lives in the CLI layer (`_run_define`
etc.), not in the library functions. Tests of the library don't
touch the filesystem.

## Public surface

  ratatoskr.local_agents:
    LocalAgentEntry (frozen dataclass)
    load_local_agents() -> list[LocalAgentEntry]
    add_local_agent(entry)
    update_local_agent(entry)  # same semantics as add (agent_id key)
    remove_local_agent(agent_id)
    make_description(system_prompt) -> str  # synthetic picker label

Failure modes are lenient: missing file → empty index; corrupt JSON
or schema mismatch → empty index (no crash). The picker continues
to show foundational agents either way; tier-3 surface degrades to
the pre-v0.8.0 workflow.

## Picker integration

Local entries convert to ratatoskr.sessions.AgentInfo with synthetic
fields:
  name        = agent_name (from LocalAgentEntry)
  description = "(tier 3) <first non-empty line of system prompt>"
  version, capabilities, supported_models, persona_traits, ui_hints
    = None / [] / [] / {} / {}

If Worldtree later starts returning tier-3 in GET /agents, this
module's role narrows to redundant local cache; can be removed
cleanly since the dedup-by-agent-id keeps remote-wins behavior.

## Tests

286/286 GREEN (was 265, +21: 20 local_agents + 1 picker-merge
integration). Ruff clean. Tests isolate the index via
$RATATOSKR_LOCAL_AGENTS pointed at pytest's tmp_path — no pollution
of operator's real ~/.config/ratatoskr/.

## Manual smoke

Sindra-like define against personal Worldtree:
  python -m ratatoskr.tier3 define --name foo --system-prompt "..." --model X
  cat ~/.config/ratatoskr/local_agents.json
  # ratatoskr --new picker now shows ratatoskr:foo alongside mimir et al.

Cross-machine: the file is per-host. Operator can sync via dotfiles
if needed; out of scope for this commit.

Minor bump (v0.7.1 → v0.8.0) — new public module + new picker
behavior (more agents shown). No caller-side breaking changes.
2026-05-24 21:13:30 -07:00
vh 9918c10acf fix(tui): coalesce thinking deltas on \n (v0.7.1)
Operator: "thinking tokens seem to be split by token — each on a
newline, is that correct? We don't want that."

Root cause: v0.6.5 wrote each Thinking SSE delta as its own
`thinking_log.write(event.content)` call. Worldtree emits Thinking
events at token granularity (per-token or per-few-tokens), so EACH
token became its own RichLog line — visually choppy, one short
fragment per visual row. Wrong UX.

## Fix: coalesce-on-newline

Thinking deltas accumulate in `TuiPresenterState.thinking_chunk_buffer`
(new str field). On each Thinking event:

  1. Append delta content to buffer.
  2. Flush every COMPLETE line (chars before each `\n`) as one
     thinking_log.write(line) call.
  3. Leave the post-final-`\n` tail in the buffer for the next delta.

On any non-thinking event (run close):
  1. Flush remaining buffer tail (if any) as one final line.
  2. Write Rule(end).

Empty lines (blank paragraph separators in the model's `\n\n` flow)
are skipped — they'd render as no-content RichLog entries which
just add vertical noise. Natural paragraph breaks become single
visible lines; multi-paragraph thinking renders top-to-bottom.

## Verified live (tier-3 smoke against personal Worldtree)

Defined a `thinky-smoke` agent via `python -m ratatoskr.tier3 define`,
asked "What is 12 times 13?". Thinking pane rendered with natural
paragraph chunks:

  ── turn N · thinking #1 start ──
  Thinking Process:
  1.  **Analyze the Request:** The user wants to know the result of $12 \times 13$.
  2.  **Calculate:**
      *   Method 1: Standard multiplication.
          $$12 \times 10 = 120$$
          $$12 \times 3 = 36$$
          $$120 + 36 = 156$$
      *   Method 2: $(10 + 2)(10 + 3) = 100 + 30 + 20 + 6 = 156$.
  ── turn N · thinking #1 end ──

Each line = one natural paragraph or list item. No per-token fragments.

## Edge cases noted

- Long-running thinking with NO `\n` at all stays buffered until run
  close → operator sees nothing until close. Possible follow-up: add
  a length-threshold flush (e.g., > 500 chars → flush at the last
  space). For now this is acceptable; thinking content typically has
  `\n` breaks every few sentences.
- Empty deltas (`""`) are ignored implicitly — no buffer growth, no
  flush.
- `\n` at the very start of a delta flushes whatever was buffered
  before, then leaves the empty post-`\n` tail (empty string) in the
  buffer, which doesn't show up as an empty line because of the
  `if line:` guard.

## Contract amendment

docs/contracts/issues/13.contract.md INV-022 amended for v0.7.1
coalesce semantics. Drift-check clean.

## Tests

265/265 GREEN; ruff clean. Two updated tests:

- `test_thinking_streams_into_thinking_log` → renamed
  `test_thinking_coalesces_until_newline`: 3 token-shaped deltas
  with no `\n` → only Rule(start) writes, buffer holds accumulated.
- NEW `test_thinking_flushes_on_newline`: delta carrying `\n` →
  Rule(start) + accumulated line + clear buffer.
- `test_thinking_closes_to_thinking_log`: 2 deltas "a", "b" +
  close → Rule(start) + tail-flush "ab" + Rule(end) = 3 writes
  (was 4 with per-delta).

Patch bump (v0.7.0 → v0.7.1) — internal presenter routing change;
no public-API or layout change.
2026-05-24 20:39:55 -07:00
12 changed files with 742 additions and 162 deletions
+1 -1
View File
@@ -161,7 +161,7 @@ New `Static(id="pane-name")` widget alongside the existing `identity` + `hint` w
- **INV-019** *(amended v0.6.0)*: Three TabPanes in the right column: `Tools` (id `tools-tab`, contains `#tools-log`) + `Debug` (id `debug-tab`, contains `#debug-log`) + `Thinking` (id `thinking-tab`, contains `#thinking-log`). Ctrl+1/Ctrl+2/Ctrl+3 activate respective tabs. `pane-name` Static reflects active tab name dynamically.
- **INV-020** *(amended v0.6.0)*: Render-exception fallback (INV-009) preserves routing per event class: `ToolStart` / `ToolResult``tools_log`; `Thinking``thinking_log`; `WorkerPhase` / `TextBoundary``debug_log`; everything else → `log`.
- **INV-021** *(new v0.6.0)*: `Text` events do NOT route to `log` per-delta. They accumulate into `TuiPresenterState.text_buffer` and update a single `current_text` Static (docked above the prompt). On terminal event (`Done`/`Error`/`Cancelled`), `current_text` is cleared and (raw mode) accumulated text or (non-raw) post-Done `Markdown(response)` is written to `log`. The pre-v0.6.0 per-token RichLog spam is retired.
- **INV-022** *(amended v0.6.5)*: Thinking deltas stream DIRECTLY into `thinking_log` (one delta = one RichLog line). The first delta of a run writes `Rule(title=f"turn N · thinking #K start")`; subsequent deltas write their raw content as lines; the run closes on the next non-thinking event with `Rule(title=f"turn N · thinking #K end")`. Pre-v0.6.5 markdown re-render dropped — the streamed deltas ARE the content; the whole pane scrolls naturally as content arrives.
- **INV-022** *(amended v0.7.1)*: Thinking deltas COALESCE on `\n` boundaries before writing to `thinking_log`. The first delta of a run writes `Rule(title=f"turn N · thinking #K start")`; subsequent deltas accumulate in `TuiPresenterState.thinking_chunk_buffer`; whenever the buffer contains `\n`, the leading line(s) flush as RichLog entries (one entry per natural paragraph). The run closes on the next non-thinking event: any tail in the buffer flushes as a final line, then `Rule(title=f"turn N · thinking #K end")`. Pre-v0.7.1 per-delta-per-line caused token-spam (Worldtree emits thinking at token granularity); coalescing produces one log line per natural paragraph, not per token.
- **INV-023** *(new v0.6.0)*: Turn-ID header `Rule(title=f"turn N")` is written to all four log panes (`log`, `tools_log`, `debug_log`, `thinking_log`) by `_stream_turn_worker` on the first event of each turn — enables cross-pane visual correlation during multi-turn debugging.
- **INV-024** *(amended v0.6.5)*: `thinking-current` Static REMOVED. v0.6.1 placed it inside the Thinking pane (docked bottom); operators reported the bottom-docked Static "scrolling a little section at the bottom" (its 200-char tail acting as a scroll-window) instead of letting the whole pane scroll. v0.6.5 deletes the Static entirely and streams Thinking deltas directly into `thinking_log` (the scrollable RichLog) — the whole pane scrolls naturally as content arrives. The Rule(start) at the first delta of a run is now the live "thinking is happening" indicator.
+7 -3
View File
@@ -32,9 +32,9 @@ separate dev team rather than an in-tree Worldtree tool.
## Current state / in-flight
_As of 2026-05-25 (post-v0.7.0 Tier 3 agent lifecycle):_
_As of 2026-05-25 (post-v0.8.2 drop double-print; v0.9.0 live-md next):_
**Status: v0.7.0 shipped.** Ten core features complete (`sse_client`
**Status: v0.8.2 shipped.** Eleven core features complete (`sse_client`
#1, `sessions` #2, `cli` #3, `tui` #4, `--end-user-id` #5, TUI
startup error visibility #6, presenter contract semantics amendment
#12, startup agent picker #8, §5 layout reshape + Tools pane #13)
@@ -51,7 +51,11 @@ Static in the footer (static "Tools" v1; dynamic when more tabs
land). CLI mode (--send) unaffected by design — INV-018.
Last commits on `main`:
- v0.7.0 feat(tier3): ratatoskr.tier3 module + CLI — Worldtree Tier 3 lifecycle
- v0.8.2 fix(tui): drop post-Done Markdown body re-render (no double-print)
- `11ef683` fix(tui,sse): inline Text streaming + empty-id keepalive skip (v0.8.1)
- `9fade55` feat(local_agents): JSON-backed local tier-3 index + picker merge (v0.8.0)
- `9918c10` fix(tui): coalesce thinking deltas on `\n` (v0.7.1)
- `c086ae2` feat(tier3): ratatoskr.tier3 module + CLI (v0.7.0)
- `d356990` refactor(tui): thinking streams into thinking-log (v0.6.5)
- `82437bd` style(tui): picker highlighted item → Aurora blue (v0.6.4)
- `ac690c1` style(tui): restore Australis palette, only $background → pure black (v0.6.3)
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "ratatoskr"
version = "0.7.0"
version = "0.8.2"
description = "Worldtree Conversation API debug TUI — multi-pane observability dashboard"
readme = "README.md"
requires-python = ">=3.12"
+134
View File
@@ -0,0 +1,134 @@
"""Local index of tier-3 agents defined via `python -m ratatoskr.tier3`.
Workaround for Worldtree's ``GET /agents`` not returning consumer-defined
agents (the public list excludes tier-3 per-spec; see issue #15 smoke
findings). Local file maintains a list of agent_ids + display metadata so
the picker can show them alongside foundational agents.
Storage shape: JSON at ``$XDG_CONFIG_HOME/ratatoskr/local_agents.json``
(default ``~/.config/ratatoskr/local_agents.json``). Override via
``$RATATOSKR_LOCAL_AGENTS`` env var for tests / per-machine isolation.
If Worldtree later starts returning tier-3 agents in ``GET /agents``, this
module's role narrows to redundant local cache; can be removed cleanly
since the picker's dedup-by-agent-id keeps remote-wins behavior.
Failure modes are lenient: missing file → empty index; corrupt JSON or
schema mismatch → empty index (no crash). The picker continues to show
foundational agents either way; the local-tier-3 surface degrades to
"operator passes --agent ratatoskr:<name> explicitly" — the
pre-v0.8.0 workflow.
"""
from __future__ import annotations
import json
import os
from dataclasses import asdict, dataclass
from pathlib import Path
_SCHEMA_VERSION = 1
@dataclass(frozen=True)
class LocalAgentEntry:
"""One row in the local tier-3 agent index.
Schema:
- ``agent_id``: full "user_id:agent_name" string (Worldtree-owned).
- ``agent_name``: slug from define (display name).
- ``model``: provider model ID at last define/patch.
- ``description``: synthetic display string (typically derived from
the system_prompt's first line + a "(tier 3)" prefix; the picker
uses this in its ``{id} · {name}{description}`` rendering).
- ``defined_at``: ISO-8601 timestamp from the Tier3AgentInfo response.
"""
agent_id: str
agent_name: str
model: str
description: str
defined_at: str
def _local_agents_path() -> Path:
"""Resolve the local index file path with XDG + env-var override."""
override = os.environ.get("RATATOSKR_LOCAL_AGENTS")
if override:
return Path(override)
xdg = os.environ.get("XDG_CONFIG_HOME")
base = Path(xdg) if xdg else (Path.home() / ".config")
return base / "ratatoskr" / "local_agents.json"
def load_local_agents() -> list[LocalAgentEntry]:
"""Read the local index. Returns ``[]`` on missing file, corrupt JSON,
schema mismatch, or any read error — never raises.
"""
path = _local_agents_path()
if not path.exists():
return []
try:
raw = json.loads(path.read_text())
except (json.JSONDecodeError, OSError):
return []
if not isinstance(raw, dict) or raw.get("version") != _SCHEMA_VERSION:
return []
agents = raw.get("agents", [])
if not isinstance(agents, list):
return []
out: list[LocalAgentEntry] = []
for item in agents:
if not isinstance(item, dict):
continue
try:
out.append(LocalAgentEntry(**item))
except TypeError:
# Malformed row (missing/extra fields) — skip silently.
continue
return out
def _save_local_agents(agents: list[LocalAgentEntry]) -> None:
"""Persist the index. Creates parent dir as needed."""
path = _local_agents_path()
path.parent.mkdir(parents=True, exist_ok=True)
payload = {"version": _SCHEMA_VERSION, "agents": [asdict(a) for a in agents]}
path.write_text(json.dumps(payload, indent=2))
def add_local_agent(entry: LocalAgentEntry) -> None:
"""Add (or replace) an agent in the local index. agent_id is the key."""
agents = [a for a in load_local_agents() if a.agent_id != entry.agent_id]
agents.append(entry)
_save_local_agents(agents)
def update_local_agent(entry: LocalAgentEntry) -> None:
"""Update an existing entry. Identical semantics to ``add_local_agent``
(agent_id is the dedup key), exposed separately so callers can
self-document intent.
"""
add_local_agent(entry)
def remove_local_agent(agent_id: str) -> None:
"""Remove an entry by agent_id. No-op if absent (idempotent)."""
agents = [a for a in load_local_agents() if a.agent_id != agent_id]
_save_local_agents(agents)
def make_description(system_prompt: str) -> str:
"""Synthesize a one-line description for the picker from a system prompt.
Strategy: first non-empty line, stripped of leading markdown heading
markers and whitespace, prefixed with "(tier 3) ", truncated to 80
chars. Falls back to "(tier 3) custom system prompt" if the prompt is
empty (defensive — define rejects empty prompts at PRE-002).
"""
for line in system_prompt.splitlines():
stripped = line.lstrip("# ").strip()
if stripped:
label = f"(tier 3) {stripped}"
return label[:80] + ("" if len(label) > 80 else "")
return "(tier 3) custom system prompt"
+8
View File
@@ -309,6 +309,14 @@ async def _iter_events(
# with a bad id is still a keepalive). Don't reorder.
if sse.data == "":
continue
# v0.8.1: empty-id frames are also treated as keepalives. Worldtree
# SOMETIMES emits events without an `id:` line (observed mid-stream
# on the qwen3.6-35-a3b-heretic provider, 2026-05-25). Per the SSE
# RFC, events without ids are legitimate (they just don't update
# Last-Event-ID); the previous strict behavior crashed every turn
# on the offending agent. Treat same as empty-data: skip silently.
if sse.id == "":
continue
try:
sse_id = _parse_sse_id(sse.id)
except ValueError as exc:
+33
View File
@@ -309,6 +309,11 @@ def _resolve_auth(ns: argparse.Namespace) -> tuple[str, str]:
async def _run_define(ns: argparse.Namespace) -> int:
api_key, server_url = _resolve_auth(ns)
from ratatoskr.cli import USER_AGENT
from ratatoskr.local_agents import (
LocalAgentEntry,
add_local_agent,
make_description,
)
async with httpx.AsyncClient(
base_url=server_url,
@@ -324,6 +329,16 @@ async def _run_define(ns: argparse.Namespace) -> int:
system_prompt=ns.system_prompt,
model=ns.model,
)
# v0.8.0: persist to local index so the picker can show it.
add_local_agent(
LocalAgentEntry(
agent_id=info.agent_id,
agent_name=info.agent_name,
model=info.model,
description=make_description(info.system_prompt),
defined_at=info.created_at,
)
)
print(f"defined {info.agent_id} ({info.model})")
return 0
@@ -331,6 +346,11 @@ async def _run_define(ns: argparse.Namespace) -> int:
async def _run_patch(ns: argparse.Namespace) -> int:
api_key, server_url = _resolve_auth(ns)
from ratatoskr.cli import USER_AGENT
from ratatoskr.local_agents import (
LocalAgentEntry,
make_description,
update_local_agent,
)
if ns.system_prompt is None and ns.model is None:
raise _Tier3UsageError(
@@ -350,6 +370,16 @@ async def _run_patch(ns: argparse.Namespace) -> int:
system_prompt=ns.system_prompt,
model=ns.model,
)
# v0.8.0: refresh local index with the post-patch state.
update_local_agent(
LocalAgentEntry(
agent_id=info.agent_id,
agent_name=info.agent_name,
model=info.model,
description=make_description(info.system_prompt),
defined_at=info.updated_at,
)
)
print(f"patched {info.agent_id}")
return 0
@@ -357,6 +387,7 @@ async def _run_patch(ns: argparse.Namespace) -> int:
async def _run_delete(ns: argparse.Namespace) -> int:
api_key, server_url = _resolve_auth(ns)
from ratatoskr.cli import USER_AGENT
from ratatoskr.local_agents import remove_local_agent
async with httpx.AsyncClient(
base_url=server_url,
@@ -367,6 +398,8 @@ async def _run_delete(ns: argparse.Namespace) -> int:
timeout=httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0),
) as client:
await delete_agent(client, ns.agent_id)
# v0.8.0: drop from local index so the picker stops listing it.
remove_local_agent(ns.agent_id)
print(f"deleted {ns.agent_id}")
return 0
+89 -56
View File
@@ -10,7 +10,7 @@ from __future__ import annotations
import asyncio
import sys
from dataclasses import dataclass, field
from dataclasses import dataclass
from typing import ClassVar, Literal
import httpx
@@ -186,18 +186,28 @@ class TuiPresenterState:
"""
thinking_open: bool = False
# v0.6.0: per-turn streaming text buffer. Text deltas accumulate here
# and update `current_text` Static in place — no per-token RichLog spam.
text_buffer: list[str] = field(default_factory=list)
# Thinking-run counter for turn-scoped start/end markers.
thinking_run_index: int = 0
# v0.7.1: thinking-content accumulator. Worldtree emits Thinking deltas
# at token granularity; flushing each delta as its own RichLog line
# produces per-token-per-newline visual spam. Buffer here and flush
# only on `\n` boundaries (one written line per natural paragraph) or
# when the run closes (any leftover tail).
thinking_chunk_buffer: str = ""
# v0.8.1: same pattern for Text deltas. Pre-v0.8.1 the Text deltas
# streamed into a dedicated #current-text Static below the transcript;
# that Static (docked-bottom, height: auto) grew during streaming and
# visually OVERLAPPED the transcript above (Textual didn't dynamically
# resize the 1fr transcript while the dock-bottom child expanded).
# The Static is gone in v0.8.1 — Text deltas coalesce on `\n` and write
# directly to `log` (transcript), the same shape thinking uses.
text_chunk_buffer: str = ""
def render(
self,
event: Event,
*,
log: RichLog,
current_text: Static,
tools_log: RichLog,
debug_log: RichLog,
thinking_log: RichLog,
@@ -205,18 +215,14 @@ class TuiPresenterState:
) -> None:
"""Render one Worldtree SSE event with the TUI hierarchy + coalescing.
v0.6.5 routing:
- `log` (transcript) = content only: user-prompt echo (written
outside the presenter), terminal labels, post-Done Markdown body.
- `current_text` (Static below transcript) = live-streaming Text
deltas accumulated into one growing line; cleared on terminal.
v0.8.1 routing:
- `log` (transcript) = chat content: user-prompt echo (written
outside the presenter), coalesced Text deltas, terminal labels,
optional post-Done Markdown body.
- `tools_log` = ToolStart + ToolResult.
- `debug_log` = WorkerPhase + TextBoundary.
- `thinking_log` = streaming Thinking deltas inline (each chunk =
one line in the scrollable log). Rule(start)/Rule(end) markers
wrap each run. The whole pane scrolls naturally — no separate
tail-scrolling Static at the bottom (v0.6.5 removed
`thinking-current`).
- `thinking_log` = streaming Thinking deltas inline (coalesced on
`\n`). Rule(start)/Rule(end) wrap each run.
Exceptions caught at the presenter boundary (INV-009 fallback).
"""
@@ -234,10 +240,11 @@ class TuiPresenterState:
return RichText(s, style=_AU_DEMOTED)
try:
# v0.6.5: Thinking deltas stream directly into thinking_log.
# First delta of a run writes the Rule(start) header; each
# subsequent delta writes its content as a line; the run closes
# on the next non-thinking event with a Rule(end).
# v0.7.1: Thinking deltas coalesce by newline before flushing.
# Worldtree emits Thinking events at token granularity; per-delta
# RichLog writes produce one visual line per token (per-token-per-
# newline spam). Buffer the deltas and flush only on `\n` (one
# written line per natural paragraph) or run close.
if isinstance(event, Thinking):
from rich.rule import Rule
@@ -249,13 +256,24 @@ class TuiPresenterState:
style=_AU_DEMOTED,
))
self.thinking_open = True
# Stream the delta content (chunk-of-tokens) as one line.
thinking_log.write(event.content)
self.thinking_chunk_buffer += event.content
# Flush every complete line in the buffer. Whatever's after
# the final `\n` stays buffered for the next delta or close.
while "\n" in self.thinking_chunk_buffer:
line, _, rest = self.thinking_chunk_buffer.partition("\n")
if line: # skip empty lines (blank paragraph separators)
thinking_log.write(line)
self.thinking_chunk_buffer = rest
return
# Non-thinking event: close any open thinking run with Rule(end).
if self.thinking_open:
from rich.rule import Rule
# Flush the tail (content with no trailing `\n`) before the
# end rule so nothing gets lost on close.
if self.thinking_chunk_buffer:
thinking_log.write(self.thinking_chunk_buffer)
self.thinking_chunk_buffer = ""
turn_id = event.sse_id.turn_id if hasattr(event, "sse_id") else (
event.turn_id if hasattr(event, "turn_id") else "?"
)
@@ -266,19 +284,23 @@ class TuiPresenterState:
self.thinking_open = False
# Now render the non-thinking event itself.
if isinstance(event, Text):
# v0.6.0: streaming text accumulates into current_text Static
# — one growing live line, NOT per-delta RichLog entries.
self.text_buffer.append(event.content)
current_text.update("".join(self.text_buffer))
# v0.8.1: stream Text deltas into transcript directly,
# coalesced on `\n`. Same pattern as Thinking (v0.7.1).
# The pre-v0.8.1 #current-text Static is gone — its dock-
# bottom growth was overlapping the transcript visually.
self.text_chunk_buffer += event.content
while "\n" in self.text_chunk_buffer:
line, _, rest = self.text_chunk_buffer.partition("\n")
if line:
log.write(line)
self.text_chunk_buffer = rest
return
if isinstance(event, (Done, Error, Cancelled)):
# Terminal event: clear the streaming Static first so the
# live-preview band collapses. Then write the colored label
# + (non-raw) Markdown body / (raw) accumulated plain text
# to the transcript.
accumulated = "".join(self.text_buffer)
self.text_buffer.clear()
current_text.update("")
# Terminal event: flush any remaining text tail before the
# label / Markdown body lands.
if self.text_chunk_buffer:
log.write(self.text_chunk_buffer)
self.text_chunk_buffer = ""
# Terminal labels tinted per outcome (Aurora green / Dawn red
# / Dawn yellow) for at-a-glance scanning.
if isinstance(event, Done):
@@ -288,17 +310,13 @@ class TuiPresenterState:
f"usage {_format_usage(event.usage, arrow='')}",
style=_AU_SUCCESS,
))
if raw:
# Raw mode: emit the accumulated streamed text verbatim
# so the operator has a record after the Static clears.
if accumulated:
log.write(accumulated)
else:
from rich.markdown import Markdown
from rich.rule import Rule
log.write(Rule(style=_AU_DEMOTED))
log.write(Markdown(event.response))
# v0.8.2: post-Done Markdown body re-render dropped. Pre-
# v0.8.2 the transcript got BOTH the streamed text AND
# the Markdown(response) re-render — same content twice,
# operator-flagged as "double prints". The streamed text
# IS the response now; markdown formatting (bold, lists,
# code) renders as plain text. Matches thinking pane's
# stream-as-content semantics (no post-close re-render).
elif isinstance(event, Error):
log.write(RichText(
f"[error] turn_id={event.sse_id.turn_id} code={event.error_code} "
@@ -551,16 +569,9 @@ class RatatoskrApp(App[int]):
background: $background;
padding: 0 1;
}
/* v0.6.0: streaming-text Static carries in-flight assistant tokens.
Replaces per-token RichLog spam — one growing line that updates in
place. Cleared on terminal event; final Markdown body lands in the
transcript. */
#current-text {
dock: bottom;
height: auto;
background: $background;
padding: 0 1;
}
/* v0.8.1: #current-text Static removed. Streaming text now coalesces
on `\n` and writes directly to #transcript (same pattern as v0.7.1
thinking fix). Eliminates the dock-bottom-growth-overlap bug. */
#tools-log, #debug-log, #thinking-log {
background: $background;
padding: 0 1;
@@ -660,7 +671,6 @@ class RatatoskrApp(App[int]):
with Horizontal(id="main-row"):
with Vertical(id="left-column"):
yield RichLog(id="transcript", wrap=True, markup=False, highlight=False)
yield Static("", id="current-text")
yield Input(id="prompt", placeholder="Type a message and press Enter")
with Vertical(id="right-column"):
with TabbedContent(id="side-panes"):
@@ -780,7 +790,6 @@ class RatatoskrApp(App[int]):
assert self.client is not None
assert content
log = self.query_one("#transcript", RichLog)
current_text = self.query_one("#current-text", Static)
tools_log = self.query_one("#tools-log", RichLog)
debug_log = self.query_one("#debug-log", RichLog)
thinking_log = self.query_one("#thinking-log", RichLog)
@@ -796,7 +805,6 @@ class RatatoskrApp(App[int]):
presenter.render(
event,
log=log,
current_text=current_text,
tools_log=tools_log,
debug_log=debug_log,
thinking_log=thinking_log,
@@ -910,6 +918,14 @@ async def _resolve_then_run(args: ParsedArgs) -> int:
# Issue #8: startup agent picker — fetch GET /agents and prompt when
# --new is passed without --agent. list_agents errors land on real
# stderr before any alt-screen opens (preserves issue #6 INV-001).
#
# v0.8.0: merge in local tier-3 agent index. Worldtree's GET /agents
# doesn't return consumer-defined agents (issue #15 smoke finding);
# ratatoskr keeps its own JSON-backed index of agents the operator
# defined via `python -m ratatoskr.tier3 define`. Merged here so the
# picker shows foundational + local-tier-3 in one list. Dedup by
# agent_id (remote wins on conflict, since a server-listed agent
# is the authoritative source).
chosen_agent_id: str | None = args.agent_id
if args.new and args.agent_id is None:
try:
@@ -922,6 +938,23 @@ async def _resolve_then_run(args: ParsedArgs) -> int:
except (httpx.ConnectError, httpx.ReadTimeout, httpx.TransportError) as exc:
sys.stderr.write(f"[network_error] {type(exc).__name__}: {exc}\n")
return 21
# v0.8.0: append local tier-3 entries not already in the remote list.
from ratatoskr.local_agents import load_local_agents
remote_ids = {a.agent_id for a in agents}
for entry in load_local_agents():
if entry.agent_id in remote_ids:
continue
agents.append(AgentInfo(
agent_id=entry.agent_id,
name=entry.agent_name,
description=entry.description,
version=None,
capabilities=[],
supported_models=[],
persona_traits={},
ui_hints={},
))
if not agents:
sys.stderr.write("[no_agents] server returned empty agent list\n")
return 13
+187
View File
@@ -0,0 +1,187 @@
"""Tests for ratatoskr.local_agents.
Use ``$RATATOSKR_LOCAL_AGENTS`` env-var override + pytest tmp_path to
isolate from the operator's real ``~/.config/ratatoskr/local_agents.json``.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from ratatoskr.local_agents import (
LocalAgentEntry,
_local_agents_path,
add_local_agent,
load_local_agents,
make_description,
remove_local_agent,
update_local_agent,
)
@pytest.fixture
def local_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
"""Point $RATATOSKR_LOCAL_AGENTS at a fresh tmp file for the test."""
path = tmp_path / "local_agents.json"
monkeypatch.setenv("RATATOSKR_LOCAL_AGENTS", str(path))
return path
def _entry(
agent_id: str = "ratatoskr:wizard",
agent_name: str = "wizard",
model: str = "qwen3.6-35-a3b",
description: str = "(tier 3) test agent",
defined_at: str = "2026-05-25T00:00:00+00:00",
) -> LocalAgentEntry:
return LocalAgentEntry(
agent_id=agent_id,
agent_name=agent_name,
model=model,
description=description,
defined_at=defined_at,
)
class TestPathResolution:
def test_env_override(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("RATATOSKR_LOCAL_AGENTS", "/tmp/custom-agents.json")
assert _local_agents_path() == Path("/tmp/custom-agents.json")
def test_xdg_config_home(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("RATATOSKR_LOCAL_AGENTS", raising=False)
monkeypatch.setenv("XDG_CONFIG_HOME", "/tmp/xdg-config")
assert (
_local_agents_path()
== Path("/tmp/xdg-config/ratatoskr/local_agents.json")
)
def test_default_home(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("RATATOSKR_LOCAL_AGENTS", raising=False)
monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
path = _local_agents_path()
assert path == Path.home() / ".config" / "ratatoskr" / "local_agents.json"
class TestLoadEmpty:
def test_missing_file_returns_empty(self, local_path: Path) -> None:
assert not local_path.exists()
assert load_local_agents() == []
def test_corrupt_json_returns_empty(self, local_path: Path) -> None:
local_path.parent.mkdir(parents=True, exist_ok=True)
local_path.write_text("not json at all")
assert load_local_agents() == []
def test_wrong_schema_version_returns_empty(self, local_path: Path) -> None:
local_path.parent.mkdir(parents=True, exist_ok=True)
local_path.write_text(json.dumps({"version": 999, "agents": []}))
assert load_local_agents() == []
def test_missing_version_key_returns_empty(self, local_path: Path) -> None:
local_path.parent.mkdir(parents=True, exist_ok=True)
local_path.write_text(json.dumps({"agents": []}))
assert load_local_agents() == []
def test_malformed_row_skipped(self, local_path: Path) -> None:
local_path.parent.mkdir(parents=True, exist_ok=True)
local_path.write_text(
json.dumps(
{
"version": 1,
"agents": [
{"agent_id": "incomplete"}, # missing required fields
{
"agent_id": "ratatoskr:good",
"agent_name": "good",
"model": "m",
"description": "d",
"defined_at": "t",
},
],
}
)
)
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].agent_id == "ratatoskr:good"
class TestAdd:
def test_add_one(self, local_path: Path) -> None:
add_local_agent(_entry())
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].agent_id == "ratatoskr:wizard"
def test_add_two_different(self, local_path: Path) -> None:
add_local_agent(_entry(agent_id="ratatoskr:a", agent_name="a"))
add_local_agent(_entry(agent_id="ratatoskr:b", agent_name="b"))
ids = {e.agent_id for e in load_local_agents()}
assert ids == {"ratatoskr:a", "ratatoskr:b"}
def test_add_replaces_same_id(self, local_path: Path) -> None:
add_local_agent(_entry(model="old-model"))
add_local_agent(_entry(model="new-model"))
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].model == "new-model"
def test_creates_parent_dirs(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
nested = tmp_path / "deep" / "nested" / "path" / "agents.json"
monkeypatch.setenv("RATATOSKR_LOCAL_AGENTS", str(nested))
add_local_agent(_entry())
assert nested.exists()
class TestUpdate:
def test_update_changes_existing(self, local_path: Path) -> None:
add_local_agent(_entry(model="v1"))
update_local_agent(_entry(model="v2"))
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].model == "v2"
class TestRemove:
def test_remove_existing(self, local_path: Path) -> None:
add_local_agent(_entry())
remove_local_agent("ratatoskr:wizard")
assert load_local_agents() == []
def test_remove_missing_is_noop(self, local_path: Path) -> None:
add_local_agent(_entry())
remove_local_agent("ratatoskr:doesnotexist")
assert len(load_local_agents()) == 1
class TestMakeDescription:
def test_first_nonempty_line(self) -> None:
prompt = "\n\n# IDENTITY\nYou are a test agent..."
desc = make_description(prompt)
assert desc.startswith("(tier 3) IDENTITY")
def test_strips_heading_markers(self) -> None:
prompt = "# A nice heading\nMore prompt..."
desc = make_description(prompt)
assert "(tier 3) A nice heading" == desc
def test_truncates_long(self) -> None:
prompt = "x" * 200
desc = make_description(prompt)
# 80 char cap including the prefix
assert len(desc) == 81 # 80 + ellipsis char
assert desc.endswith("")
def test_empty_prompt_fallback(self) -> None:
desc = make_description("")
assert desc == "(tier 3) custom system prompt"
def test_whitespace_only_fallback(self) -> None:
desc = make_description(" \n\n ")
assert desc == "(tier 3) custom system prompt"
+41
View File
@@ -711,6 +711,47 @@ def _sse_raw_chunk(sse_id: str, raw_data: str) -> bytes:
return f"id: {sse_id}\ndata: {raw_data}\n\n".encode()
def _sse_no_id_chunk(data: str) -> bytes:
"""SSE frame with NO id line + arbitrary data (v0.8.1: keepalive shape)."""
return f"data: {data}\n\n".encode()
class TestEmptyIdSkipped:
@respx.mock
async def test_empty_id_on_first_event_skipped(self) -> None:
"""empty_id_on_first_event_skipped [v0.8.1]: stream starts with an
event carrying NO `id:` line → httpx_sse exposes sse.id == ''
(no prior id to inherit). Pre-v0.8.1: MalformedSseId raw='' crashed
the turn. v0.8.1: treat same as empty-data keepalive — skip silently.
Observed 2026-05-25 on Worldtree's qwen3.6-35-a3b-heretic provider:
the first stream frame had no id line, every turn died with
`[malformed_sse_id] raw=''`.
"""
from ratatoskr.sse_client import Done as _Done
from ratatoskr.sse_client import Text as _Text
# First frame: no id line (httpx_sse → sse.id = ""). Skip it.
# Subsequent frames have ids; normal processing resumes.
stream = (
_sse_no_id_chunk('{"type":"keepalive"}') # ← skipped (sse.id == "")
+ _sse_chunk("42:1", {"type": "text", "content": "first"})
+ _sse_chunk("42:2", _DONE_42_6)
)
respx.post("https://w.example/sessions/s1/messages").mock(
return_value=httpx.Response(
200, headers={"content-type": "text/event-stream"}, content=stream
)
)
async with httpx.AsyncClient(base_url="https://w.example") as client:
events = [e async for e in stream_turn(client, "s1", "hi")]
# 2 events — the no-id frame is invisible (no MalformedSseId crash).
assert len(events) == 2
assert isinstance(events[0], _Text)
assert events[0].content == "first"
assert isinstance(events[1], _Done)
class TestEmptyDataSkipped:
@respx.mock
async def test_empty_data_skipped(self) -> None:
+60 -6
View File
@@ -1,5 +1,7 @@
"""Tests for ratatoskr.tier3 per docs/contracts/issues/15.contract.md."""
from pathlib import Path
import httpx
import pytest
import respx
@@ -315,12 +317,29 @@ class TestDeleteAgent:
assert exc.value.status == 500
@pytest.fixture
def _isolated_local_agents(
tmp_path: "Path", monkeypatch: pytest.MonkeyPatch
) -> "Path":
"""Isolate the v0.8.0 local-tier-3 index from the operator's real file."""
path = tmp_path / "local_agents.json"
monkeypatch.setenv("RATATOSKR_LOCAL_AGENTS", str(path))
return path
class TestCli:
@respx.mock
def test_cli_define_happy(
self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
self,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
_isolated_local_agents: "Path",
) -> None:
"""cli_define_happy [happy]: argv → 201 mock → stdout confirmation."""
"""cli_define_happy [happy]: argv → 201 mock → stdout confirmation;
local index updated with the new entry (v0.8.0 hook).
"""
from ratatoskr.local_agents import load_local_agents
monkeypatch.setenv("WORLDTREE_API_URL", "https://w.example")
monkeypatch.setenv("WORLDTREE_API_KEY", "k")
respx.post("https://w.example/agents/define").mock(
@@ -335,12 +354,24 @@ class TestCli:
out = capsys.readouterr()
assert rc == 0
assert out.out.strip() == "defined ratatoskr:wizard (qwen3.6-35-a3b)"
# v0.8.0: local index now has the new entry.
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].agent_id == "ratatoskr:wizard"
assert entries[0].model == "qwen3.6-35-a3b"
@respx.mock
def test_cli_patch_happy(
self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
self,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
_isolated_local_agents: "Path",
) -> None:
"""cli_patch_happy [happy]: argv → 200 mock → stdout confirmation."""
"""cli_patch_happy [happy]: argv → 200 mock → stdout confirmation;
local index refreshed with the post-patch state.
"""
from ratatoskr.local_agents import load_local_agents
monkeypatch.setenv("WORLDTREE_API_URL", "https://w.example")
monkeypatch.setenv("WORLDTREE_API_KEY", "k")
respx.patch("https://w.example/agents/ratatoskr:wizard").mock(
@@ -350,12 +381,34 @@ class TestCli:
out = capsys.readouterr()
assert rc == 0
assert out.out.strip() == "patched ratatoskr:wizard"
entries = load_local_agents()
assert len(entries) == 1
assert entries[0].agent_id == "ratatoskr:wizard"
@respx.mock
def test_cli_delete_happy(
self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
self,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
_isolated_local_agents: "Path",
) -> None:
"""cli_delete_happy [happy]: argv → 204 mock → stdout confirmation."""
"""cli_delete_happy [happy]: argv → 204 mock → stdout confirmation;
local index entry removed (v0.8.0 hook).
"""
from ratatoskr.local_agents import (
LocalAgentEntry,
add_local_agent,
load_local_agents,
)
# Pre-populate so we can verify removal.
add_local_agent(LocalAgentEntry(
agent_id="ratatoskr:wizard",
agent_name="wizard",
model="m",
description="d",
defined_at="t",
))
monkeypatch.setenv("WORLDTREE_API_URL", "https://w.example")
monkeypatch.setenv("WORLDTREE_API_KEY", "k")
respx.delete("https://w.example/agents/ratatoskr:wizard").mock(
@@ -365,6 +418,7 @@ class TestCli:
out = capsys.readouterr()
assert rc == 0
assert out.out.strip() == "deleted ratatoskr:wizard"
assert load_local_agents() == []
def test_cli_missing_auth(
self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
+180 -94
View File
@@ -1,5 +1,6 @@
"""Tests for ratatoskr.tui per docs/contracts/issues/4.contract.md."""
from pathlib import Path
from unittest.mock import MagicMock
import httpx
@@ -115,10 +116,11 @@ SID = SseId(42, 5)
class TestTuiPresenterState:
"""Tests for the new TuiPresenterState — per issue #12 contract."""
def test_thinking_streams_into_thinking_log(self) -> None:
"""thinking_streams_into_thinking_log [happy,tracer, v0.6.5]:
3 Thinking deltas → thinking_log gets Rule(start) + 3 delta lines.
Transcript untouched; no thinking-current Static involved.
def test_thinking_coalesces_until_newline(self) -> None:
"""thinking_coalesces_until_newline [happy,tracer, v0.7.1]:
Per-token deltas accumulate in the buffer; flush only on `\\n`.
Three short token-shaped deltas without `\\n` → thinking_log gets
ONLY Rule(start); content stays buffered.
"""
from rich.rule import Rule
@@ -127,30 +129,50 @@ class TestTuiPresenterState:
log = MagicMock()
thinking_log = MagicMock()
state = TuiPresenterState()
for chunk in ("a", "b", "c"):
for chunk in ("Let", " me", " think"):
state.render(
Thinking(sse_id=SID, content=chunk),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(),
thinking_log=thinking_log,
raw=False,
)
writes = [c[0][0] for c in thinking_log.write.call_args_list]
# 1 Rule(start) + 3 content lines = 4 writes
assert len(writes) == 4
# Only Rule(start) content stays buffered (no `\n` seen).
assert len(writes) == 1
assert isinstance(writes[0], Rule)
assert writes[1] == "a"
assert writes[2] == "b"
assert writes[3] == "c"
# Transcript untouched during thinking streaming.
assert state.thinking_chunk_buffer == "Let me think"
assert log.write.call_count == 0
def test_thinking_flushes_on_newline(self) -> None:
"""thinking_flushes_on_newline [happy, v0.7.1]:
Delta carrying `\\n` flushes the accumulated buffer as ONE line.
"""
from ratatoskr.tui import TuiPresenterState
thinking_log = MagicMock()
state = TuiPresenterState()
for chunk in ("Hello", " world", "\n"):
state.render(
Thinking(sse_id=SID, content=chunk),
log=MagicMock(),
tools_log=MagicMock(),
debug_log=MagicMock(),
thinking_log=thinking_log,
raw=False,
)
writes = [c[0][0] for c in thinking_log.write.call_args_list]
# Rule(start) + "Hello world" (one coalesced line) = 2 writes
assert len(writes) == 2
assert writes[1] == "Hello world"
assert state.thinking_chunk_buffer == ""
def test_thinking_closes_to_thinking_log(self) -> None:
"""thinking_closes_to_thinking_log [happy, v0.6.5]: 2x Thinking + WorkerPhase →
thinking_log gets Rule(start) + 2 delta lines + Rule(end); debug_log gets
the worker_phase line; transcript untouched.
"""thinking_closes_to_thinking_log [happy, v0.7.1]: 2x Thinking + WorkerPhase →
v0.7.1 coalesces "a"+"b" into one buffered string; the close flushes
"ab" as a single line before Rule(end). Result: Rule(start) + "ab" +
Rule(end) = 3 writes. debug_log gets worker_phase; transcript untouched.
"""
from rich.rule import Rule
@@ -166,7 +188,6 @@ class TestTuiPresenterState:
log=log,
tools_log=MagicMock(),
debug_log=debug_log,
current_text=MagicMock(),
thinking_log=thinking_log,
raw=False,
)
@@ -175,17 +196,15 @@ class TestTuiPresenterState:
log=log,
tools_log=MagicMock(),
debug_log=debug_log,
current_text=MagicMock(),
thinking_log=thinking_log,
raw=False,
)
thinking_writes = [c[0][0] for c in thinking_log.write.call_args_list]
# 1 Rule(start) + 2 delta lines + 1 Rule(end) = 4 writes
assert len(thinking_writes) == 4
# v0.7.1: 1 Rule(start) + 1 coalesced "ab" tail-flush + 1 Rule(end) = 3 writes
assert len(thinking_writes) == 3
assert isinstance(thinking_writes[0], Rule)
assert thinking_writes[1] == "a"
assert thinking_writes[2] == "b"
assert isinstance(thinking_writes[3], Rule)
assert thinking_writes[1] == "ab"
assert isinstance(thinking_writes[2], Rule)
# worker_phase still goes to debug_log; transcript untouched.
assert "· worker_phase:" in _text_of(debug_log.write.call_args_list[-1][0][0])
assert not log.write.called
@@ -194,10 +213,12 @@ class TestTuiPresenterState:
# and test_thinking_widget_visibility_lifecycle deleted (no longer apply).
def test_multiple_thinking_runs_each_get_thinking_log_section(self) -> None:
"""multiple_thinking_runs_each_get_section [scenario, v0.6.5]:
"""multiple_thinking_runs_each_get_section [scenario, v0.8.1]:
Thinking → Text → Thinking → Done → TWO start/end Rule pairs in
thinking_log, each wrapping their delta lines. Text goes to
current_text (buffered). Transcript: [done] + Markdown body.
thinking_log (deltas coalesced into tail-flushes per run).
Text deltas now stream into the transcript via coalesce-on-newline
(no current-text Static); "hi" with no `\\n` stays buffered until
Done's tail-flush.
"""
from rich.rule import Rule
@@ -205,7 +226,6 @@ class TestTuiPresenterState:
log = MagicMock()
thinking_log = MagicMock()
current_text = MagicMock()
state = TuiPresenterState()
for evt in (
Thinking(sse_id=SID, content="first"),
@@ -215,25 +235,24 @@ class TestTuiPresenterState:
state.render(
evt, log=log,
tools_log=MagicMock(), debug_log=MagicMock(),
current_text=current_text, thinking_log=thinking_log, raw=False,
thinking_log=thinking_log, raw=False,
)
state.render(
_make_tui_done(),
log=log,
tools_log=MagicMock(), debug_log=MagicMock(),
current_text=current_text, thinking_log=thinking_log, raw=False,
thinking_log=thinking_log, raw=False,
)
# v0.6.5: thinking_log holds 4 Rules (start + end per run) + 2 delta lines.
# thinking_log: 4 Rules (start+end per run) + 2 tail-flush strings.
thinking_writes = [c[0][0] for c in thinking_log.write.call_args_list]
rules = [w for w in thinking_writes if isinstance(w, Rule)]
delta_strs = [w for w in thinking_writes if isinstance(w, str)]
assert len(rules) == 4, f"expected 4 Rules (2 start + 2 end), got {len(rules)}"
assert "first" in delta_strs
assert "second" in delta_strs
# Text "hi" went to current_text (buffered), not the transcript directly.
current_text.update.assert_any_call("hi")
# Transcript: [done] label + Markdown(response) (raw=False).
# v0.8.1: Text "hi" flushes as a line in transcript on Done.
log_writes = [_text_of(c[0][0]) for c in log.write.call_args_list]
assert "hi" in log_writes
assert any(w.startswith("[done]") for w in log_writes if isinstance(w, str))
def test_render_exception_fallback(self) -> None:
@@ -258,7 +277,6 @@ class TestTuiPresenterState:
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(),
thinking_log=thinking_log,
raw=False,
)
@@ -278,7 +296,6 @@ class TestTuiPresenterState:
log=MagicMock(),
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(),
thinking_log=MagicMock(),
raw=False,
)
@@ -300,8 +317,7 @@ class TestTuiPresenterState:
Thinking(sse_id=SID, content="partial"),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=thinking_log, raw=False,
debug_log=MagicMock(), thinking_log=thinking_log, raw=False,
)
state.render(
Cancelled(
@@ -309,8 +325,7 @@ class TestTuiPresenterState:
),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=thinking_log, raw=False,
debug_log=MagicMock(), thinking_log=thinking_log, raw=False,
)
# v0.6.5: streamed thinking + Rule(end) in thinking_log; [cancelled] in transcript.
log_writes = [_text_of(c[0][0]) for c in log.write.call_args_list]
@@ -318,11 +333,12 @@ class TestTuiPresenterState:
# thinking_log got at least Rule(start) + "partial" delta + Rule(end)
assert thinking_log.write.call_count >= 3
def test_done_renders_markdown_after_label(self) -> None:
"""done_renders_markdown_after_label [happy, v0.6.0]:
Text("hi") accumulates into current_text Static (buffered streaming);
Done(response="hi") with raw=False → [done] label + Rule + Markdown
in transcript. current_text cleared on terminal.
def test_done_flushes_tail_and_writes_label(self) -> None:
"""done_flushes_tail_and_writes_label [happy, v0.8.2]:
Text("hi") buffers in text_chunk_buffer (no `\\n`). Done flushes
"hi" tail to transcript, then writes [done] label. v0.8.2 drops
the post-Done Markdown body re-render — streamed text is the
canonical content (no double-print).
"""
from rich.markdown import Markdown
from rich.rule import Rule
@@ -330,34 +346,33 @@ class TestTuiPresenterState:
from ratatoskr.tui import TuiPresenterState
log = MagicMock()
current_text = MagicMock()
state = TuiPresenterState()
state.render(
Text(sse_id=SID, content="hi"),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=current_text,
thinking_log=MagicMock(),
raw=False,
)
# Text accumulated to current_text, NOT written to log.
current_text.update.assert_any_call("hi")
assert not log.write.called
assert state.text_chunk_buffer == "hi"
state.render(
_make_tui_done(),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=current_text,
thinking_log=MagicMock(),
raw=False,
)
# Done cleared current_text and wrote [done] label + Rule + Markdown.
current_text.update.assert_any_call("")
# On Done: tail flush "hi" + [done] label. No Markdown, no Rule.
writes = [c[0][0] for c in log.write.call_args_list]
assert "hi" in writes
assert any(_text_of(w).startswith("[done]") for w in writes)
assert any(isinstance(w, Rule) for w in writes)
assert any(isinstance(w, Markdown) for w in writes)
# v0.8.2: no post-Done re-render — no duplicate content.
assert not any(isinstance(w, Markdown) for w in writes)
assert not any(isinstance(w, Rule) for w in writes)
assert state.text_chunk_buffer == ""
def test_raw_flag_skips_markdown(self) -> None:
"""raw_flag_skips_markdown [trace]: raw=True → no Rule, no Markdown."""
@@ -372,15 +387,13 @@ class TestTuiPresenterState:
Text(sse_id=SID, content="hi"),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=MagicMock(), raw=True,
debug_log=MagicMock(), thinking_log=MagicMock(), raw=True,
)
state.render(
_make_tui_done(),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=MagicMock(), raw=True,
debug_log=MagicMock(), thinking_log=MagicMock(), raw=True,
)
writes = [c[0][0] for c in log.write.call_args_list]
assert not any(isinstance(w, Rule) for w in writes)
@@ -402,8 +415,7 @@ class TestTuiPresenterState:
WorkerPhase(sse_id=SID, phase="streaming", turn_id=42),
log=log,
tools_log=MagicMock(),
debug_log=debug_log,
current_text=MagicMock(), thinking_log=MagicMock(), raw=False,
debug_log=debug_log, thinking_log=MagicMock(), raw=False,
)
# v0.5.0: WorkerPhase routes to debug_log, NOT transcript.
assert not log.write.called
@@ -438,8 +450,7 @@ class TestTuiPresenterState:
ToolStart(sse_id=SID, name="read_file", arguments={"path": "/x"}),
log=log,
tools_log=tools_log,
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=MagicMock(), raw=False,
debug_log=MagicMock(), thinking_log=MagicMock(), raw=False,
)
# INV-014: write went to tools_log
assert tools_log.write.called
@@ -458,56 +469,55 @@ class TestTuiPresenterState:
ToolResult(sse_id=SID, name="read_file", result="ok", duration_ms=12),
log=log,
tools_log=tools_log,
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=MagicMock(), raw=False,
debug_log=MagicMock(), thinking_log=MagicMock(), raw=False,
)
assert tools_log.write.called
assert _text_of(tools_log.write.call_args[0][0]).startswith("· tool_result:")
assert not log.write.called
def test_text_event_buffers_into_current_text(self) -> None:
"""text_event_buffers_into_current_text [v0.6.0]: Text → current_text Static
(accumulated), NOT log or tools_log. Streaming UX fix — no per-token spam.
def test_text_event_buffers_until_newline(self) -> None:
"""text_event_buffers_until_newline [v0.8.1]: Text deltas without
`\\n` accumulate in text_chunk_buffer; no log write yet.
"""
from ratatoskr.tui import TuiPresenterState
log = MagicMock()
tools_log = MagicMock()
current_text = MagicMock()
state = TuiPresenterState()
state.render(
Text(sse_id=SID, content="hello"),
log=log,
tools_log=tools_log,
debug_log=MagicMock(),
current_text=current_text,
thinking_log=MagicMock(),
raw=False,
)
current_text.update.assert_called_once_with("hello")
# v0.8.1: buffered, not written until `\n` or Done.
assert state.text_chunk_buffer == "hello"
assert not log.write.called
assert not tools_log.write.called
def test_text_deltas_accumulate(self) -> None:
"""text_deltas_accumulate [v0.6.0]: multiple Text deltas → current_text shows
concatenated content, NOT separate per-delta lines.
def test_text_flushes_on_newline(self) -> None:
"""text_flushes_on_newline [v0.8.1]: a delta carrying `\\n` flushes
the accumulated buffer as ONE line to log (transcript).
"""
from ratatoskr.tui import TuiPresenterState
current_text = MagicMock()
log = MagicMock()
state = TuiPresenterState()
for tok in ("Hel", "lo", " ", "world"):
for tok in ("Hel", "lo", " ", "world", "\n"):
state.render(
Text(sse_id=SID, content=tok),
log=MagicMock(),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=current_text,
thinking_log=MagicMock(),
raw=False,
)
# Final update reflects the full concatenation.
assert current_text.update.call_args_list[-1][0][0] == "Hello world"
writes = [c[0][0] for c in log.write.call_args_list]
# "Hello world" coalesces to ONE log entry.
assert writes == ["Hello world"]
assert state.text_chunk_buffer == ""
def test_duration_format_seconds(self) -> None:
"""duration_format_seconds [trace]: Done(duration_ms=5467) → label has "duration=5.5s"."""
@@ -519,8 +529,7 @@ class TestTuiPresenterState:
_make_tui_done(duration_ms=5467),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=MagicMock(), raw=True,
debug_log=MagicMock(), thinking_log=MagicMock(), raw=True,
)
done_line = next(
_text_of(c[0][0])
@@ -546,8 +555,7 @@ class TestTuiPresenterState:
_make_tui_done(usage=usage),
log=log,
tools_log=MagicMock(),
debug_log=MagicMock(),
current_text=MagicMock(), thinking_log=MagicMock(), raw=True,
debug_log=MagicMock(), thinking_log=MagicMock(), raw=True,
)
done_line = next(
_text_of(c[0][0])
@@ -834,7 +842,8 @@ class TestLayoutShape:
log=log,
tools_log=app.query_one("#tools-log", RichLog),
debug_log=app.query_one("#debug-log", RichLog),
current_text=MagicMock(), thinking_log=MagicMock(), raw=True,
thinking_log=MagicMock(),
raw=True,
)
done = next(
c for c in seen
@@ -1051,10 +1060,12 @@ async def _submit_and_wait(app: RatatoskrApp, pilot, content: str) -> None:
class TestStreamTurnWorker:
@respx.mock
async def test_happy_text_done_renders_markdown(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""happy_text_done_renders_markdown [happy,tracer, v0.6.0]:
Text deltas go to current_text (not transcript); on Done, transcript
gets turn-header Rule, [done] label, post-Done Rule + Markdown body.
async def test_happy_text_done_no_double_print(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""happy_text_done_no_double_print [happy,tracer, v0.8.2]:
Text("hello") buffers; on Done, "hello" flushes as tail to transcript
+ [done] label. v0.8.2 drops the post-Done Markdown body re-render
(was double-printing the response — streamed text + Markdown twice).
Only the turn-header Rule remains in the transcript.
"""
stream = _sse_chunk("42:1", {"type": "text", "content": "hello"}) + _sse_chunk(
"42:2", _DONE_BODY
@@ -1070,16 +1081,17 @@ class TestStreamTurnWorker:
await pilot.pause()
await _submit_and_wait(app, pilot, "hi")
assert app.state == "idle"
# v0.6.0: Text("hello") goes to current_text Static, NOT log.
# writes spy captures RichLog.write only, so "hello" SHOULD NOT appear.
from rich.markdown import Markdown
from rich.rule import Rule
assert not any(w == "hello" for w in writes)
# "hello" appears as a tail-flush; [done] label fires.
assert any(w == "hello" for w in writes)
assert any("[done]" in str(w) for w in writes)
# Post-Done: Markdown body + Rule + turn-header Rule all present.
assert any(isinstance(w, Markdown) for w in writes)
assert any(isinstance(w, Rule) for w in writes)
# v0.8.2: NO Markdown body re-render (was the duplicate).
assert not any(isinstance(w, Markdown) for w in writes)
# The turn-header Rule is written to all 4 panes; we still expect
# SOME Rules in the spy (one per pane), but NOT the post-Done
# separator Rule that pre-v0.8.2 wrote.
# We rely on _spy_writes counting turn-header Rules only.
@respx.mock
async def test_raw_flag_skips_markdown_render(self, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -2099,6 +2111,72 @@ class TestResolveThenRunWithPicker:
assert agents_route.call_count == 0
assert sessions_route.call_count == 1
@respx.mock
def test_picker_merges_local_tier3_agents(
self,
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
"""picker_merges_local_tier3_agents [v0.8.0]: local index entries
appear in the picker's agent list alongside remote agents."""
from ratatoskr.local_agents import LocalAgentEntry, add_local_agent
# Isolate the local index in a tmp file.
monkeypatch.setenv(
"RATATOSKR_LOCAL_AGENTS", str(tmp_path / "local_agents.json")
)
add_local_agent(LocalAgentEntry(
agent_id="ratatoskr:wizard",
agent_name="wizard",
model="qwen3.6-35-a3b",
description="(tier 3) test wizard",
defined_at="2026-05-25T00:00:00+00:00",
))
respx.get("https://w.example/agents").mock(
return_value=httpx.Response(200, json=_AGENTS_RESP)
)
respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(201, json=_CREATE_OK_RESP)
)
from ratatoskr.tui import AgentPickerApp
captured: list = []
async def capture_picker_init(self, *a, **kw):
captured.append(list(self.agents))
return "mimir" # auto-pick something so the rest succeeds
# Patch __init__ to capture the agent list passed to the picker.
orig_init = AgentPickerApp.__init__
def init_spy(self, agents):
captured.append(list(agents))
orig_init(self, agents)
monkeypatch.setattr(AgentPickerApp, "__init__", init_spy)
async def picker_returns_mimir(self):
return "mimir"
monkeypatch.setattr(AgentPickerApp, "run_async", picker_returns_mimir)
async def fake_main(self, *a, **kw):
return 0
monkeypatch.setattr(RatatoskrApp, "run_async", fake_main)
from ratatoskr.tui import run_tui
rc = run_tui(_args_new_no_agent())
assert rc == 0
# The local tier-3 agent should appear in the picker's agents list.
assert captured, "AgentPickerApp.__init__ was never called"
agent_ids = {a.agent_id for a in captured[0]}
assert "ratatoskr:wizard" in agent_ids
# Plus the remote agents.
assert "mimir" in agent_ids
assert "lofn" in agent_ids
@respx.mock
def test_picker_skipped_when_session_mode(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""picker_skipped_when_session_mode: --session s-1 → no list_agents, no create_session."""
@@ -2165,8 +2243,16 @@ class TestResolveThenRunWithPicker:
self,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
tmp_path: Path,
) -> None:
"""list_agents returns [] → stderr [no_agents]; exit 13; picker NOT opened."""
"""list_agents returns [] AND no local tier-3 entries → stderr
[no_agents]; exit 13; picker NOT opened. Isolate
$RATATOSKR_LOCAL_AGENTS so the operator's real local index
doesn't merge in and turn this into a non-empty list."""
# v0.8.0 isolation: point local agents at an empty tmp file.
monkeypatch.setenv(
"RATATOSKR_LOCAL_AGENTS", str(tmp_path / "empty_local_agents.json")
)
respx.get("https://w.example/agents").mock(return_value=httpx.Response(200, json=[]))
from ratatoskr.tui import AgentPickerApp
Generated
+1 -1
View File
@@ -968,7 +968,7 @@ wheels = [
[[package]]
name = "ratatoskr"
version = "0.7.0"
version = "0.8.2"
source = { editable = "." }
dependencies = [
{ name = "httpx" },