From 3887f2e02b84d60b05544294b85a38a08facb3c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:45:06 +0000 Subject: [PATCH 1/3] Normalize malformed response failures across the remaining typed parsers Todos, room todos, skills, groups, rooms topics/messages/roster/app tiles, artifacts, note comments, image details, blog, chat send, sign-in and whoami parsers now raise ApiError (status 200) naming the shape or field instead of leaking KeyError/TypeError. Lists a poller reads (groups, group messages, artifacts, todos) skip and count a bad row; other lists fail whole. Optional fields keep their defaults. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QNDehAurHo1CzCzisi6nYx --- src/pepper_cli/api_client.py | 752 ++++++++++++--------- src/pepper_cli/tui/poller.py | 4 +- tests/test_api_client_malformed_parsers.py | 352 ++++++++++ tests/test_api_client_room_skills.py | 2 +- 4 files changed, 793 insertions(+), 317 deletions(-) create mode 100644 tests/test_api_client_malformed_parsers.py diff --git a/src/pepper_cli/api_client.py b/src/pepper_cli/api_client.py index d03cf1d..b6607e7 100644 --- a/src/pepper_cli/api_client.py +++ b/src/pepper_cli/api_client.py @@ -395,12 +395,14 @@ class SkillDetail: def _skill_detail_from_dict(row: dict) -> SkillDetail: + what = "skill" + row = _wire_row(row, what) return SkillDetail( - name=row["name"], - description=row["description"], - body=row["body"], + name=_wire_get(row, "name", what, str), + description=_wire_get(row, "description", what, str), + body=_wire_get(row, "body", what, str), model=row.get("model"), - toolsets=tuple(row.get("toolsets") or ()), + toolsets=tuple(_optional_list(row, "toolsets", what)), max_tool_rounds=row.get("max_tool_rounds"), builtin=bool(row.get("builtin", False)), ) @@ -450,17 +452,29 @@ class RoomSkillDetail: skill: SkillDetail +def _skill_summary_from_dict(row: dict) -> SkillSummary: + what = "skill" + row = _wire_row(row, what) + return SkillSummary( + name=_wire_get(row, "name", what, str), + description=_wire_get(row, "description", what, str), + builtin=bool(row.get("builtin", False)), + ) + + def _room_skill_from_dict(row: dict) -> RoomSkill: + what = "room skill" + row = _wire_row(row, what) return RoomSkill( - id=row["id"], - name=row["name"], - description=row["description"], + id=_wire_get(row, "id", what, str), + name=_wire_get(row, "name", what, str), + description=_wire_get(row, "description", what, str), granted_by=row.get("granted_by"), owner_is_you=bool(row.get("owner_is_you", False)), builtin=bool(row.get("builtin", False)), - toolsets=tuple(row.get("toolsets") or ()), + toolsets=tuple(_optional_list(row, "toolsets", what)), state=row.get("state", "active"), - ungrantable_toolsets=tuple(row.get("ungrantable_toolsets") or ()), + ungrantable_toolsets=tuple(_optional_list(row, "ungrantable_toolsets", what)), can_revoke=bool(row.get("can_revoke", False)), ) @@ -933,6 +947,17 @@ class RoomTodos: items: list[TodoEntry] +class TodoList(list[TodoEntry]): + """``GET /api/v1/todos``'s rows, plus ``skipped``: how many rows were left out because they + were malformed (only when the caller asked to skip them). A plain list otherwise.""" + + skipped: int = 0 + + def __init__(self, rows: list[TodoEntry] | None = None, *, skipped: int = 0) -> None: + super().__init__(rows or []) + self.skipped = skipped + + @dataclass(frozen=True) class RoomTodosList: """``GET /api/v1/todos/rooms``: the rooms with todos, and whether the list is partial.""" @@ -940,6 +965,8 @@ class RoomTodosList: rooms: list[RoomTodos] #: The server could not read the caller's rooms: ``rooms`` is empty, not "no todos". degraded: bool = False + #: Rooms or items the server sent that could not be read and were left out. + skipped: int = 0 # MIRROR: src/pepper/api/scheduled_tasks.py::TaskSummary @@ -1434,13 +1461,14 @@ def device_start( ) if resp.status_code >= 400: _raise_for_error(resp) - body = resp.json() + what = "device start response" + body = _wire_row(resp.json(), what) return DeviceStart( - device_code=SecretStr(body["device_code"]), - user_code=body["user_code"], - verification_url=body["verification_url"], - expires_in=body["expires_in"], - interval=body["interval"], + device_code=SecretStr(_wire_get(body, "device_code", what, str)), + user_code=_wire_get(body, "user_code", what, str), + verification_url=_wire_get(body, "verification_url", what, str), + expires_in=_wire_get(body, "expires_in", what, int), + interval=_wire_get(body, "interval", what, int), ) finally: if owns_client: @@ -1481,22 +1509,15 @@ def device_poll( return DevicePoll(status="slow_down", interval=interval) if resp.status_code >= 400: _raise_for_error(resp) - body = resp.json() + what = "device poll response" + body = _wire_row(resp.json(), what) status_value = body.get("status", "") if status_value == "approved": - user_row = body["user"] + user_row = _wire_row(_wire_get(body, "user", what), "device poll user") return DevicePoll( status="approved", - token=SecretStr(body["token"]), - user=Whoami( - user_id=user_row["user_id"], - email=user_row.get("email"), - display_name=user_row["display_name"], - timezone=user_row.get("timezone"), - merged_from=user_row.get("merged_from", []), - date_format=user_row.get("date_format", "mdy"), - time_format=user_row.get("time_format", "12h"), - ), + token=SecretStr(_wire_get(body, "token", what, str)), + user=_whoami_from(user_row, "device poll user", person_id=False), ) return DevicePoll(status=status_value) finally: @@ -1673,6 +1694,9 @@ class GroupList: archived_total: int groups: list[GroupSummary] = field(default_factory=list) features: tuple[str, ...] = () + #: Rooms the server sent that could not be read and were left out, so a poller can say the + #: list is partial rather than show it as complete. + skipped: int = 0 # MIRROR: src/pepper/api/groups.py::topic_messages @@ -1798,6 +1822,8 @@ class GroupMessagePage: messages: list[GroupMessage] = field(default_factory=list) next_before: str | None = None permalink_target_missing: bool = False + #: Messages that could not be read and were left out, so one bad row never hides the page. + skipped: int = 0 # MIRROR: src/pepper/api/groups.py::room_roster @@ -1832,16 +1858,20 @@ class GroupAppTile: def _group_card_from_dict(row: dict[str, Any]) -> GroupCard: - summary = row.get("summary") or {} + what = "group card" + row = _wire_row(row, what) + summary = row.get("summary") + if summary is not None and not isinstance(summary, dict): + raise _malformed(f"{what} field 'summary' has the wrong type", row) return GroupCard( kind=row.get("kind", "card"), - app_key=row["app_key"], - slug=row["slug"], - title=row["title"], - principal=row["principal"], - url=row["url"], + app_key=_wire_get(row, "app_key", what, str), + slug=_wire_get(row, "slug", what, str), + title=_wire_get(row, "title", what, str), + principal=_wire_get(row, "principal", what, str), + url=_wire_get(row, "url", what, str), view=row.get("view"), - summary_lines=list(summary.get("lines") or []), + summary_lines=_optional_list(summary or {}, "lines", what), ) @@ -1863,25 +1893,34 @@ def _mention_ids(raw: object) -> list[str]: def group_message_from_dict(row: dict[str, Any]) -> GroupMessage: """Parse one message. A free function so the page read and any later single-message read parse through one place and cannot drift.""" + what = "group message" + row = _wire_row(row, what) + required = { + **{ + k: _wire_get(row, k, what, str) + for k in ( + "id", + "display_name", + "initial", + "avatar_tint", + "raw_body", + "rendered_html", + "created_at", + "created_at_display", + "day_key", + "day_kicker", + "day_heading", + "day_label", + "quote_excerpt", + ) + }, + **{ + k: _wire_get(row, k, what, bool) + for k in ("is_pepper", "is_you", "is_deleted", "is_broken", "run_start") + }, + } return GroupMessage( - id=row["id"], - is_pepper=row["is_pepper"], - is_you=row["is_you"], - is_deleted=row["is_deleted"], - is_broken=row["is_broken"], - run_start=row["run_start"], - display_name=row["display_name"], - initial=row["initial"], - avatar_tint=row["avatar_tint"], - raw_body=row["raw_body"], - rendered_html=row["rendered_html"], - created_at=row["created_at"], - created_at_display=row["created_at_display"], - day_key=row["day_key"], - day_kicker=row["day_kicker"], - day_heading=row["day_heading"], - day_label=row["day_label"], - quote_excerpt=row["quote_excerpt"], + **required, picture_url=row.get("picture_url"), via_display_name=row.get("via_display_name"), is_bridged=bool(row.get("is_bridged", False)), @@ -1891,12 +1930,12 @@ def group_message_from_dict(row: dict[str, Any]) -> GroupMessage: is_edited=row.get("is_edited", False), edited_at=row.get("edited_at"), deleted_at=row.get("deleted_at"), - reactions=list(row.get("reactions") or []), - link_previews=list(row.get("link_previews") or []), - attachments=list(row.get("attachments") or []), - mention_names=list(row.get("mention_names") or []), + reactions=_optional_list(row, "reactions", what), + link_previews=_optional_list(row, "link_previews", what), + attachments=_optional_list(row, "attachments", what), + mention_names=_optional_list(row, "mention_names", what), quote=row.get("quote"), - cards=[_group_card_from_dict(c) for c in row.get("cards") or []], + cards=[_group_card_from_dict(c) for c in _optional_list(row, "cards", what)], is_permalink_target=row.get("is_permalink_target", False), author_person_id=row.get("author_person_id"), mentions=_mention_ids(row.get("mentions")), @@ -1909,35 +1948,73 @@ def group_message_from_dict(row: dict[str, Any]) -> GroupMessage: ) +def _roster_member_from_dict(row: dict[str, Any]) -> GroupRosterMember: + what = "group roster member" + row = _wire_row(row, what) + return GroupRosterMember( + person_id=_wire_get(row, "person_id", what, str), + display_name=_wire_get(row, "display_name", what, str), + picture_url=row.get("picture_url"), + is_pepper=row.get("is_pepper", False), + is_agent=bool(row.get("is_agent", False)), + ) + + +def _app_tile_from_dict(row: dict[str, Any]) -> GroupAppTile: + what = "group app tile" + row = _wire_row(row, what) + return GroupAppTile( + app_key=_wire_get(row, "app_key", what, str), + slug=_wire_get(row, "slug", what, str), + title=_wire_get(row, "title", what, str), + principal=_wire_get(row, "principal", what, str), + icon=row.get("icon"), + ) + + def _group_list_from_dict(body: dict[str, Any]) -> GroupList: + """The poller reads this on a timer, so a malformed room is left out and counted in + ``skipped`` rather than hiding every other room.""" + what = "group list" + body = _wire_row(body, what) + groups, skipped = _wire_rows( + _optional_list(body, "groups", what), "group", _group_summary_from_dict, skip_bad_rows=True + ) return GroupList( - enabled=body["enabled"], - degraded=body["degraded"], - total=body["total"], - archived_total=body["archived_total"], - groups=[_group_summary_from_dict(g) for g in body.get("groups") or []], - features=tuple(f for f in body.get("features") or () if isinstance(f, str)), + enabled=_wire_get(body, "enabled", what, bool), + degraded=_wire_get(body, "degraded", what, bool), + total=_wire_get(body, "total", what, int), + archived_total=_wire_get(body, "archived_total", what, int), + groups=groups, + features=tuple(f for f in _optional_list(body, "features", what) if isinstance(f, str)), + skipped=skipped, ) def _group_summary_from_dict(row: dict[str, Any]) -> GroupSummary: + what = "group" + row = _wire_row(row, what) return GroupSummary( - group_id=row["group_id"], - display_name=row["display_name"], - color=row["color"], - sub=row["sub"], - member_count=row["member_count"], - archived=row["archived"], - topics=[_group_topic_from_dict(t) for t in row.get("topics") or []], + group_id=_wire_get(row, "group_id", what, str), + display_name=_wire_get(row, "display_name", what, str), + color=_wire_get(row, "color", what, str), + sub=_wire_get(row, "sub", what, str), + member_count=_wire_get(row, "member_count", what, int), + archived=_wire_get(row, "archived", what, bool), + topics=_wire_rows( + _optional_list(row, "topics", what), "group topic", _group_topic_from_dict + )[0], mascot_url=mascot if isinstance(mascot := row.get("mascot_url"), str) else None, ) def _group_topic_from_dict(row: dict[str, Any]) -> GroupTopicSummary: + what = "group topic" + row = _wire_row(row, what) return GroupTopicSummary( - topic_id=row["topic_id"], - name=row["name"], - last_activity_at=row["last_activity_at"], + topic_id=_wire_get(row, "topic_id", what, str), + name=_wire_get(row, "name", what, str), + last_activity_at=_wire_get(row, "last_activity_at", what, str, nullable=True), dedicated_conversation=row.get("dedicated_conversation", False), archived_at=row.get("archived_at"), imported_history=row.get("imported_history", False), @@ -1994,6 +2071,14 @@ class ArtifactListResponse: items: list[ArtifactListItem] = field(default_factory=list) +@dataclass(frozen=True) +class ArtifactListPage(ArtifactListResponse): + """:class:`ArtifactListResponse` plus ``skipped``: rows that could not be read and were left + out (the notes pane polls this list). Not a server model, so not mirrored.""" + + skipped: int = 0 + + # The note-comment routes answer untyped JSON the server has not published in the vendored # snapshot yet, so these carry no contract marker; add one once the snapshot refresh lands. # They follow the prototype contract (GET/POST /api/v1/artifacts/{id}/comments, and @@ -2036,17 +2121,22 @@ class NoteComments: def _note_comment_from_dict(row: dict[str, Any]) -> NoteComment: + what = "note comment" + row = _wire_row(row, what) anchor = row.get("anchor") resolver = row.get("resolved_by") + author = row.get("author") + if author is not None and not isinstance(author, dict): + raise _malformed(f"{what} field 'author' has the wrong type", row) return NoteComment( - id=str(row["id"]), + id=str(_wire_get(row, "id", what, str, int)), body=str(row.get("body") or ""), - author=str((row.get("author") or {}).get("display_name") or ""), + author=str((author or {}).get("display_name") or ""), created_at=str(row.get("created_at") or ""), mentions=_mention_ids( [ {"person_id": m["id"]} if isinstance(m, dict) and "id" in m else m - for m in row.get("mentions") or [] + for m in _optional_list(row, "mentions", what) ] ), anchor=anchor if isinstance(anchor, dict) else None, @@ -2057,17 +2147,25 @@ def _note_comment_from_dict(row: dict[str, Any]) -> NoteComment: def _note_thread_from_dict(t: dict[str, Any]) -> NoteCommentThread: + what = "note comment thread" + t = _wire_row(t, what) position = t.get("position") return NoteCommentThread( - message=_note_comment_from_dict(t["message"]), + message=_note_comment_from_dict(_wire_get(t, "message", what, dict)), position=position if isinstance(position, dict) else None, detached=bool(t.get("detached", False)), - replies=[_note_comment_from_dict(r) for r in t.get("replies") or []], + replies=_wire_rows( + _optional_list(t, "replies", what), "note comment", _note_comment_from_dict + )[0], ) def _note_comments_from_dict(body: dict[str, Any]) -> NoteComments: - threads = [_note_thread_from_dict(t) for t in body.get("threads") or []] + what = "note comments response" + body = _wire_row(body, what) + threads = _wire_rows( + _optional_list(body, "threads", what), "note comment thread", _note_thread_from_dict + )[0] return NoteComments( artifact_id=str(body.get("artifact_id") or ""), group_id=body.get("group_id"), @@ -2100,10 +2198,12 @@ class ImageDetails: def _image_details_from_dict(body: dict[str, Any]) -> ImageDetails: + what = "image details response" + body = _wire_row(body, what) sources = body.get("sources") last_run = body.get("last_run") return ImageDetails( - id=str(body["id"]), + id=str(_wire_get(body, "id", what, str, int)), alt_text=body.get("alt_text") or "", title=body.get("title") or "", caption=body.get("caption") or "", @@ -2151,13 +2251,15 @@ class ArtifactDetail: def _artifact_list_item_from_dict(row: dict[str, Any]) -> ArtifactListItem: + what = "artifact list item" + row = _wire_row(row, what) return ArtifactListItem( - id=str(row["id"]), - name=row["name"], - kind=row["kind"], - updated_at=row["updated_at"], - etag=row["etag"], - labels=list(row.get("labels") or []), + id=str(_wire_get(row, "id", what, str, int)), + name=_wire_get(row, "name", what, str), + kind=_wire_get(row, "kind", what, str), + updated_at=_wire_get(row, "updated_at", what, str), + etag=_wire_get(row, "etag", what, str), + labels=_optional_list(row, "labels", what), summary=row.get("summary"), ) @@ -2172,15 +2274,17 @@ def _artifact_detail_from_dict(body: dict[str, Any]) -> ArtifactDetail: server's own ``read_detail`` — so parsing it once here means the two callers can't drift on which fields are required versus defaulted. """ + what = "artifact detail" + body = _wire_row(body, what) return ArtifactDetail( - id=str(body["id"]), - name=body["name"], - kind=body["kind"], - updated_at=body["updated_at"], - etag=body["etag"], + id=str(_wire_get(body, "id", what, str, int)), + name=_wire_get(body, "name", what, str), + kind=_wire_get(body, "kind", what, str), + updated_at=_wire_get(body, "updated_at", what, str), + etag=_wire_get(body, "etag", what, str), shared=bool(body.get("shared", False)), body=body.get("body"), - labels=list(body.get("labels") or []), + labels=_optional_list(body, "labels", what), summary=body.get("summary"), ) @@ -2370,17 +2474,7 @@ def whoami(self) -> Whoami: a freshly-pasted token, and by ``pepper whoami`` to show the identity behind the current credentials.""" resp = self._request("GET", "/api/v1/whoami") - body = resp.json() - return Whoami( - user_id=body["user_id"], - email=body.get("email"), - display_name=body["display_name"], - timezone=body.get("timezone"), - merged_from=body.get("merged_from", []), - date_format=body.get("date_format", "mdy"), - time_format=body.get("time_format", "12h"), - person_id=body.get("person_id"), - ) + return _whoami_from(_wire_row(resp.json(), "whoami response"), "whoami response") def get_agent_self(self) -> AgentSelf | None: """``GET /api/v1/groups/self``: who this agent token is. Agent tokens only (a PAT is a @@ -2429,15 +2523,7 @@ def list_skills(self) -> list[SkillSummary]: can choose to bail (401) or degrade to static-only completion (everything else).""" resp = self._request("GET", "/api/v1/skills") - body = resp.json() - return [ - SkillSummary( - name=row["name"], - description=row["description"], - builtin=bool(row.get("builtin", False)), - ) - for row in body - ] + return _wire_rows(resp.json(), "skill", _skill_summary_from_dict)[0] def get_skill(self, name: str) -> SkillDetail: """``GET /api/v1/skills/{name}`` — full skill, yours or built-in. @@ -2504,19 +2590,17 @@ def list_room_skills(self, group_id: str) -> list[RoomSkill]: room, for any member — including ones a room turn cannot run now.""" resp = self._request("GET", _room_skills_path(group_id)) body = resp.json() - if not isinstance(body, list): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return [_room_skill_from_dict(row) for row in body] + return _wire_rows(body, "room skill", _room_skill_from_dict)[0] def get_room_skill(self, group_id: str, grant_id: str) -> RoomSkillDetail: """``GET /api/v1/groups/{id}/skills/{grant_id}``. 404 for an id that is not one of this room's grants.""" resp = self._request("GET", f"{_room_skills_path(group_id)}/{grant_id}") body = resp.json() - if not isinstance(body, dict) or not isinstance(body.get("skill"), dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") + body = _wire_row(body, "room skill response") return RoomSkillDetail( - row=_room_skill_from_dict(body), skill=_skill_detail_from_dict(body["skill"]) + row=_room_skill_from_dict(body), + skill=_skill_detail_from_dict(_wire_get(body, "skill", "room skill response", dict)), ) def share_room_skill(self, group_id: str, name: str) -> RoomSkill: @@ -2527,8 +2611,7 @@ def share_room_skill(self, group_id: str, name: str) -> RoomSkill: skill a room cannot run.""" resp = self._request("POST", _room_skills_path(group_id), json={"name": name}) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") + body = _wire_row(body, "share room skill response") return _room_skill_from_dict(body) def revoke_room_skill(self, group_id: str, grant_id: str) -> None: @@ -2544,7 +2627,8 @@ def list_todos( group_id: str | None = None, mine: bool = False, asked: bool = False, - ) -> list[TodoEntry]: + skip_bad_rows: bool = False, + ) -> TodoList: """``GET /api/v1/todos?status=`` (a room's: ``/api/v1/groups/{id}/todos``). ``status`` is one of ``open`` (default) / ``done`` / ``dismissed`` @@ -2564,9 +2648,8 @@ def list_todos( path += "&requester=me" resp = self._request("GET", path) body = resp.json() - if not isinstance(body, list): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return [_todo_from_dict(row) for row in body] + rows, skipped = _wire_rows(body, "todo", _todo_from_dict, skip_bad_rows=skip_bad_rows) + return TodoList(rows, skipped=skipped) def list_room_todos(self, *, mine: bool = False) -> RoomTodosList: """``GET /api/v1/todos/rooms``: the todos on each of the caller's rooms. @@ -2578,23 +2661,29 @@ def list_room_todos(self, *, mine: bool = False) -> RoomTodosList: path = "/api/v1/todos/rooms" + ("?assignee=me" if mine else "") # MIRROR: src/pepper/api/router.py::list_room_todos body = self._request("GET", path).json() - raw_rooms = body.get("rooms") if isinstance(body, dict) else None - if not isinstance(raw_rooms, list): - raise ApiError(status=200, body="", detail="malformed response") - rooms = [ - RoomTodos( - group_id=str(raw["group_id"]), - name=str(raw.get("name") or ""), - items=[ - _room_todo_from_dict(item) - for item in raw.get("items") or [] - if isinstance(item, dict) - ], + what = "room todos response" + body = _wire_row(body, what) + raw_rooms, skipped = _wire_rows( + _wire_get(body, "rooms", what, list), "room todos", _wire_row_copy, skip_bad_rows=True + ) + rooms: list[RoomTodos] = [] + for raw in raw_rooms: + if "group_id" not in raw: + skipped += 1 + continue + raw_items = _optional_list(raw, "items", "room todos") + objects = [item for item in raw_items if isinstance(item, dict)] + skipped += len(raw_items) - len(objects) + # An object that is not a todo means the shape is not the one this client knows: + # that fails the whole read (the caller shows your own list and no rooms). + rooms.append( + RoomTodos( + group_id=str(_wire_get(raw, "group_id", "room todos", str, int)), + name=str(raw.get("name") or ""), + items=_wire_rows(objects, "room todo", _room_todo_from_dict)[0], + ) ) - for raw in raw_rooms - if isinstance(raw, dict) and "group_id" in raw - ] - return RoomTodosList(rooms=rooms, degraded=bool(body.get("degraded"))) + return RoomTodosList(rooms=rooms, degraded=bool(body.get("degraded")), skipped=skipped) def calendar_range( self, *, start: str, days: int, principal: str | None = None, view: str | None = None @@ -2627,9 +2716,7 @@ def _calendar_object( path += f"&view={view}" resp = self._request("GET", path) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return body + return _wire_row(body, "calendar object response") def calendar_environment(self, *, dates: list[str], focus: str) -> dict[str, Any]: """``GET /api/v1/calendars/environment``: per-day weather and daylight (read-only).""" @@ -2681,9 +2768,7 @@ def _feed_object( ) -> dict[str, Any]: resp = self._request(method, f"/api/v1/calendars/feed{suffix}", json=json) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body="", detail="malformed response") - return body + return _wire_row(body, "feed object response") def graph_people(self, query: str | None = None, *, limit: int = 10) -> dict[str, Any]: """``GET /api/v1/graph/people``: people matching ``query``, else the strongest ties. @@ -2810,23 +2895,17 @@ def graph_me_unmark(self, address: str) -> dict[str, Any]: """``DELETE /api/v1/graph/me``: take one address off the caller's marks.""" resp = self._request("DELETE", "/api/v1/graph/me", json={"address": address}) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return body + return _wire_row(body, "graph me unmark response") def _post_object(self, path: str, payload: dict[str, Any] | None) -> dict[str, Any]: resp = self._request("POST", path, json=payload) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return body + return _wire_row(body, "post object response") def _get_object(self, path: str) -> dict[str, Any]: resp = self._request("GET", path) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return body + return _wire_row(body, "get object response") def create_todo( self, @@ -2936,11 +3015,9 @@ def list_scheduled_tasks( query = "?include_inactive=true" if include_inactive else "" resp = self._request("GET", f"{_scheduled_tasks_path(group_id)}{query}") body = resp.json() - if not isinstance(body, list): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") if group_id: - return [_room_scheduled_task_from_dict(row) for row in body] - return [_scheduled_task_from_dict(row) for row in body] + return [*_wire_rows(body, "room scheduled task", _room_scheduled_task_from_dict)[0]] + return _wire_rows(body, "scheduled task", _scheduled_task_from_dict)[0] def get_scheduled_task( self, task_id: str, *, group_id: str | None = None @@ -2986,9 +3063,7 @@ def list_scheduled_task_runs( params=_keyset_params(limit, before, before_id), ) body = resp.json() - if not isinstance(body, list): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return [_scheduled_run_from_dict(row) for row in body] + return _wire_rows(body, "scheduled task run", _scheduled_run_from_dict)[0] def get_scheduled_task_thread( self, @@ -3012,20 +3087,7 @@ def get_scheduled_task_thread( params=_keyset_params(limit, before, before_id), ) body = resp.json() - if not isinstance(body, list): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return [ - ScheduledTaskMessage( - id=row["id"], - role=row["role"], - text=row["text"], - channel=row["channel"], - trajectory_id=row.get("trajectory_id"), - created_at=row["created_at"], - attachments=row.get("attachments") or [], - ) - for row in body - ] + return _wire_rows(body, "scheduled task message", _scheduled_message_from_dict)[0] def create_scheduled_task( self, @@ -3254,9 +3316,7 @@ def trajectory_get_raw(self, trajectory_id: str) -> dict[str, Any]: format through unchanged.""" resp = self._request("GET", f"/api/v1/trajectories/{trajectory_id}") body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return body + return _wire_row(body, "trajectory get raw response") def trajectory_list( self, *, limit: int = 20, offset: int = 0, principal: str | None = None @@ -3275,22 +3335,7 @@ def trajectory_list( params["principal"] = principal resp = self._request("GET", "/api/v1/trajectories", params=params) body = resp.json() - if not isinstance(body, list): - raise ApiError(status=resp.status_code, body=resp.text, detail="malformed response") - return [ - TrajectoryListEntry( - id=row["id"], - channel=row["channel"], - created_at=row["created_at"], - closed_at=row.get("closed_at"), - meta=row.get("meta") or {}, - event_count=row["event_count"], - first_user_message=row.get("first_user_message"), - group_id=row.get("group_id"), - group_name=row.get("group_name"), - ) - for row in body - ] + return _wire_rows(body, "trajectory", _trajectory_list_entry)[0] def chat_history(self) -> ChatHistory: """``GET /api/v1/chat/history`` — today's live Pepper thread, oldest first. @@ -3380,13 +3425,14 @@ def chat_send(self, message: str, *, attachment_ids: list[str] | None = None) -> if (capabilities := turn_capabilities(sys.stdout.isatty())) is not None: payload["capabilities"] = capabilities resp = self._request("POST", "/api/v1/chat/send", json=payload) - body = resp.json() + what = "chat send response" + body = _wire_row(resp.json(), what) return ChatReply( - reply=body["reply"], + reply=_wire_get(body, "reply", what, str), trajectory_id=body.get("trajectory_id"), - user_message_id=body["user_message_id"], - assistant_message_id=body["assistant_message_id"], - steps=body.get("steps") or [], + user_message_id=_wire_get(body, "user_message_id", what, str), + assistant_message_id=_wire_get(body, "assistant_message_id", what, str), + steps=_optional_list(body, "steps", what), client_tools_ignored=body.get("client_tools_ignored"), client_message_id=body.get("client_message_id") or None, replayed=body.get("replayed") is True, @@ -3912,8 +3958,7 @@ def poll_research_run( path = _research_path(group_id, project_id, "runs", run_id) resp = self._request("GET", path, timeout=timeout) body = resp.json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body)[:200], detail="malformed response") + body = _wire_row(body, "poll research run response") return _research_run_detail(body), _retry_after(resp) def steer_research_project( @@ -3966,17 +4011,11 @@ def _research_write( ) -> dict[str, Any]: resp = self._request(method, path, json=body) parsed = resp.json() - if not isinstance(parsed, dict): - raise ApiError( - status=resp.status_code, body=str(parsed)[:200], detail="malformed response" - ) - return parsed + return _wire_row(parsed, "research write response") def _research_get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]: body = self._request("GET", path, params=params).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body)[:200], detail="malformed response") - return body + return _wire_row(body, "research get response") # ------------------------------------------------------------------ # Groups (MIRROR: src/pepper/api/groups.py) @@ -4006,8 +4045,11 @@ def get_group(self, group_id: str) -> dict[str, Any]: def list_group_topics(self, group_id: str) -> list[GroupTopicSummary]: """``GET /api/v1/groups/{gid}/topics`` — every topic, archived included; hiding them is the client's fold over one full answer.""" - body = self._request("GET", f"/api/v1/groups/{group_id}/topics").json() - return [_group_topic_from_dict(t) for t in body.get("topics") or []] + what = "group topics response" + body = _wire_row(self._request("GET", f"/api/v1/groups/{group_id}/topics").json(), what) + return _wire_rows( + _optional_list(body, "topics", what), "group topic", _group_topic_from_dict + )[0] def list_group_messages( self, @@ -4033,8 +4075,17 @@ def list_group_messages( body = self._request( "GET", f"/api/v1/groups/{group_id}/topics/{topic_id}/messages", params=params ).json() + what = "group messages response" + body = _wire_row(body, what) + messages, skipped = _wire_rows( + _optional_list(body, "messages", what), + "group message", + group_message_from_dict, + skip_bad_rows=True, + ) return GroupMessagePage( - messages=[group_message_from_dict(m) for m in body.get("messages") or []], + messages=messages, + skipped=skipped, next_before=body.get("next_before"), permalink_target_missing=body.get("permalink_target_missing", False), ) @@ -4083,7 +4134,7 @@ def post_group_message( json=payload, extra_headers=headers, ) - return resp.json()["message"] + return _wire_field(resp.json(), "message", "group message response", dict) def upload_group_attachment( self, group_id: str, *, filename: str, content: bytes, content_type: str @@ -4136,7 +4187,7 @@ def react_to_group_message( f"/api/v1/groups/{group_id}/messages/{message_id}/reactions", json={"emoji": emoji}, ) - return resp.json()["reactions"] + return _wire_field(resp.json(), "reactions", "group reactions response", list) def clear_group_reaction( self, group_id: str, message_id: str, *, emoji: str @@ -4148,7 +4199,7 @@ def clear_group_reaction( f"/api/v1/groups/{group_id}/messages/{message_id}/reactions/clear", json={"emoji": emoji}, ) - return resp.json()["reactions"] + return _wire_field(resp.json(), "reactions", "group reactions response", list) def create_group_topic( self, group_id: str, *, name: str, origin_message_id: str | None = None @@ -4159,7 +4210,7 @@ def create_group_topic( if origin_message_id: payload["origin_message_id"] = origin_message_id resp = self._request("POST", f"/api/v1/groups/{group_id}/topics", json=payload) - return resp.json()["topic"] + return _wire_field(resp.json(), "topic", "create group topic response", dict) def rename_group_topic(self, group_id: str, topic_id: str, *, name: str) -> dict[str, Any]: """``POST /api/v1/groups/{gid}/topics/{tid}/rename``.""" @@ -4243,8 +4294,9 @@ def get_groups_unread(self) -> GroupsUnread: has none. A server without the route answers 404 (an :class:`ApiError`).""" # MIRROR: src/pepper/api/groups.py::person_unread # (route handler; the response is an untyped dict, so no snapshot schema) - body = self._request("GET", "/api/v1/groups/unread").json() - raw_rows = [r for r in body.get("topics") or [] if isinstance(r, dict)] + what = "group unread response" + body = _wire_row(self._request("GET", "/api/v1/groups/unread").json(), what) + raw_rows = [r for r in _optional_list(body, "topics", what) if isinstance(r, dict)] total = body.get("unread_total") return GroupsUnread( marks={ @@ -4285,17 +4337,11 @@ def set_group_sharing(self, group_id: str, *, calendars: dict[str, str]) -> dict def group_roster(self, group_id: str) -> list[GroupRosterMember]: """``GET /api/v1/groups/{gid}/roster`` — the ``@``-mention roster, Pepper prepended.""" - body = self._request("GET", f"/api/v1/groups/{group_id}/roster").json() - return [ - GroupRosterMember( - person_id=m["person_id"], - display_name=m["display_name"], - picture_url=m.get("picture_url"), - is_pepper=m.get("is_pepper", False), - is_agent=bool(m.get("is_agent", False)), - ) - for m in body.get("members") or [] - ] + what = "group roster response" + body = _wire_row(self._request("GET", f"/api/v1/groups/{group_id}/roster").json(), what) + return _wire_rows( + _optional_list(body, "members", what), "group roster member", _roster_member_from_dict + )[0] def create_group(self, *, people: list[str], name: str | None = None) -> dict[str, Any]: """``POST /api/v1/groups`` — start a room from a member set. @@ -4330,15 +4376,15 @@ def group_activity( params: dict[str, Any] = {"since": since} if topic_ids: params["topic_ids"] = ",".join(topic_ids) - return self._request("GET", "/api/v1/groups/activity", params=params).json()["topics"] + body = self._request("GET", "/api/v1/groups/activity", params=params).json() + return _wire_field(body, "topics", "group activity response", list) def search_group_topics(self, q: str) -> list[dict[str, Any]]: """``GET /api/v1/groups/topics/search`` — case-insensitive substring across the caller's unarchived rooms. An archived topic matches only on its exact name.""" - return self._request("GET", "/api/v1/groups/topics/search", params={"q": q}).json()[ - "topics" - ] + body = self._request("GET", "/api/v1/groups/topics/search", params={"q": q}).json() + return _wire_field(body, "topics", "group topic search response", list) def install_group_app(self, group_id: str, *, app_key: str) -> dict[str, Any]: """``POST /api/v1/groups/{gid}/apps``. A key this build does not know, @@ -4362,18 +4408,14 @@ def group_app_launcher(self, group_id: str) -> tuple[list[GroupAppTile], bool]: a transient registry failure as "this room has no apps" wipes tiles it had already drawn correctly. """ - body = self._request("GET", f"/api/v1/groups/{group_id}/apps/launcher").json() - tiles = [ - GroupAppTile( - app_key=t["app_key"], - slug=t["slug"], - title=t["title"], - principal=t["principal"], - icon=t.get("icon"), - ) - for t in body.get("tiles") or [] - ] - return tiles, body.get("installed_unavailable", False) + what = "group app launcher response" + body = _wire_row( + self._request("GET", f"/api/v1/groups/{group_id}/apps/launcher").json(), what + ) + tiles = _wire_rows( + _optional_list(body, "tiles", what), "group app tile", _app_tile_from_dict + ) + return tiles[0], body.get("installed_unavailable", False) def group_app_chat( self, @@ -4403,9 +4445,8 @@ def group_app_chat( def group_app_transcript(self, group_id: str, slug: str) -> list[dict[str, Any]]: """``GET /api/v1/groups/{gid}/apps/{slug}/chat`` — the last lines of the room's **shared** thread about this app, oldest-first.""" - return self._request("GET", f"/api/v1/groups/{group_id}/apps/{slug}/chat").json()[ - "exchanges" - ] + body = self._request("GET", f"/api/v1/groups/{group_id}/apps/{slug}/chat").json() + return _wire_field(body, "exchanges", "group app transcript response", list) def search_contacts(self, q: str) -> list[dict[str, Any]]: """``GET /api/v1/people/contacts/search`` — the create-group field's @@ -4415,9 +4456,8 @@ def search_contacts(self, q: str) -> list[dict[str, Any]]: ``handle`` is the one field to fill into :meth:`create_group`. """ - return self._request("GET", "/api/v1/people/contacts/search", params={"q": q}).json()[ - "contacts" - ] + body = self._request("GET", "/api/v1/people/contacts/search", params={"q": q}).json() + return _wire_field(body, "contacts", "contact search response", list) def list_artifacts( self, @@ -4429,7 +4469,7 @@ def list_artifacts( name: str | None = None, name_prefix: str | None = None, limit: int | None = None, - ) -> ArtifactListResponse: + ) -> ArtifactListPage: """``GET /api/v1/artifacts`` — list and search one owner's artifacts. ``principal`` omitted (or equal to the caller) is self-access with no @@ -4453,10 +4493,16 @@ def list_artifacts( ): if value is not None: params[key] = value - body = self._request("GET", "/api/v1/artifacts", params=params).json() - return ArtifactListResponse( - truncated=body["truncated"], - items=[_artifact_list_item_from_dict(row) for row in body.get("items") or []], + what = "artifact list response" + body = _wire_row(self._request("GET", "/api/v1/artifacts", params=params).json(), what) + items, skipped = _wire_rows( + _optional_list(body, "items", what), + "artifact list item", + _artifact_list_item_from_dict, + skip_bad_rows=True, + ) + return ArtifactListPage( + truncated=_wire_get(body, "truncated", what, bool), items=items, skipped=skipped ) def get_artifact_detail(self, artifact_id: str) -> ArtifactDetail: @@ -4480,8 +4526,7 @@ def get_note_links(self, artifact_id: str) -> NoteLinks | None: link fields alone would make it look like a note with no links. The kind is checked on this same response, so the note is read once.""" body = self._request("GET", f"/api/v1/artifacts/{artifact_id}/detail").json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") + body = _wire_row(body, "get note links response") if body.get("kind") != "inline_text": return None return _note_links_from_dict(body, artifact_id=artifact_id) @@ -4489,8 +4534,7 @@ def get_note_links(self, artifact_id: str) -> NoteLinks | None: def list_note_comments(self, artifact_id: str) -> NoteComments: """``GET /api/v1/artifacts/{id}/comments`` — a note's comment threads, oldest first.""" body = self._request("GET", f"/api/v1/artifacts/{artifact_id}/comments").json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") + body = _wire_row(body, "list note comments response") return _note_comments_from_dict(body) def create_note_comment( @@ -4518,9 +4562,7 @@ def create_note_comment( json=payload, extra_headers=headers, ).json() - if not isinstance(resp, dict): - raise ApiError(status=200, body=str(resp), detail="malformed response") - return resp + return _wire_row(resp, "create note comment response") def _set_note_thread_resolved( self, artifact_id: str, thread_id: str, action: str @@ -4529,8 +4571,7 @@ def _set_note_thread_resolved( "POST", f"/api/v1/artifacts/{artifact_id}/comments/{thread_id}/{action}" ).json() thread = resp.get("thread") if isinstance(resp, dict) else None - if not isinstance(thread, dict): - raise ApiError(status=200, body=str(resp), detail="malformed response") + thread = _wire_row(thread, "set note thread resolved response") return _note_thread_from_dict(thread) def resolve_note_thread(self, artifact_id: str, thread_id: str) -> NoteCommentThread: @@ -4566,7 +4607,13 @@ def create_artifact( json={"name": name, "kind": "inline_text", "body": body}, params=params or None, ).json() - return ArtifactCreateResult(id=str(resp["id"]), name=resp["name"], etag=resp["etag"]) + what = "create artifact response" + resp = _wire_row(resp, what) + return ArtifactCreateResult( + id=str(_wire_get(resp, "id", what, str, int)), + name=_wire_get(resp, "name", what, str), + etag=_wire_get(resp, "etag", what, str), + ) def edit_artifact( self, @@ -4617,7 +4664,9 @@ def edit_artifact( current_etag=current.get("etag"), current_updated_at=current.get("updated_at"), ) from exc - return _artifact_detail_from_dict(resp["artifact"]) + return _artifact_detail_from_dict( + _wire_field(resp, "artifact", "edit artifact response", dict) + ) def toggle_checklist( self, @@ -4694,9 +4743,7 @@ def blog_posts(self, group_id: str) -> dict[str, Any]: """``GET /api/v1/groups/{id}/blog/posts``: the room blog's posts and, for an owner, the room's notes not yet published, as the server's own dict.""" body = self._request("GET", f"/api/v1/groups/{group_id}/blog/posts").json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "blog posts response") def blog_check( self, group_id: str, note_id: str, *, published_at: str | None = None @@ -4708,9 +4755,7 @@ def blog_check( body = self._request( "GET", f"/api/v1/groups/{group_id}/blog/notes/{note_id}/check", params=params ).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "blog check response") def blog_publish( self, @@ -4735,11 +4780,13 @@ def blog_publish( body = self._request( "POST", f"/api/v1/groups/{group_id}/blog/notes/{note_id}/publish", json=payload ).json() + what = "blog publish response" + body = _wire_row(body, what) return BlogPublished( - post_id=str(body["post_id"]), - slug=str(body["slug"]), - url=str(body["url"]), - republished=bool(body["republished"]), + post_id=str(_wire_get(body, "post_id", what, str, int)), + slug=_wire_get(body, "slug", what, str), + url=_wire_get(body, "url", what, str), + republished=_wire_get(body, "republished", what, bool), card=str(body.get("card", "")), copy=body.get("copy"), ) @@ -4749,9 +4796,11 @@ def blog_withdraw(self, group_id: str, post_id: str) -> BlogWithdrawn: body = self._request( "POST", f"/api/v1/groups/{group_id}/blog/posts/{post_id}/withdraw" ).json() + what = "blog withdraw response" + body = _wire_row(body, what) return BlogWithdrawn( - post_id=str(body["post_id"]), - already=bool(body["already"]), + post_id=str(_wire_get(body, "post_id", what, str, int)), + already=_wire_get(body, "already", what, bool), card=str(body.get("card", "")), copy=body.get("copy"), ) @@ -4761,8 +4810,7 @@ def list_apps(self) -> list[dict[str, Any]]: ``owner_scoped_actions``, ...). The list is the only place the server names an app's actions, and it names just the ``owner_scoped`` ones.""" body = self._request("GET", "/api/v1/apps").json() - if not isinstance(body, list): - raise ApiError(status=200, body=str(body), detail="malformed response") + body = _wire_list(body, "list apps response") return [row for row in body if isinstance(row, dict)] def get_artifact_detail_raw(self, artifact_id: str) -> dict[str, Any]: @@ -4770,9 +4818,7 @@ def get_artifact_detail_raw(self, artifact_id: str) -> dict[str, Any]: ``mime_type``, ``size_label``, ``text_body``, ``link``, ``viewer``, ... for every kind), where :meth:`get_artifact_detail` keeps only the note fields.""" body = self._request("GET", f"/api/v1/artifacts/{artifact_id}/detail").json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "get artifact detail raw response") def get_image_details(self, artifact_id: str, *, principal: str | None = None) -> ImageDetails: """``GET /api/v1/artifacts/{id}/image-details`` — a picture's alt text and captions. @@ -4787,8 +4833,7 @@ def get_image_details(self, artifact_id: str, *, principal: str | None = None) - body = self._request( "GET", f"/api/v1/artifacts/{artifact_id}/image-details", params=params ).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") + body = _wire_row(body, "get image details response") return _image_details_from_dict(body) def put_image_details( @@ -4823,8 +4868,7 @@ def put_image_details( json=payload, params=params, ).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") + body = _wire_row(body, "put image details response") return _image_details_from_dict(body) def suggest_image_details( @@ -4843,11 +4887,10 @@ def suggest_image_details( json={"all": replace_all}, params=params, ).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") + body = _wire_row(body, "suggest image details response") run = body.get("run") return ImageSuggestion( - id=str(body["id"]), + id=str(_wire_get(body, "id", "suggest image details response", str, int)), started=bool(body.get("started")), run=run if isinstance(run, int) else None, ) @@ -4889,8 +4932,9 @@ def upload_artifact( }, params=params, ).json() - if not isinstance(resp, dict) or not resp.get("id"): - raise ApiError(status=200, body=str(resp), detail="malformed response") + resp = _wire_row(resp, "upload artifact response") + if not resp.get("id"): + raise _malformed("upload artifact response has no 'id'", resp) return resp def send_draft(self, draft_id: str) -> None: @@ -4904,9 +4948,7 @@ def get_calendar_preferences(self) -> dict[str, Any]: (addresses, timezone, work days and hours, meals, workout, weather switches) plus two page helpers, ``timezones`` (the allowed zone names) and ``maps``.""" body = self._request("GET", "/api/v1/calendars/preferences").json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "get calendar preferences response") def set_calendar_preferences(self, changes: dict[str, Any]) -> dict[str, Any]: """``POST /api/v1/calendars/preferences`` with only the keys given: the server keeps @@ -4914,18 +4956,14 @@ def set_calendar_preferences(self, changes: dict[str, Any]) -> dict[str, Any]: saved values. 422 for a value it refuses (unknown timezone, an address Maps cannot place, a bad time).""" body = self._request("POST", "/api/v1/calendars/preferences", json=changes).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "set calendar preferences response") def get_app_data(self, slug: str, *, principal: str | None = None) -> dict[str, Any]: """``GET /api/v1/apps/{slug}/data[?principal=]``: ``{"rev": int, "data": {...}}``, the app's document for the caller, or for the room ``principal``.""" params = {"principal": principal} if principal is not None else None body = self._request("GET", f"/api/v1/apps/{slug}/data", params=params).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "get app data response") def run_app_action( self, @@ -4944,9 +4982,7 @@ def run_app_action( json={"params": params}, params=query, ).json() - if not isinstance(body, dict): - raise ApiError(status=200, body=str(body), detail="malformed response") - return body + return _wire_row(body, "run app action response") def download_takeout(self, *, out_path: str | None = None) -> str: """``GET /api/v1/takeout``. Streams the zip archive straight to @@ -5063,6 +5099,25 @@ def _request( return resp +def _trajectory_list_entry(row: dict[str, Any]) -> TrajectoryListEntry: + what = "trajectory" + row = _wire_row(row, what) + meta = row.get("meta") + if meta is not None and not isinstance(meta, dict): + raise _malformed(f"{what} field 'meta' has the wrong type", row) + return TrajectoryListEntry( + id=_wire_get(row, "id", what, str), + channel=_wire_get(row, "channel", what, str), + created_at=_wire_get(row, "created_at", what, str), + closed_at=row.get("closed_at"), + meta=meta or {}, + event_count=_wire_get(row, "event_count", what, int), + first_user_message=row.get("first_user_message"), + group_id=row.get("group_id"), + group_name=row.get("group_name"), + ) + + def _trajectory_detail_from_dict(body: dict[str, Any]) -> TrajectoryDetail: """Parse a ``TrajectoryDetailResponse`` JSON body into dataclasses. @@ -5111,6 +5166,11 @@ def _todos_path(group_id: str | None) -> str: return f"/api/v1/groups/{group_id}/todos" if group_id else "/api/v1/todos" +def _wire_row_copy(row: dict[str, Any]) -> dict[str, Any]: + """The identity parser for :func:`_wire_rows`: each element only has to be an object.""" + return row + + def _todo_from_dict(row: dict[str, Any]) -> TodoEntry: """Parse one ``TodoEntry`` JSON object into the dataclass. @@ -5118,16 +5178,18 @@ def _todo_from_dict(row: dict[str, Any]) -> TodoEntry: single-row create/done/dismiss responses all parse through one place and can't drift on field handling. """ + what = "todo" + row = _wire_row(row, what) return TodoEntry( - id=row["id"], - title=row["title"], + id=_wire_get(row, "id", what, str), + title=_wire_get(row, "title", what, str), details=row.get("details"), - status=row["status"], - source=row["source"], + status=_wire_get(row, "status", what, str), + source=_wire_get(row, "source", what, str), priority=row.get("priority"), due_date=row.get("due_date"), due_is_date_only=row.get("due_is_date_only"), - created_at=row["created_at"], + created_at=_wire_get(row, "created_at", what, str), done_at=row.get("done_at"), source_ref=row.get("source_ref"), remind_at=row.get("remind_at"), @@ -5294,6 +5356,21 @@ def error_code(exc: ApiError) -> str | None: return code if isinstance(code, str) else None +def _whoami_from(row: dict[str, Any], what: str, *, person_id: bool = True) -> Whoami: + """A :class:`Whoami` from ``/api/v1/whoami`` or the user object of an approved device poll. + ``merged_from``, the two formats and ``person_id`` may be missing (an older server).""" + return Whoami( + user_id=_wire_get(row, "user_id", what, str), + email=row.get("email"), + display_name=_wire_get(row, "display_name", what, str), + timezone=row.get("timezone"), + merged_from=_optional_list(row, "merged_from", what), + date_format=row.get("date_format", "mdy"), + time_format=row.get("time_format", "12h"), + person_id=row.get("person_id") if person_id else None, + ) + + def _page_params(limit: int, before: str | None) -> dict[str, Any]: params: dict[str, Any] = {"limit": limit} if before is not None: @@ -5353,11 +5430,44 @@ def _wire_get( value = row[key] if value is None and nullable: return None - if not isinstance(value, types) or (isinstance(value, bool) and bool not in types): + if types and (not isinstance(value, types) or (isinstance(value, bool) and bool not in types)): raise _malformed(f"{what} field {key!r} has the wrong type", row) return value +def _wire_field(raw: object, key: str, what: str, *types: type) -> Any: + """``raw[key]`` for a response that is one object and carries the field wanted, of one of + ``types``; any other shape is a malformed-response :class:`ApiError`.""" + return _wire_get(_wire_row(raw, what), key, what, *types) + + +def _wire_list(raw: object, what: str) -> list[Any]: + """``raw`` as a JSON array, or a malformed-response :class:`ApiError` naming ``what``.""" + if not isinstance(raw, list): + raise _malformed(f"{what} is not a list", raw) + return raw + + +def _wire_rows[T]( + raw: object, what: str, parse: Callable[[dict[str, Any]], T], *, skip_bad_rows: bool = False +) -> tuple[list[T], int]: + """``parse`` over each element of the array ``raw``: the parsed rows and how many were left + out. A response that is not an array always fails. With ``skip_bad_rows`` (a list a poller or + stream reads on every tick) a row that fails to parse is left out and counted, so one bad row + never costs the rest; without it the first bad row fails the whole response. Only the + malformed-response :class:`ApiError` is caught, never a programmer error.""" + parsed: list[T] = [] + skipped = 0 + for item in _wire_list(raw, what): + try: + parsed.append(parse(_wire_row(item, what))) + except ApiError: + if not skip_bad_rows: + raise + skipped += 1 + return parsed, skipped + + def _fields[T](cls: type[T], row: dict[str, Any], **parsed: Any) -> T: """``cls`` built from the keys of ``row`` it declares. An unknown key is ignored (``/api/v1`` is additive-only); an optional field (``X | None``) the server leaves out reads as ``None``. @@ -5510,8 +5620,7 @@ def _research_page[T]( body: dict[str, Any], parse: Callable[[dict[str, Any]], T] ) -> ResearchPage[T]: rows = body.get("items") - if not isinstance(rows, list): - raise ApiError(status=200, body=str(body)[:200], detail="malformed response") + rows = _wire_list(rows, "research page items") for i, r in enumerate(rows): if not isinstance(r, dict): raise _malformed(f"research page item {i} is not an object", r) @@ -5522,6 +5631,21 @@ def _research_page[T]( ) +def _scheduled_message_from_dict(row: dict[str, Any]) -> ScheduledTaskMessage: + """Parse one row of a scheduled task's thread.""" + what = "scheduled task message" + row = _wire_row(row, what) + return ScheduledTaskMessage( + id=_wire_get(row, "id", what, str), + role=_wire_get(row, "role", what, str), + text=_wire_get(row, "text", what, str), + channel=_wire_get(row, "channel", what, str), + trajectory_id=row.get("trajectory_id"), + created_at=_wire_get(row, "created_at", what, str), + attachments=_optional_list(row, "attachments", what), + ) + + def _scheduled_run_from_dict(row: dict[str, Any]) -> ScheduledTaskRunEntry: """Parse one run row — the runs listing and ``latest_run``.""" what = "scheduled task run" diff --git a/src/pepper_cli/tui/poller.py b/src/pepper_cli/tui/poller.py index 3623d6d..57ccc0d 100644 --- a/src/pepper_cli/tui/poller.py +++ b/src/pepper_cli/tui/poller.py @@ -284,7 +284,7 @@ def fetch_room_shelf(api: ApiClient, room_id: str) -> tuple[list[GroupAppTile], def fetch_todos(api: ApiClient, owner: str | None, *, mine: bool) -> list[TodoEntry]: """Every todo of one owner, open and closed, in one call: a room's (``owner`` is its id) or your own (``None``). ``mine`` keeps what someone asked of you.""" - return api.list_todos(status="all", group_id=owner, mine=mine) + return api.list_todos(status="all", group_id=owner, mine=mine, skip_bad_rows=True) @dataclass(frozen=True) @@ -303,7 +303,7 @@ def fetch_own_todos(api: ApiClient, *, mine: bool) -> OwnTodos: A failure of your own list raises, as any pane read does; a 401 on either one too, so the app takes its login path (an upgrade-required answer is not caught here either). """ - todos = api.list_todos(status="all", mine=mine) + todos = api.list_todos(status="all", mine=mine, skip_bad_rows=True) try: listed = api.list_room_todos(mine=mine) except ApiError as exc: diff --git a/tests/test_api_client_malformed_parsers.py b/tests/test_api_client_malformed_parsers.py new file mode 100644 index 0000000..b0ab17d --- /dev/null +++ b/tests/test_api_client_malformed_parsers.py @@ -0,0 +1,352 @@ +"""The rest of the typed parsers (todos, groups, artifacts, notes, skills, chat send, sign-in) +turn a malformed successful response into ``ApiError`` (status 200) naming the field or shape, +never a ``KeyError``/``TypeError``, and never echo the offending value. Lists a poller reads on +a timer skip and count a bad row; every other list fails whole.""" + +from __future__ import annotations + +import httpx +import pytest + +from pepper_cli import api_client +from pepper_cli.api_client import ApiError +from pepper_cli.secret import SecretStr + + +def _api(body: object) -> api_client.ApiClient: + return api_client.ApiClient( + server_url="http://example.com", + token=SecretStr("pep_pat_abc"), + client=httpx.Client( + transport=httpx.MockTransport(lambda _r: httpx.Response(200, json=body)) + ), + ) + + +def _todo(**over: object) -> dict: + row = {"id": "t1", "title": "x", "status": "open", "source": "user", "created_at": "z"} + return {**row, **over} + + +def _topic(**over: object) -> dict: + return {"topic_id": "tp", "name": "General", "last_activity_at": None, **over} + + +def _group(**over: object) -> dict: + row = { + "group_id": "g1", + "display_name": "G", + "color": "c", + "sub": "s", + "member_count": 2, + "archived": False, + "topics": [_topic()], + } + return {**row, **over} + + +def _groups(**over: object) -> dict: + body = {"enabled": True, "degraded": False, "total": 1, "archived_total": 0} + return {**body, "groups": [_group()], **over} + + +def _message(**over: object) -> dict: + row = {k: "s" for k in api_client.GroupMessage.__dataclass_fields__ if k in _MSG_STR} + row |= dict.fromkeys(_MSG_BOOL, False) + return {**row, **over} + + +_MSG_STR = [ + "id", + "display_name", + "initial", + "avatar_tint", + "raw_body", + "rendered_html", + "created_at", + "created_at_display", + "day_key", + "day_kicker", + "day_heading", + "day_label", + "quote_excerpt", +] +_MSG_BOOL = ["is_pepper", "is_you", "is_deleted", "is_broken", "run_start"] + + +def _without(row: dict, key: str) -> dict: + return {k: v for k, v in row.items() if k != key} + + +def _malformed(raised: pytest.ExceptionInfo[ApiError]) -> str: + assert raised.value.status == 200 + assert len(raised.value.body) <= 200 + return str(raised.value.detail) + + +# --- a missing key, a wrong container type and a wrong scalar type, per parser ---------------- + + +@pytest.mark.parametrize( + ("call", "body", "names"), + [ + (lambda a: a.list_todos(), [_without(_todo(), "title")], "'title'"), + (lambda a: a.list_todos(), [_todo(id=7)], "'id'"), + (lambda a: a.list_todos(), {"items": []}, "not a list"), + (lambda a: a.list_todos(), ["row"], "not an object"), + (lambda a: a.list_skills(), [{"name": "n"}], "'description'"), + (lambda a: a.list_skills(), [{"name": 3, "description": "d"}], "'name'"), + (lambda a: a.list_skills(), "nope", "not a list"), + (lambda a: a.list_room_skills("g"), [{"id": "1", "name": "n"}], "'description'"), + (lambda a: a.get_skill("n"), {"name": "n", "description": "d", "body": 1}, "'body'"), + ( + lambda a: a.get_skill("n"), + {"name": "n", "description": "d", "body": "b", "toolsets": "x"}, + "'toolsets'", + ), + (lambda a: a.list_groups(), _groups(groups="x"), "'groups'"), + (lambda a: a.list_groups(), _without(_groups(), "total"), "'total'"), + (lambda a: a.list_groups(), _groups(enabled="yes"), "'enabled'"), + (lambda a: a.list_groups(), [], "not an object"), + ( + lambda a: a.list_group_topics("g"), + {"topics": [_without(_topic(), "name")]}, + "'name'", + ), + (lambda a: a.list_group_topics("g"), {"topics": 1}, "'topics'"), + (lambda a: a.group_roster("g"), {"members": [{"person_id": "p"}]}, "'display_name'"), + (lambda a: a.group_roster("g"), {"members": {"a": 1}}, "'members'"), + ( + lambda a: a.group_app_launcher("g"), + {"tiles": [{"app_key": "k", "slug": "s", "title": "t"}]}, + "'principal'", + ), + (lambda a: a.list_artifacts(), {"items": []}, "'truncated'"), + (lambda a: a.list_artifacts(), {"truncated": False, "items": 3}, "'items'"), + ( + lambda a: a.list_artifacts(), + {"truncated": "no", "items": []}, + "'truncated'", + ), + (lambda a: a.get_artifact_detail("a"), {"id": "a", "name": "n"}, "'kind'"), + (lambda a: a.get_artifact_detail("a"), [], "not an object"), + ( + lambda a: a.get_artifact_detail("a"), + {"id": "a", "name": "n", "kind": "k", "updated_at": "u", "etag": "e", "labels": 5}, + "'labels'", + ), + ( + lambda a: a.list_note_comments("a"), + {"threads": [{"replies": []}]}, + "'message'", + ), + (lambda a: a.list_note_comments("a"), {"threads": "x"}, "'threads'"), + (lambda a: a.list_note_comments("a"), {"threads": [{"message": []}]}, "'message'"), + (lambda a: a.chat_send("hi"), {"reply": "r"}, "'user_message_id'"), + ( + lambda a: a.chat_send("hi"), + {"reply": 1, "user_message_id": "u", "assistant_message_id": "a"}, + "'reply'", + ), + (lambda a: a.whoami(), {"user_id": "u"}, "'display_name'"), + (lambda a: a.whoami(), {"user_id": 3, "display_name": "d"}, "'user_id'"), + ( + lambda a: a.whoami(), + {"user_id": "u", "display_name": "d", "merged_from": "x"}, + "'merged_from'", + ), + ( + lambda a: a.trajectory_list(), + [{"id": "t", "channel": "c", "created_at": "z"}], + "'event_count'", + ), + ], +) +def test_malformed_response_names_the_shape_or_field(call, body, names) -> None: + with _api(body) as api, pytest.raises(ApiError) as raised: + call(api) + assert names in _malformed(raised) + + +def test_the_diagnostic_never_echoes_the_value() -> None: + with _api([_todo(title=None, secret="hunter2-sentinel")]) as api, pytest.raises(ApiError) as r: + api.list_todos() + assert "hunter2-sentinel" not in str(r.value.detail) + assert "'title'" in str(r.value.detail) + + +def test_a_non_object_raw_helper_response_is_malformed_not_a_crash() -> None: + with _api([1]) as api, pytest.raises(ApiError) as raised: + api.get_app_data("slug") + assert "not an object" in _malformed(raised) + + +def test_a_reply_missing_the_sub_object_field_is_malformed() -> None: + with _api({"id": "a"}) as api, pytest.raises(ApiError) as raised: + api.edit_artifact("a", body="b") + assert "'artifact'" in _malformed(raised) + + +def test_a_group_message_response_without_the_message_is_malformed() -> None: + with _api({}) as api, pytest.raises(ApiError) as raised: + api.post_group_message("g", "tp", message="x") + assert "'message'" in _malformed(raised) + + +# --- compatibility: optional fields an older server leaves out keep their defaults ------------ + + +def test_older_server_rows_keep_their_defaults() -> None: + with _api([_todo(future_field=1)]) as api: + (todo,) = api.list_todos() + assert (todo.id, todo.details, todo.assignee, todo.next_action) == ("t1", None, None, None) + with _api({"name": "n", "description": "d", "body": "b"}) as api: + skill = api.get_skill("n") + assert (skill.toolsets, skill.builtin, skill.model) == ((), False, None) + with _api({"user_id": "u", "display_name": "d"}) as api: + who = api.whoami() + assert (who.merged_from, who.date_format, who.time_format, who.person_id) == ( + [], + "mdy", + "12h", + None, + ) + with _api(_groups(groups=[_group(topics=None, future=1)])) as api: + listed = api.list_groups() + assert (listed.groups[0].topics, listed.skipped, listed.features) == ([], 0, ()) + with _api({"truncated": False}) as api: + assert api.list_artifacts().items == [] + + +# --- polled lists skip and count a bad row; the others fail whole ----------------------------- + + +def test_the_group_list_skips_and_counts_a_malformed_room() -> None: + body = _groups(groups=[_group(), _group(group_id=None), "x", _group(group_id="g3")]) + with _api(body) as api: + listed = api.list_groups() + assert [g.group_id for g in listed.groups] == ["g1", "g3"] + assert listed.skipped == 2 + + +def test_a_room_with_a_malformed_topic_is_skipped_not_the_whole_list() -> None: + body = _groups(groups=[_group(topics=[{"topic_id": "x"}]), _group(group_id="g2")]) + with _api(body) as api: + listed = api.list_groups() + assert [g.group_id for g in listed.groups] == ["g2"] + assert listed.skipped == 1 + + +def test_group_messages_skip_and_count_a_malformed_row() -> None: + body = {"messages": [_message(), _message(id=None), 4, _message(id="m3")]} + with _api(body) as api: + page = api.list_group_messages("g", "tp") + assert [m.id for m in page.messages] == ["s", "m3"] + assert page.skipped == 2 + + +@pytest.mark.parametrize("bad", [{"messages": "x"}, []]) +def test_group_messages_that_are_not_a_list_fail_the_page(bad: object) -> None: + with _api(bad) as api, pytest.raises(ApiError): + api.list_group_messages("g", "tp") + + +def test_a_group_message_with_a_malformed_card_is_a_bad_row() -> None: + body = {"messages": [_message(cards=[{"app_key": "k"}]), _message(id="ok")]} + with _api(body) as api: + page = api.list_group_messages("g", "tp") + assert [m.id for m in page.messages] == ["ok"] + assert page.skipped == 1 + + +def test_artifacts_skip_and_count_a_malformed_item() -> None: + good = {"id": "a", "name": "n", "kind": "k", "updated_at": "u", "etag": "e"} + with _api({"truncated": False, "items": [good, {"id": "b"}, good]}) as api: + listed = api.list_artifacts() + assert (len(listed.items), listed.skipped) == (2, 1) + + +def test_todos_skip_only_when_the_caller_polls() -> None: + rows = [_todo(), _without(_todo(id="t2"), "status"), _todo(id="t3")] + with _api(rows) as api: + polled = api.list_todos(skip_bad_rows=True) + assert ([t.id for t in polled], polled.skipped) == (["t1", "t3"], 1) + with _api(rows) as api, pytest.raises(ApiError): + api.list_todos() + + +def test_a_todo_list_that_is_not_a_list_fails_even_when_skipping() -> None: + with _api({"todos": []}) as api, pytest.raises(ApiError): + api.list_todos(skip_bad_rows=True) + + +def test_room_todos_skip_non_objects_but_a_malformed_todo_fails_the_read() -> None: + body = { + "rooms": [{"name": "no id", "items": []}, "junk", {"group_id": "g", "items": [_todo(), 1]}] + } + with _api(body) as api: + listed = api.list_room_todos() + assert [(r.group_id, len(r.items)) for r in listed.rooms] == [("g", 1)] + assert listed.skipped == 3 + bad = {"rooms": [{"group_id": "g", "items": [{"id": "x"}]}]} + with _api(bad) as api, pytest.raises(ApiError) as raised: + api.list_room_todos() + assert "'title'" in _malformed(raised) + with _api({"rooms": "x"}) as api, pytest.raises(ApiError) as raised: + api.list_room_todos() + assert "'rooms'" in _malformed(raised) + + +# --- sign-in ---------------------------------------------------------------------------------- + + +def _device(handler) -> httpx.Client: + return httpx.Client(transport=httpx.MockTransport(handler)) + + +def test_device_start_names_a_missing_or_mistyped_field() -> None: + body = { + "device_code": "d", + "user_code": "u", + "verification_url": "v", + "expires_in": 60, + "interval": 5, + } + ok = api_client.device_start( + "http://x", "n", client=_device(lambda _r: httpx.Response(200, json=body)) + ) + assert (ok.user_code, ok.interval) == ("u", 5) + for bad, name in ( + (_without(body, "interval"), "'interval'"), + ({**body, "expires_in": "60"}, "'expires_in'"), + ): + with pytest.raises(ApiError) as raised: + api_client.device_start( + "http://x", "n", client=_device(lambda _r, b=bad: httpx.Response(200, json=b)) + ) + assert name in _malformed(raised) + + +def test_device_poll_approved_without_a_token_or_user_is_malformed() -> None: + user = {"user_id": "u", "display_name": "d"} + for body, name in ( + ({"status": "approved", "user": user}, "'token'"), + ({"status": "approved", "token": "t"}, "'user'"), + ({"status": "approved", "token": "t", "user": {"user_id": "u"}}, "'display_name'"), + ([], "not an object"), + ): + with pytest.raises(ApiError) as raised: + api_client.device_poll( + "http://x", + SecretStr("dc"), + client=_device(lambda _r, b=body: httpx.Response(200, json=b)), + ) + assert name in _malformed(raised) + poll = api_client.device_poll( + "http://x", + SecretStr("dc"), + client=_device( + lambda _r: httpx.Response(200, json={"status": "approved", "token": "t", "user": user}) + ), + ) + assert poll.user is not None and poll.user.user_id == "u" diff --git a/tests/test_api_client_room_skills.py b/tests/test_api_client_room_skills.py index 8f83513..53e88c5 100644 --- a/tests/test_api_client_room_skills.py +++ b/tests/test_api_client_room_skills.py @@ -159,4 +159,4 @@ def test_a_body_of_the_wrong_shape_is_an_api_error_not_a_crash(call) -> None: _, handler = _capture(httpx.Response(200, json="nope")) with _client(handler) as api, pytest.raises(api_client.ApiError) as err: call(api) - assert err.value.detail == "malformed response" + assert str(err.value.detail).startswith("malformed response") From 81352939bec06ff879112712c77d296ad9987ca3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:57:48 +0000 Subject: [PATCH 2/3] Drop skip-and-count from the polled list parsers; keep raw bodies out of errors Every list parser is strict again: a malformed group, group message, artifact or todo row fails the whole read with ApiError(200), as it did before this PR, so the rail never commits an ETag for a partial list, a note or room lookup cannot miss a row, and a stale-message refresh is retried. The unread `skipped` fields, TodoList, ArtifactListPage and the skip_bad_rows flag go with it. Room todos keep their older tolerance for non-object rooms and items. Showing partial lists is #353. _malformed no longer puts the raw value in ApiError.body: a device-poll body can carry the approved token. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QNDehAurHo1CzCzisi6nYx --- src/pepper_cli/api_client.py | 132 ++++++--------------- src/pepper_cli/tui/poller.py | 4 +- tests/test_api_client_malformed_parsers.py | 128 ++++++++++++-------- 3 files changed, 120 insertions(+), 144 deletions(-) diff --git a/src/pepper_cli/api_client.py b/src/pepper_cli/api_client.py index b6607e7..5671436 100644 --- a/src/pepper_cli/api_client.py +++ b/src/pepper_cli/api_client.py @@ -947,17 +947,6 @@ class RoomTodos: items: list[TodoEntry] -class TodoList(list[TodoEntry]): - """``GET /api/v1/todos``'s rows, plus ``skipped``: how many rows were left out because they - were malformed (only when the caller asked to skip them). A plain list otherwise.""" - - skipped: int = 0 - - def __init__(self, rows: list[TodoEntry] | None = None, *, skipped: int = 0) -> None: - super().__init__(rows or []) - self.skipped = skipped - - @dataclass(frozen=True) class RoomTodosList: """``GET /api/v1/todos/rooms``: the rooms with todos, and whether the list is partial.""" @@ -965,8 +954,6 @@ class RoomTodosList: rooms: list[RoomTodos] #: The server could not read the caller's rooms: ``rooms`` is empty, not "no todos". degraded: bool = False - #: Rooms or items the server sent that could not be read and were left out. - skipped: int = 0 # MIRROR: src/pepper/api/scheduled_tasks.py::TaskSummary @@ -1694,9 +1681,6 @@ class GroupList: archived_total: int groups: list[GroupSummary] = field(default_factory=list) features: tuple[str, ...] = () - #: Rooms the server sent that could not be read and were left out, so a poller can say the - #: list is partial rather than show it as complete. - skipped: int = 0 # MIRROR: src/pepper/api/groups.py::topic_messages @@ -1822,8 +1806,6 @@ class GroupMessagePage: messages: list[GroupMessage] = field(default_factory=list) next_before: str | None = None permalink_target_missing: bool = False - #: Messages that could not be read and were left out, so one bad row never hides the page. - skipped: int = 0 # MIRROR: src/pepper/api/groups.py::room_roster @@ -1973,13 +1955,11 @@ def _app_tile_from_dict(row: dict[str, Any]) -> GroupAppTile: def _group_list_from_dict(body: dict[str, Any]) -> GroupList: - """The poller reads this on a timer, so a malformed room is left out and counted in - ``skipped`` rather than hiding every other room.""" + """A malformed room fails the whole list, so no caller ever sees a partial list as + complete (the rail keeps its last list, and a name lookup cannot miss a room).""" what = "group list" body = _wire_row(body, what) - groups, skipped = _wire_rows( - _optional_list(body, "groups", what), "group", _group_summary_from_dict, skip_bad_rows=True - ) + groups = _wire_rows(_optional_list(body, "groups", what), "group", _group_summary_from_dict) return GroupList( enabled=_wire_get(body, "enabled", what, bool), degraded=_wire_get(body, "degraded", what, bool), @@ -1987,7 +1967,6 @@ def _group_list_from_dict(body: dict[str, Any]) -> GroupList: archived_total=_wire_get(body, "archived_total", what, int), groups=groups, features=tuple(f for f in _optional_list(body, "features", what) if isinstance(f, str)), - skipped=skipped, ) @@ -2003,7 +1982,7 @@ def _group_summary_from_dict(row: dict[str, Any]) -> GroupSummary: archived=_wire_get(row, "archived", what, bool), topics=_wire_rows( _optional_list(row, "topics", what), "group topic", _group_topic_from_dict - )[0], + ), mascot_url=mascot if isinstance(mascot := row.get("mascot_url"), str) else None, ) @@ -2071,14 +2050,6 @@ class ArtifactListResponse: items: list[ArtifactListItem] = field(default_factory=list) -@dataclass(frozen=True) -class ArtifactListPage(ArtifactListResponse): - """:class:`ArtifactListResponse` plus ``skipped``: rows that could not be read and were left - out (the notes pane polls this list). Not a server model, so not mirrored.""" - - skipped: int = 0 - - # The note-comment routes answer untyped JSON the server has not published in the vendored # snapshot yet, so these carry no contract marker; add one once the snapshot refresh lands. # They follow the prototype contract (GET/POST /api/v1/artifacts/{id}/comments, and @@ -2156,7 +2127,7 @@ def _note_thread_from_dict(t: dict[str, Any]) -> NoteCommentThread: detached=bool(t.get("detached", False)), replies=_wire_rows( _optional_list(t, "replies", what), "note comment", _note_comment_from_dict - )[0], + ), ) @@ -2165,7 +2136,7 @@ def _note_comments_from_dict(body: dict[str, Any]) -> NoteComments: body = _wire_row(body, what) threads = _wire_rows( _optional_list(body, "threads", what), "note comment thread", _note_thread_from_dict - )[0] + ) return NoteComments( artifact_id=str(body.get("artifact_id") or ""), group_id=body.get("group_id"), @@ -2523,7 +2494,7 @@ def list_skills(self) -> list[SkillSummary]: can choose to bail (401) or degrade to static-only completion (everything else).""" resp = self._request("GET", "/api/v1/skills") - return _wire_rows(resp.json(), "skill", _skill_summary_from_dict)[0] + return _wire_rows(resp.json(), "skill", _skill_summary_from_dict) def get_skill(self, name: str) -> SkillDetail: """``GET /api/v1/skills/{name}`` — full skill, yours or built-in. @@ -2590,7 +2561,7 @@ def list_room_skills(self, group_id: str) -> list[RoomSkill]: room, for any member — including ones a room turn cannot run now.""" resp = self._request("GET", _room_skills_path(group_id)) body = resp.json() - return _wire_rows(body, "room skill", _room_skill_from_dict)[0] + return _wire_rows(body, "room skill", _room_skill_from_dict) def get_room_skill(self, group_id: str, grant_id: str) -> RoomSkillDetail: """``GET /api/v1/groups/{id}/skills/{grant_id}``. 404 for an id that @@ -2627,8 +2598,7 @@ def list_todos( group_id: str | None = None, mine: bool = False, asked: bool = False, - skip_bad_rows: bool = False, - ) -> TodoList: + ) -> list[TodoEntry]: """``GET /api/v1/todos?status=`` (a room's: ``/api/v1/groups/{id}/todos``). ``status`` is one of ``open`` (default) / ``done`` / ``dismissed`` @@ -2648,8 +2618,7 @@ def list_todos( path += "&requester=me" resp = self._request("GET", path) body = resp.json() - rows, skipped = _wire_rows(body, "todo", _todo_from_dict, skip_bad_rows=skip_bad_rows) - return TodoList(rows, skipped=skipped) + return _wire_rows(body, "todo", _todo_from_dict) def list_room_todos(self, *, mine: bool = False) -> RoomTodosList: """``GET /api/v1/todos/rooms``: the todos on each of the caller's rooms. @@ -2663,27 +2632,24 @@ def list_room_todos(self, *, mine: bool = False) -> RoomTodosList: body = self._request("GET", path).json() what = "room todos response" body = _wire_row(body, what) - raw_rooms, skipped = _wire_rows( - _wire_get(body, "rooms", what, list), "room todos", _wire_row_copy, skip_bad_rows=True - ) rooms: list[RoomTodos] = [] - for raw in raw_rooms: - if "group_id" not in raw: - skipped += 1 + # A room that is not an object, or has no id, and an item that is not an object are + # left out, as this read always has; a todo object of the wrong shape fails it. + for raw in _wire_get(body, "rooms", what, list): + if not isinstance(raw, dict) or "group_id" not in raw: continue raw_items = _optional_list(raw, "items", "room todos") objects = [item for item in raw_items if isinstance(item, dict)] - skipped += len(raw_items) - len(objects) # An object that is not a todo means the shape is not the one this client knows: # that fails the whole read (the caller shows your own list and no rooms). rooms.append( RoomTodos( group_id=str(_wire_get(raw, "group_id", "room todos", str, int)), name=str(raw.get("name") or ""), - items=_wire_rows(objects, "room todo", _room_todo_from_dict)[0], + items=_wire_rows(objects, "room todo", _room_todo_from_dict), ) ) - return RoomTodosList(rooms=rooms, degraded=bool(body.get("degraded")), skipped=skipped) + return RoomTodosList(rooms=rooms, degraded=bool(body.get("degraded"))) def calendar_range( self, *, start: str, days: int, principal: str | None = None, view: str | None = None @@ -3016,8 +2982,8 @@ def list_scheduled_tasks( resp = self._request("GET", f"{_scheduled_tasks_path(group_id)}{query}") body = resp.json() if group_id: - return [*_wire_rows(body, "room scheduled task", _room_scheduled_task_from_dict)[0]] - return _wire_rows(body, "scheduled task", _scheduled_task_from_dict)[0] + return [*_wire_rows(body, "room scheduled task", _room_scheduled_task_from_dict)] + return _wire_rows(body, "scheduled task", _scheduled_task_from_dict) def get_scheduled_task( self, task_id: str, *, group_id: str | None = None @@ -3063,7 +3029,7 @@ def list_scheduled_task_runs( params=_keyset_params(limit, before, before_id), ) body = resp.json() - return _wire_rows(body, "scheduled task run", _scheduled_run_from_dict)[0] + return _wire_rows(body, "scheduled task run", _scheduled_run_from_dict) def get_scheduled_task_thread( self, @@ -3087,7 +3053,7 @@ def get_scheduled_task_thread( params=_keyset_params(limit, before, before_id), ) body = resp.json() - return _wire_rows(body, "scheduled task message", _scheduled_message_from_dict)[0] + return _wire_rows(body, "scheduled task message", _scheduled_message_from_dict) def create_scheduled_task( self, @@ -3335,7 +3301,7 @@ def trajectory_list( params["principal"] = principal resp = self._request("GET", "/api/v1/trajectories", params=params) body = resp.json() - return _wire_rows(body, "trajectory", _trajectory_list_entry)[0] + return _wire_rows(body, "trajectory", _trajectory_list_entry) def chat_history(self) -> ChatHistory: """``GET /api/v1/chat/history`` — today's live Pepper thread, oldest first. @@ -4049,7 +4015,7 @@ def list_group_topics(self, group_id: str) -> list[GroupTopicSummary]: body = _wire_row(self._request("GET", f"/api/v1/groups/{group_id}/topics").json(), what) return _wire_rows( _optional_list(body, "topics", what), "group topic", _group_topic_from_dict - )[0] + ) def list_group_messages( self, @@ -4077,15 +4043,11 @@ def list_group_messages( ).json() what = "group messages response" body = _wire_row(body, what) - messages, skipped = _wire_rows( - _optional_list(body, "messages", what), - "group message", - group_message_from_dict, - skip_bad_rows=True, + messages = _wire_rows( + _optional_list(body, "messages", what), "group message", group_message_from_dict ) return GroupMessagePage( messages=messages, - skipped=skipped, next_before=body.get("next_before"), permalink_target_missing=body.get("permalink_target_missing", False), ) @@ -4341,7 +4303,7 @@ def group_roster(self, group_id: str) -> list[GroupRosterMember]: body = _wire_row(self._request("GET", f"/api/v1/groups/{group_id}/roster").json(), what) return _wire_rows( _optional_list(body, "members", what), "group roster member", _roster_member_from_dict - )[0] + ) def create_group(self, *, people: list[str], name: str | None = None) -> dict[str, Any]: """``POST /api/v1/groups`` — start a room from a member set. @@ -4415,7 +4377,7 @@ def group_app_launcher(self, group_id: str) -> tuple[list[GroupAppTile], bool]: tiles = _wire_rows( _optional_list(body, "tiles", what), "group app tile", _app_tile_from_dict ) - return tiles[0], body.get("installed_unavailable", False) + return tiles, body.get("installed_unavailable", False) def group_app_chat( self, @@ -4469,7 +4431,7 @@ def list_artifacts( name: str | None = None, name_prefix: str | None = None, limit: int | None = None, - ) -> ArtifactListPage: + ) -> ArtifactListResponse: """``GET /api/v1/artifacts`` — list and search one owner's artifacts. ``principal`` omitted (or equal to the caller) is self-access with no @@ -4495,15 +4457,10 @@ def list_artifacts( params[key] = value what = "artifact list response" body = _wire_row(self._request("GET", "/api/v1/artifacts", params=params).json(), what) - items, skipped = _wire_rows( - _optional_list(body, "items", what), - "artifact list item", - _artifact_list_item_from_dict, - skip_bad_rows=True, - ) - return ArtifactListPage( - truncated=_wire_get(body, "truncated", what, bool), items=items, skipped=skipped + items = _wire_rows( + _optional_list(body, "items", what), "artifact list item", _artifact_list_item_from_dict ) + return ArtifactListResponse(truncated=_wire_get(body, "truncated", what, bool), items=items) def get_artifact_detail(self, artifact_id: str) -> ArtifactDetail: """``GET /api/v1/artifacts/{id}/detail`` — one artifact's full text. @@ -5379,9 +5336,10 @@ def _page_params(limit: int, before: str | None) -> dict[str, Any]: def _malformed(what: str, raw: object = None) -> ApiError: - """A malformed successful response: status 200, ``what`` names the shape or field that - failed, and the context is the first 200 characters of ``raw`` (never the whole payload).""" - return ApiError(status=200, body=str(raw)[:200], detail=f"malformed response: {what}") + """A malformed successful response: status 200 and ``what`` naming the shape or field that + failed. ``raw`` is never put in the error: a response body can carry a credential (the + device poll's token), and an ``ApiError`` is printed and logged.""" + return ApiError(status=200, body="", detail=f"malformed response: {what}") def _wire_row(raw: object, what: str) -> dict[str, Any]: @@ -5448,24 +5406,10 @@ def _wire_list(raw: object, what: str) -> list[Any]: return raw -def _wire_rows[T]( - raw: object, what: str, parse: Callable[[dict[str, Any]], T], *, skip_bad_rows: bool = False -) -> tuple[list[T], int]: - """``parse`` over each element of the array ``raw``: the parsed rows and how many were left - out. A response that is not an array always fails. With ``skip_bad_rows`` (a list a poller or - stream reads on every tick) a row that fails to parse is left out and counted, so one bad row - never costs the rest; without it the first bad row fails the whole response. Only the - malformed-response :class:`ApiError` is caught, never a programmer error.""" - parsed: list[T] = [] - skipped = 0 - for item in _wire_list(raw, what): - try: - parsed.append(parse(_wire_row(item, what))) - except ApiError: - if not skip_bad_rows: - raise - skipped += 1 - return parsed, skipped +def _wire_rows[T](raw: object, what: str, parse: Callable[[dict[str, Any]], T]) -> list[T]: + """``parse`` over each element of the array ``raw``. A response that is not an array, or any + row that fails to parse, fails the whole response: no row is ever silently left out.""" + return [parse(_wire_row(item, what)) for item in _wire_list(raw, what)] def _fields[T](cls: type[T], row: dict[str, Any], **parsed: Any) -> T: diff --git a/src/pepper_cli/tui/poller.py b/src/pepper_cli/tui/poller.py index 57ccc0d..3623d6d 100644 --- a/src/pepper_cli/tui/poller.py +++ b/src/pepper_cli/tui/poller.py @@ -284,7 +284,7 @@ def fetch_room_shelf(api: ApiClient, room_id: str) -> tuple[list[GroupAppTile], def fetch_todos(api: ApiClient, owner: str | None, *, mine: bool) -> list[TodoEntry]: """Every todo of one owner, open and closed, in one call: a room's (``owner`` is its id) or your own (``None``). ``mine`` keeps what someone asked of you.""" - return api.list_todos(status="all", group_id=owner, mine=mine, skip_bad_rows=True) + return api.list_todos(status="all", group_id=owner, mine=mine) @dataclass(frozen=True) @@ -303,7 +303,7 @@ def fetch_own_todos(api: ApiClient, *, mine: bool) -> OwnTodos: A failure of your own list raises, as any pane read does; a 401 on either one too, so the app takes its login path (an upgrade-required answer is not caught here either). """ - todos = api.list_todos(status="all", mine=mine, skip_bad_rows=True) + todos = api.list_todos(status="all", mine=mine) try: listed = api.list_room_todos(mine=mine) except ApiError as exc: diff --git a/tests/test_api_client_malformed_parsers.py b/tests/test_api_client_malformed_parsers.py index b0ab17d..7b8cecb 100644 --- a/tests/test_api_client_malformed_parsers.py +++ b/tests/test_api_client_malformed_parsers.py @@ -1,16 +1,19 @@ """The rest of the typed parsers (todos, groups, artifacts, notes, skills, chat send, sign-in) turn a malformed successful response into ``ApiError`` (status 200) naming the field or shape, -never a ``KeyError``/``TypeError``, and never echo the offending value. Lists a poller reads on -a timer skip and count a bad row; every other list fails whole.""" +never a ``KeyError``/``TypeError``, and never echo the offending value. A bad row fails the +whole list, so nothing is silently left out.""" from __future__ import annotations import httpx import pytest -from pepper_cli import api_client +from pepper_cli import api_client, cli from pepper_cli.api_client import ApiError from pepper_cli.secret import SecretStr +from pepper_cli.tui import app as tui_app +from pepper_cli.tui import poller +from tests import tui_support as ts def _api(body: object) -> api_client.ApiClient: @@ -213,36 +216,38 @@ def test_older_server_rows_keep_their_defaults() -> None: ) with _api(_groups(groups=[_group(topics=None, future=1)])) as api: listed = api.list_groups() - assert (listed.groups[0].topics, listed.skipped, listed.features) == ([], 0, ()) + assert (listed.groups[0].topics, listed.features) == ([], ()) with _api({"truncated": False}) as api: assert api.list_artifacts().items == [] -# --- polled lists skip and count a bad row; the others fail whole ----------------------------- +# --- every list fails whole on a bad row: nothing is silently left out ------------------------ -def test_the_group_list_skips_and_counts_a_malformed_room() -> None: - body = _groups(groups=[_group(), _group(group_id=None), "x", _group(group_id="g3")]) - with _api(body) as api: - listed = api.list_groups() - assert [g.group_id for g in listed.groups] == ["g1", "g3"] - assert listed.skipped == 2 - - -def test_a_room_with_a_malformed_topic_is_skipped_not_the_whole_list() -> None: - body = _groups(groups=[_group(topics=[{"topic_id": "x"}]), _group(group_id="g2")]) - with _api(body) as api: - listed = api.list_groups() - assert [g.group_id for g in listed.groups] == ["g2"] - assert listed.skipped == 1 +@pytest.mark.parametrize( + "rooms", + [ + [_group(), _group(group_id=None)], + [_group(), "x"], + [_group(topics=[{"topic_id": "x"}]), _group(group_id="g2")], + ], +) +def test_a_malformed_room_fails_the_group_list(rooms: list) -> None: + with _api(_groups(groups=rooms)) as api, pytest.raises(ApiError) as raised: + api.list_groups() + _malformed(raised) -def test_group_messages_skip_and_count_a_malformed_row() -> None: - body = {"messages": [_message(), _message(id=None), 4, _message(id="m3")]} - with _api(body) as api: - page = api.list_group_messages("g", "tp") - assert [m.id for m in page.messages] == ["s", "m3"] - assert page.skipped == 2 +@pytest.mark.parametrize( + "messages", [[_message(), _message(id=None)], [_message(), 4], [_message(cards=[{"a": 1}])]] +) +def test_a_malformed_group_message_fails_the_page(messages: list) -> None: + with _api({"messages": messages}) as api, pytest.raises(ApiError) as raised: + api.list_group_messages("g", "tp", at="m1") + _malformed(raised) + # A refresh that fails this way is retried (200 is not a permanent refusal), so a stale + # row is never left in place as if it had been read again. + assert raised.value.status not in tui_app._PUBLISH_PERMANENT @pytest.mark.parametrize("bad", [{"messages": "x"}, []]) @@ -251,43 +256,31 @@ def test_group_messages_that_are_not_a_list_fail_the_page(bad: object) -> None: api.list_group_messages("g", "tp") -def test_a_group_message_with_a_malformed_card_is_a_bad_row() -> None: - body = {"messages": [_message(cards=[{"app_key": "k"}]), _message(id="ok")]} - with _api(body) as api: - page = api.list_group_messages("g", "tp") - assert [m.id for m in page.messages] == ["ok"] - assert page.skipped == 1 - - -def test_artifacts_skip_and_count_a_malformed_item() -> None: +def test_a_malformed_artifact_fails_the_list() -> None: good = {"id": "a", "name": "n", "kind": "k", "updated_at": "u", "etag": "e"} - with _api({"truncated": False, "items": [good, {"id": "b"}, good]}) as api: - listed = api.list_artifacts() - assert (len(listed.items), listed.skipped) == (2, 1) + body = {"truncated": False, "items": [good, {"id": "b"}]} + with _api(body) as api, pytest.raises(ApiError) as raised: + api.list_artifacts() + _malformed(raised) -def test_todos_skip_only_when_the_caller_polls() -> None: - rows = [_todo(), _without(_todo(id="t2"), "status"), _todo(id="t3")] - with _api(rows) as api: - polled = api.list_todos(skip_bad_rows=True) - assert ([t.id for t in polled], polled.skipped) == (["t1", "t3"], 1) +def test_a_malformed_todo_fails_the_list_and_the_pane_read() -> None: + rows = [_todo(), _todo(id="t2", title=None)] with _api(rows) as api, pytest.raises(ApiError): api.list_todos() - - -def test_a_todo_list_that_is_not_a_list_fails_even_when_skipping() -> None: + with _api(rows) as api, pytest.raises(ApiError): + poller.fetch_todos(api, None, mine=True) with _api({"todos": []}) as api, pytest.raises(ApiError): - api.list_todos(skip_bad_rows=True) + api.list_todos() -def test_room_todos_skip_non_objects_but_a_malformed_todo_fails_the_read() -> None: +def test_room_todos_leave_out_non_objects_but_a_malformed_todo_fails_the_read() -> None: body = { "rooms": [{"name": "no id", "items": []}, "junk", {"group_id": "g", "items": [_todo(), 1]}] } with _api(body) as api: listed = api.list_room_todos() assert [(r.group_id, len(r.items)) for r in listed.rooms] == [("g", 1)] - assert listed.skipped == 3 bad = {"rooms": [{"group_id": "g", "items": [{"id": "x"}]}]} with _api(bad) as api, pytest.raises(ApiError) as raised: api.list_room_todos() @@ -297,6 +290,45 @@ def test_room_todos_skip_non_objects_but_a_malformed_todo_fails_the_read() -> No assert "'rooms'" in _malformed(raised) +def test_a_malformed_same_named_note_fails_the_lookup_rather_than_resolving_the_other() -> None: + good = {"id": "A", "name": "Runbook", "kind": "note", "updated_at": "u", "etag": "e"} + bad = {"id": "B", "name": "Runbook", "kind": "note", "updated_at": "u"} + with _api({"truncated": False, "items": [good, bad]}) as api, pytest.raises(ApiError): + cli._resolve_note(api, room_principal=None, value="Runbook") + + +def test_the_rail_keeps_its_etag_when_a_room_is_malformed() -> None: + server = ts.standard_server() + with server.client() as api: + rail = poller.RailPoller(api) + first = rail.step() + assert first.groups is not None + rail.commit(first) + kept = first.etag + assert len(first.groups.groups) == 2 + good_topic = dict(server.rooms[1]["topics"][0]) + server.rooms[1]["topics"][0] = {"topic_id": "x"} # no name + server.bump() + with pytest.raises(ApiError): + rail.step() + assert rail._etag == kept # nothing committed: the partial list is never adopted + server.rooms[1]["topics"][0] = good_topic + server.bump() + again = rail.step() + assert again.groups is not None + assert len(again.groups.groups) == 2 + + +def test_a_malformed_device_poll_never_carries_the_token_in_the_error() -> None: + body = {"status": "approved", "token": "pep_pat_sentinel"} + client = httpx.Client(transport=httpx.MockTransport(lambda _r: httpx.Response(200, json=body))) + with pytest.raises(ApiError) as raised: + api_client.device_poll("http://example.com", SecretStr("dc"), client=client) + assert "pep_pat_sentinel" not in raised.value.body + assert "pep_pat_sentinel" not in str(raised.value) + assert "pep_pat_sentinel" not in repr(raised.value) + + # --- sign-in ---------------------------------------------------------------------------------- From b5fc6e3d958ff2d3780893d1c12f5a40982644bc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:23:56 +0000 Subject: [PATCH 3/3] Type-check optional scalars on the wire instead of coercing them _note_comments_from_dict called int() on resolved_count, so an object or list value escaped as TypeError. A new _wire_opt helper returns the default for a missing or null value and raises the malformed-response ApiError for any other wrong type (a bool is never an int). It is used for resolved_count and for the bare str() coercions in this PR's typed parsers: a note comment's body, created_at and author name, the note comments artifact_id, the room todos name and the blog publish/withdraw card. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QNDehAurHo1CzCzisi6nYx --- src/pepper_cli/api_client.py | 25 ++++++++---- tests/test_api_client_malformed_parsers.py | 47 ++++++++++++++++++++++ 2 files changed, 64 insertions(+), 8 deletions(-) diff --git a/src/pepper_cli/api_client.py b/src/pepper_cli/api_client.py index 5671436..f3af770 100644 --- a/src/pepper_cli/api_client.py +++ b/src/pepper_cli/api_client.py @@ -2101,9 +2101,9 @@ def _note_comment_from_dict(row: dict[str, Any]) -> NoteComment: raise _malformed(f"{what} field 'author' has the wrong type", row) return NoteComment( id=str(_wire_get(row, "id", what, str, int)), - body=str(row.get("body") or ""), - author=str((author or {}).get("display_name") or ""), - created_at=str(row.get("created_at") or ""), + body=_wire_opt(row, "body", what, "", str), + author=_wire_opt(author or {}, "display_name", "note comment author", "", str), + created_at=_wire_opt(row, "created_at", what, "", str), mentions=_mention_ids( [ {"person_id": m["id"]} if isinstance(m, dict) and "id" in m else m @@ -2138,12 +2138,12 @@ def _note_comments_from_dict(body: dict[str, Any]) -> NoteComments: _optional_list(body, "threads", what), "note comment thread", _note_thread_from_dict ) return NoteComments( - artifact_id=str(body.get("artifact_id") or ""), + artifact_id=str(_wire_opt(body, "artifact_id", what, "", str, int)), group_id=body.get("group_id"), topic_id=body.get("topic_id"), etag=body.get("etag"), threads=threads, - resolved_count=int(body.get("resolved_count") or 0), + resolved_count=_wire_opt(body, "resolved_count", what, 0, int), ) @@ -2645,7 +2645,7 @@ def list_room_todos(self, *, mine: bool = False) -> RoomTodosList: rooms.append( RoomTodos( group_id=str(_wire_get(raw, "group_id", "room todos", str, int)), - name=str(raw.get("name") or ""), + name=_wire_opt(raw, "name", "room todos", "", str), items=_wire_rows(objects, "room todo", _room_todo_from_dict), ) ) @@ -4744,7 +4744,7 @@ def blog_publish( slug=_wire_get(body, "slug", what, str), url=_wire_get(body, "url", what, str), republished=_wire_get(body, "republished", what, bool), - card=str(body.get("card", "")), + card=_wire_opt(body, "card", what, "", str), copy=body.get("copy"), ) @@ -4758,7 +4758,7 @@ def blog_withdraw(self, group_id: str, post_id: str) -> BlogWithdrawn: return BlogWithdrawn( post_id=str(_wire_get(body, "post_id", what, str, int)), already=_wire_get(body, "already", what, bool), - card=str(body.get("card", "")), + card=_wire_opt(body, "card", what, "", str), copy=body.get("copy"), ) @@ -5376,6 +5376,15 @@ def _optional_list(row: dict[str, Any], key: str, what: str) -> list[Any]: return _wire_get(row, key, what, list) +def _wire_opt(row: dict[str, Any], key: str, what: str, default: Any, *types: type) -> Any: + """``row[key]`` when present and one of ``types``; ``default`` when it is missing or + ``null``. A value of any other type (a bool where an int is wanted, say) is a + malformed-response :class:`ApiError` naming the field, never a ``TypeError``.""" + if row.get(key) is None: + return default + return _wire_get(row, key, what, *types) + + def _wire_get( row: dict[str, Any], key: str, what: str, *types: type, nullable: bool = False ) -> Any: diff --git a/tests/test_api_client_malformed_parsers.py b/tests/test_api_client_malformed_parsers.py index 7b8cecb..c19f8db 100644 --- a/tests/test_api_client_malformed_parsers.py +++ b/tests/test_api_client_malformed_parsers.py @@ -329,6 +329,53 @@ def test_a_malformed_device_poll_never_carries_the_token_in_the_error() -> None: assert "pep_pat_sentinel" not in repr(raised.value) +# --- an optional scalar keeps its default when absent, and fails typed when wrong ------------ + + +@pytest.mark.parametrize("bad", [{"bad": 1}, True, "3", 1.5]) +def test_a_wrong_typed_resolved_count_fails_the_comment_read(bad: object) -> None: + with _api({"threads": [], "resolved_count": bad}) as api, pytest.raises(ApiError) as raised: + api.list_note_comments("a") + assert "'resolved_count'" in _malformed(raised) + + +def test_an_absent_resolved_count_keeps_its_default() -> None: + for body in ({"threads": []}, {"threads": [], "resolved_count": None}): + with _api(body) as api: + assert api.list_note_comments("a").resolved_count == 0 + with _api({"threads": [], "resolved_count": 2}) as api: + assert api.list_note_comments("a").resolved_count == 2 + + +@pytest.mark.parametrize( + ("message", "names"), + [ + ({"id": "c", "body": {"x": 1}}, "'body'"), + ({"id": "c", "created_at": 5}, "'created_at'"), + ({"id": "c", "author": {"display_name": ["x"]}}, "'display_name'"), + ], +) +def test_a_wrong_typed_comment_field_fails_the_read(message: dict, names: str) -> None: + with _api({"threads": [{"message": message}]}) as api, pytest.raises(ApiError) as raised: + api.list_note_comments("a") + assert names in _malformed(raised) + + +def test_a_wrong_typed_blog_card_or_room_todos_name_fails_the_read() -> None: + with ( + _api({"post_id": "p", "already": False, "card": 1}) as api, + pytest.raises(ApiError) as raised, + ): + api.blog_withdraw("g", "p") + assert "'card'" in _malformed(raised) + with ( + _api({"rooms": [{"group_id": "g", "name": 3, "items": []}]}) as api, + pytest.raises(ApiError) as raised, + ): + api.list_room_todos() + assert "'name'" in _malformed(raised) + + # --- sign-in ----------------------------------------------------------------------------------