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): suggest the charts chat can draw (#3869)

Raghav Chamadiya27a5c761dbd4
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.md
index 22cdc71ca..f7bcdf0bd 100644
--- a/docs/reference/API_REFERENCE.md
+++ b/docs/reference/API_REFERENCE.md
@@ -90,7 +90,8 @@ disable the model calls themselves.
it and price with the right model) and calls the pricing table only. It is a
read-only preflight, not a model call.
- `GET /api/repos/{repo_id}/chat/suggestions` goes through the same grounding
- reads as chat but makes no model call.
+ reads as chat but makes no model call. With no `target` it only quotes chart
+ datasets already cached for the current index and reads nothing cold.
- `POST /api/repos/{repo_id}/claude-md/generate` renders `CLAUDE.md` from
indexed data synchronously, with no LLM call (`routers/claude_md.py`).
- `POST /api/repos/{repo_id}/blast-radius` is a deterministic graph analysis
diff --git a/packages/server/src/repowise/server/chat_datasets/__init__.py b/packages/server/src/repowise/server/chat_datasets/__init__.py
index 95a904c41..7c04504ac 100644
--- a/packages/server/src/repowise/server/chat_datasets/__init__.py
+++ b/packages/server/src/repowise/server/chat_datasets/__init__.py
@@ -221,6 +221,28 @@ async def load_rows(name: str, repo: str | None) -> DatasetRows:
return DatasetRows(rows=loaded, as_of=as_of, stale=stale, cached=hit)
+async def cached_rows(names: Iterable[str], repo: str | None) -> dict[str, list[dict[str, Any]]]:
+ """The rows of each dataset in *names* already cached for the current index state.
+
+ Nothing is loaded: a page chip quoting a figure is not worth a cold read
+ (``files`` takes about 2s on a 5,000-file index), so a dataset no chart has
+ read yet is simply absent. Warming the cache at index time would lift that.
+ """
+ from repowise.core.persistence.database import get_session
+ from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context
+ from repowise.server.mcp_server._index_state import index_state_key
+
+ wanted = list(names)
+ if not wanted or not _cache:
+ return {}
+ ctx = await _resolve_repo_context(repo)
+ async with get_session(ctx.session_factory) as session:
+ repository = await _get_repo(session)
+ state = index_state_key(repository)
+ keys = {name: (repository.id, state, name) for name in wanted}
+ return {name: _cache[key] for name, key in keys.items() if key in _cache}
+
+
def _fresh(repository: Any) -> tuple[str | None, bool]:
"""The indexed commit and the stale flag ``_meta`` reports for *repository* now."""
from repowise.server.mcp_server._meta import build_meta
@@ -243,6 +265,7 @@ __all__ = [
"DatasetField",
"DatasetRows",
"LoadContext",
+ "cached_rows",
"catalog",
"clear_cache",
"dataset_names",
diff --git a/packages/server/src/repowise/server/chat_suggestions.py b/packages/server/src/repowise/server/chat_suggestions.py
index 93d851521..e878fdb53 100644
--- a/packages/server/src/repowise/server/chat_suggestions.py
+++ b/packages/server/src/repowise/server/chat_suggestions.py
@@ -2,21 +2,27 @@
``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.
+caller keeps its own static tier. ``collection_suggestions`` does the same for
+a page with no target, from chart dataset rows. ``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
+All take tool results or rows, 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
+from collections.abc import Callable, Mapping, Sequence
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from repowise.server.chat_datasets import Dataset
MAX_PAGE_SUGGESTIONS = 3
+# A page with no target leads its static questions with these, never replaces them.
+MAX_COLLECTION_SUGGESTIONS = 2
MAX_FOLLOW_UPS = 2
# A whole path crowds a 390px dock, so a target is named by its last segment.
@@ -288,6 +294,77 @@ def page_suggestions(
return _dedupe(derive(primary, result))[:MAX_PAGE_SUGGESTIONS]
+# --------------------------------------------------------------------------
+# Collection tier: a page with no target -> a chart its datasets can draw
+# --------------------------------------------------------------------------
+
+Rows = Sequence[Mapping[str, Any]]
+
+
+def _at_risk(rows: Rows) -> str | None:
+ n = sum(1 for r in rows if r.get("health_band") == "at risk")
+ return f"Chart the {n:,} at-risk files by package" if n > 1 else None
+
+
+def _coverage_packages(rows: Rows) -> str | None:
+ n = len({r.get("package") for r in rows})
+ return f"Which of the {n} packages has the lowest coverage?" if n > 1 else None
+
+
+def _findings(rows: Rows) -> str | None:
+ n = len(rows)
+ return f"Chart the {n:,} open findings by severity and package" if n > 1 else None
+
+
+def _hotspots(rows: Rows) -> str | None:
+ n = sum(1 for r in rows if r.get("is_hotspot"))
+ return f"Chart the {n:,} hotspot files by package" if n > 1 else None
+
+
+def _fixed_files(rows: Rows) -> str | None:
+ n = sum(1 for r in rows if (r.get("fix_count") or 0) > 0)
+ return f"Top 10 of the {n:,} files with bug fixes, rest as Other" if n > 10 else None
+
+
+def _dead_code(rows: Rows) -> str | None:
+ n = len(rows)
+ text = f"Stacked bar of the {n:,} dead-code findings by kind and confidence tier"
+ return text if n > 1 else None
+
+
+def _changes(rows: Rows) -> str | None:
+ n = len(rows)
+ return f"Heatmap of the {n:,} merged changes by week and category" if n > 1 else None
+
+
+# Page kind -> (dataset, chip) pairs, most telling first.
+_COLLECTION_CHIPS: dict[str, tuple[tuple[str, Callable[[Rows], str | None]], ...]] = {
+ "repository": (("files", _at_risk), ("changes", _changes)),
+ "overview": (("files", _at_risk), ("changes", _changes)),
+ "health": (("files", _at_risk), ("coverage", _coverage_packages), ("findings", _findings)),
+ "refactoring": (("findings", _findings), ("files", _at_risk)),
+ "risk": (("files", _fixed_files), ("files", _hotspots)),
+ "dead-code": (("dead_code", _dead_code),),
+ "commit": (("changes", _changes),),
+}
+
+
+def collection_datasets(kind: str) -> list[str]:
+ """The datasets a page of *kind* with no target quotes figures from."""
+ return list(dict.fromkeys(name for name, _ in _COLLECTION_CHIPS.get(kind, ())))
+
+
+def collection_suggestions(kind: str, rows: Mapping[str, Rows]) -> list[dict[str, Any]]:
+ """Chart questions quoting what the cached *rows* hold; a dataset absent
+ from *rows* or with nothing to count produces no question."""
+ out = []
+ for name, chip in _COLLECTION_CHIPS.get(kind, ()):
+ text = chip(rows[name]) if name in rows else None
+ if text:
+ out.append(_suggestion(text, "page", "chart"))
+ return _dedupe(out)[:MAX_COLLECTION_SUGGESTIONS]
+
+
# --------------------------------------------------------------------------
# Follow-up tier: what a finished turn read -> the next read worth making
# --------------------------------------------------------------------------
@@ -335,7 +412,69 @@ _FOLLOW_UPS: dict[str, tuple[tuple[str, str, str], ...]] = {
}
+# A chart's next question depends on what it drew, so these are built per call.
+_FIX_FIRST = {
+ "files": ("Which of these files should we fix first?", "get_health"),
+ "findings": ("Which of these findings should we fix first?", "get_health"),
+ "coverage": ("Where should we add tests first?", "get_health"),
+ "dead_code": ("Which of these dead-code findings are safe to remove?", "get_dead_code"),
+}
+
+
+def _drawn(arguments: Mapping[str, Any]) -> set[str]:
+ """The fields a chart call already plots on x or as its series."""
+ x = arguments.get("x")
+ fields = set(x) if isinstance(x, list) else {x}
+ fields.add(arguments.get("series"))
+ return {f for f in fields if isinstance(f, str)}
+
+
+def _breakdown(dataset: Dataset, arguments: Mapping[str, Any], by: str) -> str:
+ """A count over a grouping (health bands, severities) reads as a stacked
+ bar; "break the files down" there drew a table on gpt-5.6-luna. Anything
+ else (a file, a week, a series already drawn) takes the plain wording."""
+ x = arguments.get("x")
+ field = dataset.fields.get(x) if isinstance(x, str) else None
+ if (
+ field is not None
+ and field.type == "text"
+ and x not in dataset.hierarchy
+ and x != "path"
+ and not arguments.get("series")
+ ):
+ return f"Show {_humanize(x)} by {by} as a stacked bar"
+ return f"Break the {dataset.noun} down by {by}"
+
+
+def _chart_follow_ups(arguments: Mapping[str, Any]) -> list[dict[str, Any]]:
+ """Fix first where the rows are things to fix, then a breakdown the chart
+ did not draw, then the same numbers as a table. A discovery call (no x)
+ drew nothing and earns none."""
+ from repowise.server.chat_datasets import get_dataset
+
+ name = arguments.get("dataset")
+ dataset = get_dataset(name) if isinstance(name, str) else None
+ if dataset is None or arguments.get("x") is None:
+ return []
+ out = []
+ if name in _FIX_FIRST:
+ text, hint = _FIX_FIRST[name]
+ out.append(_suggestion(text, "followup", hint))
+ by = next((f for f in ("package", "category") if f in dataset.fields), None)
+ if by and by not in _drawn(arguments):
+ out.append(_suggestion(_breakdown(dataset, arguments, by), "followup", "chart"))
+ if arguments.get("kind") != "table":
+ out.append(_suggestion("Show this as a table", "followup", "show_view"))
+ return out
+
+
def _follow_ups_for(tool_name: str, arguments: Mapping[str, Any]) -> list[dict[str, Any]]:
+ if tool_name == "chart":
+ return _chart_follow_ups(arguments)
+ if tool_name == "show_view":
+ # No table chip: redrawing a redrawn view as a table failed half the
+ # time on gpt-5.6-luna, where a chart tool's table never did.
+ return [_suggestion("What should we fix first here?", "followup", "get_health")]
subject = _subject(arguments)
return [
_suggestion(
diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.py
index 8aa3cff52..b3aaaf2eb 100644
--- a/packages/server/src/repowise/server/routers/chat.py
+++ b/packages/server/src/repowise/server/routers/chat.py
@@ -25,6 +25,7 @@ from repowise.core.providers.llm.resolve import UntrustedBaseUrlError
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_datasets import cached_rows
from repowise.server.chat_errors import (
INVALID_PROVIDER_MESSAGE,
NO_PROVIDER_MESSAGE,
@@ -46,7 +47,11 @@ from repowise.server.chat_session import (
IdempotencyConflictError,
SessionNotFoundError,
)
-from repowise.server.chat_suggestions import page_suggestions
+from repowise.server.chat_suggestions import (
+ collection_datasets,
+ collection_suggestions,
+ page_suggestions,
+)
from repowise.server.deps import (
get_db_session,
request_principal,
@@ -274,7 +279,8 @@ async def chat_suggestions(
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.
+ ships. A page with no target gets chart questions quoting the datasets a
+ chart has already cached, and nothing is read cold for them.
"""
factory = resolve_request_session_factory(request)
repo_name, repo_path = await _get_repo_info(factory, repo_id)
@@ -286,13 +292,17 @@ async def chat_suggestions(
# banner over a composer.
return {"suggestions": []}
+ alias = _workspace_alias(request, repo_path, repo_name)
+ if not context.target:
+ return {"suggestions": await _collection_suggestions(kind, alias)}
+
principal = request_principal(request)
scope = SessionScope(
kind="repo",
repo_id=repo_id,
repo_name=repo_name,
repo_path=repo_path,
- repo_alias=_workspace_alias(request, repo_path, repo_name),
+ repo_alias=alias,
storage=factory,
)
tools = tool_backends.get()(scope, principal)
@@ -311,6 +321,16 @@ async def chat_suggestions(
}
+async def _collection_suggestions(kind: str, alias: str | None) -> list[dict[str, Any]]:
+ """Chart questions from datasets a chart already cached; a failed read is no chips."""
+ try:
+ rows = await cached_rows(collection_datasets(kind), alias)
+ except Exception:
+ logger.exception("chat_collection_suggestions_failed", extra={"kind": kind})
+ return []
+ return collection_suggestions(kind, rows)
+
+
# ---------------------------------------------------------------------------
# Headless sessions
# ---------------------------------------------------------------------------
diff --git a/packages/ui/__tests__/chat/chat-dock-command.test.tsx b/packages/ui/__tests__/chat/chat-dock-command.test.tsx
index 929172f16..844d6c321 100644
--- a/packages/ui/__tests__/chat/chat-dock-command.test.tsx
+++ b/packages/ui/__tests__/chat/chat-dock-command.test.tsx
@@ -121,7 +121,7 @@ describe("ChatDock handoff receiver", () => {
screen.getByRole("button", { name: "Explain the main architectural boundaries" }),
).toBeInTheDocument();
expect(
- screen.getByRole("button", { name: "Where should a new contributor start?" }),
+ screen.getByRole("button", { name: "Give me a one-slide health summary with charts" }),
).toBeInTheDocument();
});
diff --git a/packages/ui/__tests__/chat/chat-dock.test.tsx b/packages/ui/__tests__/chat/chat-dock.test.tsx
index 79662c61a..6b8018521 100644
--- a/packages/ui/__tests__/chat/chat-dock.test.tsx
+++ b/packages/ui/__tests__/chat/chat-dock.test.tsx
@@ -55,7 +55,7 @@ describe("ChatDock", () => {
for (const suggestion of [
"Explain the main architectural boundaries",
"Which parts of this repository deserve attention first?",
- "Where should a new contributor start?",
+ "Give me a one-slide health summary with charts",
]) {
expect(screen.getByRole("button", { name: suggestion })).toBeVisible();
}
diff --git a/packages/ui/__tests__/chat/chat-interface.test.tsx b/packages/ui/__tests__/chat/chat-interface.test.tsx
index b9b9778b8..76fd8ca9a 100644
--- a/packages/ui/__tests__/chat/chat-interface.test.tsx
+++ b/packages/ui/__tests__/chat/chat-interface.test.tsx
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { ChatInterface } from "../../src/chat/chat-interface.js";
+import { EMPTY_CHAT_SUGGESTIONS } from "../../src/chat/chat-context.js";
import type { ChatUIMessage } from "@repowise-dev/types/chat";
const ASSISTANT_MSG: ChatUIMessage = {
@@ -84,9 +85,9 @@ describe("ChatInterface shell", () => {
/>,
);
expect(screen.getByText(/Ask anything about acme/i)).toBeInTheDocument();
- expect(
- screen.getByText(/Give me an overview of this codebase/i),
- ).toBeInTheDocument();
+ for (const suggestion of EMPTY_CHAT_SUGGESTIONS.slice(0, 4)) {
+ expect(screen.getByRole("button", { name: suggestion })).toBeInTheDocument();
+ }
});
it("renders messages and hides empty-state when transcript is non-empty", () => {
diff --git a/packages/ui/src/chat/chat-context.ts b/packages/ui/src/chat/chat-context.ts
index 492c836d0..7029b1cdc 100644
--- a/packages/ui/src/chat/chat-context.ts
+++ b/packages/ui/src/chat/chat-context.ts
@@ -44,13 +44,24 @@ function toPresentations<T extends Record<string, PresentationCopy | undefined>>
) as { [K in keyof T]: ChatContextPresentation };
}
+/** The empty chat's questions: what chat can draw, for readers of either kind.
+ * The empty state shows the first four. */
+export const EMPTY_CHAT_SUGGESTIONS: readonly string[] = [
+ "Chart code health by package as a treemap",
+ "Which files are riskiest to change, and why?",
+ "Show what kinds of changes we made each week",
+ "Give me a one-slide health summary with charts",
+ "Where are the biggest test coverage gaps?",
+ "What dead code can be safely removed?",
+];
+
const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
repository: {
placeholder: "Ask about this repository, or paste a file path",
suggestions: [
"Give me an overview of this codebase",
+ "Chart code health by package as a treemap",
"Which files have the worst code health?",
- "What architectural decisions have been made?",
"What dead code can be safely removed?",
],
},
@@ -59,7 +70,7 @@ const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
suggestions: [
"Explain the main architectural boundaries",
"Which parts of this repository deserve attention first?",
- "Where should a new contributor start?",
+ "Give me a one-slide health summary with charts",
],
},
documentation: {
@@ -74,7 +85,7 @@ const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
placeholder: "Ask about this architecture view",
suggestions: [
"Explain the main component boundaries",
- "Which dependencies create the most coupling?",
+ "Chart the architecture layers by file count",
"Trace a request through this architecture",
],
},
@@ -89,8 +100,8 @@ const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
health: {
placeholder: "Ask about these code health findings",
suggestions: [
+ "Show health bands as a donut",
"Which finding should I address first and why?",
- "Explain the evidence behind the highest-risk finding",
"Propose a safe refactoring sequence",
],
},
@@ -99,7 +110,7 @@ const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
suggestions: [
"Turn this into a safe refactoring plan",
"Which refactoring opportunity is safest to start with?",
- "Which refactoring targets affect the most dependents?",
+ "Chart open findings by severity and package",
],
},
file: {
@@ -153,16 +164,16 @@ const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
risk: {
placeholder: "Ask about the risk evidence on this page",
suggestions: [
+ "Top 10 files by bug fixes, rest as Other",
"Explain the highest-risk result in plain language",
"Which tests reduce the most uncertainty?",
- "Propose the safest order for these changes",
],
},
"dead-code": {
placeholder: "Ask about this dead-code result",
suggestions: [
"Is this safe to remove, and what still reaches it?",
- "Explain the evidence behind this result",
+ "Dead code by kind and confidence tier",
"What should I check before deleting it?",
],
},
@@ -200,12 +211,7 @@ const PRESENTATION_COPY: Record<ChatContextKind, PresentationCopy> = {
},
chat: {
placeholder: "Ask a follow-up, or paste a file path",
- suggestions: [
- "Give me an overview of this codebase",
- "Which files have the worst code health?",
- "Score the change risk of HEAD",
- "What architectural decisions have been made?",
- ],
+ suggestions: EMPTY_CHAT_SUGGESTIONS,
},
};
@@ -244,8 +250,8 @@ const COLLECTION_PRESENTATION_COPY: Partial<
commit: {
placeholder: "Ask about repository history",
suggestions: [
+ "Heatmap of changes by week and category",
"Review the risk of the latest commit",
- "Which files have the most bug-fix history?",
"Find the history behind an architectural choice",
],
},
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index fb51144f0..b7f7e003f 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -36,6 +36,7 @@ import { ChatMessage, type UnverifiedFigureCopy } from "./chat-message";
import { ArtifactPanel } from "./artifact-panel";
import { ChatContextIndicator } from "./chat-context-indicator";
import {
+ EMPTY_CHAT_SUGGESTIONS,
getChatContextPresentation,
type ChatContext,
} from "./chat-context";
@@ -49,14 +50,9 @@ import { ChatComposer } from "./chat-composer";
import { ChatSuggestions } from "./chat-suggestions";
import { useChatScroll } from "./use-chat-scroll";
-const DEFAULT_SUGGESTIONS: readonly ChatSuggestion[] = [
- "Give me an overview of this codebase",
- "Which files have the worst code health?",
- "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 DEFAULT_SUGGESTIONS: readonly ChatSuggestion[] = EMPTY_CHAT_SUGGESTIONS.map(
+ (text) => ({ text, source: "static" as const }),
+);
// Radix wraps viewport content in an inline `display: table` div that grows
// to its widest child, so one wide table or code line widened the whole
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 83c7f768a..b10c670ad 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -915,6 +915,14 @@
"noProviderShort": "No chat provider is configured. Add an API key in <link>settings</link>.",
"unverifiedFigure": "Not found in this turn's tool results",
"unverifiedFiguresNote": "Figures with a dotted underline were not found in this turn's tool results.",
+ "emptySuggestions": {
+ "treemap": "Chart code health by package as a treemap",
+ "riskiest": "Which files are riskiest to change, and why?",
+ "weeklyChanges": "Show what kinds of changes we made each week",
+ "coverageGaps": "Where are the biggest test coverage gaps?",
+ "deadCode": "What dead code can be safely removed?",
+ "healthSlide": "Give me a one-slide health summary with charts"
+ },
"modelMenu": {
"dialog": "Choose conversation model",
"provider": "Provider",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 06c497d6e..ea36fb24a 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -915,6 +915,14 @@
"noProviderShort": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥。",
"unverifiedFigure": "未在本轮工具结果中找到",
"unverifiedFiguresNote": "带点状下划线的数字未在本轮工具结果中找到。",
+ "emptySuggestions": {
+ "treemap": "用树状图按包展示代码健康度",
+ "riskiest": "哪些文件改动风险最高?为什么?",
+ "weeklyChanges": "展示我们每周做了哪些类型的变更",
+ "coverageGaps": "测试覆盖率最大的缺口在哪里?",
+ "deadCode": "哪些死代码可以安全删除?",
+ "healthSlide": "用图表做一页代码健康摘要"
+ },
"modelMenu": {
"dialog": "选择对话模型",
"provider": "提供商",
diff --git a/packages/web/src/components/chat/chat-interface.test.tsx b/packages/web/src/components/chat/chat-interface.test.tsx
index 0e6bb1143..9738678e9 100644
--- a/packages/web/src/components/chat/chat-interface.test.tsx
+++ b/packages/web/src/components/chat/chat-interface.test.tsx
@@ -121,4 +121,15 @@ describe("chat route conversation lifecycle", () => {
expect(mocks.shellProps?.onArtifactNavigate).toBe(navigate);
expect(mocks.shellProps?.onArtifactCompare).toBe(compare);
});
+
+ it("offers the translated empty-chat questions when the page measured none", async () => {
+ render(<ChatInterface repoId="r1" />);
+ await waitFor(() => expect(mocks.shellProps).not.toBeNull());
+ const suggestions = mocks.shellProps?.suggestions as { text: string; source: string }[];
+ expect(suggestions).toHaveLength(6);
+ expect(suggestions[0]).toEqual({
+ text: "Chart code health by package as a treemap",
+ source: "static",
+ });
+ });
});
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index 2be1d9e0f..77099ab48 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -1,6 +1,6 @@
"use client";
-import React, { useCallback, useEffect, useRef } from "react";
+import React, { useCallback, useEffect, useMemo, useRef } from "react";
import useSWR from "swr";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
@@ -45,6 +45,21 @@ export function ChatInterface({
replaceArtifact,
suggestions,
} = useRepositoryChat();
+ // The ui package ships these in English; the empty chat page shows them translated.
+ const emptyChatSuggestions = useMemo(
+ () =>
+ [
+ t("emptySuggestions.treemap"),
+ t("emptySuggestions.riskiest"),
+ t("emptySuggestions.weeklyChanges"),
+ t("emptySuggestions.healthSlide"),
+ t("emptySuggestions.coverageGaps"),
+ t("emptySuggestions.deadCode"),
+ ].map((text) => ({ text, source: "static" as const })),
+ [t],
+ );
+ const visibleSuggestions =
+ suggestions ?? (pageContext.kind === "chat" ? emptyChatSuggestions : undefined);
const pathname = usePathname();
const router = useRouter();
const searchParams = useSearchParams();
@@ -182,7 +197,7 @@ export function ChatInterface({
error={error}
onSend={sendWithConversationModel}
onCancel={cancel}
- {...(suggestions ? { suggestions } : {})}
+ {...(visibleSuggestions ? { suggestions: visibleSuggestions } : {})}
autoFocus
draft={draft}
onDraftChange={setDraft}
diff --git a/packages/web/src/components/chat/repository-chat-provider.tsx b/packages/web/src/components/chat/repository-chat-provider.tsx
index 33881cf42..e7dff37cd 100644
--- a/packages/web/src/components/chat/repository-chat-provider.tsx
+++ b/packages/web/src/components/chat/repository-chat-provider.tsx
@@ -15,6 +15,7 @@ import useSWR from "swr";
import {
ChatHandoffProvider,
ChatSelectionAffordance,
+ getChatContextPresentation,
useChatShortcut,
type ChatContext as PageChatContext,
type ChatDockCommand,
@@ -139,12 +140,13 @@ 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;
+ // Without a target the server prefetches nothing and answers only with chart
+ // questions from datasets it already holds, so the request costs no read.
+ // The full chat page shows its own empty-state questions instead.
+ const suggestionKey =
+ activeContext.kind === "chat"
+ ? null
+ : `chat-suggestions:${repoId}:${activeContext.kind}:${activeContext.target ?? ""}`;
const { data: suggestionData } = useSWR(
suggestionKey,
() =>
@@ -157,10 +159,19 @@ export function RepositoryChatProvider({
{ 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;
+ // cue, not an instruction to show no chips at all. A page with no target
+ // measured counts, not the page itself, so its chips lead the static ones.
+ const measured = suggestionData?.suggestions;
+ const suggestions = useMemo(() => {
+ if (!measured?.length) return undefined;
+ if (activeContext.target) return measured;
+ const shown = getChatContextPresentation(activeContext).suggestions;
+ const texts = new Set(measured.map((s) => s.text));
+ return [...measured, ...shown.filter((s) => !texts.has(s.text))].slice(
+ 0,
+ Math.max(shown.length, measured.length),
+ );
+ }, [activeContext, measured]);
// The full chat page mounts no dock, so a handoff made there would lead
// nowhere. Its transcript already carries its own follow-up affordance.
diff --git a/packages/web/src/components/chat/repository-chat-suggestions.test.tsx b/packages/web/src/components/chat/repository-chat-suggestions.test.tsx
index 5217160d2..f90b6d18b 100644
--- a/packages/web/src/components/chat/repository-chat-suggestions.test.tsx
+++ b/packages/web/src/components/chat/repository-chat-suggestions.test.tsx
@@ -88,14 +88,46 @@ describe("the page tier the provider fetches", () => {
});
});
- it("does not ask when the route names no target", async () => {
- pathname = "/repos/r1/overview";
+ it("does not ask on the full chat page", async () => {
+ pathname = "/repos/r1/chat";
renderShell();
await waitFor(() => expect(shown()).toBe("none"));
expect(getChatSuggestions).not.toHaveBeenCalled();
});
+ it("leads a page with no target's static questions with its measured ones", async () => {
+ pathname = "/repos/r1/hotspots";
+ getChatSuggestions.mockResolvedValue({
+ suggestions: [{ text: "Chart the 40 hotspot files by package", source: "page" }],
+ });
+ renderShell();
+
+ await waitFor(() =>
+ expect(shown()).toBe(
+ "Chart the 40 hotspot files by package|Top 10 files by bug fixes, rest as Other|Explain the highest-risk result in plain language",
+ ),
+ );
+ expect(getChatSuggestions).toHaveBeenCalledWith("r1", { kind: "risk" });
+ });
+
+ it("keeps the page's chip count when two measured chips lead", async () => {
+ pathname = "/repos/r1/hotspots";
+ getChatSuggestions.mockResolvedValue({
+ suggestions: [
+ { text: "Chart the 40 hotspot files by package", source: "page" },
+ { text: "Top 10 files by bug fixes, rest as Other", source: "page" },
+ ],
+ });
+ renderShell();
+
+ await waitFor(() =>
+ expect(shown()).toBe(
+ "Chart the 40 hotspot files by package|Top 10 files by bug fixes, rest as Other|Explain the highest-risk result in plain language",
+ ),
+ );
+ });
+
it("leaves the static tier standing when the page measured nothing", async () => {
getChatSuggestions.mockResolvedValue({ suggestions: [] });
renderShell();
diff --git a/tests/unit/server/mcp/test_chat_datasets.py b/tests/unit/server/mcp/test_chat_datasets.py
index 646b34e01..0a3f55842 100644
--- a/tests/unit/server/mcp/test_chat_datasets.py
+++ b/tests/unit/server/mcp/test_chat_datasets.py
@@ -114,6 +114,13 @@ async def test_rows_are_cached_per_index_state(chart_index):
assert second.rows is first.rows
+async def test_cached_rows_returns_only_what_a_chart_already_read(chart_index):
+ assert await chat_datasets.cached_rows(["files", "changes"], None) == {}
+ files = await _rows("files")
+ cached = await chat_datasets.cached_rows(["files", "changes"], None)
+ assert cached == {"files": files}
+
+
async def test_findings_dead_code_coverage_history_and_layers(chart_index):
findings = await _rows("findings")
assert {f["kind"] for f in findings} >= {"complex_method", "io_in_loop"}
diff --git a/tests/unit/server/test_chat_router.py b/tests/unit/server/test_chat_router.py
index c18486c8b..efc43cdba 100644
--- a/tests/unit/server/test_chat_router.py
+++ b/tests/unit/server/test_chat_router.py
@@ -382,6 +382,37 @@ async def test_a_route_with_no_target_leaves_the_static_tier_standing():
execute.assert_not_awaited()
+async def test_a_route_with_no_target_quotes_datasets_a_chart_cached():
+ app = await _make_app()
+ cached = AsyncMock(return_value={"dead_code": [{}, {}, {}]})
+ execute = AsyncMock(return_value=_RISK_RESULT)
+
+ with patch("repowise.server.routers.chat.cached_rows", cached), patch(_EXECUTE, execute):
+ body = await _suggestions(app, kind="dead-code")
+
+ assert body == {
+ "suggestions": [
+ {
+ "text": "Stacked bar of the 3 dead-code findings by kind and confidence tier",
+ "source": "page",
+ "toolHint": "chart",
+ }
+ ]
+ }
+ cached.assert_awaited_once_with(["dead_code"], None)
+ execute.assert_not_awaited()
+
+
+async def test_a_failed_cache_read_yields_no_chips():
+ app = await _make_app()
+ with patch(
+ "repowise.server.routers.chat.cached_rows", AsyncMock(side_effect=RuntimeError("x"))
+ ):
+ assert await _suggestions(app, kind="health") == {"suggestions": []}
+
+
@pytest.mark.asyncio
async def test_a_page_kind_the_server_does_not_serve_is_not_an_error():
app = await _make_app()
diff --git a/tests/unit/server/test_chat_suggestions.py b/tests/unit/server/test_chat_suggestions.py
index 2ad5fc7ee..80e909769 100644
--- a/tests/unit/server/test_chat_suggestions.py
+++ b/tests/unit/server/test_chat_suggestions.py
@@ -3,8 +3,11 @@
from __future__ import annotations
from repowise.server.chat_suggestions import (
+ MAX_COLLECTION_SUGGESTIONS,
MAX_FOLLOW_UPS,
MAX_PAGE_SUGGESTIONS,
+ collection_datasets,
+ collection_suggestions,
conversation_title,
follow_up_suggestions,
page_suggestions,
@@ -267,6 +270,127 @@ def test_a_malformed_stored_call_is_skipped_rather_than_raising():
]
+# ---------------------------------------------------------------------------
+# A page with no target quotes the datasets a chart already read
+# ---------------------------------------------------------------------------
+
+
+def _files(*bands: str, hotspots: int = 0, fixed: int = 0) -> list[dict]:
+ rows = [{"health_band": band, "is_hotspot": False, "fix_count": 0} for band in bands]
+ for i in range(hotspots):
+ rows[i]["is_hotspot"] = True
+ for i in range(fixed):
+ rows[i]["fix_count"] = 2
+ return rows
+
+
+def test_a_health_page_quotes_the_at_risk_files_and_the_package_count():
+ rows = {
+ "files": _files("at risk", "at risk", "at risk", "good"),
+ "coverage": [{"package": "core"}, {"package": "cli"}, {"package": "core"}],
+ }
+ suggestions = collection_suggestions("health", rows)
+
+ assert _texts(suggestions) == [
+ "Chart the 3 at-risk files by package",
+ "Which of the 2 packages has the lowest coverage?",
+ ]
+ assert all(e["source"] == "page" and e["toolHint"] == "chart" for e in suggestions)
+
+
+def test_a_dataset_no_chart_has_read_earns_no_question():
+ assert collection_suggestions("health", {}) == []
+ assert collection_suggestions("dead-code", {"files": _files("at risk", "at risk")}) == []
+
+
+def test_a_count_too_small_to_chart_earns_no_question():
+ rows = {"files": _files("at risk", "good"), "coverage": [{"package": "core"}]}
+ assert collection_suggestions("health", rows) == []
+
+
+def test_large_counts_read_with_separators_and_the_tier_is_capped():
+ rows = {
+ "files": _files(*(["at risk"] * 1200)),
+ "coverage": [{"package": "a"}, {"package": "b"}],
+ "findings": [{}] * 12503,
+ }
+ suggestions = collection_suggestions("health", rows)
+
+ assert "Chart the 1,200 at-risk files by package" in _texts(suggestions)
+ assert len(suggestions) == MAX_COLLECTION_SUGGESTIONS
+
+
+def test_a_risk_page_names_bug_fixes_and_hotspots_never_a_score():
+ rows = {"files": _files(*(["good"] * 20), hotspots=4, fixed=12)}
+ assert _texts(collection_suggestions("risk", rows)) == [
+ "Top 10 of the 12 files with bug fixes, rest as Other",
+ "Chart the 4 hotspot files by package",
+ ]
+
+
+def test_each_collection_kind_reads_only_the_datasets_it_quotes():
+ assert collection_datasets("health") == ["files", "coverage", "findings"]
+ assert collection_datasets("dead-code") == ["dead_code"]
+ assert collection_datasets("settings") == []
+
+
+# ---------------------------------------------------------------------------
+# Charts earn follow-ups about what they drew
+# ---------------------------------------------------------------------------
+
+
+def test_a_chart_follow_up_names_its_dataset_and_a_breakdown_it_did_not_draw():
+ calls = [{"name": "chart", "arguments": {"dataset": "findings", "x": "severity"}}]
+ assert _texts(follow_up_suggestions(calls)) == [
+ "Which of these findings should we fix first?",
+ "Show severity by package as a stacked bar",
+ ]
+
+
+def test_a_chart_of_files_or_one_with_a_series_breaks_its_rows_down():
+ by_file = [{"name": "chart", "arguments": {"dataset": "files", "x": "file", "y": "fix_count"}}]
+ with_series = [
+ {"name": "chart", "arguments": {"dataset": "dead_code", "x": "kind", "series": "tier"}}
+ ]
+ assert _texts(follow_up_suggestions(by_file))[1] == "Break the files down by package"
+ assert _texts(follow_up_suggestions(with_series))[1] == (
+ "Break the dead-code findings down by package"
+ )
+
+
+def test_a_chart_already_by_package_offers_a_table_instead():
+ calls = [{"name": "chart", "arguments": {"dataset": "coverage", "x": "package"}}]
+ assert _texts(follow_up_suggestions(calls)) == [
+ "Where should we add tests first?",
+ "Show this as a table",
+ ]
+
+
+def test_a_history_chart_breaks_down_by_category():
+ calls = [{"name": "chart", "arguments": {"dataset": "changes", "x": "week"}}]
+ assert _texts(follow_up_suggestions(calls)) == [
+ "Break the merged changes down by category",
+ "Show this as a table",
+ ]
+
+
+def test_a_table_is_not_offered_as_a_table_again():
+ calls = [
+ {"name": "chart", "arguments": {"dataset": "layers", "x": "layer", "kind": "table"}}
+ ]
+ assert follow_up_suggestions(calls) == []
+
+
+def test_a_chart_discovery_call_drew_nothing_and_earns_nothing():
+ assert follow_up_suggestions([{"name": "chart", "arguments": {"dataset": "files"}}]) == []
+ assert follow_up_suggestions([{"name": "chart", "arguments": {"dataset": "nope", "x": "a"}}]) == []
+
+
+def test_a_redrawn_view_asks_what_to_fix_first():
+ calls = [{"name": "show_view", "arguments": {"artifact_id": "v1", "view": "chart"}}]
+ assert _texts(follow_up_suggestions(calls)) == ["What should we fix first here?"]
+
+
# ---------------------------------------------------------------------------
# Titles
# ---------------------------------------------------------------------------