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.

feat(chat): build composer suggestions from what the page measured (#2205)

Raghav Chamadiyaa01686dc3584
diff --git a/packages/api-client/src/chat.ts b/packages/api-client/src/chat.ts
index db1f14ce3..5744db221 100644
--- a/packages/api-client/src/chat.ts
+++ b/packages/api-client/src/chat.ts
@@ -4,7 +4,11 @@
import { apiGet, apiDelete, apiPatch, apiPost, BASE_URL, buildHeaders } from "./client";
import type { ConversationResponse, ChatMessageResponse } from "./types";
-import type { ChatArtifact, ChatContext } from "@repowise-dev/types/chat";
+import type {
+ ChatArtifact,
+ ChatContext,
+ ChatSuggestion,
+} from "@repowise-dev/types/chat";
export async function listConversations(
repoId: string,
@@ -14,6 +18,19 @@ export async function listConversations(
);
}
+/**
+ * Questions built from what the page actually shows. Derived on the server from
+ * the same prefetch a first question would make, so this costs no model call.
+ */
+export async function getChatSuggestions(
+ repoId: string,
+ context: Pick<ChatContext, "kind" | "target">,
+): Promise<{ suggestions: ChatSuggestion[] }> {
+ const query = new URLSearchParams({ kind: context.kind });
+ if (context.target) query.set("target", context.target);
+ return apiGet(`/api/repos/${repoId}/chat/suggestions?${query.toString()}`);
+}
+
export async function getConversation(
repoId: string,
conversationId: string,
diff --git a/packages/server/src/repowise/server/chat_suggestions.py b/packages/server/src/repowise/server/chat_suggestions.py
new file mode 100644
index 000000000..16a450242
--- /dev/null
+++ b/packages/server/src/repowise/server/chat_suggestions.py
@@ -0,0 +1,453 @@
+"""Questions built from measured values, not from adjectives.
+
+``page_suggestions`` turns one already-fetched tool result into questions the
+page has earned; a value absent from the result produces no question, so the
+caller keeps its own static tier. ``follow_up_suggestions`` turns the tools a
+finished turn called into the next read worth making.
+
+Both take tool results, never a repository path, so a host with its own artifact
+store can feed them. Kept apart from ``routers/chat.py``'s
+``_build_tool_summary``: that labels a row that already happened, this asks a
+question nobody has asked yet.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+MAX_PAGE_SUGGESTIONS = 3
+MAX_FOLLOW_UPS = 2
+
+# A whole path crowds a 390px dock, so a target is named by its last segment.
+_MAX_LABEL_CHARS = 48
+
+_TARGET_SEPARATOR = ", "
+
+
+def _label(target: str) -> str:
+ cleaned = target.strip()
+ tail = cleaned.rsplit("/", 1)[-1].rsplit("\\", 1)[-1] or cleaned
+ if len(tail) > _MAX_LABEL_CHARS:
+ return f"{tail[: _MAX_LABEL_CHARS - 1]}…"
+ return tail
+
+
+def _humanize(value: str) -> str:
+ return value.replace("_", " ").replace("-", " ").strip()
+
+
+def _suggestion(text: str, source: str, tool_hint: str | None = None) -> dict[str, Any]:
+ entry: dict[str, Any] = {"text": text, "source": source}
+ if tool_hint:
+ entry["toolHint"] = tool_hint
+ return entry
+
+
+def _targets(result: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]:
+ targets = result.get("targets")
+ if not isinstance(targets, dict):
+ return {}
+ return {k: v for k, v in targets.items() if isinstance(v, Mapping)}
+
+
+def _worst_target(result: Mapping[str, Any]) -> tuple[str, Mapping[str, Any]] | None:
+ """Ranked by counted fixes then churn, so a multi-select page names the
+ file carrying the most evidence rather than whichever came first."""
+ entries = _targets(result)
+ if not entries:
+ return None
+
+ def rank(item: tuple[str, Mapping[str, Any]]) -> tuple[float, float]:
+ profile = item[1].get("defect_profile")
+ fixes = profile.get("fix_count", 0) if isinstance(profile, Mapping) else 0
+ hotspot = item[1].get("hotspot_score", 0.0)
+ return (
+ float(fixes) if isinstance(fixes, (int, float)) else 0.0,
+ float(hotspot) if isinstance(hotspot, (int, float)) else 0.0,
+ )
+
+ return max(entries.items(), key=rank)
+
+
+# --------------------------------------------------------------------------
+# Page tier: one prefetched tool result -> questions naming what it measured
+# --------------------------------------------------------------------------
+
+
+def _from_get_context(target: str, result: Mapping[str, Any]) -> list[dict[str, Any]]:
+ entries = _targets(result)
+ path, card = next(iter(entries.items()), (target, {}))
+ name = _label(path)
+ out: list[dict[str, Any]] = []
+
+ history = card.get("fix_history")
+ if isinstance(history, Mapping):
+ count = history.get("fix_count")
+ if isinstance(count, int) and count > 0:
+ out.append(
+ _suggestion(f"Explain the {count} bug fixes in {name}", "page", "get_risk")
+ )
+ if card.get("hotspot") is True:
+ out.append(
+ _suggestion(f"Why does {name} change so often?", "page", "get_risk")
+ )
+ episodes = card.get("episodes")
+ if isinstance(episodes, int) and episodes > 0:
+ out.append(
+ _suggestion(f"What happened in {name} and why?", "page", "get_why")
+ )
+ return out
+
+
+def _from_get_risk(target: str, result: Mapping[str, Any]) -> list[dict[str, Any]]:
+ worst = _worst_target(result)
+ if worst is None:
+ return []
+ path, card = worst
+ name = _label(path)
+ out: list[dict[str, Any]] = []
+
+ profile = card.get("defect_profile")
+ if isinstance(profile, Mapping):
+ count = profile.get("fix_count")
+ if isinstance(count, int) and count > 0:
+ out.append(
+ _suggestion(f"Explain the {count} bug fixes in {name}", "page", "get_risk")
+ )
+
+ biomarkers = card.get("top_biomarkers")
+ if isinstance(biomarkers, Sequence) and biomarkers and isinstance(biomarkers[0], Mapping):
+ top = biomarkers[0]
+ kind = top.get("biomarker_type")
+ function = top.get("function_name")
+ if isinstance(kind, str) and kind:
+ where = f" in {function}" if isinstance(function, str) and function else f" in {name}"
+ out.append(
+ _suggestion(
+ f"Explain the {_humanize(kind)} finding{where}", "page", "get_health"
+ )
+ )
+
+ owner = card.get("primary_owner")
+ owner_pct = card.get("owner_pct")
+ if isinstance(owner, str) and owner and isinstance(owner_pct, (int, float)):
+ out.append(
+ _suggestion(
+ f"{owner} wrote {round(owner_pct * 100)}% of {name}. Who else should review a change?",
+ "page",
+ "get_risk",
+ )
+ )
+
+ partners = card.get("co_change_partners_total")
+ if isinstance(partners, int) and partners > 0:
+ out.append(
+ _suggestion(
+ f"What are the {partners} files that change with {name}?", "page", "get_risk"
+ )
+ )
+ return out
+
+
+def _from_get_health(target: str, result: Mapping[str, Any]) -> list[dict[str, Any]]:
+ findings = result.get("findings")
+ if not isinstance(findings, Sequence):
+ findings = result.get("top_findings")
+ out: list[dict[str, Any]] = []
+
+ if isinstance(findings, Sequence) and findings and isinstance(findings[0], Mapping):
+ top = findings[0]
+ kind = top.get("biomarker_type")
+ function = top.get("function_name")
+ file_path = top.get("file_path")
+ where = (
+ f" in {function}"
+ if isinstance(function, str) and function
+ else f" in {_label(file_path)}"
+ if isinstance(file_path, str) and file_path
+ else ""
+ )
+ if isinstance(kind, str) and kind:
+ out.append(
+ _suggestion(
+ f"Explain the {_humanize(kind)} finding{where}", "page", "get_health"
+ )
+ )
+
+ total = result.get("findings_total")
+ if not isinstance(total, int):
+ total = result.get("top_findings_total")
+ if isinstance(total, int) and total > 1:
+ out.append(
+ _suggestion(
+ f"Which of the {total} findings should I fix first?", "page", "get_health"
+ )
+ )
+
+ metrics = result.get("metrics")
+ if isinstance(metrics, Sequence) and metrics and isinstance(metrics[0], Mapping):
+ metric = metrics[0]
+ score = metric.get("score")
+ path = metric.get("file_path")
+ if isinstance(score, (int, float)) and isinstance(path, str) and path:
+ out.append(
+ _suggestion(
+ f"Why does {_label(path)} score {round(float(score), 1)} out of 10?",
+ "page",
+ "get_health",
+ )
+ )
+ return out
+
+
+def _from_get_why(target: str, result: Mapping[str, Any]) -> list[dict[str, Any]]:
+ decisions = result.get("decisions")
+ out: list[dict[str, Any]] = []
+ if isinstance(decisions, Sequence) and decisions and isinstance(decisions[0], Mapping):
+ title = decisions[0].get("title")
+ if isinstance(title, str) and title.strip():
+ short = title.strip()
+ if len(short) > _MAX_LABEL_CHARS:
+ short = f"{short[: _MAX_LABEL_CHARS - 1]}…"
+ out.append(_suggestion(f'Why was "{short}" decided?', "page", "get_why"))
+ out.append(
+ _suggestion(
+ f'Has later work conflicted with "{short}"?', "page", "get_why"
+ )
+ )
+
+ alignment = result.get("alignment")
+ if isinstance(alignment, Mapping):
+ score = alignment.get("score")
+ if score is not None:
+ out.append(
+ _suggestion(
+ f"Alignment scores {score}. Where does the code diverge?",
+ "page",
+ "get_why",
+ )
+ )
+ return out
+
+
+def _from_get_change_risk(target: str, result: Mapping[str, Any]) -> list[dict[str, Any]]:
+ ref = _label(str(result.get("ref") or target or "this change"))
+ out: list[dict[str, Any]] = []
+
+ # ``drivers`` is diagnostics-gated and absent from the prefetch, so the
+ # measured values named here are the ones the default response always
+ # carries.
+ classification = result.get("classification") or result.get("review_priority")
+ if isinstance(classification, str) and classification:
+ percentile = result.get("risk_percentile")
+ # Stored to one decimal; every other surface shows it whole.
+ measured = (
+ f" at p{round(percentile)}" if isinstance(percentile, (int, float)) else ""
+ )
+ out.append(
+ _suggestion(
+ f"Why is {ref} rated {classification}{measured}?", "page", "get_change_risk"
+ )
+ )
+ if result.get("is_fix") is True:
+ out.append(_suggestion(f"What did {ref} fix?", "page", "get_change_risk"))
+ if isinstance(classification, str) and classification:
+ out.append(
+ _suggestion(
+ f"Which files in {ref} deserve the closest review?", "page", "get_risk"
+ )
+ )
+ return out
+
+
+_PAGE_DERIVATIONS = {
+ "get_context": _from_get_context,
+ "get_risk": _from_get_risk,
+ "get_health": _from_get_health,
+ "get_why": _from_get_why,
+ "get_change_risk": _from_get_change_risk,
+}
+
+
+def page_suggestions(
+ tool_name: str,
+ target: str,
+ result: Mapping[str, Any] | None,
+) -> list[dict[str, Any]]:
+ """Questions this result earned, most specific first; empty when nothing
+ was measured. ``get_symbol`` returns source and no figures, so it derives
+ nothing and the caller's static tier stands."""
+ if not isinstance(result, Mapping) or "error" in result:
+ return []
+ derive = _PAGE_DERIVATIONS.get(tool_name)
+ if derive is None:
+ return []
+ primary = target.split(_TARGET_SEPARATOR)[0].strip() if target else ""
+ return _dedupe(derive(primary, result))[:MAX_PAGE_SUGGESTIONS]
+
+
+# --------------------------------------------------------------------------
+# Follow-up tier: what a finished turn read -> the next read worth making
+# --------------------------------------------------------------------------
+
+
+# (templated, plain, next tool). The plain form stands in when the call named no
+# subject, so no chip ever reads "changing ?".
+_FOLLOW_UPS: dict[str, tuple[tuple[str, str, str], ...]] = {
+ "get_context": (
+ ("What is risky about changing {subject}?", "What is risky about changing this?", "get_risk"),
+ ("Which decisions govern {subject}?", "Which decisions govern this code?", "get_why"),
+ ),
+ "get_risk": (
+ ("Which tests reduce the most uncertainty for {subject}?", "Which tests reduce the most uncertainty?", "get_risk"),
+ ("Which decisions govern {subject}?", "Which decisions govern this code?", "get_why"),
+ ),
+ "get_health": (
+ ("Propose a safe refactoring sequence for {subject}", "Propose a safe refactoring sequence for these findings", "get_health"),
+ ("What breaks if I change {subject}?", "What breaks if I change these files?", "get_risk"),
+ ),
+ "get_why": (
+ ("Show the code {subject} affects", "Show the code these decisions affect", "get_context"),
+ ("Has later work conflicted with this?", "Has later work conflicted with this?", "get_why"),
+ ),
+ "get_symbol": (
+ ("Who calls {subject}?", "Who calls this symbol?", "get_context"),
+ ("What behavior should tests protect in {subject}?", "What behavior should tests protect here?", "get_risk"),
+ ),
+ "get_change_risk": (
+ ("Which files in {subject} deserve the closest review?", "Which files in this change deserve the closest review?", "get_risk"),
+ ("What tests should validate {subject}?", "What tests should validate this change?", "get_risk"),
+ ),
+ "search_codebase": (
+ ("Explain the most relevant result in depth", "Explain the most relevant result in depth", "get_context"),
+ ("Which of these results are riskiest to modify?", "Which of these results are riskiest to modify?", "get_risk"),
+ ),
+ "get_overview": (
+ ("Which files are riskiest to modify?", "Which files are riskiest to modify?", "get_risk"),
+ ("What architectural decisions have been made?", "What architectural decisions have been made?", "get_why"),
+ ),
+ "get_dead_code": (
+ ("Is the highest-confidence result safe to remove?", "Is the highest-confidence result safe to remove?", "get_risk"),
+ ("What should I check before deleting it?", "What should I check before deleting it?", "get_context"),
+ ),
+}
+
+
+def _follow_ups_for(tool_name: str, arguments: Mapping[str, Any]) -> list[dict[str, Any]]:
+ subject = _subject(arguments)
+ return [
+ _suggestion(
+ templated.format(subject=subject) if subject else plain,
+ "followup",
+ hint,
+ )
+ for templated, plain, hint in _FOLLOW_UPS.get(tool_name, ())
+ ]
+
+
+def _subject(arguments: Mapping[str, Any]) -> str:
+ for key in ("targets", "symbol_id", "revspec", "id", "query"):
+ value = arguments.get(key)
+ if isinstance(value, str) and value.strip():
+ return _label(value)
+ if isinstance(value, Sequence) and not isinstance(value, (str, bytes)):
+ first = next((v for v in value if isinstance(v, str) and v.strip()), None)
+ if first:
+ return _label(first)
+ return ""
+
+
+def _errored(call: Mapping[str, Any]) -> bool:
+ """A call whose result carries an error taught the turn nothing, so it
+ cannot justify a next step or name the conversation. ``run_grounding``
+ already drops the prefetch on the same rule."""
+ artifact = call.get("artifact")
+ data = artifact.get("data") if isinstance(artifact, Mapping) else None
+ return isinstance(data, Mapping) and "error" in data
+
+
+def tool_names(tool_calls: Sequence[Mapping[str, Any]]) -> list[str]:
+ """The tools a turn actually learned something from, in call order."""
+ return [
+ call["name"]
+ for call in tool_calls
+ if isinstance(call.get("name"), str) and not _errored(call)
+ ]
+
+
+def _dedupe(entries: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ seen: set[str] = set()
+ out: list[dict[str, Any]] = []
+ for entry in entries:
+ text = entry.get("text")
+ if not isinstance(text, str) or not text.strip() or text in seen:
+ continue
+ seen.add(text)
+ out.append(dict(entry))
+ return out
+
+
+def follow_up_suggestions(
+ tool_calls: Sequence[Mapping[str, Any]],
+) -> list[dict[str, Any]]:
+ """Newest call first, so follow-ups sit on the freshest evidence. A turn
+ that called no tool earns none."""
+ out: list[dict[str, Any]] = []
+ for call in reversed(list(tool_calls)):
+ name = call.get("name")
+ if not isinstance(name, str) or _errored(call):
+ continue
+ arguments = call.get("arguments")
+ out.extend(
+ _follow_ups_for(name, arguments if isinstance(arguments, Mapping) else {})
+ )
+ if len(_dedupe(out)) >= MAX_FOLLOW_UPS:
+ break
+ return _dedupe(out)[:MAX_FOLLOW_UPS]
+
+
+# --------------------------------------------------------------------------
+# Conversation titles
+# --------------------------------------------------------------------------
+
+_TITLE_MAX_CHARS = 60
+_TITLE_STOPWORDS = {
+ "a", "an", "and", "are", "can", "did", "do", "does", "for", "give",
+ "how", "in", "is", "me", "of", "on", "please", "show", "tell", "the",
+ "this", "to", "what", "whats", "why", "you",
+}
+# A tool names the subject of the conversation better than the question's own
+# opening words do, which are usually "what does" or "explain the".
+_TOOL_SUBJECTS = {
+ "get_risk": "Risk",
+ "get_change_risk": "Change risk",
+ "get_health": "Code health",
+ "get_why": "Decisions",
+ "get_dead_code": "Dead code",
+ "get_context": "Context",
+ "get_symbol": "Symbol",
+ "get_overview": "Overview",
+ "search_codebase": "Search",
+}
+
+
+def conversation_title(question: str, tool_names: Sequence[str]) -> str:
+ """The first question, prefixed by what the turn read.
+
+ No model call: a second provider round trip per new conversation would cost
+ every first answer latency for a string that only has to be recognisable.
+ """
+ words = question.split()
+ keep = [w for w in words if w.strip(".,?!:;\"'").lower() not in _TITLE_STOPWORDS]
+ body = " ".join(keep or words).strip(".,?!:;\"' ")
+ if not body:
+ body = " ".join(words[:6]).strip() or "New conversation"
+
+ subject = next(
+ (_TOOL_SUBJECTS[name] for name in tool_names if name in _TOOL_SUBJECTS), None
+ )
+ title = f"{subject}: {body}" if subject else body
+ if len(title) > _TITLE_MAX_CHARS:
+ title = f"{title[: _TITLE_MAX_CHARS - 1].rstrip()}…"
+ return title
diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.py
index 9e631ae78..eb9b5733b 100644
--- a/packages/server/src/repowise/server/routers/chat.py
+++ b/packages/server/src/repowise/server/routers/chat.py
@@ -9,6 +9,7 @@ from pathlib import Path
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Request
+from pydantic import ValidationError
from starlette.responses import StreamingResponse
from repowise.core.persistence import crud
@@ -21,6 +22,12 @@ from repowise.server.chat_artifacts import (
set_artifact_pinned,
)
from repowise.server.chat_grounding import plan_grounding, run_grounding
+from repowise.server.chat_suggestions import (
+ conversation_title,
+ follow_up_suggestions,
+ page_suggestions,
+ tool_names,
+)
from repowise.server.chat_tools import (
ChatToolContract,
execute_tool,
@@ -41,6 +48,7 @@ from repowise.server.schemas import (
ChatArtifactEnvelope,
ChatMessageResponse,
ChatRequest,
+ ChatSuggestionsResponse,
ConversationDetailResponse,
ConversationForkRequest,
ConversationResponse,
@@ -265,6 +273,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
conv_id = body.conversation_id
msg_id = ""
user_msg_id = ""
+ opened_conversation = False
try:
# Emit retry interval
@@ -287,11 +296,14 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
)
return
else:
- title = " ".join(body.message.split()[:6])
+ # Placeholder; refined once the turn's tools are known.
conv = await crud.create_conversation(
- session, repository_id=repo_id, title=title
+ session,
+ repository_id=repo_id,
+ title=" ".join(body.message.split()[:6]),
)
conv_id = conv.id
+ opened_conversation = True
# Save user message
user_msg = await crud.create_chat_message(
@@ -534,6 +546,11 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
}
if truncated:
content["truncated"] = True
+ # A turn that read nothing, or read only failures, has no next
+ # step to propose.
+ follow_ups = follow_up_suggestions(tool_calls_made)
+ if follow_ups:
+ content["follow_ups"] = follow_ups
async with get_session(factory) as session:
msg = await crud.create_chat_message(
session,
@@ -543,6 +560,18 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
)
msg_id = msg.id
await crud.touch_conversation(session, conv_id)
+ # Opening turn only, so a later rename is never overwritten.
+ if opened_conversation:
+ await crud.update_conversation_title(
+ session,
+ conv_id,
+ conversation_title(body.message, tool_names(tool_calls_made)),
+ )
+
+ if follow_ups:
+ yield _sse_event(
+ "data", {"type": "suggestions", "suggestions": follow_ups}
+ )
yield _sse_event(
"data",
@@ -579,6 +608,55 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):
)
+ "/api/repos/{repo_id}/chat/suggestions",
+ response_model=ChatSuggestionsResponse,
+ # `toolHint` is absent, never null: the TypeScript contract declares it
+ # optional, and a serialized null would be a value the clients do not type.
+ response_model_exclude_none=True,
+)
+async def chat_suggestions(
+ repo_id: str,
+ request: Request,
+ kind: str,
+ target: str | None = None,
+):
+ """Questions this page has earned, from the read a first question makes.
+
+ Goes through the same two grounding functions ``chat_messages`` uses, so the
+ two can never map a page kind differently, and makes no model call. Returns
+ the measured tier only: an empty list leaves the client's static tier
+ standing rather than restating copy the UI already ships.
+ """
+ factory = resolve_request_session_factory(request)
+ repo_name, repo_path = await _get_repo_info(factory, repo_id)
+ repo_alias = _workspace_alias(request, repo_path, repo_name)
+
+ try:
+ context = ChatPageContext(kind=kind, label=kind, target=target)
+ except ValidationError:
+ # A page kind this server does not serve yet, not an error worth a
+ # banner over a composer.
+ return {"suggestions": []}
+
+ tool_catalog = get_tool_catalog(repo_path)
+ plan = plan_grounding(context, (tool.entry for tool in tool_catalog))
+ if plan is None:
+ return {"suggestions": []}
+
+ async def _execute(name: str, args: dict) -> dict:
+ return await execute_tool(name, args, repo_path=repo_path, repo=repo_alias)
+
+ grounding = await run_grounding(plan, _execute)
+ if grounding is None:
+ return {"suggestions": []}
+ return {
+ "suggestions": page_suggestions(
+ grounding.tool_name, grounding.summary, grounding.result
+ )
+ }
+
+
# ---------------------------------------------------------------------------
# Conversation history endpoints
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index c00b313a5..9bd002d8a 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -39,6 +39,8 @@ from .chat import (
ChatArtifactEnvelope,
ChatMessageResponse,
ChatRequest,
+ ChatSuggestion,
+ ChatSuggestionsResponse,
ConversationDetailResponse,
ConversationForkRequest,
ConversationResponse,
@@ -317,6 +319,8 @@ __all__ = [
"ChatArtifactEnvelope",
"ChatMessageResponse",
"ChatRequest",
+ "ChatSuggestion",
+ "ChatSuggestionsResponse",
"ChurnComplexityPoint",
"ChurnComplexityResponse",
"ClaudeMdGenerateResponse",
diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.py
index 3144fd6f8..85eb4fa40 100644
--- a/packages/server/src/repowise/server/schemas/chat.py
+++ b/packages/server/src/repowise/server/schemas/chat.py
@@ -148,6 +148,22 @@ class ChatArtifactEnvelope(BaseModel):
created_at: str | None = None
+class ChatSuggestion(BaseModel):
+ """One composer chip. ``source`` lets a client rank a measured question
+ above the static tier it already ships."""
+
+ text: str
+ source: Literal["static", "page", "followup"]
+ toolHint: str | None = None # noqa: N815 - wire shape is camelCase
+
+
+class ChatSuggestionsResponse(BaseModel):
+ """Only the measured tier. An empty list means the page had nothing to
+ measure, and the client's own static tier stands."""
+
+ suggestions: list[ChatSuggestion] = []
+
+
class ConversationDetailResponse(BaseModel):
conversation: ConversationResponse
messages: list[ChatMessageResponse] = []
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index bce4e5fcb..c5ed1f859 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -122,6 +122,8 @@ export interface ChatMessage {
model?: string;
/** The step ceiling was reached before a final answer. */
truncated?: boolean;
+ /** Next steps derived from the artifacts this turn produced. */
+ follow_ups?: ChatSuggestion[];
};
created_at: string;
}
@@ -153,6 +155,8 @@ export interface ChatUIMessage {
model?: string;
/** The step ceiling was reached before a final answer. */
truncated?: boolean;
+ /** Next steps this turn earned. Absent on a turn that called no tool. */
+ followUps?: ChatSuggestion[];
}
// ---------------------------------------------------------------------------
@@ -643,5 +647,8 @@ export type ChatSSEEvent =
}
/** Every turn ended in a tool call; `done` still follows. */
| { type: "truncated"; loops: number }
+ /** Next steps for the turn that just finished, sent just before `done`.
+ * A turn that failed or called no tool sends none. */
+ | { type: "suggestions"; suggestions: ChatSuggestion[] }
| { type: "done"; conversation_id: string; message_id: string; user_message_id?: string; provider?: string; model?: string }
| { type: "error"; message: string };
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 8a06591d3..4621c4bfb 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -332,6 +332,24 @@ export interface ChatRequest {
context?: ChatPageContext | null;
}
+/**
+ * One composer chip. ``source`` lets a client rank a measured question
+ * above the static tier it already ships.
+ */
+export interface ChatSuggestion {
+ text: string;
+ source: "static" | "page" | "followup";
+ toolHint?: string | null;
+}
+
+/**
+ * Only the measured tier. An empty list means the page had nothing to
+ * measure, and the client's own static tier stands.
+ */
+export interface ChatSuggestionsResponse {
+ suggestions?: ChatSuggestion[];
+}
+
/**
* One file on the churn-vs-complexity scatter.
*
diff --git a/packages/ui/__tests__/chat/chat-context.test.ts b/packages/ui/__tests__/chat/chat-context.test.ts
index 32c047014..d033540d3 100644
--- a/packages/ui/__tests__/chat/chat-context.test.ts
+++ b/packages/ui/__tests__/chat/chat-context.test.ts
@@ -33,7 +33,9 @@ describe("getChatContextPresentation", () => {
label: "Symbols",
target: "useChat",
});
- expect(presentation.suggestions).toContain("Explain what this symbol does");
+ expect(presentation.suggestions.map((s) => s.text)).toContain(
+ "Explain what this symbol does",
+ );
});
it("distinguishes a collection route from a selected entity", () => {
diff --git a/packages/ui/__tests__/chat/chat-followups.test.tsx b/packages/ui/__tests__/chat/chat-followups.test.tsx
new file mode 100644
index 000000000..b10f04eca
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-followups.test.tsx
@@ -0,0 +1,169 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { ChatInterface } from "../../src/chat/chat-interface.js";
+import { ChatDock, type ChatDockProps } from "../../src/chat/chat-dock.js";
+import type { ChatSuggestion, ChatUIMessage } from "@repowise-dev/types/chat";
+
+const FOLLOW_UPS: ChatSuggestion[] = [
+ { text: "Which tests cover incremental.py?", source: "followup", toolHint: "get_risk" },
+ { text: "What changed there most recently?", source: "followup" },
+];
+
+const ANSWER: ChatUIMessage = {
+ id: "asst-1",
+ role: "assistant",
+ text: "incremental.py carries 28 recorded bug fixes.",
+ toolCalls: [],
+ isStreaming: false,
+ followUps: FOLLOW_UPS,
+};
+
+const QUESTION: ChatUIMessage = {
+ id: "user-1",
+ role: "user",
+ text: "What is risky about incremental.py?",
+ toolCalls: [],
+ isStreaming: false,
+};
+
+function interfaceProps(messages: ChatUIMessage[]) {
+ return {
+ repoId: "r1",
+ messages,
+ isStreaming: false,
+ onSend: vi.fn(),
+ onCancel: vi.fn(),
+ };
+}
+
+afterEach(cleanup);
+
+describe("follow-ups in the transcript", () => {
+ it("offers the newest answer's next steps", () => {
+ render(<ChatInterface {...interfaceProps([QUESTION, ANSWER])} />);
+ const group = screen.getByRole("group", { name: "Next steps" });
+ expect(group).toBeInTheDocument();
+ for (const followUp of FOLLOW_UPS) {
+ expect(screen.getByRole("button", { name: followUp.text })).toBeInTheDocument();
+ }
+ });
+
+ it("seeds the composer with the chip's question", () => {
+ render(<ChatInterface {...interfaceProps([QUESTION, ANSWER])} />);
+ fireEvent.click(screen.getByRole("button", { name: FOLLOW_UPS[0]!.text }));
+ expect(screen.getByRole("textbox")).toHaveValue(FOLLOW_UPS[0]!.text);
+ });
+
+ it("stays out of the way of a question the reader is already writing", () => {
+ render(
+ <ChatInterface
+ {...interfaceProps([QUESTION, ANSWER])}
+ draft="half a question"
+ onDraftChange={vi.fn()}
+ />,
+ );
+ expect(screen.queryByRole("group", { name: "Next steps" })).not.toBeInTheDocument();
+ });
+
+ it("never follows an error", () => {
+ render(
+ <ChatInterface {...interfaceProps([QUESTION, ANSWER])} error="Provider refused" />,
+ );
+ expect(screen.queryByRole("group", { name: "Next steps" })).not.toBeInTheDocument();
+ });
+
+ it("waits for the answer to finish", () => {
+ render(
+ <ChatInterface
+ {...interfaceProps([QUESTION, { ...ANSWER, isStreaming: true }])}
+ isStreaming
+ />,
+ );
+ expect(screen.queryByRole("group", { name: "Next steps" })).not.toBeInTheDocument();
+ });
+
+ it("offers only the newest answer's, not every past turn's", () => {
+ const older: ChatUIMessage = {
+ ...ANSWER,
+ id: "asst-0",
+ followUps: [{ text: "A stale next step", source: "followup" }],
+ };
+ render(<ChatInterface {...interfaceProps([QUESTION, older, QUESTION, ANSWER])} />);
+ expect(screen.queryByRole("button", { name: "A stale next step" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: FOLLOW_UPS[0]!.text })).toBeInTheDocument();
+ });
+});
+
+function dockProps(overrides: Partial<ChatDockProps> = {}): ChatDockProps {
+ return {
+ storageKey: "dock:suggestions",
+ repoId: "r1",
+ context: { kind: "file", label: "Files", target: "src/a.py", targetKind: "path" },
+ messages: [],
+ isStreaming: false,
+ onSend: vi.fn(),
+ onCancel: vi.fn(),
+ ...overrides,
+ };
+}
+
+function openDock() {
+ fireEvent.click(screen.getByRole("button", { name: "Open repository chat" }));
+}
+
+describe("the compact dock's chip slot", () => {
+ beforeEach(() => window.localStorage.clear());
+
+ it("falls back to the page kind's static tier", () => {
+ render(<ChatDock {...dockProps()} />);
+ openDock();
+ expect(
+ screen.getByRole("button", { name: "Explain this file's responsibility" }),
+ ).toHaveAttribute("data-chat-suggestion", "static");
+ });
+
+ it("prefers suggestions measured from the page", () => {
+ const measured: ChatSuggestion[] = [
+ { text: "Explain the 28 bug fixes in src/a.py", source: "page" },
+ ];
+ render(<ChatDock {...dockProps({ suggestions: measured })} />);
+ openDock();
+ expect(
+ screen.getByRole("button", { name: "Explain the 28 bug fixes in src/a.py" }),
+ ).toHaveAttribute("data-chat-suggestion", "page");
+ expect(
+ screen.queryByRole("button", { name: "Explain this file's responsibility" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("turns the slot over to the last answer's next steps once a conversation starts", () => {
+ render(<ChatDock {...dockProps({ messages: [QUESTION, ANSWER] })} />);
+ openDock();
+ expect(
+ screen.queryByRole("button", { name: "Explain this file's responsibility" }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: FOLLOW_UPS[0]!.text })).toBeInTheDocument();
+ });
+
+ it("seeds the composer instead of sending, so the reader can edit first", () => {
+ const onSend = vi.fn();
+ render(<ChatDock {...dockProps({ onSend })} />);
+ openDock();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Explain this file's responsibility" }),
+ );
+ expect(onSend).not.toHaveBeenCalled();
+ expect(screen.getByRole("textbox")).toHaveValue(
+ "Explain this file's responsibility",
+ );
+ });
+
+ it("clears the slot while a draft is being written", () => {
+ render(<ChatDock {...dockProps()} />);
+ openDock();
+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "my own" } });
+ expect(
+ screen.queryByRole("button", { name: "Explain this file's responsibility" }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/chat/chat-suggestions.test.tsx b/packages/ui/__tests__/chat/chat-suggestions.test.tsx
new file mode 100644
index 000000000..592273463
--- /dev/null
+++ b/packages/ui/__tests__/chat/chat-suggestions.test.tsx
@@ -0,0 +1,115 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { ChatSuggestions } from "../../src/chat/chat-suggestions.js";
+import { getChatContextPresentation } from "../../src/chat/chat-context.js";
+import type { ChatSuggestion } from "@repowise-dev/types/chat";
+
+const PAGE: ChatSuggestion[] = [
+ { text: "Explain the 28 bug fixes in incremental.py", source: "page", toolHint: "get_risk" },
+ { text: "Which tests cover incremental.py?", source: "page" },
+];
+
+afterEach(cleanup);
+
+describe("the static fallback tier", () => {
+ it("carries every presentation string as a static suggestion", () => {
+ const presentation = getChatContextPresentation({
+ kind: "symbol",
+ label: "Symbols",
+ target: "useChat",
+ });
+ expect(presentation.suggestions.length).toBeGreaterThan(0);
+ expect(presentation.suggestions.every((s) => s.source === "static")).toBe(true);
+ expect(presentation.suggestions.map((s) => s.text)).toContain(
+ "Explain what this symbol does",
+ );
+ });
+
+ it("keeps the collection tier separate from the targeted tier", () => {
+ const collection = getChatContextPresentation({ kind: "file", label: "Files" });
+ const targeted = getChatContextPresentation({
+ kind: "file",
+ label: "Files",
+ target: "src/index.ts",
+ });
+ expect(collection.suggestions.map((s) => s.text)).toContain(
+ "Which files are the main entry points?",
+ );
+ expect(targeted.suggestions.map((s) => s.text)).toContain(
+ "Explain this file's responsibility",
+ );
+ expect(collection.suggestions.every((s) => s.source === "static")).toBe(true);
+ });
+});
+
+describe("ChatSuggestions", () => {
+ it("renders nothing when there is nothing to suggest", () => {
+ const { container } = render(
+ <ChatSuggestions suggestions={[]} onSelect={vi.fn()} layout="chips" />,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("hands the whole suggestion back, not just its text", () => {
+ const onSelect = vi.fn();
+ render(<ChatSuggestions suggestions={PAGE} onSelect={onSelect} layout="chips" />);
+ fireEvent.click(screen.getByRole("button", { name: PAGE[0]!.text }));
+ expect(onSelect).toHaveBeenCalledWith(PAGE[0]);
+ });
+
+ it("renders every suggestion as a keyboard-reachable button in both layouts", () => {
+ const { rerender } = render(
+ <ChatSuggestions suggestions={PAGE} onSelect={vi.fn()} layout="chips" />,
+ );
+ expect(screen.getAllByRole("button")).toHaveLength(2);
+
+ rerender(
+ <ChatSuggestions
+ suggestions={PAGE}
+ onSelect={vi.fn()}
+ layout="rows"
+ label="Start with"
+ />,
+ );
+ const rows = screen.getAllByRole("button");
+ expect(rows).toHaveLength(2);
+ for (const row of rows) {
+ expect(row).not.toHaveAttribute("disabled");
+ expect(row.tabIndex).not.toBe(-1);
+ }
+ expect(screen.getByText("Start with")).toBeInTheDocument();
+ });
+
+ it("marks each chip with its source so a page tier is distinguishable", () => {
+ render(
+ <ChatSuggestions
+ suggestions={[
+ { text: "measured", source: "page" },
+ { text: "generic", source: "static" },
+ ]}
+ onSelect={vi.fn()}
+ layout="chips"
+ />,
+ );
+ expect(screen.getByRole("button", { name: "measured" })).toHaveAttribute(
+ "data-chat-suggestion",
+ "page",
+ );
+ expect(screen.getByRole("button", { name: "generic" })).toHaveAttribute(
+ "data-chat-suggestion",
+ "static",
+ );
+ });
+
+ it("names the chip group for a screen reader, which has no visible heading", () => {
+ render(
+ <ChatSuggestions
+ suggestions={PAGE}
+ onSelect={vi.fn()}
+ layout="chips"
+ ariaLabel="Next steps"
+ />,
+ );
+ expect(screen.getByRole("group", { name: "Next steps" })).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/chat/chat-context.ts b/packages/ui/src/chat/chat-context.ts
index 47e1b50e9..e05637baf 100644
--- a/packages/ui/src/chat/chat-context.ts
+++ b/packages/ui/src/chat/chat-context.ts
@@ -1,4 +1,8 @@
-import type { ChatContext, ChatContextKind } from "@repowise-dev/types/chat";
+import type {
+ ChatContext,
+ ChatContextKind,
+ ChatSuggestion,
+} from "@repowise-dev/types/chat";
export type {
ChatContext,
@@ -7,11 +11,40 @@ export type {
} from "@repowise-dev/types/chat";
export interface ChatContextPresentation {
+ placeholder: string;
+ suggestions: readonly ChatSuggestion[];
+}
+
+/** The copy tables below stay plain strings so they read as copy. This is the
+ * one place they become the static tier. */
+interface PresentationCopy {
placeholder: string;
suggestions: readonly string[];
}
-const PRESENTATIONS: Record<ChatContextKind, ChatContextPresentation> = {
+function toPresentation(copy: PresentationCopy): ChatContextPresentation {
+ return {
+ placeholder: copy.placeholder,
+ suggestions: copy.suggestions.map((text) => ({
+ text,
+ source: "static" as const,
+ })),
+ };
+}
+
+// Homomorphic so a partial copy table stays partial: the collection tier
+// deliberately covers only the kinds that read differently without a target.
+function toPresentations<T extends Record<string, PresentationCopy | undefined>>(
+ table: T,
+): { [K in keyof T]: ChatContextPresentation } {
+ return Object.fromEntries(
+ Object.entries(table)
+ .filter((entry): entry is [string, PresentationCopy] => entry[1] !== undefined)
+ .map(([kind, copy]) => [kind, toPresentation(copy)]),
+ ) as { [K in keyof T]: ChatContextPresentation };
+}
+
+const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
repository: {
placeholder: "Ask about this repository, or paste a file path",
suggestions: [
@@ -176,8 +209,8 @@ const PRESENTATIONS: Record<ChatContextKind, ChatContextPresentation> = {
},
};
-const COLLECTION_PRESENTATIONS: Partial<
- Record<ChatContextKind, ChatContextPresentation>
+const COLLECTION_PRESENTATION_COPY: Partial<
+ Record<ChatContextKind, PresentationCopy>
> = {
documentation: {
placeholder: "Ask about this repository's documentation",
@@ -237,6 +270,9 @@ const COLLECTION_PRESENTATIONS: Partial<
},
};
+const PRESENTATIONS = toPresentations(PRESENTATION_COPY);
+const COLLECTION_PRESENTATIONS = toPresentations(COLLECTION_PRESENTATION_COPY);
+
export function getChatContextPresentation(
context?: ChatContext,
): ChatContextPresentation {
diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsx
index 11dc30f2c..0d5b44623 100644
--- a/packages/ui/src/chat/chat-dock.tsx
+++ b/packages/ui/src/chat/chat-dock.tsx
@@ -7,8 +7,21 @@ import {
Minus,
X,
} from "lucide-react";
-import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
-import type { ChatArtifact, ChatHandoff, ChatUIMessage } from "@repowise-dev/types/chat";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+ type ReactNode,
+} from "react";
+import type {
+ ChatArtifact,
+ ChatHandoff,
+ ChatSuggestion,
+ ChatUIMessage,
+} from "@repowise-dev/types/chat";
import { BrandMark } from "../shared/brand-mark";
import { Button } from "../ui/button";
import { ActivityDot } from "../ui/activity-dot";
@@ -19,6 +32,7 @@ import { ChatContextIndicator } from "./chat-context-indicator";
import { getChatContextPresentation, type ChatContext } from "./chat-context";
import { ChatInterface } from "./chat-interface";
import { buildHandoffDraft } from "./chat-handoff";
+import { ChatSuggestions } from "./chat-suggestions";
import { CHAT_SHORTCUT_HINT } from "./use-chat-shortcut";
export type ChatDockMode = "minimized" | "compact" | "expanded";
@@ -138,6 +152,9 @@ export interface ChatDockProps {
error?: string | null;
onSend: (text: string, context?: ChatContext) => void | Promise<void>;
onCancel: () => void;
+ /** Suggestions derived from the live page. Omit to use the static tier the
+ * page kind already carries. */
+ suggestions?: readonly ChatSuggestion[];
/** Applied once, then handed back through `onCommandHandled` so remounting
* the dock does not replay it. */
command?: ChatDockCommand | null;
@@ -184,6 +201,7 @@ export function ChatDock({
error,
onSend,
onCancel,
+ suggestions,
command,
onCommandHandled,
firstVisitHint,
@@ -310,6 +328,24 @@ export function ChatDock({
const activeContext = dismissedContext === identity ? undefined : context;
const presentation = getChatContextPresentation(activeContext);
+ // Openers before the first question, the last answer's next steps after, so
+ // the slot is never spent on a stale opener.
+ const chips = useMemo<readonly ChatSuggestion[]>(() => {
+ if (messages.length === 0) return suggestions ?? presentation.suggestions;
+ const last = messages[messages.length - 1];
+ return last?.role === "assistant" && !last.isStreaming
+ ? last.followUps ?? []
+ : [];
+ }, [messages, presentation.suggestions, suggestions]);
+
+ const seedDraft = useCallback(
+ (suggestion: ChatSuggestion) => {
+ setDraft(suggestion.text);
+ compactTextareaRef.current?.focus();
+ },
+ [setDraft],
+ );
+
if (suppressed) return null;
const send = (text: string) => onSend(text, activeContext);
@@ -478,24 +514,16 @@ export function ChatDock({
autoFocus
textareaRef={compactTextareaRef}
/>
- {messages.length === 0 && draft.length === 0 && presentation.suggestions.length > 0 && (
- /* Chips wrap rather than truncate: at 390px a one-line suggestion
- loses the half of the question that made it specific. */
- <div className="mt-2 flex flex-wrap gap-1.5">
- {presentation.suggestions.map((text) => (
- <button
- key={text}
- type="button"
- onClick={() => {
- setDraft(text);
- compactTextareaRef.current?.focus();
- }}
- className="rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-left text-xs text-[var(--color-text-tertiary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
- >
- {text}
- </button>
- ))}
- </div>
+ {draft.length === 0 && (
+ <ChatSuggestions
+ suggestions={chips}
+ onSelect={seedDraft}
+ layout="chips"
+ ariaLabel={
+ messages.length === 0 ? "Suggested questions" : "Next steps"
+ }
+ className="mt-2"
+ />
)}
{sendDisabled && sendDisabledReason && (
<div className="mt-2 text-xs text-[var(--color-text-secondary)]">
@@ -584,6 +612,7 @@ export function ChatDock({
{...(error !== undefined ? { error } : {})}
onSend={send}
onCancel={onCancel}
+ {...(suggestions ? { suggestions } : {})}
draft={draft}
onDraftChange={setDraft}
onContextRemove={removeExpandedContext}
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index 391ab2c69..dececba5e 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -27,7 +27,7 @@ import {
type RefObject,
type ReactNode,
} from "react";
-import { ArrowDown, Send, PanelRight } from "lucide-react";
+import { ArrowDown, PanelRight } from "lucide-react";
import { Button } from "../ui/button";
import { ActivityDot } from "../ui/activity-dot";
import { ScrollArea } from "../ui/scroll-area";
@@ -40,20 +40,25 @@ import {
getChatContextPresentation,
type ChatContext,
} from "./chat-context";
-import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
+import type {
+ ChatArtifact,
+ ChatSuggestion,
+ ChatUIMessage,
+} from "@repowise-dev/types/chat";
import type { SourceReference } from "./source-citations";
import { ChatComposer } from "./chat-composer";
+import { ChatSuggestions } from "./chat-suggestions";
import { CHAT_SHORTCUT_HINT } from "./use-chat-shortcut";
import { useChatScroll } from "./use-chat-scroll";
-const DEFAULT_SUGGESTIONS = [
+const DEFAULT_SUGGESTIONS: readonly ChatSuggestion[] = [
"Give me an overview of this codebase",
"What are the highest-risk files to modify?",
"Score the change risk of HEAD",
"What dead code can be safely removed?",
"What architectural decisions have been made?",
"Search for authentication-related code",
-];
+].map((text) => ({ text, source: "static" as const }));
const MICRO_LABEL =
"font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
@@ -100,8 +105,8 @@ export interface ChatInterfaceProps {
linkPrefix?: string;
/** Logo shown above the empty-state heading. */
emptyStateLogoSrc?: string;
- /** Override default suggestion chips. */
- suggestions?: readonly string[];
+ /** Override the static tier with suggestions derived from live page data. */
+ suggestions?: readonly ChatSuggestion[];
/** Override the context-derived composer placeholder. */
placeholder?: string;
/** Orientation line under the empty-state subtitle — index status, page
@@ -201,6 +206,13 @@ export function ChatInterface({
const visibleSuggestions =
suggestions ?? (context ? contextPresentation.suggestions : DEFAULT_SUGGESTIONS);
const composerPlaceholder = placeholder ?? contextPresentation.placeholder;
+ const lastMessage = messages[messages.length - 1];
+ // An errored turn never carries follow-ups: the server sends them only on a
+ // turn that completed and called a tool.
+ const followUps =
+ !error && lastMessage?.role === "assistant" && !lastMessage.isStreaming
+ ? lastMessage.followUps ?? []
+ : [];
const showContext =
context !== undefined &&
context.kind !== "repository" &&
@@ -301,8 +313,8 @@ export function ChatInterface({
return undefined;
}, [totalArtifactCount, artifactPanelOpen]);
- function handleSuggestion(text: string) {
- setInput(text);
+ function handleSuggestion(suggestion: ChatSuggestion) {
+ setInput(suggestion.text);
textareaRef.current?.focus();
}
@@ -363,24 +375,12 @@ export function ChatInterface({
<p className={cn(MICRO_LABEL)}>{CHAT_SHORTCUT_HINT}</p>
</div>
- {/* Hairline rows, not a grid of bordered boxes. A suggestion is
- not a discrete object you act on repeatedly; it is a list. */}
- <div>
- <p className={cn(MICRO_LABEL, "mb-1")}>Start with</p>
- <ul className="border-t border-[var(--color-border-default)]">
- {visibleSuggestions.map((s) => (
- <li key={s}>
- <button
- className="group flex w-full items-center gap-3 border-b border-[var(--color-border-default)] py-3 text-left text-[15px] text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)]"
- onClick={() => handleSuggestion(s)}
- >
- <span className="flex-1 min-w-0">{s}</span>
- <Send className="h-3.5 w-3.5 shrink-0 opacity-0 transition-opacity group-hover:opacity-100" />
- </button>
- </li>
- ))}
- </ul>
- </div>
+ <ChatSuggestions
+ suggestions={visibleSuggestions}
+ onSelect={handleSuggestion}
+ layout="rows"
+ label="Start with"
+ />
</div>
</ScrollArea>
) : (
@@ -427,6 +427,17 @@ export function ChatInterface({
/>
);
})}
+ {followUps.length > 0 && input.length === 0 && (
+ /* Newest answer only, and only while the composer is empty: a
+ chip that overwrote a half-written question costs more than
+ it saves. */
+ <ChatSuggestions
+ suggestions={followUps}
+ onSelect={handleSuggestion}
+ layout="chips"
+ ariaLabel="Next steps"
+ />
+ )}
{error && (
<div className="rounded-lg border border-[var(--color-error)]/30 bg-[var(--color-error)]/10 px-4 py-2.5 text-sm text-[var(--color-error)]">
{error}
diff --git a/packages/ui/src/chat/chat-suggestions.tsx b/packages/ui/src/chat/chat-suggestions.tsx
new file mode 100644
index 000000000..cc3469b77
--- /dev/null
+++ b/packages/ui/src/chat/chat-suggestions.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+import { Send } from "lucide-react";
+import { cn } from "../lib/cn";
+import type { ChatSuggestion } from "@repowise-dev/types/chat";
+
+export interface ChatSuggestionsProps {
+ suggestions: readonly ChatSuggestion[];
+ onSelect: (suggestion: ChatSuggestion) => void;
+ /** `chips` for the compact dock and for follow-ups beneath an answer;
+ * `rows` for the empty state, where the list is the page's subject. */
+ layout: "chips" | "rows";
+ /** Micro-label above a `rows` list. Chips carry no heading. */
+ label?: string;
+ /** Group name for a screen reader. Defaults to `label` where one shows. */
+ ariaLabel?: string;
+ className?: string;
+}
+
+/**
+ * The one place a suggestion becomes a control, so a chip cannot drift into two
+ * designs. A suggestion is a question, not an object acted on repeatedly, so
+ * neither layout uses a card.
+ */
+export function ChatSuggestions({
+ suggestions,
+ onSelect,
+ layout,
+ label,
+ ariaLabel,
+ className,
+}: ChatSuggestionsProps) {
+ if (suggestions.length === 0) return null;
+
+ if (layout === "chips") {
+ return (
+ /* Chips wrap rather than truncate: at 390px a one-line suggestion loses
+ the half of the question that made it specific. */
+ <div
+ className={cn("flex flex-wrap gap-1.5", className)}
+ {...(ariaLabel ? { role: "group", "aria-label": ariaLabel } : {})}
+ >
+ {suggestions.map((suggestion) => (
+ <button
+ key={suggestion.text}
+ type="button"
+ data-chat-suggestion={suggestion.source}
+ onClick={() => onSelect(suggestion)}
+ className="rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-left text-xs text-[var(--color-text-tertiary)] hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {suggestion.text}
+ </button>
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={className}
+ {...(label || ariaLabel ? { role: "group", "aria-label": ariaLabel ?? label } : {})}
+ >
+ {label && (
+ <p className="mb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {label}
+ </p>
+ )}
+ <ul className="border-t border-[var(--color-border-default)]">
+ {suggestions.map((suggestion) => (
+ <li key={suggestion.text}>
+ <button
+ type="button"
+ data-chat-suggestion={suggestion.source}
+ className="group flex w-full items-center gap-3 border-b border-[var(--color-border-default)] py-3 text-left text-[15px] text-[var(--color-text-secondary)] transition-colors hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ onClick={() => onSelect(suggestion)}
+ >
+ <span className="min-w-0 flex-1">{suggestion.text}</span>
+ <Send
+ aria-hidden
+ className="h-3.5 w-3.5 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100"
+ />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.ts
index df7973797..5b09ac3fe 100644
--- a/packages/ui/src/chat/index.ts
+++ b/packages/ui/src/chat/index.ts
@@ -7,6 +7,7 @@ export * from "./use-chat-draft";
export * from "./chat-composer";
export * from "./chat-dock";
export * from "./chat-context";
+export * from "./chat-suggestions";
export * from "./chat-handoff";
export * from "./ask-about-this";
export * from "./chat-selection-affordance";
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index cbea039e1..7a54622d2 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -48,6 +48,7 @@ export function ChatInterface({
selectModel,
artifactOverrides,
replaceArtifact,
+ suggestions,
} = useRepositoryChat();
const pathname = usePathname();
const router = useRouter();
@@ -182,6 +183,7 @@ export function ChatInterface({
error={error}
onSend={sendWithConversationModel}
onCancel={cancel}
+ {...(suggestions ? { suggestions } : {})}
autoFocus
draft={draft}
onDraftChange={setDraft}
diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsx
index cb21fe1e0..51a0e432f 100644
--- a/packages/web/src/components/chat/repository-chat-dock.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.tsx
@@ -95,6 +95,7 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
...(chat.selectedModel ? { model: chat.selectedModel } : {}),
})}
onCancel={chat.cancel}
+ {...(chat.suggestions ? { suggestions: chat.suggestions } : {})}
command={chat.dockCommand}
onCommandHandled={chat.clearDockCommand}
{...(introduce ? { firstVisitHint: CHAT_SHORTCUT_HINT } : {})}
diff --git a/packages/web/src/components/chat/repository-chat-provider.tsx b/packages/web/src/components/chat/repository-chat-provider.tsx
index d2d7bfdee..33881cf42 100644
--- a/packages/web/src/components/chat/repository-chat-provider.tsx
+++ b/packages/web/src/components/chat/repository-chat-provider.tsx
@@ -11,6 +11,7 @@ import {
type ReactNode,
} from "react";
import { usePathname, useSearchParams } from "next/navigation";
+import useSWR from "swr";
import {
ChatHandoffProvider,
ChatSelectionAffordance,
@@ -19,6 +20,8 @@ import {
type ChatDockCommand,
type ChatHandoff,
} from "@repowise-dev/ui/chat";
+import type { ChatSuggestion } from "@repowise-dev/types/chat";
+import { getChatSuggestions } from "@/lib/api/chat";
import { useChat } from "@/lib/hooks/use-chat";
import { setChatDockHidden } from "@/lib/config";
import { getRepositoryChatContext, getRepositoryChatContextQuery } from "./repository-chat-context";
@@ -37,6 +40,9 @@ export interface RepositoryChatValue extends ChatController {
/** One pending imperative request for the dock. */
dockCommand: ChatDockCommand | null;
clearDockCommand: () => void;
+ /** Questions derived from this page's own data, or undefined while the
+ * request is in flight and whenever the page has nothing measured. */
+ suggestions: ChatSuggestion[] | undefined;
}
const RepositoryChatContext = createContext<RepositoryChatValue | null>(null);
@@ -133,6 +139,29 @@ export function RepositoryChatProvider({
? handoffContext.context
: pageContext;
+ // Without a target the server has nothing to prefetch and would answer with
+ // the static tier the chips already fall back to, so that request is skipped
+ // rather than made and discarded.
+ const suggestionKey = activeContext.target
+ ? `chat-suggestions:${repoId}:${activeContext.kind}:${activeContext.target}`
+ : null;
+ const { data: suggestionData } = useSWR(
+ suggestionKey,
+ () =>
+ getChatSuggestions(repoId, {
+ kind: activeContext.kind,
+ ...(activeContext.target ? { target: activeContext.target } : {}),
+ }),
+ // The key already isolates each page. Stated anyway so a future global
+ // default cannot start offering the previous file's questions.
+ { keepPreviousData: false },
+ );
+ // An empty list means the page measured nothing, which is the static tier's
+ // cue, not an instruction to show no chips at all.
+ const suggestions = suggestionData?.suggestions?.length
+ ? suggestionData.suggestions
+ : undefined;
+
// The full chat page mounts no dock, so a handoff made there would lead
// nowhere. Its transcript already carries its own follow-up affordance.
const onChatPage = pageContext.kind === "chat";
@@ -178,6 +207,7 @@ export function RepositoryChatProvider({
replaceArtifact,
dockCommand,
clearDockCommand,
+ suggestions,
}),
[
repoId,
@@ -197,6 +227,7 @@ export function RepositoryChatProvider({
selectModel,
dockCommand,
clearDockCommand,
+ suggestions,
],
);
diff --git a/packages/web/src/components/chat/repository-chat-suggestions.test.tsx b/packages/web/src/components/chat/repository-chat-suggestions.test.tsx
new file mode 100644
index 000000000..5217160d2
--- /dev/null
+++ b/packages/web/src/components/chat/repository-chat-suggestions.test.tsx
@@ -0,0 +1,134 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { SWRConfig } from "swr";
+import {
+ RepositoryChatProvider,
+ useRepositoryChat,
+} from "./repository-chat-provider";
+
+let pathname = "/repos/r1/files/src/a.py";
+let search = new URLSearchParams();
+
+vi.mock("next/navigation", () => ({
+ usePathname: () => pathname,
+ useSearchParams: () => search,
+}));
+
+vi.mock("@/lib/hooks/use-chat", () => ({
+ useChat: () => ({
+ messages: [],
+ conversationId: null,
+ isStreaming: false,
+ error: null,
+ sendMessage: vi.fn(),
+ loadConversation: vi.fn(),
+ cancel: vi.fn(),
+ reset: vi.fn(),
+ artifactOverrides: {},
+ replaceArtifact: vi.fn(),
+ }),
+}));
+
+const getChatSuggestions = vi.fn();
+vi.mock("@/lib/api/chat", () => ({
+ getChatSuggestions: (...args: unknown[]) => getChatSuggestions(...args),
+}));
+
+function Probe() {
+ const { suggestions } = useRepositoryChat();
+ return (
+ <span data-testid="suggestions">
+ {suggestions === undefined ? "none" : suggestions.map((s) => s.text).join("|")}
+ </span>
+ );
+}
+
+/** A fresh cache per test: the SWR key is shared across these cases, and a
+ * carried-over entry would answer the next one without a request. */
+function shell() {
+ return (
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ <RepositoryChatProvider repoId="r1" repoName="acme">
+ <Probe />
+ </RepositoryChatProvider>
+ </SWRConfig>
+ );
+}
+
+function renderShell() {
+ return render(shell());
+}
+
+function shown(): string {
+ return screen.getByTestId("suggestions").textContent ?? "";
+}
+
+describe("the page tier the provider fetches", () => {
+ beforeEach(() => {
+ pathname = "/repos/r1/files/src/a.py";
+ search = new URLSearchParams();
+ getChatSuggestions.mockReset();
+ window.localStorage.clear();
+ });
+ afterEach(cleanup);
+
+ it("asks for the page the reader is on", async () => {
+ getChatSuggestions.mockResolvedValue({
+ suggestions: [{ text: "Explain the 28 bug fixes in a.py", source: "page" }],
+ });
+ renderShell();
+
+ await waitFor(() => expect(shown()).toBe("Explain the 28 bug fixes in a.py"));
+ expect(getChatSuggestions).toHaveBeenCalledWith("r1", {
+ kind: "file",
+ target: "src/a.py",
+ });
+ });
+
+ it("does not ask when the route names no target", async () => {
+ pathname = "/repos/r1/overview";
+ renderShell();
+
+ await waitFor(() => expect(shown()).toBe("none"));
+ expect(getChatSuggestions).not.toHaveBeenCalled();
+ });
+
+ it("leaves the static tier standing when the page measured nothing", async () => {
+ getChatSuggestions.mockResolvedValue({ suggestions: [] });
+ renderShell();
+
+ await waitFor(() => expect(getChatSuggestions).toHaveBeenCalled());
+ expect(shown()).toBe("none");
+ });
+
+ it("keeps the composer usable when the request fails", async () => {
+ getChatSuggestions.mockRejectedValue(new Error("offline"));
+ renderShell();
+
+ await waitFor(() => expect(getChatSuggestions).toHaveBeenCalled());
+ expect(shown()).toBe("none");
+ });
+
+ it("asks again for a different file rather than holding the last one", async () => {
+ getChatSuggestions.mockResolvedValue({
+ suggestions: [{ text: "About a.py", source: "page" }],
+ });
+ const { rerender } = renderShell();
+ await waitFor(() => expect(shown()).toBe("About a.py"));
+
+ pathname = "/repos/r1/files/src/b.py";
+ getChatSuggestions.mockResolvedValue({
+ suggestions: [{ text: "About b.py", source: "page" }],
+ });
+ rerender(shell());
+
+ await waitFor(() => expect(shown()).toBe("About b.py"));
+ expect(getChatSuggestions).toHaveBeenLastCalledWith("r1", {
+ kind: "file",
+ target: "src/b.py",
+ });
+ });
+});
diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.test.ts b/packages/web/src/lib/chat/to-chat-ui-messages.test.ts
index 413375925..8c2240688 100644
--- a/packages/web/src/lib/chat/to-chat-ui-messages.test.ts
+++ b/packages/web/src/lib/chat/to-chat-ui-messages.test.ts
@@ -160,4 +160,35 @@ describe("toChatUiMessages grounding and truncation", () => {
]);
expect(message).not.toHaveProperty("truncated");
});
+
+ it("restores next steps so a reload shows the same chips as the stream", () => {
+ const followUps = [
+ { text: "Which tests cover a.py?", source: "followup" as const },
+ ];
+ const stored: ChatMessageResponse[] = [
+ {
+ id: "m1",
+ conversation_id: "c1",
+ role: "assistant",
+ content: { text: "Risky.", follow_ups: followUps },
+ created_at: "2026-08-28T00:00:00Z",
+ },
+ ];
+
+ expect(toChatUiMessages(stored)[0]?.followUps).toEqual(followUps);
+ });
+
+ it("leaves a turn that proposed nothing without the field", () => {
+ const stored: ChatMessageResponse[] = [
+ {
+ id: "m1",
+ conversation_id: "c1",
+ role: "assistant",
+ content: { text: "From memory." },
+ created_at: "2026-08-28T00:00:00Z",
+ },
+ ];
+
+ expect(toChatUiMessages(stored)[0]).not.toHaveProperty("followUps");
+ });
});
diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.ts
index 837eb65b9..9cfeb0775 100644
--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts
+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts
@@ -45,5 +45,8 @@ export function toChatUiMessages(
...(message.content.provider ? { provider: message.content.provider } : {}),
...(message.content.model ? { model: message.content.model } : {}),
...(message.content.truncated ? { truncated: true } : {}),
+ ...(message.content.follow_ups?.length
+ ? { followUps: message.content.follow_ups }
+ : {}),
}));
}
diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsx
index e9dedc479..ac07728d2 100644
--- a/packages/web/src/lib/hooks/use-chat.test.tsx
+++ b/packages/web/src/lib/hooks/use-chat.test.tsx
@@ -284,6 +284,46 @@ describe("useChat grounding and truncation events", () => {
expect(result.current.error).toBeNull();
});
+ it("carries the turn's next steps onto the answer", async () => {
+ const followUps = [
+ { text: "Which decisions govern a.py?", source: "followup", toolHint: "get_why" },
+ ];
+ const push = streamed([
+ { type: "suggestions", suggestions: followUps },
+ { type: "done", conversation_id: "c1", message_id: "m1" },
+ ]);
+ const { result } = renderHook(() => useChat("r1"));
+
+ await act(async () => {
+ const sending = result.current.sendMessage("Is a.py risky?");
+ await push();
+ await sending;
+ });
+
+ expect(result.current.messages.at(-1)?.followUps).toEqual(followUps);
+ });
+
+ it("drops the last turn's next steps when a new conversation starts", async () => {
+ const push = streamed([
+ {
+ type: "suggestions",
+ suggestions: [{ text: "Which decisions govern a.py?", source: "followup" }],
+ },
+ { type: "done", conversation_id: "c1", message_id: "m1" },
+ ]);
+ const { result } = renderHook(() => useChat("r1"));
+
+ await act(async () => {
+ const sending = result.current.sendMessage("Is a.py risky?");
+ await push();
+ await sending;
+ });
+ expect(result.current.messages.at(-1)?.followUps).toHaveLength(1);
+
+ act(() => result.current.reset());
+ expect(result.current.messages).toEqual([]);
+ });
+
it("flags the answer when the server reports the step ceiling", async () => {
const push = streamed([
{ type: "truncated", loops: 10 },
diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.ts
index 69621cafd..ecf04ac9d 100644
--- a/packages/web/src/lib/hooks/use-chat.ts
+++ b/packages/web/src/lib/hooks/use-chat.ts
@@ -276,6 +276,9 @@ export function useChat(repoId: string) {
case "truncated":
return { ...m, truncated: true };
+ case "suggestions":
+ return { ...m, followUps: ev.suggestions };
+
case "done":
return {
...m,
diff --git a/tests/unit/server/test_chat_router.py b/tests/unit/server/test_chat_router.py
index eaf1f3693..b55468a9f 100644
--- a/tests/unit/server/test_chat_router.py
+++ b/tests/unit/server/test_chat_router.py
@@ -9,7 +9,7 @@ from unittest.mock import AsyncMock, patch
import pytest
from httpx import ASGITransport, AsyncClient
-from repowise.core.providers.llm.base import ChatStreamEvent, ChatToolCall
+from repowise.core.providers.llm.base import ChatStreamEvent, ChatToolCall, ProviderError
from repowise.server.chat_tools import get_tool_catalog
from repowise.server.routers.chat import _MAX_AGENTIC_LOOPS, _build_system_prompt
from repowise.server.schemas.chat import ChatPageContext
@@ -140,7 +140,7 @@ async def test_file_page_grounds_before_the_first_model_turn():
await _post(app, {"message": "What does this file do?", "context": _FILE_PAGE})
)
- assert _types(events) == ["grounding", "text_delta", "done"]
+ assert _types(events) == ["grounding", "text_delta", "suggestions", "done"]
grounding = events[0]
assert grounding["tool_name"] == "get_context"
assert grounding["input"] == {"targets": ["src/a.py"]}
@@ -233,7 +233,13 @@ async def test_an_unrelated_question_still_calls_tools_normally():
with patch(_PROVIDER, return_value=provider), patch(_EXECUTE, execute):
events = _data_events(await _post(app, {"message": "Is b.py risky?"}))
- assert _types(events) == ["tool_start", "tool_result", "text_delta", "done"]
+ assert _types(events) == [
+ "tool_start",
+ "tool_result",
+ "text_delta",
+ "suggestions",
+ "done",
+ ]
assert events[1]["tool_name"] == "get_risk"
execute.assert_awaited_once()
@@ -255,8 +261,8 @@ async def test_exhausting_the_loop_ceiling_is_reported_before_done():
events = _data_events(await _post(app, {"message": "loop forever"}))
types = _types(events)
- assert types[-2:] == ["truncated", "done"]
- assert events[-2]["loops"] == _MAX_AGENTIC_LOOPS
+ assert types[-3:] == ["truncated", "suggestions", "done"]
+ assert events[-3]["loops"] == _MAX_AGENTIC_LOOPS
assert types.count("tool_result") == _MAX_AGENTIC_LOOPS
assert len(provider.calls) == _MAX_AGENTIC_LOOPS
@@ -279,3 +285,247 @@ async def test_a_turn_that_finishes_with_text_is_not_truncated():
assert "truncated" not in _types(events)
stored = await _stored_messages(app, events[-1]["conversation_id"])
assert "truncated" not in stored[-1]["content"]
+
+
+# ---------------------------------------------------------------------------
+# Suggestions: the endpoint, the follow-ups, and the refined title
+# ---------------------------------------------------------------------------
+
+
+_RISK_RESULT = {
+ "targets": {
+ "src/a.py": {
+ "defect_profile": {"fix_count": 28, "bug_magnet": True},
+ "hotspot_score": 0.96,
+ }
+ }
+}
+
+
+async def _suggestions(app, **params) -> dict:
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get(
+ f"/api/repos/{_REPO_ID}/chat/suggestions", params=params
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+async def test_a_page_with_findings_gets_chips_that_name_them():
+ app = await _make_app()
+ execute = AsyncMock(return_value=_RISK_RESULT)
+
+ with patch(_EXECUTE, execute):
+ body = await _suggestions(app, kind="risk", target="src/a.py")
+
+ texts = [entry["text"] for entry in body["suggestions"]]
+ assert "Explain the 28 bug fixes in a.py" in texts
+ assert all(entry["source"] == "page" for entry in body["suggestions"])
+ execute.assert_awaited_once_with(
+ "get_risk", {"targets": ["src/a.py"]}, repo_path="/tmp/repo", repo=None
+ )
+
+
+async def test_a_route_with_no_target_leaves_the_static_tier_standing():
+ app = await _make_app()
+ execute = AsyncMock(return_value=_RISK_RESULT)
+
+ with patch(_EXECUTE, execute):
+ body = await _suggestions(app, kind="repository")
+
+ assert body == {"suggestions": []}
+ execute.assert_not_awaited()
+
+
+async def test_a_page_kind_the_server_does_not_serve_is_not_an_error():
+ app = await _make_app()
+ assert await _suggestions(app, kind="not-a-page", target="x") == {"suggestions": []}
+
+
+async def test_a_failed_prefetch_yields_no_chips_rather_than_a_broken_one():
+ app = await _make_app()
+
+ with patch(_EXECUTE, AsyncMock(return_value={"error": "no index"})):
+ assert await _suggestions(app, kind="risk", target="src/a.py") == {
+ "suggestions": []
+ }
+
+
+async def test_the_suggestions_endpoint_maps_pages_through_grounding():
+ """The endpoint must not carry a second page-kind table of its own."""
+ app = await _make_app()
+ execute = AsyncMock(return_value=_CONTEXT_RESULT)
+
+ with patch(_EXECUTE, execute):
+ await _suggestions(app, kind="file", target="src/a.py")
+
+ assert execute.await_args.args[0] == "get_context"
+
+
+async def test_a_tool_using_answer_ends_with_next_steps():
+ app = await _make_app()
+ provider = _ScriptedProvider(
+ [[_tool("t1", "get_risk", {"targets": ["src/a.py"]})], [_text("Risky.")]]
+ )
+
+ with patch(_PROVIDER, return_value=provider), patch(
+ _EXECUTE, AsyncMock(return_value=_RISK_RESULT)
+ ):
+ events = _data_events(await _post(app, {"message": "Is a.py risky?"}))
+
+ suggestions = events[-2]
+ assert suggestions["type"] == "suggestions"
+ assert [entry["source"] for entry in suggestions["suggestions"]] == [
+ "followup",
+ "followup",
+ ]
+ assert "Which decisions govern a.py?" in [
+ entry["text"] for entry in suggestions["suggestions"]
+ ]
+
+ stored = await _stored_messages(app, events[-1]["conversation_id"])
+ assert stored[-1]["content"]["follow_ups"] == suggestions["suggestions"]
+
+
+async def test_an_answer_that_read_nothing_proposes_nothing():
+ app = await _make_app()
+ provider = _ScriptedProvider([[_text("From memory.")]])
+
+ with patch(_PROVIDER, return_value=provider):
+ events = _data_events(await _post(app, {"message": "hello"}))
+
+ assert "suggestions" not in _types(events)
+ stored = await _stored_messages(app, events[-1]["conversation_id"])
+ assert "follow_ups" not in stored[-1]["content"]
+
+
+async def test_a_failed_turn_proposes_nothing():
+ app = await _make_app()
+
+ class _Failing:
+ provider_name = "test"
+ model_name = "test-model"
+
+ async def stream_chat(self, **_kwargs):
+ raise ProviderError("provider refused")
+ yield # pragma: no cover
+
+ with patch(_PROVIDER, return_value=_Failing()):
+ events = _data_events(await _post(app, {"message": "hello"}))
+
+ types = _types(events)
+ assert "suggestions" not in types
+ assert types[-1] == "error"
+
+
+async def test_the_opening_turn_names_the_conversation_after_what_it_read():
+ app = await _make_app()
+ provider = _ScriptedProvider(
+ [[_tool("t1", "get_risk", {"targets": ["src/a.py"]})], [_text("Risky.")]]
+ )
+
+ with patch(_PROVIDER, return_value=provider), patch(
+ _EXECUTE, AsyncMock(return_value=_RISK_RESULT)
+ ):
+ events = _data_events(
+ await _post(app, {"message": "What are the highest-risk files to modify?"})
+ )
+
+ conversation_id = events[-1]["conversation_id"]
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ detail = await client.get(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"
+ )
+ assert detail.json()["conversation"]["title"] == "Risk: highest-risk files modify"
+
+
+async def test_a_later_turn_never_overwrites_a_renamed_conversation():
+ app = await _make_app()
+ provider = _ScriptedProvider(lambda _index: [_text("Fine.")])
+
+ with patch(_PROVIDER, return_value=provider):
+ first = _data_events(await _post(app, {"message": "opening question"}))
+ conversation_id = first[-1]["conversation_id"]
+
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ await client.patch(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}",
+ json={"title": "Chosen by hand"},
+ )
+
+ with patch(_PROVIDER, return_value=provider):
+ await _post(app, {"message": "second question", "conversation_id": conversation_id})
+
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ detail = await client.get(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"
+ )
+ assert detail.json()["conversation"]["title"] == "Chosen by hand"
+
+
+async def test_a_tool_that_failed_mid_turn_does_not_propose_a_next_step():
+ """The answer still arrives; it just has nothing measured to build on."""
+ app = await _make_app()
+ provider = _ScriptedProvider(
+ [[_tool("t1", "get_risk", {"targets": ["src/a.py"]})], [_text("No index.")]]
+ )
+
+ with patch(_PROVIDER, return_value=provider), patch(
+ _EXECUTE, AsyncMock(return_value={"error": "no index"})
+ ):
+ events = _data_events(await _post(app, {"message": "Is a.py risky?"}))
+
+ types = _types(events)
+ assert types[-1] == "done"
+ assert "suggestions" not in types
+
+ conversation_id = events[-1]["conversation_id"]
+ stored = await _stored_messages(app, conversation_id)
+ assert "follow_ups" not in stored[-1]["content"]
+
+ transport = ASGITransport(app=app)
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ detail = await client.get(
+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"
+ )
+ # The question alone, with no "Risk:" prefix: nothing was read.
+ assert detail.json()["conversation"]["title"] == "a.py risky"
+
+
+async def test_a_chip_without_a_tool_hint_omits_the_field_rather_than_nulling_it():
+ """No generator omits a hint today, so the shape is pinned from the outside.
+
+ The schema allows a null, which the TypeScript contract does not, and a
+ future derivation that drops the hint must not be what discovers that.
+ """
+ app = await _make_app()
+ hintless = [{"text": "A question with no next tool", "source": "page"}]
+
+ transport = ASGITransport(app=app)
+ with patch(_EXECUTE, AsyncMock(return_value=_RISK_RESULT)), patch(
+ "repowise.server.routers.chat.page_suggestions", return_value=hintless
+ ):
+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.get(
+ f"/api/repos/{_REPO_ID}/chat/suggestions",
+ params={"kind": "risk", "target": "src/a.py"},
+ )
+
+ assert response.status_code == 200, response.text
+ assert "toolHint" not in response.text
+ assert response.json()["suggestions"] == hintless
diff --git a/tests/unit/server/test_chat_suggestions.py b/tests/unit/server/test_chat_suggestions.py
new file mode 100644
index 000000000..feb42dd74
--- /dev/null
+++ b/tests/unit/server/test_chat_suggestions.py
@@ -0,0 +1,338 @@
+"""Deterministic suggestion derivation: measured values only, or nothing."""
+
+from __future__ import annotations
+
+from repowise.server.chat_suggestions import (
+ MAX_FOLLOW_UPS,
+ MAX_PAGE_SUGGESTIONS,
+ conversation_title,
+ follow_up_suggestions,
+ page_suggestions,
+ tool_names,
+)
+
+
+def _texts(entries):
+ return [entry["text"] for entry in entries]
+
+
+# ---------------------------------------------------------------------------
+# The page tier names what the tool measured
+# ---------------------------------------------------------------------------
+
+
+def test_a_file_with_counted_fixes_is_named_by_its_count():
+ result = {
+ "targets": {
+ "packages/core/src/repowise/core/pipeline/incremental.py": {
+ "fix_history": {"fix_count": 28, "last_fix_days_ago": 2, "bug_magnet": True},
+ "hotspot": True,
+ }
+ }
+ }
+ suggestions = page_suggestions("get_context", "packages/.../incremental.py", result)
+
+ assert "Explain the 28 bug fixes in incremental.py" in _texts(suggestions)
+ assert all(entry["source"] == "page" for entry in suggestions)
+
+
+def test_a_file_with_nothing_measured_earns_no_question():
+ result = {"targets": {"src/a.py": {"docs": {"summary": "A module."}}}}
+ assert page_suggestions("get_context", "src/a.py", result) == []
+
+
+def test_risk_names_the_target_carrying_the_most_evidence():
+ result = {
+ "targets": {
+ "src/quiet.py": {"defect_profile": {"fix_count": 1}, "hotspot_score": 0.1},
+ "src/loud.py": {"defect_profile": {"fix_count": 19}, "hotspot_score": 0.9},
+ }
+ }
+ assert "Explain the 19 bug fixes in loud.py" in _texts(
+ page_suggestions("get_risk", "src/quiet.py, src/loud.py", result)
+ )
+
+
+def test_risk_names_a_biomarker_and_the_function_it_sits_in():
+ result = {
+ "targets": {
+ "src/a.py": {
+ "hotspot_score": 0.4,
+ "top_biomarkers": [
+ {
+ "biomarker_type": "nested_complexity",
+ "severity": "high",
+ "function_name": "_db_messages_to_llm_format",
+ }
+ ],
+ }
+ }
+ }
+ assert "Explain the nested complexity finding in _db_messages_to_llm_format" in _texts(
+ page_suggestions("get_risk", "src/a.py", result)
+ )
+
+
+def test_risk_reports_ownership_as_a_measured_share():
+ result = {
+ "targets": {
+ "src/a.py": {"primary_owner": "Raghav", "owner_pct": 0.82, "hotspot_score": 0.3}
+ }
+ }
+ assert "Raghav wrote 82% of a.py. Who else should review a change?" in _texts(
+ page_suggestions("get_risk", "src/a.py", result)
+ )
+
+
+def test_risk_with_no_git_metadata_earns_nothing():
+ result = {
+ "targets": {
+ "src/a.py": {
+ "hotspot_score": 0.0,
+ "is_hotspot": False,
+ "primary_owner": None,
+ "trend": "unknown",
+ "risk_summary": "src/a.py — no git metadata available",
+ }
+ }
+ }
+ assert page_suggestions("get_risk", "src/a.py", result) == []
+
+
+def test_health_names_the_top_finding_and_the_count_behind_it():
+ result = {
+ "mode": "targets",
+ "findings": [
+ {
+ "biomarker_type": "change_entropy",
+ "severity": "critical",
+ "file_path": "src/a.py",
+ "function_name": "handle",
+ "health_impact": 1.14,
+ }
+ ],
+ "findings_total": 7,
+ "metrics": [{"file_path": "src/a.py", "score": 1.0}],
+ }
+ texts = _texts(page_suggestions("get_health", "src/a.py", result))
+
+ assert "Explain the change entropy finding in handle" in texts
+ assert "Which of the 7 findings should I fix first?" in texts
+
+
+def test_health_reads_the_dashboard_shape_too():
+ result = {
+ "top_findings": [
+ {"biomarker_type": "complex_method", "file_path": "src/b.py"}
+ ],
+ "top_findings_total": 3,
+ }
+ texts = _texts(page_suggestions("get_health", "", result))
+
+ assert "Explain the complex method finding in b.py" in texts
+ assert "Which of the 3 findings should I fix first?" in texts
+
+
+def test_a_decision_page_quotes_the_decision_title():
+ result = {
+ "mode": "search",
+ "decisions": [{"id": "d1", "title": "Avoid Ruff formatting", "status": "active"}],
+ }
+ texts = _texts(page_suggestions("get_why", "d1", result))
+
+ assert 'Why was "Avoid Ruff formatting" decided?' in texts
+ assert 'Has later work conflicted with "Avoid Ruff formatting"?' in texts
+
+
+def test_decision_health_mode_has_no_single_decision_to_name():
+ assert page_suggestions("get_why", "", {"mode": "health", "counts": {"active": 4}}) == []
+
+
+def test_a_commit_names_its_rating_without_the_gated_drivers_block():
+ result = {
+ "ref": "9f52f0a",
+ "classification": "elevated",
+ "review_priority": "high",
+ "risk_percentile": 88,
+ "is_fix": True,
+ }
+ texts = _texts(page_suggestions("get_change_risk", "9f52f0a", result))
+
+ assert "Why is 9f52f0a rated elevated at p88?" in texts
+ assert "What did 9f52f0a fix?" in texts
+
+
+def test_a_symbol_page_derives_nothing_and_leaves_the_static_tier_standing():
+ assert page_suggestions("get_symbol", "src/a.py::run", {"source": "def run(): ..."}) == []
+
+
+def test_an_errored_or_missing_result_derives_nothing():
+ assert page_suggestions("get_risk", "src/a.py", {"error": "no index"}) == []
+ assert page_suggestions("get_risk", "src/a.py", None) == []
+ assert page_suggestions("unknown_tool", "src/a.py", {"targets": {}}) == []
+
+
+def test_the_page_tier_is_capped_and_free_of_repeats():
+ result = {
+ "targets": {
+ "src/a.py": {
+ "defect_profile": {"fix_count": 12},
+ "hotspot_score": 0.9,
+ "primary_owner": "Raghav",
+ "owner_pct": 0.5,
+ "co_change_partners_total": 6,
+ "top_biomarkers": [{"biomarker_type": "complex_method", "function_name": "f"}],
+ }
+ }
+ }
+ suggestions = page_suggestions("get_risk", "src/a.py", result)
+
+ assert len(suggestions) == MAX_PAGE_SUGGESTIONS
+ assert len(set(_texts(suggestions))) == MAX_PAGE_SUGGESTIONS
+
+
+# ---------------------------------------------------------------------------
+# Follow-ups come from the tools the turn actually called
+# ---------------------------------------------------------------------------
+
+
+def test_follow_ups_name_the_subject_the_call_was_about():
+ calls = [{"name": "get_context", "arguments": {"targets": ["src/parser.py"]}}]
+ texts = _texts(follow_up_suggestions(calls))
+
+ assert texts == [
+ "What is risky about changing parser.py?",
+ "Which decisions govern parser.py?",
+ ]
+
+
+def test_follow_ups_stay_readable_when_the_call_named_no_subject():
+ texts = _texts(follow_up_suggestions([{"name": "get_health", "arguments": {}}]))
+
+ assert texts == [
+ "Propose a safe refactoring sequence for these findings",
+ "What breaks if I change these files?",
+ ]
+
+
+def test_follow_ups_sit_on_the_freshest_evidence():
+ calls = [
+ {"name": "get_overview", "arguments": {}},
+ {"name": "get_change_risk", "arguments": {"revspec": "HEAD"}},
+ ]
+ texts = _texts(follow_up_suggestions(calls))
+
+ assert texts == [
+ "Which files in HEAD deserve the closest review?",
+ "What tests should validate HEAD?",
+ ]
+
+
+def test_a_turn_that_called_no_tool_earns_no_follow_ups():
+ assert follow_up_suggestions([]) == []
+
+
+def test_an_unmapped_tool_falls_through_to_the_next_call_back():
+ calls = [
+ {"name": "get_overview", "arguments": {}},
+ {"name": "annotate_file", "arguments": {"path": "src/a.py"}},
+ ]
+ assert _texts(follow_up_suggestions(calls)) == [
+ "Which files are riskiest to modify?",
+ "What architectural decisions have been made?",
+ ]
+
+
+def test_follow_ups_are_capped_and_tagged():
+ calls = [
+ {"name": "get_context", "arguments": {"targets": ["src/a.py"]}},
+ {"name": "get_risk", "arguments": {"targets": ["src/a.py"]}},
+ ]
+ suggestions = follow_up_suggestions(calls)
+
+ assert len(suggestions) == MAX_FOLLOW_UPS
+ assert all(entry["source"] == "followup" for entry in suggestions)
+ assert all(entry["toolHint"] for entry in suggestions)
+
+
+def test_a_malformed_stored_call_is_skipped_rather_than_raising():
+ calls = [
+ {"name": "get_overview", "arguments": {}},
+ {"name": None, "arguments": None},
+ {"arguments": {"targets": ["src/a.py"]}},
+ ]
+ assert _texts(follow_up_suggestions(calls)) == [
+ "Which files are riskiest to modify?",
+ "What architectural decisions have been made?",
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Titles
+# ---------------------------------------------------------------------------
+
+
+def test_a_title_names_the_subject_the_turn_read_and_drops_filler():
+ assert (
+ conversation_title("What are the highest-risk files to modify?", ["get_risk"])
+ == "Risk: highest-risk files modify"
+ )
+
+
+def test_a_title_without_a_mapped_tool_is_the_question_alone():
+ assert conversation_title("Explain the parser", []) == "Explain parser"
+
+
+def test_a_title_is_capped():
+ question = "why " + "verylongword " * 20
+ title = conversation_title(question, ["get_health"])
+
+ assert len(title) <= 60
+ assert title.startswith("Code health: ")
+
+
+def test_a_question_that_is_all_filler_keeps_its_own_words():
+ assert conversation_title("what is this", []) == "what is this"
+
+
+def test_an_empty_question_still_produces_a_title():
+ assert conversation_title("", []) == "New conversation"
+
+
+def test_a_windows_path_is_named_by_its_last_segment():
+ result = {
+ "targets": {
+ r"packages\server\src\chat.py": {"defect_profile": {"fix_count": 4}}
+ }
+ }
+ assert "Explain the 4 bug fixes in chat.py" in _texts(
+ page_suggestions("get_risk", r"packages\server\src\chat.py", result)
+ )
+
+
+def test_a_call_that_errored_taught_the_turn_nothing():
+ calls = [
+ {"name": "get_overview", "arguments": {}, "artifact": {"data": {"title": "R"}}},
+ {
+ "name": "get_risk",
+ "arguments": {"targets": ["src/a.py"]},
+ "artifact": {"data": {"error": "no index"}},
+ },
+ ]
+ assert _texts(follow_up_suggestions(calls)) == [
+ "Which files are riskiest to modify?",
+ "What architectural decisions have been made?",
+ ]
+ assert tool_names(calls) == ["get_overview"]
+
+
+def test_a_turn_whose_every_call_failed_proposes_nothing():
+ calls = [{"name": "get_risk", "arguments": {}, "artifact": {"data": {"error": "x"}}}]
+ assert follow_up_suggestions(calls) == []
+ assert tool_names(calls) == []
+
+
+def test_a_title_ignores_a_tool_that_errored():
+ assert conversation_title("What is risky here?", tool_names(
+ [{"name": "get_risk", "artifact": {"data": {"error": "no index"}}}]
+ )) == "risky here"