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(vscode): sidebar home dashboard with freshness, theme switcher, and consolidated trees (#650)

Raghav Chamadiya8092ebfd3097
diff --git a/packages/vscode/package.json b/packages/vscode/package.json
index af2c56561..a6bc900f8 100644
--- a/packages/vscode/package.json
+++ b/packages/vscode/package.json
@@ -216,12 +216,7 @@
{
"command": "repowise.showHealthDashboard",
"group": "navigation",
- "when": "view == repowise.healthView"
- },
- {
- "command": "repowise.showDecisionTimeline",
- "group": "navigation",
- "when": "view == repowise.decisionsView"
+ "when": "view == repowise.findingsView"
}
]
},
@@ -242,29 +237,22 @@
"when": "repowise.state != 'ready'"
},
{
- "id": "repowise.healthView",
- "name": "Health",
+ "id": "repowise.homeView",
+ "type": "webview",
+ "name": "Home",
"when": "repowise.state == 'ready'"
},
{
- "id": "repowise.refactoringView",
- "name": "Refactoring",
- "when": "repowise.state == 'ready'"
+ "id": "repowise.findingsView",
+ "name": "Findings",
+ "when": "repowise.state == 'ready'",
+ "visibility": "collapsed"
},
{
- "id": "repowise.hotspotsView",
- "name": "Hotspots & Ownership",
- "when": "repowise.state == 'ready'"
- },
- {
- "id": "repowise.deadCodeView",
- "name": "Dead Code",
- "when": "repowise.state == 'ready'"
- },
- {
- "id": "repowise.decisionsView",
- "name": "Decisions",
- "when": "repowise.state == 'ready'"
+ "id": "repowise.refactoringView",
+ "name": "Refactoring",
+ "when": "repowise.state == 'ready'",
+ "visibility": "collapsed"
}
]
},
diff --git a/packages/vscode/src/constants.ts b/packages/vscode/src/constants.ts
index 7ba66a5fd..e5e32f712 100644
--- a/packages/vscode/src/constants.ts
+++ b/packages/vscode/src/constants.ts
@@ -43,14 +43,15 @@ export const InternalCommands = {
openRefactoringPlan: "repowise.openRefactoringPlan",
} as const;
-/** Tree view ids, mirrored from package.json `contributes.views`. */
+/** Sidebar view ids, mirrored from package.json `contributes.views`. */
export const Views = {
+ /** Welcome/onboarding tree shown until the server is ready. */
home: "repowise.home",
- health: "repowise.healthView",
+ /** The Home webview view (hero score, freshness, dashboard launcher). */
+ homeDashboard: "repowise.homeView",
+ /** Consolidated findings tree: health, hotspots and ownership, dead code. */
+ findings: "repowise.findingsView",
refactoring: "repowise.refactoringView",
- hotspots: "repowise.hotspotsView",
- deadCode: "repowise.deadCodeView",
- decisions: "repowise.decisionsView",
} as const;
/** Context key the welcome views gate on. */
diff --git a/packages/vscode/src/core/gitApi.ts b/packages/vscode/src/core/gitApi.ts
index 6fe5077d6..8c7e275df 100644
--- a/packages/vscode/src/core/gitApi.ts
+++ b/packages/vscode/src/core/gitApi.ts
@@ -1,4 +1,6 @@
import * as vscode from "vscode";
+import { readFile } from "node:fs/promises";
+import * as path from "node:path";
/**
* Guarded adapter over the built-in `vscode.git` extension. We deliberately do
@@ -99,6 +101,46 @@ export async function getHeadCommit(repoRoot: string): Promise<string | null> {
return repo?.state.HEAD?.commit ?? null;
}
+/**
+ * Checked-out commit, preferring the git extension and falling back to reading
+ * `.git/HEAD` from disk. Null when neither side can resolve it.
+ */
+export async function resolveLiveHead(repoRoot: string): Promise<string | null> {
+ const viaGit = await getHeadCommit(repoRoot);
+ if (viaGit) return viaGit;
+ return readHeadFromDisk(repoRoot);
+}
+
+/**
+ * Reads the checked-out commit from `.git` when the git extension is
+ * unavailable. Resolves a symbolic ref to its loose ref file. Packed refs are
+ * not read here; that path degrades to null (no false staleness) and the git
+ * extension covers it when enabled.
+ */
+async function readHeadFromDisk(root: string): Promise<string | null> {
+ try {
+ const raw = (await readFile(path.join(root, ".git", "HEAD"), "utf8")).trim();
+ if (raw.startsWith("ref:")) {
+ const ref = raw.slice(4).trim();
+ const refPath = path.join(root, ".git", ...ref.split("/"));
+ const sha = (await readFile(refPath, "utf8")).trim();
+ return sha || null;
+ }
+ // Detached HEAD: the file holds the commit id directly.
+ return raw || null;
+ } catch {
+ return null;
+ }
+}
+
+/** True when two commit ids refer to the same commit (tolerates short shas). */
+export function commitsMatch(a: string, b: string): boolean {
+ if (a === b) return true;
+ const shorter = a.length < b.length ? a : b;
+ const longer = a.length < b.length ? b : a;
+ return shorter.length > 0 && longer.startsWith(shorter);
+}
+
/**
* Invokes `cb` when the repository's HEAD name or commit changes. Returns a
* disposable, or a no-op disposable when git is unavailable. The underlying
diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.ts
index d5dad39a5..3f36336d2 100644
--- a/packages/vscode/src/core/webviewApi.ts
+++ b/packages/vscode/src/core/webviewApi.ts
@@ -26,9 +26,9 @@ import { getPageById, listAllPages } from "@repowise-dev/api-client/pages";
import { getRiskRange } from "@repowise-dev/api-client/risk";
import { buildRefactoringPlanPrompt } from "@repowise-dev/ui/health/ai-prompt-builder";
import { CONFIG_SECTION } from "../constants";
-import type { HostApi, RiskRangeReport } from "../shared/webviewMessages";
+import type { HomeSummary, HostApi, RiskRangeReport } from "../shared/webviewMessages";
import type { RepowiseContext } from "./context";
-import { getCurrentBranchName } from "./gitApi";
+import { commitsMatch, getCurrentBranchName, resolveLiveHead } from "./gitApi";
/** Thrown by the dispatcher when a request arrives while disconnected. */
class NotReadyError extends Error {
@@ -80,6 +80,69 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostAp
return request;
}
+ /**
+ * Aggregates the sidebar Home payload. Sub-fetches go through the same
+ * cached() keys the dashboards use (limits included), so opening a dashboard
+ * after the sidebar costs nothing extra. Refactoring uses the lighter
+ * medium-confidence query, not the panel's unfiltered multi-megabyte one.
+ * allSettled: one failing endpoint degrades its section to null.
+ */
+ async function homeSummary(): Promise<HomeSummary> {
+ const id = repoId();
+ const [overview, trend, refactor, decisions, liveCommit, branch] =
+ await Promise.allSettled([
+ cached("health:overview:25", () => getHealthOverview(id, 25)),
+ cached("health:trend:20", () => getHealthTrend(id, 20)),
+ cached("home:refactor", () =>
+ getRefactoringTargets(id, { minConfidence: "medium" }),
+ ),
+ cached("decisions:timeline", () =>
+ listDecisions(id, { include_proposed: true, limit: 500 }),
+ ),
+ resolveLiveHead(ctx.workspace.repoRoot ?? ""),
+ getCurrentBranchName(ctx.workspace.repoRoot ?? ""),
+ ]);
+
+ const summary = overview.status === "fulfilled" ? overview.value.summary : null;
+ const trendVal = trend.status === "fulfilled" ? trend.value : null;
+ const indexedCommit =
+ (overview.status === "fulfilled" ? overview.value.meta?.head_commit : null) ??
+ ctx.repo?.head_commit ??
+ null;
+ const live = liveCommit.status === "fulfilled" ? liveCommit.value : null;
+ return {
+ health: summary
+ ? {
+ hotspot: summary.hotspot_health ?? null,
+ average: summary.average_health ?? null,
+ fileCount: summary.file_count,
+ openFindings: summary.open_findings,
+ band: summary.band ?? null,
+ hotspotDelta: trendVal?.summary?.hotspot_delta ?? null,
+ history: (trendVal?.history ?? [])
+ .slice()
+ .reverse()
+ .map((p) => p.hotspot_health),
+ }
+ : null,
+ counts: {
+ refactoringPlans:
+ refactor.status === "fulfilled" ? refactor.value.plans.length : null,
+ decisions: decisions.status === "fulfilled" ? decisions.value.length : null,
+ },
+ freshness: {
+ indexedCommit,
+ liveCommit: live,
+ stale: Boolean(indexedCommit && live && !commitsMatch(indexedCommit, live)),
+ branch: branch.status === "fulfilled" ? branch.value : null,
+ lastIndexedAt:
+ overview.status === "fulfilled"
+ ? (overview.value.meta?.last_indexed_at ?? null)
+ : null,
+ },
+ };
+ }
+
return {
// Health dashboard
healthOverview: (limit) => cached(`health:overview:${limit ?? ""}`, (id) => getHealthOverview(id, limit)),
@@ -142,5 +205,8 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostAp
const branch = await getCurrentBranchName(ctx.workspace.repoRoot ?? "");
return { base, branch, result };
},
+
+ // Sidebar home
+ homeSummary,
};
}
diff --git a/packages/vscode/src/core/webviews.ts b/packages/vscode/src/core/webviews.ts
index 93ddfe1d0..62590cf0c 100644
--- a/packages/vscode/src/core/webviews.ts
+++ b/packages/vscode/src/core/webviews.ts
@@ -1,17 +1,25 @@
import * as vscode from "vscode";
import * as path from "node:path";
import { randomBytes } from "node:crypto";
+import { Commands, Views } from "../constants";
import type { RepowiseContext } from "./context";
import { createHostApi } from "./webviewApi";
import type {
HostApi,
HostToWebviewMessage,
+ PanelViewId,
RepoInit,
+ ThemePreference,
ViewParams,
WebviewToHostMessage,
WebviewViewId,
} from "../shared/webviewMessages";
+/** Workspace-state key for the persisted webview theme preference. */
+const THEME_STATE_KEY = "repowise.webviewTheme";
+
+const THEME_VALUES: readonly ThemePreference[] = ["auto", "light", "dark"];
+
interface ViewMeta {
title: string;
/**
@@ -22,7 +30,7 @@ interface ViewMeta {
retainContextWhenHidden: boolean;
}
-const VIEW_META: Record<WebviewViewId, ViewMeta> = {
+const VIEW_META: Record<PanelViewId, ViewMeta> = {
health: { title: "Repowise Health", retainContextWhenHidden: false },
architecture: { title: "Repowise Architecture", retainContextWhenHidden: false },
graph: { title: "Repowise Knowledge Graph", retainContextWhenHidden: false },
@@ -32,6 +40,11 @@ const VIEW_META: Record<WebviewViewId, ViewMeta> = {
risk: { title: "Repowise Branch Risk", retainContextWhenHidden: false },
};
+/** Tab title for a panel; the sidebar Home view's title lives in the manifest. */
+function viewTitle(view: WebviewViewId): string {
+ return view === "home" ? "Repowise" : VIEW_META[view].title;
+}
+
/** Singleton wired by registerWebviews(); features open panels through it. */
let manager: WebviewManager | null = null;
@@ -40,7 +53,7 @@ let manager: WebviewManager | null = null;
* fresh params are pushed as a new init message so e.g. a different
* refactoring plan replaces the current one instead of spawning a second tab.
*/
-export function openViewPanel<V extends WebviewViewId>(
+export function openViewPanel<V extends PanelViewId>(
ctx: RepowiseContext,
view: V,
params?: ViewParams[V],
@@ -58,14 +71,22 @@ export function openViewPanel<V extends WebviewViewId>(
manager.open(view, params ?? ({} as ViewParams[V]));
}
-/** Registers the panel infrastructure. Idle until the first open. */
+/**
+ * Registers the panel infrastructure and the sidebar Home webview view. Idle
+ * until the first panel open or until the sidebar resolves the Home view.
+ */
export function registerWebviews(
ctx: RepowiseContext,
extensionUri: vscode.Uri,
): vscode.Disposable {
- manager = new WebviewManager(ctx, extensionUri);
+ const created = new WebviewManager(ctx, extensionUri);
+ manager = created;
+ const homeProvider = vscode.window.registerWebviewViewProvider(Views.homeDashboard, {
+ resolveWebviewView: (view) => created.resolveHome(view),
+ });
return {
dispose(): void {
+ homeProvider.dispose();
manager?.dispose();
manager = null;
},
@@ -73,8 +94,10 @@ export function registerWebviews(
}
class WebviewManager {
- private readonly panels = new Map<WebviewViewId, vscode.WebviewPanel>();
- private readonly params = new Map<WebviewViewId, unknown>();
+ private readonly panels = new Map<PanelViewId, vscode.WebviewPanel>();
+ private readonly params = new Map<PanelViewId, unknown>();
+ /** The sidebar Home view, while resolved. */
+ private homeView: vscode.WebviewView | null = null;
private readonly hostApi: HostApi;
private freshnessSub: vscode.Disposable | null = null;
private readonly disposables: vscode.Disposable[] = [];
@@ -102,24 +125,50 @@ class WebviewManager {
private broadcastRefresh(): void {
const repo = this.repoInit();
+ const message = { kind: "refresh", repo } satisfies HostToWebviewMessage;
for (const panel of this.panels.values()) {
- void panel.webview.postMessage({ kind: "refresh", repo } satisfies HostToWebviewMessage);
+ void panel.webview.postMessage(message);
}
+ if (this.homeView) void this.homeView.webview.postMessage(message);
+ }
+
+ /**
+ * Wires the sidebar Home webview view. VS Code resolves it when the view
+ * first becomes visible; with context retention off the webview content is
+ * torn down while hidden and re-runs its script (a fresh ready/init
+ * handshake) on every reveal, so no visibility handling is needed here.
+ */
+ resolveHome(view: vscode.WebviewView): void {
+ this.homeView = view;
+ view.webview.options = {
+ enableScripts: true,
+ localResourceRoots: [vscode.Uri.joinPath(this.extensionUri, "dist", "webview")],
+ };
+ view.webview.html = this.renderHtml("home", view.webview);
+ const msgSub = view.webview.onDidReceiveMessage((msg: WebviewToHostMessage) =>
+ void this.onMessage("home", view.webview, msg),
+ );
+ const dispSub = view.onDidDispose(() => {
+ if (this.homeView === view) this.homeView = null;
+ msgSub.dispose();
+ dispSub.dispose();
+ });
+ this.ensureFreshness();
}
- open(view: WebviewViewId, params: unknown): void {
+ open(view: PanelViewId, params: unknown): void {
this.params.set(view, params);
const existing = this.panels.get(view);
if (existing) {
existing.reveal(undefined, false);
- this.postInit(view, existing);
+ this.postInit(view, existing.webview);
return;
}
const meta = VIEW_META[view];
const panel = vscode.window.createWebviewPanel(
`repowise.${view}`,
- meta.title,
+ viewTitle(view),
vscode.ViewColumn.Active,
{
enableScripts: true,
@@ -132,7 +181,7 @@ class WebviewManager {
// Per-panel subscriptions are released with the panel, not the manager,
// so open/close cycles never accumulate dead listeners.
const msgSub = panel.webview.onDidReceiveMessage((msg: WebviewToHostMessage) =>
- void this.onMessage(view, panel, msg),
+ void this.onMessage(view, panel.webview, msg),
);
const dispSub = panel.onDidDispose(() => {
this.panels.delete(view);
@@ -166,23 +215,30 @@ class WebviewManager {
};
}
- private postInit(view: WebviewViewId, panel: vscode.WebviewPanel): void {
+ private themePref(): ThemePreference {
+ const stored = this.ctx.state.get<ThemePreference>(THEME_STATE_KEY);
+ return stored && THEME_VALUES.includes(stored) ? stored : "auto";
+ }
+
+ private postInit(view: WebviewViewId, webview: vscode.Webview): void {
+ const params = view === "home" ? {} : (this.params.get(view) ?? {});
const message = {
kind: "init",
view,
repo: this.repoInit(),
- params: (this.params.get(view) ?? {}) as ViewParams[typeof view],
+ params: params as ViewParams[typeof view],
+ theme: this.themePref(),
} satisfies HostToWebviewMessage;
- void panel.webview.postMessage(message);
+ void webview.postMessage(message);
}
private async onMessage(
view: WebviewViewId,
- panel: vscode.WebviewPanel,
+ webview: vscode.Webview,
msg: WebviewToHostMessage,
): Promise<void> {
try {
- await this.handleMessage(view, panel, msg);
+ await this.handleMessage(view, webview, msg);
} catch (err) {
// Webview payloads are untrusted input; a malformed one is logged, never
// an unhandled rejection.
@@ -192,12 +248,12 @@ class WebviewManager {
private async handleMessage(
view: WebviewViewId,
- panel: vscode.WebviewPanel,
+ webview: vscode.Webview,
msg: WebviewToHostMessage,
): Promise<void> {
switch (msg.kind) {
case "ready":
- this.postInit(view, panel);
+ this.postInit(view, webview);
return;
case "rpc-request": {
let response: HostToWebviewMessage;
@@ -215,7 +271,36 @@ class WebviewManager {
this.ctx.log.warn(`webview ${view} ${String(msg.method)} failed: ${message}`);
response = { kind: "rpc-response", id: msg.id, ok: false, error: message };
}
- void panel.webview.postMessage(response);
+ void webview.postMessage(response);
+ return;
+ }
+ case "open-view": {
+ // The view id is untrusted input from the webview; validate against
+ // the panel table before opening anything.
+ if (typeof msg.view !== "string" || !Object.hasOwn(VIEW_META, msg.view)) return;
+ const params =
+ msg.params && typeof msg.params === "object" ? msg.params : undefined;
+ openViewPanel(this.ctx, msg.view, params);
+ return;
+ }
+ case "update-index":
+ // Resolves when the update finishes (the command returns its promise).
+ // A successful update also lands as a refresh broadcast; this ack is
+ // what lets the view stop its spinner when the update fails.
+ await vscode.commands.executeCommand(Commands.updateIndex);
+ void webview.postMessage({ kind: "update-done" } satisfies HostToWebviewMessage);
+ return;
+ case "set-theme": {
+ if (!THEME_VALUES.includes(msg.theme)) return;
+ await this.ctx.state.update(THEME_STATE_KEY, msg.theme);
+ const message = {
+ kind: "theme-changed",
+ theme: msg.theme,
+ } satisfies HostToWebviewMessage;
+ for (const panel of this.panels.values()) {
+ void panel.webview.postMessage(message);
+ }
+ if (this.homeView) void this.homeView.webview.postMessage(message);
return;
}
case "open-file": {
@@ -277,7 +362,7 @@ class WebviewManager {
`<meta http-equiv="Content-Security-Policy" content="${csp}" />`,
`<meta name="viewport" content="width=device-width, initial-scale=1.0" />`,
`<link rel="stylesheet" href="${styleUri.toString()}" />`,
- `<title>${VIEW_META[view].title}</title>`,
+ `<title>${viewTitle(view)}</title>`,
"</head>",
"<body>",
`<div id="root"></div>`,
@@ -292,6 +377,9 @@ class WebviewManager {
this.freshnessSub = null;
for (const panel of this.panels.values()) panel.dispose();
this.panels.clear();
+ // The sidebar view is owned by VS Code; dropping the reference is all the
+ // cleanup available (its own onDidDispose releases the subscriptions).
+ this.homeView = null;
for (const d of this.disposables) d.dispose();
this.disposables.length = 0;
}
diff --git a/packages/vscode/src/features/fileScoreStatus.ts b/packages/vscode/src/features/fileScoreStatus.ts
index 606a55523..b4fb69967 100644
--- a/packages/vscode/src/features/fileScoreStatus.ts
+++ b/packages/vscode/src/features/fileScoreStatus.ts
@@ -1,5 +1,5 @@
import * as vscode from "vscode";
-import { Commands, Views } from "../constants";
+import { Commands } from "../constants";
import { getBulkHealth, type FileScores } from "../core/bulkHealth";
import type { RepowiseContext } from "../core/context";
import { repoRelativePath } from "../core/fileSignals";
@@ -109,10 +109,9 @@ export function registerFileScoreStatus(ctx: RepowiseContext): vscode.Disposable
}
});
- // The health tree view auto-generates a `<viewId>.focus` command; reuse it so
- // clicking the score reveals the fuller breakdown.
+ // Clicking the score opens the full health dashboard panel.
const commandSub = vscode.commands.registerCommand(Commands.showFileHealth, () => {
- void vscode.commands.executeCommand(`${Views.health}.focus`);
+ void vscode.commands.executeCommand(Commands.showHealthDashboard);
});
if (ctx.getExtensionState() === "ready") {
diff --git a/packages/vscode/src/features/staleness.ts b/packages/vscode/src/features/staleness.ts
index 3e91a3f29..c780cfb12 100644
--- a/packages/vscode/src/features/staleness.ts
+++ b/packages/vscode/src/features/staleness.ts
@@ -1,9 +1,7 @@
import * as vscode from "vscode";
-import { readFile } from "node:fs/promises";
-import * as path from "node:path";
import { Commands } from "../constants";
import type { RepowiseContext } from "../core/context";
-import { getHeadCommit } from "../core/gitApi";
+import { commitsMatch, resolveLiveHead } from "../core/gitApi";
/** Update runs can be long on a large repo; well above the default timeout. */
const UPDATE_TIMEOUT_MS = 30 * 60_000;
@@ -39,13 +37,6 @@ export function registerStaleness(ctx: RepowiseContext): vscode.Disposable {
/** True while an update is in flight, to enforce single-flight. */
let updating = false;
- /** Live checked-out commit, preferring the git extension over disk reads. */
- async function liveHead(root: string): Promise<string | null> {
- const viaGit = await getHeadCommit(root);
- if (viaGit) return viaGit;
- return readHeadFromDisk(root);
- }
-
async function evaluate(): Promise<void> {
const indexed = ctx.repo?.head_commit;
const root = ctx.workspace.repoRoot;
@@ -55,7 +46,7 @@ export function registerStaleness(ctx: RepowiseContext): vscode.Disposable {
item.hide();
return;
}
- const live = await liveHead(root);
+ const live = await resolveLiveHead(root);
if (!live) {
item.hide();
return;
@@ -202,7 +193,9 @@ export function registerStaleness(ctx: RepowiseContext): vscode.Disposable {
const disposables: vscode.Disposable[] = [
item,
- vscode.commands.registerCommand(Commands.updateIndex, () => void updateIndex()),
+ // Returns the promise so `executeCommand` callers (the sidebar Home view)
+ // resolve when the update actually finishes, not when it starts.
+ vscode.commands.registerCommand(Commands.updateIndex, () => updateIndex()),
ctx.onDidChangeExtensionState((state) => {
if (state === "ready") {
ensureWatcher();
@@ -232,36 +225,6 @@ export function registerStaleness(ctx: RepowiseContext): vscode.Disposable {
};
}
-/** True when two commit ids refer to the same commit (tolerates short shas). */
-function commitsMatch(a: string, b: string): boolean {
- if (a === b) return true;
- const shorter = a.length < b.length ? a : b;
- const longer = a.length < b.length ? b : a;
- return shorter.length > 0 && longer.startsWith(shorter);
-}
-
-/**
- * Reads the checked-out commit from `.git` when the git extension is
- * unavailable. Resolves a symbolic ref to its loose ref file. Packed refs are
- * not read here; that path degrades to null (no false staleness) and the git
- * extension covers it when enabled.
- */
-async function readHeadFromDisk(root: string): Promise<string | null> {
- try {
- const raw = (await readFile(path.join(root, ".git", "HEAD"), "utf8")).trim();
- if (raw.startsWith("ref:")) {
- const ref = raw.slice(4).trim();
- const refPath = path.join(root, ".git", ...ref.split("/"));
- const sha = (await readFile(refPath, "utf8")).trim();
- return sha || null;
- }
- // Detached HEAD: the file holds the commit id directly.
- return raw || null;
- } catch {
- return null;
- }
-}
-
/** Turns a snake_case stage name into a readable progress message. */
function humanize(name: string): string {
const spaced = name.replace(/_/g, " ");
diff --git a/packages/vscode/src/features/trees.ts b/packages/vscode/src/features/trees.ts
index 887af5615..8e55fe167 100644
--- a/packages/vscode/src/features/trees.ts
+++ b/packages/vscode/src/features/trees.ts
@@ -1,23 +1,19 @@
import * as vscode from "vscode";
import type { RepowiseContext } from "../core/context";
-import { registerDeadCodeTree } from "./trees/deadCode";
-import { registerDecisionsTree } from "./trees/decisions";
-import { registerHealthTree } from "./trees/health";
-import { registerHotspotsTree } from "./trees/hotspots";
+import { registerFindingsTree } from "./trees/findings";
import { registerRefactoringTree } from "./trees/refactoring";
/**
- * Instantiates the five activity-bar tree views (Health, Refactoring, Hotspots
- * & Ownership, Dead Code, Decisions) and bundles their disposables into one.
- * Registration is cheap: each provider defers its first fetch until VS Code
- * asks for children, which only happens once the view is visible.
+ * Instantiates the two activity-bar tree views (Findings, Refactoring) and
+ * bundles their disposables into one. Registration is cheap: each provider
+ * defers its first fetch until VS Code asks for children, which only happens
+ * once the view is visible. Decisions live in the Home launcher and the
+ * decisions panel; hotspots, ownership, dead code, and health are sections of
+ * the Findings tree.
*/
export function registerTrees(ctx: RepowiseContext): vscode.Disposable {
return vscode.Disposable.from(
- registerHealthTree(ctx),
+ registerFindingsTree(ctx),
registerRefactoringTree(ctx),
- registerHotspotsTree(ctx),
- registerDeadCodeTree(ctx),
- registerDecisionsTree(ctx),
);
}
diff --git a/packages/vscode/src/features/trees/deadCode.ts b/packages/vscode/src/features/trees/deadCode.ts
index d1275f1fe..fdca5baa3 100644
--- a/packages/vscode/src/features/trees/deadCode.ts
+++ b/packages/vscode/src/features/trees/deadCode.ts
@@ -1,18 +1,14 @@
import * as vscode from "vscode";
-import { getDeadCodeSummary, listDeadCode } from "@repowise-dev/api-client/dead-code";
+import { listDeadCode } from "@repowise-dev/api-client/dead-code";
import type { DeadCodeFindingResponse } from "@repowise-dev/api-client/types";
-import { Views } from "../../constants";
-import type { RepowiseContext } from "../../core/context";
import {
baseName,
- mountView,
openFileCommand,
RepowiseTreeProvider,
type RepoTreeNode,
} from "./shared";
const FINDINGS_KEY = "deadcode:findings";
-const SUMMARY_KEY = "deadcode:summary";
/** Confidence tiers, most-confident first, with their inclusive lower bounds. */
const TIERS: Array<{ key: string; label: string; min: number }> = [
@@ -22,20 +18,19 @@ const TIERS: Array<{ key: string; label: string; min: number }> = [
];
/**
- * Dead Code view: findings grouped into High / Medium / Low confidence tiers.
+ * Dead Code roots: findings grouped into High / Medium / Low confidence tiers.
* Empty tiers are dropped. Findings use `start_line`/`end_line` (distinct from
* the health findings' `line_start`/`line_end`); a click jumps to `start_line`
- * when present. The badge is the summary's total finding count.
+ * when present. Mounted as a section of the Findings composite, which owns the
+ * view badge (failing health files, deliberately not dead-code counts).
*/
-class DeadCodeTreeProvider extends RepowiseTreeProvider {
+export class DeadCodeTreeProvider extends RepowiseTreeProvider {
protected readonly name = "Dead Code";
protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {
const findings = await this.cached(FINDINGS_KEY, () =>
listDeadCode(repoId, { limit: 500 }),
);
- void this.loadBadge(repoId);
-
if (findings.length === 0) return [this.messageNode("No dead code")];
const roots: RepoTreeNode[] = [];
@@ -68,17 +63,6 @@ class DeadCodeTreeProvider extends RepowiseTreeProvider {
command: openFileCommand(this.ctx, row.file_path, row.start_line),
};
}
-
- private async loadBadge(repoId: string): Promise<void> {
- try {
- const summary = await this.cached(SUMMARY_KEY, () =>
- getDeadCodeSummary(repoId),
- );
- this.setBadge(summary.total_findings, `${summary.total_findings} dead-code findings`);
- } catch (err) {
- this.ctx.log.debug(`Dead Code badge load failed: ${String(err)}`);
- }
- }
}
/** Maps a 0-1 confidence to its tier key. */
@@ -88,8 +72,3 @@ function tierOf(confidence: number): string {
}
return "low";
}
-
-/** Registers the Dead Code tree view. */
-export function registerDeadCodeTree(ctx: RepowiseContext): vscode.Disposable {
- return mountView(ctx, Views.deadCode, new DeadCodeTreeProvider(ctx));
-}
diff --git a/packages/vscode/src/features/trees/decisions.ts b/packages/vscode/src/features/trees/decisions.ts
deleted file mode 100644
index f3e03de5b..000000000
--- a/packages/vscode/src/features/trees/decisions.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import * as vscode from "vscode";
-import { listDecisions } from "@repowise-dev/api-client/decisions";
-import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";
-import { Views } from "../../constants";
-import type { RepowiseContext } from "../../core/context";
-import {
- mountView,
- openFileCommand,
- RepowiseTreeProvider,
- truncate,
- type RepoTreeNode,
-} from "./shared";
-
-const DECISIONS_KEY = "decisions:all";
-
-/** Status display order: accepted/active first, retired states last, else A-Z. */
-const STATUS_RANK: Record<string, number> = {
- accepted: 0,
- active: 1,
- proposed: 2,
- deprecated: 4,
- superseded: 5,
-};
-
-/**
- * Decisions view: architectural decision records grouped by status, accepted
- * first. A record with a backing `evidence_file` opens it on click (at
- * `evidence_line`, 1-based, when present); records without evidence are not
- * clickable. No badge.
- */
-class DecisionsTreeProvider extends RepowiseTreeProvider {
- protected readonly name = "Decisions";
-
- protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {
- // Same key and limit as the hover feature's decision lookup, so whichever
- // fetches first serves both.
- const decisions = await this.cached(DECISIONS_KEY, () =>
- listDecisions(repoId, { limit: 500 }),
- );
- if (decisions.length === 0) return [this.messageNode("No decisions")];
-
- const byStatus = new Map<string, DecisionRecordResponse[]>();
- for (const record of decisions) {
- const bucket = byStatus.get(record.status);
- if (bucket) bucket.push(record);
- else byStatus.set(record.status, [record]);
- }
-
- return Array.from(byStatus.keys())
- .sort(compareStatus)
- .map((status) => {
- const rows = byStatus.get(status) ?? [];
- return {
- key: `status:${status}`,
- label: capitalize(status),
- description: `${rows.length}`,
- collapsibleState: vscode.TreeItemCollapsibleState.Expanded,
- children: rows.map((row) => this.decisionNode(row)),
- };
- });
- }
-
- private decisionNode(row: DecisionRecordResponse): RepoTreeNode {
- const tooltip = new vscode.MarkdownString();
- tooltip.appendMarkdown(`**Decision:** ${row.decision}\n\n`);
- tooltip.appendMarkdown(`**Rationale:** ${row.rationale}\n`);
- return {
- key: `decision:${row.id}`,
- label: truncate(row.title),
- description: row.source,
- tooltip,
- icon: new vscode.ThemeIcon("law"),
- collapsibleState: vscode.TreeItemCollapsibleState.None,
- command: row.evidence_file
- ? openFileCommand(this.ctx, row.evidence_file, row.evidence_line)
- : undefined,
- };
- }
-}
-
-/** Orders two status keys by preferred rank, falling back to alphabetical. */
-function compareStatus(a: string, b: string): number {
- const ra = STATUS_RANK[a] ?? 3;
- const rb = STATUS_RANK[b] ?? 3;
- return ra === rb ? a.localeCompare(b) : ra - rb;
-}
-
-/** Upper-cases the first letter for a status label. */
-function capitalize(text: string): string {
- return text.length === 0 ? text : text.charAt(0).toUpperCase() + text.slice(1);
-}
-
-/** Registers the Decisions tree view. */
-export function registerDecisionsTree(ctx: RepowiseContext): vscode.Disposable {
- return mountView(ctx, Views.decisions, new DecisionsTreeProvider(ctx));
-}
diff --git a/packages/vscode/src/features/trees/findings.ts b/packages/vscode/src/features/trees/findings.ts
new file mode 100644
index 000000000..3c50f16ba
--- /dev/null
+++ b/packages/vscode/src/features/trees/findings.ts
@@ -0,0 +1,82 @@
+import * as vscode from "vscode";
+import { Views } from "../../constants";
+import type { RepowiseContext } from "../../core/context";
+import { DeadCodeTreeProvider } from "./deadCode";
+import { HealthTreeProvider } from "./health";
+import { HotspotsTreeProvider } from "./hotspots";
+import { mountView, RepowiseTreeProvider, type RepoTreeNode } from "./shared";
+
+/**
+ * The single Findings view: Health, Hotspots, Ownership, and Dead Code as
+ * sections of one tree instead of four stacked sidebar views, so the sidebar
+ * leads with the Home view rather than a wall of section headers. The section
+ * providers are never mounted; this composite calls their loaders directly and
+ * owns the one root cache, freshness watcher, and badge (failing health files,
+ * the actionable count; dead-code totals would be four-digit badge noise).
+ */
+class FindingsTreeProvider extends RepowiseTreeProvider {
+ protected readonly name = "Findings";
+
+ private readonly health = new HealthTreeProvider(this.ctx);
+ private readonly hotspots = new HotspotsTreeProvider(this.ctx);
+ private readonly deadCode = new DeadCodeTreeProvider(this.ctx);
+ private readonly badgeSub: vscode.Disposable;
+
+ constructor(ctx: RepowiseContext) {
+ super(ctx);
+ // The health loader computes the failing-file count as its badge; re-fire
+ // it as this view's badge since the health provider itself is unmounted.
+ this.badgeSub = this.health.onDidChangeBadge((badge) => {
+ if (badge) this.setBadge(badge.value, badge.tooltip ?? "");
+ else this.setBadge(0, "");
+ });
+ }
+
+ protected loadRoots(repoId: string): Promise<RepoTreeNode[]> {
+ return Promise.resolve([
+ this.category("health", "Health", "pulse", true, () =>
+ this.health.rootsFor(repoId),
+ ),
+ this.category("hotspots", "Hotspots", "flame", false, () =>
+ this.hotspots.loadHotspots(),
+ ),
+ this.category("ownership", "Ownership", "organization", false, () =>
+ this.hotspots.loadOwnership(),
+ ),
+ this.category("deadcode", "Dead Code", "trash", false, () =>
+ this.deadCode.rootsFor(repoId),
+ ),
+ ]);
+ }
+
+ private category(
+ key: string,
+ label: string,
+ icon: string,
+ expanded: boolean,
+ loader: () => Promise<RepoTreeNode[]>,
+ ): RepoTreeNode {
+ return {
+ key: `cat:${key}`,
+ label,
+ icon: new vscode.ThemeIcon(icon),
+ collapsibleState: expanded
+ ? vscode.TreeItemCollapsibleState.Expanded
+ : vscode.TreeItemCollapsibleState.Collapsed,
+ loadChildren: loader,
+ };
+ }
+
+ override dispose(): void {
+ this.badgeSub.dispose();
+ this.health.dispose();
+ this.hotspots.dispose();
+ this.deadCode.dispose();
+ super.dispose();
+ }
+}
+
+/** Registers the consolidated Findings tree view. */
+export function registerFindingsTree(ctx: RepowiseContext): vscode.Disposable {
+ return mountView(ctx, Views.findings, new FindingsTreeProvider(ctx));
+}
diff --git a/packages/vscode/src/features/trees/health.ts b/packages/vscode/src/features/trees/health.ts
index e7130bca6..87e538899 100644
--- a/packages/vscode/src/features/trees/health.ts
+++ b/packages/vscode/src/features/trees/health.ts
@@ -1,11 +1,8 @@
import * as vscode from "vscode";
import { listHealthFiles } from "@repowise-dev/api-client/code-health";
import type { HealthFileMetric } from "@repowise-dev/api-client/code-health";
-import { Views } from "../../constants";
-import type { RepowiseContext } from "../../core/context";
import {
baseName,
- mountView,
openFileCommand,
RepowiseTreeProvider,
type RepoTreeNode,
@@ -27,7 +24,7 @@ function score(value: number | null | undefined): string {
* order yields both worst-first files and worst-first modules for free. The
* badge counts failing files (a separate one-row query for its `total`).
*/
-class HealthTreeProvider extends RepowiseTreeProvider {
+export class HealthTreeProvider extends RepowiseTreeProvider {
protected readonly name = "Health";
protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {
@@ -82,8 +79,3 @@ class HealthTreeProvider extends RepowiseTreeProvider {
}
}
}
-
-/** Registers the Health tree view. */
-export function registerHealthTree(ctx: RepowiseContext): vscode.Disposable {
- return mountView(ctx, Views.health, new HealthTreeProvider(ctx));
-}
diff --git a/packages/vscode/src/features/trees/hotspots.ts b/packages/vscode/src/features/trees/hotspots.ts
index 9da2d65bf..536e6baaf 100644
--- a/packages/vscode/src/features/trees/hotspots.ts
+++ b/packages/vscode/src/features/trees/hotspots.ts
@@ -4,11 +4,8 @@ import type {
HotspotResponse,
OwnershipEntry,
} from "@repowise-dev/api-client/types";
-import { Views } from "../../constants";
-import type { RepowiseContext } from "../../core/context";
import {
baseName,
- mountView,
openFileCommand,
RepowiseTreeProvider,
type RepoTreeNode,
@@ -23,7 +20,7 @@ const OWNERSHIP_KEY = "ownership:page";
* shown). Hotspots are the highest-churn files; Ownership rolls up who owns
* each module and flags single-owner silos.
*/
-class HotspotsTreeProvider extends RepowiseTreeProvider {
+export class HotspotsTreeProvider extends RepowiseTreeProvider {
protected readonly name = "Hotspots";
protected loadRoots(): Promise<RepoTreeNode[]> {
@@ -33,7 +30,8 @@ class HotspotsTreeProvider extends RepowiseTreeProvider {
]);
}
- private async loadHotspots(): Promise<RepoTreeNode[]> {
+ /** Public: the Findings composite mounts these as its own sections. */
+ async loadHotspots(): Promise<RepoTreeNode[]> {
const repoId = this.ctx.repoId;
if (!repoId) return [];
const page = await this.cached(HOTSPOTS_KEY, () =>
@@ -61,7 +59,7 @@ class HotspotsTreeProvider extends RepowiseTreeProvider {
};
}
- private async loadOwnership(): Promise<RepoTreeNode[]> {
+ async loadOwnership(): Promise<RepoTreeNode[]> {
const repoId = this.ctx.repoId;
if (!repoId) return [];
const page = await this.cached(OWNERSHIP_KEY, () =>
@@ -89,8 +87,3 @@ class HotspotsTreeProvider extends RepowiseTreeProvider {
};
}
}
-
-/** Registers the Hotspots & Ownership tree view. */
-export function registerHotspotsTree(ctx: RepowiseContext): vscode.Disposable {
- return mountView(ctx, Views.hotspots, new HotspotsTreeProvider(ctx));
-}
diff --git a/packages/vscode/src/features/trees/shared.ts b/packages/vscode/src/features/trees/shared.ts
index e72b67af9..d70332442 100644
--- a/packages/vscode/src/features/trees/shared.ts
+++ b/packages/vscode/src/features/trees/shared.ts
@@ -52,6 +52,15 @@ export abstract class RepowiseTreeProvider
/** Builds the root nodes for a resolved repo. Throws are caught upstream. */
protected abstract loadRoots(repoId: string): Promise<RepoTreeNode[]>;
+ /**
+ * Public window onto `loadRoots` for composite providers that nest this
+ * provider's roots under a section of their own tree. Bypasses this
+ * provider's root cache and watcher on purpose: the composite owns both.
+ */
+ rootsFor(repoId: string): Promise<RepoTreeNode[]> {
+ return this.loadRoots(repoId);
+ }
+
getTreeItem(node: RepoTreeNode): vscode.TreeItem {
const item = new vscode.TreeItem(node.label, node.collapsibleState);
if (node.description !== undefined) item.description = node.description;
diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.ts
index cf70fee4b..b3fbbfb25 100644
--- a/packages/vscode/src/shared/webviewMessages.ts
+++ b/packages/vscode/src/shared/webviewMessages.ts
@@ -33,8 +33,8 @@ import type { ArchitectureView } from "@repowise-dev/ui/c4";
import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring/types";
import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
-/** Every webview panel the extension can open. */
-export type WebviewViewId =
+/** Every editor-tab webview panel the extension can open. */
+export type PanelViewId =
| "health"
| "architecture"
| "graph"
@@ -43,6 +43,9 @@ export type WebviewViewId =
| "docs"
| "risk";
+/** Panels plus the sidebar Home view (a WebviewView, never a tab). */
+export type WebviewViewId = PanelViewId | "home";
+
/** Per-view open parameters, carried in the init message. */
export interface ViewParams {
health: Record<string, never>;
@@ -52,8 +55,16 @@ export interface ViewParams {
decisions: Record<string, never>;
docs: { pageId?: string; filePath?: string };
risk: Record<string, never>;
+ home: Record<string, never>;
}
+/**
+ * Webview color scheme. "auto" follows the editor theme; a fixed value pins
+ * every Repowise webview regardless of the editor. Persisted host-side so all
+ * views (and future opens) agree.
+ */
+export type ThemePreference = "auto" | "light" | "dark";
+
/** Repo facts the webview needs for labels and cache-busting. */
export interface RepoInit {
id: string;
@@ -98,6 +109,41 @@ export interface HostApi {
fileDetail(relPath: string): Promise<FileDetailResponse>;
// Branch risk
riskRange(): Promise<RiskRangeReport>;
+ // Sidebar home
+ homeSummary(): Promise<HomeSummary>;
+}
+
+/**
+ * The sidebar Home payload, aggregated host-side so one RPC serves the whole
+ * view and only compact numbers cross the postMessage boundary. Sections are
+ * independently nullable: one failing endpoint degrades its card, not the view.
+ */
+export interface HomeSummary {
+ health: {
+ /** Headline: NLOC-weighted health of the hotspot files. */
+ hotspot: number | null;
+ average: number | null;
+ fileCount: number;
+ openFindings: number;
+ band: string | null;
+ hotspotDelta: number | null;
+ /** Hotspot-health history, oldest first, for the hero sparkline. */
+ history: number[];
+ } | null;
+ counts: {
+ refactoringPlans: number | null;
+ decisions: number | null;
+ };
+ freshness: {
+ /** Commit the index was built from (null when the server has none). */
+ indexedCommit: string | null;
+ /** Checked-out commit, or null when git cannot serve it. */
+ liveCommit: string | null;
+ /** True only when both commits are known and differ. */
+ stale: boolean;
+ branch: string | null;
+ lastIndexedAt: string | null;
+ };
}
/** Branch risk payload: the endpoint response plus the refs it compared. */
@@ -143,6 +189,7 @@ export interface InitMessage<V extends WebviewViewId = WebviewViewId> {
view: V;
repo: RepoInit;
params: ViewParams[V];
+ theme: ThemePreference;
}
/**
@@ -177,11 +224,51 @@ export interface OpenExternalMessage {
url: string;
}
+/** Webview -> host: open (or reveal) an editor-tab panel. Sent by Home. */
+export interface OpenViewMessage {
+ kind: "open-view";
+ view: PanelViewId;
+ params?: ViewParams[PanelViewId];
+}
+
+/** Webview -> host: run an incremental index update. Sent by Home. */
+export interface UpdateIndexMessage {
+ kind: "update-index";
+}
+
+/** Webview -> host: persist a theme preference. Sent by Home's switcher. */
+export interface SetThemeMessage {
+ kind: "set-theme";
+ theme: ThemePreference;
+}
+
+/** Host -> webview: the theme preference changed; every open view applies it. */
+export interface ThemeChangedMessage {
+ kind: "theme-changed";
+ theme: ThemePreference;
+}
+
+/**
+ * Host -> webview: the requested index update finished (either way). The view
+ * refetches its summary; a successful update also arrives as a refresh.
+ */
+export interface UpdateDoneMessage {
+ kind: "update-done";
+}
+
export type WebviewToHostMessage =
| ReadyMessage
| RpcRequestMessage
| OpenFileMessage
| CopyTextMessage
- | OpenExternalMessage;
+ | OpenExternalMessage
+ | OpenViewMessage
+ | UpdateIndexMessage
+ | SetThemeMessage;
-export type HostToWebviewMessage = InitMessage | RefreshMessage | RpcResponseMessage;
+export type HostToWebviewMessage =
+ | InitMessage
+ | RefreshMessage
+ | RpcResponseMessage
+ | UpdateDoneMessage
+ | ThemeChangedMessage;
diff --git a/packages/vscode/webview/src/assets/owl-dark-theme.png b/packages/vscode/webview/src/assets/owl-dark-theme.png
new file mode 100644
index 000000000..366c1784a
Binary files /dev/null and b/packages/vscode/webview/src/assets/owl-dark-theme.png differ
diff --git a/packages/vscode/webview/src/assets/owl-light-theme.png b/packages/vscode/webview/src/assets/owl-light-theme.png
new file mode 100644
index 000000000..868100dbe
Binary files /dev/null and b/packages/vscode/webview/src/assets/owl-light-theme.png differ
diff --git a/packages/vscode/webview/src/runtime/mount.tsx b/packages/vscode/webview/src/runtime/mount.tsx
index aa314e890..f8d06e476 100644
--- a/packages/vscode/webview/src/runtime/mount.tsx
+++ b/packages/vscode/webview/src/runtime/mount.tsx
@@ -13,7 +13,7 @@ import type {
WebviewViewId,
} from "../../../src/shared/webviewMessages";
import { createHost, type WebviewHost } from "./rpc";
-import { initTheme } from "./theme";
+import { initTheme, setThemePreference } from "./theme";
/** Everything a view component receives. */
export interface ViewProps<V extends WebviewViewId> {
@@ -30,6 +30,10 @@ export function mountView<V extends WebviewViewId>(
): void {
initTheme();
const host = createHost();
+ // Registered before render so the persisted preference is applied by the
+ // time the view component first mounts (init subscribers fire in order).
+ host.onInit((msg) => setThemePreference(msg.theme ?? "auto"));
+ host.onThemeChanged((theme) => setThemePreference(theme));
const container = document.getElementById("root");
if (!container) throw new Error("Webview root element missing");
createRoot(container).render(
diff --git a/packages/vscode/webview/src/runtime/rpc.test.ts b/packages/vscode/webview/src/runtime/rpc.test.ts
index e1c9d2612..37f880335 100644
--- a/packages/vscode/webview/src/runtime/rpc.test.ts
+++ b/packages/vscode/webview/src/runtime/rpc.test.ts
@@ -16,6 +16,7 @@ const INIT: InitMessage = {
view: "health",
repo: { id: "r1", name: "repo", headCommit: "abc", defaultBranch: "main" },
params: {},
+ theme: "auto",
};
function postToWebview(msg: HostToWebviewMessage): void {
@@ -95,6 +96,31 @@ describe("webview rpc round trip", () => {
expect(received).toContainEqual({ kind: "open-external", url: "https://example.com" });
});
+ it("routes home-view services and delivers update-done", async () => {
+ const received = installHost();
+ const { createHost } = await import("./rpc");
+ const host = createHost();
+
+ host.openView("health");
+ host.openView("refactoring", { planId: "p1" });
+ host.updateIndex();
+ host.setTheme("dark");
+ expect(received).toContainEqual({ kind: "open-view", view: "health", params: undefined });
+ expect(received).toContainEqual({ kind: "open-view", view: "refactoring", params: { planId: "p1" } });
+ expect(received).toContainEqual({ kind: "update-index" });
+ expect(received).toContainEqual({ kind: "set-theme", theme: "dark" });
+
+ const done = vi.fn();
+ host.onUpdateDone(done);
+ postToWebview({ kind: "update-done" });
+ expect(done).toHaveBeenCalledTimes(1);
+
+ const themed = vi.fn();
+ host.onThemeChanged(themed);
+ postToWebview({ kind: "theme-changed", theme: "light" });
+ expect(themed).toHaveBeenCalledWith("light");
+ });
+
it("ignores garbage messages without breaking pending calls", async () => {
installHost();
const { createHost } = await import("./rpc");
diff --git a/packages/vscode/webview/src/runtime/rpc.ts b/packages/vscode/webview/src/runtime/rpc.ts
index 842ddef15..19f12c3ff 100644
--- a/packages/vscode/webview/src/runtime/rpc.ts
+++ b/packages/vscode/webview/src/runtime/rpc.ts
@@ -9,7 +9,10 @@ import type {
HostApiMethod,
HostToWebviewMessage,
InitMessage,
+ PanelViewId,
RefreshMessage,
+ ThemePreference,
+ ViewParams,
} from "../../../src/shared/webviewMessages";
import { getVsCodeApi } from "./vscodeApi";
@@ -20,11 +23,21 @@ export interface WebviewHost {
onInit(cb: (msg: InitMessage) => void): () => void;
/** Fires when the index moved and the view should refetch. */
onRefresh(cb: (msg: RefreshMessage) => void): () => void;
+ /** Fires when a requested index update finished (success or failure). */
+ onUpdateDone(cb: () => void): () => void;
+ /** Fires when the persisted theme preference changed (any view's switcher). */
+ onThemeChanged(cb: (theme: ThemePreference) => void): () => void;
/** Tell the host we are listening; it answers with init. */
ready(): void;
openFile(path: string, line?: number): void;
copyText(text: string, toast?: string): void;
openExternal(url: string): void;
+ /** Open (or reveal) an editor-tab panel. Used by the sidebar Home view. */
+ openView<V extends PanelViewId>(view: V, params?: ViewParams[V]): void;
+ /** Run an incremental index update; completion arrives via onUpdateDone. */
+ updateIndex(): void;
+ /** Persist a theme preference; every open view gets onThemeChanged. */
+ setTheme(theme: ThemePreference): void;
}
interface Pending {
@@ -37,6 +50,8 @@ export function createHost(): WebviewHost {
const pending = new Map<number, Pending>();
const initSubs = new Set<(msg: InitMessage) => void>();
const refreshSubs = new Set<(msg: RefreshMessage) => void>();
+ const updateDoneSubs = new Set<() => void>();
+ const themeSubs = new Set<(theme: ThemePreference) => void>();
// Buffered so a subscriber attaching after the host already replied to
// ready() (possible if React yields before the effect commits) still gets it.
let lastInit: InitMessage | null = null;
@@ -61,6 +76,12 @@ export function createHost(): WebviewHost {
case "refresh":
for (const cb of refreshSubs) cb(msg);
return;
+ case "update-done":
+ for (const cb of updateDoneSubs) cb();
+ return;
+ case "theme-changed":
+ for (const cb of themeSubs) cb(msg.theme);
+ return;
}
});
@@ -91,9 +112,20 @@ export function createHost(): WebviewHost {
refreshSubs.add(cb);
return () => refreshSubs.delete(cb);
},
+ onUpdateDone(cb) {
+ updateDoneSubs.add(cb);
+ return () => updateDoneSubs.delete(cb);
+ },
+ onThemeChanged(cb) {
+ themeSubs.add(cb);
+ return () => themeSubs.delete(cb);
+ },
ready: () => vscode.postMessage({ kind: "ready" }),
openFile: (path, line) => vscode.postMessage({ kind: "open-file", path, line }),
copyText: (text, toast) => vscode.postMessage({ kind: "copy-text", text, toast }),
openExternal: (url) => vscode.postMessage({ kind: "open-external", url }),
+ openView: (view, params) => vscode.postMessage({ kind: "open-view", view, params }),
+ updateIndex: () => vscode.postMessage({ kind: "update-index" }),
+ setTheme: (theme) => vscode.postMessage({ kind: "set-theme", theme }),
};
}
diff --git a/packages/vscode/webview/src/runtime/theme.ts b/packages/vscode/webview/src/runtime/theme.ts
index 55f57e2ec..8f4dad81e 100644
--- a/packages/vscode/webview/src/runtime/theme.ts
+++ b/packages/vscode/webview/src/runtime/theme.ts
@@ -7,11 +7,15 @@
* (the next-themes shim, canvas renderers).
*/
+import type { ThemePreference } from "../../../src/shared/webviewMessages";
+
export type ThemeKind = "light" | "dark";
const subscribers = new Set<(kind: ThemeKind) => void>();
let current: ThemeKind = "light";
let started = false;
+/** Pinned scheme from the Home switcher; "auto" follows the editor. */
+let preference: ThemePreference = "auto";
function compute(): ThemeKind {
const cls = document.body.classList;
@@ -30,15 +34,33 @@ function apply(kind: ThemeKind): void {
for (const cb of subscribers) cb(kind);
}
+/** The effective kind under the current preference. */
+function resolve(): ThemeKind {
+ return preference === "auto" ? compute() : preference;
+}
+
/** Idempotent; called by the mount helper before first render. */
export function initTheme(): void {
if (started) return;
started = true;
- apply(compute());
- const observer = new MutationObserver(() => apply(compute()));
+ apply(resolve());
+ const observer = new MutationObserver(() => apply(resolve()));
observer.observe(document.body, { attributes: true, attributeFilter: ["class"] });
}
+/**
+ * Applies the persisted preference pushed by the host (init and theme-changed
+ * messages). A pinned value wins over the editor theme until set back to auto.
+ */
+export function setThemePreference(pref: ThemePreference): void {
+ preference = pref;
+ apply(resolve());
+}
+
+export function getThemePreference(): ThemePreference {
+ return preference;
+}
+
export function getThemeKind(): ThemeKind {
return current;
}
diff --git a/packages/vscode/webview/src/views/architecture/App.test.tsx b/packages/vscode/webview/src/views/architecture/App.test.tsx
index 8c0e71a1d..aa8bc7309 100644
--- a/packages/vscode/webview/src/views/architecture/App.test.tsx
+++ b/packages/vscode/webview/src/views/architecture/App.test.tsx
@@ -90,10 +90,15 @@ function makeHost(overrides: Partial<WebviewHost["api"]> = {}): WebviewHost {
api,
onInit: () => () => {},
onRefresh: () => () => {},
+ onUpdateDone: () => () => {},
+ onThemeChanged: () => () => {},
ready: () => {},
openFile: vi.fn(),
copyText: vi.fn(),
openExternal: vi.fn(),
+ openView: vi.fn(),
+ updateIndex: vi.fn(),
+ setTheme: vi.fn(),
};
}
diff --git a/packages/vscode/webview/src/views/decisions/App.test.tsx b/packages/vscode/webview/src/views/decisions/App.test.tsx
index 3f05a1c19..d0afada3c 100644
--- a/packages/vscode/webview/src/views/decisions/App.test.tsx
+++ b/packages/vscode/webview/src/views/decisions/App.test.tsx
@@ -45,10 +45,15 @@ function makeHost(list: DecisionRecordResponse[]): WebviewHost {
api: { decisionsList: vi.fn().mockResolvedValue(list) } as unknown as WebviewHost["api"],
onInit: () => () => {},
onRefresh: () => () => {},
+ onUpdateDone: () => () => {},
+ onThemeChanged: () => () => {},
ready: () => {},
openFile: () => {},
copyText: () => {},
openExternal: () => {},
+ openView: () => {},
+ updateIndex: () => {},
+ setTheme: () => {},
};
}
diff --git a/packages/vscode/webview/src/views/docs/App.test.tsx b/packages/vscode/webview/src/views/docs/App.test.tsx
index a0d631bbe..14b5af04f 100644
--- a/packages/vscode/webview/src/views/docs/App.test.tsx
+++ b/packages/vscode/webview/src/views/docs/App.test.tsx
@@ -73,10 +73,15 @@ function mockHost(pages: DocPage[]): WebviewHost {
} as unknown as WebviewHost["api"],
onInit: () => () => {},
onRefresh: () => () => {},
+ onUpdateDone: () => () => {},
+ onThemeChanged: () => () => {},
ready: () => {},
openFile: vi.fn(),
copyText: vi.fn(),
openExternal: vi.fn(),
+ openView: vi.fn(),
+ updateIndex: vi.fn(),
+ setTheme: vi.fn(),
};
}
diff --git a/packages/vscode/webview/src/views/graph/App.test.tsx b/packages/vscode/webview/src/views/graph/App.test.tsx
index b02501a6a..a0c22ffd1 100644
--- a/packages/vscode/webview/src/views/graph/App.test.tsx
+++ b/packages/vscode/webview/src/views/graph/App.test.tsx
@@ -25,10 +25,15 @@ function mockHost(): { host: WebviewHost; api: Record<string, ReturnType<typeof
api: api as unknown as WebviewHost["api"],
onInit: () => () => {},
onRefresh: () => () => {},
+ onUpdateDone: () => () => {},
+ onThemeChanged: () => () => {},
ready: () => {},
openFile: vi.fn(),
copyText: vi.fn(),
openExternal: vi.fn(),
+ openView: vi.fn(),
+ updateIndex: vi.fn(),
+ setTheme: vi.fn(),
} satisfies WebviewHost;
return { host, api };
}
diff --git a/packages/vscode/webview/src/views/home/App.test.tsx b/packages/vscode/webview/src/views/home/App.test.tsx
new file mode 100644
index 000000000..cf7d062b7
--- /dev/null
+++ b/packages/vscode/webview/src/views/home/App.test.tsx
@@ -0,0 +1,143 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import type { HomeSummary } from "../../../../src/shared/webviewMessages";
+import type { WebviewHost } from "../../runtime/rpc";
+import { App } from "./App";
+
+const SUMMARY: HomeSummary = {
+ health: {
+ hotspot: 5.1,
+ average: 7.4,
+ fileCount: 1280,
+ openFindings: 42,
+ band: "warning",
+ hotspotDelta: 0.3,
+ history: [4.8, 4.9, 5.0, 5.1],
+ },
+ counts: { refactoringPlans: 12, decisions: 48 },
+ freshness: {
+ indexedCommit: "abc1234deadbeef",
+ liveCommit: "abc1234deadbeef",
+ stale: false,
+ branch: "main",
+ lastIndexedAt: "2026-07-01T10:00:00Z",
+ },
+};
+
+function makeHost(summary: HomeSummary = SUMMARY) {
+ const openView = vi.fn();
+ const updateIndex = vi.fn();
+ const setTheme = vi.fn();
+ let fireUpdateDone: () => void = () => {};
+ const host = {
+ api: { homeSummary: vi.fn(() => Promise.resolve(summary)) },
+ openView,
+ updateIndex,
+ setTheme,
+ onUpdateDone: (cb: () => void) => {
+ fireUpdateDone = cb;
+ return () => {};
+ },
+ onThemeChanged: () => () => {},
+ } as unknown as WebviewHost;
+ return { host, openView, updateIndex, setTheme, fireUpdateDone: () => fireUpdateDone() };
+}
+
+function renderApp(host: WebviewHost) {
+ return render(
+ <App
+ host={host}
+ repo={{ id: "r1", name: "demo-repo", headCommit: "abc1234", defaultBranch: "main" }}
+ params={{}}
+ refreshToken={0}
+ />,
+ );
+}
+
+afterEach(cleanup);
+
+describe("Home sidebar", () => {
+ it("renders the hero score, freshness, and live card stats", async () => {
+ const { host } = makeHost();
+ renderApp(host);
+
+ expect(await screen.findByText("5.1")).toBeTruthy();
+ expect(screen.getByText("demo-repo")).toBeTruthy();
+ expect(screen.getByText("Index up to date")).toBeTruthy();
+ expect(screen.getByText("12 ranked plans")).toBeTruthy();
+ expect(screen.getByText("48 decision records")).toBeTruthy();
+ expect(screen.getByText(/42 open findings/)).toBeTruthy();
+ });
+
+ it("opens the matching panel when a launcher card is clicked", async () => {
+ const { host, openView } = makeHost();
+ renderApp(host);
+
+ fireEvent.click(await screen.findByText("Health Dashboard"));
+ expect(openView).toHaveBeenCalledWith("health");
+
+ fireEvent.click(screen.getByText("Branch Risk"));
+ expect(openView).toHaveBeenCalledWith("risk");
+ });
+
+ it("flags a stale index and runs the update through the host", async () => {
+ const { host, updateIndex, fireUpdateDone } = makeHost({
+ ...SUMMARY,
+ freshness: { ...SUMMARY.freshness, liveCommit: "fff9999aaaa", stale: true },
+ });
+ renderApp(host);
+
+ expect(await screen.findByText("Index behind checkout")).toBeTruthy();
+ expect(screen.getByText("abc1234 → fff9999")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: /Update/ }));
+ expect(updateIndex).toHaveBeenCalledTimes(1);
+ expect(screen.getByText("Updating index…")).toBeTruthy();
+
+ // The host ack clears the spinner and refetches the summary.
+ fireUpdateDone();
+ expect(await screen.findByText(/Index/)).toBeTruthy();
+ expect((host.api.homeSummary as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(1);
+ });
+
+ it("falls back to the average score when hotspot scoring is gated off", async () => {
+ const { host } = makeHost({
+ ...SUMMARY,
+ health: { ...SUMMARY.health!, hotspot: null, hotspotDelta: null },
+ });
+ renderApp(host);
+
+ expect(await screen.findByText("7.4")).toBeTruthy();
+ expect(screen.getByText(/Average health/)).toBeTruthy();
+ });
+
+ it("pins the theme through the host and applies it locally", async () => {
+ const { host, setTheme } = makeHost();
+ renderApp(host);
+ await screen.findByText("5.1");
+
+ fireEvent.click(screen.getByTitle("Dark"));
+ expect(setTheme).toHaveBeenCalledWith("dark");
+ expect(document.documentElement.classList.contains("dark")).toBe(true);
+
+ fireEvent.click(screen.getByTitle("Light"));
+ expect(setTheme).toHaveBeenCalledWith("light");
+ expect(document.documentElement.classList.contains("dark")).toBe(false);
+ });
+
+ it("keeps the launcher usable when the summary fails", async () => {
+ const host = {
+ api: { homeSummary: () => Promise.reject(new Error("down")) },
+ openView: vi.fn(),
+ updateIndex: vi.fn(),
+ setTheme: vi.fn(),
+ onUpdateDone: () => () => {},
+ onThemeChanged: () => () => {},
+ } as unknown as WebviewHost;
+ renderApp(host);
+
+ expect(await screen.findByText("Knowledge Graph")).toBeTruthy();
+ expect(screen.getByText("Server-ranked refactoring opportunities")).toBeTruthy();
+ expect(screen.getByText(/No health data yet/)).toBeTruthy();
+ });
+});
diff --git a/packages/vscode/webview/src/views/home/App.tsx b/packages/vscode/webview/src/views/home/App.tsx
new file mode 100644
index 000000000..7ab3a1678
--- /dev/null
+++ b/packages/vscode/webview/src/views/home/App.tsx
@@ -0,0 +1,457 @@
+/**
+ * Sidebar Home: the face of the extension. A hero card with the repo's
+ * hotspot-health score and trend, an index-freshness row with a one-click
+ * update, and a launcher card per dashboard panel so everything the extension
+ * can show is discoverable from the first click on the activity-bar icon.
+ * Designed for the sidebar's ~300px width; the dashboards themselves open as
+ * editor tabs via `host.openView`.
+ */
+
+import { useCallback, useEffect, useState, type ComponentType } from "react";
+import {
+ Activity,
+ BookOpen,
+ ChevronRight,
+ GitBranch,
+ Layers,
+ Monitor,
+ Moon,
+ RefreshCw,
+ Scale,
+ Share2,
+ Sun,
+ Wrench,
+} from "lucide-react";
+import type {
+ HomeSummary,
+ PanelViewId,
+ ThemePreference,
+} from "../../../../src/shared/webviewMessages";
+import type { ViewProps } from "../../runtime/mount";
+import type { WebviewHost } from "../../runtime/rpc";
+import {
+ getThemeKind,
+ getThemePreference,
+ setThemePreference,
+ subscribeTheme,
+ type ThemeKind,
+} from "../../runtime/theme";
+import owlDarkTheme from "../../assets/owl-dark-theme.png";
+import owlLightTheme from "../../assets/owl-light-theme.png";
+
+/** 0-10 score to its signal color; the same bands the risk view uses, inverted. */
+function scoreColor(score: number | null): string {
+ if (score == null) return "var(--color-text-tertiary)";
+ if (score >= 7.5) return "var(--color-success)";
+ if (score >= 5) return "var(--color-warning)";
+ return "var(--color-error)";
+}
+
+/** Compact relative time for the freshness row ("3h ago"). */
+function timeAgo(iso: string): string {
+ const then = Date.parse(iso);
+ if (Number.isNaN(then)) return "";
+ const minutes = Math.floor((Date.now() - then) / 60_000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ return days < 30 ? `${days}d ago` : new Date(then).toLocaleDateString();
+}
+
+function short(commit: string | null): string | null {
+ return commit ? commit.slice(0, 7) : null;
+}
+
+interface CardSpec {
+ view: PanelViewId;
+ title: string;
+ icon: ComponentType<{ className?: string }>;
+ /** Live micro-stat when the summary carries one, otherwise a static hook. */
+ subtitle: (summary: HomeSummary | null, defaultBranch: string | null) => string;
+}
+
+const CARDS: CardSpec[] = [
+ {
+ view: "health",
+ title: "Health Dashboard",
+ icon: Activity,
+ subtitle: (s) =>
+ s?.health
+ ? `${s.health.openFindings.toLocaleString()} open findings · ${s.health.fileCount.toLocaleString()} files`
+ : "Score map, trends, and the churn quadrant",
+ },
+ {
+ view: "architecture",
+ title: "Architecture Map",
+ icon: Layers,
+ subtitle: () => "Modules and layers on one canvas",
+ },
+ {
+ view: "graph",
+ title: "Knowledge Graph",
+ icon: Share2,
+ subtitle: () => "Dependencies, communities, execution flows",
+ },
+ {
+ view: "refactoring",
+ title: "Refactoring Plans",
+ icon: Wrench,
+ subtitle: (s) =>
+ s?.counts.refactoringPlans != null
+ ? `${s.counts.refactoringPlans.toLocaleString()} ranked plans`
+ : "Server-ranked refactoring opportunities",
+ },
+ {
+ view: "decisions",
+ title: "Decision Timeline",
+ icon: Scale,
+ subtitle: (s) =>
+ s?.counts.decisions != null
+ ? `${s.counts.decisions.toLocaleString()} decision records`
+ : "Architectural decision records",
+ },
+ {
+ view: "docs",
+ title: "Docs",
+ icon: BookOpen,
+ subtitle: () => "Browse the generated wiki",
+ },
+ {
+ view: "risk",
+ title: "Branch Risk",
+ icon: GitBranch,
+ subtitle: (_s, defaultBranch) => `Score this branch against ${defaultBranch ?? "main"}`,
+ },
+];
+
+export function App({ host, repo, refreshToken }: ViewProps<"home">) {
+ const [summary, setSummary] = useState<HomeSummary | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [updating, setUpdating] = useState(false);
+
+ const load = useCallback(() => {
+ setLoading(true);
+ host.api
+ .homeSummary()
+ .then((s) => {
+ setSummary(s);
+ setLoading(false);
+ })
+ .catch(() => {
+ // The launcher stays useful without stats; sections degrade to their
+ // static subtitles and the hero shows its empty state.
+ setSummary(null);
+ setLoading(false);
+ });
+ }, [host]);
+
+ useEffect(() => {
+ load();
+ }, [load, refreshToken]);
+
+ // The host acks update completion whether it succeeded or failed; a success
+ // also lands as a refresh, so this reload mostly re-reads the fresh cache.
+ useEffect(
+ () =>
+ host.onUpdateDone(() => {
+ setUpdating(false);
+ load();
+ }),
+ [host, load],
+ );
+
+ const runUpdate = () => {
+ if (updating) return;
+ setUpdating(true);
+ host.updateIndex();
+ };
+
+ return (
+ <div className="min-h-screen space-y-3 bg-[var(--color-bg-root)] p-3">
+ <Hero
+ repoName={repo.name}
+ branch={summary?.freshness.branch ?? null}
+ health={summary?.health ?? null}
+ loading={loading && !summary}
+ />
+ <Freshness
+ freshness={summary?.freshness ?? null}
+ updating={updating}
+ onUpdate={runUpdate}
+ />
+ <nav aria-label="Dashboards" className="space-y-1.5">
+ <p className="px-1 pt-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Explore
+ </p>
+ {CARDS.map((card) => (
+ <LauncherCard
+ key={card.view}
+ spec={card}
+ subtitle={card.subtitle(summary, repo.defaultBranch)}
+ onOpen={() => host.openView(card.view)}
+ />
+ ))}
+ </nav>
+ <Footer host={host} />
+ </div>
+ );
+}
+
+/** Brand mark plus the theme switcher. The preference applies to every
+ * Repowise webview and persists via the host; "auto" follows the editor. */
+function Footer({ host }: { host: WebviewHost }) {
+ const [pref, setPref] = useState<ThemePreference>(getThemePreference());
+ const [kind, setKind] = useState<ThemeKind>(getThemeKind());
+ useEffect(() => subscribeTheme(setKind), []);
+
+ const choose = (next: ThemePreference) => {
+ setPref(next);
+ // Applied locally for instant feedback; the host persists it and pushes
+ // theme-changed to every other open Repowise view.
+ setThemePreference(next);
+ host.setTheme(next);
+ };
+
+ const options: { value: ThemePreference; icon: ComponentType<{ className?: string }>; label: string }[] = [
+ { value: "auto", icon: Monitor, label: "Follow editor theme" },
+ { value: "light", icon: Sun, label: "Light" },
+ { value: "dark", icon: Moon, label: "Dark" },
+ ];
+
+ return (
+ <footer className="flex items-center justify-between px-1 pb-1 pt-2">
+ <span className="flex items-center gap-1.5">
+ <img
+ src={kind === "dark" ? owlDarkTheme : owlLightTheme}
+ alt=""
+ className="h-4 w-4"
+ />
+ <span className="text-[11px] font-semibold tracking-wide text-[var(--color-text-tertiary)]">
+ Repowise
+ </span>
+ </span>
+ <div
+ role="group"
+ aria-label="Theme"
+ className="inline-flex rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-0.5"
+ >
+ {options.map(({ value, icon: Icon, label }) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() => choose(value)}
+ aria-pressed={pref === value}
+ title={label}
+ className={
+ pref === value
+ ? "rounded-md bg-[var(--color-accent-primary)] p-1 text-[var(--color-text-on-accent)]"
+ : "rounded-md p-1 text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-text-primary)]"
+ }
+ >
+ <Icon className="h-3 w-3" />
+ </button>
+ ))}
+ </div>
+ </footer>
+ );
+}
+
+function Hero({
+ repoName,
+ branch,
+ health,
+ loading,
+}: {
+ repoName: string;
+ branch: string | null;
+ health: HomeSummary["health"];
+ loading: boolean;
+}) {
+ // Quiet or small repos can gate hotspot scoring off; the hero then falls
+ // back to the repo average rather than claiming there is no health data.
+ const usingHotspot = health?.hotspot != null;
+ const headline = health?.hotspot ?? health?.average ?? null;
+ const color = scoreColor(headline);
+ return (
+ <section
+ aria-label="Repository health"
+ className="rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4"
+ >
+ <div className="flex items-center justify-between gap-2">
+ <p className="truncate text-sm font-semibold text-[var(--color-text-primary)]">
+ {repoName}
+ </p>
+ {branch ? (
+ <span className="flex min-w-0 shrink items-center gap-1 text-[11px] text-[var(--color-text-tertiary)]">
+ <GitBranch className="h-3 w-3 shrink-0" />
+ <span className="truncate font-mono">{branch}</span>
+ </span>
+ ) : null}
+ </div>
+
+ {loading ? (
+ <div className="mt-3 space-y-2" aria-hidden>
+ <div className="h-9 w-24 animate-pulse rounded-md bg-[var(--color-bg-inset)]" />
+ <div className="h-3 w-40 animate-pulse rounded bg-[var(--color-bg-inset)]" />
+ </div>
+ ) : headline != null ? (
+ <>
+ <div className="mt-3 flex items-end gap-2">
+ <span className="text-4xl font-bold leading-none tracking-tight" style={{ color }}>
+ {headline.toFixed(1)}
+ </span>
+ <span className="pb-0.5 text-sm text-[var(--color-text-tertiary)]">/ 10</span>
+ {usingHotspot ? <DeltaChip delta={health?.hotspotDelta ?? null} /> : null}
+ </div>
+ <p className="mt-1.5 text-[11px] text-[var(--color-text-secondary)]">
+ {usingHotspot ? "Hotspot health" : "Average health"}
+ {usingHotspot && health?.average != null
+ ? ` · average ${health.average.toFixed(1)}`
+ : ""}
+ {` · ${(health?.fileCount ?? 0).toLocaleString()} files`}
+ </p>
+ {usingHotspot && (health?.history.length ?? 0) >= 2 ? (
+ <Sparkline values={health?.history ?? []} color={color} />
+ ) : null}
+ </>
+ ) : (
+ <p className="mt-3 text-xs text-[var(--color-text-secondary)]">
+ No health data yet. Scores appear after the first full index.
+ </p>
+ )}
+ </section>
+ );
+}
+
+function DeltaChip({ delta }: { delta: number | null }) {
+ if (delta == null || delta === 0) return null;
+ const up = delta > 0;
+ return (
+ <span
+ className="mb-0.5 rounded-full px-1.5 py-0.5 text-[10px] font-semibold"
+ style={{
+ color: up ? "var(--color-success)" : "var(--color-error)",
+ backgroundColor: "var(--color-bg-inset)",
+ }}
+ title="Hotspot health change since the previous snapshot"
+ >
+ {up ? "▲" : "▼"} {Math.abs(delta).toFixed(1)}
+ </span>
+ );
+}
+
+/** Tiny inline trend line; the hero already labels it, so it is decorative. */
+function Sparkline({ values, color }: { values: number[]; color: string }) {
+ const width = 100;
+ const height = 24;
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const span = max - min || 1;
+ const step = width / (values.length - 1);
+ const points = values
+ .map((v, i) => `${(i * step).toFixed(1)},${(height - 3 - ((v - min) / span) * (height - 6)).toFixed(1)}`)
+ .join(" ");
+ return (
+ <svg
+ viewBox={`0 0 ${width} ${height}`}
+ preserveAspectRatio="none"
+ className="mt-2 h-6 w-full"
+ aria-hidden
+ >
+ <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" opacity="0.9" />
+ </svg>
+ );
+}
+
+function Freshness({
+ freshness,
+ updating,
+ onUpdate,
+}: {
+ freshness: HomeSummary["freshness"] | null;
+ updating: boolean;
+ onUpdate: () => void;
+}) {
+ const stale = freshness?.stale ?? false;
+ const indexed = short(freshness?.indexedCommit ?? null);
+ const live = short(freshness?.liveCommit ?? null);
+ const dotColor = stale ? "var(--color-warning)" : "var(--color-success)";
+
+ let detail = "";
+ if (stale && indexed && live) detail = `${indexed} → ${live}`;
+ else if (indexed) {
+ const ago = freshness?.lastIndexedAt ? timeAgo(freshness.lastIndexedAt) : "";
+ detail = ago ? `${indexed} · indexed ${ago}` : indexed;
+ }
+
+ return (
+ <section
+ aria-label="Index freshness"
+ className="flex items-center gap-2.5 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2.5"
+ >
+ <span
+ className="h-2 w-2 shrink-0 rounded-full"
+ style={{ backgroundColor: dotColor }}
+ aria-hidden
+ />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-medium text-[var(--color-text-primary)]">
+ {updating ? "Updating index…" : stale ? "Index behind checkout" : "Index up to date"}
+ </p>
+ {detail ? (
+ <p className="truncate font-mono text-[10px] text-[var(--color-text-tertiary)]">
+ {detail}
+ </p>
+ ) : null}
+ </div>
+ <button
+ type="button"
+ onClick={onUpdate}
+ disabled={updating}
+ title="Run an incremental index update"
+ className={
+ stale && !updating
+ ? "flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--color-accent-primary)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-on-accent)] transition-opacity hover:opacity-90"
+ : "flex shrink-0 items-center gap-1.5 rounded-lg border border-[var(--color-border-default)] px-2.5 py-1.5 text-[11px] font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)] disabled:cursor-default disabled:opacity-60"
+ }
+ >
+ <RefreshCw className={updating ? "h-3 w-3 animate-spin" : "h-3 w-3"} />
+ {updating ? "Updating" : "Update"}
+ </button>
+ </section>
+ );
+}
+
+function LauncherCard({
+ spec,
+ subtitle,
+ onOpen,
+}: {
+ spec: CardSpec;
+ subtitle: string;
+ onOpen: () => void;
+}) {
+ const Icon = spec.icon;
+ return (
+ <button
+ type="button"
+ onClick={onOpen}
+ className="group flex w-full items-center gap-3 rounded-xl border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-2.5 text-left transition-colors hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)]"
+ >
+ <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)]">
+ <Icon className="h-4 w-4" />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-[13px] font-medium text-[var(--color-text-primary)]">
+ {spec.title}
+ </span>
+ <span className="block truncate text-[11px] text-[var(--color-text-tertiary)]">
+ {subtitle}
+ </span>
+ </span>
+ <ChevronRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] opacity-0 transition-opacity group-hover:opacity-100" />
+ </button>
+ );
+}
diff --git a/packages/vscode/webview/src/views/home/main.tsx b/packages/vscode/webview/src/views/home/main.tsx
new file mode 100644
index 000000000..30b27b011
--- /dev/null
+++ b/packages/vscode/webview/src/views/home/main.tsx
@@ -0,0 +1,5 @@
+import "../../styles/index.css";
+import { mountView } from "../../runtime/mount";
+import { App } from "./App";
+
+mountView("home", App);
diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsx
index a6fd064db..f37d092c7 100644
--- a/packages/vscode/webview/src/views/risk/App.test.tsx
+++ b/packages/vscode/webview/src/views/risk/App.test.tsx
@@ -32,10 +32,15 @@ function makeHost(riskRange: WebviewHost["api"]["riskRange"]): WebviewHost {
api: { riskRange } as WebviewHost["api"],
onInit: () => () => {},
onRefresh: () => () => {},
+ onUpdateDone: () => () => {},
+ onThemeChanged: () => () => {},
ready: () => {},
openFile: () => {},
copyText: () => {},
openExternal: () => {},
+ openView: () => {},
+ updateIndex: () => {},
+ setTheme: () => {},
};
}
diff --git a/packages/vscode/webview/vite.config.mts b/packages/vscode/webview/vite.config.mts
index f83233389..6d8dddc9e 100644
--- a/packages/vscode/webview/vite.config.mts
+++ b/packages/vscode/webview/vite.config.mts
@@ -6,8 +6,9 @@ import tailwindcss from "@tailwindcss/vite";
const here = path.dirname(fileURLToPath(import.meta.url));
-/** One entry per panel; the host HTML loads dist/webview/<view>.js. */
+/** One entry per view; the host HTML loads dist/webview/<view>.js. */
const VIEWS = [
+ "home",
"health",
"architecture",
"graph",