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): what's new after every upgrade, with highlights and the numbers (#3874)

Raghav Chamadiya846e24abb389
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 65088a2a6..e73a9bdca 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,11 +6,34 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
<!-- Use `git-cliff` to auto-generate entries from conventional commits -->
+<!-- A minor release opens with a short summary, then `### Highlights` (3-5 bullets shaped `- **Title** · one-line blurb. → /route`; the route is optional and `:id` stands for the current repository) and `### By the numbers` from `python scripts/release_stats.py`. The web UI and `repowise whats-new` show both. -->
---
## [Unreleased]
+Chat draws any chart of your repository, from bars and lines to donuts, treemaps and heatmaps, and every chart in the web UI shares one palette. Models and base URLs are set from Settings with live model lists, so a local server such as LM Studio is one form away, and a failed sync says what went wrong and how to fix it. Every merged change becomes a Change Record with its evidence, and the Commits page groups commits by change.
+
+### Highlights
+
+- **Charts in chat** · Ask for any chart of your files, findings, changes, health trend, coverage, dead code, dependencies or layers, drawn as bars, lines, donuts, treemaps or heatmaps. → /repos/:id/chat
+- **Models from Settings, with live lists** · Pick a model from the provider's live list or type any id, and point repowise at LM Studio or another local OpenAI-compatible server with no key. → /settings
+- **Sync failures explain themselves** · A rejected key, rate limit, unreachable base URL or missing model shows on the sync with a short hint saying what to do. → /repos/:id/settings
+- **Commits grouped by change** · Every merged change is a Change Record with its evidence checklist, and the Commits page groups commits by the change that landed them. → /repos/:id/commits
+- **One palette for every chart** · Charts and share bars draw from the same eight series colours, and a commit type keeps its colour on every chart.
+
+### By the numbers
+
+In the 3 days since 0.56.0:
+
+- **205 pull requests** merged, from **24 contributors**, **11 of them first-time contributors**
+- **1,226 files** changed, **+103,206 / -11,127** lines
+- **147 fixes, 45 features**, 4 refactors and 6 documentation changes
+- **437 test files** touched, **144** of them new
+- **25 issues** closed
+
+Thank you to everyone who built this release with us.
+
### Changed
- **Charts are in colour again, from one palette.** Every chart and share bar in the web UI draws from the same eight series colours, a commit type keeps one colour on every chart, health and risk charts keep their green, amber and red, heatmaps step through the accent orange, and chat charts sit on the conversation without a card around them.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index ec004e8bd..3d90ec2c8 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2281,7 +2281,7 @@ version as seen. Works offline from the changelog bundled with the install.
| `--all` | Show the full changelog history |
| `--format` | `table` (default) or `json` |
-JSON carries every selected release; the panel caps at 5 releases and 8 bullets each.
+Each release leads with its highlights and a one-line "By the numbers" (pull requests, contributors, files and lines changed). JSON carries every selected release with its `summary`, `highlights` and `stats`; the panel caps at 5 releases and 8 bullets each.
```bash
repowise whats-new # what changed since you last looked
diff --git a/docs/reference/UPGRADING.md b/docs/reference/UPGRADING.md
index 43c0a7493..63c36c27e 100644
--- a/docs/reference/UPGRADING.md
+++ b/docs/reference/UPGRADING.md
@@ -19,7 +19,7 @@ When you run `repowise update` (or `repowise serve`) after upgrading, repowise:
1. **Reads your store's format version** and compares it to the running build. The on-disk store records which version wrote it, so repowise knows exactly what, if anything, an upgrade needs.
2. **Applies any automatic, no-cost adjustments in place.** New database columns are back-filled automatically. If your embedding model changed, vectors are re-embedded for you (no LLM calls). You don't run anything.
3. **Keeps your parse cache warm.** Ordinary releases do not invalidate cached work, so updates stay fast.
-4. **Shows you what changed.** A short "what's new" summary appears for the versions you crossed, and `repowise whats-new` shows release notes any time. The web UI surfaces a dismissible "update available" banner and a what's-new view.
+4. **Shows you what changed.** A short "what's new" summary appears for the versions you crossed, and `repowise whats-new` shows release notes any time. The web UI surfaces a dismissible "update available" banner that names the newer release's highlights, and after an upgrade it opens What's new once for a minor release (a short note for a patch), with the release's highlights, its numbers and every change.
## When a reindex is recommended
diff --git a/packages/api-client/src/meta.ts b/packages/api-client/src/meta.ts
index 6e8c3d5b7..92d8cb2c4 100644
--- a/packages/api-client/src/meta.ts
+++ b/packages/api-client/src/meta.ts
@@ -3,34 +3,23 @@
* Powers the upgrade banner, what's-new view, and version footer.
*/
+import type {
+ ChangelogEntryModel,
+ ChangelogHighlightModel,
+ ChangelogResponse,
+ ChangelogSectionModel,
+ ReleaseStatsModel,
+ VersionResponse,
+} from "@repowise-dev/types/generated/http";
import { apiGet } from "./client";
-export interface MetaVersion {
- server_version: string;
- latest_version: string | null;
- /** null when PyPI could not be reached (distinct from "up to date"). */
- update_available: boolean | null;
- upgrade_command: string;
- store_format_version: number | null;
- store_compatible: boolean | null;
- reindex_recommended: boolean;
- reindex_command: string | null;
-}
-
-export interface ChangelogSection {
- name: string;
- items: string[];
-}
-
-export interface ChangelogEntry {
- version: string;
- label: string | null;
- sections: ChangelogSection[];
-}
-
-export interface ChangelogData {
- entries: ChangelogEntry[];
-}
+export type MetaVersion = VersionResponse;
+export type ChangelogSection = ChangelogSectionModel;
+export type ChangelogHighlight = ChangelogHighlightModel;
+export type ReleaseStats = ReleaseStatsModel;
+/** `version` is `"unreleased"` for the next release's notes in a dev build. */
+export type ChangelogEntry = ChangelogEntryModel;
+export type ChangelogData = ChangelogResponse;
export async function getMetaVersion(repoId?: string): Promise<MetaVersion> {
return apiGet<MetaVersion>(
diff --git a/packages/cli/src/repowise/cli/commands/whats_new_cmd.py b/packages/cli/src/repowise/cli/commands/whats_new_cmd.py
index 8ed8b0886..d330e654c 100644
--- a/packages/cli/src/repowise/cli/commands/whats_new_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/whats_new_cmd.py
@@ -13,6 +13,8 @@ from repowise.cli.whats_new import (
render_whats_new,
write_last_seen_version,
)
+from repowise.core.upgrade.changelog import UNRELEASED
+from repowise.core.upgrade.release import load_release_stats
def _entry_dict(entry) -> dict:
@@ -27,6 +29,12 @@ def _entry_dict(entry) -> dict:
return {
"version": entry.version,
"label": entry.label,
+ "summary": entry.summary,
+ "highlights": [
+ {"id": h.id, "title": h.title, "blurb": h.blurb, "href": h.href}
+ for h in entry.highlights
+ ],
+ "stats": load_release_stats().get(entry.version),
"sections": [{"name": s.name, "items": list(s.items)} for s in entry.sections],
}
@@ -69,7 +77,8 @@ def whats_new_command(version: str | None, show_all: bool, fmt: str) -> None:
}
)
return
- render_whats_new(console, match, since_version=None, title=f"repowise v{version}")
+ title = "repowise (unreleased)" if version == UNRELEASED else f"repowise v{version}"
+ render_whats_new(console, match, since_version=None, title=title)
return
if show_all:
diff --git a/packages/cli/src/repowise/cli/whats_new.py b/packages/cli/src/repowise/cli/whats_new.py
index 22e5c01c9..d3a0de0c5 100644
--- a/packages/cli/src/repowise/cli/whats_new.py
+++ b/packages/cli/src/repowise/cli/whats_new.py
@@ -17,14 +17,16 @@ import os
from pathlib import Path
from rich.console import Console
+from rich.markup import escape
from rich.panel import Panel
from repowise.core.upgrade.changelog import (
+ UNRELEASED,
ChangelogEntry,
entries_between,
parse_changelog,
)
-from repowise.core.upgrade.release import BUNDLED_CHANGELOG_PATH
+from repowise.core.upgrade.release import BUNDLED_CHANGELOG_PATH, load_release_stats
from .helpers import user_global_dir
from .update_check import windows_upgrade_caveat
@@ -95,26 +97,60 @@ def write_last_seen_version(version: str) -> None:
# --- rendering ------------------------------------------------------------
-def _format_entry(entry: ChangelogEntry, *, max_items: int) -> str:
+def numbers_line(stats: dict | None) -> str | None:
+ """One line of a release's "By the numbers", or ``None`` without figures."""
+ if not stats:
+ return None
+ try:
+ first = stats.get("first_time_contributors")
+ people = f"{stats['contributors']:,} contributors"
+ if first:
+ people += f" ({first:,} first-time)"
+ return (
+ f"{stats['prs']:,} pull requests from {people}, {stats['files_changed']:,} files, "
+ f"+{stats['lines_added']:,} / -{stats['lines_removed']:,} lines, "
+ f"{stats['days']:,} days since {stats['since']}"
+ )
+ except (KeyError, TypeError, ValueError):
+ return None
+
+
+def _format_entry(entry: ChangelogEntry, *, max_items: int, stats: dict | None = None) -> str:
+ # Highlights and the numbers lead and do not count toward the bullet cap:
+ # they are the part of the release a reader should not miss.
+ lines = _highlight_lines(entry)
+ numbers = numbers_line(stats)
+ if numbers:
+ lines.append(f"[dim]By the numbers: {numbers}[/dim]")
+ lines.extend(_section_lines(entry, max_items=max_items))
+ return "\n".join(lines)
+
+
+def _highlight_lines(entry: ChangelogEntry) -> list[str]:
+ if not entry.highlights:
+ return []
+ lines = ["[bold]Highlights[/bold]"]
+ for h in entry.highlights:
+ blurb = f": {escape(h.blurb)}" if h.blurb else ""
+ lines.append(f" - [bold]{escape(h.title)}[/bold]{blurb}")
+ return lines
+
+
+def _section_lines(entry: ChangelogEntry, *, max_items: int) -> list[str]:
+ """Section bullets up to *max_items* in total, then an ellipsis."""
lines: list[str] = []
- shown = 0
- truncated = False
+ budget = max_items
for section in entry.sections:
- if shown >= max_items:
- truncated = True
- break
if not section.items:
continue
+ if budget <= 0:
+ return [*lines, " [dim]...[/dim]"]
lines.append(f"[bold]{section.name}[/bold]")
- for item in section.items:
- if shown >= max_items:
- truncated = True
- break
- lines.append(f" - {_strip_markdown(item)}")
- shown += 1
- if truncated:
- lines.append(" [dim]...[/dim]")
- return "\n".join(lines)
+ lines.extend(f" - {_strip_markdown(item)}" for item in section.items[:budget])
+ if len(section.items) > budget:
+ return [*lines, " [dim]...[/dim]"]
+ budget -= len(section.items)
+ return lines
def _strip_markdown(text: str) -> str:
@@ -146,11 +182,15 @@ def render_whats_new(
if not selected:
return False
+ stats = load_release_stats()
blocks: list[str] = []
for entry in selected[:max_versions]:
label = f" [dim]({entry.label})[/dim]" if entry.label else ""
- body = _format_entry(entry, max_items=max_items_per_version)
- blocks.append(f"[bold cyan]v{entry.version}[/bold cyan]{label}\n{body}")
+ body = _format_entry(
+ entry, max_items=max_items_per_version, stats=stats.get(entry.version)
+ )
+ name = "Unreleased" if entry.version == UNRELEASED else f"v{entry.version}"
+ blocks.append(f"[bold cyan]{name}[/bold cyan]{label}\n{body}")
extra = len(selected) - max_versions
if extra > 0:
@@ -189,6 +229,7 @@ __all__ = [
"RELEASES_URL",
"find_changelog_path",
"load_changelog_entries",
+ "numbers_line",
"read_last_seen_version",
"render_update_advisory",
"render_whats_new",
diff --git a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
index 0a9f965fe..e73a9bdca 100644
--- a/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
+++ b/packages/core/src/repowise/core/upgrade/_data/CHANGELOG.md
@@ -6,15 +6,39 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
<!-- Use `git-cliff` to auto-generate entries from conventional commits -->
+<!-- A minor release opens with a short summary, then `### Highlights` (3-5 bullets shaped `- **Title** · one-line blurb. → /route`; the route is optional and `:id` stands for the current repository) and `### By the numbers` from `python scripts/release_stats.py`. The web UI and `repowise whats-new` show both. -->
---
## [Unreleased]
+Chat draws any chart of your repository, from bars and lines to donuts, treemaps and heatmaps, and every chart in the web UI shares one palette. Models and base URLs are set from Settings with live model lists, so a local server such as LM Studio is one form away, and a failed sync says what went wrong and how to fix it. Every merged change becomes a Change Record with its evidence, and the Commits page groups commits by change.
+
+### Highlights
+
+- **Charts in chat** · Ask for any chart of your files, findings, changes, health trend, coverage, dead code, dependencies or layers, drawn as bars, lines, donuts, treemaps or heatmaps. → /repos/:id/chat
+- **Models from Settings, with live lists** · Pick a model from the provider's live list or type any id, and point repowise at LM Studio or another local OpenAI-compatible server with no key. → /settings
+- **Sync failures explain themselves** · A rejected key, rate limit, unreachable base URL or missing model shows on the sync with a short hint saying what to do. → /repos/:id/settings
+- **Commits grouped by change** · Every merged change is a Change Record with its evidence checklist, and the Commits page groups commits by the change that landed them. → /repos/:id/commits
+- **One palette for every chart** · Charts and share bars draw from the same eight series colours, and a commit type keeps its colour on every chart.
+
+### By the numbers
+
+In the 3 days since 0.56.0:
+
+- **205 pull requests** merged, from **24 contributors**, **11 of them first-time contributors**
+- **1,226 files** changed, **+103,206 / -11,127** lines
+- **147 fixes, 45 features**, 4 refactors and 6 documentation changes
+- **437 test files** touched, **144** of them new
+- **25 issues** closed
+
+Thank you to everyone who built this release with us.
+
### Changed
- **Charts are in colour again, from one palette.** Every chart and share bar in the web UI draws from the same eight series colours, a commit type keeps one colour on every chart, health and risk charts keep their green, amber and red, heatmaps step through the accent orange, and chat charts sit on the conversation without a card around them.
- **One provider order everywhere.** The CLI, `repowise serve` chat and jobs, and the MCP server now resolve provider, model and base URL as flag or UI choice, then `.repowise/config.yaml`, then the web UI's global default, then `REPOWISE_PROVIDER` / `REPOWISE_MODEL`, so `config.yaml` now wins over those env vars in the CLI. Choosing a model or base URL for a repo in the web UI writes that repo's `config.yaml`, which makes switching models on a local OpenAI-compatible server such as LM Studio a single edit. A base URL in `config.yaml` now beats `OPENAI_BASE_URL` and the other `*_BASE_URL` variables. The default provider and model saved in the web UI settings now also apply to CLI runs in repos whose `config.yaml` names none. A `config.yaml` base URL receives an API key from outside that repo's `.repowise/.env` only when it is a local address or was confirmed in Settings or with `repowise init`.
+- **Current model lists and prices.** Pickers offer GPT-6 Luna and Sol, Claude Sonnet 5.5 and Opus 5.5, Gemini 3.8 Flash and Gemini 4 Argon. DeepSeek now defaults to `deepseek-flash` and LiteLLM to `groq/openai/gpt-oss-120b`, since the old ids were retired. Cost estimates use current rates, and GPT-6 models get the same reasoning, temperature and chat tool handling as GPT-5.6.
## [0.56.0] - 2026-10-12
diff --git a/packages/core/src/repowise/core/upgrade/_data/release_stats.json b/packages/core/src/repowise/core/upgrade/_data/release_stats.json
new file mode 100644
index 000000000..0afb66eec
--- /dev/null
+++ b/packages/core/src/repowise/core/upgrade/_data/release_stats.json
@@ -0,0 +1,42 @@
+{
+ "0.56.0": {
+ "since": "0.55.0",
+ "days": 8,
+ "prs": 311,
+ "contributors": 41,
+ "first_time_contributors": 25,
+ "files_changed": 1475,
+ "lines_added": 117442,
+ "lines_removed": 21293,
+ "types": {
+ "fixes": 165,
+ "features": 89,
+ "perf": 10,
+ "refactors": 28,
+ "docs": 6
+ },
+ "test_files_touched": 492,
+ "test_files_new": 158,
+ "issues_closed": 76
+ },
+ "unreleased": {
+ "since": "0.56.0",
+ "days": 3,
+ "prs": 205,
+ "contributors": 24,
+ "first_time_contributors": 11,
+ "files_changed": 1226,
+ "lines_added": 103206,
+ "lines_removed": 11127,
+ "types": {
+ "fixes": 147,
+ "features": 45,
+ "perf": 0,
+ "refactors": 4,
+ "docs": 6
+ },
+ "test_files_touched": 437,
+ "test_files_new": 144,
+ "issues_closed": 25
+ }
+}
diff --git a/packages/core/src/repowise/core/upgrade/changelog.py b/packages/core/src/repowise/core/upgrade/changelog.py
index ba752c2ba..e51b7b1f0 100644
--- a/packages/core/src/repowise/core/upgrade/changelog.py
+++ b/packages/core/src/repowise/core/upgrade/changelog.py
@@ -1,13 +1,18 @@
"""Parse ``CHANGELOG.md`` (Keep-a-Changelog) into structured release entries.
-Shared by the CLI ("what's new" panel + ``repowise whats-new``) and, in a later
-phase, the web ``/api/meta/changelog`` endpoint, so the format is parsed once
-here rather than in each presenter.
+Shared by the CLI ("what's new" panel + ``repowise whats-new``) and the web
+``/api/meta/changelog`` endpoint, so the format is parsed once here rather than
+in each presenter.
The parser is intentionally forgiving: it recognises ``## [X.Y.Z] - date``
-release headers and ``### Section`` subsection headers, and collects the bullet
-lines under each. Anything it does not understand (the preamble, HTML comments,
-horizontal rules) is skipped rather than treated as an error.
+release headers (and ``## [Unreleased]``, as version ``unreleased``) and
+``### Section`` subsection headers, and collects the bullet lines under each.
+The prose between a release header and its first section is the release
+summary. ``### Highlights`` bullets (``- **Title** · blurb. → /route``) come back
+as structured highlights, and ``### By the numbers`` is left out of the sections
+because its figures ship as data in ``_data/release_stats.json``. Anything it
+does not understand (the preamble, HTML comments, horizontal rules) is skipped
+rather than treated as an error.
"""
from __future__ import annotations
@@ -16,16 +21,31 @@ import re
from dataclasses import dataclass, field
# ``## [0.21.0] - 2026-06-19`` or ``## [0.21.0] — Unreleased`` (any dash). The
-# version must be a dotted numeric; the trailing label (date / "Unreleased") is
-# optional and captured loosely.
+# version must be a dotted numeric or ``Unreleased``; the trailing label (date /
+# "Unreleased") is optional and captured loosely.
# The trailing label group allows an empty label (a stray ``-`` with no date)
# so a malformed header degrades to ``label=None`` instead of dropping the whole
# release. ``.*\S`` keeps the captured label trimmed of trailing whitespace.
_RELEASE_RE = re.compile(
- r"^##\s*\[(?P<version>\d+\.\d+(?:\.\d+)?)\]\s*(?:[-–—]\s*(?P<label>.*\S)?)?\s*$"
+ r"^##\s*\[(?P<version>\d+\.\d+(?:\.\d+)?|[Uu]nreleased)\]\s*(?:[-–—]\s*(?P<label>.*\S)?)?\s*$"
)
_SECTION_RE = re.compile(r"^###\s+(?P<name>.+?)\s*$")
_BULLET_RE = re.compile(r"^[-*]\s+(?P<text>.+?)\s*$")
+# ``**Title** · blurb. → /route``. The separator after the title may be ``·``,
+# ``:``, ``|`` or a dash, and the trailing route (``→`` or ``->``) is optional,
+# so a loosely written highlight still parses.
+_HIGHLIGHT_RE = re.compile(
+ r"^\*\*(?P<title>.+?)\*\*(?:\s*[·:|]|\s+[-–—](?=\s))?\s*(?P<rest>.*)$"
+)
+_ROUTE_RE = re.compile(r"\s*(?:→|->)\s*(?P<href>/\S*)\s*$")
+
+#: Version string the parser gives ``## [Unreleased]``.
+UNRELEASED = "unreleased"
+HIGHLIGHTS_SECTION = "Highlights"
+NUMBERS_SECTION = "By the numbers"
+
+# Unreleased sorts above every release, so it is never "already seen".
+_UNRELEASED_RANK = 10**9
@dataclass(frozen=True, slots=True)
@@ -36,6 +56,17 @@ class ChangelogSection:
items: tuple[str, ...] = field(default_factory=tuple)
+@dataclass(frozen=True, slots=True)
+class ChangelogHighlight:
+ """One ``### Highlights`` bullet. ``id`` is the title's slug, so it stays
+ stable while the blurb is edited."""
+
+ id: str
+ title: str
+ blurb: str
+ href: str | None = None
+
+
@dataclass(frozen=True, slots=True)
class ChangelogEntry:
"""One ``## [X.Y.Z]`` release with its grouped bullet sections."""
@@ -43,61 +74,114 @@ class ChangelogEntry:
version: str
label: str | None
sections: tuple[ChangelogSection, ...] = field(default_factory=tuple)
+ #: The prose paragraphs between the release header and its first section.
+ summary: str = ""
+ highlights: tuple[ChangelogHighlight, ...] = field(default_factory=tuple)
@property
def release_tuple(self) -> tuple[int, ...]:
"""Numeric release tuple for ordering/comparison (e.g. (0, 21, 0))."""
+ if self.version == UNRELEASED:
+ return (_UNRELEASED_RANK,)
return tuple(int(p) for p in self.version.split("."))
+ @property
+ def is_empty(self) -> bool:
+ return not self.summary and not self.highlights and not any(s.items for s in self.sections)
+
+
+def parse_highlight(text: str) -> ChangelogHighlight:
+ """Parse one highlight bullet. A bullet without a bold title keeps its whole
+ text as the title, so a loosely written line is never lost."""
+ href = None
+ route = _ROUTE_RE.search(text)
+ if route:
+ href = route.group("href")
+ text = text[: route.start()]
+ m = _HIGHLIGHT_RE.match(text.strip())
+ if m:
+ title, blurb = m.group("title").strip(), m.group("rest").strip()
+ else:
+ title, blurb = text.strip(), ""
+ return ChangelogHighlight(id=_slug(title), title=title, blurb=blurb, href=href)
+
+
+def _slug(text: str) -> str:
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
+
def parse_changelog(text: str) -> list[ChangelogEntry]:
- """Parse Keep-a-Changelog *text* into entries, newest first (as written)."""
- entries: list[ChangelogEntry] = []
- cur_version: str | None = None
- cur_label: str | None = None
- sections: list[ChangelogSection] = []
- cur_section_name: str | None = None
- cur_items: list[str] = []
-
- def _flush_section() -> None:
- nonlocal cur_section_name, cur_items
- if cur_section_name is not None:
- sections.append(ChangelogSection(name=cur_section_name, items=tuple(cur_items)))
- cur_section_name = None
- cur_items = []
-
- def _flush_release() -> None:
- nonlocal cur_version, cur_label, sections
- _flush_section()
- if cur_version is not None:
- entries.append(
- ChangelogEntry(version=cur_version, label=cur_label, sections=tuple(sections))
- )
- cur_version = None
- cur_label = None
- sections = []
+ """Parse Keep-a-Changelog *text* into entries, newest first (as written).
+ An ``Unreleased`` block with no content is dropped (the normal state right
+ after a release).
+ """
+ entries = [_parse_release(*block) for block in _release_blocks(text)]
+ return [e for e in entries if not (e.version == UNRELEASED and e.is_empty)]
+
+
+def _release_blocks(text: str):
+ """``(version, label, lines)`` per release header; the preamble is skipped."""
+ version: str | None = None
+ label: str | None = None
+ lines: list[str] = []
for raw in text.splitlines():
line = raw.rstrip()
rel = _RELEASE_RE.match(line)
if rel:
- _flush_release()
- cur_version = rel.group("version")
- cur_label = rel.group("label")
- continue
- if cur_version is None:
- continue # still in the preamble
+ if version is not None:
+ yield version, label, lines
+ found = rel.group("version")
+ version = UNRELEASED if found.lower() == UNRELEASED else found
+ label, lines = rel.group("label"), []
+ elif version is not None:
+ lines.append(line)
+ if version is not None:
+ yield version, label, lines
+
+
+def _parse_release(version: str, label: str | None, lines: list[str]) -> ChangelogEntry:
+ """One release's lines: summary prose up to the first ``###``, then
+ sections of bullets. Highlights come out separately and By the numbers
+ is dropped."""
+ summary: list[str] = []
+ groups: list[tuple[str, list[str]]] = []
+ for line in lines:
sec = _SECTION_RE.match(line)
if sec:
- _flush_section()
- cur_section_name = sec.group("name")
+ groups.append((sec.group("name"), []))
+ elif not groups:
+ summary.append(line)
+ elif bullet := _BULLET_RE.match(line):
+ groups[-1][1].append(bullet.group("text"))
+ highlights = [parse_highlight(i) for name, items in groups if name == HIGHLIGHTS_SECTION for i in items]
+ sections = [
+ ChangelogSection(name=name, items=tuple(items))
+ for name, items in groups
+ if name not in (HIGHLIGHTS_SECTION, NUMBERS_SECTION)
+ ]
+ return ChangelogEntry(
+ version=version,
+ label=label,
+ sections=tuple(sections),
+ summary=_join_paragraphs(summary),
+ highlights=tuple(highlights),
+ )
+
+
+def _join_paragraphs(lines: list[str]) -> str:
+ """Summary lines to paragraphs, dropping rules and HTML comments."""
+ paragraphs: list[str] = []
+ cur: list[str] = []
+ for line in [*lines, ""]:
+ text = line.strip()
+ if not text or text == "---" or text.startswith("<!--"):
+ if cur:
+ paragraphs.append(" ".join(cur))
+ cur = []
continue
- bullet = _BULLET_RE.match(line)
- if bullet and cur_section_name is not None:
- cur_items.append(bullet.group("text"))
-
- _flush_release()
- return entries
+ cur.append(text)
+ return "\n\n".join(paragraphs)
def entries_between(
@@ -142,8 +226,13 @@ def _gt(a: tuple[int, ...], b: tuple[int, ...] | None) -> bool:
__all__ = [
+ "HIGHLIGHTS_SECTION",
+ "NUMBERS_SECTION",
+ "UNRELEASED",
"ChangelogEntry",
+ "ChangelogHighlight",
"ChangelogSection",
"entries_between",
"parse_changelog",
+ "parse_highlight",
]
diff --git a/packages/core/src/repowise/core/upgrade/release.py b/packages/core/src/repowise/core/upgrade/release.py
index c5aa41000..a2309e29d 100644
--- a/packages/core/src/repowise/core/upgrade/release.py
+++ b/packages/core/src/repowise/core/upgrade/release.py
@@ -17,11 +17,15 @@ import json
import time
from dataclasses import dataclass
from pathlib import Path
+from typing import Any
from .changelog import ChangelogEntry, parse_changelog
PYPI_URL = "https://pypi.org/pypi/repowise/json"
+#: The changelog on main, read only to name what a newer release brings.
+CHANGELOG_URL = "https://raw.githubusercontent.com/repowise-dev/repowise/main/docs/CHANGELOG.md"
+
#: Default freshness window for the cached PyPI check (hours). Within it the last
#: fetched ``latest_version`` is reused so routine calls never hit the network.
DEFAULT_TTL_HOURS = 24.0
@@ -30,9 +34,17 @@ DEFAULT_TTL_HOURS = 24.0
#: ``repowise whats-new`` and the web what's-new view work offline.
BUNDLED_CHANGELOG_PATH = Path(__file__).parent / "_data" / "CHANGELOG.md"
+#: Per-release figures ("By the numbers"), keyed by version, written by
+#: ``scripts/release_stats.py`` and bundled beside the changelog.
+RELEASE_STATS_PATH = Path(__file__).parent / "_data" / "release_stats.json"
+
#: Shared cache file (also written by the CLI advisory) under the user-global dir.
_CACHE_PATH = Path.home() / ".repowise" / "update-check.json"
+#: Highlight titles of the newer release. A file of its own because the CLI
+#: rewrites ``update-check.json`` whole.
+_HIGHLIGHTS_CACHE_PATH = Path.home() / ".repowise" / "release-highlights.json"
+
# --- version comparison ---------------------------------------------------
@@ -159,25 +171,109 @@ def _write_cached_latest(latest: str | None, error: str | None) -> None:
)
-# --- bundled changelog ----------------------------------------------------
+# --- newer release highlights ---------------------------------------------
+
+
+def fetch_release_highlights(version: str, timeout: float = 2.0) -> list[str] | None:
+ """Highlight titles *version* lists in the changelog on main. Never raises.
+
+ ``None`` on any network or parse failure, so the caller keeps its plain
+ wording. Nothing is sent but the GET.
+ """
+ import httpx
+
+ try:
+ resp = httpx.get(CHANGELOG_URL, timeout=timeout)
+ resp.raise_for_status()
+ except httpx.HTTPError: # offline, timeout, non-2xx
+ return None
+ for entry in parse_changelog(resp.text):
+ if entry.version == version:
+ return [h.title for h in entry.highlights]
+ return []
+
+
+_EMPTY_TTL_HOURS = 0.25
+
+
+def latest_highlights_cached(
+ version: str,
+ *,
+ ttl_hours: float = DEFAULT_TTL_HOURS,
+ timeout: float = 2.0,
+) -> list[str]:
+ """TTL-cached :func:`fetch_release_highlights`, ``[]`` when unknown.
+
+ An empty or failed lookup is kept for :data:`_EMPTY_TTL_HOURS` only, so an
+ offline machine does not retry on every request but a flaky first check
+ does not hide the titles for a whole day.
+ """
+ try:
+ cached = json.loads(_HIGHLIGHTS_CACHE_PATH.read_text(encoding="utf-8"))
+ age = time.time() - float(cached["checked_at"])
+ titles = list(cached.get("titles") or [])
+ ttl = ttl_hours if titles else min(ttl_hours, _EMPTY_TTL_HOURS)
+ if cached.get("version") == version and 0 <= age < ttl * 3600:
+ return titles
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ pass # no cache yet, or a malformed one: fetch
+ titles = fetch_release_highlights(version, timeout=timeout)
+ with contextlib.suppress(OSError): # a read-only home only costs a refetch
+ _HIGHLIGHTS_CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ _HIGHLIGHTS_CACHE_PATH.write_text(
+ json.dumps({"checked_at": time.time(), "version": version, "titles": titles or []}),
+ encoding="utf-8",
+ )
+ return titles or []
+
+
+# --- bundled changelog and release stats ----------------------------------
+
+# Parsed files keyed by path, reused while the file's mtime is unchanged, so a
+# request does not re-read and re-parse a 3,000-line changelog.
+_FILE_CACHE: dict[Path, tuple[float, Any]] = {}
+
+
+def _load_cached(path: Path, parse):
+ mtime = path.stat().st_mtime
+ hit = _FILE_CACHE.get(path)
+ if hit and hit[0] == mtime:
+ return hit[1]
+ value = parse(path.read_text(encoding="utf-8"))
+ _FILE_CACHE[path] = (mtime, value)
+ return value
def load_bundled_changelog() -> list[ChangelogEntry]:
"""Parse repowise's bundled changelog, or ``[]`` if it cannot be read."""
try:
- return parse_changelog(BUNDLED_CHANGELOG_PATH.read_text(encoding="utf-8"))
- except Exception:
+ return list(_load_cached(BUNDLED_CHANGELOG_PATH, parse_changelog))
+ except (OSError, UnicodeDecodeError): # missing from an unusual install
return []
+def load_release_stats() -> dict[str, dict[str, Any]]:
+ """Bundled "By the numbers" figures keyed by version, or ``{}``."""
+ try:
+ data = _load_cached(RELEASE_STATS_PATH, json.loads)
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError): # missing, or not JSON
+ return {}
+
+
__all__ = [
"BUNDLED_CHANGELOG_PATH",
+ "CHANGELOG_URL",
"DEFAULT_TTL_HOURS",
"PYPI_URL",
+ "RELEASE_STATS_PATH",
"ReleaseCheck",
"check_latest_version_cached",
"fetch_latest_version",
+ "fetch_release_highlights",
"is_newer_version",
+ "latest_highlights_cached",
"load_bundled_changelog",
+ "load_release_stats",
"parse_release",
]
diff --git a/packages/server/src/repowise/server/routers/meta.py b/packages/server/src/repowise/server/routers/meta.py
index 43fcbdff0..4077415d8 100644
--- a/packages/server/src/repowise/server/routers/meta.py
+++ b/packages/server/src/repowise/server/routers/meta.py
@@ -8,21 +8,32 @@ failures degrade to partial responses, never errors.
from __future__ import annotations
+import asyncio
import json
from pathlib import Path
from fastapi import APIRouter, Depends, Request
+from pydantic import ValidationError
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
from repowise.core.upgrade import UpgradeTier, assess
-from repowise.core.upgrade.release import check_latest_version_cached, load_bundled_changelog
+from repowise.core.upgrade.changelog import ChangelogEntry, ChangelogHighlight
+from repowise.core.upgrade.release import (
+ ReleaseCheck,
+ check_latest_version_cached,
+ latest_highlights_cached,
+ load_bundled_changelog,
+ load_release_stats,
+)
from repowise.server import __version__
from repowise.server.deps import resolve_session_factory, verify_api_key
from repowise.server.schemas import (
ChangelogEntryModel,
+ ChangelogHighlightModel,
ChangelogResponse,
ChangelogSectionModel,
+ ReleaseStatsModel,
VersionResponse,
)
@@ -40,12 +51,16 @@ async def get_version(request: Request, repo_id: str | None = None) -> VersionRe
The global version/freshness path needs no database; a session is opened
lazily only when a ``repo_id`` is supplied (for the store-format fields).
"""
- check = check_latest_version_cached(__version__)
+ # Off the event loop: a cache miss makes up to two 2 s network calls.
+ check, latest_titles = await asyncio.to_thread(_freshness)
+ current = next((e for e in load_bundled_changelog() if e.version == __version__), None)
resp = VersionResponse(
server_version=__version__,
latest_version=check.latest_version,
update_available=check.update_available,
upgrade_command=_UPGRADE_COMMAND,
+ highlights=[_highlight(h) for h in current.highlights] if current else [],
+ latest_highlights=latest_titles,
)
if repo_id:
@@ -53,6 +68,14 @@ async def get_version(request: Request, repo_id: str | None = None) -> VersionRe
return resp
+def _freshness() -> tuple[ReleaseCheck, list[str]]:
+ """PyPI check, plus the newer release's highlight titles when there is one."""
+ check = check_latest_version_cached(__version__)
+ if check.update_available and check.latest_version:
+ return check, latest_highlights_cached(check.latest_version)
+ return check, []
+
+
async def _attach_store_status(resp: VersionResponse, repo_id: str, request: Request) -> None:
"""Fill the store-format fields for *repo_id*. Best-effort, never raises."""
try:
@@ -76,15 +99,28 @@ async def _attach_store_status(resp: VersionResponse, repo_id: str, request: Req
async def get_changelog(limit: int = 20) -> ChangelogResponse:
"""Return repowise's bundled changelog, newest first, capped at *limit*."""
entries = load_bundled_changelog()[: max(0, limit)]
- return ChangelogResponse(
- entries=[
- ChangelogEntryModel(
- version=e.version,
- label=e.label,
- sections=[
- ChangelogSectionModel(name=s.name, items=list(s.items)) for s in e.sections
- ],
- )
- for e in entries
- ]
+ stats = load_release_stats()
+ return ChangelogResponse(entries=[_entry(e, stats.get(e.version)) for e in entries])
+
+
+def _highlight(h: ChangelogHighlight) -> ChangelogHighlightModel:
+ return ChangelogHighlightModel(id=h.id, title=h.title, blurb=h.blurb, href=h.href)
+
+
+def _entry(e: ChangelogEntry, stats: dict | None) -> ChangelogEntryModel:
+ return ChangelogEntryModel(
+ version=e.version,
+ label=e.label,
+ summary=e.summary,
+ highlights=[_highlight(h) for h in e.highlights],
+ stats=_stats(stats),
+ sections=[ChangelogSectionModel(name=s.name, items=list(s.items)) for s in e.sections],
)
+
+
+def _stats(raw: dict | None) -> ReleaseStatsModel | None:
+ """Validated figures, or ``None`` for a missing or malformed record."""
+ try:
+ return ReleaseStatsModel.model_validate(raw) if raw else None
+ except ValidationError:
+ return None
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 4c0869bfd..132b2b874 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -197,8 +197,11 @@ if TYPE_CHECKING:
)
from .meta import (
ChangelogEntryModel,
+ ChangelogHighlightModel,
ChangelogResponse,
ChangelogSectionModel,
+ ReleaseStatsModel,
+ ReleaseTypeCountsModel,
VersionResponse,
)
from .ownership import (
@@ -507,8 +510,11 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
"mcp": ("McpToolInfo", "McpToolSurfaceResponse", "UpdateMcpToolsRequest"),
"meta": (
"ChangelogEntryModel",
+ "ChangelogHighlightModel",
"ChangelogResponse",
"ChangelogSectionModel",
+ "ReleaseStatsModel",
+ "ReleaseTypeCountsModel",
"VersionResponse",
),
"ownership": (
@@ -681,6 +687,7 @@ __all__ = [
"CardRef",
"ChangeFeaturesResponse",
"ChangelogEntryModel",
+ "ChangelogHighlightModel",
"ChangelogResponse",
"ChangelogSectionModel",
"ChartView",
@@ -852,6 +859,8 @@ __all__ = [
"RelatedWorkLens",
"RelatedWorkRequest",
"RelatedWorkResponse",
+ "ReleaseStatsModel",
+ "ReleaseTypeCountsModel",
"RepoCreate",
"RepoDeletedResponse",
"RepoResponse",
diff --git a/packages/server/src/repowise/server/schemas/meta.py b/packages/server/src/repowise/server/schemas/meta.py
index 3e7980da9..3ed647e41 100644
--- a/packages/server/src/repowise/server/schemas/meta.py
+++ b/packages/server/src/repowise/server/schemas/meta.py
@@ -22,6 +22,47 @@ class VersionResponse(BaseModel):
reindex_recommended: bool = False
reindex_command: str | None = None
+ #: Highlights of the running release, from the bundled changelog. Drives the
+ #: post-upgrade "What's new" and the "New" marks in the nav.
+ highlights: list[ChangelogHighlightModel] = []
+ #: Highlight titles of ``latest_version`` when it is newer, read from the
+ #: changelog on GitHub (cached a day). Empty when offline or unknown.
+ latest_highlights: list[str] = []
+
+
+class ChangelogHighlightModel(BaseModel):
+ id: str
+ title: str
+ blurb: str
+ #: An app route; ``:id`` stands for the current repository.
+ href: str | None = None
+
+
+class ReleaseTypeCountsModel(BaseModel):
+ fixes: int = 0
+ features: int = 0
+ perf: int = 0
+ refactors: int = 0
+ docs: int = 0
+
+
+class ReleaseStatsModel(BaseModel):
+ """A release's "By the numbers", from ``scripts/release_stats.py``."""
+
+ since: str
+ days: int
+ prs: int
+ contributors: int
+ #: ``None`` when GitHub could not be asked who was new.
+ first_time_contributors: int | None = None
+ files_changed: int
+ lines_added: int
+ lines_removed: int
+ types: ReleaseTypeCountsModel
+ test_files_touched: int
+ test_files_new: int
+ issues_closed: int
+
class ChangelogSectionModel(BaseModel):
name: str
@@ -29,8 +70,12 @@ class ChangelogSectionModel(BaseModel):
class ChangelogEntryModel(BaseModel):
+ #: ``unreleased`` for the next release's notes in a development build.
version: str
label: str | None = None
+ summary: str = ""
+ highlights: list[ChangelogHighlightModel] = []
+ stats: ReleaseStatsModel | None = None
sections: list[ChangelogSectionModel]
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 909b10cf1..d5f175293 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -499,9 +499,19 @@ export interface ChangeRecord {
export interface ChangelogEntryModel {
version: string;
label?: string | null;
+ summary?: string;
+ highlights?: ChangelogHighlightModel[];
+ stats?: ReleaseStatsModel | null;
sections: ChangelogSectionModel[];
}
+export interface ChangelogHighlightModel {
+ id: string;
+ title: string;
+ blurb: string;
+ href?: string | null;
+}
+
export interface ChangelogResponse {
entries: ChangelogEntryModel[];
}
@@ -3308,6 +3318,30 @@ export interface RelatedWorkResponse {
per_lens_limit?: number;
}
+/** A release's "By the numbers", from ``scripts/release_stats.py``. */
+export interface ReleaseStatsModel {
+ since: string;
+ days: number;
+ prs: number;
+ contributors: number;
+ first_time_contributors?: number | null;
+ files_changed: number;
+ lines_added: number;
+ lines_removed: number;
+ types: ReleaseTypeCountsModel;
+ test_files_touched: number;
+ test_files_new: number;
+ issues_closed: number;
+}
+
+export interface ReleaseTypeCountsModel {
+ fixes?: number;
+ features?: number;
+ perf?: number;
+ refactors?: number;
+ docs?: number;
+}
+
export interface RepoCreate {
name: string;
local_path: string;
@@ -3873,6 +3907,8 @@ export interface VersionResponse {
store_compatible?: boolean | null;
reindex_recommended?: boolean;
reindex_command?: string | null;
+ highlights?: ChangelogHighlightModel[];
+ latest_highlights?: string[];
}
export interface WebhookResponse {
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 82edb1399..ed08691f8 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -115,6 +115,7 @@
"./shared/virtualized-table": "./src/shared/virtualized-table/index.ts",
"./shared/context-drawer": "./src/shared/context-drawer/index.ts",
"./shared/file-card": "./src/shared/file-card/index.ts",
+ "./shared/series": "./src/shared/series.ts",
"./shared/*": "./src/shared/*.tsx",
"./hooks": "./src/hooks/index.ts",
"./ui": "./src/ui/index.ts",
diff --git a/packages/ui/scripts/contrast-check.py b/packages/ui/scripts/contrast-check.py
index 2a0479969..f711fcbf1 100755
--- a/packages/ui/scripts/contrast-check.py
+++ b/packages/ui/scripts/contrast-check.py
@@ -147,6 +147,8 @@ LIGHT = {
# at 10/26/50%, then accent-primary and accent-hover.
"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",
}
DARK = {
@@ -196,6 +198,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",
}
# (fg, bg, floor, label) — floor is the WCAG ratio the pair must meet.
@@ -243,6 +246,20 @@ CHECKS = [
# Heatmap cells print their value: ink on the light steps, card colour on the dark.
*[("text-primary", f"heat-{n}", 4.5, f"Value on heat step {n}") for n in (1, 2, 3)],
*[("bg-surface", f"heat-{n}", 4.5, f"Value on heat step {n}") for n in (4, 5)],
+ # What's new: ink on the ground and both glow stops (the band carries the
+ # heading only, so links sit on the ground), and the series accents
+ # beside the release figures.
+ *[
+ (fg, bg, floor, f"{fg} on {bg}")
+ for bg in ("release-ground", "release-glow-1", "release-glow-2")
+ for fg, floor in (("text-primary", 7.0), ("text-secondary", 4.5))
+ ],
+ ("accent-primary", "release-ground", 4.5, "accent-primary on release-ground"),
+ *[
+ (fg, "release-card", floor, f"{fg} on release-card")
+ for fg, floor in (("text-primary", 7.0), ("text-secondary", 4.5), ("accent-primary", 4.5))
+ ],
+ *[(f"series-{n}", "release-ground", 3.0, f"Series {n} on release ground") for n in range(1, 6)],
]
diff --git a/packages/ui/styles/globals.css b/packages/ui/styles/globals.css
index 11b2427d8..60767385f 100644
--- a/packages/ui/styles/globals.css
+++ b/packages/ui/styles/globals.css
@@ -145,6 +145,14 @@
--color-heat-3: color-mix(in srgb, var(--color-accent-primary) 50%, var(--color-bg-surface));
--color-heat-4: var(--color-accent-primary);
--color-heat-5: var(--color-accent-hover);
+ /* Release moment (What's new) — a deeper ground than the overlay plane and
+ a low-opacity orange-to-plum glow band behind the version heading, and
+ the card a linked highlight sits on. Solid values so ink on them is
+ checked (contrast-check.py). */
+ --color-release-ground: var(--color-bg-root);
+ --color-release-card: var(--color-bg-surface);
+ --color-release-glow-1: #f8dfc2;
+ --color-release-glow-2: #e8deef;
/* 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));
@@ -516,6 +524,10 @@
--color-heat-3: color-mix(in srgb, var(--color-accent-primary) 42%, var(--color-bg-surface));
--color-heat-4: color-mix(in srgb, var(--color-accent-primary) 75%, var(--color-bg-surface));
--color-heat-5: var(--color-accent-primary);
+ --color-release-ground: #111013;
+ --color-release-card: #1b191e;
+ --color-release-glow-1: #2b1c0e;
+ --color-release-glow-2: #1f1729;
--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 45ab80ea2..baf06d15c 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -47,6 +47,11 @@
"updateBanner": "repowise <b>v{latest}</b> is available",
"updateBannerCurrent": " (you have v{current})",
"updateBannerCommand": "Run <code>{command}</code> to upgrade.",
+ "updateBannerHighlights": "repowise <b>v{latest}</b> adds {titles}",
+ "newMark": "New",
+ "updatedLabel": "Updated",
+ "updatedNotice": "repowise is now <b>v{version}</b>.",
+ "seeWhatChanged": "See what changed",
"ask": "Ask",
"commandPalette": {
"label": "Command palette",
@@ -96,6 +101,32 @@
"whatsNewModal": {
"title": "What's new in repowise",
"loading": "Loading release notes...",
+ "description": "Release notes for each repowise version: a summary, the numbers, highlights and every change.",
+ "nextRelease": "Next release",
+ "unreleasedNote": "Not released yet. This is what the next release brings so far.",
+ "numbersTitle": "By the numbers",
+ "numbersSince": "{days, plural, =0 {same day as v{since}} one {# day since v{since}} other {# days since v{since}}}",
+ "statPrs": "Pull requests",
+ "statPrsSub": "{count} issues closed",
+ "statContributors": "Contributors",
+ "statContributorsSub": "{count} first-time",
+ "statFiles": "Files changed",
+ "statFilesSub": "+{added} / -{removed} lines",
+ "statFixes": "Fixes",
+ "statFeatures": "{count} features",
+ "statPerf": "{count} performance changes",
+ "statRefactors": "{count} refactors",
+ "statDocs": "{count} documentation changes",
+ "statTests": "Test files",
+ "statTestsSub": "{count} new",
+ "thanks": "Thank you to the {count} contributors who built this release.",
+ "thanksFirst": "Thank you to the {count} contributors who built this release, and welcome to the {first} who made their first contribution.",
+ "highlightsTitle": "Highlights",
+ "open": "Open",
+ "inEachRepo": "Open a repository to see it",
+ "everything": "Everything in this release",
+ "sectionCount": "{count, plural, one {# change} other {# changes}}",
+ "earlier": "Earlier releases",
"unavailable": "Release notes unavailable. <link>View on GitHub</link>"
}
},
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 1e07f888f..20a374c55 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -47,6 +47,11 @@
"updateBanner": "repowise <b>v{latest}</b> 已发布",
"updateBannerCurrent": "(当前 v{current})",
"updateBannerCommand": "运行 <code>{command}</code> 升级。",
+ "updateBannerHighlights": "repowise <b>v{latest}</b> 新增{titles}",
+ "newMark": "新",
+ "updatedLabel": "已更新",
+ "updatedNotice": "repowise 已更新到 <b>v{version}</b>。",
+ "seeWhatChanged": "查看更新内容",
"ask": "提问",
"commandPalette": {
"label": "命令面板",
@@ -96,6 +101,32 @@
"whatsNewModal": {
"title": "repowise 更新内容",
"loading": "正在加载发行说明…",
+ "description": "每个 repowise 版本的发行说明:概要、数据、亮点和全部改动。",
+ "nextRelease": "下一版本",
+ "unreleasedNote": "尚未发布。这是下一版本目前已有的内容。",
+ "numbersTitle": "数据一览",
+ "numbersSince": "{days, plural, =0 {与 v{since} 同日} other {距 v{since} # 天}}",
+ "statPrs": "拉取请求",
+ "statPrsSub": "关闭 {count} 个问题",
+ "statContributors": "贡献者",
+ "statContributorsSub": "{count} 位首次贡献",
+ "statFiles": "改动文件",
+ "statFilesSub": "+{added} / -{removed} 行",
+ "statFixes": "修复",
+ "statFeatures": "{count} 项新功能",
+ "statPerf": "{count} 项性能改进",
+ "statRefactors": "{count} 项重构",
+ "statDocs": "{count} 项文档改动",
+ "statTests": "测试文件",
+ "statTestsSub": "{count} 个新增",
+ "thanks": "感谢参与本次发布的 {count} 位贡献者。",
+ "thanksFirst": "感谢参与本次发布的 {count} 位贡献者,也欢迎 {first} 位首次贡献的朋友。",
+ "highlightsTitle": "亮点",
+ "open": "打开",
+ "inEachRepo": "打开一个仓库即可查看",
+ "everything": "本次发布的全部改动",
+ "sectionCount": "{count, plural, other {# 项改动}}",
+ "earlier": "更早的版本",
"unavailable": "发行说明暂不可用。<link>在 GitHub 上查看</link>"
}
},
diff --git a/packages/web/src/app/layout.tsx b/packages/web/src/app/layout.tsx
index 8c9d2cd3a..d63e94f42 100644
--- a/packages/web/src/app/layout.tsx
+++ b/packages/web/src/app/layout.tsx
@@ -17,6 +17,7 @@ import { ContextDrawerShell } from "@/components/layout/context-drawer-provider"
import { SWRProvider } from "@/components/layout/swr-provider";
import { PreviewBadgeStrings } from "@/components/layout/preview-badge-strings";
import { UpgradeBanner } from "@/components/layout/upgrade-banner";
+import { ReleaseMoment } from "@/components/layout/release-moment";
import { listRepos } from "@/lib/api/repos";
import { getWorkspace } from "@/lib/api/workspace";
import type { WorkspaceResponse } from "@/lib/api/types";
@@ -102,6 +103,7 @@ export default async function RootLayout({
transcript) flows across sheets instead of one viewport. */}
<div className="flex h-screen flex-col overflow-hidden print:block print:h-auto print:overflow-visible">
<UpgradeBanner />
+ <ReleaseMoment firstRepoId={repos[0]?.id ?? null} />
<div className="flex flex-1 overflow-hidden print:block print:overflow-visible">
<Sidebar
repos={repos}
diff --git a/packages/web/src/components/layout/mobile-nav.tsx b/packages/web/src/components/layout/mobile-nav.tsx
index ed3e87509..29709d1b8 100644
--- a/packages/web/src/components/layout/mobile-nav.tsx
+++ b/packages/web/src/components/layout/mobile-nav.tsx
@@ -18,6 +18,8 @@ import { ScrollArea } from "@repowise-dev/ui/ui/scroll-area";
import { Separator } from "@repowise-dev/ui/ui/separator";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
import { VersionFooter } from "./version-footer";
+import { NewMark } from "./new-mark";
+import { useIsNewSurface } from "@/lib/hooks/use-new-surfaces";
import { FeedbackButton } from "./feedback-button";
import { LanguageSwitcher } from "./language-switcher";
import { ThemeToggle } from "@repowise-dev/ui/shared/theme-toggle";
@@ -39,6 +41,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
const t = useTranslations("nav");
const ts = useTranslations("shell");
const isWorkspace = workspace?.is_workspace ?? false;
+ const isNew = useIsNewSurface();
const [open, setOpen] = React.useState(false);
const pathname = usePathname();
const activeRepoId = React.useMemo(() => {
@@ -135,6 +138,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
/>
</span>
<span className="truncate">{t(item.labelKey)}</span>
+ {isNew(item.href) && <NewMark />}
</Link>
);
})}
@@ -244,6 +248,7 @@ export function MobileNav({ repos = [], workspace }: MobileNavProps) {
/>
</span>
<span className="truncate">{t(item.labelKey)}</span>
+ {isNew(item.href) && <NewMark />}
</Link>
);
})}
diff --git a/packages/web/src/components/layout/new-mark.tsx b/packages/web/src/components/layout/new-mark.tsx
new file mode 100644
index 000000000..cba392fe0
--- /dev/null
+++ b/packages/web/src/components/layout/new-mark.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { useTranslations } from "next-intl";
+import { useIsNewSurface } from "@/lib/hooks/use-new-surfaces";
+
+/** Whether a nav item's page is new, and its accessible name with the mark
+ * spelled out (the icon rail shows only a dot). */
+export function useNavNewMark(href: string, label: string) {
+ const t = useTranslations("shell");
+ const isNew = useIsNewSurface()(href);
+ return { isNew, ariaLabel: isNew ? `${label}, ${t("newMark")}` : label };
+}
+
+/** Dot plus "New" beside a nav label for a page the latest upgrade added or
+ * changed. `dotOnly` for the collapsed icon rail, with the word kept for
+ * screen readers. */
+export function NewMark({ dotOnly = false }: { dotOnly?: boolean }) {
+ const t = useTranslations("shell");
+ if (dotOnly) {
+ return (
+ <span className="absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-[var(--color-info)]">
+ <span className="sr-only">{t("newMark")}</span>
+ </span>
+ );
+ }
+ return (
+ <span className="ml-auto inline-flex shrink-0 items-center gap-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-info)]">
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-[var(--color-info)]" />
+ {t("newMark")}
+ </span>
+ );
+}
diff --git a/packages/web/src/components/layout/release-moment.test.tsx b/packages/web/src/components/layout/release-moment.test.tsx
new file mode 100644
index 000000000..c129dbcf9
--- /dev/null
+++ b/packages/web/src/components/layout/release-moment.test.tsx
@@ -0,0 +1,50 @@
+// @vitest-environment jsdom
+
+import { StrictMode } from "react";
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ReleaseMoment } from "./release-moment";
+
+const meta = vi.hoisted(() => ({ server_version: "0.57.0", highlights: [] as unknown[] }));
+
+vi.mock("@/lib/hooks/use-meta-version", () => ({
+ useMetaVersion: () => ({ meta }),
+ useChangelog: () => ({ entries: [], error: null, isLoading: false }),
+}));
+vi.mock("next/navigation", () => ({ usePathname: () => "/" }));
+
+beforeEach(() => window.localStorage.clear());
+afterEach(cleanup);
+
+describe("ReleaseMoment", () => {
+ it("opens What's new once after a minor upgrade, even under StrictMode", () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.56.0");
+ render(
+ <StrictMode>
+ <ReleaseMoment />
+ </StrictMode>,
+ );
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ });
+
+ it("opens on load for a browser that used repowise before the key existed", () => {
+ window.localStorage.setItem("repowise:locale", "en");
+ render(<ReleaseMoment />);
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ });
+
+ it("stays quiet on a first visit", () => {
+ render(<ReleaseMoment />);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(window.localStorage.getItem("repowise:last-seen-server-version")).toBe("0.57.0");
+ });
+
+ it("shows the quiet note after a patch upgrade", () => {
+ meta.server_version = "0.57.1";
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.57.0");
+ render(<ReleaseMoment />);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(screen.getByText("See what changed")).toBeTruthy();
+ meta.server_version = "0.57.0";
+ });
+});
diff --git a/packages/web/src/components/layout/release-moment.tsx b/packages/web/src/components/layout/release-moment.tsx
new file mode 100644
index 000000000..c5d36ee9b
--- /dev/null
+++ b/packages/web/src/components/layout/release-moment.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { usePathname } from "next/navigation";
+import { X } from "lucide-react";
+import { useTranslations } from "next-intl";
+import { Callout } from "@repowise-dev/ui/shared/callout";
+import { useChangelog, useMetaVersion } from "@/lib/hooks/use-meta-version";
+import {
+ decideMoment,
+ rememberRepo,
+ startNewSurfaces,
+ visitNewSurface,
+ type UpgradeMoment,
+} from "@/lib/release-moment";
+import { WhatsNewModal } from "./whats-new-modal";
+
+/**
+ * The once-per-version "you just upgraded" moment: the What's new dialog for a
+ * minor release, a quiet note for a patch, nothing on a fresh browser. Also
+ * clears a page's "New" mark once it is visited. The decision itself lives in
+ * `decideMoment`.
+ *
+ * `?whats-new=preview` (dialog) and `?whats-new=patch` (note) replay it on
+ * demand, using the newest changelog entry, without changing what this
+ * browser has seen. Read on a full page load only.
+ */
+export function ReleaseMoment({ firstRepoId = null }: { firstRepoId?: string | null }) {
+ const { version, moment, setMoment, preview } = useReleaseMoment(firstRepoId);
+ const [dialogOpen, setDialogOpen] = useState(false);
+
+ useEffect(() => {
+ if (moment === "dialog") setDialogOpen(true);
+ }, [moment]);
+
+ if (!version) return null;
+ return (
+ <>
+ {moment === "notice" && (
+ <UpdatedNote
+ version={version}
+ onOpen={() => setDialogOpen(true)}
+ onDismiss={() => setMoment("none")}
+ />
+ )}
+ <WhatsNewModal
+ open={dialogOpen}
+ onOpenChange={(open) => {
+ setDialogOpen(open);
+ if (!open) setMoment("none");
+ }}
+ version={preview ? null : version}
+ fresh
+ />
+ </>
+ );
+}
+
+function useReleaseMoment(firstRepoId: string | null) {
+ const { meta } = useMetaVersion();
+ const pathname = usePathname();
+ const [moment, setMoment] = useState<UpgradeMoment>("none");
+ const [preview, setPreview] = useState(false);
+ const version = meta?.server_version ?? null;
+
+ // Once per version: StrictMode runs effects twice in development, and the
+ // second run would read the version the first one stored.
+ const decided = useRef<string | null>(null);
+ useEffect(() => {
+ if (!version || !meta || decided.current === version) return;
+ decided.current = version;
+ const next = decideMoment(version, meta.highlights ?? [], window.location.search);
+ setPreview(next.preview);
+ setMoment(next.moment);
+ // `meta` refreshes hourly with the same version; the version is the key.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [version]);
+
+ // A preview marks the newest entry's pages, which in a development build is
+ // the next release's.
+ const { entries } = useChangelog(preview);
+ const newest = entries[0];
+ useEffect(() => {
+ if (preview && newest) startNewSurfaces(newest.version, newest.highlights ?? []);
+ }, [preview, newest]);
+
+ useEffect(() => {
+ if (pathname) visitNewSurface(pathname);
+ rememberRepo(pathname, firstRepoId);
+ }, [pathname, firstRepoId]);
+
+ return { version, moment, setMoment, preview };
+}
+
+function UpdatedNote({
+ version,
+ onOpen,
+ onDismiss,
+}: {
+ version: string;
+ onOpen: () => void;
+ onDismiss: () => void;
+}) {
+ const t = useTranslations("shell");
+ const tc = useTranslations("common");
+ return (
+ <div className="px-3 pt-2 sm:px-[var(--page-pad)]">
+ <Callout
+ tone="info"
+ label={t("updatedLabel")}
+ className="py-1.5"
+ action={
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label={tc("dismiss")}
+ className="rounded p-1.5 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ }
+ >
+ {t.rich("updatedNotice", {
+ version,
+ b: (chunks) => <span className="font-medium">{chunks}</span>,
+ })}{" "}
+ <button
+ type="button"
+ onClick={onOpen}
+ className="text-[var(--color-accent-primary)] underline-offset-2 hover:underline"
+ >
+ {t("seeWhatChanged")}
+ </button>
+ </Callout>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/layout/release-notes.tsx b/packages/web/src/components/layout/release-notes.tsx
new file mode 100644
index 000000000..0ba08b9ba
--- /dev/null
+++ b/packages/web/src/components/layout/release-notes.tsx
@@ -0,0 +1,304 @@
+"use client";
+
+import Link from "next/link";
+import { useMemo, useState, type ReactNode } from "react";
+import { ArrowRight } from "lucide-react";
+import { useFormatter, useTranslations } from "next-intl";
+import { Markdown } from "@repowise-dev/ui/shared/markdown";
+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";
+
+export function releaseName(version: string, nextLabel: string): string {
+ return version === "unreleased" ? nextLabel : `v${version}`;
+}
+
+/** The band at the top of the dialog: the version as the display heading. */
+export function ReleaseHeader({
+ entry,
+ title,
+}: {
+ entry: ChangelogEntry;
+ /** The dialog title, rendered above the version (a `DialogTitle`). */
+ title: ReactNode;
+}) {
+ 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 }}
+ >
+ {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">
+ {releaseName(entry.version, t("nextRelease"))}
+ </span>
+ {entry.label && (
+ <span className="font-mono text-xs text-[var(--color-text-secondary)]">{entry.label}</span>
+ )}
+ </h3>
+ {entry.version === "unreleased" && (
+ <p className="mt-2 text-xs text-[var(--color-text-secondary)]">{t("unreleasedNote")}</p>
+ )}
+ </header>
+ );
+}
+
+/** One release below its header: summary, the numbers, highlights, then
+ * every change. */
+export function ReleaseNotes({
+ entry,
+ repoId,
+ fresh,
+ onNavigate,
+}: {
+ entry: ChangelogEntry;
+ /** The repository the reader is in, for repo-scoped highlight routes. */
+ repoId: string | null;
+ /** Marks the highlights "New": the reader just upgraded to this release. */
+ fresh: boolean;
+ onNavigate: () => void;
+}) {
+ const t = useTranslations("shell.whatsNewModal");
+ const highlights = entry.highlights ?? [];
+ const sections = entry.sections.filter((s) => s.items.length > 0);
+
+ return (
+ <article className="space-y-8" aria-labelledby={`release-${entry.version}`}>
+ {entry.summary && (
+ <div className="text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ <Markdown content={linkPullRequests(entry.summary)} density="narrow" fill />
+ </div>
+ )}
+ {entry.stats && <ReleaseNumbers stats={entry.stats} />}
+ {highlights.length > 0 && (
+ <Block id={`highlights-${entry.version}`} title={t("highlightsTitle")}>
+ <ul className="grid gap-2.5 sm:grid-cols-2">
+ {highlights.map((h, i) => (
+ <li key={h.id} className={`flex ${ENTER}`}>
+ <HighlightItem
+ highlight={h}
+ href={resolveHighlightHref(h.href, repoId)}
+ color={seriesColor(i)}
+ fresh={fresh}
+ onNavigate={onNavigate}
+ />
+ </li>
+ ))}
+ </ul>
+ </Block>
+ )}
+ {sections.length > 0 && (
+ <Block id={`all-${entry.version}`} title={t("everything")}>
+ <div className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ {sections.map((s) => (
+ <ChangeSection key={s.name} name={s.name} items={s.items} />
+ ))}
+ </div>
+ </Block>
+ )}
+ </article>
+ );
+}
+
+/** A titled part of the release: micro-label heading, then its content. */
+function Block({ id, title, children }: { id: string; title: string; children: ReactNode }) {
+ return (
+ <section className="space-y-3" aria-labelledby={id}>
+ <h4 id={id} className={MICRO}>
+ {title}
+ </h4>
+ {children}
+ </section>
+ );
+}
+
+/** A card only when it opens something; a highlight with no page keeps its
+ * colour as a dot and stays plain. */
+function HighlightItem({
+ highlight: h,
+ href,
+ color,
+ fresh,
+ onNavigate,
+}: {
+ highlight: ChangelogHighlight;
+ /** Resolved route, or null when there is none for this reader. */
+ href: string | null;
+ color: string;
+ fresh: boolean;
+ onNavigate: () => void;
+}) {
+ const t = useTranslations("shell.whatsNewModal");
+ const body = (
+ <>
+ <p className="flex items-baseline gap-2 text-[15px] font-medium text-[var(--color-text-primary)]">
+ {h.title}
+ {fresh && <NewMark />}
+ </p>
+ {h.blurb && (
+ <p className="mt-1 text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {h.blurb}
+ </p>
+ )}
+ </>
+ );
+ if (href) {
+ return (
+ <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)]"
+ style={{ borderLeftColor: color }}
+ >
+ {body}
+ <span className="mt-auto inline-flex items-center gap-1 pt-2 text-xs text-[var(--color-accent-primary)] group-hover:underline">
+ {t("open")}
+ <ArrowRight aria-hidden className="h-3 w-3" />
+ </span>
+ </Link>
+ );
+ }
+ return (
+ <div className="flex w-full gap-3 px-1 py-3">
+ <span aria-hidden className="mt-1.5 h-2 w-2 shrink-0 rounded-full" style={{ background: color }} />
+ <div className="min-w-0">
+ {body}
+ {h.href && <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">{t("inEachRepo")}</p>}
+ </div>
+ </div>
+ );
+}
+
+function ChangeSection({ name, items }: { name: string; items: string[] }) {
+ const t = useTranslations("shell.whatsNewModal");
+ // Rendered only once opened: a release's Fixed list runs to a hundred bullets.
+ const [opened, setOpened] = useState(false);
+ return (
+ <details
+ className="group/section"
+ onToggle={(e) => {
+ if (e.currentTarget.open) setOpened(true);
+ }}
+ >
+ <summary className="flex cursor-pointer list-none items-baseline gap-2 rounded py-2 text-sm text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]">
+ <span aria-hidden className="text-[var(--color-text-tertiary)] group-open/section:rotate-90 motion-safe:transition-transform">
+ ›
+ </span>
+ <span className="font-medium">{name}</span>
+ <span className="text-xs tabular-nums text-[var(--color-text-tertiary)]">
+ {t("sectionCount", { count: items.length })}
+ </span>
+ </summary>
+ {opened && <SectionBody items={items} />}
+ </details>
+ );
+}
+
+function SectionBody({ items }: { items: string[] }) {
+ const content = useMemo(
+ () => items.map((i) => `- ${linkPullRequests(i)}`).join("\n"),
+ [items],
+ );
+ return (
+ <div className="pb-2 pl-4 text-[var(--color-text-secondary)]">
+ <Markdown content={content} density="compact" fill />
+ </div>
+ );
+}
+
+interface Figure {
+ label: string;
+ value: string;
+ sub?: string | undefined;
+}
+
+/** "By the numbers": large figures, each over a short bar in its series
+ * colour, then the thank-you. No names: the counts carry the credit. */
+export function ReleaseNumbers({ stats }: { stats: ReleaseStats }) {
+ const t = useTranslations("shell.whatsNewModal");
+ const format = useFormatter();
+ const n = (v: number | null | undefined) => format.number(v ?? 0);
+ const first = stats.first_time_contributors ?? 0;
+ // Kinds with no commits are left out; "0 performance changes" says nothing.
+ const kt = stats.types;
+ const kinds = (
+ [
+ ["statFeatures", kt.features],
+ ["statPerf", kt.perf],
+ ["statRefactors", kt.refactors],
+ ["statDocs", kt.docs],
+ ] as const
+ )
+ .filter(([, count]) => !!count)
+ .map(([key, count]) => t(key, { count: n(count) }));
+ const kindsSub = kinds.length ? format.list(kinds, { type: "conjunction" }) : undefined;
+
+ const figures: Figure[] = [
+ { label: t("statPrs"), value: n(stats.prs), sub: t("statPrsSub", { count: n(stats.issues_closed) }) },
+ {
+ label: t("statContributors"),
+ value: n(stats.contributors),
+ sub: first ? t("statContributorsSub", { count: n(first) }) : undefined,
+ },
+ {
+ label: t("statFiles"),
+ value: n(stats.files_changed),
+ sub: t("statFilesSub", { added: n(stats.lines_added), removed: n(stats.lines_removed) }),
+ },
+ ...(kt.fixes ? [{ label: t("statFixes"), value: n(kt.fixes), sub: kindsSub }] : []),
+ {
+ label: t("statTests"),
+ value: n(stats.test_files_touched),
+ sub: t("statTestsSub", { count: n(stats.test_files_new) }),
+ },
+ ];
+
+ return (
+ <section className="space-y-4" aria-label={t("numbersTitle")}>
+ <p className={MICRO}>
+ {t("numbersTitle")} · {t("numbersSince", { days: stats.days, since: stats.since })}
+ </p>
+ <dl className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-3 lg:grid-cols-5">
+ {figures.map((f, i) => (
+ <div key={f.label} className={`min-w-0 ${ENTER}`}>
+ <span
+ aria-hidden
+ className="mb-2.5 block h-[3px] w-8 rounded-full"
+ style={{ background: seriesColor(i) }}
+ />
+ <dt className={MICRO}>{f.label}</dt>
+ <dd className="mt-1 text-3xl font-semibold tabular-nums tracking-tight text-[var(--color-text-primary)]">
+ {f.value}
+ </dd>
+ {f.sub && (
+ <dd className="mt-1 text-xs tabular-nums leading-snug text-[var(--color-text-secondary)]">
+ {f.sub}
+ </dd>
+ )}
+ </div>
+ ))}
+ </dl>
+ <p className="text-sm leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {first
+ ? t("thanksFirst", { count: n(stats.contributors), first: n(first) })
+ : t("thanks", { count: n(stats.contributors) })}
+ </p>
+ </section>
+ );
+}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 2b794557f..fd1309f47 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -26,6 +26,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@repowise-dev/ui/ui/too
import { ThemeToggle } from "@repowise-dev/ui/shared/theme-toggle";
import { AddRepoDialog } from "@/components/repos/add-repo-dialog";
import { VersionFooter } from "./version-footer";
+import { NewMark, useNavNewMark } from "./new-mark";
import { FeedbackButton } from "./feedback-button";
import { LanguageSwitcher } from "./language-switcher";
import type { RepoResponse, WorkspaceResponse } from "@/lib/api/types";
@@ -564,6 +565,7 @@ function SidebarNavItem({
const t = useTranslations("nav");
const label = t(item.labelKey);
const Icon = item.icon;
+ const { isNew, ariaLabel } = useNavNewMark(item.href, label);
if (iconOnly) {
return (
@@ -571,15 +573,16 @@ function SidebarNavItem({
<TooltipTrigger asChild>
<Link
href={item.href}
- aria-label={label}
+ aria-label={ariaLabel}
className={cn(
- "flex items-center justify-center rounded-lg p-2.5 transition-colors",
+ "relative flex items-center justify-center rounded-lg p-2.5 transition-colors",
isActive
? "bg-[var(--color-bg-elevated)] text-[var(--color-accent-primary)]"
: "text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]",
)}
>
<Icon className="h-[18px] w-[18px] shrink-0" />
+ {isNew && <NewMark dotOnly />}
</Link>
</TooltipTrigger>
<TooltipContent side="right">{label}</TooltipContent>
@@ -602,6 +605,7 @@ function SidebarNavItem({
/>
</RowGlyph>
<span className="truncate">{label}</span>
+ {isNew && <NewMark />}
</Link>
);
}
diff --git a/packages/web/src/components/layout/upgrade-banner.tsx b/packages/web/src/components/layout/upgrade-banner.tsx
index 305dd611c..2a89c16b8 100644
--- a/packages/web/src/components/layout/upgrade-banner.tsx
+++ b/packages/web/src/components/layout/upgrade-banner.tsx
@@ -3,11 +3,13 @@
import { useEffect, useState } from "react";
import { X } from "lucide-react";
import { Callout } from "@repowise-dev/ui/shared/callout";
-import { useTranslations } from "next-intl";
+import { useFormatter, useTranslations } from "next-intl";
import { useMetaVersion } from "@/lib/hooks/use-meta-version";
import { WhatsNewModal } from "./whats-new-modal";
const STORAGE_PREFIX = "repowise:upgrade-banner-dismissed:v";
+/** Highlight titles named in the banner; the rest wait in the release notes. */
+const BANNER_TITLES = 2;
/**
* Global, non-blocking "newer release available" banner. Dismissal is keyed per
@@ -17,6 +19,7 @@ const STORAGE_PREFIX = "repowise:upgrade-banner-dismissed:v";
export function UpgradeBanner() {
const t = useTranslations("shell");
const tc = useTranslations("common");
+ const format = useFormatter();
const { meta } = useMetaVersion();
const [dismissed, setDismissed] = useState(true);
const [showWhatsNew, setShowWhatsNew] = useState(false);
@@ -34,6 +37,7 @@ export function UpgradeBanner() {
}, [updateAvailable, latest]);
if (!updateAvailable || dismissed) return null;
+ const titles = (meta?.latest_highlights ?? []).slice(0, BANNER_TITLES);
const dismiss = () => {
try {
@@ -62,10 +66,18 @@ export function UpgradeBanner() {
</button>
}
>
- {t.rich("updateBanner", {
- latest,
- b: (chunks) => <span className="font-medium">{chunks}</span>,
- })}
+ {/* Names what the newer release brings when GitHub could be read,
+ otherwise the plain "is available". */}
+ {titles.length > 0
+ ? t.rich("updateBannerHighlights", {
+ latest,
+ titles: format.list(titles, { type: "conjunction" }),
+ b: (chunks) => <span className="font-medium">{chunks}</span>,
+ })
+ : t.rich("updateBanner", {
+ latest,
+ b: (chunks) => <span className="font-medium">{chunks}</span>,
+ })}
{meta?.server_version ? (
<span className="hidden text-[var(--color-text-tertiary)] sm:inline">
{t("updateBannerCurrent", { current: meta.server_version })}
diff --git a/packages/web/src/components/layout/whats-new-modal.test.tsx b/packages/web/src/components/layout/whats-new-modal.test.tsx
new file mode 100644
index 000000000..ba2587b05
--- /dev/null
+++ b/packages/web/src/components/layout/whats-new-modal.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import type { ChangelogEntry } from "@/lib/api/meta";
+import { WhatsNewModal } from "./whats-new-modal";
+
+const ENTRIES: ChangelogEntry[] = [
+ {
+ version: "0.57.0",
+ label: "2026-10-20",
+ summary: "Chat draws charts (#3860).",
+ highlights: [
+ { id: "charts-in-chat", title: "Charts in chat", blurb: "Any chart.", href: "/repos/:id/chat" },
+ { id: "settings", title: "Models from Settings", blurb: "Live lists.", href: "/settings" },
+ { id: "palette", title: "One palette", blurb: "Same colours.", href: null },
+ ],
+ stats: {
+ since: "0.56.0",
+ days: 8,
+ prs: 1205,
+ contributors: 24,
+ first_time_contributors: 11,
+ files_changed: 1226,
+ lines_added: 103206,
+ lines_removed: 11127,
+ types: { fixes: 147, features: 45, perf: 0, refactors: 4, docs: 6 },
+ test_files_touched: 437,
+ test_files_new: 144,
+ issues_closed: 25,
+ },
+ sections: [{ name: "Fixed", items: ["A fix (#12)."] }],
+ },
+ {
+ version: "0.56.0",
+ label: "2026-10-12",
+ summary: "The earlier release.",
+ highlights: [],
+ stats: null,
+ sections: [{ name: "Added", items: ["Old thing."] }],
+ },
+];
+
+vi.mock("@/lib/hooks/use-meta-version", () => ({
+ useChangelog: () => ({ entries: ENTRIES, error: null, isLoading: false }),
+}));
+vi.mock("next/navigation", () => ({ usePathname: () => "/repos/r1/overview" }));
+
+describe("WhatsNewModal", () => {
+ it("leads with the release, its numbers and highlights", () => {
+ render(<WhatsNewModal open onOpenChange={() => {}} version="0.57.0" fresh />);
+ const dialog = screen.getByRole("dialog");
+ expect(within(dialog).getByText("v0.57.0")).toBeTruthy();
+ expect(within(dialog).getByRole("link", { name: "#3860" }).getAttribute("href")).toBe(
+ "https://github.com/repowise-dev/repowise/pull/3860",
+ );
+ // Locale separators, and no contributor names anywhere.
+ expect(within(dialog).getByText("1,205")).toBeTruthy();
+ expect(within(dialog).getByText("+103,206 / -11,127 lines")).toBeTruthy();
+ expect(within(dialog).getByText(/welcome to the 11 who made their first contribution/)).toBeTruthy();
+ expect(dialog.textContent).not.toContain("@");
+ // Kinds with no commits are left out of the strip.
+ expect(within(dialog).getByText(/^45 features, 4 refactors,? and 6 documentation changes$/)).toBeTruthy();
+ expect(dialog.textContent).not.toContain("performance");
+ // Repo-scoped routes resolve to the repository being read.
+ expect(within(dialog).getByRole("link", { name: /^Charts in chat/ }).getAttribute("href")).toBe(
+ "/repos/r1/chat",
+ );
+ expect(within(dialog).getByRole("link", { name: /^Models from Settings/ }).getAttribute("href")).toBe(
+ "/settings",
+ );
+ expect(within(dialog).getAllByText("New")).toHaveLength(3);
+ });
+
+ it("keeps every change collapsed until opened", () => {
+ render(<WhatsNewModal open onOpenChange={() => {}} version="0.57.0" />);
+ const dialog = screen.getByRole("dialog");
+ expect(within(dialog).queryByText("New")).toBeNull();
+ expect(within(dialog).queryByText(/A fix/)).toBeNull();
+ const details = within(dialog).getByText("Fixed").closest("details")!;
+ details.open = true;
+ fireEvent(details, new Event("toggle"));
+ expect(within(dialog).getByText(/A fix/)).toBeTruthy();
+ });
+
+ it("switches to an earlier release", () => {
+ render(<WhatsNewModal open onOpenChange={() => {}} version="0.57.0" />);
+ const dialog = screen.getByRole("dialog");
+ fireEvent.click(within(dialog).getByRole("button", { name: /v0\.56\.0/ }));
+ expect(within(dialog).getByText("The earlier release.")).toBeTruthy();
+ expect(within(dialog).queryByText("By the numbers", { exact: false })).toBeNull();
+ });
+});
diff --git a/packages/web/src/components/layout/whats-new-modal.tsx b/packages/web/src/components/layout/whats-new-modal.tsx
index 2422d2376..087e09fc6 100644
--- a/packages/web/src/components/layout/whats-new-modal.tsx
+++ b/packages/web/src/components/layout/whats-new-modal.tsx
@@ -1,32 +1,75 @@
"use client";
+import { useEffect, useState } from "react";
+import { usePathname } from "next/navigation";
import {
Dialog,
DialogContent,
+ DialogDescription,
DialogHeader,
DialogTitle,
} from "@repowise-dev/ui/ui/dialog";
import { useChangelog } from "@/lib/hooks/use-meta-version";
+import { highlightRepoId } from "@/lib/release-moment";
import { useTranslations } from "next-intl";
+import { ReleaseHeader, ReleaseNotes, releaseName } from "./release-notes";
+
+/** How many earlier releases the switcher lists. */
+const EARLIER_SHOWN = 8;
export interface WhatsNewModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
+ /** Release to open on. Defaults to the newest entry in the changelog. */
+ version?: string | null;
+ /** The reader just upgraded to `version`: its highlights read "New". */
+ fresh?: boolean;
}
-/** Renders repowise's recent release notes from the bundled changelog. */
-export function WhatsNewModal({ open, onOpenChange }: WhatsNewModalProps) {
+/** repowise's release notes from the bundled changelog: the chosen release on
+ * top, earlier ones a click away. */
+export function WhatsNewModal({ open, onOpenChange, version, fresh = false }: WhatsNewModalProps) {
const t = useTranslations("shell");
+ const pathname = usePathname();
// Only fetch once the modal is opened.
const { entries, error, isLoading } = useChangelog(open);
+ const [selected, setSelected] = useState<string | null>(null);
+
+ // Each opening starts on the release it was opened for.
+ useEffect(() => {
+ if (open) setSelected(null);
+ }, [open, version]);
+
+ // With no version to open on (a preview), the next release leads when it
+ // has highlights; in a released build there is no such entry.
+ const fallback =
+ entries.find((e) => e.version === version) ??
+ entries.find((e) => e.version === "unreleased" && (e.highlights?.length ?? 0) > 0) ??
+ entries[0];
+ const entry = entries.find((e) => e.version === selected) ?? fallback;
+ const earlier = entries.filter((e) => e !== entry).slice(0, EARLIER_SHOWN);
+
+ const title = (
+ <DialogHeader>
+ <DialogTitle className="font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-secondary)]">
+ {t("whatsNewModal.title")}
+ </DialogTitle>
+ <DialogDescription className="sr-only">{t("whatsNewModal.description")}</DialogDescription>
+ </DialogHeader>
+ );
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="max-h-[80vh] overflow-y-auto sm:max-w-2xl">
- <DialogHeader>
- <DialogTitle>{t("whatsNewModal.title")}</DialogTitle>
- </DialogHeader>
+ {/* 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">
+ {entry ? (
+ <ReleaseHeader key={`h-${entry.version}`} entry={entry} title={title} />
+ ) : (
+ <div className="px-6 pt-6 sm:px-8">{title}</div>
+ )}
+ <div className="space-y-8 px-6 py-6 sm:px-8">
{isLoading && (
<p className="text-sm text-[var(--color-text-tertiary)]">
{t("whatsNewModal.loading")}
@@ -49,38 +92,44 @@ export function WhatsNewModal({ open, onOpenChange }: WhatsNewModalProps) {
</p>
)}
- <div className="space-y-6">
- {entries.map((entry) => (
- <section key={entry.version} className="space-y-2">
- <h3 className="flex items-baseline gap-2">
- <span className="text-base font-semibold text-[var(--color-text-primary)]">
- v{entry.version}
- </span>
- {entry.label && (
- <span className="text-xs text-[var(--color-text-tertiary)]">{entry.label}</span>
- )}
- </h3>
- {entry.sections.map((section) => (
- <div key={section.name} className="space-y-1">
- <p className="text-xs font-medium uppercase tracking-wide text-[var(--color-text-secondary)]">
- {section.name}
- </p>
- <ul className="list-disc space-y-1 pl-5 text-sm text-[var(--color-text-secondary)]">
- {section.items.map((item, i) => (
- <li key={i}>{stripMarkdown(item)}</li>
- ))}
- </ul>
- </div>
+ {entry && (
+ <ReleaseNotes
+ key={entry.version}
+ entry={entry}
+ repoId={highlightRepoId(pathname)}
+ fresh={fresh && entry === fallback}
+ onNavigate={() => onOpenChange(false)}
+ />
+ )}
+
+ {earlier.length > 0 && (
+ <nav
+ aria-label={t("whatsNewModal.earlier")}
+ className="space-y-1.5 border-t border-[var(--color-border-default)] pt-4"
+ >
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {t("whatsNewModal.earlier")}
+ </p>
+ <ul className="flex flex-wrap gap-x-4 gap-y-1">
+ {earlier.map((e) => (
+ <li key={e.version}>
+ <button
+ type="button"
+ onClick={() => setSelected(e.version)}
+ className="rounded text-xs text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {releaseName(e.version, t("whatsNewModal.nextRelease"))}
+ {e.label && (
+ <span className="ml-1 text-[var(--color-text-tertiary)]">{e.label}</span>
+ )}
+ </button>
+ </li>
))}
- </section>
- ))}
+ </ul>
+ </nav>
+ )}
</div>
</DialogContent>
</Dialog>
);
}
-
-/** Light touch: drop bold markers so they don't render as literal asterisks. */
-function stripMarkdown(text: string): string {
- return text.replace(/\*\*/g, "");
-}
diff --git a/packages/web/src/lib/hooks/use-new-surfaces.ts b/packages/web/src/lib/hooks/use-new-surfaces.ts
new file mode 100644
index 000000000..058b6a21e
--- /dev/null
+++ b/packages/web/src/lib/hooks/use-new-surfaces.ts
@@ -0,0 +1,30 @@
+"use client";
+
+import { useCallback, useSyncExternalStore } from "react";
+import {
+ activeNewRoutes,
+ readNewSurfaces,
+ routeMatches,
+ subscribeNewSurfaces,
+} from "@/lib/release-moment";
+
+// The snapshot is the joined route list, a string, so an unchanged value keeps
+// its identity and the nav does not re-render on every storage event.
+function snapshot(): string {
+ return activeNewRoutes(readNewSurfaces(), Date.now()).join("\n");
+}
+
+/** Whether a nav href opens a page the latest upgrade highlighted. */
+export function useIsNewSurface(): (href: string) => boolean {
+ const joined = useSyncExternalStore(subscribeNewSurfaces, snapshot, () => "");
+ return useCallback(
+ (href: string) => !!joined && joined.split("\n").some((r) => routeMatches(r, href) && sameDepth(r, href)),
+ [joined],
+ );
+}
+
+// A nav item marks only its own page, not a parent of it: `/repos/:id` is not
+// the chat page.
+function sameDepth(route: string, href: string): boolean {
+ return route.split("/").filter(Boolean).length === href.split("/").filter(Boolean).length;
+}
diff --git a/packages/web/src/lib/release-moment.test.ts b/packages/web/src/lib/release-moment.test.ts
new file mode 100644
index 000000000..1711eba37
--- /dev/null
+++ b/packages/web/src/lib/release-moment.test.ts
@@ -0,0 +1,150 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ NEW_MARK_DAYS,
+ activeNewRoutes,
+ decideMoment,
+ highlightRepoId,
+ rememberRepo,
+ linkPullRequests,
+ previewMoment,
+ readNewSurfaces,
+ repoIdFromPath,
+ resolveHighlightHref,
+ routeMatches,
+ startNewSurfaces,
+ takeUpgradeMoment,
+ upgradeMoment,
+ visitNewSurface,
+} from "./release-moment";
+
+const HL = (href: string | null) => ({ id: "x", title: "X", blurb: "", href });
+
+beforeEach(() => window.localStorage.clear());
+
+describe("upgradeMoment", () => {
+ it("shows nothing on a first visit, a repeat, or a downgrade", () => {
+ expect(upgradeMoment(null, "0.57.0", true)).toBe("none");
+ expect(upgradeMoment("0.57.0", "0.57.0", true)).toBe("none");
+ expect(upgradeMoment("0.57.1", "0.57.0", true)).toBe("none");
+ });
+
+ it("opens the dialog for a minor release or one with highlights", () => {
+ expect(upgradeMoment("0.56.3", "0.57.0", false)).toBe("dialog");
+ expect(upgradeMoment("0.57.0", "0.57.1", true)).toBe("dialog");
+ });
+
+ it("shows the quiet note for a patch", () => {
+ expect(upgradeMoment("0.57.0", "0.57.1", false)).toBe("notice");
+ });
+});
+
+describe("takeUpgradeMoment", () => {
+ it("stores silently on the first visit, then fires once per version", () => {
+ expect(takeUpgradeMoment("0.56.0", false)).toBe("none");
+ expect(takeUpgradeMoment("0.57.0", true)).toBe("dialog");
+ expect(takeUpgradeMoment("0.57.0", true)).toBe("none");
+ expect(takeUpgradeMoment("0.57.1", false)).toBe("notice");
+ expect(takeUpgradeMoment("0.57.1", false)).toBe("none");
+ });
+});
+
+describe("browsers from before the last-seen key", () => {
+ it("counts earlier repowise state as an upgrade", () => {
+ window.localStorage.setItem("repowise:upgrade-banner-dismissed:v0.55.0", "1");
+ expect(takeUpgradeMoment("0.57.0", true)).toBe("dialog");
+ expect(takeUpgradeMoment("0.57.0", true)).toBe("none");
+ });
+
+ it("counts underscore keys too, and a patch gets the note", () => {
+ window.localStorage.setItem("repowise_chat_hint_seen", "1");
+ expect(takeUpgradeMoment("0.57.1", false)).toBe("notice");
+ });
+
+ it("keeps a truly fresh browser quiet", () => {
+ window.localStorage.setItem("theme", "dark");
+ expect(takeUpgradeMoment("0.57.0", true)).toBe("none");
+ });
+});
+
+describe("new surfaces", () => {
+ it("marks highlight routes until visited", () => {
+ startNewSurfaces("0.57.0", [HL("/repos/:id/chat"), HL("/settings"), HL(null)]);
+ const now = Date.now();
+ expect(activeNewRoutes(readNewSurfaces(), now)).toEqual(["/repos/:id/chat", "/settings"]);
+ visitNewSurface("/repos/abc/chat/42");
+ expect(activeNewRoutes(readNewSurfaces(), now)).toEqual(["/settings"]);
+ });
+
+ it("drops every mark after the window", () => {
+ startNewSurfaces("0.57.0", [HL("/settings")]);
+ const later = Date.now() + (NEW_MARK_DAYS + 1) * 24 * 60 * 60 * 1000;
+ expect(activeNewRoutes(readNewSurfaces(), later)).toEqual([]);
+ });
+
+ it("matches routes by segment", () => {
+ expect(routeMatches("/repos/:id/chat", "/repos/a/chat")).toBe(true);
+ expect(routeMatches("/settings", "/repos/a/settings")).toBe(false);
+ expect(routeMatches("/repos/:id/chat", "/repos/a")).toBe(false);
+ });
+});
+
+describe("links", () => {
+ it("resolves repo-scoped routes for the current repository only", () => {
+ expect(resolveHighlightHref("/repos/:id/chat", "my repo")).toBe("/repos/my%20repo/chat");
+ expect(resolveHighlightHref("/repos/:id/chat", null)).toBeNull();
+ expect(resolveHighlightHref("/settings", null)).toBe("/settings");
+ expect(repoIdFromPath("/repos/abc/overview")).toBe("abc");
+ expect(repoIdFromPath("/settings")).toBeNull();
+ });
+
+ it("links PR refs outside code spans", () => {
+ expect(linkPullRequests("Charts (#3860, #3843) and `#1`")).toBe(
+ "Charts ([#3860](https://github.com/repowise-dev/repowise/pull/3860), " +
+ "[#3843](https://github.com/repowise-dev/repowise/pull/3843)) and `#1`",
+ );
+ expect(linkPullRequests("[#5](x) and a#6")).toBe("[#5](x) and a#6");
+ });
+
+ it("reads the preview query", () => {
+ expect(previewMoment("?whats-new=preview")).toBe("dialog");
+ expect(previewMoment("?whats-new=patch")).toBe("notice");
+ expect(previewMoment("?x=1")).toBeNull();
+ });
+});
+
+describe("decideMoment", () => {
+ it("replays a preview without touching what the browser has seen", () => {
+ expect(decideMoment("0.57.0", [], "?whats-new=preview")).toEqual({ moment: "dialog", preview: true });
+ expect(window.localStorage.getItem("repowise:last-seen-server-version")).toBeNull();
+ });
+
+ it("starts the New marks only for a real upgrade", () => {
+ window.localStorage.setItem("repowise:last-seen-server-version", "0.56.0");
+ expect(decideMoment("0.57.0", [HL("/settings")], "")).toEqual({ moment: "dialog", preview: false });
+ expect(readNewSurfaces()?.routes).toEqual(["/settings"]);
+ });
+});
+
+describe("highlight repository", () => {
+ it("uses the page's repo, else the last opened, else the first listed", () => {
+ rememberRepo("/workspace", "first");
+ expect(highlightRepoId("/workspace")).toBe("first");
+ rememberRepo("/repos/abc/chat", "first");
+ expect(highlightRepoId("/workspace")).toBe("abc");
+ rememberRepo("/settings", "first");
+ expect(highlightRepoId("/settings")).toBe("abc");
+ expect(highlightRepoId("/repos/xyz/overview")).toBe("xyz");
+ });
+
+ it("is null with no repositories", () => {
+ rememberRepo("/", null);
+ expect(highlightRepoId("/")).toBeNull();
+ });
+
+ it("does not count as earlier use", () => {
+ rememberRepo("/repos/abc/chat", null);
+ expect(takeUpgradeMoment("0.57.0", true)).toBe("none");
+ });
+});
diff --git a/packages/web/src/lib/release-moment.ts b/packages/web/src/lib/release-moment.ts
new file mode 100644
index 000000000..b4b7370a1
--- /dev/null
+++ b/packages/web/src/lib/release-moment.ts
@@ -0,0 +1,234 @@
+/**
+ * The "just upgraded" moment, decided once per version in the browser.
+ *
+ * The last server version this browser saw lives in localStorage. When it
+ * changes, a minor release (x.y.0, or any release with highlights) opens the
+ * 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.
+ *
+ * Every storage call is best-effort: blocked site data means no moment, never
+ * an error.
+ */
+
+import type { ChangelogHighlight } from "@/lib/api/meta";
+
+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";
+/** 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]);
+export const NEW_MARK_DAYS = 14;
+
+export type UpgradeMoment = "none" | "dialog" | "notice";
+
+/** The numeric parts of a plain release version, or null for anything else
+ * (a dev or rc build is not compared as a release). */
+function releaseParts(version: string): number[] | null {
+ return /^\d+(\.\d+)*$/.test(version) ? version.split(".").map(Number) : null;
+}
+
+function isNewer(next: string, prev: string): boolean {
+ const a = releaseParts(next);
+ const b = releaseParts(prev);
+ if (!a || !b) return false;
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const d = (a[i] ?? 0) - (b[i] ?? 0);
+ if (d !== 0) return d > 0;
+ }
+ return false;
+}
+
+/** What to show for a move from `stored` to `current`. A first visit
+ * (`stored` null) and a downgrade show nothing. */
+export function upgradeMoment(
+ stored: string | null,
+ current: string,
+ hasHighlights: boolean,
+): UpgradeMoment {
+ if (!stored || stored === current || !isNewer(current, stored)) return "none";
+ return isMinorRelease(current, hasHighlights) ? "dialog" : "notice";
+}
+
+/** x.y.0, or any release that names highlights. */
+function isMinorRelease(version: string, hasHighlights: boolean): boolean {
+ return hasHighlights || (releaseParts(version)?.[2] ?? 0) === 0;
+}
+
+function read(key: string): string | null {
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ // Blocked site data (privacy mode, storage disabled): read as unset.
+ return null;
+ }
+}
+
+function write(key: string, value: string): void {
+ try {
+ window.localStorage.setItem(key, value);
+ } catch {
+ /* blocked site data: the moment simply does not persist */
+ }
+}
+
+/** Whether this browser used repowise before it stored a version: any of the
+ * 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 {
+ try {
+ const store = window.localStorage;
+ for (let i = 0; i < store.length; i++) {
+ const key = store.key(i);
+ if (key && /^repowise[:_]/.test(key) && !OWN_KEYS.has(key)) {
+ return true;
+ }
+ }
+ } catch {
+ /* blocked site data reads as a fresh browser */
+ }
+ return false;
+}
+
+/** Reads the stored version, stores `current`, and returns the moment due. */
+export function takeUpgradeMoment(current: string, hasHighlights: boolean): UpgradeMoment {
+ // "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);
+ return moment;
+}
+
+// --- "New" marks ------------------------------------------------------------
+
+export interface NewSurfaces {
+ version: string;
+ /** When the upgrade was first seen, ms since epoch. */
+ since: number;
+ /** Highlight routes, with `:id` left in for repo-scoped pages. */
+ routes: string[];
+ visited: string[];
+}
+
+export function readNewSurfaces(): NewSurfaces | null {
+ const raw = read(NEW_SURFACES_KEY);
+ if (!raw) return null;
+ try {
+ const v = JSON.parse(raw) as NewSurfaces;
+ return Array.isArray(v.routes) && Array.isArray(v.visited) ? v : null;
+ } catch {
+ // A hand-edited or truncated value: no marks, and the next upgrade rewrites it.
+ return null;
+ }
+}
+
+function saveNewSurfaces(value: NewSurfaces): void {
+ write(NEW_SURFACES_KEY, JSON.stringify(value));
+ window.dispatchEvent(new Event(NEW_SURFACES_EVENT));
+}
+
+export function startNewSurfaces(version: string, highlights: ChangelogHighlight[]): void {
+ const routes = highlights.map((h) => h.href).filter((h): h is string => !!h);
+ saveNewSurfaces({ version, since: Date.now(), routes, visited: [] });
+}
+
+/** `/repos/abc/chat/123` matches `/repos/:id/chat`. */
+export function routeMatches(route: string, pathname: string): boolean {
+ const want = route.split("/").filter(Boolean);
+ const have = pathname.split("/").filter(Boolean);
+ if (have.length < want.length) return false;
+ return want.every((p, i) => p === ":id" || p === have[i]);
+}
+
+/** Routes still marked "New" for `now`. */
+export function activeNewRoutes(value: NewSurfaces | null, now: number): string[] {
+ if (!value || now - value.since > NEW_MARK_DAYS * 24 * 60 * 60 * 1000) return [];
+ return value.routes.filter((r) => !value.visited.includes(r));
+}
+
+/** Records a visit to `pathname`, clearing the mark of the route it opens. */
+export function visitNewSurface(pathname: string): void {
+ const value = readNewSurfaces();
+ const hit = activeNewRoutes(value, Date.now()).find((r) => routeMatches(r, pathname));
+ if (!value || !hit) return;
+ saveNewSurfaces({ ...value, visited: [...value.visited, hit] });
+}
+
+export function subscribeNewSurfaces(onChange: () => void): () => void {
+ window.addEventListener(NEW_SURFACES_EVENT, onChange);
+ window.addEventListener("storage", onChange);
+ return () => {
+ window.removeEventListener(NEW_SURFACES_EVENT, onChange);
+ window.removeEventListener("storage", onChange);
+ };
+}
+
+/** A highlight's route for the current repository, or null when it needs one
+ * and there is none. */
+export function resolveHighlightHref(href: string | null | undefined, repoId: string | null): string | null {
+ if (!href) return null;
+ if (!href.includes(":id")) return href;
+ return repoId ? href.replace(":id", encodeURIComponent(repoId)) : null;
+}
+
+/** The repository the current page belongs to, from `/repos/<id>/...`. */
+export function repoIdFromPath(pathname: string | null): string | null {
+ const m = pathname?.match(/^\/repos\/([^/]+)/);
+ return m?.[1] ? decodeURIComponent(m[1]) : null;
+}
+
+/** Remembers the repository the reader last opened, so a highlight opened
+ * from outside a repository (the dashboard, /workspace) still has one. The
+ * first listed repository stands in until one is opened. */
+export function rememberRepo(pathname: string | null, firstRepoId: string | null): void {
+ const id = repoIdFromPath(pathname);
+ if (id) write(LAST_REPO_KEY, id);
+ else if (firstRepoId && !read(LAST_REPO_KEY)) write(LAST_REPO_KEY, firstRepoId);
+}
+
+/** The repository a repo-scoped highlight should open: the current page's,
+ * else the last one opened. */
+export function highlightRepoId(pathname: string | null): string | null {
+ return repoIdFromPath(pathname) ?? read(LAST_REPO_KEY);
+}
+
+/** `?whats-new=preview` replays the minor-release moment, `?whats-new=patch`
+ * the patch note, without touching what this browser has seen. */
+const PREVIEWS: Record<string, UpgradeMoment> = { preview: "dialog", patch: "notice" };
+
+export function previewMoment(search: string): UpgradeMoment | null {
+ return PREVIEWS[new URLSearchParams(search).get("whats-new") ?? ""] ?? null;
+}
+
+/** The moment due on load: a `?whats-new=` replay, or the real upgrade check,
+ * which also starts the "New" marks for that release. */
+export function decideMoment(
+ version: string,
+ highlights: ChangelogHighlight[],
+ search: string,
+): { moment: UpgradeMoment; preview: boolean } {
+ const replay = previewMoment(search);
+ if (replay) return { moment: replay, preview: true };
+ const moment = takeUpgradeMoment(version, highlights.length > 0);
+ if (moment !== "none") startNewSurfaces(version, highlights);
+ return { moment, preview: false };
+}
+
+/** `#123` in changelog prose links to its pull request, outside code spans. */
+export function linkPullRequests(markdown: string): string {
+ return markdown
+ .split(/(`[^`]*`)/)
+ .map((part, i) =>
+ i % 2 === 1
+ ? part
+ : part.replace(
+ /(^|[^\w[/&])#(\d+)\b/g,
+ (_m, pre: string, n: string) =>
+ `${pre}[#${n}](https://github.com/repowise-dev/repowise/pull/${n})`,
+ ),
+ )
+ .join("");
+}
diff --git a/pyproject.toml b/pyproject.toml
index 451dd7974..160e4fa4f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -161,7 +161,7 @@ namespaces = true
# and the web what's-new view work offline from the installed wheel. Lives in
# core (the neutral home shared by cli + server). Kept in sync with the
# canonical docs/CHANGELOG.md by a drift-guard test (see tests/unit/upgrade).
-"repowise.core.upgrade" = ["_data/CHANGELOG.md"]
+"repowise.core.upgrade" = ["_data/CHANGELOG.md", "_data/release_stats.json"]
# Codex slash commands. A Codex plugin manifest has no slot for commands, so
# ~/.codex/prompts is the only surface that yields one and the CLI is the only
# thing that can write it, which means the content has to be in the wheel.
diff --git a/scripts/release_stats.py b/scripts/release_stats.py
new file mode 100644
index 000000000..6a3582fa3
--- /dev/null
+++ b/scripts/release_stats.py
@@ -0,0 +1,344 @@
+"""Compute a release's "By the numbers" figures from git (and GitHub, if reachable).
+
+Usage::
+
+ python scripts/release_stats.py # latest tag..HEAD
+ python scripts/release_stats.py --from v0.56.0 --to origin/main --version unreleased
+ python scripts/release_stats.py --version 0.57.0 --write-json
+ python scripts/release_stats.py --pr # add the thank-you block
+
+Prints the ``### By the numbers`` block for the CHANGELOG release section.
+``--write-json`` stores the same figures under ``--version`` in the bundled
+``release_stats.json`` the dashboard and ``repowise whats-new`` read. ``--pr``
+also prints the returning and first-time contributor handles, for the release
+PR body only: names never go into the changelog or the bundled data.
+
+Contributor handles and the first-time split need the ``gh`` CLI. Without it
+(or offline) the git counts are still printed and the first-time count is
+omitted.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import shutil
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from datetime import datetime
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+STATS_JSON = ROOT / "packages/core/src/repowise/core/upgrade/_data/release_stats.json"
+GITHUB_REPO = "repowise-dev/repowise"
+MAINTAINER_LOGINS = frozenset({"raghavchamadiya", "swati510"})
+MAINTAINER_NAMES = frozenset({"raghav", "swati", "raghav chamadiya", "swati ahuja"})
+
+_PR_RE = re.compile(r"\(#(\d+)\)\s*$")
+_TYPE_RE = re.compile(r"^([a-z]+)[(!:]")
+_ISSUE_RE = re.compile(r"\b(?:fix(?:es|ed)?|close[sd]?|resolve[sd]?)\s+#(\d+)", re.IGNORECASE)
+_TEST_RE = re.compile(r"(^|/)tests?/|(^|/)test_[^/]*$|\.test\.[a-z]+$|_test\.[a-z]+$")
+_SHORTSTAT_RE = re.compile(
+ r"(\d+) files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?"
+)
+_COMMIT_SEP, _FIELD_SEP = "\x1e", "\x1f"
+
+#: Commit types the numbers line names, in the order it names them.
+TYPE_KEYS = {"fix": "fixes", "feat": "features", "perf": "perf", "refactor": "refactors", "docs": "docs"}
+
+
+# --- pure parsing (unit-tested) -------------------------------------------
+
+
+def parse_log(text: str) -> list[dict[str, str]]:
+ """``git log`` output in the ``_log_format`` shape to commit dicts."""
+ commits = []
+ for chunk in text.split(_COMMIT_SEP):
+ parts = chunk.strip("\n").split(_FIELD_SEP)
+ if len(parts) < 5:
+ continue
+ sha, name, email, subject, body = parts[:5]
+ commits.append({"sha": sha, "name": name, "email": email, "subject": subject, "body": body})
+ return commits
+
+
+def parse_shortstat(text: str) -> tuple[int, int, int]:
+ """``git diff --shortstat`` to ``(files, added, removed)``."""
+ m = _SHORTSTAT_RE.search(text)
+ if not m:
+ return 0, 0, 0
+ return int(m.group(1)), int(m.group(2) or 0), int(m.group(3) or 0)
+
+
+def count_types(subjects: list[str]) -> dict[str, int]:
+ counts = dict.fromkeys(TYPE_KEYS.values(), 0)
+ for subject in subjects:
+ m = _TYPE_RE.match(subject)
+ if m and m.group(1) in TYPE_KEYS:
+ counts[TYPE_KEYS[m.group(1)]] += 1
+ return counts
+
+
+def count_prs(subjects: list[str]) -> int:
+ return len({m.group(1) for s in subjects if (m := _PR_RE.search(s))})
+
+
+def count_issues(bodies: list[str]) -> int:
+ return len({n for body in bodies for n in _ISSUE_RE.findall(body)})
+
+
+def is_test_path(path: str) -> bool:
+ return bool(_TEST_RE.search(path))
+
+
+def is_maintainer(login: str | None, name: str) -> bool:
+ if login:
+ return login.lower() in MAINTAINER_LOGINS
+ return name.strip().lower() in MAINTAINER_NAMES
+
+
+def is_bot(login: str | None, name: str) -> bool:
+ return (login or name).lower().endswith("[bot]")
+
+
+def split_first_time(
+ handles: list[str], prior_commits: dict[str, int | None]
+) -> tuple[list[str], list[str]]:
+ """Split *handles* into (returning, first-time) by their commits before the
+ previous tag. A handle whose count is unknown (lookup failed) is left out
+ of both, so no one is welcomed twice or by mistake."""
+ returning, first = [], []
+ for handle in sorted(set(handles), key=str.lower):
+ count = prior_commits.get(handle)
+ if count is None:
+ continue
+ (returning if count > 0 else first).append(handle)
+ return returning, first
+
+
+def _kinds_line(t: dict) -> str:
+ """``**165 fixes, 89 features**, 28 refactors and 6 documentation changes``,
+ leaving out kinds with no commits (the JSON keeps the zeros)."""
+
+ def _join(parts: list[str]) -> str:
+ if len(parts) < 2:
+ return "".join(parts)
+ return ", ".join(parts[:-1]) + " and " + parts[-1]
+
+ lead = [
+ f"{t[k]:,} {name}"
+ for k, name in (("fixes", "fixes"), ("features", "features"), ("perf", "performance changes"))
+ if t.get(k)
+ ]
+ rest = [
+ f"{t[k]:,} {name}"
+ for k, name in (("refactors", "refactors"), ("docs", "documentation changes"))
+ if t.get(k)
+ ]
+ if lead and rest:
+ return f"**{', '.join(lead)}**, {_join(rest)}"
+ if lead:
+ return f"**{_join(lead)}**"
+ return _join(rest)
+
+
+def render_markdown(stats: dict) -> str:
+ """The ``### By the numbers`` block for the CHANGELOG."""
+ t = stats["types"]
+ days = stats["days"]
+ since = stats["since"]
+ first = stats.get("first_time_contributors")
+ people = f"**{stats['contributors']:,} contributors**"
+ if first:
+ people += f", **{first:,} of them first-time contributors**"
+ lines = [
+ "### By the numbers",
+ "",
+ f"In the {days:,} day{'s' if days != 1 else ''} since {since}:",
+ "",
+ f"- **{stats['prs']:,} pull requests** merged, from {people}",
+ f"- **{stats['files_changed']:,} files** changed, "
+ f"**+{stats['lines_added']:,} / -{stats['lines_removed']:,}** lines",
+ *([f"- {kinds}"] if (kinds := _kinds_line(t)) else []),
+ f"- **{stats['test_files_touched']:,} test files** touched, "
+ f"**{stats['test_files_new']:,}** of them new",
+ f"- **{stats['issues_closed']:,} issues** closed",
+ "",
+ "Thank you to everyone who built this release with us.",
+ ]
+ return "\n".join(lines)
+
+
+def render_thanks(returning: list[str], first: list[str]) -> str:
+ """The contributor thank-you for the release PR body (never bundled)."""
+
+ def _join(handles: list[str]) -> str:
+ tagged = [f"@{h}" for h in handles]
+ return tagged[0] if len(tagged) == 1 else ", ".join(tagged[:-1]) + " and " + tagged[-1]
+
+ out = []
+ if returning:
+ out.append(
+ f"To our returning contributors: {_join(returning)}, thank you for coming back "
+ "and raising the bar again."
+ )
+ if first:
+ n = len(first)
+ who = "person whose first contribution" if n == 1 else "people whose first contribution"
+ out.append(
+ f"And a special welcome to the **{n} {who} landed in this release**: "
+ f"{_join(first)}. Glad to have you here."
+ )
+ return "\n\n".join(out)
+
+
+# --- git and GitHub -------------------------------------------------------
+
+
+def _git(*args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=ROOT, check=True, capture_output=True, text=True, encoding="utf-8"
+ ).stdout
+
+
+def _gh(path: str, jq: str) -> str | None:
+ try:
+ out = subprocess.run(
+ ["gh", "api", path, "--jq", jq],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ timeout=30,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ return out.stdout.strip() if out.returncode == 0 else None
+
+
+def _commit_date(ref: str) -> datetime:
+ return datetime.fromisoformat(_git("log", "-1", "--format=%cI", ref).strip())
+
+
+def _resolve_handles(commits: list[dict[str, str]]) -> dict[str, str | None]:
+ """Email to GitHub login, one lookup per distinct author email."""
+ first_sha: dict[str, str] = {}
+ for c in commits:
+ first_sha.setdefault(c["email"], c["sha"])
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ logins = pool.map(
+ lambda sha: _gh(f"repos/{GITHUB_REPO}/commits/{sha}", ".author.login"),
+ first_sha.values(),
+ )
+ return {
+ email: (login if login and login != "null" else None)
+ for email, login in zip(first_sha, logins, strict=True)
+ }
+
+
+def _prior_commit_counts(handles: list[str], until: str) -> dict[str, int | None]:
+ def _one(handle: str) -> int | None:
+ out = _gh(f"repos/{GITHUB_REPO}/commits?author={handle}&until={until}&per_page=1", "length")
+ return int(out) if out and out.isdigit() else None
+
+ with ThreadPoolExecutor(max_workers=8) as pool:
+ return dict(zip(handles, pool.map(_one, handles), strict=True))
+
+
+def _test_files(rng: str, *extra: str) -> int:
+ return sum(1 for p in _git("diff", "--name-only", *extra, rng).splitlines() if is_test_path(p))
+
+
+def _git_stats(prev: str, ref: str, commits: list[dict[str, str]]) -> dict:
+ """Every figure git alone can give for ``prev..ref``."""
+ rng = f"{prev}..{ref}"
+ files, added, removed = parse_shortstat(_git("diff", "--shortstat", rng))
+ subjects = [c["subject"] for c in commits]
+ return {
+ "since": prev.lstrip("v"),
+ "days": max(0, (_commit_date(ref).date() - _commit_date(prev).date()).days),
+ "prs": count_prs(subjects),
+ "contributors": len({c["name"] for c in commits if not is_bot(None, c["name"])}),
+ "first_time_contributors": None,
+ "files_changed": files,
+ "lines_added": added,
+ "lines_removed": removed,
+ "types": count_types(subjects),
+ "test_files_touched": _test_files(rng),
+ "test_files_new": _test_files(rng, "--diff-filter=A"),
+ "issues_closed": count_issues([c["body"] for c in commits]),
+ }
+
+
+def _community_split(commits: list[dict[str, str]], until: str) -> tuple[list[str], list[str], bool]:
+ """(returning, first-time, known) community handles, from GitHub."""
+ by_email = _resolve_handles(commits)
+ community = sorted(
+ {
+ login
+ for c in commits
+ if (login := by_email.get(c["email"]))
+ and not is_maintainer(login, c["name"])
+ and not is_bot(login, c["name"])
+ }
+ )
+ if not community:
+ return [], [], False
+ prior = _prior_commit_counts(community, until)
+ returning, first = split_first_time(community, prior)
+ return returning, first, any(v is not None for v in prior.values())
+
+
+def compute(prev: str, ref: str, *, github: bool) -> tuple[dict, list[str], list[str]]:
+ """Figures for ``prev..ref`` plus the (returning, first-time) handle lists."""
+ fmt = _FIELD_SEP.join(["%H", "%an", "%ae", "%s", "%B"]) + _COMMIT_SEP
+ commits = parse_log(_git("log", f"--format={fmt}", f"{prev}..{ref}"))
+ stats = _git_stats(prev, ref, commits)
+ if not (github and shutil.which("gh")):
+ return stats, [], []
+ returning, first, known = _community_split(commits, _commit_date(prev).isoformat())
+ if known:
+ stats["first_time_contributors"] = len(first)
+ return stats, returning, first
+
+
+def write_json(version: str, stats: dict, path: Path = STATS_JSON) -> None:
+ data = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}
+ if version != "unreleased":
+ # Releasing turns the Unreleased figures into this version's.
+ data.pop("unreleased", None)
+ data[version] = stats
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+
+
+def _latest_tag(ref: str) -> str:
+ return _git("describe", "--tags", "--abbrev=0", "--match", "v[0-9]*", ref).strip()
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("--from", dest="prev", help="previous release tag (default: latest v* tag)")
+ ap.add_argument("--to", dest="ref", default="HEAD", help="end of the range (default: HEAD)")
+ ap.add_argument("--version", help="key for --write-json, e.g. 0.57.0 or unreleased")
+ ap.add_argument("--write-json", action="store_true", help="store the figures in release_stats.json")
+ ap.add_argument("--pr", action="store_true", help="also print the contributor thank-you")
+ ap.add_argument("--no-github", action="store_true", help="skip the gh lookups")
+ args = ap.parse_args(argv)
+ if args.write_json and not args.version:
+ ap.error("--write-json needs --version")
+
+ prev = args.prev or _latest_tag(args.ref)
+ stats, returning, first = compute(prev, args.ref, github=not args.no_github)
+ print(render_markdown(stats))
+ if args.pr:
+ print("\n<!-- release PR body only -->\n")
+ print(render_thanks(returning, first) or "(contributor handles unavailable: gh not reachable)")
+ if args.write_json:
+ write_json(args.version, stats)
+ print(f"\nwrote {args.version} to {STATS_JSON.relative_to(ROOT)}", file=sys.stderr)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit/server/test_meta_api.py b/tests/unit/server/test_meta_api.py
index 7d4bf1ed6..c3050e424 100644
--- a/tests/unit/server/test_meta_api.py
+++ b/tests/unit/server/test_meta_api.py
@@ -12,7 +12,11 @@ import repowise.core.upgrade.release as rel
def _stub_pypi(monkeypatch, tmp_path):
"""Keep these tests offline and deterministic."""
monkeypatch.setattr(rel, "_CACHE_PATH", tmp_path / "update-check.json")
+ monkeypatch.setattr(rel, "_HIGHLIGHTS_CACHE_PATH", tmp_path / "release-highlights.json")
monkeypatch.setattr(rel, "fetch_latest_version", lambda timeout=2.0: ("9.9.9", None))
+ monkeypatch.setattr(
+ rel, "fetch_release_highlights", lambda version, timeout=2.0: ["Charts in chat"]
+ )
@pytest.mark.asyncio
@@ -27,6 +31,18 @@ async def test_version_endpoint(client: AsyncClient) -> None:
# No repo_id -> store fields stay unset.
assert body["store_format_version"] is None
assert body["reindex_recommended"] is False
+ assert body["latest_highlights"] == ["Charts in chat"]
+ assert isinstance(body["highlights"], list)
+
+
+async def test_version_endpoint_offline_highlights_keep_plain_banner(
+ client: AsyncClient, monkeypatch
+) -> None:
+ monkeypatch.setattr(rel, "fetch_release_highlights", lambda version, timeout=2.0: None)
+ body = (await client.get("/api/meta/version")).json()
+ assert body["update_available"] is True
+ assert body["latest_highlights"] == []
@pytest.mark.asyncio
@@ -37,6 +53,7 @@ async def test_version_endpoint_up_to_date(client: AsyncClient, monkeypatch) ->
resp = await client.get("/api/meta/version")
assert resp.status_code == 200
assert resp.json()["update_available"] is False
+ assert resp.json()["latest_highlights"] == []
@pytest.mark.asyncio
@@ -114,3 +131,54 @@ async def test_changelog_endpoint(client: AsyncClient) -> None:
first = entries[0]
assert first["version"]
assert isinstance(first["sections"], list)
+
+
+async def test_changelog_endpoint_carries_summary_highlights_and_stats(
+ client: AsyncClient, monkeypatch, tmp_path
+) -> None:
+ changelog = tmp_path / "CHANGELOG.md"
+ changelog.write_text(
+ "## [1.2.0] - 2026-10-20\n\nThe summary.\n\n### Highlights\n\n"
+ "- **Charts in chat** · Any chart. → /repos/:id/chat\n\n### Added\n\n- A thing.\n",
+ encoding="utf-8",
+ )
+ stats = tmp_path / "release_stats.json"
+ stats.write_text(
+ '{"1.2.0": {"since": "1.1.0", "days": 4, "prs": 12, "contributors": 3,'
+ ' "first_time_contributors": 1, "files_changed": 40, "lines_added": 900,'
+ ' "lines_removed": 100, "types": {"fixes": 5, "features": 4},'
+ ' "test_files_touched": 9, "test_files_new": 2, "issues_closed": 3}}',
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(rel, "BUNDLED_CHANGELOG_PATH", changelog)
+ monkeypatch.setattr(rel, "RELEASE_STATS_PATH", stats)
+
+ entry = (await client.get("/api/meta/changelog")).json()["entries"][0]
+ assert entry["summary"] == "The summary."
+ assert entry["highlights"] == [
+ {
+ "id": "charts-in-chat",
+ "title": "Charts in chat",
+ "blurb": "Any chart.",
+ "href": "/repos/:id/chat",
+ }
+ ]
+ assert entry["stats"]["prs"] == 12
+ assert entry["stats"]["types"]["perf"] == 0
+ assert [s["name"] for s in entry["sections"]] == ["Added"]
+
+
+async def test_changelog_endpoint_drops_malformed_stats(
+ client: AsyncClient, monkeypatch, tmp_path
+) -> None:
+ changelog = tmp_path / "CHANGELOG.md"
+ changelog.write_text("## [1.2.0] - x\n\n### Added\n\n- A thing.\n", encoding="utf-8")
+ stats = tmp_path / "release_stats.json"
+ stats.write_text('{"1.2.0": {"prs": "many"}}', encoding="utf-8")
+ monkeypatch.setattr(rel, "BUNDLED_CHANGELOG_PATH", changelog)
+ monkeypatch.setattr(rel, "RELEASE_STATS_PATH", stats)
+
+ entry = (await client.get("/api/meta/changelog")).json()["entries"][0]
+ assert entry["stats"] is None
diff --git a/tests/unit/upgrade/test_release_highlights.py b/tests/unit/upgrade/test_release_highlights.py
new file mode 100644
index 000000000..06bad202f
--- /dev/null
+++ b/tests/unit/upgrade/test_release_highlights.py
@@ -0,0 +1,259 @@
+"""Highlights, release summary and Unreleased parsing, the newer-release
+highlight fetch, and guards on the shipped changelog's highlights."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+import repowise.core.upgrade.release as rel
+from repowise.core.upgrade.changelog import (
+ UNRELEASED,
+ entries_between,
+ parse_changelog,
+ parse_highlight,
+)
+
+SAMPLE = """# Changelog
+
+<!-- preamble comment -->
+
+---
+
+## [Unreleased]
+
+The next release in one paragraph.
+
+### Highlights
+
+- **Charts in chat** · Any chart of your repo. → /repos/:id/chat
+
+### Added
+
+- Pending thing.
+
+## [0.57.0] - 2026-10-20
+
+First paragraph of the summary,
+wrapped over two lines.
+
+Second paragraph.
+
+### Highlights
+
+- **Charts in chat** · Ask for any chart. → /repos/:id/chat
+- **One palette**: every chart shares one set of colours.
+- **Settings models** - live lists -> /settings
+- plain bullet with no bold title
+
+### By the numbers
+
+In the 3 days since 0.56.0:
+
+- **205 pull requests** merged
+
+### Added
+
+- A feature.
+
+---
+
+## [0.56.0] - 2026-10-12
+
+### Fixed
+
+- A fix.
+"""
+
+
+def test_highlights_parse_separately_from_sections():
+ e = parse_changelog(SAMPLE)[1]
+ assert e.version == "0.57.0"
+ assert [s.name for s in e.sections] == ["Added"] # Highlights and numbers left out
+ assert [h.title for h in e.highlights] == [
+ "Charts in chat",
+ "One palette",
+ "Settings models",
+ "plain bullet with no bold title",
+ ]
+
+
+def test_highlight_fields():
+ h = parse_highlight("**Charts in chat** · Ask for any chart. → /repos/:id/chat")
+ assert (h.id, h.title, h.blurb, h.href) == (
+ "charts-in-chat",
+ "Charts in chat",
+ "Ask for any chart.",
+ "/repos/:id/chat",
+ )
+ assert parse_highlight("**One palette**: every chart.").href is None
+ assert parse_highlight("**One palette**: every chart.").blurb == "every chart."
+ assert parse_highlight("**Settings models** - live lists -> /settings").href == "/settings"
+ # A dash is a separator only with space on both sides.
+ assert parse_highlight("**Fast** -fast path").blurb == "-fast path"
+ assert parse_highlight("**Fast** — a path").blurb == "a path"
+
+
+def test_highlight_id_is_stable_across_blurb_edits():
+ a = parse_highlight("**Charts in chat!** · one")
+ b = parse_highlight("**Charts in chat!** · two → /x")
+ assert a.id == b.id == "charts-in-chat"
+
+
+def test_summary_is_the_prose_before_the_first_section():
+ entries = parse_changelog(SAMPLE)
+ assert entries[1].summary == (
+ "First paragraph of the summary, wrapped over two lines.\n\nSecond paragraph."
+ )
+ assert entries[2].summary == ""
+
+
+def test_unreleased_parses_with_content():
+ first = parse_changelog(SAMPLE)[0]
+ assert first.version == UNRELEASED
+ assert first.summary == "The next release in one paragraph."
+ assert first.highlights[0].id == "charts-in-chat"
+
+
+def test_empty_unreleased_is_dropped():
+ text = "## [Unreleased]\n\n---\n\n## [1.0.0] - x\n### Added\n- real\n"
+ assert [e.version for e in parse_changelog(text)] == ["1.0.0"]
+
+
+def test_unreleased_is_never_within_a_running_version():
+ entries = parse_changelog(SAMPLE)
+ sel = entries_between(entries, newer_than="0.56.0", up_to="0.57.0")
+ assert [e.version for e in sel] == ["0.57.0"]
+
+
+# --- newer release highlights (banner) ------------------------------------
+
+
+def _redirect(monkeypatch, tmp_path):
+ monkeypatch.setattr(rel, "_HIGHLIGHTS_CACHE_PATH", tmp_path / "release-highlights.json")
+
+
+def test_latest_highlights_cached_hit_skips_the_network(monkeypatch, tmp_path):
+ _redirect(monkeypatch, tmp_path)
+ calls = {"n": 0}
+
+ def _fetch(version, timeout=2.0):
+ calls["n"] += 1
+ return ["Charts in chat"]
+
+ monkeypatch.setattr(rel, "fetch_release_highlights", _fetch)
+ assert rel.latest_highlights_cached("0.57.0") == ["Charts in chat"]
+ assert rel.latest_highlights_cached("0.57.0") == ["Charts in chat"]
+ assert calls["n"] == 1
+ # A different newer version is a miss.
+ rel.latest_highlights_cached("0.58.0")
+ assert calls["n"] == 2
+
+
+def test_latest_highlights_offline_is_empty_and_cached(monkeypatch, tmp_path):
+ _redirect(monkeypatch, tmp_path)
+ calls = {"n": 0}
+
+ def _fetch(version, timeout=2.0):
+ calls["n"] += 1
+ return None
+
+ monkeypatch.setattr(rel, "fetch_release_highlights", _fetch)
+ assert rel.latest_highlights_cached("0.57.0") == []
+ assert rel.latest_highlights_cached("0.57.0") == []
+ assert calls["n"] == 1
+
+
+def test_latest_highlights_empty_result_expires_sooner(monkeypatch, tmp_path):
+ import time
+
+ _redirect(monkeypatch, tmp_path)
+ (tmp_path / "release-highlights.json").write_text(
+ json.dumps({"checked_at": time.time() - 3600, "version": "0.57.0", "titles": []}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(rel, "fetch_release_highlights", lambda v, timeout=2.0: ["Now"])
+ assert rel.latest_highlights_cached("0.57.0") == ["Now"]
+
+
+def test_latest_highlights_expired_cache_refetches(monkeypatch, tmp_path):
+ _redirect(monkeypatch, tmp_path)
+ (tmp_path / "release-highlights.json").write_text(
+ json.dumps({"checked_at": 0, "version": "0.57.0", "titles": ["Old"]}), encoding="utf-8"
+ )
+ monkeypatch.setattr(rel, "fetch_release_highlights", lambda v, timeout=2.0: ["New"])
+ assert rel.latest_highlights_cached("0.57.0") == ["New"]
+
+
+def test_fetch_release_highlights_reads_that_version(monkeypatch):
+ class _Resp:
+ text = SAMPLE
+
+ def raise_for_status(self):
+ return None
+
+ import httpx
+
+ monkeypatch.setattr(httpx, "get", lambda url, timeout: _Resp())
+ assert rel.fetch_release_highlights("0.57.0")[0] == "Charts in chat"
+ assert rel.fetch_release_highlights("9.9.9") == []
+
+
+def test_fetch_release_highlights_offline_is_none(monkeypatch):
+ import httpx
+
+ def _boom(url, timeout):
+ raise httpx.ConnectError("offline")
+
+ monkeypatch.setattr(httpx, "get", _boom)
+ assert rel.fetch_release_highlights("0.57.0") is None
+
+
+def test_release_stats_missing_file_is_empty(monkeypatch, tmp_path):
+ monkeypatch.setattr(rel, "RELEASE_STATS_PATH", tmp_path / "nope.json")
+ assert rel.load_release_stats() == {}
+
+
+def test_bundled_release_stats_parse():
+ stats = rel.load_release_stats()
+ assert all(isinstance(v, dict) and "prs" in v for v in stats.values())
+
+
+# --- guards on the shipped changelog --------------------------------------
+
+_ROOT = Path(__file__).resolve().parents[3]
+_APP = _ROOT / "packages" / "web" / "src" / "app"
+
+
+def _route_exists(href: str) -> bool:
+ """``/repos/:id/chat`` resolves to ``app/repos/[id]/chat/page.tsx``."""
+ path = href.split("?")[0].split("#")[0].strip("/")
+ parts = ["[id]" if p == ":id" else p for p in path.split("/") if p]
+ return (_APP.joinpath(*parts) / "page.tsx").is_file()
+
+
+def test_released_minor_versions_have_highlights():
+ """From 0.57.0 every minor release (x.y.0) names what it brought."""
+ missing = [
+ e.version
+ for e in rel.load_bundled_changelog()
+ if e.version != UNRELEASED
+ and e.release_tuple >= (0, 57, 0)
+ and len(e.release_tuple) == 3
+ and e.release_tuple[2] == 0
+ and not e.highlights
+ ]
+ assert not missing, f"add a ### Highlights block (3-5 bullets) to: {missing}"
+
+
[email protected](not _APP.is_dir(), reason="web app sources not present")
+def test_highlight_routes_exist_in_the_web_app():
+ bad = [
+ (e.version, h.href)
+ for e in rel.load_bundled_changelog()
+ for h in e.highlights
+ if h.href and not _route_exists(h.href)
+ ]
+ assert not bad, f"highlight routes with no page under packages/web/src/app: {bad}"
diff --git a/tests/unit/upgrade/test_release_stats_script.py b/tests/unit/upgrade/test_release_stats_script.py
new file mode 100644
index 000000000..6608a6ffb
--- /dev/null
+++ b/tests/unit/upgrade/test_release_stats_script.py
@@ -0,0 +1,161 @@
+"""The pure parts of ``scripts/release_stats.py``: git output parsing, counting,
+the first-time split and the rendered blocks."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+
+
+def _script():
+ path = ROOT / "scripts" / "release_stats.py"
+ spec = importlib.util.spec_from_file_location("release_stats", path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules["release_stats"] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+rs = _script()
+
+
+def _log(*commits: tuple[str, str, str, str, str]) -> str:
+ return "".join(rs._FIELD_SEP.join(c) + rs._COMMIT_SEP + "\n" for c in commits)
+
+
+def test_parse_log():
+ text = _log(
+ ("a1", "Ada", "ada@x", "feat(web): a thing (#12)", "feat(web): a thing (#12)\n\nFixes #3"),
+ ("b2", "Bo", "bo@x", "fix: other (#13)", "fix: other (#13)"),
+ )
+ commits = rs.parse_log(text)
+ assert [c["sha"] for c in commits] == ["a1", "b2"]
+ assert commits[0]["body"].endswith("Fixes #3")
+
+
+def test_parse_shortstat():
+ assert rs.parse_shortstat(" 12 files changed, 300 insertions(+), 40 deletions(-)\n") == (
+ 12,
+ 300,
+ 40,
+ )
+ assert rs.parse_shortstat(" 1 file changed, 2 insertions(+)") == (1, 2, 0)
+ assert rs.parse_shortstat(" 1 file changed, 5 deletions(-)") == (1, 0, 5)
+ assert rs.parse_shortstat("") == (0, 0, 0)
+
+
+def test_counts():
+ subjects = [
+ "feat(web): one (#1)",
+ "fix: two (#2)",
+ "fix(core)!: three (#3)",
+ "perf: four (#4)",
+ "refactor(x): five",
+ "docs: six (#6)",
+ "chore(deps): seven (#7)",
+ "Merge branch main",
+ "fix: two again (#2)",
+ ]
+ assert rs.count_types(subjects) == {
+ "fixes": 3,
+ "features": 1,
+ "perf": 1,
+ "refactors": 1,
+ "docs": 1,
+ }
+ assert rs.count_prs(subjects) == 6
+ bodies = ["Fixes #10 and closes #11", "Resolved #10", "see #12", "fixed #13"]
+ assert rs.count_issues(bodies) == 3
+
+
+def test_is_test_path():
+ assert rs.is_test_path("tests/unit/test_x.py")
+ assert rs.is_test_path("packages/web/src/a.test.tsx")
+ assert rs.is_test_path("pkg/foo_test.go")
+ assert not rs.is_test_path("packages/core/src/attest.py")
+ assert not rs.is_test_path("docs/testing.md")
+
+
+def test_split_first_time_drops_unknown_lookups():
+ returning, first = rs.split_first_time(
+ ["zed", "Amy", "bob", "amy-unknown"], {"zed": 4, "Amy": 0, "bob": 1, "amy-unknown": None}
+ )
+ assert returning == ["bob", "zed"]
+ assert first == ["Amy"]
+
+
+def test_maintainers_and_bots():
+ assert rs.is_maintainer("RaghavChamadiya", "anything")
+ assert rs.is_maintainer(None, "Swati")
+ assert not rs.is_maintainer("someone", "Raghav")
+ assert rs.is_bot("dependabot[bot]", "x")
+
+
+_STATS = {
+ "since": "0.56.0",
+ "days": 3,
+ "prs": 1205,
+ "contributors": 24,
+ "first_time_contributors": 11,
+ "files_changed": 1226,
+ "lines_added": 103206,
+ "lines_removed": 11127,
+ "types": {"fixes": 147, "features": 45, "perf": 2, "refactors": 4, "docs": 6},
+ "test_files_touched": 437,
+ "test_files_new": 144,
+ "issues_closed": 25,
+}
+
+
+def test_render_markdown_has_no_names():
+ md = rs.render_markdown(_STATS)
+ assert md.startswith("### By the numbers\n\nIn the 3 days since 0.56.0:")
+ assert "- **1,205 pull requests** merged, from **24 contributors**, **11 of them" in md
+ assert "**+103,206 / -11,127** lines" in md
+ assert "**147 fixes, 45 features, 2 performance changes**, 4 refactors and 6" in md
+ assert "@" not in md
+
+
+def test_render_markdown_without_github_omits_first_time():
+ md = rs.render_markdown({**_STATS, "first_time_contributors": None, "days": 1})
+ assert "first-time" not in md
+ assert "In the 1 day since" in md
+
+
+def test_render_thanks():
+ text = rs.render_thanks(["a", "b"], ["c"])
+ assert "@a and @b, thank you" in text
+ assert "**1 person whose first contribution landed in this release**: @c." in text
+ assert rs.render_thanks([], []) == ""
+
+
+def test_write_json_merges_by_version(tmp_path):
+ path = tmp_path / "release_stats.json"
+ rs.write_json("0.56.0", {"prs": 1}, path)
+ rs.write_json("unreleased", {"prs": 2}, path)
+ assert json.loads(path.read_text(encoding="utf-8")) == {
+ "0.56.0": {"prs": 1},
+ "unreleased": {"prs": 2},
+ }
+ # Releasing replaces the Unreleased figures.
+ rs.write_json("0.57.0", {"prs": 3}, path)
+ assert json.loads(path.read_text(encoding="utf-8")) == {
+ "0.56.0": {"prs": 1},
+ "0.57.0": {"prs": 3},
+ }
+
+
+def test_render_markdown_omits_zero_kinds():
+ types = {"fixes": 147, "features": 45, "perf": 0, "refactors": 4, "docs": 0}
+ md = rs.render_markdown({**_STATS, "types": types})
+ assert "- **147 fixes, 45 features**, 4 refactors\n" in md
+ assert "performance" not in md and "documentation" not in md
+ none = {"fixes": 0, "features": 0, "perf": 0, "refactors": 0, "docs": 0}
+ assert "fixes" not in rs.render_markdown({**_STATS, "types": none})
+ only = {"fixes": 3, "features": 0, "perf": 1, "refactors": 0, "docs": 0}
+ assert "- **3 fixes and 1 performance changes**\n" in rs.render_markdown({**_STATS, "types": only})
diff --git a/tests/unit/upgrade/test_whats_new.py b/tests/unit/upgrade/test_whats_new.py
index 63d2c2ab5..dd2dbc43e 100644
--- a/tests/unit/upgrade/test_whats_new.py
+++ b/tests/unit/upgrade/test_whats_new.py
@@ -164,3 +164,38 @@ def test_advisory_silent_when_latest_unknown():
buf = io.StringIO()
console = Console(file=buf, width=100)
assert wn.render_update_advisory(console, _check(None, latest=None)) is False
+
+
+def test_render_whats_new_leads_with_highlights_and_numbers(monkeypatch):
+ import io
+
+ text = (
+ "## [0.57.0] - 2026-10-20\n\nSummary.\n\n### Highlights\n\n"
+ "- **Charts in chat** · Any chart. → /repos/:id/chat\n\n"
+ "### Added\n\n- A feature.\n"
+ )
+ stats = {
+ "0.57.0": {
+ "since": "0.56.0",
+ "days": 3,
+ "prs": 205,
+ "contributors": 24,
+ "first_time_contributors": 11,
+ "files_changed": 1226,
+ "lines_added": 103206,
+ "lines_removed": 11127,
+ }
+ }
+ monkeypatch.setattr(wn, "load_release_stats", lambda: stats)
+ buf = io.StringIO()
+ console = Console(file=buf, width=200)
+ assert wn.render_whats_new(console, parse_changelog(text), since_version="0.56.0")
+ out = buf.getvalue()
+ assert out.index("Charts in chat") < out.index("205 pull requests") < out.index("A feature")
+ assert "24 contributors (11 first-time)" in out
+ assert "+103,206 / -11,127 lines" in out
+
+
+def test_numbers_line_tolerates_missing_figures():
+ assert wn.numbers_line(None) is None
+ assert wn.numbers_line({"prs": 1}) is None