804c2df6eb
Issue #6 (TUI startup error visibility): restructure run_tui lifecycle so pre-App.run() failures land on real stderr instead of getting eaten by the alt-screen teardown. New _resolve_then_run async helper opens the AsyncClient via async-with, does pre-flight session resolution, routes AgentNotFound / SessionApiFailed / network errors to sys.stderr (verbatim same labels + exit codes as cli._amain), then constructs RatatoskrApp with pre-resolved state and awaits app.run_async(). RatatoskrApp.__init__ signature widens to (args, *, session_id, agent_id, client) — all three required. on_mount narrows to identity-widget population; on_unmount becomes a no-op (client lifetime owned by run_tui's async-with). Issue #5 (--end-user-id for per-end-user agents): sessions.create_session gains keyword-only end_user_id kwarg with PRE-003 non-empty assertion; ParsedArgs.end_user_id field added (default None); --end-user-id flag with non-empty validation; _amain + _resolve_then_run thread it to their create_session calls. RATATOSKR_END_USER_ID env-var fallback (flag > env > None) per the post-2026-05-23 amendment; env.sh (gitignored) ships "ratatoskr-tui" as project-stable partition default. Worldtree-dev consumer-API follow-up (althing 01KSBARG2B8M): User-Agent header added (ratatoskr/<version> (vh@phasefinal.com), version pulled via importlib.metadata) to both AsyncClient constructions so server logs can distinguish ratatoskr traffic from other consumers. Volva code-review (2 rounds on #6) found 8 test-precision gaps + 1 PRE assertion drift, all Category 1 fixed: missing PRE-001 at _resolve_then_run entry; Rule separator assertions on markdown render; RichLog-write spy on empty submit; input-cleared + no-new-worker on cancelling busy; worker.cancel observation on three force-exit paths; on_unmount-no-close focused test (the prior client-lifetime test patched run_async so on_unmount was never exercised); happy --new resolve test verifying POST count + identity propagation. Issues #2/#3/#4/#5 contracts amended in-place to reflect: - create_session widened (PRE-003, body construction step, body shape POST) - ParsedArgs description + _parse_args STEPS + _amain create_session call + new TESTS for end_user_id + env-var fallback - _resolve_then_run STEPS + new TEST entries; on_mount narrowed; INV-007 amended for new client ownership - Post-#6 adjustment note on issue #5 (_resolve_then_run replaces on_mount as the threading site since #6 moved session resolution out of the alt-screen) 188 tests GREEN; ruff clean. Bumps to v0.1.0 — first minor release, the load-bearing reason is RatatoskrApp.__init__'s breaking signature change (additive end_user_id alone wouldn't have triggered a minor pre-v1.x). Files Gitea issues #9 (spec-pin refresh v0.19.0 → v0.22.1), #10 (track Worldtree #196 subject:{type,id} migration), #11 (AdminEvents pane auth prerequisite admin.events.read). Infra-ops pinged via althing for agents.call:lofn scope add (broker pattern; they forwarded to worldtree-dev because personal Worldtree exposes no public scope-mutation endpoint).
415 lines
17 KiB
Python
415 lines
17 KiB
Python
"""Tests for ratatoskr.sessions per docs/contracts/issues/2.contract.md."""
|
|
|
|
import httpx
|
|
import pytest
|
|
import respx
|
|
|
|
from ratatoskr.sessions import (
|
|
AgentNotFound,
|
|
InvalidCursor,
|
|
SessionApiFailed,
|
|
SessionPage,
|
|
create_session,
|
|
list_sessions,
|
|
)
|
|
|
|
|
|
class TestCreateSession:
|
|
@respx.mock
|
|
async def test_happy_create(self) -> None:
|
|
"""happy_create [happy,tracer]: full 201 body -> SessionInfo with create-origin defaults."""
|
|
respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
201,
|
|
json={
|
|
"session_id": "550e8400-e29b-41d4-a716-446655440000",
|
|
"agent_id": "mimir",
|
|
"message_count": 0,
|
|
"created_at": "2026-04-15T12:00:00+00:00",
|
|
"last_active": "2026-04-15T12:00:00+00:00",
|
|
"metadata": {},
|
|
},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
info = await create_session(client, "mimir")
|
|
assert info.session_id == "550e8400-e29b-41d4-a716-446655440000"
|
|
assert info.agent_id == "mimir"
|
|
assert info.created_at == "2026-04-15T12:00:00+00:00"
|
|
assert info.last_active == "2026-04-15T12:00:00+00:00"
|
|
assert info.metadata == {}
|
|
assert info.message_count == 0
|
|
# INV-001 create-origin fixed defaults
|
|
assert info.name is None
|
|
assert info.archived is False
|
|
assert info.tags == []
|
|
|
|
@respx.mock
|
|
async def test_happy_create_with_metadata(self) -> None:
|
|
"""happy_create_with_metadata: response carries metadata -> SessionInfo.metadata matches."""
|
|
respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
201,
|
|
json={
|
|
"session_id": "s1",
|
|
"agent_id": "mimir",
|
|
"message_count": 0,
|
|
"created_at": "2026-04-15T12:00:00+00:00",
|
|
"last_active": "2026-04-15T12:00:00+00:00",
|
|
"metadata": {"model": "glm5-turbo"},
|
|
},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
info = await create_session(client, "mimir")
|
|
assert info.metadata == {"model": "glm5-turbo"}
|
|
|
|
@respx.mock
|
|
async def test_request_body_shape(self) -> None:
|
|
"""request_body_shape [trace]: outbound JSON is exactly {"agent_id": <arg>}."""
|
|
import json as _json
|
|
|
|
route = respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
201,
|
|
json={
|
|
"session_id": "s1",
|
|
"agent_id": "mimir",
|
|
"message_count": 0,
|
|
"created_at": "2026-04-15T12:00:00+00:00",
|
|
"last_active": "2026-04-15T12:00:00+00:00",
|
|
"metadata": {},
|
|
},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
await create_session(client, "mimir")
|
|
body = _json.loads(route.calls[0].request.content)
|
|
assert body == {"agent_id": "mimir"}
|
|
|
|
@respx.mock
|
|
async def test_unknown_agent_id(self) -> None:
|
|
"""unknown_agent_id: 404 -> AgentNotFound(agent_id=<arg>)."""
|
|
respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(404, json={"error": "unknown_agent_id"})
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(AgentNotFound) as exc_info:
|
|
await create_session(client, "mimir")
|
|
assert exc_info.value.agent_id == "mimir"
|
|
|
|
@respx.mock
|
|
async def test_validation_failed(self) -> None:
|
|
"""validation_failed: 422 -> SessionApiFailed(status=422); body truncated."""
|
|
respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
422,
|
|
json={"error_code": "validation_failed", "message": "missing agent_id"},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(SessionApiFailed) as exc_info:
|
|
await create_session(client, "mimir")
|
|
assert exc_info.value.status == 422
|
|
assert len(exc_info.value.body) <= 1024
|
|
|
|
@respx.mock
|
|
async def test_unexpected_status_truncates(self) -> None:
|
|
"""unexpected_status_truncates: 500 + 5000-byte body -> SessionApiFailed; body == 1024."""
|
|
big = b"x" * 5000
|
|
respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(500, content=big)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(SessionApiFailed) as exc_info:
|
|
await create_session(client, "mimir")
|
|
assert exc_info.value.status == 500
|
|
assert exc_info.value.body == big[:1024]
|
|
|
|
@respx.mock
|
|
async def test_empty_agent_id(self) -> None:
|
|
"""empty_agent_id [adversarial]: '' -> AssertionError; no HTTP issued."""
|
|
route = respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(201, content=b"{}")
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(AssertionError):
|
|
await create_session(client, "")
|
|
assert route.call_count == 0
|
|
|
|
@respx.mock
|
|
async def test_happy_create_with_end_user_id(self) -> None:
|
|
"""happy_create_with_end_user_id [happy]: body carries both keys (issue #5)."""
|
|
import json as _json
|
|
|
|
route = respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
201,
|
|
json={
|
|
"session_id": "s-new",
|
|
"agent_id": "lofn",
|
|
"message_count": 0,
|
|
"created_at": "2026-05-22T12:00:00+00:00",
|
|
"last_active": "2026-05-22T12:00:00+00:00",
|
|
"metadata": {},
|
|
},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
info = await create_session(client, "lofn", end_user_id="alice")
|
|
body = _json.loads(route.calls[0].request.content)
|
|
# INV: body MUST be exactly {"agent_id": ..., "end_user_id": ...} — byte-for-byte
|
|
assert body == {"agent_id": "lofn", "end_user_id": "alice"}
|
|
assert info.session_id == "s-new"
|
|
assert info.agent_id == "lofn"
|
|
|
|
@respx.mock
|
|
async def test_default_omits_end_user_id(self) -> None:
|
|
"""default_omits_end_user_id [trace]: omit kwarg → body has no end_user_id (INV-002)."""
|
|
import json as _json
|
|
|
|
route = respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
201,
|
|
json={
|
|
"session_id": "s-new",
|
|
"agent_id": "mimir",
|
|
"message_count": 0,
|
|
"created_at": "2026-05-22T12:00:00+00:00",
|
|
"last_active": "2026-05-22T12:00:00+00:00",
|
|
"metadata": {},
|
|
},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
await create_session(client, "mimir")
|
|
body = _json.loads(route.calls[0].request.content)
|
|
# Exact equality — no end_user_id key in the body when the kwarg is omitted
|
|
assert body == {"agent_id": "mimir"}
|
|
assert "end_user_id" not in body
|
|
|
|
@respx.mock
|
|
async def test_empty_end_user_id(self) -> None:
|
|
"""empty_end_user_id [adversarial]: '' → AssertionError before HTTP (PRE-003)."""
|
|
route = respx.post("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(201, content=b"{}")
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(AssertionError):
|
|
await create_session(client, "mimir", end_user_id="")
|
|
assert route.call_count == 0
|
|
|
|
|
|
def _list_item(
|
|
*,
|
|
session_id: str = "s1",
|
|
agent_id: str = "mimir",
|
|
created_at: str = "2026-04-15T12:00:00+00:00",
|
|
last_active: str = "2026-04-15T12:05:00+00:00",
|
|
metadata: dict[str, object] | None = None,
|
|
name: str | None = "Research session",
|
|
archived: bool = False,
|
|
tags: list[str] | None = None,
|
|
) -> dict[str, object]:
|
|
"""Build a GET /sessions list-item body for tests."""
|
|
item: dict[str, object] = {
|
|
"session_id": session_id,
|
|
"agent_id": agent_id,
|
|
"created_at": created_at,
|
|
"last_active": last_active,
|
|
"metadata": metadata if metadata is not None else {},
|
|
"name": name,
|
|
"archived": archived,
|
|
"tags": tags if tags is not None else ["work"],
|
|
}
|
|
return item
|
|
|
|
|
|
class TestListSessions:
|
|
@respx.mock
|
|
async def test_explicit_null_list_defaults(self) -> None:
|
|
"""INV-002: explicit-null archived -> False; explicit-null tags -> []."""
|
|
raw_item = {
|
|
"session_id": "s1",
|
|
"agent_id": "mimir",
|
|
"created_at": "2026-04-15T12:00:00+00:00",
|
|
"last_active": "2026-04-15T12:05:00+00:00",
|
|
"metadata": {},
|
|
"name": None,
|
|
"archived": None,
|
|
"tags": None,
|
|
}
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
200, json={"items": [raw_item], "next_cursor": None}
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
page = await list_sessions(client)
|
|
info = page.items[0]
|
|
assert info.archived is False, "explicit-null archived must default to False"
|
|
assert info.tags == [], "explicit-null tags must default to []"
|
|
assert info.name is None
|
|
|
|
@respx.mock
|
|
async def test_happy_first_page(self) -> None:
|
|
"""happy_first_page [happy,tracer]: one item + next_cursor -> SessionPage shape."""
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
200,
|
|
json={
|
|
"items": [_list_item()],
|
|
"next_cursor": "v1.eyJhYmMifQ",
|
|
},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
page = await list_sessions(client)
|
|
assert isinstance(page, SessionPage)
|
|
assert len(page.items) == 1
|
|
assert page.next_cursor == "v1.eyJhYmMifQ"
|
|
info = page.items[0]
|
|
assert info.session_id == "s1"
|
|
assert info.message_count is None # INV-002: not in list response
|
|
assert info.name == "Research session"
|
|
assert info.archived is False
|
|
assert info.tags == ["work"]
|
|
|
|
@respx.mock
|
|
async def test_happy_last_page(self) -> None:
|
|
"""happy_last_page: next_cursor=null -> SessionPage(next_cursor=None)."""
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
200,
|
|
json={"items": [_list_item()], "next_cursor": None},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
page = await list_sessions(client)
|
|
assert page.next_cursor is None
|
|
|
|
@respx.mock
|
|
async def test_empty_results(self) -> None:
|
|
"""empty_results: {items: [], next_cursor: null} -> SessionPage([], None)."""
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(200, json={"items": [], "next_cursor": None})
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
page = await list_sessions(client)
|
|
assert page == SessionPage(items=[], next_cursor=None)
|
|
|
|
@respx.mock
|
|
async def test_include_archived_query(self) -> None:
|
|
"""include_archived_query: True -> has param; default -> NO param at all."""
|
|
route = respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
200, json={"items": [], "next_cursor": None}
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
await list_sessions(client, include_archived=True)
|
|
await list_sessions(client) # default
|
|
url_with = str(route.calls[0].request.url)
|
|
url_default = str(route.calls[1].request.url)
|
|
assert "include_archived=true" in url_with
|
|
assert "include_archived" not in url_default
|
|
|
|
@respx.mock
|
|
async def test_cursor_threaded(self) -> None:
|
|
"""cursor_threaded: cursor=opaque -> URL has cursor=opaque."""
|
|
route = respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
200, json={"items": [], "next_cursor": None}
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
await list_sessions(client, cursor="opaque-from-prev-page")
|
|
assert "cursor=opaque-from-prev-page" in str(route.calls[0].request.url)
|
|
|
|
@respx.mock
|
|
async def test_limit_query(self) -> None:
|
|
"""limit_query: limit=10 -> URL has limit=10."""
|
|
route = respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
200, json={"items": [], "next_cursor": None}
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
await list_sessions(client, limit=10)
|
|
assert "limit=10" in str(route.calls[0].request.url)
|
|
|
|
@respx.mock
|
|
async def test_invalid_cursor_server(self) -> None:
|
|
"""invalid_cursor_server: 422 cursor_invalid -> InvalidCursor(raw=<passed cursor>)."""
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
422,
|
|
json={"error_code": "cursor_invalid", "message": "bad cursor"},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(InvalidCursor) as exc_info:
|
|
await list_sessions(client, cursor="bogus")
|
|
assert exc_info.value.raw == "bogus"
|
|
|
|
@respx.mock
|
|
async def test_other_validation_failed(self) -> None:
|
|
"""other_validation_failed: 422 other error_code -> SessionApiFailed(422); truncated."""
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(
|
|
422,
|
|
json={"error_code": "validation_failed", "message": "limit out of range"},
|
|
)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(SessionApiFailed) as exc_info:
|
|
await list_sessions(client)
|
|
assert exc_info.value.status == 422
|
|
assert len(exc_info.value.body) <= 1024
|
|
|
|
@respx.mock
|
|
async def test_unexpected_status_truncates(self) -> None:
|
|
"""unexpected_status_truncates: 500 + 5000-byte body -> SessionApiFailed; body == 1024."""
|
|
big = b"x" * 5000
|
|
respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(500, content=big)
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(SessionApiFailed) as exc_info:
|
|
await list_sessions(client)
|
|
assert exc_info.value.status == 500
|
|
assert exc_info.value.body == big[:1024]
|
|
|
|
@respx.mock
|
|
async def test_limit_below_one(self) -> None:
|
|
"""limit_below_one [adversarial]: limit=0 -> AssertionError; no HTTP."""
|
|
route = respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(200, json={"items": [], "next_cursor": None})
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(AssertionError):
|
|
await list_sessions(client, limit=0)
|
|
assert route.call_count == 0
|
|
|
|
@respx.mock
|
|
async def test_limit_above_max(self) -> None:
|
|
"""limit_above_max [adversarial]: limit=300 -> AssertionError; no HTTP."""
|
|
route = respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(200, json={"items": [], "next_cursor": None})
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(AssertionError):
|
|
await list_sessions(client, limit=300)
|
|
assert route.call_count == 0
|
|
|
|
@respx.mock
|
|
async def test_empty_cursor(self) -> None:
|
|
"""empty_cursor [adversarial]: cursor='' -> AssertionError; no HTTP."""
|
|
route = respx.get("https://w.example/sessions").mock(
|
|
return_value=httpx.Response(200, json={"items": [], "next_cursor": None})
|
|
)
|
|
async with httpx.AsyncClient(base_url="https://w.example") as client:
|
|
with pytest.raises(AssertionError):
|
|
await list_sessions(client, cursor="")
|
|
assert route.call_count == 0
|