Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(chat): views cite results across the conversation, and setup failures end as chat errors (#3834)

Raghav Chamadiya5e402b9e5eb2
diff --git a/docs/architecture/chat.md b/docs/architecture/chat.md
index 08c2c7578..6778bacde 100644
--- a/docs/architecture/chat.md
+++ b/docs/architecture/chat.md
@@ -273,6 +273,12 @@ for each iteration:
After the loop, the assistant message (text + all tool calls with results) is
saved to the database and a `done` event is emitted.
+**Charts in chat:** the model calls an analysis tool, then the chat-only
+`show_view` tool, which the server turns into a table or chart from that
+result. Every result the model sees starts with its `artifact_id`, and
+`show_view` takes any id from the conversation or `latest:<tool_name>` for
+that tool's newest result. A chart whose values are all zero is not drawn.
+
---
## 8. REST API Endpoints
diff --git a/packages/cli/src/repowise/cli/ui/progress.py b/packages/cli/src/repowise/cli/ui/progress.py
index fe0c9cbbc..db4e80cf0 100644
--- a/packages/cli/src/repowise/cli/ui/progress.py
+++ b/packages/cli/src/repowise/cli/ui/progress.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import contextlib
-import re
from collections.abc import Callable
from typing import Any
@@ -12,6 +11,7 @@ from rich.progress import ProgressColumn, Task
from rich.text import Text
from repowise.cli.ui.brand import ERR, WARN, print_phase_header
+from repowise.core.redaction import redact_secrets
# Message levels that mean "this run degraded". ``notice`` is deliberately not
# here: it is visible (warning-styled) but informational, e.g. a file skipped on
@@ -38,37 +38,6 @@ _STAGE_HEADERS: dict[str, tuple[int, str, str]] = {
}
-# Credential shapes that turn up inside provider exception text. OpenAI and
-# Anthropic auth errors quote the offending key back ("Incorrect API key
-# provided: sk-abc…"), and several pipeline warnings interpolate ``str(exc)``
-# verbatim. That was transient terminal output; once the warnings are also
-# written to ``.repowise/state.json`` it becomes a secret at rest, in the one
-# file agents and MCP tools read back.
-_SECRET_PATTERNS = (
- re.compile(r"\bsk-[A-Za-z0-9_-]{8,}"), # OpenAI / Anthropic
- re.compile(r"\bAIza[A-Za-z0-9_-]{10,}"), # Google
- re.compile(r"\bgh[pousr]_[A-Za-z0-9]{10,}"), # GitHub
- re.compile(r"\bgl(?:pat|dt|rt|ptt|oas|imt|cbt)-[\w.-]{10,}"), # GitLab
- re.compile(r"\bGR1348941[\w-]{10,}"), # GitLab runner registration
- re.compile(r"\b[0-9A-Za-z]{76}AZDO[0-9A-Za-z]{4}\b"), # Azure DevOps
-)
-# A git remote quoted in a clone or fetch error carries its credentials.
-_URL_USERINFO = re.compile(r"://[^\s/@:]+:[^\s/@]+@")
-
-
-def redact_secrets(text: str) -> str:
- """Blank anything key-shaped in *text*.
-
- Deliberately conservative: it matches issuer-prefixed shapes rather than
- "any long token", because over-matching would eat the file paths and hashes
- that make these messages useful. A key in an unrecognised format still gets
- through, so this reduces exposure rather than guaranteeing its absence.
- """
- for pattern in _SECRET_PATTERNS:
- text = pattern.sub("[redacted]", text)
- return _URL_USERINFO.sub("://***@", text)
-
-
class MaybeCountColumn(ProgressColumn):
"""Progress column that shows ``completed/total`` when total is known,
or just ``completed`` when total is ``None`` (indeterminate phase).
diff --git a/packages/core/src/repowise/core/redaction.py b/packages/core/src/repowise/core/redaction.py
new file mode 100644
index 000000000..20227f198
--- /dev/null
+++ b/packages/core/src/repowise/core/redaction.py
@@ -0,0 +1,39 @@
+"""Blank credential shapes in text that may be shown, logged or stored.
+
+Provider and forge errors quote what they were sent: auth errors echo the key
+("Incorrect API key provided: sk-abc..."), an HTTP error carries its URL (a
+Google ``?key=`` query) and a git error its remote with credentials.
+"""
+
+from __future__ import annotations
+
+import re
+
+_SECRET_PATTERNS = (
+ re.compile(r"\bsk-[A-Za-z0-9_-]{8,}"), # OpenAI / Anthropic
+ re.compile(r"\bAIza[A-Za-z0-9_-]{10,}"), # Google
+ re.compile(r"\bgh[pousr]_[A-Za-z0-9]{10,}"), # GitHub
+ re.compile(r"\bgl(?:pat|dt|rt|ptt|oas|imt|cbt)-[\w.-]{10,}"), # GitLab
+ re.compile(r"\bGR1348941[\w-]{10,}"), # GitLab runner registration
+ re.compile(r"\b[0-9A-Za-z]{76}AZDO[0-9A-Za-z]{4}\b"), # Azure DevOps
+)
+# A key in a URL query (Google's ``?key=``) or an Authorization header value.
+_QUERY_KEY = re.compile(r"([?&](?:api[_-]?)?key=)[^&\s'\"]+", re.IGNORECASE)
+_BEARER = re.compile(r"(\bBearer\s+)[A-Za-z0-9._~+/=-]{8,}", re.IGNORECASE)
+# A git remote quoted in a clone or fetch error carries its credentials.
+_URL_USERINFO = re.compile(r"://[^\s/@:]+:[^\s/@]+@")
+
+
+def redact_secrets(text: str) -> str:
+ """Blank anything key-shaped in *text*.
+
+ Deliberately conservative: it matches issuer-prefixed shapes rather than
+ "any long token", because over-matching would eat the file paths and hashes
+ that make these messages useful. A key in an unrecognised format still gets
+ through, so this reduces exposure rather than guaranteeing its absence.
+ """
+ for pattern in _SECRET_PATTERNS:
+ text = pattern.sub("[redacted]", text)
+ text = _QUERY_KEY.sub(r"\1[redacted]", text)
+ text = _BEARER.sub(r"\1[redacted]", text)
+ return _URL_USERINFO.sub("://***@", text)
diff --git a/packages/server/src/repowise/server/chat_errors.py b/packages/server/src/repowise/server/chat_errors.py
new file mode 100644
index 000000000..0f6883d86
--- /dev/null
+++ b/packages/server/src/repowise/server/chat_errors.py
@@ -0,0 +1,95 @@
+"""User-facing copy for the chat failures a person can fix.
+
+A missing provider or a rejected API key is a setup problem, not a server
+bug: the chat says what happened and what to do next. Provider error text can
+quote the request (a URL with its key, an echoed body), so the person sees a
+plain line and the server log keeps the redacted detail. Anything else stays
+an internal error, logged with its traceback.
+"""
+
+from __future__ import annotations
+
+import functools
+import importlib
+import logging
+
+from repowise.core.providers.llm.base import ProviderError
+from repowise.core.redaction import redact_secrets
+
+logger = logging.getLogger(__name__)
+
+NO_PROVIDER_MESSAGE = (
+ "No LLM provider is configured. Open Settings to add one, then send your message again."
+)
+INVALID_PROVIDER_MESSAGE = (
+ "The chat provider configuration is invalid. Check it in Settings, then send "
+ "your message again."
+)
+PROVIDER_START_MESSAGE = (
+ "Could not start the chat provider. Check its settings in Settings; "
+ "the server log has the details."
+)
+
+# Base classes of the provider SDKs a chat provider may let through unwrapped.
+# Matched by class, not package: a tool's own httpx or google.auth error is
+# not a provider failure. litellm's errors subclass openai's.
+_SDK_ERRORS = (
+ ("anthropic", "APIError"),
+ ("openai", "OpenAIError"),
+ ("google.genai.errors", "APIError"),
+ ("google.api_core.exceptions", "GoogleAPIError"),
+ ("ollama", "ResponseError"),
+)
+
+
+def _sdk_error_types() -> tuple[type[BaseException], ...]:
+ """The installed SDKs' error bases, imported on the first failure only."""
+ found: list[type[BaseException]] = []
+ for module, name in _SDK_ERRORS:
+ try:
+ found.append(getattr(importlib.import_module(module), name))
+ except (ImportError, AttributeError):
+ continue
+ return tuple(found)
+
+
+def _status(exc: BaseException) -> int | None:
+ for attribute in ("status_code", "code"):
+ value = getattr(exc, attribute, None)
+ if isinstance(value, int) and not isinstance(value, bool):
+ return value
+ return None
+
+
+def provider_failure(exc: BaseException, provider_name: str) -> str | None:
+ """The message for a provider call that failed, or None when *exc* is not one."""
+ is_provider_error = isinstance(exc, ProviderError)
+ if not (is_provider_error or isinstance(exc, _sdk_error_types())):
+ return None
+ detail = redact_secrets(str(exc))
+ logger.warning("chat_provider_failed: %s: %s", type(exc).__name__, detail)
+ status = _status(exc)
+ if status in (401, 403):
+ return (
+ f"The {provider_name} provider rejected its API key (HTTP {status}). "
+ "Check the key in Settings, then send your message again."
+ )
+ if status == 429:
+ return (
+ f"The {provider_name} provider is rate limiting requests. "
+ "Wait a moment, then send your message again."
+ )
+ if is_provider_error:
+ # Repowise's own wrapper: its text is written to be read.
+ return detail
+ http = f", HTTP {status}" if status is not None else ""
+ return (
+ f"The {provider_name} provider failed ({type(exc).__name__}{http}). "
+ "See the server log for details."
+ )
+
+
+def internal_error(exc: BaseException) -> str:
+ """The line for a failure no person can fix; the traceback goes to the log."""
+ return f"Internal error: {type(exc).__name__}: {redact_secrets(str(exc))}"
diff --git a/packages/server/src/repowise/server/chat_grounding.py b/packages/server/src/repowise/server/chat_grounding.py
index ea4fdfbbb..f3dee4358 100644
--- a/packages/server/src/repowise/server/chat_grounding.py
+++ b/packages/server/src/repowise/server/chat_grounding.py
@@ -83,7 +83,7 @@ class Grounding:
"role": "tool",
"tool_call_id": self.tool_id,
"name": self.tool_name,
- "content": json.dumps(self.result),
+ "content": json.dumps(self.result, default=str),
},
]
diff --git a/packages/server/src/repowise/server/chat_prompt.py b/packages/server/src/repowise/server/chat_prompt.py
index ea2ef073b..3bc790275 100644
--- a/packages/server/src/repowise/server/chat_prompt.py
+++ b/packages/server/src/repowise/server/chat_prompt.py
@@ -7,6 +7,7 @@ import re
from typing import Any
from repowise.server.chat_artifacts import normalize_message_artifacts
+from repowise.server.chat_references import replayed_result
from repowise.server.chat_tools import ChatToolContract
from repowise.server.schemas.chat import ChatPageContext
@@ -15,7 +16,7 @@ _SYSTEM_PROMPT_TEMPLATE = """You are a codebase intelligence assistant for the r
The repository has configured these callable tools: {tool_names}. Use only this advertised surface, and use a tool when it provides stronger evidence than memory.
{routing}
{recipes}
-{page}
+{page}{views}
Guidelines:
- Cite specific file paths, function names, and line numbers from tool results; be concrete, not general
- Format responses in markdown. File paths in backticks. Code in fenced blocks.
@@ -70,11 +71,18 @@ def _page_advisory(page_context: ChatPageContext | None) -> str:
return line + "."
+_VIEWS_GUIDANCE = """
+Charts and tables: call the analysis tool first, then show_view with that result's artifact_id or latest:<tool_name>. The show_view schema lists the views. A view carries its numbers, so explain what they mean and do not repeat them.
+"""
+
+
def _build_system_prompt(
repo_name: str,
repo_path: str,
tools: list[ChatToolContract],
page_context: ChatPageContext | None = None,
+ *,
+ shows_views: bool = False,
) -> str:
recipes = [recipe.call for tool in tools for recipe in tool.entry.recipes]
recipe_text = (
@@ -89,6 +97,7 @@ def _build_system_prompt(
routing=_routing_guidance(tools),
recipes=recipe_text,
page=_page_advisory(page_context),
+ views=_VIEWS_GUIDANCE if shows_views else "",
)
@@ -167,7 +176,8 @@ def tool_result_message(tool_id: str, name: str, result: Any) -> dict[str, Any]:
"role": "tool",
"tool_call_id": tool_id,
"name": name,
- "content": json.dumps(result),
+ # default=str: a backend value JSON has no type for (a datetime) is text, not a crash.
+ "content": json.dumps(result, default=str),
}
@@ -179,9 +189,8 @@ def _assistant_history(content: dict[str, Any]) -> list[dict[str, Any]]:
return [{"role": "assistant", "content": text}]
messages = [assistant_tool_call_message(text, tool_calls)]
for tc in tool_calls:
- artifact = tc.get("artifact")
- result = artifact.get("data", {}) if isinstance(artifact, dict) else {}
- messages.append(tool_result_message(tc["id"], tc["name"], result))
+ # Stamped with the stored id, so a view in a later turn can cite it.
+ messages.append(tool_result_message(tc["id"], tc["name"], replayed_result(tc)))
return messages
diff --git a/packages/server/src/repowise/server/chat_references.py b/packages/server/src/repowise/server/chat_references.py
new file mode 100644
index 000000000..f7265f92c
--- /dev/null
+++ b/packages/server/src/repowise/server/chat_references.py
@@ -0,0 +1,149 @@
+"""Tool results a chat view may cite, across the whole conversation.
+
+``show_view`` names its source by ``artifact_id``. An id is minted when a tool
+result enters a turn and stored on that call's artifact envelope, so
+:class:`ArtifactIndex` reads the conversation's stored envelopes once per turn
+and then takes each new result of the turn as it arrives. A reference may also
+be ``latest:<tool_name>``, the newest usable result of that tool, so the model
+never has to copy an id. The id is the first key of every result the model
+sees (live or replayed), so a truncated excerpt still shows it.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass
+from typing import Any
+
+from repowise.server.chat_artifacts import ARTIFACT_ID_FIELD, normalize_message_artifacts
+
+SHOW_VIEW_TOOL = "show_view"
+LATEST_PREFIX = "latest:"
+#: References an unknown-id error lists, newest first.
+_LISTED = 8
+
+
+@dataclass(frozen=True)
+class ViewArtifact:
+ """One tool result of this conversation, as builders read it."""
+
+ artifact_id: str
+ tool_name: str
+ artifact_type: str
+ evidence_basis: str
+ arguments: dict[str, Any]
+ data: dict[str, Any]
+
+ @property
+ def usable(self) -> bool:
+ return "error" not in self.data
+
+
+def stamp(data: Mapping[str, Any], artifact_id: str) -> dict[str, Any]:
+ """*data* with ``artifact_id`` as its first key; the stamp replaces a tool's own field."""
+ return {
+ ARTIFACT_ID_FIELD: artifact_id,
+ **{key: value for key, value in data.items() if key != ARTIFACT_ID_FIELD},
+ }
+
+
+def replayed_result(call: Mapping[str, Any]) -> Any:
+ """A stored call's result as the model sees it again: stamped when a view can cite it."""
+ artifact = call.get("artifact")
+ data = artifact.get("data", {}) if isinstance(artifact, Mapping) else {}
+ if (
+ call.get("name") != SHOW_VIEW_TOOL
+ and isinstance(data, Mapping)
+ and "error" not in data
+ and isinstance(artifact.get("id"), str)
+ ):
+ return stamp(data, artifact["id"])
+ return data
+
+
+def _age(turns_ago: int) -> str:
+ if turns_ago == 0:
+ return "this turn"
+ return "1 turn ago" if turns_ago == 1 else f"{turns_ago} turns ago"
+
+
+class ArtifactIndex:
+ """Every citable tool result of one conversation, oldest first."""
+
+ def __init__(self) -> None:
+ self._entries: dict[str, tuple[ViewArtifact, int]] = {}
+ #: The current turn's number; earlier turns are 1..turn-1.
+ self.turn = 1
+
+ @classmethod
+ def from_history(cls, messages: Iterable[Any]) -> ArtifactIndex:
+ """Index the envelopes stored on *messages* (``id``, ``role``, ``content``)."""
+ index = cls()
+ for message in messages:
+ if message.role != "assistant":
+ continue
+ content = normalize_message_artifacts(message.content, message_id=str(message.id))
+ for call in content.get("tool_calls") or []:
+ if isinstance(call, dict):
+ index._add_stored(call)
+ index.turn += 1
+ return index
+
+ def _add_stored(self, call: dict[str, Any]) -> None:
+ artifact = call.get("artifact")
+ if call.get("name") == SHOW_VIEW_TOOL or not isinstance(artifact, dict):
+ return
+ artifact_id, data = artifact.get("id"), artifact.get("data")
+ if not isinstance(artifact_id, str) or not isinstance(data, dict):
+ return
+ evidence = artifact.get("evidence")
+ arguments = call.get("arguments")
+ self.add(
+ ViewArtifact(
+ artifact_id=artifact_id,
+ tool_name=str(call.get("name", "")),
+ artifact_type=str(artifact.get("type") or "generic"),
+ evidence_basis=str((evidence or {}).get("basis", "unknown"))
+ if isinstance(evidence, dict)
+ else "unknown",
+ arguments=arguments if isinstance(arguments, dict) else {},
+ data=data,
+ )
+ )
+
+ def add(self, artifact: ViewArtifact) -> None:
+ self._entries[artifact.artifact_id] = (artifact, self.turn)
+
+ def resolve(self, reference: Any) -> ViewArtifact | None:
+ """The artifact an id or ``latest:<tool_name>`` names, or None."""
+ if not isinstance(reference, str):
+ return None
+ if reference.startswith(LATEST_PREFIX):
+ tool = reference[len(LATEST_PREFIX) :].strip()
+ return next(
+ (
+ artifact
+ for artifact, _ in reversed(self._entries.values())
+ if artifact.tool_name == tool and artifact.usable
+ ),
+ None,
+ )
+ entry = self._entries.get(reference)
+ return entry[0] if entry else None
+
+ def available(self) -> list[dict[str, str]]:
+ """The newest usable references, for an error the model can retry from."""
+ listed: list[dict[str, str]] = []
+ for artifact, turn in reversed(self._entries.values()):
+ if not artifact.usable:
+ continue
+ listed.append(
+ {
+ "artifact_id": artifact.artifact_id,
+ "tool": artifact.tool_name,
+ "age": _age(self.turn - turn),
+ }
+ )
+ if len(listed) == _LISTED:
+ break
+ return listed
diff --git a/packages/server/src/repowise/server/chat_session.py b/packages/server/src/repowise/server/chat_session.py
index f6c6e3dfb..1c48da8ba 100644
--- a/packages/server/src/repowise/server/chat_session.py
+++ b/packages/server/src/repowise/server/chat_session.py
@@ -11,7 +11,7 @@ events as SSE, and an in-process caller uses the class directly.
The tools a model is shown, and the only ones it can run, are the backend's
catalog for the principal narrowed by the policy's allowlist and safety
ceiling, plus the chat-only ``show_view`` tool, which builds tables and
-charts from this turn's results (:mod:`repowise.server.chat_views`), and
+charts from the conversation's tool results (:mod:`repowise.server.chat_views`), and
the chat-only ``find_suspects`` (:mod:`repowise.server.chat_suspects`).
Everything outside the loop goes through the seams in
:mod:`repowise.server.chat_seams`.
@@ -28,7 +28,7 @@ from typing import Any, Literal
from pydantic import ValidationError
-from repowise.core.providers.llm.base import ChatProvider, ProviderError
+from repowise.core.providers.llm.base import ChatProvider
from repowise.server.auth import Principal
from repowise.server.chat_artifacts import create_artifact_envelope
from repowise.server.chat_context import (
@@ -37,6 +37,7 @@ from repowise.server.chat_context import (
compose_request,
is_context_overflow,
)
+from repowise.server.chat_errors import NO_PROVIDER_MESSAGE, internal_error, provider_failure
from repowise.server.chat_figures import check_figures
from repowise.server.chat_grounding import plan_grounding, run_grounding
from repowise.server.chat_prompt import (
@@ -47,6 +48,7 @@ from repowise.server.chat_prompt import (
stored_messages_to_llm_format,
tool_result_message,
)
+from repowise.server.chat_references import ArtifactIndex
from repowise.server.chat_seams import (
ConversationStore,
NoTurnHooks,
@@ -70,7 +72,12 @@ from repowise.server.chat_suspects import (
find_suspects_schema,
run_find_suspects,
)
-from repowise.server.chat_tools import ChatToolContract, LocalToolBackend, tool_schemas
+from repowise.server.chat_tools import (
+ ChatToolContract,
+ LocalToolBackend,
+ make_json_serializable,
+ tool_schemas,
+)
from repowise.server.chat_views import SHOW_VIEW_TOOL, TurnViews, show_view_schema
from repowise.server.schemas.evidence import CardRef
@@ -171,6 +178,14 @@ async def _never_cancelled() -> bool:
# ---------------------------------------------------------------------------
+_CITATION_FIELDS = (
+ ("file_path", str),
+ ("symbol_name", str),
+ ("start_line", int),
+ ("end_line", int),
+)
+
+
def _citations(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Files the turn's tool results cite, first mention first, each with the
``artifact_id`` of the result that cited it and its entity ``ref``."""
@@ -184,10 +199,11 @@ def _citations(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
if isinstance(item, str):
citation = {"file_path": item}
elif isinstance(item, dict) and isinstance(item.get("file_path"), str):
+ # Only the types the citation contract takes: a tool's "10-20" is not a line.
citation = {
key: item[key]
- for key in ("file_path", "symbol_name", "start_line", "end_line")
- if item.get(key) is not None
+ for key, kind in _CITATION_FIELDS
+ if isinstance(item.get(key), kind) and not isinstance(item[key], bool)
}
else:
continue
@@ -332,13 +348,15 @@ class _Turn:
finds_suspects: bool = False,
question: str = "",
prior_calls: list[dict[str, Any]] | None = None,
+ artifacts: ArtifactIndex | None = None,
) -> None:
self.provider = provider
self.tools = tools
self.catalog = {tool.entry.name: tool for tool in catalog}
self.shows_views = shows_views
self.finds_suspects = finds_suspects
- self.views = TurnViews()
+ #: Earlier turns' results stay citable by show_view.
+ self.views = TurnViews(artifacts)
self.policy = policy
self.base = base
self.rounds: list[list[dict[str, Any]]] = []
@@ -369,7 +387,11 @@ class _Turn:
async def execute(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
"""Run one tool the session admits; also handed to providers that loop internally.
- Each result is stamped with the artifact id ``show_view`` takes.
+ Each result is stamped with the artifact id ``show_view`` takes. A
+ result is JSON-safe from here on, so a backend's datetime never fails
+ the request, the stream or the store: the local backend and
+ ``find_suspects`` already serialize theirs, any other backend's is
+ serialized here, once.
"""
if name == SHOW_VIEW_TOOL and self.shows_views:
return self.views.show(arguments)
@@ -382,10 +404,13 @@ class _Turn:
"error": f"Tool is not available in this session: {name}",
"error_code": "tool_not_enabled",
}
+ result = await self.tools.execute(name, arguments)
+ if not isinstance(self.tools, LocalToolBackend):
+ result = make_json_serializable(result)
return self.views.record(
name,
arguments,
- await self.tools.execute(name, arguments),
+ result,
artifact_type=tool.entry.artifact_type,
evidence_basis=tool.entry.evidence_basis,
)
@@ -477,14 +502,18 @@ class _Turn:
emitted = True
yield out
return
- except ProviderError as exc:
+ except Exception as exc:
+ # A provider failure is the person's to fix; anything else is a bug.
+ message = provider_failure(exc, self.provider.provider_name)
+ if message is None:
+ raise
overflow = is_context_overflow(exc)
if overflow and attempt == 0 and not emitted:
logger.warning("chat_context_overflow_retry")
pending.clear()
continue
self.stop_reason = "error"
- self.error = OVERFLOW_MESSAGE if overflow else str(exc)
+ self.error = OVERFLOW_MESSAGE if overflow else message
yield {"type": "error", "message": self.error}
return
@@ -788,7 +817,18 @@ class ChatSession:
outcome: _Outcome,
) -> AsyncIterator[dict[str, Any]]:
if self.provider is None:
- raise ValueError("this session was opened without a provider")
+ outcome.result = ChatTurnResult(
+ conversation_id=self.id,
+ message_id=None,
+ user_message_id=None,
+ answer="",
+ stop_reason="error",
+ provider="",
+ model="",
+ error=NO_PROVIDER_MESSAGE,
+ )
+ yield {"type": "error", "message": NO_PROVIDER_MESSAGE}
+ return
async with _turn_lock(self.id):
try:
async for event in self._turn(
@@ -801,7 +841,7 @@ class ChatSession:
raise
except Exception as exc:
logger.exception("Chat turn error")
- text = f"Internal error: {type(exc).__name__}: {exc}"
+ text = internal_error(exc)
outcome.result = self._unstored("error", error=text)
yield {"type": "error", "message": text}
@@ -885,6 +925,8 @@ class ChatSession:
self.id, {"text": message}, idempotency_key=idempotency_key
)
history = await self.store.messages(self.id)
+ # Indexed once for the turn, so each show_view is a dict lookup.
+ artifacts = ArtifactIndex.from_history(history)
opening = all(m.id == user_message_id for m in history)
catalog = self.catalog()
@@ -923,12 +965,13 @@ class ChatSession:
for call in stored.content.get("tool_calls") or []
if isinstance(call, dict)
],
+ artifacts=artifacts,
)
grounded = await turn.ground(context)
if grounded is not None:
yield grounded
system_prompt = _build_system_prompt(
- self.scope.repo_name, self.scope.repo_path, catalog, context
+ self.scope.repo_name, self.scope.repo_path, catalog, context, shows_views=shows_views
)
async for event in turn.run(system_prompt, schemas):
yield event
diff --git a/packages/server/src/repowise/server/chat_suspects.py b/packages/server/src/repowise/server/chat_suspects.py
index d25168bb0..e2c7630eb 100644
--- a/packages/server/src/repowise/server/chat_suspects.py
+++ b/packages/server/src/repowise/server/chat_suspects.py
@@ -56,6 +56,7 @@ async def run_find_suspects(arguments: dict[str, Any], repo: str | None) -> dict
from repowise.core.persistence.database import get_session
from repowise.core.suspects import Symptom
from repowise.core.suspects.index import find_suspects
+ from repowise.server.chat_tools import make_json_serializable
from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context
try:
@@ -78,8 +79,10 @@ async def run_find_suspects(arguments: dict[str, Any], repo: str | None) -> dict
ctx = await _resolve_repo_context(repo)
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- return await find_suspects(
- session, repository.id, repository.local_path, symptom, since=since, until=until
+ return make_json_serializable(
+ await find_suspects(
+ session, repository.id, repository.local_path, symptom, since=since, until=until
+ )
)
except Exception as exc: # a tool failure is the model's to read, not the turn's end
return {"error": f"{type(exc).__name__}: {exc}", "error_code": "tool_failed"}
diff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.py
index 9f6058979..ba3d1290e 100644
--- a/packages/server/src/repowise/server/chat_tools.py
+++ b/packages/server/src/repowise/server/chat_tools.py
@@ -72,15 +72,16 @@ def get_tool_schemas_for_llm(
return tool_schemas(get_tool_catalog(repo_path, principal))
-def _make_json_serializable(obj: Any) -> Any:
+def make_json_serializable(obj: Any) -> Any:
+ """*obj* as plain JSON values; a value JSON has no type for becomes its string."""
if obj is None or isinstance(obj, (bool, int, float, str)):
return obj
if isinstance(obj, dict):
- return {str(key): _make_json_serializable(value) for key, value in obj.items()}
+ return {str(key): make_json_serializable(value) for key, value in obj.items()}
if isinstance(obj, (list, tuple)):
- return [_make_json_serializable(item) for item in obj]
+ return [make_json_serializable(item) for item in obj]
if hasattr(obj, "__dict__"):
- return _make_json_serializable(vars(obj))
+ return make_json_serializable(vars(obj))
return str(obj)
@@ -145,7 +146,7 @@ async def execute_entry(
try:
scoped_arguments = dict(arguments)
_scope_repo_arg(entry, scoped_arguments, repo, pinned)
- return _make_json_serializable(await entry.fn(**scoped_arguments))
+ return make_json_serializable(await entry.fn(**scoped_arguments))
except Exception as exc:
logger.exception("Tool execution failed: %s", entry.name)
return {"error": f"{type(exc).__name__}: {exc}", "error_code": "tool_failed"}
diff --git a/packages/server/src/repowise/server/chat_views.py b/packages/server/src/repowise/server/chat_views.py
index c77b9559d..ecd1a4b34 100644
--- a/packages/server/src/repowise/server/chat_views.py
+++ b/packages/server/src/repowise/server/chat_views.py
@@ -1,8 +1,9 @@
"""Deterministic chat views: tables and charts built from a turn's tool results.
The model never writes a number into a view. It calls the chat-only
-``show_view`` tool naming a tool result already in the turn (by the
-``artifact_id`` stamped on it) and a view; a registered builder makes the part
+``show_view`` tool naming a tool result of the conversation (by the
+``artifact_id`` stamped on it, or ``latest:<tool_name>``; see
+:mod:`repowise.server.chat_references`) and a view; a registered builder makes the part
from that result, and ``build_view`` adds provenance, applies the guards and
validates it as a ``ViewPart``. Builders are pure functions registered on the
``chat-view`` seam, so a plugin adds one without editing this module.
@@ -28,6 +29,13 @@ from pydantic import TypeAdapter, ValidationError
from repowise.core.registry.plugins import SeamRegistry, load_plugins
from repowise.server.chat_artifacts import ARTIFACT_ID_FIELD
+from repowise.server.chat_references import (
+ LATEST_PREFIX,
+ SHOW_VIEW_TOOL,
+ ArtifactIndex,
+ ViewArtifact,
+ stamp,
+)
from repowise.server.schemas.evidence import MAX_WIRE_NUMBER
from repowise.server.schemas.views import (
VIEW_LIMITS,
@@ -38,7 +46,6 @@ from repowise.server.schemas.views import (
logger = logging.getLogger(__name__)
-SHOW_VIEW_TOOL = "show_view"
ATTRIBUTION_COVERAGE_FLOOR = 0.30
_PART = TypeAdapter(ViewPart)
@@ -63,18 +70,6 @@ class ViewError(ValueError):
return {"error": str(self), "error_code": self.code, **self.extra}
-@dataclass(frozen=True)
-class ViewArtifact:
- """One tool result of this turn, as builders read it."""
-
- artifact_id: str
- tool_name: str
- artifact_type: str
- evidence_basis: str
- arguments: dict[str, Any]
- data: dict[str, Any]
-
-
@dataclass(frozen=True)
class ViewBuilder:
"""A pure function from an artifact and options to a part without provenance ids.
@@ -172,6 +167,21 @@ def _guard(part: dict[str, Any], spec: ViewBuilder) -> None:
)
+def _all_zero(part: Mapping[str, Any]) -> bool:
+ """True when no series of a chart holds a value other than zero or empty."""
+ data = part.get("data")
+ rows = data.get("rows") if isinstance(data, Mapping) else None
+ series = part.get("series")
+ if not (isinstance(rows, list) and rows and isinstance(series, list) and series):
+ # No rows is its own refusal; a malformed part is left to validation.
+ return False
+ if not all(isinstance(key, str) for key in series):
+ return False
+ return all(
+ row.get(key) in (0, None) for row in rows if isinstance(row, Mapping) for key in series
+ )
+
+
def build_view(
artifact: ViewArtifact,
view: str,
@@ -212,6 +222,12 @@ def build_view(
stale=bool(meta.get("stale_warning")),
as_of=commit if isinstance(commit, str) and _SHA.match(commit) else None,
)
+ if part.get("kind") == "chart" and _all_zero(part):
+ raise ViewError(
+ "every value in this chart is zero, so there is nothing to draw; "
+ "say so in a sentence instead",
+ code="no_data",
+ )
_guard(part, spec)
try:
model = _PART.validate_python(part)
@@ -228,15 +244,16 @@ class TurnViews:
``record`` stamps each tool result with its artifact id before the model
sees it; ``unstamp`` gives the stored side the server's id and the tool's
- own data back. ``show`` is the ``show_view`` tool. ``parts`` holds the
- validated views in order.
+ own data back. ``show`` is the ``show_view`` tool; it resolves its source
+ in *artifacts*, the conversation's results indexed once for the turn.
+ ``parts`` holds the validated views in order.
"""
- def __init__(self) -> None:
- self._artifacts: dict[str, ViewArtifact] = {}
- # The exact stamped dicts handed out, so a tool's own ``artifact_id``
- # field is never mistaken for a stamp.
- self._stamped: dict[str, dict[str, Any]] = {}
+ def __init__(self, artifacts: ArtifactIndex | None = None) -> None:
+ self.artifacts = artifacts if artifacts is not None else ArtifactIndex()
+ # The exact stamped dicts handed out and the data each came from, so a
+ # tool's own ``artifact_id`` field is never mistaken for a stamp.
+ self._stamped: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {}
self.parts: list[dict[str, Any]] = []
def record(
@@ -252,23 +269,26 @@ class TurnViews:
if not isinstance(result, dict):
return result
artifact_id = uuid4().hex
- self._artifacts[artifact_id] = ViewArtifact(
- artifact_id=artifact_id,
- tool_name=tool_name,
- artifact_type=artifact_type,
- evidence_basis=evidence_basis,
- arguments=dict(arguments),
- data=result,
+ self.artifacts.add(
+ ViewArtifact(
+ artifact_id=artifact_id,
+ tool_name=tool_name,
+ artifact_type=artifact_type,
+ evidence_basis=evidence_basis,
+ arguments=dict(arguments),
+ data=result,
+ )
)
- stamped = {**result, ARTIFACT_ID_FIELD: artifact_id}
- self._stamped[artifact_id] = stamped
+ stamped = stamp(result, artifact_id)
+ self._stamped[artifact_id] = (stamped, result)
return stamped
def unstamp(self, result: dict[str, Any]) -> tuple[str | None, dict[str, Any]]:
"""The server's id and unstamped data for a ``record`` result; else ``(None, result)``."""
artifact_id = result.get(ARTIFACT_ID_FIELD)
- if isinstance(artifact_id, str) and self._stamped.get(artifact_id) is result:
- return artifact_id, self._artifacts[artifact_id].data
+ handed = self._stamped.get(artifact_id) if isinstance(artifact_id, str) else None
+ if handed is not None and handed[0] is result:
+ return artifact_id, handed[1]
return None, result
def show(self, arguments: Mapping[str, Any]) -> dict[str, Any]:
@@ -283,20 +303,27 @@ class TurnViews:
return ViewError("the view builder failed", code="builder_failed").payload()
self.parts.append(part)
receipt = {"view_id": part["id"], "kind": part["kind"], "title": part["title"]}
+ reference = arguments.get("artifact_id")
+ if isinstance(reference, str) and reference.startswith(LATEST_PREFIX):
+ # Say which result a symbolic reference picked.
+ receipt["resolved_artifact_id"] = part["source"]["artifact_id"]
+ receipt["source_tool"] = part["source"]["tool_name"]
if "summary" in part:
receipt["summary"] = part["summary"]
return receipt
def _build(self, arguments: Mapping[str, Any]) -> dict[str, Any]:
- artifact_id = arguments.get("artifact_id")
+ reference = arguments.get("artifact_id")
view = arguments.get("view")
options = arguments.get("options") or {}
- artifact = self._artifacts.get(artifact_id) if isinstance(artifact_id, str) else None
+ artifact = self.artifacts.resolve(reference)
if artifact is None:
raise ViewError(
- f"no tool result with artifact_id {artifact_id!r} in this turn; "
- "call the tool again and use the artifact_id on its result",
+ f"no tool result matches artifact_id {reference!r}. Pass an artifact_id "
+ f"from `available` or {LATEST_PREFIX}<tool_name>; if the result you need "
+ "is not listed, call its tool first",
code="unknown_artifact",
+ available=self.artifacts.available(),
)
if not isinstance(view, str) or not isinstance(options, Mapping):
raise ViewError("view must be a string and options an object", code="bad_arguments")
@@ -326,16 +353,21 @@ def show_view_schema(artifact_types: list[str] | None = None) -> dict[str, Any]:
"function": {
"name": SHOW_VIEW_TOOL,
"description": (
- "Show a table or chart built by the server from a tool result already "
- "returned in this turn. Pass that result's artifact_id. Never restate the "
- "numbers yourself; the view carries them. Views: " + ", ".join(names) + ". "
+ "Show a table or chart built by the server from a tool result of this "
+ "conversation. Call the tool first (an earlier call in the same round "
+ "counts), then pass its artifact_id, or latest:<tool_name> for that "
+ "tool's newest result. Never restate the numbers yourself; the view "
+ "carries them. Views: " + ", ".join(names) + ". "
"`table` takes options path (dotted path to a list or map in the result), "
"columns and limit."
),
"parameters": {
"type": "object",
"properties": {
- "artifact_id": {"type": "string"},
+ "artifact_id": {
+ "type": "string",
+ "description": "A tool result's artifact_id, or latest:<tool_name>.",
+ },
"view": {"type": "string", "enum": names},
"options": {"type": "object"},
},
diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.py
index be0450517..95e966d88 100644
--- a/packages/server/src/repowise/server/routers/chat.py
+++ b/packages/server/src/repowise/server/routers/chat.py
@@ -21,8 +21,15 @@ from starlette.responses import StreamingResponse
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
from repowise.core.providers.llm.base import ChatProvider
+from repowise.core.redaction import redact_secrets
from repowise.server.auth import PER_CALL_TOOL_SCOPE, Principal, get_authorizer
from repowise.server.chat_artifacts import find_artifact, set_artifact_pinned
+from repowise.server.chat_errors import (
+ INVALID_PROVIDER_MESSAGE,
+ NO_PROVIDER_MESSAGE,
+ PROVIDER_START_MESSAGE,
+ internal_error,
+)
from repowise.server.chat_grounding import plan_grounding, run_grounding
from repowise.server.chat_seams import (
SessionPolicy,
@@ -131,10 +138,23 @@ def _chat_provider(
model_override=model,
)
except ValueError as exc:
- # Unknown provider override, or no provider resolvable at all.
- raise HTTPException(400, str(exc)) from exc
+ # Every detail here is shown to the person, so none echoes the config.
+ # The two texts matched are get_chat_provider_instance's own; another
+ # ValueError (a bad base URL, say) is an invalid configuration.
+ reason = str(exc)
+ logger.warning("chat_provider_unavailable: %s", redact_secrets(reason))
+ if reason.startswith("No active provider configured"):
+ raise HTTPException(400, NO_PROVIDER_MESSAGE) from exc
+ if provider and reason.startswith("Unknown provider"):
+ raise HTTPException(
+ 400, f"Unknown provider {provider!r}. Pick a provider in Settings."
+ ) from exc
+ raise HTTPException(400, INVALID_PROVIDER_MESSAGE) from exc
except Exception as exc:
- raise HTTPException(422, f"No chat provider available: {exc}") from exc
+ logger.warning(
+ "chat_provider_start_failed: %s: %s", type(exc).__name__, redact_secrets(str(exc))
+ )
+ raise HTTPException(422, PROVIDER_START_MESSAGE) from exc
if not isinstance(instance, ChatProvider):
raise HTTPException(
422,
@@ -167,11 +187,14 @@ async def _session_sse(open_session: Any, run: Any) -> AsyncIterator[str]:
except SessionNotFoundError as exc:
yield _sse_event("data", {"type": "error", "message": str(exc)})
return
+ except HTTPException as exc:
+ # A setup failure the person can fix; ``_chat_provider`` writes these
+ # details for the person, without the config or exception text.
+ yield _sse_event("data", {"type": "error", "message": str(exc.detail)})
+ return
except Exception as exc:
logger.exception("Chat session open error")
- yield _sse_event(
- "data", {"type": "error", "message": f"Internal error: {type(exc).__name__}: {exc}"}
- )
+ yield _sse_event("data", {"type": "error", "message": internal_error(exc)})
return
try:
async for event in run(session):
@@ -193,22 +216,23 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
# this request opens must come from the factory resolved by ``repo_id``.
factory = resolve_request_session_factory(request)
repo_name, repo_path = await _get_repo_info(factory, repo_id)
- provider = _chat_provider(repo_path, repo_id, body.provider, body.model)
- scope = SessionScope(
- kind="repo",
- repo_id=repo_id,
- repo_name=repo_name,
- repo_path=repo_path,
- # In workspace mode the MCP tools address repos by alias, not by the
- # id in this URL, so every tool call is scoped to it.
- repo_alias=_workspace_alias(request, repo_path, repo_name),
- storage=factory,
- )
+ # Inside the stream, so a missing provider or any other setup failure
+ # reaches the chat as an error event instead of a bare HTTP error.
async def open_session() -> ChatSession:
+ scope = SessionScope(
+ kind="repo",
+ repo_id=repo_id,
+ repo_name=repo_name,
+ repo_path=repo_path,
+ # In workspace mode the MCP tools address repos by alias, not by the
+ # id in this URL, so every tool call is scoped to it.
+ repo_alias=_workspace_alias(request, repo_path, repo_name),
+ storage=factory,
+ )
return await ChatSession.open(
scope=scope,
- provider=provider,
+ provider=_chat_provider(repo_path, repo_id, body.provider, body.model),
principal=request_principal(request),
fallback_policy=WEB_POLICY,
conversation_id=body.conversation_id,
@@ -651,4 +675,5 @@ async def fork_conversation(
def _sse_event(event: str, data: dict[str, Any]) -> str:
"""Format a single SSE event."""
- return f"event: {event}\ndata: {json.dumps(data)}\n\n"
+ # default=str: one value JSON has no type for must not end the stream.
+ return f"event: {event}\ndata: {json.dumps(data, default=str)}\n\n"
diff --git a/tests/unit/server/test_chat_router.py b/tests/unit/server/test_chat_router.py
index f7a503f19..0f325afc2 100644
--- a/tests/unit/server/test_chat_router.py
+++ b/tests/unit/server/test_chat_router.py
@@ -570,3 +570,35 @@ async def test_a_chip_without_a_tool_hint_omits_the_field_rather_than_nulling_it
assert response.status_code == 200, response.text
assert "toolHint" not in response.text
assert response.json()["suggestions"] == hintless
+
+
+async def test_no_configured_provider_is_a_chat_error_event_not_an_http_error():
+ from repowise.server.chat_errors import NO_PROVIDER_MESSAGE
+
+ app = await _make_app()
+ failure = ValueError("No active provider configured. Set an API key first.")
+ with patch(_PROVIDER, side_effect=failure):
+ events = _data_events(await _post(app, {"message": "hi"}))
+ assert events == [{"type": "error", "message": NO_PROVIDER_MESSAGE}]
+
+
+ ("override", "failure", "expected"),
+ [
+ (None, ValueError("No active provider configured. Set an API key first."), "No LLM provider"),
+ ("nope", ValueError("Unknown provider: nope"), "Unknown provider 'nope'"),
+ (None, ValueError("base_url http://10.0.0.5:9/x?key=AIzaSecret1234 is invalid"), "configuration is invalid"),
+ ("openai", RuntimeError("client init failed for sk-proj-abcdef1234567890"), "Could not start the chat provider"),
+ ],
+)
+async def test_provider_setup_failures_are_plain_chat_errors(override, failure, expected):
+ app = await _make_app()
+ with patch(_PROVIDER, side_effect=failure):
+ events = _data_events(await _post(app, {"message": "hi", "provider": override}))
+ [event] = events
+ assert event["type"] == "error"
+ assert expected in event["message"]
+ assert "AIza" not in event["message"] and "sk-" not in event["message"]
+ assert "10.0.0.5" not in event["message"]
diff --git a/tests/unit/server/test_chat_session.py b/tests/unit/server/test_chat_session.py
index 1f92524cf..8774f9017 100644
--- a/tests/unit/server/test_chat_session.py
+++ b/tests/unit/server/test_chat_session.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import asyncio
import json
from collections.abc import AsyncIterator, Callable, Iterable
-from dataclasses import replace
+from dataclasses import asdict, replace
from typing import Any
import pytest
@@ -815,3 +815,195 @@ async def test_find_suspects_is_offered_on_the_local_backend_and_runs(store, mon
await _open(store, narrow, tools=FakeLocal(), policy=SessionPolicy(tool_allowlist=frozenset({"get_risk"})))
).send("q")
assert SUSPECTS_TOOL not in narrow.calls[0]["tools"]
+
+
+# ---------------------------------------------------------------------------
+# show_view references across the conversation
+# ---------------------------------------------------------------------------
+
+
+def _table(reference: str) -> dict:
+ return {"artifact_id": reference, "view": "table", "options": {"path": "files"}}
+
+
+async def test_a_view_cites_a_result_from_an_earlier_turn_by_its_replayed_id(store):
+ first = ScriptedProvider([[_tool("t1", "get_risk")], [_text("read it")]])
+ session = await _open(store, first)
+ await session.send("risk?")
+
+ def turns(index: int) -> list:
+ if index == 0:
+ replayed = next(m for m in second.calls[0]["messages"] if m["role"] == "tool")
+ # The id is the first key, so an excerpt of a long result still shows it.
+ assert replayed["content"].startswith('{"artifact_id": "')
+ artifact_id = json.loads(replayed["content"])["artifact_id"]
+ return [_tool("t2", SHOW_VIEW_TOOL, _table(artifact_id))]
+ return [_text("charted")]
+
+ second = ScriptedProvider(turns)
+ tools = FakeTools()
+ result = await (await _open(store, second, tools=tools, conversation_id=session.id)).send(
+ "now as a table"
+ )
+
+ assert tools.executed == []
+ assert [view["kind"] for view in result.views] == ["table"]
+ stored = (await store.messages(session.id))[1].content["tool_calls"][0]["artifact"]
+ assert result.views[0]["source"]["artifact_id"] == stored["id"]
+
+
+async def test_latest_reference_resolves_a_call_made_earlier_in_the_same_round(store):
+ provider = ScriptedProvider(
+ [
+ [_tool("t1", "get_risk"), _tool("t2", SHOW_VIEW_TOOL, _table("latest:get_risk"))],
+ [_text("done")],
+ ]
+ )
+ result = await (await _open(store, provider)).send("table of risk")
+ assert [view["kind"] for view in result.views] == ["table"]
+
+
+async def test_an_unknown_reference_lists_the_valid_ones_for_one_retry(store):
+ first = ScriptedProvider([[_tool("t1", "get_risk")], [_text("ok")]])
+ session = await _open(store, first)
+ await session.send("risk?")
+
+ second = ScriptedProvider(
+ [[_tool("t2", SHOW_VIEW_TOOL, _table("placeholder"))], [_text("sorry")]]
+ )
+ await (await _open(store, second, conversation_id=session.id)).send("table")
+
+ error = json.loads(second.calls[1]["messages"][-1]["content"])
+ assert error["error_code"] == "unknown_artifact"
+ assert "latest:<tool_name>" in error["error"]
+ assert [(ref["tool"], ref["age"]) for ref in error["available"]] == [("get_risk", "1 turn ago")]
+
+
+# ---------------------------------------------------------------------------
+# Failures a person can fix end the turn with a plain message, not a crash
+# ---------------------------------------------------------------------------
+
+
+async def test_a_tool_result_holding_a_datetime_is_sent_streamed_and_stored(store):
+ from datetime import UTC, datetime
+
+ class DatedTools(FakeTools):
+ async def execute(self, name, arguments):
+ return {"files": [{"path": "src/a.py", "changed": datetime(2026, 10, 1, tzinfo=UTC)}]}
+
+ provider = ScriptedProvider([[_tool("t1", "get_risk")], [_text("ok")]])
+ session = await _open(store, provider, tools=DatedTools())
+ events = await _collect(session.stream("when?"))
+
+ assert events[-1]["type"] == "done"
+ json.dumps(events)
+ stored = (await store.messages(session.id))[-1].content["tool_calls"][0]["artifact"]["data"]
+ assert stored["files"][0]["changed"].startswith("2026-10-01")
+
+
+_KEY = "sk-ant-" + "a1b2c3d4e5f6g7h8" # pragma: allowlist secret
+_GOOGLE_URL = "https://generativelanguage.googleapis.com/v1/models?key=AIza" + "SyA1b2c3d4e5f6"
+
+
+def _sdk_status_error(status: int, message: str):
+ import anthropic
+ import httpx
+
+ request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
+ response = httpx.Response(status, request=request)
+ error = anthropic.AuthenticationError if status == 401 else anthropic.APIStatusError
+ return error(message, response=response, body=None)
+
+
+async def test_an_sdk_auth_error_says_to_check_the_api_key(store):
+ provider = ScriptedProvider([_sdk_status_error(401, f"invalid x-api-key {_KEY}")])
+ result = await (await _open(store, provider)).send("hi")
+
+ assert result.stop_reason == "error"
+ assert "rejected its API key" in result.error
+ assert "Settings" in result.error
+ assert _KEY not in result.error
+
+
+async def test_an_sdk_error_body_is_not_echoed_to_the_person(store):
+ provider = ScriptedProvider([_sdk_status_error(400, f"bad request, echoed key {_KEY}")])
+ result = await (await _open(store, provider)).send("hi")
+
+ assert result.error == (
+ "The test provider failed (APIStatusError, HTTP 400). See the server log for details."
+ )
+
+
+async def test_an_httpx_error_is_not_labelled_a_provider_failure_and_its_key_is_redacted(store):
+ import httpx
+
+ request = httpx.Request("GET", _GOOGLE_URL)
+ leaked = httpx.HTTPStatusError(
+ f"Client error for url {_GOOGLE_URL}", request=request, response=httpx.Response(400)
+ )
+ provider = ScriptedProvider([leaked])
+ result = await (await _open(store, provider)).send("hi")
+
+ assert result.error.startswith("Internal error: HTTPStatusError")
+ assert "provider failed" not in result.error
+ assert "AIza" not in result.error and "key=[redacted]" in result.error
+
+
+async def test_a_provider_that_runs_tools_itself_gets_stamped_json_safe_results(store):
+ from datetime import UTC, datetime
+
+ class DatedTools(FakeTools):
+ async def execute(self, name, arguments):
+ return {"files": [{"path": "src/a.py", "changed": datetime(2026, 10, 1, tzinfo=UTC)}]}
+
+ seen: list = []
+
+ class LoopingProvider(ScriptedProvider):
+ """Runs its tool calls through ``tool_executor``, the way Gemini does."""
+
+ async def stream_chat(self, **kwargs):
+ self.calls.append({"tools": [t["function"]["name"] for t in kwargs["tools"]]})
+ call = ChatToolCall(id="g1", name="get_risk", arguments={})
+ yield ChatStreamEvent(type="tool_start", tool_call=call)
+ result = await kwargs["tool_executor"]("get_risk", {})
+ seen.append(result)
+ yield ChatStreamEvent(type="tool_result", tool_call=call, tool_result_data=result)
+ yield _text("done")
+
+ session = await _open(store, LoopingProvider([]), tools=DatedTools())
+ result = await session.send("when?")
+
+ assert next(iter(seen[0])) == "artifact_id"
+ json.dumps(seen[0])
+ assert [t.ok for t in result.tool_trace] == [True]
+
+
+async def test_a_bug_outside_the_provider_stays_an_internal_error(store):
+ provider = ScriptedProvider([KeyError("boom")])
+ result = await (await _open(store, provider)).send("hi")
+ assert result.error.startswith("Internal error: KeyError")
+
+
+async def test_a_session_without_a_provider_ends_with_a_setup_message(store):
+ from repowise.server.chat_errors import NO_PROVIDER_MESSAGE
+
+ session = await _open(store, None)
+ events = await _collect(session.stream("hi"))
+ assert events == [{"type": "error", "message": NO_PROVIDER_MESSAGE}]
+ assert (await session.send("hi")).error == NO_PROVIDER_MESSAGE
+
+
+async def test_a_citation_line_that_is_not_a_number_is_dropped_not_fatal(store):
+ from repowise.server.schemas.chat import ChatTurnResultResponse
+
+ class RangeTools(FakeTools):
+ async def execute(self, name, arguments):
+ return {"citations": [{"file_path": "src/a.py", "start_line": "10-20", "end_line": 20}]}
+
+ provider = ScriptedProvider([[_tool("t1", "get_risk")], [_text("ok")]])
+ result = await (await _open(store, provider, tools=RangeTools())).send("where?")
+
+ assert [(c["file_path"], c.get("start_line"), c["end_line"]) for c in result.citations] == [
+ ("src/a.py", None, 20)
+ ]
+ ChatTurnResultResponse.model_validate(asdict(result))
diff --git a/tests/unit/server/test_chat_views.py b/tests/unit/server/test_chat_views.py
index 8c36886bd..70c584027 100644
--- a/tests/unit/server/test_chat_views.py
+++ b/tests/unit/server/test_chat_views.py
@@ -601,3 +601,135 @@ async def test_a_turn_without_show_view_stores_no_views():
assert "view" not in [event["type"] for event in events]
stored = await _stored_messages(app, events[-1]["conversation_id"])
assert "views" not in stored[-1]["content"]
+
+
+# ---------------------------------------------------------------------------
+# References and empty charts
+# ---------------------------------------------------------------------------
+
+
+def test_a_chart_whose_series_are_all_zero_is_no_data():
+ empty = {"tiers": {tier: {"count": 0, "findings": []} for tier in ("high", "medium", "low")}}
+ with pytest.raises(ViewError) as err:
+ _build(empty, "dead_code", "get_dead_code", "dead_code.by_tier")
+ assert err.value.code == "no_data"
+
+
+def test_the_stamp_is_the_first_key_and_survives_truncation():
+ from repowise.server.chat_context import bound_tool_messages
+ from repowise.server.chat_prompt import tool_result_message
+
+ stamped = TurnViews().record("get_risk", {}, {"rows": ["x" * 200_000]}, artifact_type="risk")
+ assert next(iter(stamped)) == ARTIFACT_ID_FIELD
+ [bounded] = bound_tool_messages([tool_result_message("t1", "get_risk", stamped)])
+ assert stamped[ARTIFACT_ID_FIELD] in json.loads(bounded["content"])["excerpt"][:100]
+
+
+def test_latest_skips_a_failed_result_and_an_unknown_tool_resolves_to_nothing():
+ turn = TurnViews()
+ good = turn.record("get_risk", {}, RISK, artifact_type="risk")
+ turn.record("get_risk", {}, {"error": "boom"}, artifact_type="risk")
+ assert turn.artifacts.resolve("latest:get_risk").artifact_id == good[ARTIFACT_ID_FIELD]
+ assert turn.artifacts.resolve("latest:get_health") is None
+ assert [ref["artifact_id"] for ref in turn.artifacts.available()] == [good[ARTIFACT_ID_FIELD]]
+
+
+def test_a_legacy_row_is_indexed_under_the_id_its_replay_shows():
+ from repowise.server.chat_prompt import stored_messages_to_llm_format
+ from repowise.server.chat_references import ArtifactIndex
+ from repowise.server.chat_seams import StoredMessage
+
+ legacy = StoredMessage(
+ id="m2",
+ role="assistant",
+ content={"text": "", "tool_calls": [{"id": "t1", "name": "get_risk", "result": RISK}]},
+ )
+ history = [StoredMessage(id="m1", role="user", content={"text": "q"}), legacy]
+ index = ArtifactIndex.from_history(history)
+ replayed = json.loads(stored_messages_to_llm_format(history)[-1]["content"])
+
+ artifact = index.resolve(replayed[ARTIFACT_ID_FIELD])
+ assert artifact is not None and artifact.artifact_type == "risk"
+ assert index.available()[0]["age"] == "1 turn ago"
+ assert build_view(artifact, "risk.hotspots", {}, part_id="v1")["kind"] == "chart"
+
+
+def test_the_prompt_explains_views_only_when_show_view_is_offered():
+ from repowise.server.chat_prompt import _build_system_prompt
+
+ tools = get_tool_catalog(None)
+ assert "latest:<tool_name>" in _build_system_prompt("demo", "/tmp", tools, shows_views=True)
+ assert "show_view" not in _build_system_prompt("demo", "/tmp", tools)
+
+
+def test_a_latest_reference_with_only_a_failed_result_lists_nothing_to_cite():
+ turn = TurnViews()
+ turn.record("get_risk", {}, {"error": "boom"}, artifact_type="risk")
+ result = turn.show({"artifact_id": "latest:get_risk", "view": "risk.hotspots"})
+ assert result["error_code"] == "unknown_artifact"
+ assert result["available"] == []
+
+
+def test_a_latest_receipt_names_the_result_it_picked():
+ turn = TurnViews()
+ stamped = turn.record("get_risk", {}, RISK, artifact_type="risk")
+ receipt = turn.show({"artifact_id": "latest:get_risk", "view": "risk.hotspots"})
+ assert receipt["resolved_artifact_id"] == stamped[ARTIFACT_ID_FIELD]
+ assert receipt["source_tool"] == "get_risk"
+ plain = turn.show({"artifact_id": stamped[ARTIFACT_ID_FIELD], "view": "risk.hotspots"})
+ assert "resolved_artifact_id" not in plain
+
+
+def test_latest_across_turns_picks_a_later_legacy_row():
+ from repowise.server.chat_references import ArtifactIndex
+ from repowise.server.chat_seams import StoredMessage
+
+ first = TurnViews()
+ stamped = first.record("get_risk", {}, RISK, artifact_type="risk")
+ artifact_id, data = first.unstamp(stamped)
+ envelope = create_artifact_envelope(
+ tool_name="get_risk", artifact_type="risk", presentation="risk", data=data, artifact_id=artifact_id
+ )
+ history = [
+ StoredMessage(id="m1", role="user", content={"text": "q"}),
+ StoredMessage(
+ id="m2",
+ role="assistant",
+ content={"tool_calls": [{"id": "t1", "name": "get_risk", "artifact": envelope}]},
+ ),
+ StoredMessage(id="m3", role="user", content={"text": "again"}),
+ StoredMessage(
+ id="m4",
+ role="assistant",
+ content={"tool_calls": [{"id": "t2", "name": "get_risk", "result": RISK}]},
+ ),
+ ]
+ index = ArtifactIndex.from_history(history)
+ latest = index.resolve("latest:get_risk")
+ assert latest is not None and latest.artifact_id != artifact_id
+ assert [ref["age"] for ref in index.available()] == ["1 turn ago", "2 turns ago"]
+ assert index.resolve(artifact_id).artifact_type == "risk"
+
+
+def test_only_a_chart_with_rows_and_string_series_can_be_all_zero():
+ from repowise.server.chat_views import _all_zero
+
+ assert _all_zero({"series": ["n"], "data": {"rows": [{"n": 0}, {"n": None}]}})
+ assert not _all_zero({"series": ["n"], "data": {"rows": []}})
+ assert not _all_zero({"series": [{"key": "n"}], "data": {"rows": [{"n": 0}]}})
+ assert not _all_zero({"series": "n", "data": {"rows": [{"n": 0}]}})
+ assert not _all_zero({"series": ["n"], "data": {"rows": [{"n": 0}, {"n": 2}]}})
+
+
+ ("text", "expected"),
+ [
+ ("GET https://g.example/v1?alt=sse&key=AIzaQ&x=1", "GET https://g.example/v1?alt=sse&key=[redacted]&x=1"),
+ ("Authorization: Bearer abcdefgh12345678", "Authorization: Bearer [redacted]"),
+ ("no secret at /repo/a.py:12", "no secret at /repo/a.py:12"),
+ ],
+)
+def test_query_keys_and_bearer_tokens_are_redacted(text, expected):
+ from repowise.core.redaction import redact_secrets
+
+ assert redact_secrets(text) == expected
diff --git a/tests/unit/test_providers/test_provider_specs.py b/tests/unit/test_providers/test_provider_specs.py
index cd80fc3e4..e43a4e035 100644
--- a/tests/unit/test_providers/test_provider_specs.py
+++ b/tests/unit/test_providers/test_provider_specs.py
@@ -91,6 +91,8 @@ _ALLOWED: dict[str, frozenset[str]] = {
"core/src/repowise/core/ingestion/external_systems/classifier.py": frozenset(
{"anthropic", "openai"}
),
+ # SDK module names whose error base classes chat matches.
+ "server/src/repowise/server/chat_errors.py": frozenset({"anthropic", "openai", "ollama"}),
# Behaviour only the OpenAI adapter has: the custom-gateway row and base-url
# prompt, and its reasoning budget. Ollama's readiness is a TCP probe.
"cli/src/repowise/cli/helpers.py": frozenset({"openai"}),