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(web): add a three-step welcome for new repos, built on the What's new shell (#4682)

Raghav Chamadiyacf9024cd0765
diff --git a/packages/ui/scripts/contrast-check.py b/packages/ui/scripts/contrast-check.py
index 80344924b..513e1d7a2 100755
--- a/packages/ui/scripts/contrast-check.py
+++ b/packages/ui/scripts/contrast-check.py
@@ -149,7 +149,7 @@ LIGHT = {
"heat-1": "#F6EFE8", "heat-2": "#E7D6C2", "heat-3": "#D0B08A",
"heat-4": "#A16215", "heat-5": "#824F10",
# Release moment ground and glow band (What's new dialog).
- "release-ground": "#FBF6F1", "release-card": "#FFFFFF", "release-glow-1": "#F8DFC2", "release-glow-2": "#E8DEEF",
+ "release-ground": "#FBF6F1", "release-card": "#FFFFFF", "release-glow-1": "#F8DFC2", "release-glow-2": "#E8DEEF", "release-glow-3": "#DDE7F3",
}
DARK = {
@@ -200,7 +200,7 @@ DARK = {
# 12/26/42/75%, then accent-primary.
"heat-1": "#2F2317", "heat-2": "#4E3619", "heat-3": "#724A1A",
"heat-4": "#BD751E", "heat-5": "#F59520",
- "release-ground": "#111013", "release-card": "#1B191E", "release-glow-1": "#2B1C0E", "release-glow-2": "#1F1729",
+ "release-ground": "#111013", "release-card": "#1B191E", "release-glow-1": "#2B1C0E", "release-glow-2": "#1F1729", "release-glow-3": "#121A26",
}
# (fg, bg, floor, label) — floor is the WCAG ratio the pair must meet.
@@ -265,7 +265,7 @@ CHECKS = [
# beside the release figures.
*[
(fg, bg, floor, f"{fg} on {bg}")
- for bg in ("release-ground", "release-glow-1", "release-glow-2")
+ for bg in ("release-ground", "release-glow-1", "release-glow-2", "release-glow-3")
for fg, floor in (("text-primary", 7.0), ("text-secondary", 4.5))
],
("accent-primary", "release-ground", 4.5, "accent-primary on release-ground"),
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index ff0b83ece..c1c08724e 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -170,6 +170,8 @@
--color-release-card: var(--color-bg-surface);
--color-release-glow-1: #f8dfc2;
--color-release-glow-2: #e8deef;
+ /* The welcome's band runs plum into this blue instead of orange into plum. */
+ --color-release-glow-3: #dde7f3;
/* Supporting cast beside an accent series: tertiary ink stepped into the well. */
--color-neutral-1: color-mix(in srgb, var(--color-text-tertiary) 62%, var(--color-bg-inset));
--color-neutral-2: color-mix(in srgb, var(--color-text-tertiary) 40%, var(--color-bg-inset));
@@ -546,6 +548,7 @@
--color-release-card: #1b191e;
--color-release-glow-1: #2b1c0e;
--color-release-glow-2: #1f1729;
+ --color-release-glow-3: #121a26;
--color-neutral-1: color-mix(in srgb, var(--color-text-tertiary) 70%, var(--color-bg-inset));
--color-neutral-2: color-mix(in srgb, var(--color-text-tertiary) 45%, var(--color-bg-inset));
--color-neutral-3: color-mix(in srgb, var(--color-text-tertiary) 26%, var(--color-bg-inset));
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index dc62d34c0..cbb5c52de 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -1153,7 +1153,8 @@
"title": "This repo hasn't been indexed yet",
"description": "One click builds the code index, health signals, and documentation. You can watch it happen live.",
"starting": "Starting…",
- "action": "Index this repo"
+ "action": "Index this repo",
+ "takeTour": "Take the tour"
},
"coordinator": {
"status": "Status",
@@ -1344,6 +1345,120 @@
"badgeAction": "Write with a model",
"badgeTitle": "The subsystem pages are still generated from code structure. Write them with a model for the how and why."
},
+ "welcome": {
+ "eyebrow": "Welcome to repowise",
+ "stepsLabel": "Tour steps",
+ "stepDone": "(done)",
+ "stepOf": "Step {step} of {total}",
+ "steps": {
+ "repo": "Your repo",
+ "agent": "Your agent",
+ "yours": "Make it yours"
+ },
+ "skip": "Skip the tour",
+ "back": "Back",
+ "nextAgent": "Next: your agent",
+ "nextYours": "Next: make it yours",
+ "finish": "Finish in Setup",
+ "repo": {
+ "title": "We mapped <em>{name}</em>",
+ "lede": "{files, plural, one {# file} other {# files}} and {years, plural, one {# year} other {# years}} of history, read on this machine. Nothing left it.",
+ "ledeNoHistory": "{files, plural, one {# file} other {# files}}, read on this machine. Nothing left it.",
+ "standout": "What stood out",
+ "band": {
+ "excellent": "Excellent",
+ "good": "Good",
+ "fair": "Fair",
+ "needs_work": "Needs work",
+ "at_risk": "At risk"
+ },
+ "health": {
+ "label": "Health",
+ "caption": "<mono>{path}</mono> is lowest at {score}.",
+ "captionNone": "Scored across the code files.",
+ "open": "Open health"
+ },
+ "deadCode": {
+ "label": "Dead code",
+ "unit": "{count, plural, one {file} other {files}}",
+ "caption": "Nothing reaches them.",
+ "safe": "{count, plural, one {# finding is} other {# findings are}} safe to delete.",
+ "captionNone": "Every file is reached from somewhere.",
+ "open": "Open dead code"
+ },
+ "risk": {
+ "label": "Risk",
+ "unit": "{count, plural, one {file reached} other {files reached}}",
+ "caption": "by a change to <mono>{path}</mono>.",
+ "open": "Open risk"
+ },
+ "decisions": {
+ "label": "Decisions",
+ "unit": "to review",
+ "caption": "Candidates mined from PRs, commits and comments.",
+ "open": "Review"
+ },
+ "docs": {
+ "label": "Documentation",
+ "unit": "{count, plural, one {page} other {pages}}",
+ "caption": "Built from the index. A model can write fuller ones.",
+ "open": "Open docs"
+ },
+ "tests": {
+ "label": "Tests",
+ "measured": "measured",
+ "measuredCaption": "Line coverage from your latest report.",
+ "inferredUnit": "of {total} files, inferred",
+ "inferredCaption": "Reached from a test. Add a report to measure it.",
+ "open": "Open tests"
+ }
+ },
+ "agent": {
+ "title": "Your agent can read <em>this map</em>",
+ "lede": "It asks repowise first, so it reads less and guesses less.",
+ "none": "No agents found on this machine yet. Setup lists every one repowise supports.",
+ "connected": "Connected. Restart it to load the tools.",
+ "waiting": "Waiting for its first call",
+ "firstCall": "First call {when}",
+ "installed": "Installed on this machine. Writes <mono>{file}</mono>.",
+ "installedNoFile": "Installed on this machine.",
+ "connect": "Connect",
+ "connecting": "Connecting",
+ "connectFailed": "Couldn't connect {name}",
+ "copyPrompt": "Copy setup prompt",
+ "promptCopied": "Setup prompt copied",
+ "prompt": "Connect repowise to {name} for this repo. Run `{command}` in the repo root, then restart {name} so it loads the repowise tools. Run `repowise doctor` to check the connection.",
+ "askLabel": "Ask it something",
+ "askRisk": "Which files are riskiest to change, and why?",
+ "askHotspot": "Why does {path} change so often?",
+ "askStart": "Where should I start reading this repo?",
+ "copy": "Copy",
+ "copied": "Copied",
+ "copyQuestion": "Copy: {question}"
+ },
+ "yours": {
+ "title": "Make it <em>yours</em>",
+ "lede": "Both are optional. You can change them any time in Settings.",
+ "modelTitle": "Add a model for the parts that need one",
+ "optional": "Optional",
+ "gets": {
+ "docs": "Docs that explain how and why",
+ "chat": "Chat in this dashboard",
+ "answers": "Written answers for your agent",
+ "local": "Your key or sign-in stays here"
+ },
+ "detectedLabel": "Found on this machine",
+ "syncTitle": "Keep the index in sync",
+ "syncBody": "Updates after each commit through a git hook.",
+ "syncFailed": "Couldn't change sync",
+ "syncOffTitle": "Turn off sync?",
+ "syncOffBody": "This removes the post-commit hook. It also turns off the pre-commit security check and the health gate, if they are on.",
+ "syncOffConfirm": "Turn off",
+ "teamTitle": "Running this for a team?",
+ "teamBody": "Hosted repowise indexes on every push, reviews pull requests and gives your team one dashboard.",
+ "teamLink": "See hosted"
+ }
+ },
"chat": {
"addModel": "Add a model",
"noProvider": "No chat provider is configured. Add an API key in <link>settings</link> to start asking questions.",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 8d83fd866..76f14ce64 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -1153,7 +1153,8 @@
"title": "这个代码仓库尚未建立索引",
"description": "一次点击即可构建代码索引、健康信号与文档。整个过程都能实时查看。",
"starting": "正在启动…",
- "action": "为该仓库建立索引"
+ "action": "为该仓库建立索引",
+ "takeTour": "开始导览"
},
"coordinator": {
"status": "状态",
@@ -1344,6 +1345,120 @@
"badgeAction": "用模型撰写",
"badgeTitle": "子系统页面仍由代码结构生成。用模型撰写,讲清原理与缘由。"
},
+ "welcome": {
+ "eyebrow": "欢迎使用 repowise",
+ "stepsLabel": "导览步骤",
+ "stepDone": "(已完成)",
+ "stepOf": "第 {step} 步,共 {total} 步",
+ "steps": {
+ "repo": "你的仓库",
+ "agent": "你的智能体",
+ "yours": "按你的方式设置"
+ },
+ "skip": "跳过导览",
+ "back": "返回",
+ "nextAgent": "下一步:你的智能体",
+ "nextYours": "下一步:按你的方式设置",
+ "finish": "在设置中完成",
+ "repo": {
+ "title": "我们已为 <em>{name}</em> 绘制地图",
+ "lede": "{files, plural, other {# 个文件}}和 {years, plural, other {# 年}}的历史,都在本机读取,没有任何内容离开本机。",
+ "ledeNoHistory": "{files, plural, other {# 个文件}},都在本机读取,没有任何内容离开本机。",
+ "standout": "值得关注",
+ "band": {
+ "excellent": "优秀",
+ "good": "良好",
+ "fair": "一般",
+ "needs_work": "需要改进",
+ "at_risk": "有风险"
+ },
+ "health": {
+ "label": "健康度",
+ "caption": "<mono>{path}</mono> 最低,为 {score}。",
+ "captionNone": "按代码文件评分。",
+ "open": "打开健康度"
+ },
+ "deadCode": {
+ "label": "死代码",
+ "unit": "{count, plural, other {个文件}}",
+ "caption": "没有任何代码引用它们。",
+ "safe": "{count, plural, other {# 项发现}}可以安全删除。",
+ "captionNone": "每个文件都有代码引用。",
+ "open": "打开死代码"
+ },
+ "risk": {
+ "label": "风险",
+ "unit": "{count, plural, other {个文件受影响}}",
+ "caption": "来自对 <mono>{path}</mono> 的一次修改。",
+ "open": "打开风险"
+ },
+ "decisions": {
+ "label": "决策",
+ "unit": "待审阅",
+ "caption": "从 PR、提交和注释中挖掘出的候选项。",
+ "open": "审阅"
+ },
+ "docs": {
+ "label": "文档",
+ "unit": "{count, plural, other {页}}",
+ "caption": "基于索引构建。模型可以写出更完整的文档。",
+ "open": "打开文档"
+ },
+ "tests": {
+ "label": "测试",
+ "measured": "实测",
+ "measuredCaption": "来自最新报告的行覆盖率。",
+ "inferredUnit": "共 {total} 个文件,按推断",
+ "inferredCaption": "有测试能到达。添加报告即可实测。",
+ "open": "打开测试"
+ }
+ },
+ "agent": {
+ "title": "你的智能体可以读取<em>这张地图</em>",
+ "lede": "它会先询问 repowise,因此读得更少,猜得更少。",
+ "none": "本机暂未发现智能体。设置页列出了 repowise 支持的全部智能体。",
+ "connected": "已连接。重启它以加载工具。",
+ "waiting": "等待首次调用",
+ "firstCall": "首次调用:{when}",
+ "installed": "已安装在本机。将写入 <mono>{file}</mono>。",
+ "installedNoFile": "已安装在本机。",
+ "connect": "连接",
+ "connecting": "正在连接",
+ "connectFailed": "无法连接 {name}",
+ "copyPrompt": "复制设置提示词",
+ "promptCopied": "已复制设置提示词",
+ "prompt": "为此仓库将 repowise 连接到 {name}。在仓库根目录运行 `{command}`,然后重启 {name},让它加载 repowise 工具。运行 `repowise doctor` 检查连接。",
+ "askLabel": "问它一个问题",
+ "askRisk": "哪些文件改动风险最高?为什么?",
+ "askHotspot": "为什么 {path} 改动如此频繁?",
+ "askStart": "我应该从哪里开始阅读这个仓库?",
+ "copy": "复制",
+ "copied": "已复制",
+ "copyQuestion": "复制:{question}"
+ },
+ "yours": {
+ "title": "按<em>你的方式</em>设置",
+ "lede": "两项都是可选的。你可以随时在设置中更改。",
+ "modelTitle": "为需要模型的部分添加一个模型",
+ "optional": "可选",
+ "gets": {
+ "docs": "解释原理和原因的文档",
+ "chat": "在此仪表板中对话",
+ "answers": "为你的智能体撰写的回答",
+ "local": "你的密钥或登录信息保留在本机"
+ },
+ "detectedLabel": "在本机找到",
+ "syncTitle": "保持索引同步",
+ "syncBody": "每次提交后通过 git 钩子更新。",
+ "syncFailed": "无法更改同步设置",
+ "syncOffTitle": "关闭同步?",
+ "syncOffBody": "这会移除 post-commit 钩子,同时关闭 pre-commit 安全检查和健康门禁(如果已开启)。",
+ "syncOffConfirm": "关闭",
+ "teamTitle": "为团队运行?",
+ "teamBody": "托管版 repowise 会在每次推送时建立索引、审查拉取请求,并为你的团队提供一个仪表板。",
+ "teamLink": "了解托管版"
+ }
+ },
"chat": {
"addModel": "添加模型",
"noProvider": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥,然后就可以开始提问了。",
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index da13f7168..91e2cd0d0 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -13,6 +13,8 @@ import { QuickActionsWrapper } from "@/components/dashboard/quick-actions-wrappe
import { AskAnythingRow } from "@/components/overview/ask-anything-row";
import { NextActionsPanel } from "@/components/overview/next-actions-panel";
import { PublishOverviewSection } from "@/components/hosted/publish";
+import { WelcomeMoment } from "@/components/welcome/welcome-moment";
+import { welcomeFigures } from "@/lib/welcome-moment";
import {
OverviewBody,
OverviewSection,
@@ -153,7 +155,19 @@ export default async function OverviewPage({ params }: Props) {
routes={routes}
LinkComponent={Link}
slots={{
- header,
+ header: (
+ <>
+ {header}
+ {/* A dialog: renders in a portal, so its slot here is only a mount point. */}
+ <WelcomeMoment
+ repoId={id}
+ repoName={repo.name}
+ fileCount={stats.file_count}
+ figures={welcomeFigures(summary)}
+ hotspotPath={summary.top_hotspots[0]?.file_path ?? null}
+ />
+ </>
+ ),
ask: <AskAnythingRow repoId={id} suggestions={overviewAskSuggestions(summary, tOverview)} />,
beforeExplore: <PublishOverviewSection repoId={id} />,
// A server that predates actions returns 404; the page then keeps the
diff --git a/packages/web/src/components/layout/moment-shell.tsx b/packages/web/src/components/layout/moment-shell.tsx
new file mode 100644
index 000000000..f003000f0
--- /dev/null
+++ b/packages/web/src/components/layout/moment-shell.tsx
@@ -0,0 +1,67 @@
+import type { CSSProperties, ReactNode } from "react";
+import { cn } from "@repowise-dev/ui/lib/cn";
+
+/**
+ * The shared look of the dialogs that present instead of asking: What's new and
+ * the welcome. A deeper ground than the overlay plane, a glow band behind a
+ * display heading, and cards with a series-coloured left edge.
+ */
+
+/** The dialog ground. Pass to `DialogContent` with the dialog's own sizing. */
+export const MOMENT_GROUND = "gap-0 bg-[var(--color-release-ground)] p-0";
+
+export const MOMENT_MICRO =
+ "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
+
+/** A gentle rise on open; the global reduced-motion rule flattens it. */
+export const MOMENT_ENTER =
+ "motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 duration-500";
+
+/** The display heading's type, without its weight. */
+export const MOMENT_DISPLAY =
+ "font-serif text-4xl tracking-tight text-[var(--color-text-primary)] sm:text-5xl";
+
+/** A card on the moment ground; set `borderLeftColor` to its series colour. */
+export const MOMENT_CARD =
+ "rounded-lg border border-[var(--color-border-default)] border-l-[3px] bg-[var(--color-release-card)]";
+
+/** The glow bands, fading into the dialog ground. Solid stops, checked by
+ * contrast-check.py. What's new runs orange into plum; the welcome runs plum
+ * into blue. */
+const BANDS = {
+ release:
+ "linear-gradient(120deg, var(--color-release-glow-1) 0%, var(--color-release-glow-2) 55%, var(--color-release-ground) 100%)",
+ welcome:
+ "linear-gradient(120deg, var(--color-release-glow-2) 0%, var(--color-release-glow-3) 55%, var(--color-release-ground) 100%)",
+} as const;
+
+export type MomentTone = keyof typeof BANDS;
+
+/** The band at the top of a moment dialog. */
+export function MomentBand({
+ tone,
+ className,
+ children,
+}: {
+ tone: MomentTone;
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <header
+ className={cn("border-b border-[var(--color-border-default)] px-6 pb-6 pt-6 sm:px-8", className)}
+ style={{ backgroundImage: BANDS[tone] }}
+ >
+ {children}
+ </header>
+ );
+}
+
+/** Ink fading into plum and blue, for the emphasised words of a display heading. */
+export const MOMENT_EMPHASIS: CSSProperties = {
+ backgroundImage:
+ "linear-gradient(100deg, var(--color-text-primary) 10%, var(--color-series-2) 70%, var(--color-series-3) 115%)",
+ WebkitBackgroundClip: "text",
+ backgroundClip: "text",
+ color: "transparent",
+};
diff --git a/packages/web/src/components/layout/release-moment.test.tsx b/packages/web/src/components/layout/release-moment.test.tsx
index c129dbcf9..cb0a9f5ba 100644
--- a/packages/web/src/components/layout/release-moment.test.tsx
+++ b/packages/web/src/components/layout/release-moment.test.tsx
@@ -13,7 +13,10 @@ vi.mock("@/lib/hooks/use-meta-version", () => ({
}));
vi.mock("next/navigation", () => ({ usePathname: () => "/" }));
-beforeEach(() => window.localStorage.clear());
+beforeEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+});
afterEach(cleanup);
describe("ReleaseMoment", () => {
diff --git a/packages/web/src/components/layout/release-notes.tsx b/packages/web/src/components/layout/release-notes.tsx
index 0ba08b9ba..6fb7797b9 100644
--- a/packages/web/src/components/layout/release-notes.tsx
+++ b/packages/web/src/components/layout/release-notes.tsx
@@ -9,17 +9,13 @@ import { seriesColor } from "@repowise-dev/ui/shared/series";
import type { ChangelogEntry, ChangelogHighlight, ReleaseStats } from "@/lib/api/meta";
import { linkPullRequests, resolveHighlightHref } from "@/lib/release-moment";
import { NewMark } from "./new-mark";
-
-const MICRO =
- "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
-
-/** The glow band behind the version: orange into plum at low strength,
- * fading into the dialog ground. Solid stops, checked by contrast-check.py. */
-const BAND =
- "linear-gradient(120deg, var(--color-release-glow-1) 0%, var(--color-release-glow-2) 55%, var(--color-release-ground) 100%)";
-
-/** A gentle rise on open; the global reduced-motion rule flattens it. */
-const ENTER = "motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 duration-500";
+import {
+ MOMENT_CARD,
+ MOMENT_DISPLAY,
+ MOMENT_ENTER as ENTER,
+ MOMENT_MICRO as MICRO,
+ MomentBand,
+} from "./moment-shell";
export function releaseName(version: string, nextLabel: string): string {
return version === "unreleased" ? nextLabel : `v${version}`;
@@ -36,16 +32,13 @@ export function ReleaseHeader({
}) {
const t = useTranslations("shell.whatsNewModal");
return (
- <header
- className="border-b border-[var(--color-border-default)] px-6 pb-6 pt-6 sm:px-8"
- style={{ backgroundImage: BAND }}
- >
+ <MomentBand tone="release">
{title}
<h3
id={`release-${entry.version}`}
className={`mt-3 flex flex-wrap items-baseline gap-x-3 gap-y-1 ${ENTER}`}
>
- <span className="font-serif text-4xl font-light tracking-tight text-[var(--color-text-primary)] sm:text-5xl">
+ <span className={`${MOMENT_DISPLAY} font-light`}>
{releaseName(entry.version, t("nextRelease"))}
</span>
{entry.label && (
@@ -55,7 +48,7 @@ export function ReleaseHeader({
{entry.version === "unreleased" && (
<p className="mt-2 text-xs text-[var(--color-text-secondary)]">{t("unreleasedNote")}</p>
)}
- </header>
+ </MomentBand>
);
}
@@ -163,7 +156,7 @@ function HighlightItem({
<Link
href={href}
onClick={onNavigate}
- className="group flex w-full flex-col rounded-lg border border-[var(--color-border-default)] border-l-[3px] bg-[var(--color-release-card)] px-4 py-3 no-underline transition-colors hover:border-[var(--color-border-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ className={`${MOMENT_CARD} group flex w-full flex-col px-4 py-3 no-underline transition-colors hover:border-[var(--color-border-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]`}
style={{ borderLeftColor: color }}
>
{body}
diff --git a/packages/web/src/components/layout/whats-new-modal.tsx b/packages/web/src/components/layout/whats-new-modal.tsx
index 087e09fc6..f66c057a5 100644
--- a/packages/web/src/components/layout/whats-new-modal.tsx
+++ b/packages/web/src/components/layout/whats-new-modal.tsx
@@ -12,6 +12,7 @@ import {
import { useChangelog } from "@/lib/hooks/use-meta-version";
import { highlightRepoId } from "@/lib/release-moment";
import { useTranslations } from "next-intl";
+import { MOMENT_GROUND } from "./moment-shell";
import { ReleaseHeader, ReleaseNotes, releaseName } from "./release-notes";
/** How many earlier releases the switcher lists. */
@@ -62,7 +63,7 @@ export function WhatsNewModal({ open, onOpenChange, version, fresh = false }: Wh
<Dialog open={open} onOpenChange={onOpenChange}>
{/* Its own deeper ground and a glow band: the release moment is the one
dialog that presents rather than asks. */}
- <DialogContent className="max-h-[85vh] gap-0 overflow-y-auto bg-[var(--color-release-ground)] p-0 sm:max-w-3xl">
+ <DialogContent className={`${MOMENT_GROUND} max-h-[85vh] overflow-y-auto sm:max-w-3xl`}>
{entry ? (
<ReleaseHeader key={`h-${entry.version}`} entry={entry} title={title} />
) : (
diff --git a/packages/web/src/components/repos/first-index-experience.tsx b/packages/web/src/components/repos/first-index-experience.tsx
index f112382ea..bf8280f50 100644
--- a/packages/web/src/components/repos/first-index-experience.tsx
+++ b/packages/web/src/components/repos/first-index-experience.tsx
@@ -23,6 +23,7 @@ interface Props {
* The fresh-repo overview surface: one prominent "Index this repo" action,
* live phase-labeled progress once a job is running, and a celebratory
* handoff (with the first five files to read) when the first index lands.
+ * Its button opens the welcome tour on the indexed overview.
* Hydrates from any in-flight job so a page refresh mid-index rejoins it.
*/
export function FirstIndexExperience({ repoId, repoName }: Props) {
@@ -115,7 +116,9 @@ export function FirstIndexExperience({ repoId, repoName }: Props) {
<IndexCelebration
repoName={repoName}
pagesGenerated={completed.pages}
- onExplore={() => router.refresh()}
+ // Hands off to the welcome on the indexed overview, so the two never stack.
+ exploreLabel={t("firstIndex.takeTour")}
+ onExplore={() => router.push(`/repos/${encodeURIComponent(repoId)}/overview?tour=1`)}
>
{startHere.length > 0 && (
<FirstFiveFiles
diff --git a/packages/web/src/components/welcome/welcome-dialog.test.tsx b/packages/web/src/components/welcome/welcome-dialog.test.tsx
new file mode 100644
index 000000000..1d296e806
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-dialog.test.tsx
@@ -0,0 +1,217 @@
+// @vitest-environment jsdom
+
+import React from "react";
+import { SWRConfig } from "swr";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { SetupResponse } from "@/lib/api/setup";
+import type { WelcomeLens } from "@/lib/welcome-moment";
+import { WelcomeDialog } from "./welcome-dialog";
+import { showsHostedRow } from "./welcome-step-yours";
+
+const mocks = vi.hoisted(() => ({
+ connectSetupAgent: vi.fn(),
+ setSetupHook: vi.fn(),
+ getProviders: vi.fn(),
+ openSheet: vi.fn(),
+ toastError: vi.fn(),
+}));
+
+vi.mock("next/link", () => ({
+ default: ({ children, href, onClick }: { children: React.ReactNode; href: string; onClick?: () => void }) => (
+ <a href={href} onClick={(e) => { e.preventDefault(); onClick?.(); }}>
+ {children}
+ </a>
+ ),
+}));
+vi.mock("@/lib/api/setup", () => ({
+ connectSetupAgent: mocks.connectSetupAgent,
+ setSetupHook: mocks.setSetupHook,
+}));
+vi.mock("@/lib/api/providers", () => ({ getProviders: mocks.getProviders }));
+vi.mock("@/components/model-upgrade/model-upgrade", () => ({
+ useModelUpgrade: () => ({ openSheet: mocks.openSheet, sheet: null }),
+}));
+vi.mock("sonner", () => ({ toast: { error: mocks.toastError, success: vi.fn() } }));
+
+function setup(overrides: Partial<SetupResponse> = {}): SetupResponse {
+ return {
+ repo_id: "r1",
+ generated_at: "",
+ index: { state: "up_to_date" },
+ agents_available: true,
+ agents: [
+ { id: "claude-code", display_name: "Claude Code", installed: true, connected: true },
+ {
+ id: "cursor",
+ display_name: "Cursor",
+ installed: true,
+ connected: false,
+ config_files: { repo: [".cursor/mcp.json"] },
+ },
+ ],
+ calls_available: true,
+ calls: {},
+ coverage_available: true,
+ model_available: true,
+ sync: { installed: true },
+ rewrite_hook: { state: "not_installed" },
+ coverage: {},
+ model: { docs_mode: "deterministic" },
+ checks_available: false,
+ onboarding: { hints_enabled: true, signed_in: false },
+ writes_allowed: true,
+ ...overrides,
+ };
+}
+
+const LENSES: WelcomeLens[] = [
+ { key: "health", score: 7.4, band: "good", worstPath: "a.py", worstScore: 3.1 },
+ { key: "docs", pages: 412 },
+];
+
+function renderDialog(props: Partial<React.ComponentProps<typeof WelcomeDialog>> = {}) {
+ const onOpenChange = vi.fn();
+ render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ <WelcomeDialog
+ open
+ onOpenChange={onOpenChange}
+ repoId="r1"
+ repoName="orbit-api"
+ fileCount={1284}
+ years={9}
+ lenses={LENSES}
+ setup={setup()}
+ hotspotPath="scheduler/planner.py"
+ {...props}
+ />
+ </SWRConfig>,
+ );
+ return { onOpenChange };
+}
+
+beforeEach(() => {
+ mocks.getProviders.mockResolvedValue({ active: { provider: null, model: null }, providers: [] });
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("WelcomeDialog", () => {
+ it("walks the three steps forward and back, naming each in the title", () => {
+ renderDialog();
+ const dialog = screen.getByRole("dialog");
+ expect(within(dialog).getByRole("heading", { name: "We mapped orbit-api" })).toBeTruthy();
+ expect(screen.getByText("Step 1 of 3")).toBeTruthy();
+ expect(screen.getByText(/1,284 files and 9 years of history/)).toBeTruthy();
+ expect(document.activeElement?.textContent).toBe("We mapped orbit-api");
+
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ expect(screen.getByRole("heading", { name: "Your agent can read this map" })).toBeTruthy();
+ expect(document.activeElement?.textContent).toBe("Your agent can read this map");
+ const steps = screen.getByRole("list", { name: "Tour steps" });
+ expect(within(steps).getByText("Your agent").closest("li")?.getAttribute("aria-current")).toBe("step");
+
+ fireEvent.click(screen.getByRole("button", { name: "Next: make it yours" }));
+ expect(screen.getByText("Step 3 of 3")).toBeTruthy();
+ expect(screen.getByRole("link", { name: "Finish in Setup" }).getAttribute("href")).toBe(
+ "/repos/r1/settings/setup",
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ expect(screen.getByText("Step 2 of 3")).toBeTruthy();
+ });
+
+ it("skips the tour from the first step", () => {
+ const { onOpenChange } = renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: "Skip the tour" }));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("closes when a lens card opens its page", () => {
+ const { onOpenChange } = renderDialog();
+ const link = screen.getByRole("link", { name: "Open health" });
+ expect(link.getAttribute("href")).toBe("/repos/r1/code-health");
+ fireEvent.click(link);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ // Only the measured lenses render.
+ expect(screen.queryByText("Dead code")).toBeNull();
+ });
+
+ it("connects an agent, and rolls back when the command reports failure", async () => {
+ mocks.connectSetupAgent.mockResolvedValue({ ok: false, command: "repowise agents add", message: "no config dir" });
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ expect(screen.getByText("Waiting for its first call")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ expect(mocks.connectSetupAgent).toHaveBeenCalledWith("r1", "cursor");
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalled());
+ expect(mocks.toastError.mock.calls[0]![0]).toBe("Couldn't connect Cursor");
+ expect(screen.getByRole("button", { name: "Connect" })).toBeTruthy();
+ expect(screen.getByText(/Installed on this machine/)).toBeTruthy();
+ });
+
+ it("keeps a connected agent after a successful connect", async () => {
+ mocks.connectSetupAgent.mockResolvedValue({ ok: true, command: "repowise agents add" });
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Connect" })).toBeNull());
+ expect(screen.getAllByText("Waiting for its first call")).toHaveLength(2);
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ });
+
+ it("asks before turning sync off, and says what else goes", async () => {
+ mocks.setSetupHook.mockResolvedValue({ ok: true, command: "repowise hook uninstall" });
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ fireEvent.click(screen.getByRole("button", { name: "Next: make it yours" }));
+
+ const toggle = screen.getByRole("switch", { name: "Keep the index in sync" });
+ expect(toggle.getAttribute("aria-checked")).toBe("true");
+ fireEvent.click(toggle);
+ expect(mocks.setSetupHook).not.toHaveBeenCalled();
+ expect(screen.getByText(/pre-commit security check and the health gate/)).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Turn off" }));
+ await waitFor(() => expect(mocks.setSetupHook).toHaveBeenCalledWith("r1", "post-commit", false));
+ await waitFor(() => expect(toggle.getAttribute("aria-checked")).toBe("false"));
+ });
+
+ it("opens the model sheet from the plum box", () => {
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ fireEvent.click(screen.getByRole("button", { name: "Next: make it yours" }));
+ fireEvent.click(screen.getByRole("button", { name: "Write the docs" }));
+ expect(mocks.openSheet).toHaveBeenCalled();
+ });
+});
+
+describe("hosted row", () => {
+ it("shows with hints on for someone not signed in", () => {
+ expect(showsHostedRow(setup())).toBe(true);
+ });
+
+ it("hides when hints are off, when signed in, or without setup data", () => {
+ expect(showsHostedRow(setup({ onboarding: { hints_enabled: false, signed_in: false } }))).toBe(false);
+ expect(showsHostedRow(setup({ onboarding: { hints_enabled: true, signed_in: true } }))).toBe(false);
+ expect(showsHostedRow(null)).toBe(false);
+ });
+
+ it("renders its link to hosted only when shown", () => {
+ renderDialog({ setup: setup({ onboarding: { hints_enabled: false, signed_in: false } }) });
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ fireEvent.click(screen.getByRole("button", { name: "Next: make it yours" }));
+ expect(screen.queryByRole("link", { name: "See hosted" })).toBeNull();
+ cleanup();
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: "Next: your agent" }));
+ fireEvent.click(screen.getByRole("button", { name: "Next: make it yours" }));
+ expect(screen.getByRole("link", { name: "See hosted" }).getAttribute("href")).toContain(
+ "src=local_web_welcome",
+ );
+ });
+});
diff --git a/packages/web/src/components/welcome/welcome-dialog.tsx b/packages/web/src/components/welcome/welcome-dialog.tsx
new file mode 100644
index 000000000..9ea794080
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-dialog.tsx
@@ -0,0 +1,201 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { useTranslations } from "next-intl";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogTitle,
+} from "@repowise-dev/ui/ui/dialog";
+import { Button } from "@repowise-dev/ui/ui/button";
+import type { SetupResponse } from "@/lib/api/setup";
+import type { WelcomeLens } from "@/lib/welcome-moment";
+import {
+ MOMENT_DISPLAY,
+ MOMENT_EMPHASIS,
+ MOMENT_ENTER,
+ MOMENT_GROUND,
+ MOMENT_MICRO,
+ MomentBand,
+} from "@/components/layout/moment-shell";
+import { WelcomeStepRepo } from "./welcome-step-repo";
+import { WelcomeStepAgent } from "./welcome-step-agent";
+import { WelcomeStepYours } from "./welcome-step-yours";
+
+const STEPS = ["repo", "agent", "yours"] as const;
+type Step = (typeof STEPS)[number];
+
+/** Below 561px the dialog is a full-height sheet; above, a centred dialog. */
+const SHEET =
+ "left-0 top-0 flex h-dvh max-h-none w-full max-w-none translate-x-0 translate-y-0 flex-col overflow-hidden rounded-none border-0 " +
+ "min-[561px]:left-[50%] min-[561px]:top-[50%] min-[561px]:h-auto min-[561px]:max-h-[85vh] min-[561px]:max-w-[720px] min-[561px]:translate-x-[-50%] min-[561px]:translate-y-[-50%] min-[561px]:rounded-[14px] min-[561px]:border";
+
+export interface WelcomeDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ repoId: string;
+ repoName: string;
+ fileCount: number;
+ years: number | null;
+ lenses: WelcomeLens[];
+ setup: SetupResponse | null;
+ /** The busiest file, for the second example question. */
+ hotspotPath: string | null;
+}
+
+/**
+ * The three-step welcome: what repowise found, the agent that can read it,
+ * and the optional parts. Built on the What's new shell with a plum-to-blue
+ * band. Esc or the close button ends it at any step.
+ */
+export function WelcomeDialog(props: WelcomeDialogProps) {
+ const { open, onOpenChange, repoId } = props;
+ const t = useTranslations("welcome");
+ const [index, setIndex] = useState(0);
+ const step = STEPS[index]!;
+ const heading = useRef<HTMLHeadingElement>(null);
+
+ // Each opening starts at the first step.
+ useEffect(() => {
+ if (open) setIndex(0);
+ }, [open]);
+
+ // The heading names the step; moving focus there announces it.
+ useEffect(() => {
+ if (open) heading.current?.focus();
+ }, [index, open]);
+
+ const close = () => onOpenChange(false);
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className={`${MOMENT_GROUND} ${SHEET}`}
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ heading.current?.focus();
+ }}
+ >
+ {/* Band and body scroll; the footer and the close button stay put. */}
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <MomentBand tone="welcome" className="max-[560px]:px-[18px] max-[560px]:pb-4 max-[560px]:pt-[18px]">
+ <p className={`${MOMENT_MICRO} pr-8`}>{t("eyebrow")}</p>
+ <DialogTitle
+ ref={heading}
+ tabIndex={-1}
+ className={`${MOMENT_DISPLAY} mt-3 font-normal leading-[1.08] outline-none max-[560px]:text-[29px] ${MOMENT_ENTER}`}
+ >
+ <StepTitle step={step} repoName={props.repoName} />
+ </DialogTitle>
+ <DialogDescription className="mt-2 text-sm text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <StepLede step={step} fileCount={props.fileCount} years={props.years} />
+ </DialogDescription>
+ <StepIndicator index={index} />
+ </MomentBand>
+
+ <div className="flex-1 px-6 pb-2 pt-5 sm:px-8 max-[560px]:px-[18px]">
+ {step === "repo" && (
+ <WelcomeStepRepo repoId={repoId} lenses={props.lenses} onNavigate={close} />
+ )}
+ {step === "agent" && (
+ <WelcomeStepAgent repoId={repoId} setup={props.setup} hotspotPath={props.hotspotPath} />
+ )}
+ {step === "yours" && <WelcomeStepYours repoId={repoId} setup={props.setup} />}
+ </div>
+ </div>
+
+ <footer className="flex flex-col-reverse gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-release-ground)] px-[18px] pb-[18px] pt-3 min-[561px]:flex-row min-[561px]:items-center min-[561px]:justify-between min-[561px]:border-t-0 min-[561px]:px-8 min-[561px]:pb-5 min-[561px]:pt-3.5">
+ <span className="text-center text-xs text-[var(--color-text-tertiary)] min-[561px]:text-left">
+ {t("stepOf", { step: index + 1, total: STEPS.length })}
+ </span>
+ <div className="flex flex-col-reverse gap-2 min-[561px]:flex-row">
+ {index === 0 ? (
+ <Button variant="ghost" size="sm" className="h-9 max-[560px]:w-full" onClick={close}>
+ {t("skip")}
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-9 max-[560px]:w-full"
+ onClick={() => setIndex(index - 1)}
+ >
+ {t("back")}
+ </Button>
+ )}
+ {index < STEPS.length - 1 ? (
+ <Button size="sm" className="h-9 max-[560px]:w-full" onClick={() => setIndex(index + 1)}>
+ {index === 0 ? t("nextAgent") : t("nextYours")}
+ </Button>
+ ) : (
+ <Button asChild size="sm" className="h-9 max-[560px]:w-full">
+ <Link href={`/repos/${encodeURIComponent(repoId)}/settings/setup`} onClick={close}>
+ {t("finish")}
+ </Link>
+ </Button>
+ )}
+ </div>
+ </footer>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function StepTitle({ step, repoName }: { step: Step; repoName: string }) {
+ const t = useTranslations("welcome");
+ const em = (chunks: ReactNode) => <span style={MOMENT_EMPHASIS}>{chunks}</span>;
+ if (step === "repo") return <>{t.rich("repo.title", { name: repoName, em })}</>;
+ if (step === "agent") return <>{t.rich("agent.title", { em })}</>;
+ return <>{t.rich("yours.title", { em })}</>;
+}
+
+function StepLede({ step, fileCount, years }: { step: Step; fileCount: number; years: number | null }) {
+ const t = useTranslations("welcome");
+ if (step === "agent") return <>{t("agent.lede")}</>;
+ if (step === "yours") return <>{t("yours.lede")}</>;
+ return (
+ <>
+ {years != null
+ ? t("repo.lede", { files: fileCount, years })
+ : t("repo.ledeNoHistory", { files: fileCount })}
+ </>
+ );
+}
+
+/** Three short bars with their names: done, current, then upcoming. */
+function StepIndicator({ index }: { index: number }) {
+ const t = useTranslations("welcome");
+ return (
+ <ol aria-label={t("stepsLabel")} className="mt-4 flex flex-wrap gap-x-4 gap-y-1 text-xs">
+ {STEPS.map((s, i) => {
+ const state = i < index ? "done" : i === index ? "current" : "next";
+ return (
+ <li
+ key={s}
+ aria-current={state === "current" ? "step" : undefined}
+ className={`flex items-center gap-1.5 ${
+ state === "current"
+ ? "font-medium text-[var(--color-text-primary)]"
+ : "text-[var(--color-text-tertiary)]"
+ }`}
+ >
+ <span
+ aria-hidden
+ className={`inline-block h-0.5 w-4 ${
+ state === "current"
+ ? "bg-[var(--color-text-primary)]"
+ : state === "done"
+ ? "bg-[var(--color-success)]"
+ : "bg-[var(--color-border-hover)]"
+ }`}
+ />
+ {t(`steps.${s}`)}
+ {state === "done" && <span className="sr-only">{t("stepDone")}</span>}
+ </li>
+ );
+ })}
+ </ol>
+ );
+}
diff --git a/packages/web/src/components/welcome/welcome-moment.test.tsx b/packages/web/src/components/welcome/welcome-moment.test.tsx
new file mode 100644
index 000000000..887a73299
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-moment.test.tsx
@@ -0,0 +1,87 @@
+// @vitest-environment jsdom
+
+import React, { StrictMode } from "react";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { sessionMomentTaken } from "@/lib/release-moment";
+import { WelcomeMoment } from "./welcome-moment";
+
+const mocks = vi.hoisted(() => ({
+ search: "",
+ welcomeSeen: {} as Record<string, string>,
+ getRepoSetup: vi.fn(),
+ updateOnboardingState: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => new URLSearchParams(mocks.search),
+}));
+vi.mock("@/lib/api/setup", () => ({
+ getRepoSetup: mocks.getRepoSetup,
+ updateOnboardingState: mocks.updateOnboardingState,
+}));
+vi.mock("@/lib/api/meta", () => ({ getMetaVersion: async () => ({ server_version: "0.59.0" }) }));
+vi.mock("@/lib/api/dead-code", () => ({ getDeadCodeSummary: async () => Promise.reject(new Error("x")) }));
+vi.mock("@/lib/api/blast-radius", () => ({ analyzeBlastRadius: async () => Promise.reject(new Error("x")) }));
+vi.mock("@/lib/api/code-health", () => ({ getHealthCoverage: async () => Promise.reject(new Error("x")) }));
+vi.mock("@/lib/api/stats", () => ({ getStatsHighlights: async () => Promise.reject(new Error("x")) }));
+// The dialog itself is covered in welcome-dialog.test.tsx.
+vi.mock("./welcome-dialog", () => ({
+ WelcomeDialog: ({ open }: { open: boolean }) => (open ? <div role="dialog">welcome</div> : null),
+}));
+
+const FIGURES = { health: null, decisionsToReview: null, docPages: 10, coveragePct: null };
+
+function renderMoment() {
+ render(
+ <StrictMode>
+ <WelcomeMoment repoId="r1" repoName="orbit-api" fileCount={12} figures={FIGURES} hotspotPath={null} />
+ </StrictMode>,
+ );
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ mocks.search = "";
+ mocks.welcomeSeen = {};
+ mocks.getRepoSetup.mockImplementation(async () => ({
+ onboarding: { welcome_seen: mocks.welcomeSeen, hints_enabled: true, signed_in: false },
+ }));
+ mocks.updateOnboardingState.mockResolvedValue({});
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("WelcomeMoment", () => {
+ it("opens once for a new browser and records the repo, the version and the session", async () => {
+ renderMoment();
+ await screen.findByRole("dialog");
+ expect(mocks.updateOnboardingState).toHaveBeenCalledTimes(1);
+ expect(mocks.updateOnboardingState).toHaveBeenCalledWith({ welcome_seen_repo: "r1" });
+ expect(window.localStorage.getItem("repowise:last-seen-server-version")).toBe("0.59.0");
+ expect(sessionMomentTaken()).toBe(true);
+ });
+
+ it("stays shut for an existing user", async () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.58.0");
+ renderMoment();
+ await waitFor(() => expect(mocks.getRepoSetup).toHaveBeenCalled());
+ await new Promise((r) => setTimeout(r, 0));
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(mocks.updateOnboardingState).not.toHaveBeenCalled();
+ });
+
+ it("replays on demand with ?tour=1 without stamping a repo already seen", async () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.58.0");
+ mocks.search = "tour=1";
+ mocks.welcomeSeen = { r1: "2026-10-20T00:00:00Z" };
+ renderMoment();
+ await screen.findByRole("dialog");
+ expect(mocks.updateOnboardingState).not.toHaveBeenCalled();
+ expect(window.localStorage.getItem("repowise:last-seen-server-version")).toBe("0.58.0");
+ expect(sessionMomentTaken()).toBe(false);
+ });
+});
diff --git a/packages/web/src/components/welcome/welcome-moment.tsx b/packages/web/src/components/welcome/welcome-moment.tsx
new file mode 100644
index 000000000..75a635e1f
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-moment.tsx
@@ -0,0 +1,164 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useSearchParams } from "next/navigation";
+import { getRepoSetup, updateOnboardingState, type SetupResponse } from "@/lib/api/setup";
+import { getDeadCodeSummary } from "@/lib/api/dead-code";
+import { analyzeBlastRadius } from "@/lib/api/blast-radius";
+import { getHealthCoverage } from "@/lib/api/code-health";
+import { getStatsHighlights } from "@/lib/api/stats";
+import { getMetaVersion } from "@/lib/api/meta";
+import { isNewBrowser, markVersionSeen, sessionMomentTaken, takeSessionMoment } from "@/lib/release-moment";
+import {
+ decideWelcome,
+ historyYears,
+ welcomeLenses,
+ type WelcomeExtras,
+ type WelcomeFigures,
+ type WelcomeLens,
+} from "@/lib/welcome-moment";
+import { WelcomeDialog } from "./welcome-dialog";
+
+export interface WelcomeMomentProps {
+ repoId: string;
+ repoName: string;
+ fileCount: number;
+ figures: WelcomeFigures;
+ /** The busiest file: the risk card's change and an example question. */
+ hotspotPath: string | null;
+}
+
+interface Loaded {
+ setup: SetupResponse | null;
+ lenses: WelcomeLens[];
+ years: number | null;
+}
+
+const settled = <T,>(r: PromiseSettledResult<T>): T | null => (r.status === "fulfilled" ? r.value : null);
+
+/** The figures step 1 needs beyond what the overview loaded. Each one that
+ * fails is left out, and its card with it. */
+async function loadExtras(repoId: string, hotspotPath: string | null, needTests: boolean) {
+ const [dead, blast, coverage, stats] = await Promise.allSettled([
+ getDeadCodeSummary(repoId),
+ hotspotPath ? analyzeBlastRadius(repoId, { changed_files: [hotspotPath] }) : Promise.reject(),
+ needTests ? getHealthCoverage(repoId, { limit: 1, module_limit: 0 }) : Promise.reject(),
+ getStatsHighlights(repoId),
+ ]);
+ const d = settled(dead);
+ const unreachable = Number(d?.by_kind?.unreachable_file ?? 0);
+ const b = settled(blast);
+ const inferred = settled(coverage)?.inferred;
+ const extras: WelcomeExtras = {
+ // Never analysed reads as unmeasured, not as zero.
+ deadCode: d && (d.analyzed_at || d.total_findings > 0)
+ ? { files: unreachable, safe: d.safe_to_delete_count ?? 0 }
+ : null,
+ risk: b && hotspotPath ? { path: hotspotPath, reached: b.transitive_affected.length } : null,
+ testsReached: inferred ? { reached: inferred.files_reached, total: inferred.files_total } : null,
+ };
+ return { extras, years: historyYears(settled(stats)?.origin.age_days) };
+}
+
+/**
+ * Opens the welcome on the overview: once per repo per machine for a new
+ * browser, or on demand with `?tour=1`. An automatic open marks the repo seen
+ * on the server, stores the current version as seen so What's new stays
+ * quiet, and takes the session's one interruption.
+ */
+export function WelcomeMoment({ repoId, repoName, fileCount, figures, hotspotPath }: WelcomeMomentProps) {
+ const search = useSearchParams()?.toString() ?? "";
+ const [open, setOpen] = useState(false);
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+ const decided = useRef<string | null>(null);
+
+ // Once per repo and query: StrictMode runs effects twice in development,
+ // and a second run would stamp again. Not cancelled on cleanup for the
+ // same reason; a late result after unmount is simply never shown.
+ useEffect(() => {
+ const key = `${repoId}?${search}`;
+ if (decided.current === key) return;
+ decided.current = key;
+ void prepareWelcome({ repoId, search, fileCount, figures, hotspotPath }).then((next) => {
+ if (!next) return;
+ setLoaded(next);
+ setOpen(true);
+ dropTourParam();
+ });
+ }, [repoId, search, fileCount, figures, hotspotPath]);
+
+ if (!loaded) return null;
+ return (
+ <WelcomeDialog
+ open={open}
+ onOpenChange={setOpen}
+ repoId={repoId}
+ repoName={repoName}
+ fileCount={fileCount}
+ years={loaded.years}
+ lenses={loaded.lenses}
+ setup={loaded.setup}
+ hotspotPath={hotspotPath}
+ />
+ );
+}
+
+/** Drops `?tour=1` once the tour opens, so a reload does not replay it. */
+function dropTourParam(): void {
+ const url = new URL(window.location.href);
+ if (!url.searchParams.has("tour")) return;
+ url.searchParams.delete("tour");
+ window.history.replaceState(window.history.state, "", url);
+}
+
+/** Decides whether the welcome opens, stamps what an open records, and
+ * loads its figures. Null when it stays shut. */
+async function prepareWelcome({
+ repoId,
+ search,
+ fileCount,
+ figures,
+ hotspotPath,
+}: {
+ repoId: string;
+ search: string;
+ fileCount: number;
+ figures: WelcomeFigures;
+ hotspotPath: string | null;
+}): Promise<Loaded | null> {
+ const setup = await getRepoSetup(repoId).catch(() => null);
+ const seen = setup ? Boolean(setup.onboarding.welcome_seen?.[repoId]) : null;
+ const mode = decideWelcome({
+ search: search ? `?${search}` : "",
+ fileCount,
+ seen,
+ newBrowser: isNewBrowser(),
+ sessionTaken: sessionMomentTaken(),
+ });
+ if (mode === "none") return null;
+ if (mode === "auto") await stampAutoOpen(repoId);
+ // A first look through `?tour=1` (the first-index hand-off) still counts as
+ // seen; a replay from Setup changes nothing.
+ else if (seen === false) await stampRepoSeen(repoId);
+ const { extras, years } = await loadExtras(repoId, hotspotPath, figures.coveragePct == null);
+ return { setup, lenses: welcomeLenses(figures, extras), years };
+}
+
+/** Marks the repo's welcome seen on this machine. Best-effort: a failed
+ * write means it may open once more, never an error. */
+function stampRepoSeen(repoId: string): Promise<unknown> {
+ return updateOnboardingState({ welcome_seen_repo: repoId }).catch(() => undefined);
+}
+
+/** Before an automatic open: the repo seen, the session's one interruption
+ * taken, and the current version stored so What's new stays quiet. */
+async function stampAutoOpen(repoId: string): Promise<void> {
+ takeSessionMoment();
+ try {
+ const meta = await getMetaVersion();
+ if (meta.server_version) markVersionSeen(meta.server_version);
+ } catch {
+ /* no version to store: What's new still waits for the next session */
+ }
+ await stampRepoSeen(repoId);
+}
diff --git a/packages/web/src/components/welcome/welcome-step-agent.tsx b/packages/web/src/components/welcome/welcome-step-agent.tsx
new file mode 100644
index 000000000..54ace6999
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-step-agent.tsx
@@ -0,0 +1,193 @@
+"use client";
+
+import { useState } from "react";
+import { useFormatter, useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { AiPromptButton } from "@repowise-dev/ui/health/ai-prompt-button";
+import { CommandLine } from "@repowise-dev/ui/shared/command-line";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { connectSetupAgent, type SetupResponse } from "@/lib/api/setup";
+import { MOMENT_MICRO } from "@/components/layout/moment-shell";
+
+type SetupAgent = NonNullable<SetupResponse["agents"]>[number];
+
+const ROW = "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-t border-[var(--color-border-default)] py-2.5 max-[560px]:grid-cols-1";
+
+/** The first config file `repowise agents add` writes for this agent, if known. */
+function firstConfigFile(agent: SetupAgent): string | null {
+ for (const files of Object.values(agent.config_files ?? {})) {
+ if (files[0]) return files[0];
+ }
+ return null;
+}
+
+/** Copies `text`; false when the clipboard is blocked. */
+async function copyText(text: string): Promise<boolean> {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Step 2: the agents found on this machine, and two questions to try. */
+export function WelcomeStepAgent({
+ repoId,
+ setup,
+ hotspotPath,
+}: {
+ repoId: string;
+ setup: SetupResponse | null;
+ hotspotPath: string | null;
+}) {
+ const t = useTranslations("welcome.agent");
+ // Connected here, before the setup data catches up.
+ const [connected, setConnected] = useState<Record<string, boolean>>({});
+ const agents = (setup?.agents ?? []).filter((a) => a.installed || a.connected);
+ const questions = [
+ t("askRisk"),
+ hotspotPath ? t("askHotspot", { path: hotspotPath }) : t("askStart"),
+ ];
+
+ return (
+ <div>
+ {agents.length === 0 ? (
+ <p className="border-t border-[var(--color-border-default)] py-2.5 text-xs text-[var(--color-text-secondary)]">
+ {t("none")}
+ </p>
+ ) : (
+ agents.map((agent) => (
+ <AgentRow
+ key={agent.id}
+ repoId={repoId}
+ agent={agent}
+ connected={connected[agent.id] ?? agent.connected}
+ writesAllowed={setup?.writes_allowed ?? false}
+ callsKnown={setup?.calls_available ?? false}
+ onConnected={(value) => setConnected((c) => ({ ...c, [agent.id]: value }))}
+ />
+ ))
+ )}
+ <h3 className={`${MOMENT_MICRO} mt-4`}>{t("askLabel")}</h3>
+ <ul className="mt-2 flex flex-col gap-1.5">
+ {questions.map((q) => (
+ <li
+ key={q}
+ className="flex items-center justify-between gap-3 rounded-md border border-[var(--color-border-default)] bg-[var(--color-release-card)] px-2.5 py-2 text-[13px] text-[var(--color-text-primary)]"
+ >
+ <span className="min-w-0 [overflow-wrap:anywhere]">{q}</span>
+ <CopyQuestion text={q} />
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
+function AgentRow({
+ repoId,
+ agent,
+ connected,
+ writesAllowed,
+ callsKnown,
+ onConnected,
+}: {
+ repoId: string;
+ agent: SetupAgent;
+ connected: boolean;
+ writesAllowed: boolean;
+ /** False when the local call log could not be read: say nothing about calls. */
+ callsKnown: boolean;
+ onConnected: (value: boolean) => void;
+}) {
+ const t = useTranslations("welcome.agent");
+ const format = useFormatter();
+ const [busy, setBusy] = useState(false);
+ const name = agent.display_name;
+ const command = `repowise agents add --target=${agent.id}`;
+
+ async function connect() {
+ setBusy(true);
+ onConnected(true);
+ try {
+ const res = await connectSetupAgent(repoId, agent.id);
+ if (!res.ok) {
+ onConnected(false);
+ toast.error(t("connectFailed", { name }), res.message ? { description: res.message } : undefined);
+ }
+ } catch (e) {
+ onConnected(false);
+ toast.error(t("connectFailed", { name }), { description: toFriendlyMessage(e) });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function copyPrompt() {
+ const prompt = t("prompt", { name, command });
+ if (await copyText(prompt)) toast.success(t("promptCopied"));
+ }
+
+ const file = firstConfigFile(agent);
+ return (
+ <div className={ROW}>
+ <div className="min-w-0">
+ <h4 className="flex items-center gap-2 text-[13px] font-semibold text-[var(--color-text-primary)]">
+ <span
+ aria-hidden
+ className="h-[7px] w-[7px] shrink-0 rounded-full"
+ style={{ background: connected ? "var(--color-success)" : "var(--color-text-tertiary)" }}
+ />
+ {name}
+ </h4>
+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">
+ {connected
+ ? t("connected")
+ : file
+ ? t.rich("installed", { file, mono: (c) => <span className="font-mono">{c}</span> })
+ : t("installedNoFile")}
+ </p>
+ {!connected && !writesAllowed && <CommandLine command={command} />}
+ </div>
+ {connected ? (
+ callsKnown && (
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ {agent.first_call_at
+ ? t("firstCall", { when: format.relativeTime(new Date(agent.first_call_at)) })
+ : t("waiting")}
+ </span>
+ )
+ ) : (
+ <span className="flex flex-wrap items-center justify-end gap-1.5 max-[560px]:justify-start">
+ <AiPromptButton label={t("copyPrompt")} onClick={() => void copyPrompt()} />
+ {writesAllowed && (
+ <Button variant="outline" size="sm" disabled={busy} onClick={() => void connect()}>
+ {busy ? t("connecting") : t("connect")}
+ </Button>
+ )}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function CopyQuestion({ text }: { text: string }) {
+ const t = useTranslations("welcome.agent");
+ const [copied, setCopied] = useState(false);
+ return (
+ <button
+ type="button"
+ onClick={async () => {
+ if (!(await copyText(text))) return;
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1600);
+ }}
+ aria-label={copied ? t("copied") : t("copyQuestion", { question: text })}
+ className="shrink-0 rounded text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {copied ? t("copied") : t("copy")}
+ </button>
+ );
+}
diff --git a/packages/web/src/components/welcome/welcome-step-repo.tsx b/packages/web/src/components/welcome/welcome-step-repo.tsx
new file mode 100644
index 000000000..b71cedd43
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-step-repo.tsx
@@ -0,0 +1,177 @@
+"use client";
+
+import Link from "next/link";
+import type { ReactNode } from "react";
+import { useFormatter, useTranslations } from "next-intl";
+import { seriesColor } from "@repowise-dev/ui/shared/series";
+import type { HealthBand } from "@repowise-dev/types/health";
+import { commitsViewHref } from "@/lib/changes";
+import type { WelcomeLens } from "@/lib/welcome-moment";
+import { MOMENT_CARD, MOMENT_ENTER, MOMENT_MICRO } from "@/components/layout/moment-shell";
+
+/** Series index per lens, as the design colours them. */
+const SERIES_OF: Record<WelcomeLens["key"], number> = {
+ health: 2,
+ deadCode: 3,
+ risk: 4,
+ decisions: 1,
+ docs: 5,
+ tests: 0,
+ testsInferred: 0,
+};
+
+const BAND_DOT: Record<HealthBand, string> = {
+ excellent: "var(--color-success)",
+ good: "var(--color-success)",
+ fair: "var(--color-warning)",
+ needs_work: "var(--color-warning)",
+ at_risk: "var(--color-error)",
+};
+
+const LINK =
+ "mt-1.5 self-start rounded text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px] hover:decoration-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
+
+interface CardText {
+ label: string;
+ value: string;
+ unit?: ReactNode;
+ caption: ReactNode;
+ href: string;
+ open: string;
+}
+
+/** Step 1: one card per lens the index measured. */
+export function WelcomeStepRepo({
+ repoId,
+ lenses,
+ onNavigate,
+}: {
+ repoId: string;
+ lenses: WelcomeLens[];
+ onNavigate: () => void;
+}) {
+ const t = useTranslations("welcome.repo");
+ const text = useLensText(repoId);
+ if (lenses.length === 0) return null;
+ return (
+ <section aria-labelledby="welcome-standout">
+ <h3 id="welcome-standout" className={`${MOMENT_MICRO} mb-2`}>
+ {t("standout")}
+ </h3>
+ <ul className="grid grid-cols-1 gap-2.5 min-[561px]:grid-cols-2">
+ {lenses.map((lens) => {
+ const c = text(lens);
+ return (
+ <li
+ key={lens.key}
+ className={`${MOMENT_CARD} flex min-w-0 flex-col gap-0.5 px-3 py-2.5 ${MOMENT_ENTER}`}
+ style={{ borderLeftColor: seriesColor(SERIES_OF[lens.key]) }}
+ >
+ <span className={MOMENT_MICRO}>{c.label}</span>
+ <span className="flex items-baseline gap-2 text-[22px] font-semibold tabular-nums tracking-tight text-[var(--color-text-primary)]">
+ {c.value}
+ {c.unit && (
+ <span className="text-xs font-normal text-[var(--color-text-secondary)]">{c.unit}</span>
+ )}
+ </span>
+ <p className="text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere] [text-wrap:pretty]">
+ {c.caption}
+ </p>
+ <Link href={c.href} onClick={onNavigate} className={LINK}>
+ {c.open}
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
+
+const mono = (chunks: ReactNode) => <span className="font-mono text-[11.5px]">{chunks}</span>;
+
+/** The words and route for each lens. */
+function useLensText(repoId: string): (lens: WelcomeLens) => CardText {
+ const t = useTranslations("welcome.repo");
+ const format = useFormatter();
+ const n = (v: number) => format.number(v);
+ const base = `/repos/${encodeURIComponent(repoId)}`;
+ return (lens) => {
+ switch (lens.key) {
+ case "health":
+ return {
+ label: t("health.label"),
+ value: lens.score.toFixed(1),
+ unit: lens.band && (
+ <span className="inline-flex items-center gap-1.5">
+ <span aria-hidden className="h-[7px] w-[7px] rounded-full" style={{ background: BAND_DOT[lens.band] }} />
+ {t(`band.${lens.band}`)}
+ </span>
+ ),
+ caption:
+ lens.worstPath && lens.worstScore != null
+ ? t.rich("health.caption", { path: lens.worstPath, score: lens.worstScore.toFixed(1), mono })
+ : t("health.captionNone"),
+ href: `${base}/code-health`,
+ open: t("health.open"),
+ };
+ case "deadCode":
+ return {
+ label: t("deadCode.label"),
+ value: n(lens.files),
+ unit: t("deadCode.unit", { count: lens.files }),
+ caption:
+ lens.files === 0
+ ? t("deadCode.captionNone")
+ : `${t("deadCode.caption")}${lens.safe > 0 ? ` ${t("deadCode.safe", { count: lens.safe })}` : ""}`,
+ href: `${base}/dead-code`,
+ open: t("deadCode.open"),
+ };
+ case "risk":
+ return {
+ label: t("risk.label"),
+ value: n(lens.reached),
+ unit: t("risk.unit", { count: lens.reached }),
+ caption: t.rich("risk.caption", { path: lens.path, mono }),
+ href: commitsViewHref(repoId, "review"),
+ open: t("risk.open"),
+ };
+ case "decisions":
+ return {
+ label: t("decisions.label"),
+ value: n(lens.count),
+ unit: t("decisions.unit"),
+ caption: t("decisions.caption"),
+ href: `${base}/decisions`,
+ open: t("decisions.open"),
+ };
+ case "docs":
+ return {
+ label: t("docs.label"),
+ value: n(lens.pages),
+ unit: t("docs.unit", { count: lens.pages }),
+ caption: t("docs.caption"),
+ href: `${base}/docs`,
+ open: t("docs.open"),
+ };
+ case "tests":
+ return {
+ label: t("tests.label"),
+ value: `${lens.measuredPct.toFixed(0)}%`,
+ unit: t("tests.measured"),
+ caption: t("tests.measuredCaption"),
+ href: `${base}/tests`,
+ open: t("tests.open"),
+ };
+ case "testsInferred":
+ return {
+ label: t("tests.label"),
+ value: n(lens.reached),
+ unit: t("tests.inferredUnit", { total: n(lens.total) }),
+ caption: t("tests.inferredCaption"),
+ href: `${base}/tests`,
+ open: t("tests.open"),
+ };
+ }
+ };
+}
diff --git a/packages/web/src/components/welcome/welcome-step-yours.tsx b/packages/web/src/components/welcome/welcome-step-yours.tsx
new file mode 100644
index 000000000..98736bbe8
--- /dev/null
+++ b/packages/web/src/components/welcome/welcome-step-yours.tsx
@@ -0,0 +1,181 @@
+"use client";
+
+import { useState } from "react";
+import useSWR from "swr";
+import { useTranslations } from "next-intl";
+import { toast } from "sonner";
+import { Button } from "@repowise-dev/ui/ui/button";
+import { Switch } from "@repowise-dev/ui/ui/switch";
+import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
+import { CommandLine } from "@repowise-dev/ui/shared/command-line";
+import { orderModelSources, type ModelSource } from "@repowise-dev/ui/settings";
+import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
+import { setSetupHook, type SetupResponse } from "@/lib/api/setup";
+import { getProviders } from "@/lib/api/providers";
+import { hostedLink } from "@/lib/hosted";
+import { useModelUpgrade } from "@/components/model-upgrade/model-upgrade";
+import { MOMENT_MICRO } from "@/components/layout/moment-shell";
+
+const ROW = "grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 border-t border-[var(--color-border-default)] py-2.5";
+const DOT = "h-[7px] w-[7px] shrink-0 rounded-full";
+
+/** Whether to offer hosted: tips on, and not already signed in. */
+export function showsHostedRow(setup: SetupResponse | null): boolean {
+ return !!setup && setup.onboarding.hints_enabled && !setup.onboarding.signed_in;
+}
+
+/** Step 3: a model, sync, and hosted for a team. Every part is optional. */
+export function WelcomeStepYours({ repoId, setup }: { repoId: string; setup: SetupResponse | null }) {
+ const t = useTranslations("welcome.yours");
+ return (
+ <div>
+ {setup && setup.model.docs_mode !== "llm" && <ModelBox repoId={repoId} />}
+ <SyncRow repoId={repoId} setup={setup} />
+ {showsHostedRow(setup) && (
+ <div className={ROW}>
+ <div className="min-w-0">
+ <h4 className="flex items-center gap-2 text-[13px] font-semibold text-[var(--color-text-primary)]">
+ <span aria-hidden className={DOT} style={{ background: "var(--color-info)" }} />
+ {t("teamTitle")}
+ </h4>
+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)]">{t("teamBody")}</p>
+ </div>
+ <a
+ href={hostedLink("welcome", "team")}
+ target="_blank"
+ rel="noreferrer"
+ className="rounded text-xs font-medium text-[var(--color-text-primary)] underline decoration-[var(--color-border-hover)] underline-offset-[3px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {t("teamLink")}
+ </a>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Sources found on this machine. Shares the sheet's cache key, so opening
+ * the sheet afterwards does not ask each agent CLI again. */
+function useDetectedSources(repoId: string): ModelSource[] {
+ const { data } = useSWR(
+ ["/api/providers", repoId, "detect"],
+ () => getProviders(repoId, { detect: true }),
+ { revalidateOnFocus: false },
+ );
+ return orderModelSources(data?.providers ?? []).filter((s) => s.detected);
+}
+
+function ModelBox({ repoId }: { repoId: string }) {
+ const t = useTranslations("welcome.yours");
+ const tm = useTranslations("modelUpgrade");
+ const { openSheet, sheet } = useModelUpgrade(repoId);
+ const detected = useDetectedSources(repoId);
+ const sourceName = (s: ModelSource) =>
+ s.kind === "cli" ? tm("cliSource", { name: s.name }) : s.kind === "local" ? tm("localSource", { name: s.name }) : tm("keySource", { name: s.name });
+ const gets = [t("gets.docs"), t("gets.chat"), t("gets.answers"), t("gets.local")];
+
+ return (
+ <section
+ aria-labelledby="welcome-model"
+ className="mb-3 rounded-[10px] border border-[color-mix(in_srgb,var(--color-model)_30%,transparent)] bg-[var(--color-model-muted)] p-3.5"
+ >
+ <div className="flex items-baseline justify-between gap-2.5">
+ <h4 id="welcome-model" className="text-[13.5px] font-semibold text-[var(--color-text-primary)]">
+ {t("modelTitle")}
+ </h4>
+ <span className={MOMENT_MICRO}>{t("optional")}</span>
+ </div>
+ <ul className="my-2.5 grid grid-cols-1 gap-x-3.5 gap-y-1.5 text-xs text-[var(--color-text-secondary)] min-[561px]:grid-cols-2">
+ {gets.map((g) => (
+ <li key={g} className="flex items-baseline gap-2">
+ <span aria-hidden className={`${DOT} translate-y-[-1px]`} style={{ background: "var(--color-model)" }} />
+ {g}
+ </li>
+ ))}
+ </ul>
+ {detected.length > 0 && (
+ <div className="mb-3">
+ <p className={`${MOMENT_MICRO} mb-1`}>{t("detectedLabel")}</p>
+ <ul className="flex flex-col gap-1">
+ {detected.map((s) => (
+ <li
+ key={s.id}
+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-release-card)] px-2.5 py-1.5 text-[12.5px] text-[var(--color-text-primary)]"
+ >
+ {sourceName(s)}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <div className="flex justify-end">
+ <Button
+ size="sm"
+ onClick={openSheet}
+ className="h-8 bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)] focus-visible:ring-[var(--color-model)] max-[560px]:w-full"
+ >
+ {tm("write")}
+ </Button>
+ </div>
+ {sheet}
+ </section>
+ );
+}
+
+function SyncRow({ repoId, setup }: { repoId: string; setup: SetupResponse | null }) {
+ const t = useTranslations("welcome.yours");
+ const tc = useTranslations("common");
+ // Local until the setup data catches up with a change made here.
+ const [on, setOn] = useState<boolean | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [confirmOff, setConfirmOff] = useState(false);
+ const installed = on ?? setup?.sync.installed ?? false;
+ const writesAllowed = setup?.writes_allowed ?? false;
+
+ async function apply(enabled: boolean) {
+ setBusy(true);
+ setOn(enabled);
+ try {
+ const res = await setSetupHook(repoId, "post-commit", enabled);
+ if (!res.ok) {
+ setOn(!enabled);
+ toast.error(t("syncFailed"), res.message ? { description: res.message } : undefined);
+ }
+ } catch (e) {
+ setOn(!enabled);
+ toast.error(t("syncFailed"), { description: toFriendlyMessage(e) });
+ } finally {
+ setBusy(false);
+ setConfirmOff(false);
+ }
+ }
+
+ return (
+ <div className={ROW}>
+ <div className="min-w-0">
+ <h4 id="welcome-sync" className="text-[13px] font-semibold text-[var(--color-text-primary)]">
+ {t("syncTitle")}
+ </h4>
+ <p className="mt-0.5 text-xs text-[var(--color-text-secondary)]">{t("syncBody")}</p>
+ {!writesAllowed && !installed && <CommandLine command="repowise hook install" />}
+ </div>
+ <Switch
+ aria-labelledby="welcome-sync"
+ checked={installed}
+ disabled={!writesAllowed || busy}
+ onCheckedChange={(next) => (next ? void apply(true) : setConfirmOff(true))}
+ className="data-[state=checked]:bg-[var(--color-success)]"
+ />
+ <ConfirmDialog
+ open={confirmOff}
+ onOpenChange={setConfirmOff}
+ title={t("syncOffTitle")}
+ description={t("syncOffBody")}
+ confirmLabel={t("syncOffConfirm")}
+ cancelLabel={tc("cancel")}
+ loading={busy}
+ onConfirm={() => apply(false)}
+ />
+ </div>
+ );
+}
diff --git a/packages/web/src/lib/release-moment.test.ts b/packages/web/src/lib/release-moment.test.ts
index 1711eba37..2988430d8 100644
--- a/packages/web/src/lib/release-moment.test.ts
+++ b/packages/web/src/lib/release-moment.test.ts
@@ -21,7 +21,10 @@ import {
const HL = (href: string | null) => ({ id: "x", title: "X", blurb: "", href });
-beforeEach(() => window.localStorage.clear());
+beforeEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+});
describe("upgradeMoment", () => {
it("shows nothing on a first visit, a repeat, or a downgrade", () => {
diff --git a/packages/web/src/lib/release-moment.ts b/packages/web/src/lib/release-moment.ts
index b4b7370a1..aa2b334f4 100644
--- a/packages/web/src/lib/release-moment.ts
+++ b/packages/web/src/lib/release-moment.ts
@@ -6,7 +6,9 @@
* What's new dialog once, and a patch shows a quiet "Updated to vX" note. A
* fresh browser stores the version and shows nothing; a browser with earlier
* repowise state but no stored version counts as an upgrade. Highlighted pages carry a
- * "New" mark in the nav until visited, or for 14 days.
+ * "New" mark in the nav until visited, or for 14 days. The welcome
+ * (`welcome-moment.ts`) shares a session guard with it: one interruption per
+ * session.
*
* Every storage call is best-effort: blocked site data means no moment, never
* an error.
@@ -18,8 +20,12 @@ const LAST_SEEN_KEY = "repowise:last-seen-server-version";
const NEW_SURFACES_KEY = "repowise:new-surfaces";
const NEW_SURFACES_EVENT = "repowise:new-surfaces";
const LAST_REPO_KEY = "repowise:last-repo";
+/** Set once, on the first visit of a browser with no earlier repowise use. */
+const NEW_BROWSER_KEY = "repowise:new-browser";
+/** One interruption per session: What's new, a patch note or the welcome. */
+const SESSION_MOMENT_KEY = "repowise:session-moment";
/** Keys this module writes itself, which say nothing about earlier use. */
-const OWN_KEYS = new Set([LAST_SEEN_KEY, NEW_SURFACES_KEY, LAST_REPO_KEY]);
+const OWN_KEYS = new Set([LAST_SEEN_KEY, NEW_SURFACES_KEY, LAST_REPO_KEY, NEW_BROWSER_KEY]);
export const NEW_MARK_DAYS = 14;
export type UpgradeMoment = "none" | "dialog" | "notice";
@@ -78,7 +84,7 @@ function write(key: string, value: string): void {
* app's own keys (banner dismissals, chat and docs state). Browsers that
* predate the last-seen key would otherwise count as first visits and never
* see the release they upgraded to. */
-function hasPriorUse(): boolean {
+export function hasPriorUse(): boolean {
try {
const store = window.localStorage;
for (let i = 0; i < store.length; i++) {
@@ -98,10 +104,49 @@ export function takeUpgradeMoment(current: string, hasHighlights: boolean): Upgr
// "0" stands for "some earlier version": prior use with nothing stored.
const stored = read(LAST_SEEN_KEY) ?? (hasPriorUse() ? "0" : null);
const moment = upgradeMoment(stored, current, hasHighlights);
- write(LAST_SEEN_KEY, current);
+ markVersionSeen(current);
return moment;
}
+/** Stores `version` as seen, so the release moment stays quiet for it. */
+export function markVersionSeen(version: string): void {
+ // Whichever moment stores the first version records a new browser.
+ if (isNewBrowser()) write(NEW_BROWSER_KEY, "1");
+ write(LAST_SEEN_KEY, version);
+}
+
+/** Whether this browser started out with no repowise use: a first visit now,
+ * or one recorded by an earlier visit. A browser that predates this mark has
+ * a stored version or other repowise state, so an upgrading user never
+ * counts as new. */
+export function isNewBrowser(): boolean {
+ if (read(NEW_BROWSER_KEY) === "1") return true;
+ return read(LAST_SEEN_KEY) === null && !hasPriorUse();
+}
+
+// --- One moment per session ---------------------------------------------------
+
+/** Fallback for blocked session storage: the guard then lasts for this page load. */
+let sessionMomentFallback = false;
+
+/** Whether What's new, a patch note or the welcome already showed this session. */
+export function sessionMomentTaken(): boolean {
+ try {
+ return window.sessionStorage.getItem(SESSION_MOMENT_KEY) === "1";
+ } catch {
+ return sessionMomentFallback;
+ }
+}
+
+/** Records that this session had its one interruption. */
+export function takeSessionMoment(): void {
+ try {
+ window.sessionStorage.setItem(SESSION_MOMENT_KEY, "1");
+ } catch {
+ sessionMomentFallback = true;
+ }
+}
+
// --- "New" marks ------------------------------------------------------------
export interface NewSurfaces {
@@ -204,7 +249,8 @@ export function previewMoment(search: string): UpgradeMoment | null {
}
/** The moment due on load: a `?whats-new=` replay, or the real upgrade check,
- * which also starts the "New" marks for that release. */
+ * which also starts the "New" marks for that release. When the welcome
+ * already showed this session, the upgrade waits for the next one. */
export function decideMoment(
version: string,
highlights: ChangelogHighlight[],
@@ -212,8 +258,12 @@ export function decideMoment(
): { moment: UpgradeMoment; preview: boolean } {
const replay = previewMoment(search);
if (replay) return { moment: replay, preview: true };
+ if (sessionMomentTaken()) return { moment: "none", preview: false };
const moment = takeUpgradeMoment(version, highlights.length > 0);
- if (moment !== "none") startNewSurfaces(version, highlights);
+ if (moment !== "none") {
+ startNewSurfaces(version, highlights);
+ takeSessionMoment();
+ }
return { moment, preview: false };
}
diff --git a/packages/web/src/lib/welcome-moment.test.ts b/packages/web/src/lib/welcome-moment.test.ts
new file mode 100644
index 000000000..0c03fbf4a
--- /dev/null
+++ b/packages/web/src/lib/welcome-moment.test.ts
@@ -0,0 +1,166 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it } from "vitest";
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import {
+ decideMoment,
+ isNewBrowser,
+ markVersionSeen,
+ sessionMomentTaken,
+ takeSessionMoment,
+ takeUpgradeMoment,
+} from "./release-moment";
+import {
+ decideWelcome,
+ historyYears,
+ welcomeFigures,
+ welcomeLenses,
+ type WelcomeExtras,
+ type WelcomeFigures,
+ type WelcomeOpenInput,
+} from "./welcome-moment";
+
+beforeEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+});
+
+const NEW_USER: WelcomeOpenInput = {
+ search: "",
+ fileCount: 1284,
+ seen: false,
+ newBrowser: true,
+ sessionTaken: false,
+};
+
+describe("decideWelcome", () => {
+ it("opens once for a new browser on an indexed, unseen repo", () => {
+ expect(decideWelcome(NEW_USER)).toBe("auto");
+ });
+
+ it("never opens by itself for an existing user", () => {
+ expect(decideWelcome({ ...NEW_USER, newBrowser: false })).toBe("none");
+ });
+
+ it("stays shut once seen, before the seen mark is known, and before a first index", () => {
+ expect(decideWelcome({ ...NEW_USER, seen: true })).toBe("none");
+ expect(decideWelcome({ ...NEW_USER, seen: null })).toBe("none");
+ expect(decideWelcome({ ...NEW_USER, fileCount: 0 })).toBe("none");
+ });
+
+ it("waits for the next session when What's new already showed", () => {
+ expect(decideWelcome({ ...NEW_USER, sessionTaken: true })).toBe("none");
+ });
+
+ it("opens on demand with ?tour=1 past every guard", () => {
+ expect(
+ decideWelcome({ search: "?tour=1", fileCount: 0, seen: true, newBrowser: false, sessionTaken: true }),
+ ).toBe("tour");
+ expect(decideWelcome({ ...NEW_USER, newBrowser: false, search: "?tour=0" })).toBe("none");
+ });
+});
+
+describe("new browser and the session guard", () => {
+ it("a first visit counts as new, and stays new after the release moment stores a version", () => {
+ expect(isNewBrowser()).toBe(true);
+ takeUpgradeMoment("0.59.0", true);
+ expect(isNewBrowser()).toBe(true);
+ });
+
+ it("stays new when the welcome stores the version before the release moment runs", () => {
+ markVersionSeen("0.59.0");
+ expect(isNewBrowser()).toBe(true);
+ });
+
+ it("a browser with a stored version or earlier repowise state is an existing user", () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.58.0");
+ expect(isNewBrowser()).toBe(false);
+ window.localStorage.clear();
+ window.localStorage.setItem("repowise:locale", "en");
+ expect(isNewBrowser()).toBe(false);
+ takeUpgradeMoment("0.59.0", true);
+ expect(isNewBrowser()).toBe(false);
+ });
+
+ it("What's new takes the session, so the welcome waits", () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.58.0");
+ expect(decideMoment("0.59.0", [], "").moment).toBe("dialog");
+ expect(sessionMomentTaken()).toBe(true);
+ expect(decideWelcome({ ...NEW_USER, sessionTaken: sessionMomentTaken() })).toBe("none");
+ });
+
+ it("the welcome takes the session, so the release moment waits without using up the upgrade", () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.58.0");
+ takeSessionMoment();
+ expect(decideMoment("0.59.0", [], "")).toEqual({ moment: "none", preview: false });
+ expect(window.localStorage.getItem("repowise:last-seen-server-version")).toBe("0.58.0");
+ // A replay still works.
+ expect(decideMoment("0.59.0", [], "?whats-new=preview").moment).toBe("dialog");
+ });
+});
+
+const FIGURES: WelcomeFigures = {
+ health: { score: 7.4, band: "good", worstPath: "a.py", worstScore: 3.1 },
+ decisionsToReview: 14,
+ docPages: 412,
+ coveragePct: null,
+};
+const EXTRAS: WelcomeExtras = {
+ deadCode: { files: 38, safe: 12 },
+ risk: { path: "auth/session.py", reached: 214 },
+ testsReached: { reached: 61, total: 100 },
+};
+
+describe("welcomeLenses", () => {
+ it("shows all six lenses in order when everything was measured", () => {
+ expect(welcomeLenses(FIGURES, EXTRAS).map((l) => l.key)).toEqual([
+ "health",
+ "deadCode",
+ "risk",
+ "decisions",
+ "docs",
+ "testsInferred",
+ ]);
+ });
+
+ it("drops every lens whose value was not measured", () => {
+ const none = welcomeLenses(
+ { health: null, decisionsToReview: null, docPages: null, coveragePct: null },
+ { deadCode: null, risk: null, testsReached: null },
+ );
+ expect(none).toEqual([]);
+ const partial = welcomeLenses(
+ { ...FIGURES, docPages: 0 },
+ { ...EXTRAS, risk: { path: "x.py", reached: 0 }, testsReached: { reached: 0, total: 0 } },
+ );
+ expect(partial.map((l) => l.key)).toEqual(["health", "deadCode", "decisions"]);
+ });
+
+ it("prefers measured coverage over the inferred map", () => {
+ const lenses = welcomeLenses({ ...FIGURES, coveragePct: 72.4 }, EXTRAS);
+ expect(lenses.at(-1)).toEqual({ key: "tests", measuredPct: 72.4 });
+ });
+});
+
+describe("welcomeFigures", () => {
+ it("leaves out what the payload does not carry", () => {
+ const summary = {
+ health: { average_health: null, worst_performer_path: null, worst_performer_score: null },
+ stats: {},
+ } as unknown as OverviewSummaryResponse;
+ expect(welcomeFigures(summary)).toEqual({
+ health: null,
+ decisionsToReview: null,
+ docPages: null,
+ coveragePct: null,
+ });
+ });
+});
+
+describe("historyYears", () => {
+ it("counts whole years and drops anything under one", () => {
+ expect(historyYears(9 * 365 + 20)).toBe(9);
+ expect(historyYears(200)).toBeNull();
+ expect(historyYears(null)).toBeNull();
+ });
+});
diff --git a/packages/web/src/lib/welcome-moment.ts b/packages/web/src/lib/welcome-moment.ts
new file mode 100644
index 000000000..e95675cbc
--- /dev/null
+++ b/packages/web/src/lib/welcome-moment.ts
@@ -0,0 +1,113 @@
+/**
+ * The welcome: when it opens, and what its first step shows.
+ *
+ * It opens by itself once per repo per machine, on the overview, after a
+ * first index, for a browser that started out with no repowise use. An
+ * existing user who upgrades never gets it on their own; they hear about the
+ * new setup through What's new and can take the tour from Setup. It shares
+ * the release moment's session guard, so at most one of them interrupts a
+ * session. `?tour=1` opens it on demand past every guard.
+ */
+
+import type { HealthBand } from "@repowise-dev/types/health";
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+
+export type WelcomeOpen = "none" | "auto" | "tour";
+
+export interface WelcomeOpenInput {
+ /** `window.location.search`, or the route's search params as a string. */
+ search: string;
+ fileCount: number;
+ /** The server's per-machine mark for this repo; null while unknown. */
+ seen: boolean | null;
+ /** `isNewBrowser()`: no repowise use before this browser's first visit. */
+ newBrowser: boolean;
+ /** `sessionMomentTaken()`: What's new or a patch note already showed. */
+ sessionTaken: boolean;
+}
+
+/** Whether the welcome opens now, and how. */
+export function decideWelcome(input: WelcomeOpenInput): WelcomeOpen {
+ if (new URLSearchParams(input.search).get("tour") === "1") return "tour";
+ if (input.fileCount <= 0 || input.seen !== false) return "none";
+ if (!input.newBrowser || input.sessionTaken) return "none";
+ return "auto";
+}
+
+// --- Step 1: the lens cards ---------------------------------------------------
+
+/** What the overview already loaded, read on the server. */
+export interface WelcomeFigures {
+ health: {
+ score: number;
+ band: HealthBand | null;
+ worstPath: string | null;
+ worstScore: number | null;
+ } | null;
+ /** Decision candidates awaiting review; null when the store is absent. */
+ decisionsToReview: number | null;
+ docPages: number | null;
+ /** Measured line coverage from the latest report, when there is one. */
+ coveragePct: number | null;
+}
+
+/** Step 1's figures from the overview payload. Absent fields stay null, so
+ * their cards drop out. */
+export function welcomeFigures(summary: OverviewSummaryResponse): WelcomeFigures {
+ const { health, stats, explore } = summary;
+ return {
+ health:
+ health.average_health != null
+ ? {
+ score: health.average_health,
+ band: health.band ?? null,
+ worstPath: health.worst_performer_path,
+ worstScore: health.worst_performer_score,
+ }
+ : null,
+ decisionsToReview: explore?.decisions?.candidates ?? null,
+ docPages: stats.doc_page_count ?? null,
+ coveragePct: explore?.coverage?.line_coverage_pct ?? null,
+ };
+}
+
+/** Fetched when the welcome opens; each is null when it could not be read. */
+export interface WelcomeExtras {
+ deadCode: { files: number; safe: number } | null;
+ risk: { path: string; reached: number } | null;
+ testsReached: { reached: number; total: number } | null;
+}
+
+export type WelcomeLens =
+ | { key: "health"; score: number; band: HealthBand | null; worstPath: string | null; worstScore: number | null }
+ | { key: "deadCode"; files: number; safe: number }
+ | { key: "risk"; path: string; reached: number }
+ | { key: "decisions"; count: number }
+ | { key: "docs"; pages: number }
+ | { key: "tests"; measuredPct: number }
+ | { key: "testsInferred"; reached: number; total: number };
+
+/**
+ * The cards step 1 shows, in the design's order. A lens whose value was not
+ * measured is left out, never shown as zero.
+ */
+export function welcomeLenses(figures: WelcomeFigures, extras: WelcomeExtras): WelcomeLens[] {
+ const lenses: WelcomeLens[] = [];
+ if (figures.health) lenses.push({ key: "health", ...figures.health });
+ if (extras.deadCode) lenses.push({ key: "deadCode", ...extras.deadCode });
+ if (extras.risk && extras.risk.reached > 0) lenses.push({ key: "risk", ...extras.risk });
+ if (figures.decisionsToReview != null) lenses.push({ key: "decisions", count: figures.decisionsToReview });
+ if (figures.docPages) lenses.push({ key: "docs", pages: figures.docPages });
+ if (figures.coveragePct != null) lenses.push({ key: "tests", measuredPct: figures.coveragePct });
+ else if (extras.testsReached && extras.testsReached.total > 0) {
+ lenses.push({ key: "testsInferred", ...extras.testsReached });
+ }
+ return lenses;
+}
+
+/** Whole years between the first commit and now; null under a year or unknown. */
+export function historyYears(ageDays: number | null | undefined): number | null {
+ if (ageDays == null) return null;
+ const years = Math.floor(ageDays / 365);
+ return years >= 1 ? years : null;
+}