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.

refactor(ui): split the health and refactoring components this week grew (#3549)

Raghav Chamadiyab5ac66abb865
diff --git a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
index 4babe43a6..4322556b5 100644
--- a/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
+++ b/packages/ui/src/health/ai-prompts/refactoring-plan-steps.ts
@@ -99,15 +99,13 @@ function fenced(text: string): string[] {
return [fence, text, fence];
}
-function extractMethodSteps(plan: RefactoringPlan): string {
- const em = extractMethodPlan(plan);
- if (!em.span) return "Extract the indicated slice into a helper method.";
- const params = em.params.length ? em.params.join(", ") : "(none)";
- const returns = em.returns.length ? em.returns.join(", ") : "(nothing)";
- const name = em.suggested_name ?? HELPER_NAME_PLACEHOLDER;
- const anchors = spanAnchors(plan);
- const lines = `${em.span.start}–${em.span.end}`;
- const rendered = [
+/** The anchored span, the helper's shape and the call site, as bullets. */
+function extractMethodBullets(
+ em: ReturnType<typeof extractMethodPlan>,
+ anchors: ReturnType<typeof spanAnchors>,
+ lines: string,
+): string[] {
+ return [
...(anchors
? [
"- **The span starts with:**",
@@ -124,6 +122,17 @@ function extractMethodSteps(plan: RefactoringPlan): string {
: []),
...em.notes.map((note) => `- **Note:** ${note}`),
];
+}
+
+function extractMethodSteps(plan: RefactoringPlan): string {
+ const em = extractMethodPlan(plan);
+ if (!em.span) return "Extract the indicated slice into a helper method.";
+ const params = em.params.length ? em.params.join(", ") : "(none)";
+ const returns = em.returns.length ? em.returns.join(", ") : "(nothing)";
+ const name = em.suggested_name ?? HELPER_NAME_PLACEHOLDER;
+ const anchors = spanAnchors(plan);
+ const lines = `${em.span.start}–${em.span.end}`;
+ const rendered = extractMethodBullets(em, anchors, lines);
const what = anchors
? `the span of \`${plan.target_symbol}\` that starts and ends with the lines shown (lines ${lines} when planned)`
: `lines ${lines} of \`${plan.target_symbol}\``;
diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsx
index d5d4f194c..4736c8141 100644
--- a/packages/ui/src/health/performance/drawer.tsx
+++ b/packages/ui/src/health/performance/drawer.tsx
@@ -412,7 +412,6 @@ export function OpportunityDrawer({
// The row is the fallback body: a host without the detail call still reads
// every field the queue carried, and simply learns nothing extra.
const resolved = detail && detail.found ? detail : null;
- const unresolved = detail && !detail.found ? detail : null;
const current: PerformanceOpportunity | null = resolved ?? opportunity;
const plan = useVerifiedPlan(current, adapter, planEnabled);
@@ -431,20 +430,7 @@ export function OpportunityDrawer({
<div className="flex-1 space-y-7 overflow-y-auto px-5 py-5">
<WhereToEdit opportunity={current} />
- {unresolved ? <ModelStateNotice state={unresolved.model_state} /> : null}
- {resolved ? <ModelStateNotice state={resolved.model_state} /> : null}
- {unresolved ? (
- <p className="text-sm text-[var(--color-text-tertiary)]">{unresolved.detail}</p>
- ) : null}
- {resolved && resolved.lifecycle_status === "resolved" ? (
- <p
- role="status"
- className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"
- >
- No observation supports this cause in the current index. It is kept so a saved
- link still resolves.
- </p>
- ) : null}
+ <StatusNotices detail={detail} />
<MapLink adapter={adapter} opportunity={current} />
@@ -456,41 +442,7 @@ export function OpportunityDrawer({
<SiblingsNote siblings={current.siblings} onSelect={onSelectById} />
) : null}
- <Section title="Whether it can be changed">
- <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
- <Field
- label="Actionability"
- value={ACTIONABILITY_LABEL[current.actionability_state]}
- detail={humanizeToken(current.actionability_reason)}
- />
- <Field
- label="Actionability confidence"
- value={CONFIDENCE_LABEL[current.facets.actionability_confidence]}
- detail="Whether reducing the work is likely valid."
- />
- <Field
- label="Fix safety"
- value={current.fix ? humanizeToken(current.fix.safety) : "No named fix"}
- detail={
- current.fix
- ? "Whether this one transformation is safe to apply."
- : "No transformation was proposed, so none was judged safe."
- }
- />
- </dl>
- {current.prerequisites.length > 0 ? (
- <div className="mt-3">
- <p className="text-xs text-[var(--color-text-tertiary)]">
- Missing before a fix can be named:
- </p>
- <ul className="mt-1 list-inside list-disc text-xs text-[var(--color-text-secondary)]">
- {current.prerequisites.map((item) => (
- <li key={item}>{humanizeToken(item)}</li>
- ))}
- </ul>
- </div>
- ) : null}
- </Section>
+ <ChangeabilitySection current={current} />
<PlanSection
opportunity={current}
@@ -501,95 +453,13 @@ export function OpportunityDrawer({
<RelatedSection adapter={adapter} filePath={current.file_path} />
- {current.validation ? (
- <CollapsibleSection
- title="Tests"
- hint={
- current.validation.total > 0
- ? `${formatNumber(current.validation.total)} guarding`
- : "none guarding"
- }
- defaultOpen={current.validation.total === 0}
- >
- <ValidationSummary
- validation={toRecommendationValidation(current.validation)}
- fileHref={adapter.fileHref}
- />
- </CollapsibleSection>
- ) : null}
+ <TestsSection current={current} adapter={adapter} />
- <CollapsibleSection title="What the evidence shows">
- <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
- <Field label="Context" value={contextLabel(current.execution_context)} />
- <Field label="Boundary" value={boundaryLabel(current.boundary_kind)} />
- <Field
- label="Evidence confidence"
- value={CONFIDENCE_LABEL[current.confidence]}
- detail={`How reliably the call path resolved. Provenance: ${humanizeToken(current.provenance).toLowerCase()}.`}
- />
- <Field
- label="Affected"
- value={affectedSummary(current)}
- detail={`${current.observations_total.toLocaleString()} observation${current.observations_total === 1 ? "" : "s"} fold into this cause.`}
- />
- <Field
- label="Amplification"
- value={humanizeToken(current.facets.amplification)}
- hint={FACET_GLOSSARY.amplification}
- />
- <Field
- label="Exposure"
- value={humanizeToken(current.facets.exposure)}
- hint={FACET_GLOSSARY.exposure}
- />
- <Field
- label="Leverage"
- value={humanizeToken(current.facets.leverage)}
- hint={FACET_GLOSSARY.leverage}
- />
- <Field
- label="Change risk"
- value={humanizeToken(current.facets.change_risk)}
- hint={FACET_GLOSSARY.change_risk}
- />
- {current.facets.loop_magnitude && current.facets.loop_magnitude !== "n/a" ? (
- <Field
- label="Loop magnitude"
- value={humanizeToken(current.facets.loop_magnitude)}
- hint={FACET_GLOSSARY.loop_magnitude}
- />
- ) : null}
- </dl>
- </CollapsibleSection>
-
- <CollapsibleSection title="Why it ranks here">
- <p className="text-sm text-[var(--color-text-secondary)]">
- Position <span className="tabular-nums">{(current.rank_position + 1).toLocaleString()}</span>{" "}
- in the queue.
- </p>
- {current.why_ranked.length > 0 ? (
- <ul className="mt-2 space-y-1 text-sm text-[var(--color-text-secondary)]">
- {current.why_ranked.map((factor) => (
- <li key={factor.factor} className="tabular-nums">
- {whyRankedLabel(factor)}
- </li>
- ))}
- </ul>
- ) : null}
- </CollapsibleSection>
-
- {current.evidence.some((item) => item.path.length > 0) ? (
- <CollapsibleSection title="Caller to sink paths">
- <ProvenancePathList
- paths={current.evidence
- .filter((item) => item.path.length > 0)
- .map((item) => ({ nodes: item.path, provenance: item.provenance }))}
- total={current.observations_total}
- fileHref={adapter.fileHref}
- {...(adapter.symbolHref ? { symbolHref: adapter.symbolHref } : {})}
- />
- </CollapsibleSection>
- ) : null}
+ <EvidenceSection current={current} />
+
+ <WhyRankedSection current={current} />
+
+ <CallerPathsSection current={current} adapter={adapter} />
<RawObservations
opportunityId={current.opportunity_id}
@@ -599,20 +469,7 @@ export function OpportunityDrawer({
adapter={adapter}
/>
- <CollapsibleSection title="Hand this to an agent">
- <p className="text-sm text-[var(--color-text-secondary)]">
- Ask for the same record by its stable id:
- </p>
- <p className="mt-1 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">
- {agentHandoffCall(current.opportunity_id)}
- </p>
- {resolved?.analyzed_commit ? (
- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
- Analyzed at{" "}
- <span className="font-mono">{resolved.analyzed_commit.slice(0, 7)}</span>.
- </p>
- ) : null}
- </CollapsibleSection>
+ <AgentHandoffSection current={current} resolved={resolved} />
</div>
<div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">
@@ -767,3 +624,208 @@ function MapLink({
</a>
);
}
+
+/** Whether the id resolved, and whether anything still supports it. */
+function StatusNotices({ detail }: { detail: PerformanceOpportunityDetail | undefined }) {
+ const resolved = detail && detail.found ? detail : null;
+ const unresolved = detail && !detail.found ? detail : null;
+ return (
+ <>
+ {unresolved ? <ModelStateNotice state={unresolved.model_state} /> : null}
+ {resolved ? <ModelStateNotice state={resolved.model_state} /> : null}
+ {unresolved ? (
+ <p className="text-sm text-[var(--color-text-tertiary)]">{unresolved.detail}</p>
+ ) : null}
+ {resolved && resolved.lifecycle_status === "resolved" ? (
+ <p
+ role="status"
+ className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"
+ >
+ No observation supports this cause in the current index. It is kept so a saved
+ link still resolves.
+ </p>
+ ) : null}
+ </>
+ );
+}
+
+function ChangeabilitySection({ current }: { current: PerformanceOpportunity }) {
+ return (
+ <Section title="Whether it can be changed">
+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
+ <Field
+ label="Actionability"
+ value={ACTIONABILITY_LABEL[current.actionability_state]}
+ detail={humanizeToken(current.actionability_reason)}
+ />
+ <Field
+ label="Actionability confidence"
+ value={CONFIDENCE_LABEL[current.facets.actionability_confidence]}
+ detail="Whether reducing the work is likely valid."
+ />
+ <Field
+ label="Fix safety"
+ value={current.fix ? humanizeToken(current.fix.safety) : "No named fix"}
+ detail={
+ current.fix
+ ? "Whether this one transformation is safe to apply."
+ : "No transformation was proposed, so none was judged safe."
+ }
+ />
+ </dl>
+ {current.prerequisites.length > 0 ? (
+ <div className="mt-3">
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Missing before a fix can be named:
+ </p>
+ <ul className="mt-1 list-inside list-disc text-xs text-[var(--color-text-secondary)]">
+ {current.prerequisites.map((item) => (
+ <li key={item}>{humanizeToken(item)}</li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ </Section>
+ );
+}
+
+function TestsSection({
+ current,
+ adapter,
+}: {
+ current: PerformanceOpportunity;
+ adapter: PerformanceViewAdapter;
+}) {
+ if (!current.validation) return null;
+ return (
+ <CollapsibleSection
+ title="Tests"
+ hint={
+ current.validation.total > 0
+ ? `${formatNumber(current.validation.total)} guarding`
+ : "none guarding"
+ }
+ defaultOpen={current.validation.total === 0}
+ >
+ <ValidationSummary
+ validation={toRecommendationValidation(current.validation)}
+ fileHref={adapter.fileHref}
+ />
+ </CollapsibleSection>
+ );
+}
+
+function EvidenceSection({ current }: { current: PerformanceOpportunity }) {
+ return (
+ <CollapsibleSection title="What the evidence shows">
+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
+ <Field label="Context" value={contextLabel(current.execution_context)} />
+ <Field label="Boundary" value={boundaryLabel(current.boundary_kind)} />
+ <Field
+ label="Evidence confidence"
+ value={CONFIDENCE_LABEL[current.confidence]}
+ detail={`How reliably the call path resolved. Provenance: ${humanizeToken(current.provenance).toLowerCase()}.`}
+ />
+ <Field
+ label="Affected"
+ value={affectedSummary(current)}
+ detail={`${current.observations_total.toLocaleString()} observation${current.observations_total === 1 ? "" : "s"} fold into this cause.`}
+ />
+ <Field
+ label="Amplification"
+ value={humanizeToken(current.facets.amplification)}
+ hint={FACET_GLOSSARY.amplification}
+ />
+ <Field
+ label="Exposure"
+ value={humanizeToken(current.facets.exposure)}
+ hint={FACET_GLOSSARY.exposure}
+ />
+ <Field
+ label="Leverage"
+ value={humanizeToken(current.facets.leverage)}
+ hint={FACET_GLOSSARY.leverage}
+ />
+ <Field
+ label="Change risk"
+ value={humanizeToken(current.facets.change_risk)}
+ hint={FACET_GLOSSARY.change_risk}
+ />
+ {current.facets.loop_magnitude && current.facets.loop_magnitude !== "n/a" ? (
+ <Field
+ label="Loop magnitude"
+ value={humanizeToken(current.facets.loop_magnitude)}
+ hint={FACET_GLOSSARY.loop_magnitude}
+ />
+ ) : null}
+ </dl>
+ </CollapsibleSection>
+ );
+}
+
+function WhyRankedSection({ current }: { current: PerformanceOpportunity }) {
+ return (
+ <CollapsibleSection title="Why it ranks here">
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Position <span className="tabular-nums">{(current.rank_position + 1).toLocaleString()}</span>{" "}
+ in the queue.
+ </p>
+ {current.why_ranked.length > 0 ? (
+ <ul className="mt-2 space-y-1 text-sm text-[var(--color-text-secondary)]">
+ {current.why_ranked.map((factor) => (
+ <li key={factor.factor} className="tabular-nums">
+ {whyRankedLabel(factor)}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </CollapsibleSection>
+ );
+}
+
+function CallerPathsSection({
+ current,
+ adapter,
+}: {
+ current: PerformanceOpportunity;
+ adapter: PerformanceViewAdapter;
+}) {
+ if (!current.evidence.some((item) => item.path.length > 0)) return null;
+ return (
+ <CollapsibleSection title="Caller to sink paths">
+ <ProvenancePathList
+ paths={current.evidence
+ .filter((item) => item.path.length > 0)
+ .map((item) => ({ nodes: item.path, provenance: item.provenance }))}
+ total={current.observations_total}
+ fileHref={adapter.fileHref}
+ {...(adapter.symbolHref ? { symbolHref: adapter.symbolHref } : {})}
+ />
+ </CollapsibleSection>
+ );
+}
+
+function AgentHandoffSection({
+ current,
+ resolved,
+}: {
+ current: PerformanceOpportunity;
+ resolved: Extract<PerformanceOpportunityDetail, { found: true }> | null;
+}) {
+ return (
+ <CollapsibleSection title="Hand this to an agent">
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Ask for the same record by its stable id:
+ </p>
+ <p className="mt-1 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">
+ {agentHandoffCall(current.opportunity_id)}
+ </p>
+ {resolved?.analyzed_commit ? (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ Analyzed at{" "}
+ <span className="font-mono">{resolved.analyzed_commit.slice(0, 7)}</span>.
+ </p>
+ ) : null}
+ </CollapsibleSection>
+ );
+}
diff --git a/packages/ui/src/health/trend-view.tsx b/packages/ui/src/health/trend-view.tsx
index cf130bc0a..2b4981ab3 100644
--- a/packages/ui/src/health/trend-view.tsx
+++ b/packages/ui/src/health/trend-view.tsx
@@ -64,6 +64,126 @@ function alertTreatment(kind: string): { color: string; label: string; watch: bo
return { color: "var(--color-warning)", label: "Predicted decline.", watch: false };
}
+type TrendSummary = HealthTrendResponse["summary"];
+
+// "0.00 vs. 7.5" is the shape a delta takes when nothing happened, and it
+// reads as a measurement rather than as "no news". Say it plainly instead.
+function deltaSub(delta: number | null, previous: number | null) {
+ if (delta == null) return "no prior snapshot";
+ if (Math.abs(delta) < 0.05) return "unchanged since last index";
+ return `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`;
+}
+
+function codeHealthStat(summary: TrendSummary, otherReading: boolean): RibbonStat {
+ return {
+ label: "Code health",
+ value: otherReading ? "—" : formatScore(summary.current_average_health),
+ ...(otherReading
+ ? { sub: "recorded on the full score" }
+ : {
+ valueColor: scoreTextColor(summary.current_average_health),
+ sub: deltaSub(summary.average_delta, summary.previous_average_health),
+ ...(Math.abs(summary.average_delta ?? 0) >= 0.05
+ ? { subColor: deltaColor(summary.average_delta) }
+ : {}),
+ }),
+ };
+}
+
+function hotspotStat(summary: TrendSummary, otherReading: boolean): RibbonStat {
+ // Absent under a narrowed scope: only the average was recorded for both
+ // populations, so a repo-wide hotspot figure would describe files this view
+ // has dropped. Say so rather than printing one.
+ const hotspot = summary.current_hotspot_health;
+ return {
+ label: "Hotspot health",
+ value: otherReading || hotspot == null ? "—" : formatScore(hotspot),
+ ...(otherReading
+ ? { sub: "recorded on the full score" }
+ : {
+ ...(hotspot == null ? {} : { valueColor: scoreTextColor(hotspot) }),
+ sub:
+ hotspot == null
+ ? "not measured for this scope"
+ : deltaSub(summary.hotspot_delta, summary.previous_hotspot_health),
+ ...(hotspot != null && Math.abs(summary.hotspot_delta ?? 0) >= 0.05
+ ? { subColor: deltaColor(summary.hotspot_delta) }
+ : {}),
+ }),
+ };
+}
+
+function TrendAlerts({ alerts }: { alerts: HealthTrendResponse["alerts"] }) {
+ if (alerts.length === 0) return null;
+ return (
+ <div className="flex flex-col gap-2">
+ {alerts.map((a, i) => {
+ const { color, label, watch } = alertTreatment(a.kind);
+ const Icon = watch ? Info : AlertTriangle;
+ return (
+ <p key={i} className="flex items-start gap-2 text-sm">
+ <Icon className="mt-0.5 h-4 w-4 shrink-0" style={{ color }} aria-hidden />
+ <span>
+ <strong className="font-semibold" style={{ color }}>
+ {label}
+ </strong>{" "}
+ <span className="text-[var(--color-text-secondary)]">{a.message}</span>
+ </span>
+ </p>
+ );
+ })}
+ </div>
+ );
+}
+
+function slopeCaption(data: HealthTrendResponse) {
+ const drawn = Math.min(SLOPE_MAX, data.file_deltas.length);
+ // Without a server-sent total there is no way to know whether
+ // the list arrived complete, so claim only what is drawn.
+ // Saying "all N" off the response length would be a flat lie
+ // against a backend that caps at N and does not report it.
+ if (data.file_deltas_total == null) {
+ return `Showing the ${drawn} largest ${drawn === 1 ? "change" : "changes"}.`;
+ }
+ const total = data.file_deltas_total;
+ return drawn < total
+ ? `Showing the ${drawn} largest of ${total} files that changed.`
+ : `All ${total} ${total === 1 ? "file that changed" : "files that changed"}.`;
+}
+
+function FileDeltasSection({
+ data,
+ singleSnapshot,
+}: {
+ data: HealthTrendResponse;
+ singleSnapshot: boolean;
+}) {
+ return (
+ <section className="flex flex-col gap-2">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Largest score changes since last index
+ </h3>
+ {data.file_deltas.length === 0 ? (
+ <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
+ {singleSnapshot
+ ? "Per-file movement compares the last two snapshots, so it appears with the second one."
+ : "No file changed score between the last two snapshots."}
+ </p>
+ ) : (
+ <>
+ {/* Two caps sit between the response and the picture — the server
+ slices its list, and the chart draws the largest few of what
+ arrives. Naming the drawn count against the true total is the
+ difference between "these are the changes" and "these are the
+ biggest of N". */}
+ <p className="text-xs text-[var(--color-text-tertiary)]">{slopeCaption(data)}</p>
+ <TrendSlopeChart points={data.file_deltas} max={SLOPE_MAX} />
+ </>
+ )}
+ </section>
+ );
+}
+
export function TrendView({
data,
@@ -108,20 +228,6 @@ export function TrendView({
}
const singleSnapshot = data.snapshot_count <= 1;
- const { summary } = data;
-
- // "0.00 vs. 7.5" is the shape a delta takes when nothing happened, and it
- // reads as a measurement rather than as "no news". Say it plainly instead.
- const deltaSub = (delta: number | null, previous: number | null) => {
- if (delta == null) return "no prior snapshot";
- if (Math.abs(delta) < 0.05) return "unchanged since last index";
- return `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`;
- };
-
- // Absent under a narrowed scope: only the average was recorded for both
- // populations, so a repo-wide hotspot figure would describe files this view
- // has dropped. Say so rather than printing one.
- const hotspot = summary.current_hotspot_health;
// Snapshots recorded the full score, so there is no code-shape series to
// read. These two carry the same labels as the lede's figures, and showing
@@ -130,35 +236,8 @@ export function TrendView({
const otherReading = counts === "code_shape";
const stats: RibbonStat[] = [
- {
- label: "Code health",
- value: otherReading ? "—" : formatScore(summary.current_average_health),
- ...(otherReading
- ? { sub: "recorded on the full score" }
- : {
- valueColor: scoreTextColor(summary.current_average_health),
- sub: deltaSub(summary.average_delta, summary.previous_average_health),
- ...(Math.abs(summary.average_delta ?? 0) >= 0.05
- ? { subColor: deltaColor(summary.average_delta) }
- : {}),
- }),
- },
- {
- label: "Hotspot health",
- value: otherReading || hotspot == null ? "—" : formatScore(hotspot),
- ...(otherReading
- ? { sub: "recorded on the full score" }
- : {
- ...(hotspot == null ? {} : { valueColor: scoreTextColor(hotspot) }),
- sub:
- hotspot == null
- ? "not measured for this scope"
- : deltaSub(summary.hotspot_delta, summary.previous_hotspot_health),
- ...(hotspot != null && Math.abs(summary.hotspot_delta ?? 0) >= 0.05
- ? { subColor: deltaColor(summary.hotspot_delta) }
- : {}),
- }),
- },
+ codeHealthStat(data.summary, otherReading),
+ hotspotStat(data.summary, otherReading),
{
label: "Snapshots",
value: String(data.snapshot_count),
@@ -170,25 +249,7 @@ export function TrendView({
<div className="flex flex-col gap-6">
<StatRibbon stats={stats} />
- {data.alerts.length > 0 && (
- <div className="flex flex-col gap-2">
- {data.alerts.map((a, i) => {
- const { color, label, watch } = alertTreatment(a.kind);
- const Icon = watch ? Info : AlertTriangle;
- return (
- <p key={i} className="flex items-start gap-2 text-sm">
- <Icon className="mt-0.5 h-4 w-4 shrink-0" style={{ color }} aria-hidden />
- <span>
- <strong className="font-semibold" style={{ color }}>
- {label}
- </strong>{" "}
- <span className="text-[var(--color-text-secondary)]">{a.message}</span>
- </span>
- </p>
- );
- })}
- </div>
- )}
+ <TrendAlerts alerts={data.alerts} />
{singleSnapshot ? (
<p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
@@ -199,43 +260,7 @@ export function TrendView({
<TrendChart history={[...data.history].reverse()} />
)}
- <section className="flex flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Largest score changes since last index
- </h3>
- {data.file_deltas.length === 0 ? (
- <p className="max-w-[62ch] text-sm text-[var(--color-text-secondary)]">
- {singleSnapshot
- ? "Per-file movement compares the last two snapshots, so it appears with the second one."
- : "No file changed score between the last two snapshots."}
- </p>
- ) : (
- <>
- {/* Two caps sit between the response and the picture — the server
- slices its list, and the chart draws the largest few of what
- arrives. Naming the drawn count against the true total is the
- difference between "these are the changes" and "these are the
- biggest of N". */}
- <p className="text-xs text-[var(--color-text-tertiary)]">
- {(() => {
- const drawn = Math.min(SLOPE_MAX, data.file_deltas.length);
- // Without a server-sent total there is no way to know whether
- // the list arrived complete, so claim only what is drawn.
- // Saying "all N" off the response length would be a flat lie
- // against a backend that caps at N and does not report it.
- if (data.file_deltas_total == null) {
- return `Showing the ${drawn} largest ${drawn === 1 ? "change" : "changes"}.`;
- }
- const total = data.file_deltas_total;
- return drawn < total
- ? `Showing the ${drawn} largest of ${total} files that changed.`
- : `All ${total} ${total === 1 ? "file that changed" : "files that changed"}.`;
- })()}
- </p>
- <TrendSlopeChart points={data.file_deltas} max={SLOPE_MAX} />
- </>
- )}
- </section>
+ <FileDeltasSection data={data} singleSnapshot={singleSnapshot} />
</div>
);
}
diff --git a/packages/ui/src/refactoring/opportunity-drawer.tsx b/packages/ui/src/refactoring/opportunity-drawer.tsx
index 263024056..bdb4da4dc 100644
--- a/packages/ui/src/refactoring/opportunity-drawer.tsx
+++ b/packages/ui/src/refactoring/opportunity-drawer.tsx
@@ -651,9 +651,6 @@ function StepCode({
const [open, setOpen] = React.useState(false);
const stored = plan ? extractHelperDetail(plan) : null;
const range = stepExcerptRange(step, plan);
- const extraction = range?.extraction ?? null;
- const slice = extraction?.span ?? null;
- const stages = range?.stages ?? [];
const canRead = Boolean(readSource && range);
// One read per file however many stage excerpts ask for it.
const readOnce = React.useMemo(() => {
@@ -677,64 +674,115 @@ function StepCode({
</button>
{open ? (
<div className="mt-2 space-y-3">
- {stages.length > 0 ? (
- <p className="text-[11.5px] text-[var(--color-text-tertiary)]">
- Lines{" "}
- <span className="font-mono tabular-nums text-[var(--color-text-secondary)]">
- {formatSpans(stages.map((st) => st.span))}
- </span>{" "}
- become {stages.length} helpers the function calls in order.
- </p>
- ) : null}
- {extraction && slice ? (
- <p className="text-[11.5px] text-[var(--color-text-tertiary)]">
- Lines {slice.start} to {slice.end} become{" "}
- <code className="break-all font-mono text-[var(--color-text-primary)]">
- {extractMethodSignature(extraction)}
- </code>
- </p>
- ) : null}
- {stored?.snippet ? (
- <CodeBlock code={stored.snippet} startLine={stored.snippetStartLine} />
- ) : canRead && stages.length > 0 ? (
- // Each stage on its own: one range from the first stage to the last
- // would show the lines between them and could cut a later stage.
- stages.map((st, i) => (
- <div key={st.span.start} className="space-y-1">
- <p className="font-mono text-[11px] text-[var(--color-text-tertiary)]">
- {`${st.name ?? `Stage ${i + 1}`} · lines ${formatSpans([st.span])}`}
- </p>
- <SourceExcerpt
- path={step.file_path}
- start={st.span.start}
- end={st.span.end}
- readSource={readOnce!}
- />
- </div>
- ))
- ) : canRead ? (
- <SourceExcerpt
- path={step.file_path}
- start={range!.start}
- end={range!.end}
- readSource={readOnce!}
- />
- ) : null}
- {plan && onGenerateCode ? (
- <GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />
- ) : plan && modelSetting ? (
- <RefactoringModelToggle {...modelSetting} />
- ) : plan ? (
- <p className="text-xs text-[var(--color-text-tertiary)]">
- A diff preview is drafted by a model on request. Code generation is off here.
- </p>
- ) : null}
+ <StepSpans range={range} />
+ <StepExcerpt
+ step={step}
+ stored={stored}
+ range={canRead ? range : null}
+ readSource={readOnce}
+ />
+ <StepDiff plan={plan} onGenerateCode={onGenerateCode} modelSetting={modelSetting} />
</div>
) : null}
</div>
);
}
+/** Which lines the step lifts out, and into what. */
+function StepSpans({ range }: { range: ReturnType<typeof stepExcerptRange> }) {
+ const extraction = range?.extraction ?? null;
+ const slice = extraction?.span ?? null;
+ const stages = range?.stages ?? [];
+ return (
+ <>
+ {stages.length > 0 ? (
+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">
+ Lines{" "}
+ <span className="font-mono tabular-nums text-[var(--color-text-secondary)]">
+ {formatSpans(stages.map((st) => st.span))}
+ </span>{" "}
+ become {stages.length} helpers the function calls in order.
+ </p>
+ ) : null}
+ {extraction && slice ? (
+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">
+ Lines {slice.start} to {slice.end} become{" "}
+ <code className="break-all font-mono text-[var(--color-text-primary)]">
+ {extractMethodSignature(extraction)}
+ </code>
+ </p>
+ ) : null}
+ </>
+ );
+}
+
+/**
+ * The excerpt itself: the stored snippet when the plan carries one, else each
+ * stage read on its own, else the step's one range. `range` is null when the
+ * file cannot be read.
+ */
+function StepExcerpt({
+ step,
+ stored,
+ range,
+ readSource,
+}: {
+ step: OpportunityStep;
+ stored: ReturnType<typeof extractHelperDetail> | null;
+ range: ReturnType<typeof stepExcerptRange>;
+ readSource: ((path: string) => Promise<string>) | undefined;
+}) {
+ if (stored?.snippet) {
+ return <CodeBlock code={stored.snippet} startLine={stored.snippetStartLine} />;
+ }
+ if (!range) return null;
+ if (range.stages.length > 0) {
+ // Each stage on its own: one range from the first stage to the last
+ // would show the lines between them and could cut a later stage.
+ return range.stages.map((st, i) => (
+ <div key={st.span.start} className="space-y-1">
+ <p className="font-mono text-[11px] text-[var(--color-text-tertiary)]">
+ {`${st.name ?? `Stage ${i + 1}`} · lines ${formatSpans([st.span])}`}
+ </p>
+ <SourceExcerpt
+ path={step.file_path}
+ start={st.span.start}
+ end={st.span.end}
+ readSource={readSource!}
+ />
+ </div>
+ ));
+ }
+ return (
+ <SourceExcerpt
+ path={step.file_path}
+ start={range.start}
+ end={range.end}
+ readSource={readSource!}
+ />
+ );
+}
+
+/** The diff preview, the model setting that turns it on, or why it is off. */
+function StepDiff({
+ plan,
+ onGenerateCode,
+ modelSetting,
+}: {
+ plan?: RefactoringPlan | undefined;
+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;
+ modelSetting?: RefactoringModelToggleProps | undefined;
+}) {
+ if (!plan) return null;
+ if (onGenerateCode) return <GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />;
+ if (modelSetting) return <RefactoringModelToggle {...modelSetting} />;
+ return (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ A diff preview is drafted by a model on request. Code generation is off here.
+ </p>
+ );
+}
+
/**
* Distinct guarding tests across an opportunity's validation profiles.
*
diff --git a/packages/ui/src/refactoring/refactoring-lede.tsx b/packages/ui/src/refactoring/refactoring-lede.tsx
index d1dbbb7d5..26b42291b 100644
--- a/packages/ui/src/refactoring/refactoring-lede.tsx
+++ b/packages/ui/src/refactoring/refactoring-lede.tsx
@@ -50,6 +50,48 @@ function plural(n: number, one: string, many: string): string {
return `${formatNumber(n)} ${n === 1 ? one : many}`;
}
+/** The chips that filter the list to the subsets the lede names. */
+function LedeChips({
+ facets,
+ quickWinsActive,
+ onToggleQuickWins,
+ onSeeStructural,
+}: Pick<
+ RefactoringLedeProps,
+ "facets" | "onToggleQuickWins" | "onSeeStructural"
+> & { quickWinsActive: boolean }) {
+ const quickWins = facets?.effort?.S ?? 0;
+ const structuralShown = sumStructural(facets?.lead_type);
+ const showQuickWins = onToggleQuickWins && (quickWins > 0 || quickWinsActive);
+ const showStructural = onSeeStructural && structuralShown > 0;
+ if (!showQuickWins && !showStructural) return null;
+ return (
+ <div
+ className="flex flex-wrap items-center gap-x-4 gap-y-2 pt-1"
+ role="group"
+ aria-label="Filter the list"
+ >
+ {showQuickWins ? (
+ <FilterChip active={quickWinsActive} onClick={onToggleQuickWins}>
+ Quick wins{" "}
+ <span className="font-mono tabular-nums">{formatNumber(quickWins)}</span>
+ </FilterChip>
+ ) : null}
+ {showStructural ? (
+ <button
+ type="button"
+ onClick={onSeeStructural}
+ className="rounded text-xs text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ See the{" "}
+ <span className="font-mono tabular-nums">{formatNumber(structuralShown)}</span>{" "}
+ structural
+ </button>
+ ) : null}
+ </div>
+ );
+}
+
export function RefactoringLede({
summary,
counts,
@@ -92,11 +134,6 @@ export function RefactoringLede({
const structural = sumStructural(summary.by_lead_type);
const local = Math.max(0, total - structural);
- const quickWins = facets?.effort?.S ?? 0;
- const structuralShown = sumStructural(facets?.lead_type);
- const showQuickWins = onToggleQuickWins && (quickWins > 0 || quickWinsActive);
- const showStructural = onSeeStructural && structuralShown > 0;
-
return (
<PageLede
label="Open opportunities"
@@ -127,31 +164,12 @@ export function RefactoringLede({
person&apos;s judgment first.
</p>
) : null}
- {showQuickWins || showStructural ? (
- <div
- className="flex flex-wrap items-center gap-x-4 gap-y-2 pt-1"
- role="group"
- aria-label="Filter the list"
- >
- {showQuickWins ? (
- <FilterChip active={quickWinsActive} onClick={onToggleQuickWins}>
- Quick wins{" "}
- <span className="font-mono tabular-nums">{formatNumber(quickWins)}</span>
- </FilterChip>
- ) : null}
- {showStructural ? (
- <button
- type="button"
- onClick={onSeeStructural}
- className="rounded text-xs text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
- >
- See the{" "}
- <span className="font-mono tabular-nums">{formatNumber(structuralShown)}</span>{" "}
- structural
- </button>
- ) : null}
- </div>
- ) : null}
+ <LedeChips
+ facets={facets}
+ quickWinsActive={quickWinsActive}
+ onToggleQuickWins={onToggleQuickWins}
+ onSeeStructural={onSeeStructural}
+ />
</PageLede>
);
}