Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat: complete UI integration and rebuild the release bundle
rubenluetke10-beepfc041ab7b1c8
diff --git a/jarvis/board/insights.py b/jarvis/board/insights.pynew file mode 100644index 0000000000..274d385563--- /dev/null+++ b/jarvis/board/insights.py@@ -0,0 +1,420 @@+"""Board insights — one read-only picture of how someone works with Jarvis.++The Board's numbers come from the stores the app already keeps. Nothing new is+recorded for the Board and no text leaves this module: only counts,+timestamps and totals are read.++Sources, each optional (a missing or unreadable store reads as "nothing yet"):++* ``dictation_stats.json`` — lifetime dictation counters (words, seconds,+ dictations per local day). Never pruned, holds no text.+* ``personal.db`` — the Board ledger: per-day voice words, voice+ sessions and talk time, aggregated from ``sessions.db``.+* ``sessions.db`` — voice turn start times, for the hour-of-day map.+* ``agent_chat.db`` — chats with Jarvis and the agents: sessions per+ provider and the user's own messages (timestamps only).+* ``cli_usage_index.db`` — coding-agent turns (Claude Code, Codex, ...)+ indexed from the CLIs' own transcripts on this computer.++Days are LOCAL calendar days, like every other streak in the app.+"""+from __future__ import annotations++import contextlib+import logging+import sqlite3+import threading+import time+from collections import defaultdict+from collections.abc import Iterator+from dataclasses import dataclass+from datetime import date as _date+from datetime import datetime, timedelta+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++#: Average typing speed the "time saved" figure compares dictation against.+#: Sent to the UI with the numbers so the comparison is stated, never implied.+TYPING_WPM_REFERENCE = 40++#: Length of an average novel, for the "that is N books" line.+NOVEL_WORDS_REFERENCE = 90_000++#: How many days the daily series covers (53 weeks fill the calendar grid).+SERIES_DAYS = 371++#: Seconds a computed picture is reused before the stores are read again.+CACHE_TTL_S = 30.0+++@dataclass(frozen=True, slots=True)+class InsightSources:+ """Where each store lives. ``None`` switches a source off."""++ dictation_stats: Path | None = None+ board_db: Path | None = None+ sessions_db: Path | None = None+ agent_chat_db: Path | None = None+ cli_index_db: Path | None = None+++def _read_only(path: Path | None) -> Iterator[sqlite3.Connection | None]:+ """A read-only connection, or ``None`` when the store is absent/unreadable."""+ if path is None or not Path(path).is_file():+ yield None+ return+ try:+ conn = sqlite3.connect(f"file:{Path(path).as_posix()}?mode=ro", uri=True, timeout=2.0)+ except sqlite3.Error:+ log.warning("Board insights: %s is not readable", path)+ yield None+ return+ try:+ yield conn+ finally:+ with contextlib.suppress(sqlite3.Error):+ conn.close()+++def _local_day(ms: int) -> str:+ return datetime.fromtimestamp(ms / 1000.0).astimezone().date().isoformat()+++def _local_slot(ms: int) -> tuple[int, int]:+ """(weekday Mon=0, hour) of an epoch-ms instant in local time."""+ moment = datetime.fromtimestamp(ms / 1000.0).astimezone()+ return moment.weekday(), moment.hour+++def _today() -> _date:+ return datetime.now().astimezone().date()+++def current_streak(active_days: set[str], today: _date | None = None) -> int:+ """Consecutive active days up to today; a quiet today does not break it."""+ cursor = today or _today()+ if cursor.isoformat() not in active_days:+ cursor -= timedelta(days=1)+ streak = 0+ while cursor.isoformat() in active_days:+ streak += 1+ cursor -= timedelta(days=1)+ return streak+++def longest_streak(active_days: set[str]) -> int:+ parsed = sorted(_date.fromisoformat(d) for d in active_days)+ best = run = 0+ previous: _date | None = None+ for day in parsed:+ run = run + 1 if previous is not None and (day - previous).days == 1 else 1+ best = max(best, run)+ previous = day+ return best+++class _Day:+ __slots__ = (+ "agent_sessions",+ "agent_turns",+ "chat_messages",+ "dictation_words",+ "dictations",+ "voice_sessions",+ "voice_words",+ )++ def __init__(self) -> None:+ self.dictation_words = 0+ self.dictations = 0+ self.voice_words = 0+ self.voice_sessions = 0+ self.chat_messages = 0+ self.agent_sessions = 0+ self.agent_turns = 0++ def active(self) -> bool:+ return bool(+ self.dictations or self.voice_words or self.voice_sessions or self.chat_messages+ or self.agent_sessions or self.agent_turns+ )+++class BoardInsights:+ """Builds the Board's picture from the stores in ``sources``. Thread-safe."""++ def __init__(self, sources: InsightSources) -> None:+ self._sources = sources+ self._lock = threading.Lock()+ self._cached: dict[str, Any] | None = None+ self._cached_at = 0.0++ def get(self, *, max_age_s: float = CACHE_TTL_S) -> dict[str, Any]:+ with self._lock:+ now = time.monotonic()+ if self._cached is not None and now - self._cached_at < max_age_s:+ return self._cached+ picture = self.build()+ self._cached, self._cached_at = picture, now+ return picture++ # ------------------------------------------------------------------++ def build(self, today: _date | None = None) -> dict[str, Any]:+ today = today or _today()+ days: dict[str, _Day] = defaultdict(_Day)+ punch = [[0] * 24 for _ in range(7)]++ dictation = self._read_dictation(days)+ voice = self._read_voice(days, punch)+ chats = self._read_chats(days, punch)+ agents = self._read_agents(days, punch, today)++ active = {d for d, v in days.items() if v.active()}+ series_start = today - timedelta(days=SERIES_DAYS - 1)+ series = []+ for offset in range(SERIES_DAYS):+ key = (series_start + timedelta(days=offset)).isoformat()+ day = days.get(key)+ series.append({+ "date": key,+ "dictations": day.dictations if day else 0,+ "dictation_words": day.dictation_words if day else 0,+ "voice_sessions": day.voice_sessions if day else 0,+ "voice_words": day.voice_words if day else 0,+ "chat_messages": day.chat_messages if day else 0,+ "agent_sessions": day.agent_sessions if day else 0,+ "agent_turns": day.agent_turns if day else 0,+ })++ def words_between(start: _date, end: _date) -> int:+ total = 0+ for key, day in days.items():+ if start.isoformat() <= key <= end.isoformat():+ total += day.dictation_words + day.voice_words+ return total++ best_words = max(+ days.items(),+ key=lambda kv: (kv[1].dictation_words + kv[1].voice_words, kv[0]),+ default=None,+ )+ best_agents = max(+ days.items(), key=lambda kv: (kv[1].agent_sessions, kv[0]), default=None,+ )++ return {+ "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"),+ "reference": {+ "typing_wpm": TYPING_WPM_REFERENCE,+ "novel_words": NOVEL_WORDS_REFERENCE,+ },+ "dictation": dictation,+ "voice": voice,+ "chats": chats,+ "agents": agents,+ "days": series,+ "punch_card": punch,+ "trend": {+ "words_30d": words_between(today - timedelta(days=29), today),+ "words_prev_30d": words_between(+ today - timedelta(days=59), today - timedelta(days=30)+ ),+ },+ "streak": {+ "current_days": current_streak(active, today),+ "longest_days": longest_streak(active),+ "active_days": len(active),+ "first_day": min(active) if active else None,+ },+ "records": {+ "best_words_day": (+ {"date": best_words[0],+ "value": best_words[1].dictation_words + best_words[1].voice_words}+ if best_words and (best_words[1].dictation_words + best_words[1].voice_words)+ else None+ ),+ "best_agent_day": (+ {"date": best_agents[0], "value": best_agents[1].agent_sessions}+ if best_agents and best_agents[1].agent_sessions else None+ ),+ },+ }++ # ------------------------------------------------------------------+ # Sources+ # ------------------------------------------------------------------++ def _read_dictation(self, days: dict[str, _Day]) -> dict[str, Any]:+ out: dict[str, Any] = {"available": False, "words": 0, "dictations": 0, "seconds": 0.0}+ path = self._sources.dictation_stats+ if path is None or not Path(path).is_file():+ return out+ from jarvis.dictation.stats import DictationStats++ totals, by_day = DictationStats(path).load()+ for key, stat in by_day.items():+ day = days[key]+ day.dictation_words += stat.words+ day.dictations += stat.dictations+ out.update(+ available=True,+ words=int(totals.get("words", 0)),+ dictations=int(totals.get("dictations", 0)),+ seconds=round(float(totals.get("seconds", 0.0)), 1),+ )+ return out++ def _read_voice(self, days: dict[str, _Day], punch: list[list[int]]) -> dict[str, Any]:+ out: dict[str, Any] = {+ "available": False, "sessions": 0, "turns": 0,+ "user_words": 0, "jarvis_words": 0, "seconds": 0.0,+ }+ with _read_only(self._sources.board_db) as conn:+ if conn is not None:+ try:+ for date, user_words, jarvis_words, sessions, seconds in conn.execute(+ "SELECT date, user_words_count, jarvis_words_count, "+ "session_count, conversation_seconds_estimate FROM daily_stats"+ ):+ days[date].voice_words += int(user_words or 0)+ days[date].voice_sessions += int(sessions or 0)+ out["user_words"] += int(user_words or 0)+ out["jarvis_words"] += int(jarvis_words or 0)+ out["sessions"] += int(sessions or 0)+ out["seconds"] += float(seconds or 0.0)+ out["available"] = True+ except sqlite3.Error:+ log.warning("Board insights: board ledger unreadable", exc_info=True)+ with _read_only(self._sources.sessions_db) as conn:+ if conn is not None:+ try:+ for (started_ms,) in conn.execute("SELECT started_ms FROM voice_turns"):+ if started_ms:+ out["turns"] += 1+ weekday, hour = _local_slot(int(started_ms))+ punch[weekday][hour] += 1+ out["available"] = True+ except sqlite3.Error:+ log.warning("Board insights: sessions.db unreadable", exc_info=True)+ out["seconds"] = round(out["seconds"], 1)+ return out++ def _read_chats(self, days: dict[str, _Day], punch: list[list[int]]) -> dict[str, Any]:+ out: dict[str, Any] = {"available": False, "sessions": 0, "messages": 0, "providers": []}+ with _read_only(self._sources.agent_chat_db) as conn:+ if conn is None:+ return out+ try:+ providers: dict[str, dict[str, int]] = {}+ for provider, surface, sessions in conn.execute(+ "SELECT provider, surface, COUNT(*) FROM agent_chat_sessions "+ "GROUP BY provider, surface"+ ):+ row = providers.setdefault(+ provider or "", {"sessions": 0, "messages": 0, "jarvis_sessions": 0}+ )+ row["sessions"] += int(sessions)+ if surface == "jarvis":+ row["jarvis_sessions"] += int(sessions)+ out["sessions"] += int(sessions)+ for provider, ts_ms in conn.execute(+ "SELECT s.provider, e.ts_ms FROM agent_chat_events e "+ "JOIN agent_chat_sessions s ON s.session_id = e.session_id "+ "WHERE e.kind = 'user_message'"+ ):+ if not ts_ms:+ continue+ providers.setdefault(+ provider or "", {"sessions": 0, "messages": 0, "jarvis_sessions": 0}+ )["messages"] += 1+ out["messages"] += 1+ days[_local_day(int(ts_ms))].chat_messages += 1+ weekday, hour = _local_slot(int(ts_ms))+ punch[weekday][hour] += 1+ out["providers"] = sorted(+ ({"provider": k, **v} for k, v in providers.items() if k),+ key=lambda r: (-r["messages"], -r["sessions"], r["provider"]),+ )+ out["available"] = True+ except sqlite3.Error:+ log.warning("Board insights: agent_chat.db unreadable", exc_info=True)+ return out++ def _read_agents(+ self, days: dict[str, _Day], punch: list[list[int]], today: _date+ ) -> dict[str, Any]:+ out: dict[str, Any] = {+ "available": False, "sessions": 0, "turns": 0, "tokens": 0, "items": [],+ }+ with _read_only(self._sources.cli_index_db) as conn:+ if conn is None:+ return out+ cutoff_ms = int(+ datetime.combine(today - timedelta(days=29), datetime.min.time())+ .astimezone().timestamp() * 1000+ )+ try:+ items: dict[str, dict[str, Any]] = {}+ for agent, session_id, first_ms, last_ms, turns, tokens in conn.execute(+ "SELECT agent, session_id, MIN(ts_ms), MAX(ts_ms), COUNT(*), "+ "SUM(tokens_in + tokens_out) FROM cli_turns WHERE ts_ms > 0 "+ "GROUP BY agent, session_id"+ ):+ item = items.setdefault(agent, {+ "agent": agent, "sessions": 0, "sessions_30d": 0, "turns": 0,+ "turns_30d": 0, "tokens": 0, "last_ms": 0,+ })+ item["turns"] += int(turns)+ item["tokens"] += int(tokens or 0)+ item["last_ms"] = max(item["last_ms"], int(last_ms))+ if session_id:+ item["sessions"] += 1+ days[_local_day(int(first_ms))].agent_sessions += 1+ if int(first_ms) >= cutoff_ms:+ item["sessions_30d"] += 1+ for agent, day, turns in conn.execute(+ "SELECT agent, strftime('%Y-%m-%d', ts_ms / 1000, 'unixepoch', 'localtime'), "+ "COUNT(*) FROM cli_turns WHERE ts_ms > 0 GROUP BY 1, 2"+ ):+ days[day].agent_turns += int(turns)+ if day >= (today - timedelta(days=29)).isoformat() and agent in items:+ items[agent]["turns_30d"] += int(turns)+ for weekday, hour, turns in conn.execute(+ "SELECT "+ "CAST(strftime('%w', ts_ms / 1000, 'unixepoch', 'localtime') AS INTEGER), "+ "CAST(strftime('%H', ts_ms / 1000, 'unixepoch', 'localtime') AS INTEGER), "+ "COUNT(*) FROM cli_turns WHERE ts_ms > 0 GROUP BY 1, 2"+ ):+ # SQLite counts Sunday as 0; the punch card is Monday-first.+ punch[(int(weekday) + 6) % 7][int(hour)] += int(turns)+ out["items"] = sorted(+ items.values(), key=lambda r: (-r["sessions"], -r["turns"], r["agent"])+ )+ out["sessions"] = sum(r["sessions"] for r in items.values())+ out["turns"] = sum(r["turns"] for r in items.values())+ out["tokens"] = sum(r["tokens"] for r in items.values())+ out["available"] = True+ except sqlite3.Error:+ log.warning("Board insights: cli_usage_index.db unreadable", exc_info=True)+ return out+++def default_sources(+ *, data_dir: Path, sessions_db: Path | None, board_db: Path | None+) -> InsightSources:+ """The live app's store locations, resolved the way each store's owner does."""+ from jarvis.costs.cli_usage_index import index_db_path+ from jarvis.dictation.stats import default_stats_path++ return InsightSources(+ dictation_stats=default_stats_path(),+ board_db=board_db,+ sessions_db=sessions_db,+ agent_chat_db=Path(data_dir) / "agent_chat.db",+ cli_index_db=index_db_path(),+ )+diff --git a/jarvis/ui/web/board_routes.py b/jarvis/ui/web/board_routes.pyindex d1836829ae..51a0f217f4 100644--- a/jarvis/ui/web/board_routes.py+++ b/jarvis/ui/web/board_routes.py@@ -7,6 +7,7 @@ Endpoints:- ``GET /api/board/personal/tools`` → tool-usage histogram- ``GET /api/board/personal/records`` → personal records- ``POST /api/board/personal/refresh`` → manual aggregator run+- ``GET /api/board/insights`` → the Board page: every usage source- ``GET /api/board/achievements`` → all specs with unlock status- ``GET /api/board/bio`` → current AI bio + age- ``POST /api/board/bio/regenerate`` → manually generate a new bio@@ -258,6 +259,130 @@ async def personal_refresh(request: Request) -> RefreshResponse:raise HTTPException(status_code=500, detail=str(exc)) from exc+# ----------------------------------------------------------------------+# Insights — the Board page+# ----------------------------------------------------------------------++class InsightsReference(BaseModel):+ typing_wpm: int+ novel_words: int+++class InsightsDictation(BaseModel):+ available: bool+ words: int+ dictations: int+ seconds: float+++class InsightsVoice(BaseModel):+ available: bool+ sessions: int+ turns: int+ user_words: int+ jarvis_words: int+ seconds: float+++class InsightsChatProvider(BaseModel):+ provider: str+ sessions: int+ messages: int+ jarvis_sessions: int+++class InsightsChats(BaseModel):+ available: bool+ sessions: int+ messages: int+ providers: list[InsightsChatProvider]+++class InsightsAgent(BaseModel):+ agent: str+ sessions: int+ sessions_30d: int+ turns: int+ turns_30d: int+ tokens: int+ last_ms: int+++class InsightsAgents(BaseModel):+ available: bool+ sessions: int+ turns: int+ tokens: int+ items: list[InsightsAgent]+++class InsightsDay(BaseModel):+ date: str+ dictations: int+ dictation_words: int+ voice_sessions: int+ voice_words: int+ chat_messages: int+ agent_sessions: int+ agent_turns: int+++class InsightsTrend(BaseModel):+ words_30d: int+ words_prev_30d: int+++class InsightsStreak(BaseModel):+ current_days: int+ longest_days: int+ active_days: int+ first_day: str | None+++class InsightsRecord(BaseModel):+ date: str+ value: int+++class InsightsRecords(BaseModel):+ best_words_day: InsightsRecord | None+ best_agent_day: InsightsRecord | None+++class InsightsResponse(BaseModel):+ generated_at: str+ reference: InsightsReference+ dictation: InsightsDictation+ voice: InsightsVoice+ chats: InsightsChats+ agents: InsightsAgents+ days: list[InsightsDay]+ #: 7 rows (Monday first) x 24 local hours of activity counts.+ punch_card: list[list[int]]+ trend: InsightsTrend+ streak: InsightsStreak+ records: InsightsRecords+ categories: CategoriesResponse+++@board_router.get("/insights", response_model=InsightsResponse)+async def board_insights(request: Request) -> InsightsResponse:+ """Everything the Board page draws, from the stores the app already keeps.++ Counts and timestamps only — no text is read into the answer. Each source+ is optional: a missing store reads as ``available: false`` with zeros, so+ the page can say "nothing yet" instead of failing.+ """+ insights = getattr(request.app.state, "board_insights", None)+ if insights is None:+ raise HTTPException(status_code=503, detail="Board insights not available")+ store = _require_store(request)+ await _freshen(request)+ picture = await asyncio.to_thread(insights.get)+ categories = await asyncio.to_thread(store.categories, window_days=None)+ return InsightsResponse.model_validate({**picture, "categories": categories})++# ----------------------------------------------------------------------# Phase B — Achievements + Bio# ----------------------------------------------------------------------diff --git a/jarvis/ui/web/frontend/src/assets/voice/dictation-hero.webp b/jarvis/ui/web/frontend/src/assets/voice/dictation-hero.webpnew file mode 100644index 0000000000..5f112e06a0Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/voice/dictation-hero.webp differdiff --git a/jarvis/ui/web/frontend/src/components/board/AIProfileCard.tsx b/jarvis/ui/web/frontend/src/components/board/AIProfileCard.tsxdeleted file mode 100644index fc86dd0a49..0000000000--- a/jarvis/ui/web/frontend/src/components/board/AIProfileCard.tsx+++ /dev/null@@ -1,193 +0,0 @@-import { Check, Loader2, RefreshCw, Sparkles, X, Zap } from "lucide-react";-import { useEffect, useState } from "react";-import {- type BioFeedbackKind,- useBio,- useBioFeedback,- useBioRegenerate,-} from "@/hooks/useBoard";-import { cn } from "@/lib/utils";-import { useT } from "@/i18n";--/**- * "Who is this user?" — an AI-generated self-observation by Jarvis in- * first-person narrator style, biting with a wink (brainstorm 2026-05-02).- *- * Three reaction buttons under the text calibrate the next bio generation- * (Correct / Incorrect / Harder). Clicks do NOT regenerate immediately —- * they flow as a tone vector into the Sunday run.- */-export function AIProfileCard() {- const t = useT();- const bio = useBio();- const regen = useBioRegenerate();- const feedback = useBioFeedback();-- const data = bio.data;- const [lastFeedback, setLastFeedback] = useState<BioFeedbackKind | null>(null);-- // Hide the "Noted." toast again after 2.5s so it doesn't linger.- useEffect(() => {- if (!lastFeedback) return;- const t = setTimeout(() => setLastFeedback(null), 2500);- return () => clearTimeout(t);- }, [lastFeedback]);-- const handleFeedback = (kind: BioFeedbackKind) => {- if (!data?.generated_at) return;- feedback.mutate(- { bio_generated_at: data.generated_at, kind },- { onSuccess: () => setLastFeedback(kind) },- );- };-- const stalenessLabel = (() => {- const d = data?.staleness_days;- if (d == null) return null;- if (d === 0) return t("board_view.ai_profile_today");- if (d === 1) return t("board_view.ai_profile_one_day_ago");- return t("board_view.ai_profile_days_ago").replace("{0}", String(d));- })();-- return (- <section className="space-y-3 rounded-xl border border-border bg-card/30 p-5 backdrop-blur">- <header className="flex items-start gap-3">- <div className="flex h-8 w-8 items-center justify-center rounded-lg border border-primary/40 bg-primary/10 text-primary">- <Sparkles className="h-4 w-4" />- </div>- <div className="flex-1 min-w-0">- <h3 className="font-display text-sm font-semibold">{t("board_view.ai_profile_title")}</h3>- <p className="text-xs text-muted-foreground">- {t("board_view.ai_profile_description")}- </p>- </div>- <button- type="button"- onClick={() => regen.mutate({})}- disabled={regen.isPending}- className={cn(- "inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium transition-colors",- "hover:border-primary/40 hover:bg-background/60",- regen.isPending && "opacity-60",- )}- title={t("board_view.ai_profile_regenerate_tooltip")}- >- <RefreshCw className={cn("h-3 w-3", regen.isPending && "animate-spin")} />- {t("board_view.ai_profile_regenerate")}- </button>- </header>-- {bio.isLoading && (- <div className="flex items-center gap-2 text-xs text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin" /> {t("board_view.ai_profile_loading")}- </div>- )}-- {!bio.isLoading && !data?.text && (- <div className="rounded-lg border border-dashed border-border/60 p-4 text-sm text-muted-foreground">- <div className="flex items-center gap-2">- <Loader2 className="h-3 w-3 animate-spin opacity-60" />- <span>{t("board_view.ai_profile_collecting")}</span>- </div>- <p className="mt-1.5 text-xs opacity-80">- {t("board_view.ai_profile_first_bio_hint")}- </p>- </div>- )}-- {data?.text && (- <div className="space-y-3">- <p className="whitespace-pre-wrap text-sm leading-relaxed text-foreground/90">- {data.text}- </p>- <div className="flex items-center gap-3 text-micro uppercase tracking-wider text-muted-foreground">- {stalenessLabel && <span>{stalenessLabel}</span>}- {data.triggered_by && <span>· {data.triggered_by}</span>}- {data.model_used && <span>· {data.model_used}</span>}- </div>- <div className="flex flex-wrap items-center gap-2 border-t border-border/40 pt-3">- <FeedbackButton- kind="trifft"- icon={<Check className="h-3 w-3" />}- label={t("board_view.feedback_correct")}- colorClass="border-muted-foreground/40 bg-muted-foreground/10 text-muted-foreground hover:bg-muted-foreground/20"- active={lastFeedback === "trifft"}- disabled={feedback.isPending}- onClick={() => handleFeedback("trifft")}- />- <FeedbackButton- kind="trifft_nicht" // i18n-allow: API contract value matched in logic- icon={<X className="h-3 w-3" />}- label={t("board_view.feedback_incorrect")}- colorClass="border-rose-500/40 bg-rose-500/10 text-rose-300 hover:bg-rose-500/20"- active={lastFeedback === "trifft_nicht"} // i18n-allow: API contract value matched in logic- disabled={feedback.isPending}- onClick={() => handleFeedback("trifft_nicht")} // i18n-allow: API contract value matched in logic- />- <FeedbackButton- kind="haerter"- icon={<Zap className="h-3 w-3" />}- label={t("board_view.feedback_harder")}- colorClass="border-foreground/40 bg-foreground/10 text-foreground hover:bg-foreground/20"- active={lastFeedback === "haerter"}- disabled={feedback.isPending}- onClick={() => handleFeedback("haerter")}- />- {lastFeedback && (- <span className="text-xs italic text-muted-foreground">- {t("board_view.feedback_noted")}- </span>- )}- </div>- </div>- )}-- {regen.isError && (- <div className="text-xs text-destructive">- {t("board_view.regenerate_failed")}: {(regen.error as Error).message}- </div>- )}- {regen.data && !regen.data.ok && regen.data.reason && (- <div className="text-xs text-foreground">- {regen.data.reason}- </div>- )}- </section>- );-}--interface FeedbackButtonProps {- kind: BioFeedbackKind;- icon: React.ReactNode;- label: string;- colorClass: string;- active: boolean;- disabled: boolean;- onClick: () => void;-}--function FeedbackButton({- icon,- label,- colorClass,- active,- disabled,- onClick,-}: FeedbackButtonProps) {- return (- <button- type="button"- onClick={onClick}- disabled={disabled}- className={cn(- "inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition-colors",- colorClass,- active && "ring-1 ring-current",- disabled && "opacity-60",- )}- >- {icon}- {label}- </button>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsx b/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsxdeleted file mode 100644index a782f62cec..0000000000--- a/jarvis/ui/web/frontend/src/components/board/AchievementGrid.tsx+++ /dev/null@@ -1,128 +0,0 @@-import { useEffect } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { Award, Lock, Sparkles } from "lucide-react";-import { useAchievements, type AchievementItem } from "@/hooks/useBoard";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";--/**- * Full trophy wall. Unlocked in primary color, locked grayed out- * with a lock icon. No badge counter for other users (Plan §0 — no- * public like counts); the wall is private, only the user sees it.- */-export function AchievementGrid() {- const t = useT();- const qc = useQueryClient();- const { data, isLoading } = useAchievements();-- // Live unlock via WS — when the evaluator publishes an unlock,- // this invalidates the React-Query cache and the card fills in- // without a polling delay.- useEffect(() => {- const handler = () => qc.invalidateQueries({ queryKey: ["board", "achievements"] });- window.addEventListener("jarvis:achievement-unlocked", handler as EventListener);- return () => window.removeEventListener(- "jarvis:achievement-unlocked", handler as EventListener,- );- }, [qc]);-- if (isLoading) {- return <div className="h-24 animate-pulse rounded-md bg-muted/10" />;- }- if (!data) return null;-- const mastery = data.items.filter((i) => i.tier === "mastery");- const reflection = data.items.filter((i) => i.tier === "reflection");-- return (- <section className="space-y-4 rounded-xl border border-border bg-card/30 p-5 backdrop-blur">- <header className="flex items-start gap-3">- <div className="flex h-8 w-8 items-center justify-center rounded-lg border border-primary/40 bg-primary/10 text-primary">- <Award className="h-4 w-4" />- </div>- <div className="flex-1 min-w-0">- <h3 className="font-display text-sm font-semibold">Achievements</h3>- <p className="text-xs text-muted-foreground">- {`${data.unlocked} ${t("achievement_grid.unlocked_of")} ${data.total} ${t("achievement_grid.unlocked_count")}`}- </p>- </div>- </header>-- {mastery.length > 0 && (- <div className="space-y-2">- <div className="text-micro uppercase tracking-wider text-muted-foreground">- Mastery- </div>- <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">- {mastery.map((a) => <AchievementCard key={a.id} item={a} />)}- </div>- </div>- )}-- {reflection.length > 0 && (- <div className="space-y-2">- <div className="text-micro uppercase tracking-wider text-muted-foreground">- Reflection- </div>- <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">- {reflection.map((a) => <AchievementCard key={a.id} item={a} />)}- </div>- </div>- )}- </section>- );-}--function AchievementCard({ item }: { item: AchievementItem }) {- const unlocked = !!item.unlocked_at;- return (- <div- className={cn(- "flex items-start gap-3 rounded-lg border px-3 py-2.5 transition-colors",- unlocked- ? "border-primary/40 bg-primary/5"- : "border-border/50 bg-muted/10 opacity-70",- )}- >- <div- className={cn(- "flex h-7 w-7 shrink-0 items-center justify-center rounded-md",- unlocked- ? "bg-primary/20 text-primary"- : "bg-muted/30 text-muted-foreground",- )}- >- {unlocked ? <Sparkles className="h-3.5 w-3.5" /> : <Lock className="h-3 w-3" />}- </div>- <div className="min-w-0 flex-1">- <div- className={cn(- "text-sm font-medium",- unlocked ? "text-foreground" : "text-muted-foreground",- )}- >- {item.title}- </div>- <div className="text-xs leading-snug text-muted-foreground">- {item.description}- </div>- {unlocked && item.unlocked_at && (- <div className="mt-1 text-micro text-muted-foreground">- {formatUnlockDate(item.unlocked_at)}- </div>- )}- </div>- </div>- );-}--function formatUnlockDate(iso: string): string {- try {- const d = new Date(iso);- return d.toLocaleDateString("de-DE", {- day: "2-digit", month: "2-digit", year: "numeric",- });- } catch {- return iso;- }-}diff --git a/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsx b/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsxdeleted file mode 100644index 783ccc5fab..0000000000--- a/jarvis/ui/web/frontend/src/components/board/ActivityFeed.tsx+++ /dev/null@@ -1,155 +0,0 @@-import { useState } from "react";-import { Loader2, MessageSquarePlus, RefreshCw, Sparkles } from "lucide-react";-import {- useFeed, useFriendsList, useSendReaction,- type ActivityItemDTO, type Reaction,-} from "@/hooks/useFederation";-import { ReactionBar } from "@/components/board/ReactionBar";-import { StoryComposer } from "@/components/board/StoryComposer";-import { cn } from "@/lib/utils";-import { useT } from "@/i18n";--export function ActivityFeed() {- const t = useT();- const [sort, setSort] = useState<"interesting" | "latest">("interesting");- const [composerOpen, setComposerOpen] = useState(false);- const feed = useFeed(sort);- const friends = useFriendsList();- const sendReact = useSendReaction();-- const friendsByPubkey = new Map(- (friends.data?.friends ?? []).map((f) => [f.pubkey, f]),- );-- return (- <section className="space-y-4 rounded-xl border border-border bg-card/30 p-5 backdrop-blur">- <header className="flex flex-wrap items-center gap-3">- <h3 className="font-display text-sm font-semibold flex-1">{t("activity_feed.title")}</h3>- <SortToggle value={sort} onChange={setSort} />- <button- type="button"- onClick={() => feed.refetch()}- className="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs hover:border-primary/40"- title={t("activity_feed.refresh_tooltip")}- >- <RefreshCw className={cn("h-3 w-3", feed.isFetching && "animate-spin")} />- Refresh- </button>- <button- type="button"- onClick={() => setComposerOpen(true)}- className="inline-flex items-center gap-1 rounded-md border border-primary/40 bg-primary/10 px-2.5 py-1 text-xs text-primary hover:bg-primary/20"- >- <MessageSquarePlus className="h-3 w-3" />- Story- </button>- </header>-- {feed.isLoading && (- <div className="flex items-center gap-2 text-xs text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin" /> {t("activity_feed.loading")}- </div>- )}- {feed.isError && (- <div className="rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">- {(feed.error as Error).message}- </div>- )}-- {feed.data?.items.length === 0 && (- <div className="rounded-md border border-dashed border-border/60 p-4 text-xs text-muted-foreground">- {t("activity_feed.empty")}- </div>- )}-- <ul className="space-y-3">- {(feed.data?.items ?? []).map((it) => (- <FeedRow- key={it.id} item={it}- friendName={friendsByPubkey.get(it.author_pubkey)?.display_name}- onReact={(r) => sendReact.mutate({- item_id: it.id, reaction: r, author_pubkey: it.author_pubkey,- })}- />- ))}- </ul>-- {composerOpen && <StoryComposer onClose={() => setComposerOpen(false)} />}- </section>- );-}--function SortToggle({- value, onChange,-}: { value: "interesting" | "latest"; onChange: (v: "interesting" | "latest") => void }) {- return (- <div className="flex gap-0.5 rounded-md border border-border bg-background/40 p-0.5">- <button- onClick={() => onChange("interesting")}- className={cn(- "rounded px-2 py-0.5 text-micro uppercase tracking-wider transition-colors",- value === "interesting" ? "bg-primary/15 text-primary" : "text-muted-foreground",- )}- >Interesting</button>- <button- onClick={() => onChange("latest")}- className={cn(- "rounded px-2 py-0.5 text-micro uppercase tracking-wider transition-colors",- value === "latest" ? "bg-primary/15 text-primary" : "text-muted-foreground",- )}- >Latest</button>- </div>- );-}--function FeedRow({- item, friendName, onReact,-}: {- item: ActivityItemDTO;- friendName: string | undefined;- onReact: (r: Reaction) => void;-}) {- const author = friendName ?? item.author_display_name ?? `${item.author_pubkey.slice(0, 8)}…`;- return (- <li className="rounded-lg border border-border bg-background/40 p-3">- <header className="mb-2 flex items-center gap-2 text-micro uppercase tracking-wider text-muted-foreground">- <Sparkles className="h-3 w-3 text-primary" />- <span>{author}</span>- <span>·</span>- <span>{new Date(item.created_at).toLocaleString("de-DE")}</span>- <span>·</span>- <span className={cn(- item.visibility === "public" && "text-muted-foreground",- item.visibility === "private" && "text-foreground",- )}>{item.visibility}</span>- </header>- <ItemBody item={item} />- <footer className="mt-2 flex items-center justify-between">- <ReactionBar- counts={item.reaction_counts}- hasReactions={item.has_reactions}- onReact={onReact}- />- </footer>- </li>- );-}--function ItemBody({ item }: { item: ActivityItemDTO }) {- if (item.kind === "story") {- const text = (item.payload?.text as string) ?? "";- return <p className="whitespace-pre-wrap text-sm">{text}</p>;- }- if (item.kind === "achievement_unlocked") {- const id = (item.payload?.achievement_id as string) ?? "achievement";- return (- <p className="text-sm">- <span className="font-medium">Achievement: </span>- <span className="font-mono text-primary">{id}</span>- </p>- );- }- return (- <p className="text-xs text-muted-foreground">{item.kind}</p>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/ActivityHeatmap.tsx b/jarvis/ui/web/frontend/src/components/board/ActivityHeatmap.tsxdeleted file mode 100644index fd732bcbbc..0000000000--- a/jarvis/ui/web/frontend/src/components/board/ActivityHeatmap.tsx+++ /dev/null@@ -1,145 +0,0 @@-import { useMemo } from "react";-import type { HeatmapCell } from "@/hooks/useBoard";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";--const LEVEL: Record<number, string> = {- 0: "bg-sheen/[0.04] ring-1 ring-inset ring-sheen/[0.03]",- 1: "bg-primary/30",- 2: "bg-primary/50",- 3: "bg-primary/75",- 4: "bg-foreground/70 /50",-};--const DEFAULT_WEEKS = 26;--function isoOf(d: Date): string {- return (- `${d.getFullYear()}-` +- `${String(d.getMonth() + 1).padStart(2, "0")}-` +- `${String(d.getDate()).padStart(2, "0")}`- );-}--interface Slot {- date: string;- events: number;- hours: number;- future: boolean;-}--/**- * GitHub-style contribution grid: columns = weeks (oldest left, current week- * right), rows = weekdays (Mon..Sun). Replaces the old boustrophedon "snake"- * that was split into two scrolling halves. Bounded to ``weeks`` columns so it- * fits a one-pager without horizontal scroll.- */-export function ActivityHeatmap({- cells,- weeks = DEFAULT_WEEKS,-}: {- cells: HeatmapCell[];- weeks?: number;-}) {- const t = useT();-- const { columns, monthLabels, max } = useMemo(() => {- const byDate = new Map(cells.map((c) => [c.date, c]));- const peak = Math.max(1, ...cells.map((c) => c.activity_events));- const todayIso = cells.length- ? cells[cells.length - 1].date- : isoOf(new Date());- const today = new Date(todayIso + "T00:00:00");- // Monday-based weekday index: 0 = Mon … 6 = Sun.- const weekday = (today.getDay() + 6) % 7;- const thisMonday = new Date(today);- thisMonday.setDate(today.getDate() - weekday);-- const cols: Slot[][] = [];- const labels: string[] = [];- let prevMonth = -1;- for (let c = 0; c < weeks; c += 1) {- const colMonday = new Date(thisMonday);- colMonday.setDate(thisMonday.getDate() - (weeks - 1 - c) * 7);- const month = colMonday.getMonth();- // Label a column only when its first weekday rolls into a new month.- if (month !== prevMonth) {- labels.push(colMonday.toLocaleDateString(undefined, { month: "short" }));- prevMonth = month;- } else {- labels.push("");- }- const col: Slot[] = [];- for (let r = 0; r < 7; r += 1) {- const d = new Date(colMonday);- d.setDate(colMonday.getDate() + r);- const iso = isoOf(d);- const cell = byDate.get(iso);- col.push({- date: iso,- events: cell?.activity_events ?? 0,- hours: cell?.conversation_hours ?? 0,- future: d > today,- });- }- cols.push(col);- }- return { columns: cols, monthLabels: labels, max: peak };- }, [cells, weeks]);-- return (- <div className="inline-flex flex-col gap-1.5">- <div className="flex gap-[3px]">- {monthLabels.map((label, ci) => (- <div- key={ci}- className="w-3.5 text-micro capitalize leading-none text-muted-foreground/70"- >- {label}- </div>- ))}- </div>- <div className="flex gap-[3px]">- {columns.map((col, ci) => (- <div key={ci} className="flex flex-col gap-[3px]">- {col.map((slot, ri) => {- if (slot.future) {- return <div key={ri} className="h-3.5 w-3.5 rounded-[4px]" />;- }- const intensity =- slot.events === 0- ? 0- : Math.min(4, Math.ceil((slot.events / max) * 4));- return (- <div- key={ri}- className={cn(- "h-3.5 w-3.5 rounded-[4px] transition-colors",- LEVEL[intensity],- )}- title={t("board_view.heatmap_tooltip")- .replace("{0}", slot.date)- .replace("{1}", String(slot.events))- .replace("{2}", slot.hours.toFixed(1))}- />- );- })}- </div>- ))}- </div>- </div>- );-}--export function HeatmapScale() {- const t = useT();- return (- <div className="flex items-center gap-1.5 text-micro uppercase tracking-wider text-muted-foreground">- <span>{t("board_view.heatmap_less")}</span>- {[0, 1, 2, 3, 4].map((lvl) => (- <span key={lvl} className={cn("h-2.5 w-2.5 rounded-[2px]", LEVEL[lvl])} />- ))}- <span>{t("board_view.heatmap_more")}</span>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/BackendConnectionSection.tsx b/jarvis/ui/web/frontend/src/components/board/BackendConnectionSection.tsxdeleted file mode 100644index 96b80fce21..0000000000--- a/jarvis/ui/web/frontend/src/components/board/BackendConnectionSection.tsx+++ /dev/null@@ -1,112 +0,0 @@-import { useState } from "react";-import { Copy, Loader2, Plug, PlugZap } from "lucide-react";-import { useDisconnect, useFederationStatus } from "@/hooks/useFederation";-import { robustCopy } from "@/lib/clipboard";-import { useT } from "@/i18n";--/**- * Settings section: backend connection (Plan §D spec).- *- * - Disconnect button (local-only mode): toggles board.federation.enabled in-memory.- * - Backend URL: read-only display; a permanent change happens in jarvis.toml.- * - Pubkey: display + copy.- *- * Plan §D §0: NO online indicator. We only show whether federation- * is enabled (a setting), not whether the backend connection is currently- * "live".- */-export function BackendConnectionSection() {- const t = useT();- const status = useFederationStatus();- const disconnect = useDisconnect();- const [copied, setCopied] = useState(false);-- return (- <div className="rounded-lg border border-border bg-card/60 p-4">- <header className="mb-3 flex items-center gap-2">- {status.data?.enabled ? (- <PlugZap className="h-4 w-4 text-muted-foreground" />- ) : (- <Plug className="h-4 w-4 text-muted-foreground" />- )}- <h4 className="font-display text-sm font-semibold flex-1">- {t("board_view.backend_section_title")}- </h4>- {status.data?.enabled && (- <button- type="button"- onClick={() => disconnect.mutate()}- disabled={disconnect.isPending}- className="rounded-md border border-border px-2.5 py-1 text-xs text-muted-foreground hover:text-foreground disabled:opacity-50"- title={t("board_view.backend_disconnect_tooltip")}- >- {disconnect.isPending && <Loader2 className="mr-1 inline h-3 w-3 animate-spin" />}- {t("board_view.backend_disconnect")}- </button>- )}- </header>-- {status.isLoading && (- <div className="flex items-center gap-2 text-xs text-muted-foreground">- <Loader2 className="h-3 w-3 animate-spin" /> {t("board_view.backend_status_loading")}- </div>- )}-- {status.data && !status.data.enabled && (- <p className="text-xs text-muted-foreground">- {t("board_view.backend_local_only")}- </p>- )}-- {status.data?.enabled && (- <div className="space-y-2 text-xs">- <Row label={t("board_view.backend_url_label")}>- <code className="font-mono text-xs">- {status.data.backend_url || t("board_view.backend_url_unset")}- </code>- <p className="mt-1 text-micro text-muted-foreground">- {t("board_view.backend_url_hint")}- </p>- </Row>-- {status.data.pubkey && (- <Row label={t("board_view.backend_pubkey_label")}>- <button- type="button"- onClick={() => {- robustCopy(status.data!.pubkey!)- .then((ok) => {- if (ok) {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- }- })- .catch((err) => {- console.warn("Clipboard write failed:", err);- });- }}- className="inline-flex items-center gap-1 font-mono text-micro text-muted-foreground hover:text-foreground"- title={t("board_view.backend_pubkey_copy_tooltip")}- >- <code>{status.data.pubkey.slice(0, 20)}…{status.data.pubkey.slice(-8)}</code>- <Copy className="h-3 w-3" />- {copied && <span className="ml-1 text-primary">{t("board_view.backend_pubkey_copied")}</span>}- </button>- </Row>- )}- </div>- )}- </div>- );-}--function Row({ label, children }: { label: string; children: React.ReactNode }) {- return (- <div className="flex flex-col gap-1 sm:flex-row sm:items-baseline sm:gap-3">- <div className="w-32 shrink-0 text-micro uppercase tracking-wider text-muted-foreground">- {label}- </div>- <div className="flex-1 min-w-0">{children}</div>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/BoardCard.tsx b/jarvis/ui/web/frontend/src/components/board/BoardCard.tsxdeleted file mode 100644index 8964e0ce61..0000000000--- a/jarvis/ui/web/frontend/src/components/board/BoardCard.tsx+++ /dev/null@@ -1,35 +0,0 @@-import type { ReactNode } from "react";-import { cn } from "@/lib/utils";--interface BoardCardProps {- children: ReactNode;- className?: string;- /** Faint primary glow in the corner — for the hero / signature surface. */- glow?: boolean;-}--/**- * The board's single elevated surface. Depth comes from light, not from hard- * borders: a subtle top-lit gradient lifts the card off the near-black page,- * a hairline white border replaces the harsh grey, and an inset highlight +- * soft drop shadow give it a physical edge. This is the whole "premium, not- * AI-slop" move applied consistently.- */-export function BoardCard({ children, className, glow }: BoardCardProps) {- return (- <div- className={cn(- "relative overflow-hidden rounded-[20px]",- "bg-gradient-to-b from-sheen/[0.055] to-sheen/[0.015]",- "border border-sheen/[0.07]",- "shadow-[inset_0_1px_0_0_rgba(255,255,255,0.06),0_16px_40px_-20px_rgba(0,0,0,0.8)]",- className,- )}- >- {glow && (- <div className="pointer-events-none absolute -right-16 -top-20 h-56 w-56 rounded-full bg-primary/[0.12] blur-3xl" />- )}- {children}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/CategoryUsage.tsx b/jarvis/ui/web/frontend/src/components/board/CategoryUsage.tsxdeleted file mode 100644index 53b9fd219e..0000000000--- a/jarvis/ui/web/frontend/src/components/board/CategoryUsage.tsx+++ /dev/null@@ -1,88 +0,0 @@-import { useMemo } from "react";-import type { BoardCategories } from "@/hooks/useBoard";-import {- BOARD_CATEGORY_KEYS,- CATEGORY_META,- categoryLabelKey,- type BoardCategoryKey,-} from "@/lib/boardCategories";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";--/**- * "What you use Jarvis for" — the honest analogue of a dictation tool's- * "top apps" panel.- * Every one of the six categories is shown (zeros muted at the bottom), each- * with an icon tile, a smooth share bar, and a count + percentage indicator.- */-export function CategoryUsage({ data }: { data: BoardCategories }) {- const t = useT();-- const rows = useMemo(() => {- const counts = new Map(data.categories.map((c) => [c.category, c.count]));- const max = Math.max(1, ...data.categories.map((c) => c.count));- return BOARD_CATEGORY_KEYS.map((key) => {- const count = counts.get(key) ?? 0;- return { key, count, frac: count / max };- }).sort((a, b) => b.count - a.count);- }, [data]);-- if (data.total === 0) {- return (- <p className="text-xs text-muted-foreground">- {t("board_view.categories_empty")}- </p>- );- }-- return (- <div className="flex flex-col justify-center gap-2.5">- {rows.map(({ key, count, frac }) => {- const meta = CATEGORY_META[key as BoardCategoryKey];- const Icon = meta.icon;- const pct = data.total ? Math.round((count / data.total) * 100) : 0;- const empty = count === 0;- return (- <div- key={key}- className={cn("flex items-center gap-3", empty && "opacity-40")}- >- <div- className={cn(- "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",- "bg-sheen/[0.04] ring-1 ring-inset ring-sheen/[0.05]",- )}- >- <Icon className={cn("h-4 w-4", meta.accent)} />- </div>- <div className="min-w-0 flex-1">- <div className="mb-1 flex items-baseline justify-between gap-2">- <span className="truncate text-xs font-medium text-foreground/90">- {t(categoryLabelKey(key))}- </span>- <span className="flex shrink-0 items-baseline gap-1">- <span className="font-display text-sm font-semibold tabular-nums">- {count.toLocaleString()}- </span>- <span className="text-micro text-muted-foreground tabular-nums">- {pct}%- </span>- </span>- </div>- <div className="relative h-1.5 overflow-hidden rounded-full bg-sheen/[0.05]">- <div- className={cn(- "absolute inset-y-0 left-0 rounded-full transition-all duration-700",- meta.bar,- meta.glow,- )}- style={{ width: count > 0 ? `${Math.max(frac * 100, 5)}%` : "0%" }}- />- </div>- </div>- </div>- );- })}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/FriendsList.tsx b/jarvis/ui/web/frontend/src/components/board/FriendsList.tsxdeleted file mode 100644index ef671e8112..0000000000--- a/jarvis/ui/web/frontend/src/components/board/FriendsList.tsx+++ /dev/null@@ -1,124 +0,0 @@-import { useState } from "react";-import { Loader2, Sparkles } from "lucide-react";-import { useFriendsList, useUpdateFriend, type FriendItem } from "@/hooks/useFederation";-import { cn } from "@/lib/utils";-import { useT } from "@/i18n";--const INTERVAL_PRESETS_S = [60, 120, 300, 900];--/**- * Liste aller Friends + Per-Friend-Pull-Interval-Stepper.- *- * Plan §D-Spec: Per-Friend-Sync-Interval-Setting. Der Backend-Constraint- * ist 60..3600 s; wir bieten vier sinnvolle Presets statt freiem Input.- */-export function FriendsList() {- const t = useT();- const friends = useFriendsList();- const update = useUpdateFriend();- const [pendingPubkey, setPendingPubkey] = useState<string | null>(null);-- if (friends.isLoading) {- return <div className="h-12 animate-pulse rounded-md bg-muted/10" />;- }- if (!friends.data) return null;-- if (friends.data.friends.length === 0) {- return (- <div className="rounded-md border border-dashed border-border/60 p-3 text-xs text-muted-foreground">- {t("friends_list.empty")}- </div>- );- }-- return (- <ul className="space-y-2">- {friends.data.friends.map((f) => (- <FriendRow- key={f.pubkey}- item={f}- isPending={pendingPubkey === f.pubkey && update.isPending}- onUpdateInterval={(s) => {- setPendingPubkey(f.pubkey);- update.mutate({ pubkey: f.pubkey, pull_interval_s: s });- }}- />- ))}- </ul>- );-}--function FriendRow({- item, isPending, onUpdateInterval,-}: {- item: FriendItem;- isPending: boolean;- onUpdateInterval: (s: number) => void;-}) {- const t = useT();- return (- <li className="rounded-md border border-border bg-background/40 p-3 text-xs">- <div className="flex items-start gap-3">- <Sparkles className="mt-0.5 h-3.5 w-3.5 text-primary" />- <div className="flex-1 min-w-0">- <div className="flex items-center justify-between gap-2">- <div>- <div className="font-medium">{item.display_name}</div>- <code className="font-mono text-micro text-muted-foreground">- {item.pubkey.slice(0, 16)}…- </code>- </div>- <div className="text-right text-micro text-muted-foreground">- <div>{`${t("friends_list.since")} ${new Date(item.paired_at).toLocaleDateString("de-DE")}`}</div>- {item.last_pull_at && (- <div>{`${t("friends_list.last_pull")} ${timeSince(item.last_pull_at)}`}</div>- )}- </div>- </div>-- <div className="mt-2 flex items-center gap-2">- <span className="text-micro uppercase tracking-wider text-muted-foreground">- {t("friends_list.pull_every")}- </span>- <div className="flex gap-1">- {INTERVAL_PRESETS_S.map((s) => (- <button- key={s}- type="button"- disabled={isPending}- onClick={() => onUpdateInterval(s)}- className={cn(- "rounded-md border px-2 py-0.5 text-micro transition-colors",- item.pull_interval_s === s- ? "border-primary/40 bg-primary/10 text-primary"- : "border-border/60 bg-background/40 text-muted-foreground hover:bg-background/60",- isPending && "opacity-50 cursor-wait",- )}- >- {formatInterval(s)}- </button>- ))}- </div>- {isPending && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />}- </div>- </div>- </div>- </li>- );-}--function formatInterval(seconds: number): string {- if (seconds < 60) return `${seconds}s`;- if (seconds < 3600) return `${Math.round(seconds / 60)}m`;- return `${Math.round(seconds / 3600)}h`;-}--function timeSince(iso: string): string {- const diffMs = Date.now() - new Date(iso).getTime();- const minutes = Math.floor(diffMs / 60000);- if (minutes < 1) return "gerade";- if (minutes < 60) return `vor ${minutes}m`;- const hours = Math.floor(minutes / 60);- if (hours < 24) return `vor ${hours}h`;- return `vor ${Math.floor(hours / 24)}d`;-}diff --git a/jarvis/ui/web/frontend/src/components/board/HeatmapGrid.tsx b/jarvis/ui/web/frontend/src/components/board/HeatmapGrid.tsxdeleted file mode 100644index 6a26bcd77b..0000000000--- a/jarvis/ui/web/frontend/src/components/board/HeatmapGrid.tsx+++ /dev/null@@ -1,158 +0,0 @@-import { useMemo } from "react";-import type { HeatmapCell } from "@/hooks/useBoard";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";--interface HeatmapGridProps {- cells: HeatmapCell[];- weeks?: number;- showLegend?: boolean;-}--const ROWS = 7;--/**- * Activity heatmap in a snake layout (boustrophedon).- * Starts TOP LEFT at the first active cell and alternates- * right and left through the rows going down:- * row 1 (top): left -> right- * row 2: right -> left- * row 3: left -> right- * ...- * Leading zero-activity days (today/yesterday with no activity) are skipped,- * so active cells appear at the start of the snake.- */-export function HeatmapGrid({ cells, weeks = 53, showLegend = true }: HeatmapGridProps) {- const t = useT();- const cols = weeks;-- const byDate = useMemo(() => {- const map = new Map<string, HeatmapCell>();- for (const c of cells) map.set(c.date, c);- return map;- }, [cells]);-- const grid = useMemo(() => {- if (cells.length === 0) return [] as HeatmapCell[][];- const newest = new Date(cells[cells.length - 1].date + "T00:00:00");- const total = ROWS * cols;-- // Chronologically descending: i=0 is today, i=total-1 is the oldest slot.- const sequence: HeatmapCell[] = new Array(total);- for (let i = 0; i < total; i += 1) {- const day = new Date(newest);- day.setDate(newest.getDate() - i);- const iso = day.toISOString().slice(0, 10);- sequence[i] = byDate.get(iso) ?? {- date: iso,- tasks_completed: 0,- tasks_failed: 0,- activity_events: 0,- conversation_hours: 0,- user_words: 0,- jarvis_words: 0,- };- }-- // Skip leading zero-activity days so the snake starts at the first- // active cell instead of at today's empty day.- let startOffset = 0;- while (- startOffset < sequence.length &&- sequence[startOffset].activity_events === 0- ) {- startOffset += 1;- }- if (startOffset >= total) startOffset = 0;-- // Boustrophedon from the TOP: k = row from the top (k=0 topmost row),- // k=0 top left->right, k=1 right->left, k=2 left->right, etc.- const layout: HeatmapCell[][] = Array.from(- { length: ROWS },- () => new Array<HeatmapCell>(cols),- );- for (let i = 0; i < total; i += 1) {- const sourceIdx = i + startOffset;- if (sourceIdx >= sequence.length) break;- const k = Math.floor(i / cols);- if (k >= ROWS) break;- const offset = i % cols;- const cssRow = k;- const col = k % 2 === 0 ? offset : cols - 1 - offset;- layout[cssRow][col] = sequence[sourceIdx];- }- return layout;- }, [cells, byDate, cols]);-- const max = useMemo(- () => Math.max(1, ...cells.map((c) => c.activity_events)),- [cells],- );-- return (- <div className="overflow-x-auto">- <div- className="grid gap-[3px]"- style={{- gridTemplateColumns: `repeat(${cols}, 14px)`,- gridTemplateRows: `repeat(${ROWS}, 14px)`,- }}- >- {grid.flatMap((row, r) =>- row.map((c, ci) => {- if (!c) {- return (- <div- key={`${r}-${ci}`}- className="h-[14px] w-[14px] rounded-[3px] border border-border/20 bg-muted/10"- />- );- }- const intensity = c.activity_events === 0- ? 0- : Math.min(4, Math.ceil((c.activity_events / max) * 4));- return (- <div- key={`${r}-${ci}`}- className={cn(- "h-[14px] w-[14px] rounded-[3px] border border-border/40",- LEVEL[intensity],- )}- title={t("board.heatmap_tooltip").replace("{0}", c.date).replace("{1}", String(c.activity_events)).replace("{2}", String(c.tasks_completed)).replace("{3}", c.conversation_hours.toFixed(1))}- />- );- }),- )}- </div>- {showLegend && <HeatmapLegend className="mt-3" />}- </div>- );-}--export function HeatmapLegend({ className }: { className?: string }) {- return (- <div- className={cn(- "flex items-center gap-2 text-micro uppercase tracking-wider text-muted-foreground",- className,- )}- >- <span>less</span>- {[0, 1, 2, 3, 4].map((lvl) => (- <span- key={lvl}- className={cn("h-[10px] w-[10px] rounded-[2px]", LEVEL[lvl])}- />- ))}- <span>more</span>- </div>- );-}--const LEVEL: Record<number, string> = {- 0: "bg-muted/20",- 1: "bg-primary/25",- 2: "bg-primary/45",- 3: "bg-primary/70",- 4: "bg-foreground/70",-};diff --git a/jarvis/ui/web/frontend/src/components/board/PairDialog.tsx b/jarvis/ui/web/frontend/src/components/board/PairDialog.tsxdeleted file mode 100644index d81b920ab7..0000000000--- a/jarvis/ui/web/frontend/src/components/board/PairDialog.tsx+++ /dev/null@@ -1,163 +0,0 @@-import { useState } from "react";-import { QRCodeSVG } from "qrcode.react";-import { Copy, KeyRound, Loader2, X } from "lucide-react";-import {- usePairAcceptFromFriend,- usePairInitiate,-} from "@/hooks/useFederation";-import { cn } from "@/lib/utils";-import { robustCopy } from "@/lib/clipboard";-import { useT } from "@/i18n";--interface PairDialogProps {- onClose: () => void;-}--/**- * Pair dialog with two modes:- * - "Generate" — owner generates a token, shows URL + QR.- * - "Accept" — friend received the URL, pastes it in.- *- * Modal is non-blocking — closes on backdrop click. Plan §D §0:- * NO pop-up that interrupts feed scrolling; but this modal is- * explicitly opened by the user.- */-export function PairDialog({ onClose }: PairDialogProps) {- const t = useT();- const [mode, setMode] = useState<"generate" | "accept">("generate");- const initiate = usePairInitiate();- const accept = usePairAcceptFromFriend();- const [acceptUrl, setAcceptUrl] = useState("");- const [copied, setCopied] = useState(false);-- return (- <div- className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/50 backdrop-blur-sm"- onClick={onClose}- >- <div- className="w-full max-w-md rounded-lg bg-popover shadow-float p-6"- onClick={(e) => e.stopPropagation()}- >- <header className="mb-4 flex items-center gap-3">- <div className="flex h-8 w-8 items-center justify-center rounded-lg border border-primary/40 bg-primary/10 text-primary">- <KeyRound className="h-4 w-4" />- </div>- <h3 className="font-display text-base font-semibold flex-1">{t("pair_dialog.title")}</h3>- <button type="button" onClick={onClose} aria-label={t("common.close")}- className="text-muted-foreground hover:text-foreground">- <X className="h-4 w-4" />- </button>- </header>-- <div className="mb-4 flex gap-1.5 rounded-md border border-border bg-background/40 p-1">- <button- onClick={() => setMode("generate")}- className={cn(- "flex-1 rounded px-3 py-1.5 text-xs transition-colors",- mode === "generate" ? "bg-primary/15 text-primary" : "text-muted-foreground"- )}- >{t("pair_dialog.mode_invite")}</button>- <button- onClick={() => setMode("accept")}- className={cn(- "flex-1 rounded px-3 py-1.5 text-xs transition-colors",- mode === "accept" ? "bg-primary/15 text-primary" : "text-muted-foreground"- )}- >{t("pair_dialog.mode_follow")}</button>- </div>-- {mode === "generate" && (- <div className="space-y-3">- <p className="text-xs text-muted-foreground">- {t("pair_dialog.generate_hint")}- </p>- <button- type="button"- disabled={initiate.isPending}- onClick={() => initiate.mutate()}- className="inline-flex items-center gap-2 rounded-md border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20"- >- {initiate.isPending && <Loader2 className="h-3 w-3 animate-spin" />}- {t("pair_dialog.generate_button")}- </button>- {initiate.data && (- <div className="space-y-3 rounded-lg border border-border bg-background/40 p-3">- <div className="flex items-center justify-center">- <div className="rounded-md bg-white p-2">- <QRCodeSVG value={initiate.data.url} size={160} level="M" />- </div>- </div>- <div className="flex items-center gap-2 rounded-md border border-border bg-card/50 px-2 py-1.5">- <code className="flex-1 truncate font-mono text-micro text-muted-foreground">- {initiate.data.url}- </code>- <button- type="button"- onClick={() => {- robustCopy(initiate.data!.url)- .then((ok) => {- if (ok) {- setCopied(true);- setTimeout(() => setCopied(false), 1500);- }- })- .catch((err) => {- console.warn("Clipboard write failed:", err);- });- }}- className="inline-flex items-center gap-1 text-micro text-muted-foreground hover:text-foreground"- >- <Copy className="h-3 w-3" />{copied ? t("pair_dialog.copied") : t("pair_dialog.copy")}- </button>- </div>- <div className="text-micro text-muted-foreground">- {`${t("pair_dialog.valid_until")} ${new Date(initiate.data.expires_at).toLocaleString("de-DE")}`}- </div>- </div>- )}- {initiate.isError && (- <div className="text-xs text-destructive">- {`${t("pair_dialog.error_prefix")} ${(initiate.error as Error).message}`}- </div>- )}- </div>- )}-- {mode === "accept" && (- <div className="space-y-3">- <p className="text-xs text-muted-foreground">- {t("pair_dialog.accept_hint")}- </p>- <input- type="url"- value={acceptUrl}- onChange={(e) => setAcceptUrl(e.target.value)}- placeholder="https://board.friend.tld/api/v1/pair/redeem?token=..."- className="w-full rounded-md border border-border bg-background/40 px-3 py-1.5 text-xs"- />- <button- type="button"- disabled={accept.isPending || !acceptUrl}- onClick={() => accept.mutate(acceptUrl)}- className="inline-flex items-center gap-2 rounded-md border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20 disabled:opacity-50"- >- {accept.isPending && <Loader2 className="h-3 w-3 animate-spin" />}- {t("pair_dialog.accept_button")}- </button>- {accept.data && (- <div className="rounded-md border border-muted-foreground/30 bg-muted-foreground/5 p-2 text-xs text-muted-foreground">- {`${t("pair_dialog.paired_with")} ${accept.data.owner_display_name}.`}- </div>- )}- {accept.isError && (- <div className="text-xs text-destructive">- {`${t("pair_dialog.error_prefix")} ${(accept.error as Error).message}`}- </div>- )}- </div>- )}- </div>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/PersonalRecordsList.tsx b/jarvis/ui/web/frontend/src/components/board/PersonalRecordsList.tsxdeleted file mode 100644index c409614e18..0000000000--- a/jarvis/ui/web/frontend/src/components/board/PersonalRecordsList.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { Trophy } from "lucide-react";-import type { PersonalRecord } from "@/hooks/useBoard";-import { useT } from "@/i18n";--interface PersonalRecordsListProps {- records: PersonalRecord[];-}--const KNOWN_METRICS = [- "most_tasks_in_a_day",- "most_unique_tools_in_a_day",- "most_voice_commands_in_a_day",- "most_hours_saved_in_a_day",- "most_active_events_in_a_day",- "most_conversation_hours_in_a_day",-];--export function PersonalRecordsList({ records }: PersonalRecordsListProps) {- const t = useT();- if (records.length === 0) {- return (- <div className="flex h-32 items-center justify-center rounded-lg border border-dashed border-border/60 text-xs text-muted-foreground">- {t("board_view.no_records_yet")}- </div>- );- }-- return (- <ul className="grid gap-3 md:grid-cols-2">- {records.map((rec) => {- const meta = KNOWN_METRICS.includes(rec.metric)- ? {- title: t(`board_view.records.${rec.metric}.title`),- unit: t(`board_view.records.${rec.metric}.unit`),- }- : { title: rec.metric, unit: "" };- const value = Number.isInteger(rec.value)- ? rec.value.toString()- : rec.value.toFixed(1);- return (- <li- key={rec.metric}- className="flex items-start gap-3 rounded-xl border border-border bg-card/30 px-4 py-3 backdrop-blur"- >- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">- <Trophy className="h-4 w-4" />- </div>- <div className="min-w-0 flex-1">- <div className="text-xs uppercase tracking-wider text-muted-foreground">- {meta.title}- </div>- <div className="mt-0.5 font-display text-lg font-semibold">- {value}- {meta.unit && (- <span className="ml-1 text-xs font-normal text-muted-foreground">- {meta.unit}- </span>- )}- </div>- <div className="text-micro text-muted-foreground">- {rec.achieved_on}- </div>- </div>- </li>- );- })}- </ul>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/ReactionBar.tsx b/jarvis/ui/web/frontend/src/components/board/ReactionBar.tsxdeleted file mode 100644index 327d83346b..0000000000--- a/jarvis/ui/web/frontend/src/components/board/ReactionBar.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { Brain, Flame, Rocket } from "lucide-react";-import type { Reaction } from "@/hooks/useFederation";-import { cn } from "@/lib/utils";--interface ReactionBarProps {- counts: Record<string, number> | null;- hasReactions: boolean;- onReact: (r: Reaction) => void;- disabled?: boolean;-}--const ICONS: Record<Reaction, React.ComponentType<{ className?: string }>> = {- rocket: Rocket,- brain: Brain,- fire: Flame,-};--const LABELS: Record<Reaction, string> = {- rocket: "rocket",- brain: "brain",- fire: "fire",-};--export function ReactionBar({ counts, hasReactions, onReact, disabled }: ReactionBarProps) {- const isOwner = counts !== null;- return (- <div className="flex items-center gap-1.5">- {(Object.keys(ICONS) as Reaction[]).map((r) => {- const Icon = ICONS[r];- const cnt = isOwner ? (counts![r] ?? 0) : null;- return (- <button- key={r}- type="button"- disabled={disabled}- onClick={() => onReact(r)}- title={isOwner ? `${LABELS[r]} (${cnt})` : "Click to react"}- className={cn(- "inline-flex items-center gap-1 rounded-md border border-border/70 bg-background/40 px-2 py-1 text-xs transition-colors",- "hover:border-primary/40 hover:bg-background/60",- disabled && "cursor-not-allowed opacity-50",- )}- >- <Icon className="h-3 w-3" />- {isOwner ? <span className="font-mono">{cnt}</span> : null}- </button>- );- })}- {!isOwner && hasReactions && (- <span className="text-micro text-muted-foreground" title="Others reacted">- ·- </span>- )}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/StatsCard.tsx b/jarvis/ui/web/frontend/src/components/board/StatsCard.tsxdeleted file mode 100644index b1b32b3d3b..0000000000--- a/jarvis/ui/web/frontend/src/components/board/StatsCard.tsx+++ /dev/null@@ -1,48 +0,0 @@-import type { ReactNode } from "react";-import { cn } from "@/lib/utils";--interface StatsCardProps {- label: string;- value: string | number;- sublabel?: string;- icon?: ReactNode;- tone?: "default" | "success" | "warn";- className?: string;-}--const TONE: Record<NonNullable<StatsCardProps["tone"]>, string> = {- default: "border-border bg-card/40 text-foreground",- success: "border-muted-foreground/30 bg-muted-foreground/5 text-muted-foreground",- warn: "border-foreground/30 bg-foreground/5 text-foreground",-};--/** Compact large number + label for board metrics. */-export function StatsCard({- label,- value,- sublabel,- icon,- tone = "default",- className,-}: StatsCardProps) {- return (- <div- className={cn(- "flex flex-col gap-2 rounded-xl border px-5 py-4 backdrop-blur",- TONE[tone],- className,- )}- >- <div className="flex items-center gap-2 text-micro uppercase tracking-wider text-muted-foreground">- {icon}- <span>{label}</span>- </div>- <div className="font-display text-3xl leading-none">- {value}- </div>- {sublabel && (- <div className="text-xs text-muted-foreground">{sublabel}</div>- )}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsx b/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsxdeleted file mode 100644index 2ffdfb263e..0000000000--- a/jarvis/ui/web/frontend/src/components/board/StoryComposer.tsx+++ /dev/null@@ -1,123 +0,0 @@-import { useState } from "react";-import { Loader2, Send, X } from "lucide-react";-import { useCreateStory, type Visibility } from "@/hooks/useFederation";-import { cn } from "@/lib/utils";-import { useT } from "@/i18n";--interface StoryComposerProps {- onClose: () => void;-}--const MAX_CHARS = 280;--export function StoryComposer({ onClose }: StoryComposerProps) {- const t = useT();- const [text, setText] = useState("");- const [visibility, setVisibility] = useState<Visibility>("friends");- const create = useCreateStory();-- const remaining = MAX_CHARS - text.length;-- return (- <div- className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/50 backdrop-blur-sm"- onClick={onClose}- >- <div- className="w-full max-w-md rounded-lg bg-popover shadow-float p-5"- onClick={(e) => e.stopPropagation()}- >- <header className="mb-3 flex items-center gap-3">- <h3 className="font-display text-sm font-semibold flex-1">- {t("story_composer.title")}- </h3>- <button type="button" onClick={onClose} aria-label={t("story_composer.close")}- className="text-muted-foreground hover:text-foreground">- <X className="h-4 w-4" />- </button>- </header>-- <textarea- value={text}- onChange={(e) => setText(e.target.value.slice(0, MAX_CHARS))}- rows={4}- placeholder={t("story_composer.placeholder")}- className="w-full resize-none rounded-md border border-border bg-background/40 px-3 py-2 text-sm"- />- <div className="mt-1 flex items-center justify-between text-micro text-muted-foreground">- <span>{t("story_composer.expiry_hint")}</span>- <span className={cn(remaining < 30 && "text-foreground")}>- {`${remaining} ${t("story_composer.characters")}`}- </span>- </div>-- <div className="mt-3">- <VisibilityRadios value={visibility} onChange={setVisibility} />- </div>-- <div className="mt-4 flex justify-end gap-2">- <button- onClick={onClose}- className="rounded-md px-3 py-1.5 text-xs text-muted-foreground hover:text-foreground"- >{t("common.cancel")}</button>- <button- type="button"- disabled={create.isPending || text.trim().length === 0}- onClick={() =>- create.mutate(- { text: text.trim(), visibility },- { onSuccess: onClose },- )- }- className="inline-flex items-center gap-2 rounded-md border border-primary/40 bg-primary/10 px-3 py-1.5 text-xs font-medium text-primary hover:bg-primary/20 disabled:opacity-50"- >- {create.isPending ? <Loader2 className="h-3 w-3 animate-spin" /> : <Send className="h-3 w-3" />}- {t("story_composer.post")}- </button>- </div>- {create.isError && (- <div className="mt-2 text-xs text-destructive">- {`${t("story_composer.error_prefix")} ${(create.error as Error).message}`}- </div>- )}- </div>- </div>- );-}--export function VisibilityRadios({- value, onChange,-}: { value: Visibility; onChange: (v: Visibility) => void }) {- const t = useT();- const opts: { v: Visibility; label: string; hint: string }[] = [- { v: "private", label: t("story_composer.visibility_private"), hint: t("story_composer.visibility_private_hint") },- { v: "friends", label: t("story_composer.visibility_friends"), hint: t("story_composer.visibility_friends_hint") },- { v: "public", label: t("story_composer.visibility_public"), hint: t("story_composer.visibility_public_hint") },- ];- return (- <div className="grid grid-cols-3 gap-1.5">- {opts.map((o) => (- <label- key={o.v}- className={cn(- "flex cursor-pointer flex-col gap-0.5 rounded-md border px-2.5 py-2 text-xs transition-colors",- value === o.v- ? "border-primary/40 bg-primary/10 text-primary"- : "border-border/60 bg-background/40 text-muted-foreground hover:bg-background/60",- )}- >- <input- type="radio"- name="visibility"- value={o.v}- checked={value === o.v}- onChange={() => onChange(o.v)}- className="sr-only"- />- <span className="font-medium">{o.label}</span>- <span className="text-micro opacity-70">{o.hint}</span>- </label>- ))}- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/ToolBarChart.tsx b/jarvis/ui/web/frontend/src/components/board/ToolBarChart.tsxdeleted file mode 100644index 787c0f5ed9..0000000000--- a/jarvis/ui/web/frontend/src/components/board/ToolBarChart.tsx+++ /dev/null@@ -1,96 +0,0 @@-import {- Bar,- BarChart,- CartesianGrid,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from "recharts";-import type { ToolHistogramEntry } from "@/hooks/useBoard";-import { useT } from "@/i18n";--interface ToolBarChartProps {- histogram: ToolHistogramEntry[];- limit?: number;-}--/**- * Horizontal bar chart of the most-used tools. Takes the top N and- * sorts descending. "Days used" = number of distinct days on which- * the tool was invoked successfully at least once (NOT per- * invocation — that would skew power tools like ``bash``).- */-export function ToolBarChart({ histogram, limit = 15 }: ToolBarChartProps) {- const t = useT();- const data = histogram.slice(0, limit).map((entry) => ({- tool: entry.tool,- days: entry.days_used,- }));-- if (data.length === 0) {- return (- <div className="flex h-48 items-center justify-center rounded-lg border border-dashed border-border/60 text-xs text-muted-foreground">- {t("board_view.tools_chart_empty")}- </div>- );- }-- const height = Math.max(180, data.length * 28);-- return (- <div style={{ width: "100%", height }}>- <ResponsiveContainer- minWidth={0}- initialDimension={{ width: 640, height }}- >- <BarChart- data={data}- layout="vertical"- margin={{ top: 8, right: 24, bottom: 4, left: 8 }}- >- <CartesianGrid- strokeDasharray="3 3"- stroke="hsl(var(--border))"- horizontal={false}- />- <XAxis- type="number"- allowDecimals={false}- stroke="hsl(var(--muted-foreground))"- fontSize={11}- />- <YAxis- type="category"- dataKey="tool"- width={120}- stroke="hsl(var(--muted-foreground))"- fontSize={11}- />- <Tooltip- cursor={{ fill: "hsl(var(--muted) / 0.2)" }}- contentStyle={{- background: "hsl(var(--card))",- border: "1px solid hsl(var(--border))",- borderRadius: 6,- fontSize: 12,- }}- labelStyle={{ color: "hsl(var(--foreground))" }}- formatter={(value) => {- const n = typeof value === "number" ? value : Number(value) || 0;- const days = n === 1- ? t("board_view.tools_chart_days_used_one").replace("{0}", String(n))- : t("board_view.tools_chart_days_used").replace("{0}", String(n));- return [days, t("board_view.tools_chart_used_label")];- }}- />- <Bar- dataKey="days"- fill="hsl(var(--primary))"- radius={[0, 4, 4, 0]}- />- </BarChart>- </ResponsiveContainer>- </div>- );-}diff --git a/jarvis/ui/web/frontend/src/components/board/WordsTrendChart.tsx b/jarvis/ui/web/frontend/src/components/board/WordsTrendChart.tsxdeleted file mode 100644index 826a3d0fa0..0000000000--- a/jarvis/ui/web/frontend/src/components/board/WordsTrendChart.tsx+++ /dev/null@@ -1,163 +0,0 @@-import { useMemo } from "react";-import {- Area,- AreaChart,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from "recharts";-import type { HeatmapCell } from "@/hooks/useBoard";-import { useT } from "@/i18n";--export const TREND_YOU = "hsl(var(--primary))"; // signal yellow (primary)-export const TREND_JARVIS = "hsl(199 90% 64%)"; // soft sky--interface WordsTrendChartProps {- cells: HeatmapCell[];- days?: number;-}--interface Point {- date: string;- you: number;- jarvis: number;-}--/**- * Area chart of words per day — "you said" vs "Jarvis said" — over the recent- * window. Two stacked gradient fills with hairline strokes; axis and grid are- * stripped to near-nothing so the data shape carries the visual, not chrome.- */-export function WordsTrendChart({ cells, days = 45 }: WordsTrendChartProps) {- const t = useT();-- const data: Point[] = useMemo(- () =>- cells.slice(-days).map((c) => ({- date: c.date,- you: c.user_words,- jarvis: c.jarvis_words,- })),- [cells, days],- );-- const hasData = data.some((d) => d.you > 0 || d.jarvis > 0);- if (!hasData) {- return (- <div className="flex h-full items-center justify-center text-xs text-muted-foreground">- {t("board_view.chart_empty")}- </div>- );- }-- return (- // minHeight guards the Recharts width/height(-1) initial-measure race in a- // grid/flex parent: without a positive floor the first measure is 0×0, the- // Area paths bake in a collapsed scale, and the ResizeObserver re-measure- // recovers the axes but not the (animated) fills — leaving an empty chart.- <ResponsiveContainer- width="100%"- height="100%"- minHeight={176}- minWidth={0}- initialDimension={{ width: 640, height: 176 }}- >- <AreaChart data={data} margin={{ top: 6, right: 2, bottom: 0, left: 2 }}>- <defs>- <linearGradient id="board-grad-you" x1="0" y1="0" x2="0" y2="1">- <stop offset="0%" stopColor={TREND_YOU} stopOpacity={0.42} />- <stop offset="100%" stopColor={TREND_YOU} stopOpacity={0.02} />- </linearGradient>- <linearGradient id="board-grad-jarvis" x1="0" y1="0" x2="0" y2="1">- <stop offset="0%" stopColor={TREND_JARVIS} stopOpacity={0.28} />- <stop offset="100%" stopColor={TREND_JARVIS} stopOpacity={0.02} />- </linearGradient>- </defs>- <XAxis- dataKey="date"- tickFormatter={fmtTick}- tick={{ fill: "hsl(0 0% 50%)", fontSize: 10 }}- axisLine={false}- tickLine={false}- minTickGap={44}- dy={4}- />- <YAxis hide domain={[0, "dataMax"]} />- <Tooltip- content={<TrendTooltip t={t} />}- cursor={{ stroke: "hsl(0 0% 32%)", strokeDasharray: "3 3" }}- />- <Area- type="monotone"- dataKey="jarvis"- stroke={TREND_JARVIS}- strokeWidth={1.5}- fill="url(#board-grad-jarvis)"- activeDot={{ r: 3, strokeWidth: 0 }}- isAnimationActive={false}- />- <Area- type="monotone"- dataKey="you"- stroke={TREND_YOU}- strokeWidth={1.75}- fill="url(#board-grad-you)"- activeDot={{ r: 3, strokeWidth: 0 }}- isAnimationActive={false}- />- </AreaChart>- </ResponsiveContainer>- );-}--interface TooltipPayloadItem {- dataKey: string;- value: number;-}--function TrendTooltip(props: {- active?: boolean;- payload?: TooltipPayloadItem[];- label?: string;- t: (k: string) => string;-}) {- const { active, payload, label, t } = props;- if (!active || !payload || payload.length === 0) return null;- const you = payload.find((p) => p.dataKey === "you")?.value ?? 0;- const jarvis = payload.find((p) => p.dataKey === "jarvis")?.value ?? 0;- return (- <div className="rounded-lg border border-sheen/10 bg-[#0c0c0c]/95 px-3 py-2 text-xs backdrop-blur">- <div className="mb-1.5 font-medium text-foreground">{fmtFull(label)}</div>- <Row color={TREND_YOU} label={t("board_view.hero.you_spoke")} value={you} />- <Row color={TREND_JARVIS} label={t("board_view.hero.jarvis_spoke")} value={jarvis} />- </div>- );-}--function Row({ color, label, value }: { color: string; label: string; value: number }) {- return (- <div className="flex items-center gap-2">- <span className="h-2 w-2 rounded-full" style={{ background: color }} />- <span className="text-muted-foreground">{label}</span>- <span className="ml-auto font-semibold tabular-nums">{value.toLocaleString()}</span>- </div>- );-}--function fmtTick(iso: string): string {- const d = new Date(iso + "T00:00:00");- if (Number.isNaN(d.getTime())) return iso;- return d.toLocaleDateString(undefined, { day: "numeric", month: "short" });-}--function fmtFull(iso?: string): string {- if (!iso) return "";- const d = new Date(iso + "T00:00:00");- if (Number.isNaN(d.getTime())) return iso;- return d.toLocaleDateString(undefined, {- weekday: "short",- day: "numeric",- month: "short",- });-}diff --git a/jarvis/ui/web/frontend/src/components/board/insights/AgentsTab.tsx b/jarvis/ui/web/frontend/src/components/board/insights/AgentsTab.tsxnew file mode 100644index 0000000000..d041b45f31--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/board/insights/AgentsTab.tsx@@ -0,0 +1,222 @@+import { useState } from "react";++import type { BoardInsights, InsightsAgent } from "@/hooks/useBoardInsights";+import { agentLabel, chatProviderLabel, compactNumber, formatDay, plural } from "@/lib/boardInsights";+import {+ BOARD_CATEGORY_KEYS,+ CATEGORY_META,+ categoryLabelKey,+ type BoardCategoryKey,+} from "@/lib/boardCategories";+import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { TabBar } from "@/components/layout/SectionTabBar";+import {+ BigNumber,+ CardTitleRow,+ Eyebrow,+ InsightCard,+} from "@/components/board/insights/primitives";+import { useT, useUiLanguage } from "@/i18n";+import { cn } from "@/lib/utils";++type Range = "30d" | "all";++export function AgentsTab({ data }: { data: BoardInsights }) {+ const t = useT();+ const lang = useUiLanguage();+ const best = data.records.best_agent_day;+ const sessions30 = data.agents.items.reduce((s, a) => s + a.sessions_30d, 0);+ return (+ <div className="flex flex-col gap-4">+ <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">+ <StatCard label={t("board_insights.agents.stat_sessions")} value={data.agents.sessions.toLocaleString()} />+ <StatCard label={t("board_insights.agents.stat_sessions_30d")} value={sessions30.toLocaleString()} />+ <StatCard label={t("board_insights.agents.stat_tokens")} value={compactNumber(data.agents.tokens)} />+ <StatCard+ label={t("board_insights.agents.stat_busiest")}+ value={best ? best.value.toLocaleString() : "—"}+ sub={best ? formatDay(best.date, lang) : undefined}+ />+ </div>+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1.5fr)_minmax(0,1fr)]">+ <CodingAgentsCard data={data} />+ <div className="flex min-w-0 flex-col gap-4">+ <ChatsCard data={data} />+ <CategoriesCard data={data} />+ </div>+ </div>+ </div>+ );+}++function StatCard({ label, value, sub }: { label: string; value: string; sub?: string }) {+ return (+ <InsightCard>+ <BigNumber>{value}</BigNumber>+ <div className="mt-2">+ <Eyebrow>{label}</Eyebrow>+ </div>+ {sub && <div className="mt-1 text-sm text-muted-foreground">{sub}</div>}+ </InsightCard>+ );+}++function CodingAgentsCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const lang = useUiLanguage();+ const [range, setRange] = useState<Range>("30d");+ const sessionsOf = (a: InsightsAgent) => (range === "30d" ? a.sessions_30d : a.sessions);+ const turnsOf = (a: InsightsAgent) => (range === "30d" ? a.turns_30d : a.turns);+ const rows = [...data.agents.items].sort((a, b) => sessionsOf(b) - sessionsOf(a));+ const total = rows.reduce((s, a) => s + sessionsOf(a), 0);+ const max = Math.max(1, ...rows.map(sessionsOf));+ const relative = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });++ return (+ <InsightCard testId="board-coding-agents">+ <CardTitleRow+ title={t("board_insights.agents.title")}+ fact={plural(t, "board_insights.agents.used", rows.filter((a) => sessionsOf(a) > 0).length)}+ >+ <p className="mt-1 text-sm text-muted-foreground">{t("board_insights.agents.subtitle")}</p>+ </CardTitleRow>+ <TabBar+ className="mb-2"+ tabs={[+ { id: "30d", label: t("board_insights.agents.range_30d") },+ { id: "all", label: t("board_insights.agents.range_all") },+ ]}+ active={range}+ onChange={(id) => setRange(id as Range)}+ />+ {rows.length === 0 ? (+ <p className="py-6 text-sm text-muted-foreground">{t("board_insights.agents.empty")}</p>+ ) : (+ <table className="w-full table-fixed text-sm">+ <thead>+ <tr className="text-left text-xs uppercase tracking-[0.06em] text-muted-foreground">+ <th className="py-2 font-medium">{t("board_insights.agents.col_agent")}</th>+ <th className="w-[32%] py-2 font-medium">{t("board_insights.agents.col_share")}</th>+ <th className="w-[13%] py-2 text-right font-medium">{t("board_insights.agents.col_sessions")}</th>+ <th className="w-[13%] py-2 text-right font-medium">{t("board_insights.agents.col_turns")}</th>+ <th className="hidden w-[17%] py-2 text-right font-medium md:table-cell">+ {t("board_insights.agents.col_last")}+ </th>+ </tr>+ </thead>+ <tbody>+ {rows.map((agent) => {+ const sessions = sessionsOf(agent);+ const pct = total ? Math.round((sessions / total) * 100) : 0;+ return (+ <tr key={agent.agent} className={cn("border-t border-border", sessions === 0 && "opacity-50")}>+ <td className="py-2.5">+ <div className="flex min-w-0 items-center gap-2.5">+ <ProviderLogo providerId={agent.agent} label={agentLabel(agent.agent)} />+ <span className="truncate font-medium text-foreground-strong">{agentLabel(agent.agent)}</span>+ </div>+ </td>+ <td className="py-2.5 pr-3">+ <div className="flex items-center gap-2">+ <div className="h-2 flex-1 overflow-hidden rounded-full bg-sheen/[0.06]">+ <div+ className="h-full rounded-full bg-accent"+ style={{ width: sessions > 0 ? `${Math.max((sessions / max) * 100, 3)}%` : "0%" }}+ />+ </div>+ <span className="w-9 text-right text-xs tabular-nums text-muted-foreground">{pct}%</span>+ </div>+ </td>+ <td className="py-2.5 text-right tabular-nums text-foreground-strong">{sessions.toLocaleString()}</td>+ <td className="py-2.5 text-right tabular-nums text-muted-foreground">+ {compactNumber(turnsOf(agent))}+ </td>+ <td className="hidden py-2.5 text-right text-muted-foreground md:table-cell">+ {agent.last_ms ? relativeDays(agent.last_ms, relative) : "—"}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ </InsightCard>+ );+}++function ChatsCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const rows = data.chats.providers.slice(0, 6);+ const max = Math.max(1, ...rows.map((r) => r.messages));+ return (+ <InsightCard testId="board-chats">+ <CardTitleRow+ title={t("board_insights.chats.title")}+ fact={plural(t, "board_insights.chats.messages", data.chats.messages)}+ />+ {rows.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t("board_insights.chats.empty")}</p>+ ) : (+ <ul className="flex flex-col gap-2.5">+ {rows.map((row) => (+ <li key={row.provider} className="flex items-center gap-2.5 text-sm">+ <ProviderLogo providerId={row.provider} label={chatProviderLabel(row.provider)} size="sm" />+ <span className="w-24 shrink-0 truncate text-foreground">{chatProviderLabel(row.provider)}</span>+ <div className="h-2 flex-1 overflow-hidden rounded-full bg-sheen/[0.06]">+ <div+ className="h-full rounded-full bg-accent/70"+ style={{ width: row.messages > 0 ? `${Math.max((row.messages / max) * 100, 3)}%` : "0%" }}+ />+ </div>+ <span className="w-10 text-right tabular-nums text-foreground-strong">{row.messages.toLocaleString()}</span>+ </li>+ ))}+ </ul>+ )}+ </InsightCard>+ );+}++function CategoriesCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const counts = new Map(data.categories.categories.map((c) => [c.category, c.count]));+ const total = data.categories.total;+ const rows = BOARD_CATEGORY_KEYS.map((key) => ({ key, count: counts.get(key) ?? 0 }))+ .filter((r) => r.count > 0)+ .sort((a, b) => b.count - a.count);+ return (+ <InsightCard testId="board-categories">+ <CardTitleRow title={t("board_insights.categories.title")}>+ <p className="mt-1 text-sm text-muted-foreground">{t("board_insights.categories.subtitle")}</p>+ </CardTitleRow>+ {rows.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t("board_insights.categories.empty")}</p>+ ) : (+ <ul className="flex flex-col gap-2">+ {rows.map(({ key, count }) => {+ const Icon = CATEGORY_META[key as BoardCategoryKey].icon;+ const pct = total ? Math.round((count / total) * 100) : 0;+ return (+ <li key={key} className="flex items-center gap-2.5 text-sm">+ <Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />+ <span className="flex-1 truncate text-foreground">{t(categoryLabelKey(key))}</span>+ <span className="tabular-nums text-muted-foreground">{count.toLocaleString()}</span>+ <span className="w-10 text-right text-xs tabular-nums text-foreground-strong">{pct}%</span>+ </li>+ );+ })}+ </ul>+ )}+ </InsightCard>+ );+}++function relativeDays(ms: number, fmt: Intl.RelativeTimeFormat): string {+ const startOfToday = new Date();+ startOfToday.setHours(0, 0, 0, 0);+ const then = new Date(ms);+ then.setHours(0, 0, 0, 0);+ const days = Math.round((then.getTime() - startOfToday.getTime()) / 86_400_000);+ return fmt.format(days, "day");+}+diff --git a/jarvis/ui/web/frontend/src/components/board/insights/RhythmTab.tsx b/jarvis/ui/web/frontend/src/components/board/insights/RhythmTab.tsxnew file mode 100644index 0000000000..843b638bd0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/board/insights/RhythmTab.tsx@@ -0,0 +1,280 @@+import { useMemo } from "react";+import { Award, Bot, CalendarDays, Flame, type LucideIcon } from "lucide-react";++import type { BoardInsights } from "@/hooks/useBoardInsights";+import {+ formatDay,+ hourTotals,+ intensityLevels,+ milestoneProgress,+ peakSlot,+ plural,+ weekdayTotals,+ weeklyTotals,+ wordsOf,+} from "@/lib/boardInsights";+import { QuickTooltip } from "@/components/ui/tooltip";+import {+ CardTitleRow,+ HEAT_LEVEL_CLASS,+ InsightCard,+} from "@/components/board/insights/primitives";+import { useT, useUiLanguage } from "@/i18n";+import { cn } from "@/lib/utils";++const WEEKS_SHOWN = 26;++export function RhythmTab({ data }: { data: BoardInsights }) {+ return (+ <div className="flex flex-col gap-4">+ <PunchCard data={data} />+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">+ <WeeklyVolumeCard data={data} />+ <RecordsCard data={data} />+ </div>+ </div>+ );+}++function useWeekdayNames(style: "short" | "long") {+ const lang = useUiLanguage();+ return useMemo(() => {+ const fmt = new Intl.DateTimeFormat(lang, { weekday: style });+ return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2024, 0, 1 + i)));+ }, [lang, style]);+}++function hourLabel(hour: number, lang: string): string {+ return new Date(2024, 0, 1, hour).toLocaleTimeString(lang, { hour: "numeric" });+}++function PunchCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const lang = useUiLanguage();+ const shortDays = useWeekdayNames("short");+ const longDays = useWeekdayNames("long");+ const punch = data.punch_card;+ const level = useMemo(() => intensityLevels(punch.flat()), [punch]);+ const peak = peakSlot(punch);+ const hours = hourTotals(punch);+ const maxHour = Math.max(1, ...hours);+ const weekdays = weekdayTotals(punch);+ const topDay = weekdays.indexOf(Math.max(...weekdays));++ return (+ <InsightCard testId="board-punch-card">+ <CardTitleRow+ title={t("board_insights.rhythm.title")}+ fact={+ peak+ ? t("board_insights.rhythm.peak")+ .replace("{0}", longDays[peak.weekday])+ .replace("{1}", hourLabel(peak.hour, lang))+ : undefined+ }+ >+ <p className="mt-1 text-sm text-muted-foreground">{t("board_insights.rhythm.subtitle")}</p>+ </CardTitleRow>+ {!peak ? (+ <p className="py-6 text-sm text-muted-foreground">{t("board_insights.rhythm.empty")}</p>+ ) : (+ <div className="overflow-x-auto">+ <div+ className="grid min-w-[640px] items-center gap-1"+ style={{ gridTemplateColumns: "3rem repeat(24, minmax(0, 1fr)) 4.5rem" }}+ >+ {punch.map((row, weekday) => (+ <PunchRow+ key={weekday}+ label={shortDays[weekday]}+ values={row}+ level={level}+ total={weekdays[weekday]}+ highlight={weekday === topDay}+ describe={(hour, value) =>+ `${longDays[weekday]}, ${hourLabel(hour, lang)} — ${value.toLocaleString()}`+ }+ />+ ))}+ <span />+ {hours.map((value, hour) => (+ <div key={hour} className="flex h-12 items-end" aria-hidden>+ <div+ className="w-full rounded-t-[3px] bg-accent/60"+ style={{ height: `${Math.max((value / maxHour) * 100, value > 0 ? 4 : 0)}%` }}+ />+ </div>+ ))}+ <span />+ <span />+ {hours.map((_, hour) => (+ <span key={hour} className="text-center text-xs tabular-nums text-muted-foreground">+ {hour % 3 === 0 ? String(hour).padStart(2, "0") : ""}+ </span>+ ))}+ <span />+ </div>+ </div>+ )}+ </InsightCard>+ );+}++function PunchRow({+ label,+ values,+ level,+ total,+ highlight,+ describe,+}: {+ label: string;+ values: number[];+ level: (v: number) => 0 | 1 | 2 | 3 | 4;+ total: number;+ highlight: boolean;+ describe: (hour: number, value: number) => string;+}) {+ return (+ <>+ <span className={cn("text-xs", highlight ? "font-semibold text-foreground-strong" : "text-muted-foreground")}>+ {label}+ </span>+ {values.map((value, hour) => (+ <QuickTooltip key={hour} content={describe(hour, value)} side="top" className="block">+ <span className={cn("block h-6 w-full rounded-[4px]", HEAT_LEVEL_CLASS[level(value)])} />+ </QuickTooltip>+ ))}+ <span className="text-right text-xs tabular-nums text-muted-foreground">{total.toLocaleString()}</span>+ </>+ );+}++function WeeklyVolumeCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const lang = useUiLanguage();+ const weeks = weeklyTotals(data.days, WEEKS_SHOWN, 8);+ const max = Math.max(1, ...weeks.map((w) => w.words));+ const best = weeks.reduce((b, w) => (w.words > b ? w.words : b), 0);+ const monthFmt = new Intl.DateTimeFormat(lang, { month: "short" });++ return (+ <InsightCard testId="board-weekly-volume">+ <CardTitleRow+ title={t("board_insights.weekly.title")}+ fact={best > 0 ? t("board_insights.weekly.best").replace("{0}", best.toLocaleString()) : undefined}+ >+ <p className="mt-1 text-sm text-muted-foreground">{t("board_insights.weekly.subtitle")}</p>+ </CardTitleRow>+ <div className="flex h-44 items-end gap-1">+ {weeks.map((week, i) => {+ const date = week.start ? new Date(`${week.start}T00:00:00`) : null;+ const tip = `${week.start ? formatDay(week.start, lang) : ""} — ${t("board_insights.weekly.tooltip")+ .replace("{0}", week.words.toLocaleString())+ .replace("{1}", week.agentSessions.toLocaleString())}`;+ return (+ <QuickTooltip key={i} content={tip} side="top" className="flex h-full flex-1 flex-col justify-end">+ <div+ className={cn(+ "w-full rounded-t-[4px]",+ i === weeks.length - 1 ? "bg-accent/45" : "bg-accent",+ )}+ style={{ height: `${Math.max((week.words / max) * 100, week.words > 0 ? 2 : 0)}%` }}+ />+ <span className="mt-1.5 h-4 text-center text-xs text-muted-foreground">+ {date && date.getDate() <= 7 ? monthFmt.format(date) : ""}+ </span>+ </QuickTooltip>+ );+ })}+ </div>+ </InsightCard>+ );+}++function RecordsCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const lang = useUiLanguage();+ const totalWords = data.dictation.words + data.voice.user_words;+ const { previous, next } = milestoneProgress(totalWords);+ const progress = next > previous ? (totalWords - previous) / (next - previous) : 0;+ const bestWords = data.records.best_words_day;+ const bestAgents = data.records.best_agent_day;+ const todayWords = data.days.length ? wordsOf(data.days[data.days.length - 1]) : 0;++ return (+ <InsightCard testId="board-records">+ <CardTitleRow title={t("board_insights.records.title")} />+ <ul className="flex flex-col divide-y divide-border">+ <RecordRow+ icon={Award}+ label={t("board_insights.records.best_words")}+ value={bestWords ? bestWords.value.toLocaleString() : "—"}+ sub={bestWords ? formatDay(bestWords.date, lang) : undefined}+ />+ <RecordRow+ icon={Bot}+ label={t("board_insights.records.best_agents")}+ value={bestAgents ? bestAgents.value.toLocaleString() : "—"}+ sub={bestAgents ? formatDay(bestAgents.date, lang) : undefined}+ />+ <RecordRow+ icon={Flame}+ label={t("board_insights.records.longest_streak")}+ value={plural(t, "board_insights.records.days", data.streak.longest_days)}+ />+ <RecordRow+ icon={CalendarDays}+ label={t("board_insights.records.active_days")}+ value={data.streak.active_days.toLocaleString()}+ sub={+ data.streak.first_day+ ? t("board_insights.records.since").replace("{0}", formatDay(data.streak.first_day, lang))+ : undefined+ }+ />+ </ul>+ <div className="mt-auto pt-5">+ <div className="mb-2 flex items-baseline justify-between gap-3 text-sm">+ <span className="font-medium text-foreground-strong">+ {t("board_insights.records.next_milestone").replace("{0}", next.toLocaleString())}+ </span>+ <span className="tabular-nums text-muted-foreground">+ {t("board_insights.records.to_go").replace("{0}", Math.max(0, next - totalWords).toLocaleString())}+ </span>+ </div>+ <div className="h-2 overflow-hidden rounded-full bg-sheen/[0.06]">+ <div className="h-full rounded-full bg-accent" style={{ width: `${Math.min(100, progress * 100)}%` }} />+ </div>+ {todayWords > 0 && (+ <p className="mt-2 text-xs text-muted-foreground">+ {t("board_insights.records.today").replace("{0}", todayWords.toLocaleString())}+ </p>+ )}+ </div>+ </InsightCard>+ );+}++function RecordRow({+ icon: Icon,+ label,+ value,+ sub,+}: {+ icon: LucideIcon;+ label: string;+ value: string;+ sub?: string;+}) {+ return (+ <li className="flex items-center gap-3 py-2.5">+ <Icon className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm text-foreground">{label}</div>+ {sub && <div className="truncate text-xs text-muted-foreground">{sub}</div>}+ </div>+ <span className="shrink-0 text-base font-semibold tabular-nums text-foreground-strong">{value}</span>+ </li>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/board/insights/SpeedGauge.tsx b/jarvis/ui/web/frontend/src/components/board/insights/SpeedGauge.tsxnew file mode 100644index 0000000000..421f776a66--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/board/insights/SpeedGauge.tsx@@ -0,0 +1,67 @@+/**+ * Half-ring gauge for speaking speed. The ring runs from 0 to a scale that+ * always leaves room above the value; a tick marks the typing reference so the+ * comparison is drawn, not only written.+ */+export function SpeedGauge({+ wpm,+ typingWpm,+ centerTop,+ centerBottom,+}: {+ wpm: number;+ typingWpm: number;+ centerTop: string;+ centerBottom: string;+}) {+ const scale = Math.max(200, Math.ceil((wpm * 1.15) / 50) * 50);+ const r = 70;+ const cx = 90;+ const cy = 86;+ const point = (fraction: number, radius = r) => {+ const angle = Math.PI * (1 - Math.min(1, Math.max(0, fraction)));+ return { x: cx + radius * Math.cos(angle), y: cy - radius * Math.sin(angle) };+ };+ const arc = (fraction: number) => {+ const end = point(fraction);+ return `M ${cx - r} ${cy} A ${r} ${r} 0 0 1 ${end.x.toFixed(2)} ${end.y.toFixed(2)}`;+ };+ const tickInner = point(typingWpm / scale, r - 13);+ const tickOuter = point(typingWpm / scale, r + 13);++ return (+ <svg viewBox="0 0 180 100" className="w-full max-w-[240px]" role="img" aria-label={`${centerTop} ${centerBottom}`}>+ <path+ d={arc(1)}+ fill="none"+ stroke="rgb(var(--sheen-rgb) / 0.08)"+ strokeWidth={16}+ strokeLinecap="round"+ />+ {wpm > 0 && (+ <path+ d={arc(wpm / scale)}+ fill="none"+ stroke="hsl(var(--accent))"+ strokeWidth={16}+ strokeLinecap="round"+ />+ )}+ <line+ x1={tickInner.x}+ y1={tickInner.y}+ x2={tickOuter.x}+ y2={tickOuter.y}+ stroke="hsl(var(--foreground))"+ strokeOpacity={0.55}+ strokeWidth={1.5}+ />+ <text x={cx} y={cy - 18} textAnchor="middle" className="fill-foreground-strong" fontSize={20} fontWeight={600}>+ {centerTop}+ </text>+ <text x={cx} y={cy - 2} textAnchor="middle" className="fill-muted-foreground" fontSize={10}>+ {centerBottom}+ </text>+ </svg>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/board/insights/StreakCalendar.tsx b/jarvis/ui/web/frontend/src/components/board/insights/StreakCalendar.tsxnew file mode 100644index 0000000000..ec8d458a9a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/board/insights/StreakCalendar.tsx@@ -0,0 +1,145 @@+import { useMemo, useState } from "react";+import { ChevronLeft, ChevronRight } from "lucide-react";++import type { InsightsDay } from "@/hooks/useBoardInsights";+import { actionsOf, calendarWeeks, intensityLevels, wordsOf } from "@/lib/boardInsights";+import { QuickTooltip } from "@/components/ui/tooltip";+import { HEAT_LEVEL_CLASS } from "@/components/board/insights/primitives";+import { useT, useUiLanguage } from "@/i18n";+import { cn } from "@/lib/utils";++/** Weeks shown at once; the arrows page through the rest of the year. */+const PAGE_WEEKS = 22;++/**+ * Weekday rows x week columns, one square per day, shaded by how many things+ * the user started that day. Pages back through the 53-week series.+ */+export function StreakCalendar({ days }: { days: readonly InsightsDay[] }) {+ const t = useT();+ const lang = useUiLanguage();+ const weeks = useMemo(() => calendarWeeks(days), [days]);+ const level = useMemo(() => intensityLevels(days.map(actionsOf)), [days]);+ const lastStart = Math.max(0, weeks.length - PAGE_WEEKS);+ const [start, setStart] = useState(lastStart);+ const page = weeks.slice(start, start + PAGE_WEEKS);+ const today = days[days.length - 1]?.date;++ const monthName = useMemo(() => {+ const fmt = new Intl.DateTimeFormat(lang, { month: "short" });+ return (m: number) => fmt.format(new Date(2024, m, 1));+ }, [lang]);+ const weekdayNames = useMemo(() => {+ const fmt = new Intl.DateTimeFormat(lang, { weekday: "short" });+ // 2024-01-01 was a Monday.+ return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2024, 0, 1 + i)));+ }, [lang]);+ const dayLabel = useMemo(() => {+ const fmt = new Intl.DateTimeFormat(lang, { weekday: "short", day: "numeric", month: "short" });+ return (iso: string) => fmt.format(new Date(`${iso}T00:00:00`));+ }, [lang]);++ const describe = (day: InsightsDay) => {+ const actions = actionsOf(day);+ if (actions === 0 && day.agent_turns === 0) {+ return `${dayLabel(day.date)} — ${t("board_insights.calendar.nothing")}`;+ }+ const parts = [+ t("board_insights.calendar.started").replace("{0}", actions.toLocaleString()),+ ];+ const words = wordsOf(day);+ if (words > 0) {+ parts.push(t("board_insights.calendar.words").replace("{0}", words.toLocaleString()));+ }+ return `${dayLabel(day.date)} — ${parts.join(" · ")}`;+ };++ const navButton =+ "flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sheen/[0.06] hover:text-foreground disabled:pointer-events-none disabled:opacity-30";++ return (+ <div className="flex min-w-0 flex-col gap-3" data-testid="board-streak-calendar">+ <div className="grid items-center gap-1" style={{ gridTemplateColumns: `2.25rem repeat(${PAGE_WEEKS}, minmax(0, 1fr))` }}>+ <button+ type="button"+ className={navButton}+ onClick={() => setStart((s) => Math.max(0, s - PAGE_WEEKS))}+ disabled={start === 0}+ aria-label={t("board_insights.calendar.older")}+ >+ <ChevronLeft className="h-4 w-4" />+ </button>+ {page.map((week, i) => (+ <div key={i} className="relative h-4 text-xs text-muted-foreground">+ {week.monthStart !== null && (+ <span className="absolute left-0 top-0 whitespace-nowrap">{monthName(week.monthStart)}</span>+ )}+ </div>+ ))}+ {Array.from({ length: 7 }, (_, row) => (+ <Row+ key={row}+ label={row % 2 === 0 ? weekdayNames[row] : ""}+ cells={page.map((week) => week.days[row])}+ level={level}+ describe={describe}+ today={today}+ />+ ))}+ </div>+ <div className="flex items-center justify-between gap-3 text-xs text-muted-foreground">+ <div className="flex items-center gap-1.5">+ <span>{t("board_insights.calendar.less")}</span>+ {([0, 1, 2, 3, 4] as const).map((l) => (+ <span key={l} className={cn("h-3 w-3 rounded-[3px]", HEAT_LEVEL_CLASS[l])} />+ ))}+ <span>{t("board_insights.calendar.more")}</span>+ </div>+ <button+ type="button"+ className={navButton}+ onClick={() => setStart((s) => Math.min(lastStart, s + PAGE_WEEKS))}+ disabled={start >= lastStart}+ aria-label={t("board_insights.calendar.newer")}+ >+ <ChevronRight className="h-4 w-4" />+ </button>+ </div>+ </div>+ );+}++function Row({+ label,+ cells,+ level,+ describe,+ today,+}: {+ label: string;+ cells: (InsightsDay | null)[];+ level: (v: number) => 0 | 1 | 2 | 3 | 4;+ describe: (day: InsightsDay) => string;+ today: string | undefined;+}) {+ return (+ <>+ <span className="truncate pr-1 text-xs text-muted-foreground">{label}</span>+ {cells.map((day, i) =>+ day ? (+ <QuickTooltip key={i} content={describe(day)} side="top" className="block">+ <span+ className={cn(+ "block aspect-square w-full max-w-[22px] rounded-[4px]",+ HEAT_LEVEL_CLASS[level(actionsOf(day))],+ day.date === today && "ring-1 ring-foreground/50 ring-offset-1 ring-offset-card",+ )}+ />+ </QuickTooltip>+ ) : (+ <span key={i} className="block aspect-square w-full max-w-[22px]" />+ ),+ )}+ </>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/board/insights/UsageTab.tsx b/jarvis/ui/web/frontend/src/components/board/insights/UsageTab.tsxnew file mode 100644index 0000000000..eb76e61d80--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/board/insights/UsageTab.tsx@@ -0,0 +1,280 @@+import { Bot, Mic, MessagesSquare, PhoneCall, TrendingDown, TrendingUp, type LucideIcon } from "lucide-react";++import type { BoardInsights } from "@/hooks/useBoardInsights";+import {+ minutesSaved,+ plural,+ trendPercent,+ usageMix,+ wordsPerMinute,+ type MixRow,+} from "@/lib/boardInsights";+import {+ BigNumber,+ CardTitleRow,+ Eyebrow,+ Hairline,+ InsightCard,+} from "@/components/board/insights/primitives";+import { QuickTooltip } from "@/components/ui/tooltip";+import { SpeedGauge } from "@/components/board/insights/SpeedGauge";+import { StreakCalendar } from "@/components/board/insights/StreakCalendar";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++export function UsageTab({ data }: { data: BoardInsights }) {+ return (+ <div className="flex flex-col gap-4">+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ <SpeedCard data={data} />+ <TimeSavedCard data={data} />+ <WordsCard data={data} />+ </div>+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]">+ <UsageMixCard data={data} />+ <StreakCard data={data} />+ </div>+ </div>+ );+}++function SpeedCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const typing = data.reference.typing_wpm;+ const wpm = wordsPerMinute(data.dictation.words, data.dictation.seconds);+ const ratio = typing > 0 ? wpm / typing : 0;+ return (+ <InsightCard testId="board-speed-card">+ <BigNumber>{wpm > 0 ? Math.round(wpm).toLocaleString() : "—"}</BigNumber>+ <div className="mt-2">+ <Eyebrow hint={t("board_insights.speed.hint").replace("{0}", String(typing))}>+ {t("board_insights.speed.label")}+ </Eyebrow>+ </div>+ <div className="mt-auto flex flex-col items-center pt-4">+ {wpm > 0 ? (+ <>+ <SpeedGauge+ wpm={wpm}+ typingWpm={typing}+ centerTop={`${ratio.toFixed(1)}×`}+ centerBottom={t("board_insights.speed.vs_typing")}+ />+ <p className="mt-1 flex items-center gap-1.5 text-xs text-muted-foreground">+ <span aria-hidden className="h-3 w-px bg-foreground/60" />+ {t("board_insights.speed.typing_mark").replace("{0}", String(typing))}+ </p>+ </>+ ) : (+ <p className="py-6 text-center text-sm text-muted-foreground">+ {t("board_insights.speed.empty")}+ </p>+ )}+ </div>+ </InsightCard>+ );+}++function TimeSavedCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const typing = data.reference.typing_wpm;+ const minutes = minutesSaved(data.dictation.words, data.dictation.seconds, typing);+ const hours = minutes / 60;+ const spokenHours = data.dictation.seconds / 3600;+ return (+ <InsightCard testId="board-time-saved-card">+ <BigNumber>+ {data.dictation.words > 0+ ? hours >= 10+ ? `${Math.round(hours).toLocaleString()} h`+ : `${hours.toFixed(1)} h`+ : "—"}+ </BigNumber>+ <div className="mt-2">+ <Eyebrow hint={t("board_insights.saved.hint").replace("{0}", String(typing))}>+ {t("board_insights.saved.label")}+ </Eyebrow>+ </div>+ <Hairline />+ <dl className="flex flex-col gap-3 text-base">+ <FactRow+ value={data.dictation.dictations.toLocaleString()}+ label={t("board_insights.saved.dictations")}+ />+ <FactRow+ value={`${spokenHours >= 10 ? Math.round(spokenHours) : spokenHours.toFixed(1)} h`}+ label={t("board_insights.saved.spoken")}+ />+ <FactRow+ value={`${Math.round(typing > 0 ? data.dictation.words / typing / 60 : 0).toLocaleString()} h`}+ label={t("board_insights.saved.typing_would_take")}+ />+ </dl>+ </InsightCard>+ );+}++function FactRow({ value, label }: { value: string; label: string }) {+ return (+ <div className="flex items-baseline justify-between gap-3">+ <dt className="truncate text-muted-foreground">{label}</dt>+ <dd className="shrink-0 font-medium tabular-nums text-foreground-strong">{value}</dd>+ </div>+ );+}++function WordsCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const dictated = data.dictation.words;+ const spoken = data.voice.user_words;+ const total = dictated + spoken;+ const novels = data.reference.novel_words > 0 ? total / data.reference.novel_words : 0;+ const trend = trendPercent(data.trend.words_30d, data.trend.words_prev_30d);+ const dictatedShare = total > 0 ? dictated / total : 0;++ return (+ <InsightCard testId="board-words-card">+ <div className="flex items-start justify-between gap-3">+ <BigNumber>{total.toLocaleString()}</BigNumber>+ {trend !== null && (+ <QuickTooltip content={t("board_insights.words.trend_hint")} side="top" className="shrink-0">+ <span className="inline-flex items-center gap-1 rounded-md border border-border px-2 py-0.5 text-xs font-medium tabular-nums text-foreground">+ {trend >= 0 ? <TrendingUp className="h-3.5 w-3.5" /> : <TrendingDown className="h-3.5 w-3.5" />}+ {t("board_insights.words.trend").replace("{0}", `${trend > 0 ? "+" : ""}${trend}`)}+ </span>+ </QuickTooltip>+ )}+ </div>+ <div className="mt-2">+ <Eyebrow hint={t("board_insights.words.novel_hint").replace("{0}", data.reference.novel_words.toLocaleString())}>+ {t("board_insights.words.label")}+ </Eyebrow>+ </div>+ <Hairline />+ <p className="text-base text-foreground">+ {total === 0+ ? t("board_insights.words.empty")+ : novels >= 1+ ? t("board_insights.words.novels").replace("{0}", novels.toFixed(1))+ : t("board_insights.words.novel_share").replace("{0}", String(Math.max(1, Math.round(novels * 100))))}+ </p>+ {total > 0 && (+ <div className="mt-auto pt-4">+ <div className="flex h-7 gap-1 overflow-hidden rounded-md text-xs font-medium">+ {dictated > 0 && (+ <SplitSegment+ icon={Mic}+ label={t("board_insights.words.dictated")}+ share={dictatedShare}+ className="bg-accent text-accent-foreground"+ />+ )}+ {spoken > 0 && (+ <SplitSegment+ icon={PhoneCall}+ label={t("board_insights.words.spoken")}+ share={1 - dictatedShare}+ className="bg-accent/30 text-foreground"+ />+ )}+ </div>+ <div className="mt-2 flex justify-between text-xs tabular-nums text-muted-foreground">+ <span>{dictated.toLocaleString()}</span>+ <span>{spoken.toLocaleString()}</span>+ </div>+ </div>+ )}+ </InsightCard>+ );+}++function SplitSegment({+ icon: Icon,+ label,+ share,+ className,+}: {+ icon: LucideIcon;+ label: string;+ share: number;+ className: string;+}) {+ // A sliver still gets room for its icon, so a small share stays legible.+ return (+ <div+ className={cn("flex min-w-[28px] items-center gap-1.5 overflow-hidden rounded-md px-2", className)}+ style={{ flexGrow: share, flexBasis: 0 }}+ >+ <Icon className="h-3.5 w-3.5 shrink-0" aria-label={label} />+ {share >= 0.15 && <span className="truncate">{label}</span>}+ </div>+ );+}++const MIX_ICON: Record<MixRow["key"], LucideIcon> = {+ dictations: Mic,+ agent_sessions: Bot,+ chat_messages: MessagesSquare,+ voice_sessions: PhoneCall,+};++function UsageMixCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const rows = usageMix(data);+ const total = rows.reduce((s, r) => s + r.count, 0);+ return (+ <InsightCard testId="board-usage-mix">+ <CardTitleRow+ title={t("board_insights.mix.title")}+ fact={t("board_insights.mix.active_days").replace("{0}", data.streak.active_days.toLocaleString())}+ />+ {total === 0 ? (+ <p className="text-sm text-muted-foreground">{t("board_insights.mix.empty")}</p>+ ) : (+ <ul className="flex flex-1 flex-col justify-center gap-3">+ {rows.map((row) => {+ const Icon = MIX_ICON[row.key];+ const pct = Math.round(row.share * 100);+ return (+ <li key={row.key} className={cn("flex items-center gap-3", row.count === 0 && "opacity-50")}>+ <Icon className="h-5 w-5 shrink-0 text-muted-foreground" aria-hidden />+ <div className="relative h-9 w-[38%] shrink-0 overflow-hidden rounded-md bg-sheen/[0.05]">+ <div+ className="absolute inset-y-0 left-0 rounded-md bg-accent"+ // Wide enough to carry its own percentage, however small the share.+ style={{ width: row.count > 0 ? `${Math.max(row.share * 100, 18)}%` : "0%" }}+ />+ <span+ className={cn(+ "absolute inset-y-0 left-2.5 flex items-center text-sm font-semibold tabular-nums",+ row.count > 0 ? "text-accent-foreground" : "text-muted-foreground",+ )}+ >+ {pct < 1 && row.count > 0 ? "<1%" : `${pct}%`}+ </span>+ </div>+ <span className="min-w-0 truncate text-sm font-medium uppercase tracking-[0.06em] text-foreground">+ {plural(t, `board_insights.mix.${row.key}`, row.count)}+ </span>+ </li>+ );+ })}+ </ul>+ )}+ </InsightCard>+ );+}++function StreakCard({ data }: { data: BoardInsights }) {+ const t = useT();+ const current = data.streak.current_days;+ return (+ <InsightCard testId="board-streak-card">+ <CardTitleRow+ title={current > 0 ? plural(t, "board_insights.streak.title", current) : t("board_insights.streak.none")}+ fact={plural(t, "board_insights.streak.longest", data.streak.longest_days)}+ />+ <StreakCalendar days={data.days} />+ </InsightCard>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/board/insights/primitives.tsx b/jarvis/ui/web/frontend/src/components/board/insights/primitives.tsxnew file mode 100644index 0000000000..e1b73a6e60--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/board/insights/primitives.tsx@@ -0,0 +1,95 @@+import type { ReactNode } from "react";+import { Info } from "lucide-react";++import { QuickTooltip } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";++/** The Board's one card: a quiet object on the room, padding on the root. */+export function InsightCard({+ className,+ children,+ testId,+}: {+ className?: string;+ children: ReactNode;+ testId?: string;+}) {+ return (+ <section+ data-testid={testId}+ className={cn("flex min-w-0 flex-col rounded-lg border border-border bg-card p-5", className)}+ >+ {children}+ </section>+ );+}++/** Small uppercase caption under a headline number, with an optional hint. */+export function Eyebrow({ children, hint }: { children: ReactNode; hint?: string }) {+ return (+ <div className="flex items-center gap-1.5 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">+ <span className="truncate">{children}</span>+ {hint && (+ <QuickTooltip content={hint} side="top">+ <Info className="h-3.5 w-3.5 text-foreground-faint" aria-label={hint} />+ </QuickTooltip>+ )}+ </div>+ );+}++export function BigNumber({ children, className }: { children: ReactNode; className?: string }) {+ return (+ <div+ className={cn(+ "text-2xl font-semibold tabular-nums leading-none text-foreground-strong",+ className,+ )}+ >+ {children}+ </div>+ );+}++/** Card title row: a heading on the left, an uppercase fact on the right. */+export function CardTitleRow({+ title,+ fact,+ children,+}: {+ title: ReactNode;+ fact?: ReactNode;+ children?: ReactNode;+}) {+ return (+ <div className="mb-4 flex flex-wrap items-start justify-between gap-x-4 gap-y-2">+ <div className="min-w-0">+ <h2 className="text-xl font-semibold text-foreground-strong">{title}</h2>+ {children}+ </div>+ {fact && (+ <div className="pt-1.5 text-xs font-medium uppercase tracking-[0.08em] text-foreground tabular-nums">+ {fact}+ </div>+ )}+ </div>+ );+}++export function Hairline() {+ return <div className="my-4 h-px bg-border" />;+}++/** A loading placeholder — never a fallback number (see loading states). */+export function SkeletonBlock({ className }: { className?: string }) {+ return <div className={cn("animate-pulse rounded-md bg-foreground/10", className)} />;+}++/** Heat colour for an intensity level, from the one accent hue. */+export const HEAT_LEVEL_CLASS: Record<0 | 1 | 2 | 3 | 4, string> = {+ 0: "bg-sheen/[0.07]",+ 1: "bg-accent/25",+ 2: "bg-accent/45",+ 3: "bg-accent/70",+ 4: "bg-accent",+};diff --git a/jarvis/ui/web/frontend/src/hooks/useBoardInsights.ts b/jarvis/ui/web/frontend/src/hooks/useBoardInsights.tsnew file mode 100644index 0000000000..464ea640c5--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useBoardInsights.ts@@ -0,0 +1,101 @@+import { useQuery } from "@tanstack/react-query";++import type { BoardCategories } from "@/hooks/useBoard";++// ----------------------------------------------------------------------+// Types (mirror the InsightsResponse schema in jarvis/ui/web/board_routes.py)+// ----------------------------------------------------------------------++export interface InsightsDay {+ date: string; // local YYYY-MM-DD+ dictations: number;+ dictation_words: number;+ voice_sessions: number;+ voice_words: number;+ chat_messages: number;+ agent_sessions: number;+ agent_turns: number;+}++export interface InsightsAgent {+ agent: string;+ sessions: number;+ sessions_30d: number;+ turns: number;+ turns_30d: number;+ tokens: number;+ last_ms: number;+}++export interface InsightsChatProvider {+ provider: string;+ sessions: number;+ messages: number;+ jarvis_sessions: number;+}++export interface InsightsRecord {+ date: string;+ value: number;+}++export interface BoardInsights {+ generated_at: string;+ reference: { typing_wpm: number; novel_words: number };+ dictation: { available: boolean; words: number; dictations: number; seconds: number };+ voice: {+ available: boolean;+ sessions: number;+ turns: number;+ user_words: number;+ jarvis_words: number;+ /** Time voice sessions were OPEN (wake to hang-up), not time spent speaking. */+ seconds: number;+ };+ chats: {+ available: boolean;+ sessions: number;+ messages: number;+ providers: InsightsChatProvider[];+ };+ agents: {+ available: boolean;+ sessions: number;+ turns: number;+ tokens: number;+ items: InsightsAgent[];+ };+ days: InsightsDay[];+ /** 7 rows, Monday first, x 24 local hours. */+ punch_card: number[][];+ trend: { words_30d: number; words_prev_30d: number };+ streak: {+ current_days: number;+ longest_days: number;+ active_days: number;+ first_day: string | null;+ };+ records: {+ best_words_day: InsightsRecord | null;+ best_agent_day: InsightsRecord | null;+ };+ categories: BoardCategories;+}++async function fetchInsights(): Promise<BoardInsights> {+ const res = await fetch("/api/board/insights");+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return res.json();+}++export const boardInsightsQuery = {+ queryKey: ["board", "insights"] as const,+ queryFn: fetchInsights,+ // The backend reuses one picture for 30 s; polling faster only re-reads it.+ refetchInterval: 30_000,+ staleTime: 15_000,+};++export function useBoardInsights() {+ return useQuery(boardInsightsQuery);+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 08a702a09f..12cc5d5d81 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -471,12 +471,7 @@"state_active": "Nimmt auf","state_ready": "Bereit","state_unavailable": "Auf diesem Computer nicht verfügbar",- "shortcut_set": "Halte {0}, um zu diktieren.",- "shortcut_unset": "Noch keine Taste zugewiesen — Diktat geht auch über den Knopf unten.",- "engine_local": "Erkennt lokal auf diesem Rechner ({0}); Ausweichen: {1}.",- "engine_cloud": "Erkennt über {0}.","engine_local_off": "Lokal gerade nicht: {0}",- "assign_hint": "Weise unter Einstellungen → Sprach-Tastenkürzel eine Taste zu, um überall zu diktieren.","start": "Diktat starten","stop": "Stopp","saved": "Einstellung gespeichert",@@ -484,19 +479,45 @@"cannot_insert_generic": "Dein System blockiert, dass ein Programm in ein anderes tippt. Diktat funktioniert trotzdem — der Text landet in der Zwischenablage, du kannst ihn einfügen.","polish_first_run": "Neu: Ein schnelles Modell räumt jetzt deine Formulierung auf, bevor der Text ankommt — dein Rohtext bleibt in dieser Liste, und auf dem Tab „Sprache“ kannst du es abschalten.","history_title": "Letzte Diktate",- "history_empty": "Noch nichts diktiert.","clear_history": "Alle löschen","raw_prefix": "Gehört:","removed_words": "{0} Füllwort/-wörter entfernt","delete_entry": "Diesen Eintrag löschen","search_placeholder": "Diktate durchsuchen",+ "welcome": "Willkommen zurück{name_part}",+ "hero_hold": "Halte {0} gedrückt und diktiere",+ "hero_listening": "Ich höre zu — sprich jetzt",+ "hero_no_key": "Sprechen statt tippen",+ "hero_body": "Funktioniert in jeder App — E-Mail, Nachrichten, Dokumente oder überall sonst, wo du tippst.",+ "hero_body_active": "Sobald du stoppst, landen deine Worte in dem Feld, in dem du gerade getippt hast.",+ "hero_hands_free": "Oder drücke einmal {0}, um freihändig zu diktieren.",+ "hero_shortcuts": "Tastenkürzel ändern",+ "hero_assign": "Taste festlegen",+ "engine_title": "Erkennung",+ "engine_on_device": "Auf diesem Computer",+ "engine_cloud_short": "Cloud",+ "engine_fallback": "Ausweichlösung: {0}",+ "vocab_title": "Bring ihm deine Wörter bei",+ "vocab_body": "Füge Namen, Marken und Fachbegriffe hinzu, damit sie jedes Mal richtig geschrieben werden.",+ "vocab_cta": "Wörterbuch öffnen",+ "show_original": "Gehörtes anzeigen",+ "hide_original": "Gehörtes ausblenden",+ "empty_title": "Hier erscheinen deine Diktate",+ "empty_body": "Halte deine Taste in irgendeiner App, sprich und lass los. Jedes Diktat bleibt hier, damit du es erneut kopieren kannst.","stats": {"title": "Dein Diktat","words": "Wörter","wpm": "Wörter pro Minute","streak": "Tage in Folge","window_lifetime": "Gesamt",- "window_days": "Letzte {0} Tage"+ "window_days": "Letzte {0} Tage",+ "words_unit": "Wörter",+ "wpm_unit": "WpM",+ "streak_unit": "Tage in Folge",+ "today": "Heute: {0} Wörter",+ "best_streak": "Rekord: {0} Tage",+ "activity": "Letzte 14 Tage",+ "activity_day": "{0}: {1} Wörter"},"group": {"today": "Heute",@@ -1644,6 +1665,122 @@"group_workspaces": "Arbeitsbereiche","untitled_chat": "Chat ohne Titel"},+ "board_insights": {+ "description": "Wie du mit {name} arbeitest, gezählt auf diesem Computer.",+ "tabs": {+ "usage": "Nutzung",+ "agents": "Agenten",+ "rhythm": "Rhythmus"+ },+ "speed": {+ "label": "Wörter pro Minute",+ "hint": "Deine Diktiergeschwindigkeit. Der Strich markiert Tippen mit {0} Wörtern pro Minute.",+ "vs_typing": "Tippgeschwindigkeit",+ "typing_mark": "Tippen mit {0} Wörtern pro Minute",+ "empty": "Diktiere einmal, dann erscheint hier deine Sprechgeschwindigkeit."+ },+ "saved": {+ "label": "Stunden gespart durch Sprechen",+ "hint": "Die Zeit, die das Tippen deiner diktierten Wörter mit {0} Wörtern pro Minute dauern würde, abzüglich der Zeit, die du diktiert hast.",+ "dictations": "Diktate",+ "spoken": "Zeit beim Diktieren",+ "typing_would_take": "Tippen hätte gedauert"+ },+ "words": {+ "label": "Wörter an {name}",+ "novel_hint": "Diktierte Wörter plus die Wörter aus Sprachsitzungen. Ein durchschnittlicher Roman hat etwa {0} Wörter.",+ "trend": "{0} % ggü. letzten 30 Tagen",+ "trend_hint": "Wörter der letzten 30 Tage im Vergleich zu den 30 Tagen davor.",+ "novels": "Das reicht für {0} Romane.",+ "novel_share": "Das sind bisher {0} % eines Romans.",+ "empty": "Diktiere oder starte eine Sprachsitzung, dann summieren sich hier deine Wörter.",+ "dictated": "Diktat",+ "spoken": "Sprache"+ },+ "mix": {+ "title": "So nutzt du {name}",+ "active_days": "Aktive Tage | {0}",+ "empty": "Noch nichts erfasst. Diktiere, chatte oder starte einen Agenten.",+ "dictations": "{0} Diktate",+ "dictations_one": "{0} Diktat",+ "agent_sessions": "{0} Agenten-Sitzungen",+ "agent_sessions_one": "{0} Agenten-Sitzung",+ "chat_messages": "{0} Chat-Nachrichten",+ "chat_messages_one": "{0} Chat-Nachricht",+ "voice_sessions": "{0} Sprachsitzungen",+ "voice_sessions_one": "{0} Sprachsitzung"+ },+ "streak": {+ "title": "{0} Tage in Folge",+ "title_one": "{0} Tag in Folge",+ "none": "Noch keine Serie",+ "longest": "Längste Serie | {0} Tage",+ "longest_one": "Längste Serie | {0} Tag"+ },+ "calendar": {+ "less": "Weniger",+ "more": "Mehr",+ "older": "Frühere Wochen",+ "newer": "Spätere Wochen",+ "nothing": "nichts",+ "started": "{0} gestartet",+ "words": "{0} Wörter"+ },+ "agents": {+ "title": "Coding-Agenten",+ "subtitle": "Sitzungen der Coding-CLIs auf diesem Computer, aus ihren eigenen Protokollen gelesen.",+ "used": "{0} Agenten genutzt",+ "used_one": "{0} Agent genutzt",+ "range_30d": "Letzte 30 Tage",+ "range_all": "Gesamt",+ "col_agent": "Agent",+ "col_share": "Anteil",+ "col_sessions": "Sitzungen",+ "col_turns": "Züge",+ "col_last": "Zuletzt",+ "empty": "Auf diesem Computer wurden noch keine Coding-Agenten-Sitzungen gefunden.",+ "stat_sessions": "Agenten-Sitzungen",+ "stat_sessions_30d": "Sitzungen, letzte 30 Tage",+ "stat_tokens": "Verarbeitete Tokens",+ "stat_busiest": "Meiste Sitzungen an einem Tag"+ },+ "chats": {+ "title": "Chats",+ "messages": "{0} Nachrichten",+ "messages_one": "{0} Nachricht",+ "empty": "Noch keine Chat-Nachrichten."+ },+ "categories": {+ "title": "Was {name} für dich erledigt hat",+ "subtitle": "Werkzeuge aus Sprachzügen, nach Art.",+ "empty": "In Sprachzügen wurden noch keine Werkzeuge genutzt."+ },+ "rhythm": {+ "title": "Wann du arbeitest",+ "subtitle": "Sprachzüge, Chat-Nachrichten und Agenten-Züge nach Wochentag und Stunde.",+ "peak": "Am meisten | {0}, {1}",+ "empty": "Noch zu wenig Aktivität für einen Rhythmus."+ },+ "weekly": {+ "title": "Wörter pro Woche",+ "subtitle": "Diktierte und gesprochene Wörter, letzte 26 Wochen.",+ "best": "Beste Woche | {0}",+ "tooltip": "{0} Wörter · {1} Agenten-Sitzungen"+ },+ "records": {+ "title": "Rekorde",+ "best_words": "Meiste Wörter an einem Tag",+ "best_agents": "Meiste Agenten-Sitzungen an einem Tag",+ "longest_streak": "Längste Serie",+ "active_days": "Aktive Tage",+ "since": "seit {0}",+ "days": "{0} Tage",+ "days_one": "{0} Tag",+ "next_milestone": "Nächstes Ziel: {0} Wörter",+ "to_go": "noch {0}",+ "today": "Heute {0} Wörter."+ }+ },"board_view": {"title": "Board","subtitle": "Alles, was du und {name} zusammen gemacht habt — komplett lokal.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 48b055b5b6..b3c7cb79f9 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -471,12 +471,7 @@"state_active": "Recording","state_ready": "Ready","state_unavailable": "Not available on this computer",- "shortcut_set": "Hold {0} to dictate.",- "shortcut_unset": "No key assigned yet — dictation still works from the button below.",- "engine_local": "Recognizes locally on this machine ({0}); fallback: {1}.",- "engine_cloud": "Recognizes via {0}.","engine_local_off": "Local engine not in front right now: {0}",- "assign_hint": "Assign a key in Settings → Voice Keybinds to dictate from anywhere.","start": "Start dictating","stop": "Stop","saved": "Setting saved",@@ -484,19 +479,45 @@"cannot_insert_generic": "Your system is blocking one program from typing into another. Dictation still works — the text is placed on your clipboard so you can paste it.","polish_first_run": "New: a fast model now tidies up your wording before the text lands — your raw words stay in this list, and you can switch it off on the Language tab.","history_title": "Recent dictations",- "history_empty": "Nothing dictated yet.","clear_history": "Delete all","raw_prefix": "Heard:","removed_words": "{0} filler word(s) removed","delete_entry": "Delete this entry","search_placeholder": "Search your dictations",+ "welcome": "Welcome back{name_part}",+ "hero_hold": "Hold {0} to dictate",+ "hero_listening": "Listening — speak now",+ "hero_no_key": "Speak instead of typing",+ "hero_body": "Works in every app — email, messages, docs, or anywhere else you type.",+ "hero_body_active": "When you stop, your words land in the field you were typing in.",+ "hero_hands_free": "Or press {0} once to dictate hands-free.",+ "hero_shortcuts": "Change shortcut",+ "hero_assign": "Assign a key",+ "engine_title": "Recognition",+ "engine_on_device": "On this computer",+ "engine_cloud_short": "Cloud",+ "engine_fallback": "Fallback: {0}",+ "vocab_title": "Teach it your words",+ "vocab_body": "Add names, brands and terms so they are spelled right every time.",+ "vocab_cta": "Open dictionary",+ "show_original": "Show what was heard",+ "hide_original": "Hide what was heard",+ "empty_title": "Your dictations will show up here",+ "empty_body": "Hold your key in any app, speak, and let go. Every dictation is kept here so you can copy it again.","stats": {"title": "Your dictation","words": "Words","wpm": "Words per minute","streak": "Day streak","window_lifetime": "All time",- "window_days": "Last {0} days"+ "window_days": "Last {0} days",+ "words_unit": "words",+ "wpm_unit": "wpm",+ "streak_unit": "day streak",+ "today": "Today: {0} words",+ "best_streak": "Best streak: {0} days",+ "activity": "Last 14 days",+ "activity_day": "{0}: {1} words"},"group": {"today": "Today",@@ -1644,6 +1665,122 @@"group_workspaces": "Workspaces","untitled_chat": "Untitled chat"},+ "board_insights": {+ "description": "How you work with {name}, counted on this computer.",+ "tabs": {+ "usage": "Usage",+ "agents": "Agents",+ "rhythm": "Rhythm"+ },+ "speed": {+ "label": "Words per minute",+ "hint": "Your dictation speed. The ring marks typing at {0} words per minute.",+ "vs_typing": "typing speed",+ "typing_mark": "Typing at {0} words per minute",+ "empty": "Dictate once and your speaking speed shows up here."+ },+ "saved": {+ "label": "Hours saved by speaking",+ "hint": "The time typing your dictated words at {0} words per minute would take, minus the time you spent dictating them.",+ "dictations": "Dictations",+ "spoken": "Time spent dictating",+ "typing_would_take": "Typing would have taken"+ },+ "words": {+ "label": "Words you gave {name}",+ "novel_hint": "Dictated words plus the words you said in voice sessions. An average novel has about {0} words.",+ "trend": "{0}% vs last 30 days",+ "trend_hint": "Words in the last 30 days compared with the 30 days before.",+ "novels": "That's {0} novels' worth of words.",+ "novel_share": "That's {0}% of a novel so far.",+ "empty": "Dictate or start a voice session and your words add up here.",+ "dictated": "Dictation",+ "spoken": "Voice"+ },+ "mix": {+ "title": "How you use {name}",+ "active_days": "Active days | {0}",+ "empty": "Nothing recorded yet. Dictate, chat or start an agent to fill this in.",+ "dictations": "{0} dictations",+ "dictations_one": "{0} dictation",+ "agent_sessions": "{0} agent sessions",+ "agent_sessions_one": "{0} agent session",+ "chat_messages": "{0} chat messages",+ "chat_messages_one": "{0} chat message",+ "voice_sessions": "{0} voice sessions",+ "voice_sessions_one": "{0} voice session"+ },+ "streak": {+ "title": "{0}-day streak",+ "title_one": "{0}-day streak",+ "none": "No streak yet",+ "longest": "Longest streak | {0} days",+ "longest_one": "Longest streak | {0} day"+ },+ "calendar": {+ "less": "Less",+ "more": "More",+ "older": "Earlier weeks",+ "newer": "Later weeks",+ "nothing": "nothing",+ "started": "{0} started",+ "words": "{0} words"+ },+ "agents": {+ "title": "Coding agents",+ "subtitle": "Sessions of the coding CLIs on this computer, read from their own transcripts.",+ "used": "{0} agents used",+ "used_one": "{0} agent used",+ "range_30d": "Last 30 days",+ "range_all": "All time",+ "col_agent": "Agent",+ "col_share": "Share",+ "col_sessions": "Sessions",+ "col_turns": "Turns",+ "col_last": "Last used",+ "empty": "No coding-agent sessions found on this computer yet.",+ "stat_sessions": "Agent sessions",+ "stat_sessions_30d": "Sessions, last 30 days",+ "stat_tokens": "Tokens processed",+ "stat_busiest": "Most sessions in a day"+ },+ "chats": {+ "title": "Chats",+ "messages": "{0} messages",+ "messages_one": "{0} message",+ "empty": "No chat messages yet."+ },+ "categories": {+ "title": "What {name} did for you",+ "subtitle": "Tools used during voice turns, by kind.",+ "empty": "No tools used in voice turns yet."+ },+ "rhythm": {+ "title": "When you work",+ "subtitle": "Voice turns, chat messages and agent turns, by weekday and hour.",+ "peak": "Busiest | {0}, {1}",+ "empty": "Not enough activity yet to show a rhythm."+ },+ "weekly": {+ "title": "Words per week",+ "subtitle": "Dictated and spoken words, last 26 weeks.",+ "best": "Best week | {0}",+ "tooltip": "{0} words · {1} agent sessions"+ },+ "records": {+ "title": "Records",+ "best_words": "Most words in a day",+ "best_agents": "Most agent sessions in a day",+ "longest_streak": "Longest streak",+ "active_days": "Active days",+ "since": "since {0}",+ "days": "{0} days",+ "days_one": "{0} day",+ "next_milestone": "Next: {0} words",+ "to_go": "{0} to go",+ "today": "{0} words today."+ }+ },"board_view": {"title": "Board","subtitle": "Everything you and {name} have done together — fully local.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 7ab202532e..c2fab6dcb0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -471,12 +471,7 @@"state_active": "Grabando","state_ready": "Listo","state_unavailable": "No disponible en este ordenador",- "shortcut_set": "Mantén {0} para dictar.",- "shortcut_unset": "Aún no hay tecla asignada — el dictado también funciona con el botón de abajo.",- "engine_local": "Reconoce localmente en este equipo ({0}); alternativa: {1}.",- "engine_cloud": "Reconoce mediante {0}.","engine_local_off": "Motor local ahora no disponible: {0}",- "assign_hint": "Asigna una tecla en Ajustes → Atajos de voz para dictar desde cualquier sitio.","start": "Empezar a dictar","stop": "Detener","saved": "Ajuste guardado",@@ -484,19 +479,45 @@"cannot_insert_generic": "Tu sistema impide que un programa escriba en otro. El dictado sigue funcionando — el texto queda en el portapapeles para que lo pegues.","polish_first_run": "Novedad: un modelo rápido pule ahora tu redacción antes de que el texto llegue; tu texto original permanece en esta lista y puedes desactivarlo en la pestaña «Idioma».","history_title": "Dictados recientes",- "history_empty": "Todavía no has dictado nada.","clear_history": "Borrar todo","raw_prefix": "Se oyó:","removed_words": "{0} muletilla(s) eliminada(s)","delete_entry": "Eliminar esta entrada","search_placeholder": "Buscar en tus dictados",+ "welcome": "Bienvenido de nuevo{name_part}",+ "hero_hold": "Mantén {0} para dictar",+ "hero_listening": "Escuchando — habla ahora",+ "hero_no_key": "Habla en lugar de escribir",+ "hero_body": "Funciona en todas tus apps: correo, mensajes, documentos o cualquier otro sitio donde escribas.",+ "hero_body_active": "Cuando te detengas, tus palabras aparecerán en el campo donde estabas escribiendo.",+ "hero_hands_free": "O pulsa {0} una vez para dictar sin manos.",+ "hero_shortcuts": "Cambiar atajo",+ "hero_assign": "Asignar una tecla",+ "engine_title": "Reconocimiento",+ "engine_on_device": "En este ordenador",+ "engine_cloud_short": "Nube",+ "engine_fallback": "Alternativa: {0}",+ "vocab_title": "Enséñale tus palabras",+ "vocab_body": "Añade nombres, marcas y términos para que se escriban bien siempre.",+ "vocab_cta": "Abrir diccionario",+ "show_original": "Ver lo que se oyó",+ "hide_original": "Ocultar lo que se oyó",+ "empty_title": "Tus dictados aparecerán aquí",+ "empty_body": "Mantén tu tecla en cualquier app, habla y suelta. Cada dictado se guarda aquí para que puedas copiarlo de nuevo.","stats": {"title": "Tu dictado","words": "Palabras","wpm": "Palabras por minuto","streak": "Días seguidos","window_lifetime": "Desde siempre",- "window_days": "Últimos {0} días"+ "window_days": "Últimos {0} días",+ "words_unit": "palabras",+ "wpm_unit": "ppm",+ "streak_unit": "días seguidos",+ "today": "Hoy: {0} palabras",+ "best_streak": "Mejor racha: {0} días",+ "activity": "Últimos 14 días",+ "activity_day": "{0}: {1} palabras"},"group": {"today": "Hoy",@@ -1644,6 +1665,122 @@"group_workspaces": "Espacios de trabajo","untitled_chat": "Chat sin título"},+ "board_insights": {+ "description": "Cómo trabajas con {name}, contado en este ordenador.",+ "tabs": {+ "usage": "Uso",+ "agents": "Agentes",+ "rhythm": "Ritmo"+ },+ "speed": {+ "label": "Palabras por minuto",+ "hint": "Tu velocidad de dictado. La marca indica escribir a {0} palabras por minuto.",+ "vs_typing": "velocidad de escritura",+ "typing_mark": "Escribir a {0} palabras por minuto",+ "empty": "Dicta una vez y aquí aparecerá tu velocidad al hablar."+ },+ "saved": {+ "label": "Horas ahorradas hablando",+ "hint": "El tiempo que tardarías en escribir tus palabras dictadas a {0} palabras por minuto, menos el tiempo que pasaste dictando.",+ "dictations": "Dictados",+ "spoken": "Tiempo dictando",+ "typing_would_take": "Escribir habría llevado"+ },+ "words": {+ "label": "Palabras para {name}",+ "novel_hint": "Palabras dictadas más las dichas en sesiones de voz. Una novela media tiene unas {0} palabras.",+ "trend": "{0} % vs. últimos 30 días",+ "trend_hint": "Palabras de los últimos 30 días frente a los 30 días anteriores.",+ "novels": "Equivale a {0} novelas.",+ "novel_share": "Llevas el {0} % de una novela.",+ "empty": "Dicta o inicia una sesión de voz y tus palabras se sumarán aquí.",+ "dictated": "Dictado",+ "spoken": "Voz"+ },+ "mix": {+ "title": "Cómo usas {name}",+ "active_days": "Días activos | {0}",+ "empty": "Aún no hay nada registrado. Dicta, chatea o inicia un agente.",+ "dictations": "{0} dictados",+ "dictations_one": "{0} dictado",+ "agent_sessions": "{0} sesiones de agente",+ "agent_sessions_one": "{0} sesión de agente",+ "chat_messages": "{0} mensajes de chat",+ "chat_messages_one": "{0} mensaje de chat",+ "voice_sessions": "{0} sesiones de voz",+ "voice_sessions_one": "{0} sesión de voz"+ },+ "streak": {+ "title": "Racha de {0} días",+ "title_one": "Racha de {0} día",+ "none": "Aún sin racha",+ "longest": "Racha más larga | {0} días",+ "longest_one": "Racha más larga | {0} día"+ },+ "calendar": {+ "less": "Menos",+ "more": "Más",+ "older": "Semanas anteriores",+ "newer": "Semanas posteriores",+ "nothing": "nada",+ "started": "{0} iniciados",+ "words": "{0} palabras"+ },+ "agents": {+ "title": "Agentes de código",+ "subtitle": "Sesiones de las CLI de código en este ordenador, leídas de sus propios registros.",+ "used": "{0} agentes usados",+ "used_one": "{0} agente usado",+ "range_30d": "Últimos 30 días",+ "range_all": "Todo",+ "col_agent": "Agente",+ "col_share": "Cuota",+ "col_sessions": "Sesiones",+ "col_turns": "Turnos",+ "col_last": "Último uso",+ "empty": "Aún no hay sesiones de agentes de código en este ordenador.",+ "stat_sessions": "Sesiones de agente",+ "stat_sessions_30d": "Sesiones, últimos 30 días",+ "stat_tokens": "Tokens procesados",+ "stat_busiest": "Más sesiones en un día"+ },+ "chats": {+ "title": "Chats",+ "messages": "{0} mensajes",+ "messages_one": "{0} mensaje",+ "empty": "Aún no hay mensajes de chat."+ },+ "categories": {+ "title": "Lo que {name} hizo por ti",+ "subtitle": "Herramientas usadas en turnos de voz, por tipo.",+ "empty": "Aún no se usaron herramientas en turnos de voz."+ },+ "rhythm": {+ "title": "Cuándo trabajas",+ "subtitle": "Turnos de voz, mensajes de chat y turnos de agente por día y hora.",+ "peak": "Más activo | {0}, {1}",+ "empty": "Aún no hay actividad suficiente para mostrar un ritmo."+ },+ "weekly": {+ "title": "Palabras por semana",+ "subtitle": "Palabras dictadas y habladas, últimas 26 semanas.",+ "best": "Mejor semana | {0}",+ "tooltip": "{0} palabras · {1} sesiones de agente"+ },+ "records": {+ "title": "Récords",+ "best_words": "Más palabras en un día",+ "best_agents": "Más sesiones de agente en un día",+ "longest_streak": "Racha más larga",+ "active_days": "Días activos",+ "since": "desde {0}",+ "days": "{0} días",+ "days_one": "{0} día",+ "next_milestone": "Siguiente: {0} palabras",+ "to_go": "faltan {0}",+ "today": "{0} palabras hoy."+ }+ },"board_view": {"title": "Tablero","subtitle": "Todo lo que tú y {name} habéis hecho juntos — totalmente local.",diff --git a/jarvis/ui/web/frontend/src/lib/boardCsv.test.ts b/jarvis/ui/web/frontend/src/lib/boardCsv.test.tsdeleted file mode 100644index 0f24619b09..0000000000--- a/jarvis/ui/web/frontend/src/lib/boardCsv.test.ts+++ /dev/null@@ -1,199 +0,0 @@-import { describe, expect, it } from "vitest";-import {- CSV_HEADER,- boardCsv,- boardCsvFilename,- boardCsvRows,- csvField,-} from "./boardCsv";-import type {- BoardCategories,- BoardHeatmap,- BoardSummary,-} from "@/hooks/useBoard";--const summary: BoardSummary = {- window_days: 30,- totals: {- tasks_completed: 12,- tasks_failed: 1,- voice_commands: 40,- hours_saved: 2.5,- activity_events: 90,- conversation_hours: 3.25,- user_words: 1200,- jarvis_words: 3400,- session_count: 8,- active_days: 5,- first_day: "2026-01-04",- },- window: {- tasks_completed: 3,- tasks_failed: 0,- voice_commands: 10,- hours_saved: 0.5,- activity_events: 20,- conversation_hours: 1.5,- user_words: 300,- jarvis_words: 800,- session_count: 2,- voice_first_try_rate: null,- unique_tools: 4,- },- streak_days: 3,- longest_streak: 9,-};--const heatmap: BoardHeatmap = {- start: "2026-08-21",- end: "2026-08-22",- days: 2,- cells: [- {- date: "2026-08-21",- tasks_completed: 1,- tasks_failed: 0,- activity_events: 5,- conversation_hours: 0.5,- user_words: 100,- jarvis_words: 200,- },- ],-};--const categories: BoardCategories = {- window_days: 30,- total: 3,- categories: [- { category: "music", count: 2 },- { category: 'weather, "local"', count: 1 },- ],-};--/** Minimal RFC 4180 reader, so the quoting assertions test what a reader sees. */-function parseCsvLine(line: string): string[] {- const fields: string[] = [];- let field = "";- let inQuotes = false;- for (let i = 0; i < line.length; i++) {- const ch = line[i];- if (inQuotes) {- if (ch === '"') {- if (line[i + 1] === '"') {- field += '"';- i++;- } else inQuotes = false;- } else field += ch;- } else if (ch === '"') inQuotes = true;- else if (ch === ",") {- fields.push(field);- field = "";- } else field += ch;- }- fields.push(field);- return fields;-}--describe("csvField", () => {- it("leaves a plain value alone", () => {- expect(csvField("music")).toBe("music");- expect(csvField(42)).toBe("42");- });-- it("quotes a field containing a comma", () => {- expect(csvField("weather, local")).toBe('"weather, local"');- });-- it("doubles inner quotes", () => {- expect(csvField('say "hi"')).toBe('"say ""hi"""');- });-- it("quotes newlines and edge whitespace so a reader cannot silently trim", () => {- expect(csvField("a\nb")).toBe('"a\nb"');- expect(csvField(" padded ")).toBe('" padded "');- });-- it("writes null and undefined as an empty field, never the string 'null'", () => {- expect(csvField(null)).toBe("");- expect(csvField(undefined)).toBe("");- });-});--describe("boardCsvRows", () => {- it("returns nothing when the view holds nothing", () => {- expect(boardCsvRows({})).toEqual([]);- });-- it("omits a section the view has not loaded instead of writing zeros", () => {- const rows = boardCsvRows({ summary });- expect(rows.some((r) => r[0] === "daily")).toBe(false);- expect(rows.some((r) => r[0] === "categories")).toBe(false);- });-- it("puts first_day in the date column, not the value column", () => {- const row = boardCsvRows({ summary }).find((r) => r[2] === "first_day");- expect(row).toEqual(["totals", "2026-01-04", "first_day", ""]);- });-- it("writes a null rate as empty, so it cannot be read as zero", () => {- const row = boardCsvRows({ summary }).find(- (r) => r[0] === "window" && r[2] === "voice_first_try_rate",- );- expect(row?.[3]).toBe("");- });-- it("emits one row per metric per day, keyed by the ISO date", () => {- const rows = boardCsvRows({ heatmap }).filter((r) => r[0] === "daily");- expect(rows).toHaveLength(6);- expect(rows.every((r) => r[1] === "2026-08-21")).toBe(true);- });-- it("keeps the streak values that live outside totals", () => {- const rows = boardCsvRows({ summary });- expect(rows).toContainEqual(["totals", "", "streak_days", 3]);- expect(rows).toContainEqual(["totals", "", "longest_streak", 9]);- });-});--describe("boardCsv", () => {- it("starts with the fixed header after the BOM", () => {- const text = boardCsv({ summary });- expect(text.charCodeAt(0)).toBe(0xfeff);- expect(text.slice(1).split("\r\n")[0]).toBe(CSV_HEADER.join(","));- });-- it("quotes a category name containing a comma so columns do not shift", () => {- const line = boardCsv({ categories })- .split("\r\n")- .find((l) => l.includes("weather"));- expect(line).toBe('categories,,"weather, ""local""",1');- // And a reader still sees exactly four fields, with the comma inside one.- expect(parseCsvLine(line!)).toEqual([- "categories",- "",- 'weather, "local"',- "1",- ]);- });-- it("uses CRLF and ends with a terminating newline", () => {- const text = boardCsv({ summary });- expect(text.endsWith("\r\n")).toBe(true);- expect(text.includes("\r\n")).toBe(true);- });-- it("carries every loaded section in one document", () => {- const text = boardCsv({ summary, heatmap, categories });- for (const section of ["totals", "window", "daily", "categories"]) {- expect(text).toContain(`\r\n${section},`);- }- });-});--describe("boardCsvFilename", () => {- it("names the file with an ISO date so files sort chronologically", () => {- expect(boardCsvFilename(new Date("2026-08-22T18:04:00Z"))).toBe(- "jarvis-board-2026-08-22.csv",- );- });-});diff --git a/jarvis/ui/web/frontend/src/lib/boardCsv.ts b/jarvis/ui/web/frontend/src/lib/boardCsv.tsdeleted file mode 100644index f8533b7581..0000000000--- a/jarvis/ui/web/frontend/src/lib/boardCsv.ts+++ /dev/null@@ -1,131 +0,0 @@-/**- * Serialize the Board's aggregates as CSV.- *- * The Board holds three shapes at once — lifetime/window totals, a day-by-day- * series, and a category breakdown. Flattening them into one wide table would- * need a column per metric per shape and leave most cells empty, so this emits- * TIDY (long) rows instead: one observation per line, four fixed columns.- *- * section,date,metric,value- * totals,,user_words,124503- * daily,2026-08-22,user_words,1204- * categories,,music,42- *- * That is the shape pandas pivots in one call and Excel filters natively, and- * adding a fourth aggregate later costs a `section` value, not a schema change.- *- * Dates are ISO 8601 (`YYYY-MM-DD`), never the localized display format —- * `08/22/2026` and `22.08.2026` sort as text and are read differently on every- * machine that opens the file. The backend already speaks ISO here, so the- * values pass through untouched.- */-import type {- BoardCategories,- BoardHeatmap,- BoardSummary,-} from "@/hooks/useBoard";--/** The fixed header. Exported so a test pins it rather than restating it. */-export const CSV_HEADER = ["section", "date", "metric", "value"] as const;--/**- * Quote one field per RFC 4180.- *- * A field is quoted when it contains a comma, a quote, a newline, or edge- * whitespace that a reader would otherwise silently trim; inner quotes double.- * Category names are free text and reach this function, so this is the- * difference between a usable file and one that shifts every column after the- * first category with a comma in it.- */-export function csvField(value: string | number | null | undefined): string {- if (value === null || value === undefined) return "";- const text = String(value);- const needsQuotes =- text.includes(",") ||- text.includes('"') ||- text.includes("\n") ||- text.includes("\r") ||- text !== text.trim();- if (!needsQuotes) return text;- return `"${text.replace(/"/g, '""')}"`;-}--export interface BoardCsvInput {- summary?: BoardSummary;- heatmap?: BoardHeatmap;- categories?: BoardCategories;-}--type Row = [string, string, string, string | number];--/**- * Build the rows for whatever the view actually holds.- *- * Sections the view has not loaded are omitted rather than written as zeros —- * an empty `daily` section says "not loaded", a run of zeros would claim "no- * activity", and those are different facts.- */-export function boardCsvRows(input: BoardCsvInput): Row[] {- const rows: Row[] = [];-- if (input.summary) {- const { totals, window, streak_days, longest_streak, window_days } =- input.summary;- for (const [metric, value] of Object.entries(totals)) {- // first_day is a date, not a measurement — it belongs in the date column.- if (metric === "first_day") {- if (value) rows.push(["totals", String(value), "first_day", ""]);- continue;- }- rows.push(["totals", "", metric, value as number]);- }- rows.push(["totals", "", "streak_days", streak_days]);- rows.push(["totals", "", "longest_streak", longest_streak]);-- rows.push(["window", "", "window_days", window_days]);- for (const [metric, value] of Object.entries(window)) {- // A null rate means "not enough data to compute", which an empty cell- // carries correctly and a 0 would not.- rows.push(["window", "", metric, value === null ? "" : (value as number)]);- }- }-- if (input.heatmap) {- for (const cell of input.heatmap.cells) {- const { date, ...metrics } = cell;- for (const [metric, value] of Object.entries(metrics)) {- rows.push(["daily", date, metric, value as number]);- }- }- }-- if (input.categories) {- for (const entry of input.categories.categories) {- rows.push(["categories", "", entry.category, entry.count]);- }- }-- return rows;-}--/**- * Render the full document.- *- * CRLF line endings are what RFC 4180 specifies and what Excel expects; every- * other reader accepts them. The leading BOM is there so a double-clicked file- * opens with correct umlauts in Excel — pandas strips it, so the file stays- * usable in both places.- */-export function boardCsv(input: BoardCsvInput): string {- const lines = [- CSV_HEADER.join(","),- ...boardCsvRows(input).map((row) => row.map(csvField).join(",")),- ];- return "" + lines.join("\r\n") + "\r\n";-}--/** `jarvis-board-2026-08-22.csv` — ISO in the name too, so files sort by date. */-export function boardCsvFilename(now: Date = new Date()): string {- const iso = now.toISOString().slice(0, 10);- return `jarvis-board-${iso}.csv`;-}diff --git a/jarvis/ui/web/frontend/src/lib/boardInsights.test.ts b/jarvis/ui/web/frontend/src/lib/boardInsights.test.tsnew file mode 100644index 0000000000..c3159eb6c1--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/boardInsights.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from "vitest";++import type { InsightsDay } from "@/hooks/useBoardInsights";+import {+ actionsOf,+ calendarWeeks,+ intensityLevels,+ milestoneProgress,+ minutesSaved,+ peakSlot,+ trendPercent,+ weeklyTotals,+} from "@/lib/boardInsights";++function day(date: string, over: Partial<InsightsDay> = {}): InsightsDay {+ return {+ date,+ dictations: 0,+ dictation_words: 0,+ voice_sessions: 0,+ voice_words: 0,+ chat_messages: 0,+ agent_sessions: 0,+ agent_turns: 0,+ ...over,+ };+}++describe("board insights maths", () => {+ it("counts every started thing once per day", () => {+ expect(+ actionsOf(day("2026-10-01", { dictations: 3, voice_sessions: 1, chat_messages: 2, agent_sessions: 4, agent_turns: 99 })),+ ).toBe(10);+ });++ it("splits non-zero values into quartile levels and keeps zero at level 0", () => {+ const level = intensityLevels([0, 1, 2, 3, 4, 100]);+ expect(level(0)).toBe(0);+ expect(level(1)).toBe(1);+ expect(level(100)).toBe(4);+ });++ it("lays days into Monday-first weeks with month starts", () => {+ // 2026-09-30 is a Wednesday.+ // The API always sends a gap-free series.+ const dates = ["2026-09-30", "2026-10-01", "2026-10-02", "2026-10-03", "2026-10-04", "2026-10-05"];+ const weeks = calendarWeeks(dates.map((d) => day(d)));+ expect(weeks[0].days.slice(0, 2)).toEqual([null, null]);+ expect(weeks[0].days[2]?.date).toBe("2026-09-30");+ // The week holding the 1st of October is labelled October.+ expect(weeks[0].monthStart).toBe(9);+ expect(weeks[1].days[0]?.date).toBe("2026-10-05");+ expect(weeks[1].days.slice(1)).toEqual(Array(6).fill(null));+ });++ it("never reports negative time saved", () => {+ expect(minutesSaved(400, 60, 40)).toBe(9);+ expect(minutesSaved(10, 600, 40)).toBe(0);+ });++ it("has no trend without a previous period", () => {+ expect(trendPercent(50, 0)).toBeNull();+ expect(trendPercent(150, 100)).toBe(50);+ });++ it("finds the busiest weekday and hour", () => {+ const punch = Array.from({ length: 7 }, () => Array(24).fill(0));+ punch[2][10] = 7;+ expect(peakSlot(punch)).toEqual({ weekday: 2, hour: 10, value: 7 });+ expect(peakSlot(Array.from({ length: 7 }, () => Array(24).fill(0)))).toBeNull();+ });++ it("sums words per week", () => {+ const weeks = weeklyTotals(+ [day("2026-09-28", { dictation_words: 5 }), day("2026-09-29", { voice_words: 7 })],+ 4,+ );+ expect(weeks).toEqual([{ start: "2026-09-28", words: 12, agentSessions: 0 }]);+ });++ it("brackets the word count between milestones", () => {+ expect(milestoneProgress(261_917)).toEqual({ previous: 250_000, next: 500_000 });+ expect(milestoneProgress(0)).toEqual({ previous: 0, next: 1_000 });+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/boardInsights.ts b/jarvis/ui/web/frontend/src/lib/boardInsights.tsnew file mode 100644index 0000000000..8fdabf60df--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/boardInsights.ts@@ -0,0 +1,225 @@+/**+ * Pure maths behind the Board page. No React, no fetch — every figure the+ * page draws is derived here from the `/api/board/insights` answer, so the+ * derivations are testable on their own and named in one place.+ */+import type { BoardInsights, InsightsDay } from "@/hooks/useBoardInsights";+import { prettyProviderName } from "@/lib/prettyProviderName";++/** Things the user started on a day: each dictation, voice session, chat+ * message and coding-agent session counts once. */+export function actionsOf(day: InsightsDay): number {+ return day.dictations + day.voice_sessions + day.chat_messages + day.agent_sessions;+}++/** Words the user gave Jarvis on a day — dictated plus said in voice sessions. */+export function wordsOf(day: InsightsDay): number {+ return day.dictation_words + day.voice_words;+}++/**+ * Intensity level 0..4 per value. 0 is "nothing"; 1..4 split the non-zero+ * values at their quartiles, so one record day does not flatten every other+ * day into the palest shade.+ */+export function intensityLevels(values: readonly number[]): (v: number) => 0 | 1 | 2 | 3 | 4 {+ const sorted = values.filter((v) => v > 0).sort((a, b) => a - b);+ if (sorted.length === 0) return () => 0;+ const q = (p: number) => sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];+ const [q1, q2, q3] = [q(0.25), q(0.5), q(0.75)];+ return (v) => {+ if (v <= 0) return 0;+ if (v <= q1) return 1;+ if (v <= q2) return 2;+ if (v <= q3) return 3;+ return 4;+ };+}++export interface CalendarWeek {+ /** Seven slots, Monday first; `null` pads days outside the series. */+ days: (InsightsDay | null)[];+ /** Set on the first week of a month: the month index 0..11. */+ monthStart: number | null;+}++function parseDay(iso: string): Date {+ return new Date(`${iso}T00:00:00`);+}++/** Lay the daily series into Monday-first week columns. */+export function calendarWeeks(days: readonly InsightsDay[]): CalendarWeek[] {+ const weeks: CalendarWeek[] = [];+ let current: (InsightsDay | null)[] = [];+ let lastMonth = -1;+ let monthStart: number | null = null;+ for (const day of days) {+ const date = parseDay(day.date);+ const slot = (date.getDay() + 6) % 7;+ if (current.length === 0 && slot > 0) {+ current = Array(slot).fill(null);+ }+ if (date.getMonth() !== lastMonth) {+ lastMonth = date.getMonth();+ monthStart = lastMonth;+ }+ current.push(day);+ if (current.length === 7) {+ weeks.push({ days: current, monthStart });+ current = [];+ monthStart = null;+ }+ }+ if (current.length > 0) {+ while (current.length < 7) current.push(null);+ weeks.push({ days: current, monthStart });+ }+ return weeks;+}++/** Minutes saved by dictating instead of typing at `typingWpm`. Never negative. */+export function minutesSaved(words: number, seconds: number, typingWpm: number): number {+ if (typingWpm <= 0) return 0;+ return Math.max(0, words / typingWpm - seconds / 60);+}++export function wordsPerMinute(words: number, seconds: number): number {+ return seconds > 0 ? words / (seconds / 60) : 0;+}++/** Percent change, or `null` when there is nothing to compare against. */+export function trendPercent(current: number, previous: number): number | null {+ if (previous <= 0) return null;+ return Math.round(((current - previous) / previous) * 100);+}++export interface MixRow {+ key: "dictations" | "agent_sessions" | "chat_messages" | "voice_sessions";+ count: number;+ share: number;+}++/** How the user reaches Jarvis — every row a thing they started, by share. */+export function usageMix(data: BoardInsights): MixRow[] {+ const rows: Omit<MixRow, "share">[] = [+ { key: "dictations", count: data.dictation.dictations },+ { key: "agent_sessions", count: data.agents.sessions },+ { key: "chat_messages", count: data.chats.messages },+ { key: "voice_sessions", count: data.voice.sessions },+ ];+ const total = rows.reduce((sum, r) => sum + r.count, 0);+ return rows+ .map((r) => ({ ...r, share: total ? r.count / total : 0 }))+ .sort((a, b) => b.count - a.count);+}++export interface PeakSlot {+ weekday: number; // 0 = Monday+ hour: number;+ value: number;+}++export function peakSlot(punch: readonly (readonly number[])[]): PeakSlot | null {+ let best: PeakSlot | null = null;+ punch.forEach((row, weekday) =>+ row.forEach((value, hour) => {+ if (value > 0 && (!best || value > best.value)) best = { weekday, hour, value };+ }),+ );+ return best;+}++export function hourTotals(punch: readonly (readonly number[])[]): number[] {+ return Array.from({ length: 24 }, (_, h) => punch.reduce((s, row) => s + (row[h] ?? 0), 0));+}++export function weekdayTotals(punch: readonly (readonly number[])[]): number[] {+ return punch.map((row) => row.reduce((s, v) => s + v, 0));+}++export interface WeekTotal {+ start: string;+ words: number;+ agentSessions: number;+}++/**+ * The last `count` Monday-first weeks of the series, oldest first. Leading+ * empty weeks are dropped (down to `minimum`), so a new user's chart starts at+ * their first week instead of a row of blanks.+ */+export function weeklyTotals(+ days: readonly InsightsDay[],+ count: number,+ minimum = count,+): WeekTotal[] {+ const totals = calendarWeeks(days).slice(-count).map((week) => {+ const present = week.days.filter((d): d is InsightsDay => d !== null);+ return {+ start: present[0]?.date ?? "",+ words: present.reduce((s, d) => s + wordsOf(d), 0),+ agentSessions: present.reduce((s, d) => s + d.agent_sessions, 0),+ };+ });+ const first = totals.findIndex((w) => w.words > 0);+ const cut = first < 0 ? 0 : Math.min(first, Math.max(0, totals.length - minimum));+ return totals.slice(cut);+}++const MILESTONES = [+ 1_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 2_500_000,+ 5_000_000, 10_000_000,+];++/** The milestone just passed and the next one, for the words progress bar. */+export function milestoneProgress(words: number): { previous: number; next: number } {+ const next = MILESTONES.find((m) => m > words) ?? Math.ceil((words + 1) / 10_000_000) * 10_000_000;+ const previous = [...MILESTONES].reverse().find((m) => m <= words) ?? 0;+ return { previous, next };+}++const AGENT_LABELS: Record<string, string> = {+ "claude-cli": "Claude Code",+ "codex-cli": "Codex",+ "agy-cli": "Antigravity",+ "grok-cli": "Grok CLI",+ "opencode-cli": "OpenCode",+ "kimi-cli": "Kimi CLI",+ "glm-cli": "GLM CLI",+ "cursor-cli": "Cursor CLI",+};++export function agentLabel(id: string): string {+ return AGENT_LABELS[id] ?? id.replace(/-cli$/, "");+}++const CHAT_PROVIDER_LABELS: Record<string, string> = {+ "claude-api": "Claude",+ "openai-codex": "Codex",+ antigravity: "Antigravity",+ "grok-build": "Grok Build",+};++export function chatProviderLabel(id: string): string {+ return CHAT_PROVIDER_LABELS[id] ?? prettyProviderName(id);+}++/** Short form for big counts, in the same locale as `toLocaleString()`. */+export function compactNumber(n: number): string {+ return new Intl.NumberFormat(undefined, {+ notation: n >= 10_000 ? "compact" : "standard",+ maximumFractionDigits: n >= 10_000 ? 1 : 0,+ }).format(n);+}++/** `{0}` substitution plus the `_one` plural key convention of the locales. */+export function plural(t: (k: string) => string, baseKey: string, n: number): string {+ return t(n === 1 ? `${baseKey}_one` : baseKey).replace("{0}", n.toLocaleString());+}++/** A local day as "3 Oct 2026" in the UI language. */+export function formatDay(iso: string, lang?: string): string {+ const d = new Date(`${iso}T00:00:00`);+ if (Number.isNaN(d.getTime())) return iso;+ return d.toLocaleDateString(lang, { day: "numeric", month: "short", year: "numeric" });+}diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsxindex 75984a3868..630f90b5f8 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx@@ -1,7 +1,7 @@/** Existing voice configurations remain readable without silently switching engines. */import { afterEach, describe, expect, it, vi } from "vitest";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { cleanup, render, screen } from "@testing-library/react";import type { ReactElement } from "react";function renderKeys(ui: ReactElement = <ApiKeysView />) {diff --git a/jarvis/ui/web/frontend/src/views/BoardView.tsx b/jarvis/ui/web/frontend/src/views/BoardView.tsxindex ccbc18c4fb..19ad2faf21 100644--- a/jarvis/ui/web/frontend/src/views/BoardView.tsx+++ b/jarvis/ui/web/frontend/src/views/BoardView.tsx@@ -1,291 +1,114 @@import { useState } from "react";-import { Download, Flame, Loader2, RefreshCw, Share2, Sparkles } from "lucide-react";-import { ViewHeader } from "@/views/ChatsView";-import { BoardCard } from "@/components/board/BoardCard";+import { Share2 } from "lucide-react";++import { PageHeader } from "@/components/layout/PageHeader";+import { TabBar } from "@/components/layout/SectionTabBar";+import { BoardIcon } from "@/components/icons/sectionIcons";import { ShareDialog } from "@/components/board/ShareDialog";-import { CategoryUsage } from "@/components/board/CategoryUsage";-import { ActivityHeatmap, HeatmapScale } from "@/components/board/ActivityHeatmap";-import {- WordsTrendChart,- TREND_JARVIS,- TREND_YOU,-} from "@/components/board/WordsTrendChart";-import {- useBoardCategories,- useBoardHeatmap,- useBoardRefresh,- useBoardSummary,-} from "@/hooks/useBoard";-import { boardCsv, boardCsvFilename } from "@/lib/boardCsv";-import { cn } from "@/lib/utils";+import { UsageTab } from "@/components/board/insights/UsageTab";+import { AgentsTab } from "@/components/board/insights/AgentsTab";+import { RhythmTab } from "@/components/board/insights/RhythmTab";+import { InsightCard, SkeletonBlock } from "@/components/board/insights/primitives";+import { useBoardInsights } from "@/hooks/useBoardInsights";+import { Button } from "@/components/ui/button";import { useT } from "@/i18n";-export function BoardView() {- const t = useT();- const summary = useBoardSummary();- const heatmap = useBoardHeatmap(365);- const categories = useBoardCategories();- const refresh = useBoardRefresh();- const [shareOpen, setShareOpen] = useState(false);+type Tab = "usage" | "agents" | "rhythm";- // Export exactly what the view is holding — a section that has not loaded is- // left out of the file rather than written as zeros, because "not loaded" and- // "no activity" are different facts.- const canExport = Boolean(summary.data || heatmap.data || categories.data);+const TAB_STORAGE_KEY = "jarvis.board.tab";- function handleExportCsv() {- const text = boardCsv({- summary: summary.data,- heatmap: heatmap.data,- categories: categories.data,- });- const blob = new Blob([text], { type: "text/csv;charset=utf-8" });- const url = URL.createObjectURL(blob);- const a = document.createElement("a");- a.href = url;- a.download = boardCsvFilename();- a.click();- URL.revokeObjectURL(url);+function readStoredTab(): Tab {+ try {+ const value = window.localStorage.getItem(TAB_STORAGE_KEY);+ if (value === "usage" || value === "agents" || value === "rhythm") return value;+ } catch {+ // Storage blocked (private window, previews): the default tab is fine.}+ return "usage";+}- const s = summary.data;- const userWords = s?.totals.user_words ?? 0;- const jarvisWords = s?.totals.jarvis_words ?? 0;- const sessions = s?.totals.session_count ?? 0;- const convHours = s?.totals.conversation_hours ?? 0;- const streak = s?.streak_days ?? 0;- const longest = s?.longest_streak ?? 0;- const activeDays = s?.totals.active_days ?? 0;- const avgWords = sessions ? Math.round(userWords / sessions) : 0;- const ratio = userWords ? jarvisWords / userWords : 0;-- const nf = (n: number) => n.toLocaleString();- const loading = summary.isLoading;+/**+ * The Board: how someone works with Jarvis, from the stores the app already+ * keeps on this computer — dictation, voice sessions, chats and the coding+ * agents. Three tabs, each sized to read at a glance.+ */+export function BoardView() {+ const t = useT();+ const insights = useBoardInsights();+ const [tab, setTabState] = useState<Tab>(readStoredTab);+ const [shareOpen, setShareOpen] = useState(false);+ const data = insights.data;- const metrics = [- {- label: t("board_view.hero.you_spoke"),- dot: TREND_YOU,- value: loading ? "—" : nf(userWords),- sub: t("board_view.hero.you_spoke_sub"),- },- {- label: t("board_view.hero.jarvis_spoke"),- dot: TREND_JARVIS,- value: loading ? "—" : nf(jarvisWords),- sub: t("board_view.hero.jarvis_spoke_sub"),- },- {- label: t("board_view.hero.streak"),- value: loading ? "—" : streak > 0 ? String(streak) : "—",- sub:- longest > 0- ? plural(t, "board_view.longest_streak", longest)- : plural(t, "board_view.hero.streak_sub", activeDays),- },- {- label: t("board_view.hero.talk_time"),- value: loading ? "—" : `${convHours.toFixed(1)} h`,- sub: plural(t, "board_view.hero.talk_time_sub", sessions),- },- ];+ const setTab = (next: Tab) => {+ setTabState(next);+ try {+ window.localStorage.setItem(TAB_STORAGE_KEY, next);+ } catch {+ // Remembering the tab is a convenience; losing it changes nothing else.+ }+ };return (- <div className="flex h-full flex-col">- <ViewHeader- icon={<Sparkles className="h-4 w-4 text-primary" />}- title={t("board_view.title")}- subtitle={t("board_view.subtitle")}- right={- <div className="flex items-center gap-2">- <button- type="button"+ <div className="flex h-full min-h-0 flex-col">+ <div className="mx-auto w-full max-w-[1280px] px-6 lg:px-8">+ <PageHeader+ icon={<BoardIcon />}+ title={t("board_view.title")}+ description={t("board_insights.description")}+ actions={+ <Button+ variant="outline"+ size="sm"onClick={() => setShareOpen(true)}- disabled={loading || !s}- className={cn(- "inline-flex items-center gap-2 rounded-lg border border-sheen/[0.08] bg-sheen/[0.03] px-3 py-1.5 text-xs font-medium transition-colors",- "hover:border-primary/40 hover:bg-primary/[0.06]",- (loading || !s) && "opacity-50",- )}- title={t("board_view.share.button_tooltip")}+ disabled={!data}data-testid="board-share-button">- <Share2 className="h-3.5 w-3.5" />+ <Share2 className="h-4 w-4" />{t("board_view.share.button")}- </button>- <button- type="button"- onClick={handleExportCsv}- disabled={!canExport}- className={cn(- "inline-flex items-center gap-2 rounded-lg border border-sheen/[0.08] bg-sheen/[0.03] px-3 py-1.5 text-xs font-medium transition-colors",- "hover:border-primary/40 hover:bg-primary/[0.06]",- !canExport && "opacity-50",- )}- title={- canExport- ? t("board_view.export.button_tooltip")- : t("board_view.export.empty")- }- data-testid="board-export-csv-button"- >- <Download className="h-3.5 w-3.5" />- {t("board_view.export.button")}- </button>- <button- type="button"- onClick={() => refresh.mutate()}- disabled={refresh.isPending}- className={cn(- "inline-flex items-center gap-2 rounded-lg border border-sheen/[0.08] bg-sheen/[0.03] px-3 py-1.5 text-xs font-medium transition-colors",- "hover:border-primary/40 hover:bg-primary/[0.06]",- refresh.isPending && "opacity-60",- )}- title={t("board_view.refresh_tooltip")}- >- <RefreshCw className={cn("h-3.5 w-3.5", refresh.isPending && "animate-spin")} />- {t("board_view.refresh")}- </button>- </div>- }- />-- <div className="flex-1 overflow-y-auto scrollbar-jarvis">- <div className="mx-auto flex max-w-[1440px] flex-col gap-4 p-5 lg:gap-5 lg:p-6">- {summary.error && (- <div className="rounded-xl border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">- {t("board_view.load_error")}- </div>- )}-- {/* ── Hero band: four key numbers, hairline dividers ───────── */}- <BoardCard glow>- <div className="grid grid-cols-2 lg:grid-cols-4">- {metrics.map((m, i) => (- <Metric- key={i}- label={m.label}- value={m.value}- sub={m.sub}- dot={m.dot}- className={DIVIDERS[i]}- />- ))}- </div>- </BoardCard>+ </Button>+ }+ tabs={+ <TabBar+ tabs={[+ { id: "usage", label: t("board_insights.tabs.usage") },+ { id: "agents", label: t("board_insights.tabs.agents") },+ { id: "rhythm", label: t("board_insights.tabs.rhythm") },+ ]}+ active={tab}+ onChange={(id) => setTab(id as Tab)}+ />+ }+ />+ </div>- {/* Slim caption line of secondary stats. */}- {!loading && s && (- <p className="-mt-1 px-1 text-xs text-muted-foreground">- {t("board_view.micro.avg_words").replace("{0}", nf(avgWords))}- <Dot />- {t("board_view.micro.ratio").replace("{0}", ratio.toFixed(1))}- {s.totals.first_day && (- <>- <Dot />- {t("board_view.micro.active_since").replace("{0}", formatDay(s.totals.first_day))}- </>- )}- </p>+ <div className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis">+ <div className="mx-auto w-full max-w-[1280px] px-6 py-6 lg:px-8">+ {insights.error && !data ? (+ <InsightCard>+ <p className="text-sm text-muted-foreground">{t("board_view.load_error")}</p>+ </InsightCard>+ ) : !data ? (+ <BoardSkeleton />+ ) : tab === "usage" ? (+ <UsageTab data={data} />+ ) : tab === "agents" ? (+ <AgentsTab data={data} />+ ) : (+ <RhythmTab data={data} />)}-- {/* ── Words-over-time chart + category usage ───────────────── */}- <div className="grid grid-cols-1 gap-4 lg:grid-cols-[1.55fr_1fr] lg:gap-5">- <BoardCard className="flex flex-col p-5">- <div className="mb-3 flex items-center justify-between gap-3">- <div>- <h3 className="font-display text-sm font-semibold">- {t("board_view.chart_title")}- </h3>- <p className="text-xs text-muted-foreground">- {t("board_view.activity_subtitle")}- </p>- </div>- <div className="flex items-center gap-3 text-xs text-muted-foreground">- <LegendDot color={TREND_YOU} label={t("board_view.hero.you_spoke")} />- <LegendDot color={TREND_JARVIS} label={t("board_view.hero.jarvis_spoke")} />- </div>- </div>- <div className="h-44 lg:h-52">- {heatmap.data ? (- <WordsTrendChart cells={heatmap.data.cells} />- ) : (- <Skeleton className="h-full" />- )}- </div>- </BoardCard>-- <BoardCard className="flex flex-col p-5">- <div className="mb-3">- <h3 className="font-display text-sm font-semibold">- {t("board_view.categories_title")}- </h3>- <p className="text-xs text-muted-foreground">- {t("board_view.categories_subtitle")}- </p>- </div>- <div className="flex flex-1 flex-col justify-center">- {categories.data ? (- <CategoryUsage data={categories.data} />- ) : (- <div className="flex items-center gap-2 text-xs text-muted-foreground">- <Loader2 className="h-3.5 w-3.5 animate-spin" />- {t("board_view.loading")}- </div>- )}- </div>- </BoardCard>- </div>-- {/* ── Activity calendar ────────────────────────────────────── */}- <BoardCard className="p-5">- <div className="mb-4 flex flex-wrap items-center justify-between gap-3">- <div>- <h3 className="font-display text-sm font-semibold">- {t("board_view.activity_title")}- </h3>- <p className="text-xs text-muted-foreground">- {t("board_view.activity_heatmap_hint")}- </p>- </div>- <div className="flex items-center gap-2">- {streak > 0 && (- <span className="inline-flex items-center gap-1 rounded-full border border-primary/30 bg-primary/[0.08] px-2.5 py-1 text-xs font-medium text-primary">- <Flame className="h-3 w-3" />- {plural(t, "board_view.activity_streak_badge", streak)}- </span>- )}- {longest > 0 && (- <span className="rounded-full border border-sheen/[0.08] bg-sheen/[0.03] px-2.5 py-1 text-xs text-muted-foreground">- {plural(t, "board_view.longest_streak", longest)}- </span>- )}- </div>- </div>- {heatmap.data ? (- <div className="space-y-3">- <div className="overflow-x-auto pb-1">- <ActivityHeatmap cells={heatmap.data.cells} />- </div>- <HeatmapScale />- </div>- ) : (- <Skeleton className="h-28" />- )}- </BoardCard></div></div>- {s && (+ {data && (<ShareDialogopen={shareOpen}onOpenChange={setShareOpen}stats={{- userWords,- jarvisWords,- conversationHours: convHours,- sessionCount: sessions,- longestStreak: longest,+ userWords: data.dictation.words + data.voice.user_words,+ jarvisWords: data.voice.jarvis_words,+ conversationHours: data.voice.seconds / 3600,+ sessionCount: data.voice.sessions,+ longestStreak: data.streak.longest_days,}}/>)}@@ -293,75 +116,26 @@ export function BoardView() {);}-// -----------------------------------------------------------------------// Building blocks-// ------------------------------------------------------------------------// Per-index hairline dividers for a 2-col (mobile) / 4-col (desktop) grid.-const DIVIDERS = [- "",- "border-l border-sheen/[0.06]",- "border-t border-sheen/[0.06] lg:border-t-0 lg:border-l",- "border-l border-t border-sheen/[0.06] lg:border-t-0",-];--function Metric({- label,- value,- sub,- dot,- className,-}: {- label: string;- value: string;- sub?: string;- dot?: string;- className?: string;-}) {+function BoardSkeleton() {return (- <div className={cn("flex flex-col gap-2.5 px-5 py-5 lg:px-6", className)}>- <div className="flex items-center gap-2 text-micro font-medium uppercase tracking-[0.14em] text-muted-foreground">- {dot && (- <span className="h-1.5 w-1.5 rounded-full" style={{ background: dot }} />- )}- <span className="truncate">{label}</span>+ <div className="flex flex-col gap-4" data-testid="board-skeleton">+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">+ {[0, 1, 2].map((i) => (+ <InsightCard key={i} className="h-56">+ <SkeletonBlock className="h-7 w-24" />+ <SkeletonBlock className="mt-3 h-3 w-36" />+ <SkeletonBlock className="mt-auto h-20 w-full" />+ </InsightCard>+ ))}</div>- <div className="font-display text-2xl font-semibold leading-none tracking-tight tabular-nums">- {value}+ <div className="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]">+ {[0, 1].map((i) => (+ <InsightCard key={i} className="h-72">+ <SkeletonBlock className="h-6 w-40" />+ <SkeletonBlock className="mt-auto h-44 w-full" />+ </InsightCard>+ ))}</div>- {sub && <div className="truncate text-xs text-muted-foreground">{sub}</div>}</div>);}--function LegendDot({ color, label }: { color: string; label: string }) {- return (- <span className="inline-flex items-center gap-1.5">- <span className="h-2 w-2 rounded-full" style={{ background: color }} />- {label}- </span>- );-}--function Dot() {- return <span className="px-1.5 text-muted-foreground/40">·</span>;-}--function Skeleton({ className }: { className?: string }) {- return <div className={cn("w-full animate-pulse rounded-lg bg-sheen/[0.04]", className)} />;-}--function plural(t: (k: string) => string, baseKey: string, n: number): string {- const key = n === 1 ? `${baseKey}_one` : baseKey;- return t(key).replace("{0}", n.toLocaleString());-}--function formatDay(iso: string): string {- const d = new Date(iso + "T00:00:00");- if (Number.isNaN(d.getTime())) return iso;- return d.toLocaleDateString(undefined, {- day: "numeric",- month: "short",- year: "numeric",- });-}diff --git a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx b/jarvis/ui/web/frontend/src/views/DictationView.test.tsxindex f0d8bc8c91..5fd3d4685a 100644--- a/jarvis/ui/web/frontend/src/views/DictationView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/DictationView.test.tsx@@ -13,7 +13,9 @@* in this repo — assertions use toBeTruthy()/toBeNull().*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactElement } from "react";// ViewHeader lives in ChatsView, which drags in the whole chat surface; the// view only needs its shape.@@ -27,6 +29,12 @@ vi.mock("@/lib/clipboard", () => ({ robustCopy: copyMock }));import { DictationView } from "@/views/DictationView";import { setUiLanguage } from "@/i18n";+/** The greeting reads the profile name through react-query. */+function render(ui: ReactElement) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return rtlRender(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);+}+interface RouteResult {status?: number;body: unknown;@@ -195,6 +203,7 @@ function defaultRoutes("GET /api/dictation/history": () => ({ body: { entries, count: entries.length } }),"GET /api/dictation/stats": () => ({ body: STATS }),"PUT /api/settings/ui-language": () => ({ body: { ok: true } }),+ "GET /api/profile": () => ({ body: { user: { name: "Ada" } } }),...extra,};}@@ -459,3 +468,53 @@ describe("DictationView header", () => {expect(container.querySelector("header")).toBeNull();});});++describe("DictationView home layout", () => {+ it("greets the person by their profile name", async () => {+ installFetchMock(defaultRoutes());+ render(<DictationView />);++ await waitFor(() =>+ expect(screen.getByTestId("dictation-welcome").textContent).toBe("Welcome back, Ada"),+ );+ });++ it("puts the dictation key in the hero title, pretty-printed", async () => {+ installFetchMock(defaultRoutes());+ render(<DictationView />);++ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());+ const hero = screen.getByTestId("dictation-hero");+ expect(hero.querySelector("h2")?.textContent).toContain("to dictate");+ expect(hero.querySelector("h2")?.textContent).not.toContain("ctrl+right_alt+j");+ expect(screen.getByTestId("dictation-state").textContent).toBe("Ready");+ });++ it("draws fourteen days of activity", async () => {+ installFetchMock(defaultRoutes());+ render(<DictationView />);++ await waitFor(() => expect(screen.queryByTestId("dictation-activity")).toBeTruthy());+ expect(screen.getByTestId("dictation-activity").children).toHaveLength(14);+ });++ it("keeps what was heard one click away instead of under every row", async () => {+ installFetchMock(defaultRoutes([TODAY_ENTRY]));+ render(<DictationView />);++ await waitFor(() => expect(screen.queryByTestId("dictation-history")).toBeTruthy());+ expect(screen.queryByTestId("dictation-raw-text")).toBeNull();+ fireEvent.click(screen.getByTestId("dictation-toggle-raw"));+ expect(screen.getByTestId("dictation-raw-text").textContent).toContain(+ "so uh send the report",+ );+ });++ it("shows a designed empty surface when nothing was dictated yet", async () => {+ installFetchMock(defaultRoutes([]));+ render(<DictationView />);++ await waitFor(() => expect(screen.queryByTestId("dictation-empty")).toBeTruthy());+ expect(screen.queryByTestId("dictation-history")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/DictationView.tsx b/jarvis/ui/web/frontend/src/views/DictationView.tsxindex fab536627d..10f83d76d8 100644--- a/jarvis/ui/web/frontend/src/views/DictationView.tsx+++ b/jarvis/ui/web/frontend/src/views/DictationView.tsx@@ -1,58 +1,58 @@import { useMemo, useState } from "react";-import {- AlertTriangle,- Keyboard,- Loader2,- Mic,- Search,- Square,- Trash2,-} from "lucide-react";+import { AlertTriangle, Mic, Search, Trash2 } from "lucide-react";import { ViewHeader } from "@/views/ChatsView";import { Button } from "@/components/ui/button";-import { Card } from "@/components/ui/card";-import { EmptyState } from "@/components/layout/EmptyState";-import { PanelSkeleton, SkeletonBar } from "@/components/layout/PanelSkeleton";+import { SkeletonBar } from "@/components/layout/PanelSkeleton";import { useDictation, type DictationEntry } from "@/hooks/useDictation";-import { DictationStatsBar } from "@/views/voice/DictationStatsBar";+import { useUserName } from "@/hooks/useUserName";+import { DictationHero } from "@/views/voice/DictationHero";+import { DictationStatsCard } from "@/views/voice/DictationStatsCard";+import {+ DictationEngineCard,+ DictationVocabularyCard,+} from "@/views/voice/DictationSideCards";import { DictationHistoryGroup } from "@/views/voice/DictationHistoryGroup";import { useEventStore } from "@/store/events";-import { useT } from "@/i18n";+import { fill, useT } from "@/i18n";/**- * "Dictation" section — hold a key, speak, and the text lands in whatever text- * field currently has focus.+ * "Dictation" — the first tab of the voice section: hold a key, speak, and the+ * text lands in whatever field has focus, in any app.+ *+ * The screen is built like a home page for the feature rather than a settings+ * panel:+ *+ * Welcome back, Ruben+ * ┌───────────────────────────── hero ─┐ ┌ stats ──────┐+ * │ Hold [Ctrl + Alt] to dictate 📷 │ │ 241.2K words│+ * │ [Start dictating] [Change shortcut]│ │ 149 wpm │+ * └────────────────────────────────────┘ │ ▁▃▅▂▇ 14 d │+ * TODAY [🔍 ] │ ├─────────────┤+ * ┌ 4:12 PM transcript … ⧉ ↺ 🗑 ──┐ │ Recognition │+ * └────────────────────────────────────┘ │ Dictionary →│+ *+ * The one instruction a newcomer needs is the largest thing on the screen,+ * the numbers sit beside it instead of above the history, and the history is+ * a journal of days with a time column — something you read back, not a log.+ * Below `xl` the side column folds in between the hero and the history.*- * Four things this view deliberately makes visible rather than hiding:+ * Four things this view deliberately keeps visible:** 1. **Whether insertion can work at all.** On Wayland, on a headless host, or* while an elevated window is in front, the OS blocks one program from- * typing into another — and does so silently. The notice says it up front so- * "nothing happened" is never a mystery.- * 2. **What the filler cleanup changed.** Every entry keeps the raw transcript- * next to the inserted one, so a wrong rule is findable instead of merely- * suspected.- * 3. **What actually became of each dictation.** The outcome badge is- * translated from a fixed vocabulary — "Could not insert" is a different- * story from "Nothing heard", and the row says which one happened.+ * typing into another — silently. The notice says so up front.+ * 2. **What the cleanup changed.** Every row keeps the raw transcript one click+ * away, so a wrong rule is findable instead of merely suspected.+ * 3. **What became of each dictation.** The outcome is translated from a fixed+ * vocabulary; only faults and partial deliveries get a coloured badge.* 4. **That deleting is recoverable.** The trash icon discards; the entry stays- * listed, restorable, until the second, explicit "Delete permanently" step.+ * listed, restorable, until the explicit "Delete permanently" step.*- * What is deliberately NOT here any more: the "How dictation behaves" settings- * block — the paste shortcut, the delivery method, the insertion target and the- * three cleanup/history switches. Every one of them shipped a sensible default,- * and a wall of six controls in front of the feature made a thing that "just- * works" look like something to be configured first. The `[dictation]` config- * keys and their REST route (`PUT /api/dictation/settings`, hence- * `jarvis api dictation ...`) are untouched, so an install that genuinely needs- * a different paste shortcut can still set one — it is simply no longer the- * first thing this screen shows. The "Key behaviour (hold/toggle)" dropdown- * left earlier for the same reason: the two dictation shortcuts in the voice- * section's Shortcuts tab are the source of truth for hold-vs-hands-free.- *- * The screen is three groups — state, numbers, history — separated by 32px and- * bounded at the reading measure, because everything on it is either a card or- * a transcript and neither earns the full width of a desktop window.+ * Deliberately NOT here: the "How dictation behaves" settings block. Every one+ * of its controls shipped a sensible default, and a wall of switches in front+ * of the feature made a thing that "just works" look like something to+ * configure first. The `[dictation]` config keys and `PUT+ * /api/dictation/settings` (hence `jarvis api dictation ...`) are untouched.** Backed by /api/dictation (status/start/stop/history/stats) via useDictation.*/@@ -69,6 +69,7 @@ export interface DictationViewProps {export function DictationView({ hideHeader = false }: DictationViewProps = {}) {const t = useT();+ const userName = useUserName();const {status,entries,@@ -84,6 +85,7 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {clearHistory,} = useDictation();const pushToast = useEventStore((s) => s.pushToast);+ const setActiveSection = useEventStore((s) => s.setActiveSection);const [busy, setBusy] = useState(false);const [query, setQuery] = useState("");const [busyIds, setBusyIds] = useState<ReadonlySet<string>>(new Set());@@ -155,22 +157,15 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {const q = query.trim().toLowerCase();if (!q) return entries;return entries.filter(- (e) =>- e.text.toLowerCase().includes(q) || e.raw_text.toLowerCase().includes(q),+ (e) => e.text.toLowerCase().includes(q) || e.raw_text.toLowerCase().includes(q),);}, [entries, query]);const groups = useMemo(() => groupByDay(filtered), [filtered]);- // Life / neutral / fault, and nothing in between. A recording session is the- // one thing on this screen that is actually running, so it is the one thing- // wearing --success; "ready" is a neutral idle, and a machine that cannot- // dictate at all is a fault rather than a dimmer shade of ready.- const dotFill = status?.active- ? "bg-success motion-safe:animate-pulse"- : status?.available- ? "bg-muted-foreground"- : "bg-destructive";+ const greeting = fill(t("dictation.welcome"), {+ name_part: userName ? `, ${userName}` : "",+ });return (<div className="flex h-full flex-col">@@ -181,233 +176,180 @@ export function DictationView({ hideHeader = false }: DictationViewProps = {}) {subtitle={t("dictation.description")}/>)}- <div className="flex-1 overflow-y-auto scrollbar-jarvis p-6">- <div className="mx-auto flex max-w-reading flex-col gap-group">- {error && <p className="text-meta text-destructive">{error}</p>}+ <div className="flex-1 overflow-y-auto scrollbar-jarvis">+ <div className="mx-auto w-full max-w-[1120px] px-6 pb-12 pt-8">+ <h1+ className="text-xl font-semibold text-foreground-strong"+ data-testid="dictation-welcome"+ >+ {greeting}+ </h1>- {/* --- Insertion notice: the silent-failure paths, made loud. ---- Degraded, not broken — the words still reach the clipboard — so- it is a --warning glyph on an ordinary card, never a washed- panel that claims the whole screen has failed. */}- {blocked && (- <Card- className="flex items-start gap-3 p-5"- data-testid="dictation-insert-warning"- >- <AlertTriangle- aria-hidden="true"- className="mt-0.5 h-4 w-4 shrink-0 text-warning"- />- <div className="min-w-0">- <h4 className="text-title font-semibold text-foreground-strong">- {t("dictation.cannot_insert_title")}- </h4>- <p className="mt-1 text-meta text-muted-foreground">- {status?.insertion.detail || t("dictation.cannot_insert_generic")}- </p>- </div>- </Card>- )}+ <div className="mt-5 grid grid-cols-1 gap-6 [grid-template-areas:'hero'_'side'_'list'] xl:grid-cols-[minmax(0,1fr)_300px] xl:grid-rows-[auto_1fr] xl:[grid-template-areas:'hero_side'_'list_side']">+ <div className="flex min-w-0 flex-col gap-4 [grid-area:hero]">+ {error && <p className="text-meta text-destructive">{error}</p>}- {/* --- State, and the one primary action on the screen. --- */}- <Card className="p-5">- {loading ? (- // The real card at its real height with bars where the state- // line and the button will be — never a centred grey word, which- // is indistinguishable from a section that failed.- <div- role="status"- aria-busy="true"- aria-label={t("dictation.loading")}- className="flex items-center justify-between gap-4"- >- <div className="flex min-w-0 flex-1 flex-col gap-2">- <SkeletonBar className="h-4 w-32" />- <SkeletonBar className="h-3 w-3/5" />- </div>- <SkeletonBar className="h-9 w-32 shrink-0" />- </div>- ) : (- <div className="flex flex-wrap items-center justify-between gap-4">- <div className="min-w-0">- <div className="flex items-center gap-2">- <span- className={`h-2 w-2 shrink-0 rounded-full ${dotFill}`}- />- <span className="text-title font-semibold text-foreground-strong">- {status?.active- ? t("dictation.state_active")- : status?.available- ? t("dictation.state_ready")- : t("dictation.state_unavailable")}- </span>- </div>- <p className="mt-1 text-meta text-muted-foreground">- {status?.available- ? status.hotkey- ? t("dictation.shortcut_set").replace("{0}", status.hotkey)- : t("dictation.shortcut_unset")- : status?.reason || t("dictation.state_unavailable")}- </p>- {/* Which recognizer really answers the next press (P-41):- the settings name one, the lane may hold another. */}- {status?.available && status.engine?.provider && (+ {/* The silent-failure paths, made loud. Degraded, not broken —+ the words still reach the clipboard — so a --warning glyph+ on an ordinary card, never a washed panel. */}+ {blocked && (+ <div+ className="flex items-start gap-3 rounded-xl border border-border bg-card p-5 shadow-rim"+ data-testid="dictation-insert-warning"+ >+ <AlertTriangle+ aria-hidden="true"+ className="mt-0.5 h-4 w-4 shrink-0 text-warning"+ />+ <div className="min-w-0">+ <h4 className="text-title font-semibold text-foreground-strong">+ {t("dictation.cannot_insert_title")}+ </h4><p className="mt-1 text-meta text-muted-foreground">- {status.engine.local- ? t("dictation.engine_local")- .replace("{0}", status.engine.model || status.engine.provider)- .replace("{1}", status.engine.fallback || "—")- : t("dictation.engine_cloud").replace("{0}", status.engine.provider)}- {!status.engine.local && status.engine.detail- ? ` ${t("dictation.engine_local_off").replace("{0}", status.engine.detail)}`- : ""}+ {status?.insertion.detail || t("dictation.cannot_insert_generic")}</p>- )}+ </div></div>- <Button- className="gap-2"- disabled={busy || !status?.available}- data-testid="dictation-toggle"- onClick={() => void onToggle()}- >- {busy ? (- <Loader2- aria-hidden="true"- className="h-4 w-4 animate-spin motion-reduce:animate-none"- />- ) : status?.active ? (- <Square aria-hidden="true" className="h-4 w-4" />- ) : (- <Mic aria-hidden="true" className="h-4 w-4" />- )}- {status?.active ? t("dictation.stop") : t("dictation.start")}- </Button>- </div>- )}- {!status?.hotkey && status?.available && (- <p className="mt-block flex items-center gap-2 text-meta text-muted-foreground">- <Keyboard aria-hidden="true" className="h-3.5 w-3.5 shrink-0" />- {t("dictation.assign_hint")}- </p>- )}- </Card>-- {/* --- How much you dictate, honestly windowed. ---- While the request is in flight the three tiles stand at their- real size as empty bars. Rendering the card with zeros in it- would not read as loading; it would read as a person who has- never dictated anything. */}- {loading ? (- <Card className="p-5">- <SkeletonBar className="h-3 w-24" />- <div className="mt-stack grid gap-stack sm:grid-cols-3">- <SkeletonBar className="h-[84px]" />- <SkeletonBar className="h-[84px]" />- <SkeletonBar className="h-[84px]" />- </div>- </Card>- ) : (- stats && <DictationStatsBar stats={stats} />- )}+ )}- {/* --- History. ---- With nothing in it there is no list to frame, so the card, its- title, its hint and its search field all go and the designed- empty surface stands alone. */}- {loading ? (- <Card className="p-5">- <SkeletonBar className="h-4 w-40" />- <SkeletonBar className="mt-block h-9 w-full" />- <PanelSkeleton- className="mt-block"- rows={4}- rowHeight={56}- label={t("dictation.loading")}+ <DictationHero+ status={status}+ loading={loading}+ busy={busy}+ onToggle={() => void onToggle()}+ onOpenShortcuts={() => setActiveSection("voice-shortcuts")}/>- </Card>- ) : entries.length === 0 ? (- <EmptyState icon={<Mic />} body={t("dictation.history_empty")} />- ) : (- <Card className="p-5">- <div className="flex items-center justify-between gap-3">- <h4 className="text-title font-semibold text-foreground-strong">- {t("dictation.history_title")}- </h4>- <Button- size="sm"- variant="ghost"- className="gap-2 text-muted-foreground"- data-testid="dictation-clear-history"- onClick={() => {- void clearHistory().catch((e) =>- pushToast("error", (e as Error).message),- );- }}- >- <Trash2 aria-hidden="true" className="h-3.5 w-3.5" />- {t("dictation.clear_history")}- </Button>- </div>- <p className="mt-1 text-meta text-muted-foreground">- {t("dictation.clear_history_hint")}- </p>- {/* A field is a lift surface, not a hairline outline: it now- answers with a fill the way every other input in the app- does, and the focus ring is a rim rather than a third fill. */}- <div className="relative mt-block">- <Search- aria-hidden="true"- className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"- />- <input- value={query}- onChange={(e) => setQuery(e.target.value)}- placeholder={t("dictation.search_placeholder")}- aria-label={t("dictation.search_placeholder")}- data-testid="dictation-search"- className="h-9 w-full rounded-md bg-input pl-9 pr-3 text-body text-foreground placeholder:text-faint-foreground focus:outline-none focus:ring-2 focus:ring-border-strong"- />- </div>- {filtered.length === 0 ? (- /* Shared "nothing matched your search" string — the Dictionary- tab owns it and it is already localized everywhere. A lift- panel at the height the list would have had, so clearing the- query does not make the card jump. */- <div- className="mt-block rounded-md bg-secondary px-block py-10 text-center text-body text-muted-foreground"- data-testid="dictation-no-matches"- >- {t("dictionary.no_matches")}+ </div>++ {/* The side column. While loading it stands at its real size as+ empty bars — a card with zeros in it would read as a person+ who has never dictated anything. */}+ <aside className="flex min-w-0 flex-col gap-4 [grid-area:side] xl:sticky xl:top-0 xl:self-start">+ {loading ? (+ <div className="rounded-xl border border-border bg-card p-5 shadow-rim">+ <SkeletonBar className="h-3 w-20" />+ <div className="mt-4 flex flex-col gap-3">+ <SkeletonBar className="h-8 w-40" />+ <SkeletonBar className="h-8 w-32" />+ <SkeletonBar className="h-8 w-36" />+ </div>+ <SkeletonBar className="mt-5 h-14 w-full" /></div>) : (- <div className="mt-block" data-testid="dictation-history">- {groups.map((group) => (- <DictationHistoryGroup- key={group.key}- label={dayLabel(t, group.key)}- entries={group.entries}- busyIds={busyIds}- copiedId={copiedId}- onCopy={(entry) => void onCopy(entry)}- onRestore={(entry) => void onRestore(entry)}- onDiscard={(entry) => {- void withRowBusy(entry.id, () => discardEntry(entry.id));- }}- onDelete={(entry) => {- void withRowBusy(entry.id, () => deleteEntry(entry.id));- }}- />- ))}+ stats && <DictationStatsCard stats={stats} />+ )}+ {!loading && status?.available && status.engine?.provider && (+ <DictationEngineCard engine={status.engine} />+ )}+ <DictationVocabularyCard onOpen={() => setActiveSection("dictionary")} />+ </aside>++ <div className="min-w-0 [grid-area:list]">+ {loading ? (+ <div className="flex flex-col gap-2" aria-busy="true">+ <SkeletonBar className="h-3 w-24" />+ <SkeletonBar className="h-[220px] w-full rounded-xl" /></div>+ ) : entries.length === 0 ? (+ <EmptyHistory />+ ) : (+ <>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h2 className="text-base font-semibold text-foreground-strong">+ {t("dictation.history_title")}+ </h2>+ <div className="flex items-center gap-1">+ <div className="relative">+ <Search+ aria-hidden="true"+ className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"+ />+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t("dictation.search_placeholder")}+ aria-label={t("dictation.search_placeholder")}+ data-testid="dictation-search"+ className="h-8 w-56 rounded-md bg-input pl-8 pr-3 text-sm text-foreground placeholder:text-faint-foreground focus:outline-none focus:ring-2 focus:ring-border-strong"+ />+ </div>+ <Button+ size="sm"+ variant="ghost"+ className="gap-2 text-muted-foreground"+ title={t("dictation.clear_history_hint")}+ data-testid="dictation-clear-history"+ onClick={() => {+ void clearHistory().catch((e) =>+ pushToast("error", (e as Error).message),+ );+ }}+ >+ <Trash2 aria-hidden="true" className="h-3.5 w-3.5" />+ {t("dictation.clear_history")}+ </Button>+ </div>+ </div>++ {filtered.length === 0 ? (+ /* Shared "nothing matched your search" string — the+ Dictionary tab owns it and it is localized everywhere. */+ <div+ className="mt-4 rounded-xl border border-dashed border-border px-block py-12 text-center text-body text-muted-foreground"+ data-testid="dictation-no-matches"+ >+ {t("dictionary.no_matches")}+ </div>+ ) : (+ <div className="mt-4 flex flex-col gap-6" data-testid="dictation-history">+ {groups.map((group) => (+ <DictationHistoryGroup+ key={group.key}+ label={dayLabel(t, group.key)}+ entries={group.entries}+ busyIds={busyIds}+ copiedId={copiedId}+ onCopy={(entry) => void onCopy(entry)}+ onRestore={(entry) => void onRestore(entry)}+ onDiscard={(entry) => {+ void withRowBusy(entry.id, () => discardEntry(entry.id));+ }}+ onDelete={(entry) => {+ void withRowBusy(entry.id, () => deleteEntry(entry.id));+ }}+ />+ ))}+ </div>+ )}+ </>)}- </Card>- )}+ </div>+ </div></div></div></div>);}+/** The designed first-run surface: what will appear here, and how. */+function EmptyHistory() {+ const t = useT();+ return (+ <div+ className="flex flex-col items-center rounded-xl border border-dashed border-border px-6 py-12 text-center"+ data-testid="dictation-empty"+ >+ <span className="flex h-10 w-10 items-center justify-center rounded-full bg-secondary text-foreground">+ <Mic aria-hidden="true" className="h-4 w-4" />+ </span>+ <h3 className="mt-3 text-base font-semibold text-foreground-strong">+ {t("dictation.empty_title")}+ </h3>+ <p className="mt-1 max-w-sm text-sm text-muted-foreground">{t("dictation.empty_body")}</p>+ </div>+ );+}+interface DayGroup {/** Local calendar date, ISO `YYYY-MM-DD`. */key: string;@@ -450,7 +392,7 @@ function localDateKey(iso: string): string {return Number.isNaN(date.getTime()) ? iso : dateKey(date);}-/** "Today" / "Yesterday" / a locale-formatted date for everything older. */+/** "Today" / "Yesterday" / a long locale date ("August 23, 2026") otherwise. */function dayLabel(t: (key: string) => string, key: string): string {const now = new Date();if (key === dateKey(now)) return t("dictation.group.today");@@ -458,5 +400,7 @@ function dayLabel(t: (key: string) => string, key: string): string {yesterday.setDate(yesterday.getDate() - 1);if (key === dateKey(yesterday)) return t("dictation.group.yesterday");const parsed = new Date(`${key}T00:00:00`);- return Number.isNaN(parsed.getTime()) ? key : parsed.toLocaleDateString();+ return Number.isNaN(parsed.getTime())+ ? key+ : parsed.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });}diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHero.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHero.tsxnew file mode 100644index 0000000000..ea8bf7ec02--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHero.tsx@@ -0,0 +1,173 @@+import { Keyboard, Loader2, Mic, Square } from "lucide-react";++import type { DictationStatus } from "@/hooks/useDictation";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { formatCombo } from "@/views/settings/KeybindRow";+import heroImage from "@/assets/voice/dictation-hero.webp";++/**+ * The opening banner of the Dictation tab — the one thing a person needs to+ * know ("hold this key and speak") set large enough to be read from across the+ * desk, with the one action on the screen beside it.+ *+ * The banner is a photographic plate, and a photograph does not change with+ * the theme: it is the same dark scene in light and in dark mode. That is why+ * this component — and only this one — writes its inks as fixed white-on-dark+ * literals instead of theme tokens. A token-driven title would turn dark on a+ * light theme and vanish into the photo. The plate's own edge is a+ * `--border` ring, so on a dark page it still separates from the ground.+ *+ * The left of the plate is a solid fall-off into near-black (the image itself+ * is composed that way, and a gradient guarantees it on any aspect ratio), so+ * the text always sits on a calm surface rather than on the picture.+ */+export interface DictationHeroProps {+ status: DictationStatus | null;+ loading: boolean;+ busy: boolean;+ onToggle: () => void;+ onOpenShortcuts: () => void;+}++/** The plate's ground; also the gradient's start so the seam is invisible. */+const PLATE = "#050507";++export function DictationHero({+ status,+ loading,+ busy,+ onToggle,+ onOpenShortcuts,+}: DictationHeroProps) {+ const t = useT();+ const active = Boolean(status?.active);+ const available = Boolean(status?.available);+ const hotkey = status?.hotkey ?? "";+ const handsFree = status?.hotkey_toggle ?? "";++ // Life / neutral / fault — the same three states the status dot has always+ // had, now as a small pill on the plate instead of a separate card.+ const stateLabel = active+ ? t("dictation.state_active")+ : available+ ? t("dictation.state_ready")+ : t("dictation.state_unavailable");+ const dotFill = active+ ? "bg-success motion-safe:animate-pulse"+ : available+ ? "bg-white/70"+ : "bg-destructive";++ return (+ <section+ className="relative isolate overflow-hidden rounded-2xl ring-1 ring-border"+ style={{ backgroundColor: PLATE }}+ data-testid="dictation-hero"+ >+ <img+ src={heroImage}+ alt=""+ aria-hidden="true"+ draggable={false}+ className="pointer-events-none absolute inset-y-0 right-0 h-full w-full select-none object-cover object-right sm:w-[78%]"+ />+ <div+ aria-hidden="true"+ className="pointer-events-none absolute inset-0"+ style={{+ background: `linear-gradient(90deg, ${PLATE} 0%, ${PLATE} 30%, rgb(5 5 7 / 0.82) 48%, rgb(5 5 7 / 0.25) 72%, rgb(5 5 7 / 0) 100%)`,+ }}+ />++ <div className="relative flex min-h-[232px] flex-col justify-center gap-5 px-6 py-7 sm:px-9">+ <span+ className="inline-flex w-fit items-center gap-2 rounded-full bg-white/10 px-2.5 py-1 text-xs font-medium text-white/85 ring-1 ring-white/10 backdrop-blur-sm"+ data-testid="dictation-state"+ >+ <span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", dotFill)} />+ {loading ? t("dictation.loading") : stateLabel}+ </span>++ <div className="max-w-[520px]">+ <h2 className="text-[30px] font-semibold leading-[36px] tracking-[-0.02em] text-white [text-wrap:balance]">+ {loading ? (+ <span className="inline-block h-8 w-72 max-w-full animate-pulse rounded-md bg-white/10" />+ ) : active ? (+ t("dictation.hero_listening")+ ) : available && hotkey ? (+ <HoldTitle template={t("dictation.hero_hold")} combo={hotkey} />+ ) : (+ t("dictation.hero_no_key")+ )}+ </h2>+ <p className="mt-2 text-base text-white/70">+ {!loading && !available+ ? status?.reason || t("dictation.state_unavailable")+ : active+ ? t("dictation.hero_body_active")+ : t("dictation.hero_body")}+ </p>+ {available && !active && handsFree && (+ <p className="mt-1 text-sm text-white/50">+ {t("dictation.hero_hands_free").replace("{0}", formatCombo(handsFree))}+ </p>+ )}+ </div>++ <div className="flex flex-wrap items-center gap-2">+ <button+ type="button"+ disabled={loading || busy || !available}+ data-testid="dictation-toggle"+ onClick={onToggle}+ className="inline-flex h-9 items-center gap-2 rounded-md bg-white px-4 text-base font-medium text-neutral-900 transition-colors hover:bg-white/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/60 disabled:cursor-not-allowed disabled:opacity-50"+ >+ {busy ? (+ <Loader2+ aria-hidden="true"+ className="h-4 w-4 animate-spin motion-reduce:animate-none"+ />+ ) : active ? (+ <Square aria-hidden="true" className="h-4 w-4" />+ ) : (+ <Mic aria-hidden="true" className="h-4 w-4" />+ )}+ {active ? t("dictation.stop") : t("dictation.start")}+ </button>+ {!loading && available && (+ <button+ type="button"+ onClick={onOpenShortcuts}+ data-testid="dictation-open-shortcuts"+ className="inline-flex h-9 items-center gap-2 rounded-md px-3 text-base font-medium text-white/80 transition-colors hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/60"+ >+ <Keyboard aria-hidden="true" className="h-4 w-4" />+ {hotkey ? t("dictation.hero_shortcuts") : t("dictation.hero_assign")}+ </button>+ )}+ </div>+ </div>+ </section>+ );+}++/**+ * "Hold [Ctrl + Alt] to dictate" with the key set apart from the sentence.+ *+ * The locale owns the word order (some languages put the key in the middle+ * of the sentence, others at its end), so the template is split at its placeholder instead of+ * being glued together from fragments here.+ */+function HoldTitle({ template, combo }: { template: string; combo: string }) {+ const [before, after = ""] = template.split("{0}");+ return (+ <>+ {before}+ <span className="whitespace-nowrap rounded-lg bg-white/10 px-2 py-0.5 font-semibold text-white ring-1 ring-white/15">+ {formatCombo(combo)}+ </span>+ {after}+ </>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsxindex 99ad61ce51..c7b5410d6c 100644--- a/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx+++ b/jarvis/ui/web/frontend/src/views/voice/DictationHistoryGroup.tsx@@ -1,5 +1,5 @@import { useState, type ReactNode } from "react";-import { Check, Copy, RotateCcw, Trash2, Volume2 } from "lucide-react";+import { Check, ChevronDown, Copy, RotateCcw, Trash2, Volume2 } from "lucide-react";import { Badge } from "@/components/ui/badge";import {@@ -10,13 +10,16 @@ import {type DictationEntry,} from "@/hooks/useDictation";import { useT } from "@/i18n";+import { cn } from "@/lib/utils";/**- * One day's worth of dictations — a date header plus its rows.+ * One day's worth of dictations — a small date label and one framed list.** Grouping by day is what turns a flat list into something you can actually* read back: "what did I dictate this morning" is a question about a day, not- * about entry number 34.+ * about entry number 34. Each day is one bordered surface with hairlines+ * between its rows, so a day reads as a single page of a journal rather than+ * as a pile of separate cards.*/export interface DictationHistoryGroupProps {/** Already-localized day label — "Today", "Yesterday", or a formatted date. */@@ -43,21 +46,14 @@ export function DictationHistoryGroup({copiedId,}: DictationHistoryGroupProps) {return (- <section className="mt-group first:mt-0" data-testid="dictation-history-group">- {/* A quiet date divider, not a heading. It used to be an 11px uppercase- label with letter-spacing — the one construction that makes a screen- read as an admin panel, and it competed with the card title two lines- above it for no reason. */}+ <section data-testid="dictation-history-group"><h5- className="text-meta text-muted-foreground"+ className="px-1 text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground"data-testid="dictation-history-group-label">{label}</h5>- {/* No dividers. Separation between rows is the hover fill and the- padding, the way both reference apps do it; a rule under every row- drew a table over what is meant to read as a transcript. */}- <ul className="mt-1">+ <ul className="mt-2 divide-y divide-border overflow-hidden rounded-xl border border-border bg-card shadow-rim">{entries.map((entry) => (<HistoryRowkey={entry.id}@@ -85,12 +81,12 @@ export function DictationHistoryGroup({* to go. "Cancelled" in particular stays quiet: a bright chip on the one* outcome the user caused themselves inverts the whole ramp.*/-function outcomeVariant(outcome: string): "fault" | "degraded" | "secondary" {+function outcomeVariant(outcome: string): "fault" | "degraded" | null {if (outcome === "failed") return "fault";if (outcome === "unavailable" || outcome === "partial" || outcome === "empty") {return "degraded";}- return "secondary";+ return null;}function HistoryRow({@@ -115,24 +111,30 @@ function HistoryRow({// discards, and this flag is what turns the discarded row's follow-up button// into the one that really removes the entry and its audio.const [confirmDelete, setConfirmDelete] = useState(false);+ // What the recognizer actually heard stays one click away instead of being+ // printed under every row — it is there to check a cleanup, not to be read+ // twice.+ const [showRaw, setShowRaw] = useState(false);const cleaned = Boolean(entry.raw_text) && entry.text !== entry.raw_text;- // Both badges are computed here rather than inline so the render stays a- // list of chips. A row from before either field existed carries neither.+ // A row from before either field existed carries neither badge. "off" is the+ // one polish value worth hiding — the feature being switched off is not an+ // event; everything else is either "a model rewrote this" or "it did not,+ // and here is why", and the person who spoke deserves to see both.const polishBadge =- entry.polish_status && entry.polish_status !== "off"- ? entry.polish_status- : "";+ entry.polish_status && entry.polish_status !== "off" ? entry.polish_status : "";const polishTitle = [entry.polish_provider || "",entry.polish_latency_ms ? `${Math.round(entry.polish_latency_ms)} ms` : "",].filter(Boolean).join(" · ");+ // The filler cleanup's own verdict: outside its rule languages the cleanup+ // is a silent no-op, so a user dictating in Japanese or Polish saw the switch+ // sitting ON while nothing happened. "disabled" is skipped — that one the+ // user did themselves.const cleanupBadge =- entry.cleanup_reason && entry.cleanup_reason !== "disabled"- ? entry.cleanup_reason- : "";+ entry.cleanup_reason && entry.cleanup_reason !== "disabled" ? entry.cleanup_reason : "";// Restore is offered whenever there is something to win back: a soft-deleted// entry, a transcription that failed or only partly arrived, or kept audio// that can be run again. The two outcomes are named as well as the audio@@ -143,93 +145,97 @@ function HistoryRow({entry.audio_available ||entry.outcome === "failed" ||entry.outcome === "partial";+ const variant = entry.outcome ? outcomeVariant(entry.outcome) : null;return (<li- // The hover fill is drawn on the WHOLE row, inset from the card's own- // padding rather than on any one control inside it.- className="group -mx-2 flex items-start gap-2 rounded-md px-3 py-3 transition-colors hover:bg-secondary"+ className="group grid grid-cols-[64px_minmax(0,1fr)_auto] gap-x-4 px-5 py-4 transition-colors hover:bg-secondary/60 focus-within:bg-secondary/60 sm:grid-cols-[84px_minmax(0,1fr)_auto]"data-testid="dictation-history-row"data-entry-id={entry.id}>- <div className="min-w-0 flex-1">+ <time+ dateTime={entry.created_at}+ className="pt-0.5 text-sm tabular-nums text-muted-foreground"+ >+ {formatTime(entry.created_at)}+ </time>++ <div className="min-w-0">{/* The transcript is the reason this screen exists, so it is set as- prose — 15/1.6 in body ink — instead of as another 14px interface- label. Its measure is bounded by the column, not by the window. */}+ prose in body ink; everything else on the row is smaller and+ quieter than it. */}<p- className={`break-words text-reading ${- entry.discarded- ? "text-muted-foreground line-through"- : "text-foreground"- }`}+ className={cn(+ "whitespace-pre-wrap break-words text-base leading-6",+ entry.discarded ? "text-muted-foreground line-through" : "text-foreground",+ )}>{entry.text || entry.raw_text}</p>- {cleaned && (- <p className="mt-1 break-words text-meta text-muted-foreground">- {t("dictation.raw_prefix")} {entry.raw_text}- </p>- )}{entry.error && (<p- className="mt-1 break-words text-meta text-destructive"+ className="mt-1 break-words text-sm text-destructive"data-testid="dictation-failure-reason">{failureLabel(t, entry.error)}</p>)}- <div className="mt-2 flex flex-wrap items-center gap-2 text-meta text-muted-foreground">- <span>{new Date(entry.created_at).toLocaleTimeString()}</span>- {entry.outcome && (- <Badge- variant={outcomeVariant(entry.outcome)}- data-testid="dictation-outcome-badge"- >- {outcomeLabel(t, entry.outcome)}- </Badge>- )}+ {cleaned && showRaw && (+ <p+ className="mt-2 break-words border-l-2 border-border-strong pl-3 text-sm text-muted-foreground"+ data-testid="dictation-raw-text"+ >+ {t("dictation.raw_prefix")} {entry.raw_text}+ </p>+ )}++ <div className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">+ {entry.outcome &&+ (variant ? (+ <Badge variant={variant} data-testid="dictation-outcome-badge">+ {outcomeLabel(t, entry.outcome)}+ </Badge>+ ) : (+ <span data-testid="dictation-outcome-badge">{outcomeLabel(t, entry.outcome)}</span>+ ))}{entry.discarded && (<Badge variant="secondary" data-testid="dictation-discarded-badge">{t("dictation.discarded_badge")}</Badge>)}- {entry.audio_available && (- <Badge variant="secondary" className="gap-1">- <Volume2 aria-hidden="true" className="h-3 w-3" />- {t("dictation.audio_kept")}- </Badge>- )}- {/* What the wording pass did to this row. "off" is the one value- worth hiding — the feature being switched off is not an event,- and a badge on every single row would be noise. Everything else- is either "a model rewrote this" or "it did not, and here is- why", and both are things the person who spoke deserves to see- next to their own words. */}{polishBadge && (- <Badge- variant="secondary"- data-testid="dictation-polish-badge"- title={polishTitle || undefined}- >+ <MetaItem testId="dictation-polish-badge" title={polishTitle || undefined}>{polishStatusLabel(t, polishBadge)}- </Badge>+ </MetaItem>)}- {/* The filler cleanup's own verdict, and the reason this badge- exists at all: outside its three rule languages the cleanup is a- silent no-op, so a user dictating in Japanese or Polish saw the- switch sitting ON while nothing ever happened. "disabled" is- skipped — that one the user did themselves. */}{cleanupBadge && (- <Badge- variant="secondary"- data-testid="dictation-cleanup-reason-badge"- >+ <MetaItem testId="dictation-cleanup-reason-badge">{cleanupReasonLabel(t, cleanupBadge)}- </Badge>+ </MetaItem>)}- </div>- {entry.discarded && (- <div className="mt-2">+ {entry.audio_available && (+ <MetaItem>+ <Volume2 aria-hidden="true" className="h-3 w-3" />+ {t("dictation.audio_kept")}+ </MetaItem>+ )}+ {cleaned && (+ <button+ type="button"+ onClick={() => setShowRaw((v) => !v)}+ aria-expanded={showRaw}+ data-testid="dictation-toggle-raw"+ className="inline-flex items-center gap-0.5 rounded-sm text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"+ >+ <Dot />+ {showRaw ? t("dictation.hide_original") : t("dictation.show_original")}+ <ChevronDown+ aria-hidden="true"+ className={cn("h-3 w-3 transition-transform", showRaw && "rotate-180")}+ />+ </button>+ )}+ {entry.discarded && (<buttontype="button"disabled={busy}@@ -241,28 +247,32 @@ function HistoryRow({onDelete();}}data-testid="dictation-delete-permanently"- className="rounded-md text-meta text-muted-foreground transition-colors hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50"+ className={cn(+ "rounded-sm text-xs transition-colors hover:text-destructive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50",+ confirmDelete ? "font-medium text-destructive" : "text-muted-foreground",+ )}>{confirmDelete? `${t("dictation.delete_permanently")} ?`: t("dictation.delete_permanently")}</button>- </div>- )}+ )}+ </div></div>- {/* Row actions appear when the row does. They are still in the document- and still reachable by keyboard — focus inside the row reveals them- the same way the pointer does. */}- <div className="flex shrink-0 items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100">++ {/* Row actions appear with the row's hover. They stay in the document+ and reachable by keyboard — focus inside the row reveals them the+ same way the pointer does. */}+ <div className="-my-1 flex shrink-0 items-start gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"><RowActiononClick={onCopy}label={copied ? t("dictation.copied") : t("dictation.copy")}testId="dictation-copy-entry">{copied ? (- <Check aria-hidden="true" className="h-3.5 w-3.5" />+ <Check aria-hidden="true" className="h-4 w-4" />) : (- <Copy aria-hidden="true" className="h-3.5 w-3.5" />+ <Copy aria-hidden="true" className="h-4 w-4" />)}</RowAction>{canRestore && (@@ -273,7 +283,7 @@ function HistoryRow({title={t("dictation.restore_hint")}testId="dictation-restore-entry">- <RotateCcw aria-hidden="true" className="h-3.5 w-3.5" />+ <RotateCcw aria-hidden="true" className="h-4 w-4" /></RowAction>)}{!entry.discarded && (@@ -284,7 +294,7 @@ function HistoryRow({testId="dictation-discard-entry"destructive>- <Trash2 aria-hidden="true" className="h-3.5 w-3.5" />+ <Trash2 aria-hidden="true" className="h-4 w-4" /></RowAction>)}</div>@@ -292,13 +302,38 @@ function HistoryRow({);}+/** A quiet "· label" in the row's meta line. */+function MetaItem({+ children,+ testId,+ title,+}: {+ children: ReactNode;+ testId?: string;+ title?: string;+}) {+ return (+ <span className="inline-flex items-center">+ <Dot />+ <span className="inline-flex items-center gap-1" data-testid={testId} title={title}>+ {children}+ </span>+ </span>+ );+}++function Dot() {+ return (+ <span aria-hidden="true" className="mr-1 text-faint-foreground">+ ·+ </span>+ );+}+/**- * One icon button in a row's action strip.- *- * The three used to hover to three different inks — foreground, --primary and- * --destructive — which made the same gesture mean three things. Now they all- * answer the pointer the way every other control in the app does: one step up- * the surface ladder. Only discarding, which changes something, keeps a hue.+ * One icon button in a row's action strip. All three answer the pointer the+ * same way — one step up the surface ladder; only discarding, which changes+ * something, keeps a hue.*/function RowAction({children,@@ -325,15 +360,23 @@ function RowAction({aria-label={label}title={title ?? label}data-testid={testId}- className={`rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-popover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50 ${- destructive ? "hover:text-destructive" : "hover:text-foreground"- }`}+ className={cn(+ "rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-surface-raised focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:opacity-50",+ destructive ? "hover:text-destructive" : "hover:text-foreground",+ )}>{children}</button>);}+/** "4:12 PM" / "16:12" — the viewer's own clock format, no seconds. */+function formatTime(iso: string): string {+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return "";+ return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });+}+const KNOWN_OUTCOMES: ReadonlySet<string> = new Set(DICTATION_OUTCOMES);const KNOWN_FAILURES: ReadonlySet<string> = new Set(STT_FAILURE_REASONS);@@ -353,10 +396,9 @@ function outcomeLabel(t: (key: string) => string, outcome: string): string {* Unlike `outcomeLabel`, an unknown value does NOT fall through to the raw* string. This line exists to tell a person why their words did not arrive, and* the raw value here is either a stack-trace fragment stored by an older- * version — the exact thing this replaced — or a reason code from a newer- * backend, which is an identifier and explains nothing either. Both are better- * served by the honest generic sentence; the technical detail is in the log,- * where whoever needs it is already looking.+ * version or a reason code from a newer backend — an identifier that explains+ * nothing. Both are better served by the honest generic sentence; the+ * technical detail is in the log.*/function failureLabel(t: (key: string) => string, reason: string): string {return KNOWN_FAILURES.has(reason)diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationSideCards.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationSideCards.tsxnew file mode 100644index 0000000000..43b947dbac--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/voice/DictationSideCards.tsx@@ -0,0 +1,87 @@+import { ArrowRight, BookOpen, Cloud, Cpu } from "lucide-react";++import type { DictationStatus } from "@/hooks/useDictation";+import { useT } from "@/i18n";++/**+ * Which recognizer answers the next press (P-41) — the settings name one, the+ * lane may hold another, and this card says which. It used to be a second grey+ * sentence under the "Ready" line; as its own small card it can carry a plain+ * "On this computer" / "Cloud" headline, with the exact model and fallback+ * under it for whoever wants them.+ */+export function DictationEngineCard({+ engine,+}: {+ engine: NonNullable<DictationStatus["engine"]>;+}) {+ const t = useT();+ const Icon = engine.local ? Cpu : Cloud;+ // The headline already names the model, so the line under it only adds+ // what is not on screen yet: the fallback behind a local engine, or why+ // the local engine is not the one in front.+ const detail = engine.local+ ? engine.fallback+ ? t("dictation.engine_fallback").replace("{0}", engine.fallback)+ : ""+ : engine.detail+ ? t("dictation.engine_local_off").replace("{0}", engine.detail)+ : "";++ return (+ <section+ className="rounded-xl border border-border bg-card p-5 shadow-rim"+ data-testid="dictation-engine"+ >+ <p className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">+ {t("dictation.engine_title")}+ </p>+ <div className="mt-3 flex items-center gap-3">+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-secondary text-foreground">+ <Icon aria-hidden="true" className="h-4 w-4" />+ </span>+ <div className="min-w-0">+ <p className="text-base font-medium text-foreground-strong">+ {engine.local ? t("dictation.engine_on_device") : t("dictation.engine_cloud_short")}+ </p>+ <p className="truncate text-sm text-muted-foreground" title={engine.model || engine.provider}>+ {engine.model || engine.provider}+ </p>+ </div>+ </div>+ {detail && <p className="mt-3 text-sm text-muted-foreground">{detail}</p>}+ </section>+ );+}++/**+ * The one invitation on the screen: the dictionary is what makes names and+ * jargon come out right, and it lives one tab over, so the card is a door to+ * it rather than a copy of it.+ */+export function DictationVocabularyCard({ onOpen }: { onOpen: () => void }) {+ const t = useT();+ return (+ <section+ className="rounded-xl border border-border bg-card p-5 shadow-rim"+ data-testid="dictation-vocabulary"+ >+ <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-secondary text-foreground">+ <BookOpen aria-hidden="true" className="h-4 w-4" />+ </span>+ <h3 className="mt-3 text-base font-semibold text-foreground-strong">+ {t("dictation.vocab_title")}+ </h3>+ <p className="mt-1 text-sm text-muted-foreground">{t("dictation.vocab_body")}</p>+ <button+ type="button"+ onClick={onOpen}+ data-testid="dictation-open-dictionary"+ className="mt-4 inline-flex h-9 w-full items-center justify-center gap-2 rounded-md bg-primary px-4 text-base font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {t("dictation.vocab_cta")}+ <ArrowRight aria-hidden="true" className="h-4 w-4" />+ </button>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationStatsBar.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationStatsBar.tsxdeleted file mode 100644index 9d3a3d5fff..0000000000--- a/jarvis/ui/web/frontend/src/views/voice/DictationStatsBar.tsx+++ /dev/null@@ -1,105 +0,0 @@-import { Card } from "@/components/ui/card";-import type { DictationStats } from "@/hooks/useDictation";-import { useT } from "@/i18n";--/**- * The three numbers worth knowing about your own dictation: how many words you- * have spoken, how fast you speak them, and how many days in a row you have- * used it.- *- * The honesty rule this component exists to enforce: the totals are only- * all-time when the never-pruned stats sidecar answered. When the backend fell- * back to deriving them from the rolling history window, the strip says "Last- * N days" instead — a 30-day slice labelled "All time" would quietly understate- * every long-time user's numbers.- *- * That window line now stands where the card's own title used to. Three- * numbers labelled "Words", "Words per minute" and "Day streak" do not need a- * heading saying "Your dictation" above them — it repeated what the tiles- * already said — while the window they cover is the one fact nothing else on- * the screen carries. The three decorative icons went for the same reason: at- * --primary they rendered brighter than the numbers they decorated.- *- * Informational only. No goal, no nag, no popup.- */-export function DictationStatsBar({ stats }: { stats: DictationStats }) {- const t = useT();-- const windowLabel =- stats.source === "lifetime"- ? t("dictation.stats.window_lifetime")- : t("dictation.stats.window_days").replace(- "{0}",- String(stats.window.days),- );-- return (- <Card className="p-5" data-testid="dictation-stats">- <p- className="text-meta text-muted-foreground"- data-testid="dictation-stats-window"- >- {windowLabel}- </p>- <div className="mt-stack grid gap-stack sm:grid-cols-3">- <StatTile- label={t("dictation.stats.words")}- value={formatCount(stats.totals.words)}- testId="dictation-stat-words"- />- <StatTile- label={t("dictation.stats.wpm")}- value={formatWpm(stats.totals.wpm)}- testId="dictation-stat-wpm"- />- <StatTile- label={t("dictation.stats.streak")}- value={formatCount(stats.streak.current_days)}- testId="dictation-stat-streak"- />- </div>- </Card>- );-}--/**- * One tile: the number first, its name under it.- *- * --secondary, one step ABOVE the card it sits in. It used to be- * `bg-background/40` inside `bg-card/60`, which rendered the three headline- * numbers darker than their own container — a child below its parent, and on- * exactly the elements someone opens this screen to read.- */-function StatTile({- label,- value,- testId,-}: {- label: string;- value: string;- testId: string;-}) {- return (- <div className="rounded-md bg-secondary p-4">- <p- className="text-display tabular-nums text-foreground-strong"- data-testid={testId}- >- {value}- </p>- <p className="mt-1 text-meta text-muted-foreground">{label}</p>- </div>- );-}--/** Locale-grouped integer; a non-finite server value degrades to a dash. */-function formatCount(value: number): string {- if (!Number.isFinite(value)) return "—";- return Math.round(value).toLocaleString();-}--/** Words per minute, one decimal only while it is still small. */-function formatWpm(value: number): string {- if (!Number.isFinite(value) || value <= 0) return "—";- return value >= 10 ? String(Math.round(value)) : value.toFixed(1);-}diff --git a/jarvis/ui/web/frontend/src/views/voice/DictationStatsCard.tsx b/jarvis/ui/web/frontend/src/views/voice/DictationStatsCard.tsxnew file mode 100644index 0000000000..b862726514--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/voice/DictationStatsCard.tsx@@ -0,0 +1,211 @@+import { useMemo } from "react";++import type { DictationStats } from "@/hooks/useDictation";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++/**+ * The side card with the three numbers worth knowing about your own+ * dictation — how much, how fast, how steadily — and the last two weeks drawn+ * as a row of bars underneath.+ *+ * Each number is set large with its unit beside it ("241.2K words") so the+ * card reads as three short sentences instead of a grid of labelled tiles.+ * The exact count lives in the title attribute: the compact form is for+ * glancing, the full number is one hover away.+ *+ * The honesty rule from before still holds: the totals are only "All time"+ * when the never-pruned stats sidecar answered. When the backend fell back to+ * the rolling history window, the card says "Last N days" — a 30-day slice+ * labelled "All time" would quietly understate every long-time user.+ *+ * Informational only. No goal, no nag, no popup.+ */+export function DictationStatsCard({ stats }: { stats: DictationStats }) {+ const t = useT();++ const windowLabel =+ stats.source === "lifetime"+ ? t("dictation.stats.window_lifetime")+ : t("dictation.stats.window_days").replace("{0}", String(stats.window.days));++ const days = useMemo(() => lastDays(stats.by_day, 14), [stats.by_day]);+ const peak = Math.max(1, ...days.map((d) => d.words));++ return (+ <section+ className="rounded-xl border border-border bg-card p-5 shadow-rim"+ data-testid="dictation-stats"+ >+ <p+ className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground"+ data-testid="dictation-stats-window"+ >+ {windowLabel}+ </p>++ <dl className="mt-4 flex flex-col gap-3">+ <Stat+ value={formatCompact(stats.totals.words)}+ exact={formatCount(stats.totals.words)}+ unit={t("dictation.stats.words_unit")}+ label={t("dictation.stats.words")}+ testId="dictation-stat-words"+ />+ <Stat+ value={formatWpm(stats.totals.wpm)}+ unit={t("dictation.stats.wpm_unit")}+ label={t("dictation.stats.wpm")}+ testId="dictation-stat-wpm"+ />+ <Stat+ value={formatCount(stats.streak.current_days)}+ unit={t("dictation.stats.streak_unit")}+ label={t("dictation.stats.streak")}+ testId="dictation-stat-streak"+ />+ </dl>++ <div className="mt-5 border-t border-border pt-4">+ <div className="flex items-baseline justify-between gap-3 text-xs text-muted-foreground">+ <span>{t("dictation.stats.activity")}</span>+ {stats.streak.longest_days > 0 && (+ <span data-testid="dictation-stat-best">+ {t("dictation.stats.best_streak").replace(+ "{0}",+ formatCount(stats.streak.longest_days),+ )}+ </span>+ )}+ </div>+ {/* Two weeks as bars, today on the right. Height is relative to the+ busiest day in view; a day with nothing keeps a 2px stub so the+ row still reads as fourteen days rather than as gaps. */}+ <div+ className="mt-3 flex h-14 items-end gap-[3px]"+ role="img"+ aria-label={t("dictation.stats.activity")}+ data-testid="dictation-activity"+ >+ {days.map((day, i) => {+ const today = i === days.length - 1;+ const pct = day.words > 0 ? Math.max(8, (day.words / peak) * 100) : 0;+ return (+ <div+ key={day.date}+ title={t("dictation.stats.activity_day")+ .replace("{0}", day.label)+ .replace("{1}", formatCount(day.words))}+ className={cn(+ "min-h-[2px] flex-1 rounded-[3px] transition-colors",+ day.words === 0+ ? "bg-secondary"+ : today+ ? "bg-foreground-strong"+ : "bg-muted-foreground/45 hover:bg-muted-foreground/70",+ )}+ style={{ height: day.words > 0 ? `${pct}%` : undefined }}+ />+ );+ })}+ </div>+ <p className="mt-3 text-sm text-foreground-secondary">+ {t("dictation.stats.today").replace("{0}", formatCount(stats.today.words))}+ </p>+ </div>+ </section>+ );+}++/** One "241.2K words" line; the long label is kept for screen readers. */+function Stat({+ value,+ exact,+ unit,+ label,+ testId,+}: {+ value: string;+ exact?: string;+ unit: string;+ label: string;+ testId: string;+}) {+ return (+ <div className="flex items-baseline gap-2">+ <dt className="sr-only">{label}</dt>+ <dd className="flex items-baseline gap-2">+ <span+ className="text-[28px] font-semibold leading-[32px] tracking-[-0.02em] tabular-nums text-foreground-strong"+ title={exact && exact !== value ? exact : undefined}+ data-testid={testId}+ >+ {value}+ </span>+ <span className="text-base text-muted-foreground">{unit}</span>+ </dd>+ </div>+ );+}++interface DayBar {+ /** Local `YYYY-MM-DD`. */+ date: string;+ /** Locale-formatted short date for the tooltip. */+ label: string;+ words: number;+}++/**+ * The last `count` local calendar days, oldest first, each with its word count+ * from `by_day` (a day the backend did not list is a zero day).+ */+function lastDays(byDay: DictationStats["by_day"], count: number): DayBar[] {+ const words = new Map<string, number>();+ for (const day of byDay ?? []) words.set(day.date, day.words);+ const out: DayBar[] = [];+ const cursor = new Date();+ cursor.setHours(12, 0, 0, 0);+ cursor.setDate(cursor.getDate() - (count - 1));+ for (let i = 0; i < count; i += 1) {+ const key = localKey(cursor);+ out.push({+ date: key,+ label: cursor.toLocaleDateString(undefined, { month: "short", day: "numeric" }),+ words: words.get(key) ?? 0,+ });+ cursor.setDate(cursor.getDate() + 1);+ }+ return out;+}++function localKey(date: Date): string {+ const month = String(date.getMonth() + 1).padStart(2, "0");+ const day = String(date.getDate()).padStart(2, "0");+ return `${date.getFullYear()}-${month}-${day}`;+}++/** Locale-grouped integer; a non-finite server value degrades to a dash. */+function formatCount(value: number): string {+ if (!Number.isFinite(value)) return "—";+ return Math.round(value).toLocaleString();+}++/**+ * Short form for the headline number — "241.2K" — once it no longer fits at a+ * glance. Below ten thousand the exact count is short enough to show as is.+ */+function formatCompact(value: number): string {+ if (!Number.isFinite(value)) return "—";+ if (Math.abs(value) < 10_000) return formatCount(value);+ return new Intl.NumberFormat(undefined, {+ notation: "compact",+ maximumFractionDigits: 1,+ }).format(value);+}++/** Words per minute, one decimal only while it is still small. */+function formatWpm(value: number): string {+ if (!Number.isFinite(value) || value <= 0) return "—";+ return value >= 10 ? String(Math.round(value)) : value.toFixed(1);+}diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex a5a7c998a6..6442d652d1 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -898,6 +898,8 @@ class WebServer:from jarvis.board.aggregator import BoardAggregatorfrom jarvis.board.bio_brain import BIO_TIMEOUT_S, resolve_bio_brainfrom jarvis.board.evaluator import AchievementEvaluator+ from jarvis.board.insights import BoardInsights+ from jarvis.board.insights import default_sources as insight_sourcesfrom jarvis.board.profile import BioGenerator, BioStorefrom jarvis.board.scheduler import BioSchedulerfrom jarvis.board.store import BoardStore@@ -920,6 +922,13 @@ class WebServer:sessions_db_path=sessions_db_path,)store = BoardStore(db_path=db_path)+ insights = BoardInsights(+ insight_sources(+ data_dir=Path(self.cfg.memory.data_dir),+ sessions_db=sessions_db_path,+ board_db=db_path,+ )+ )evaluator = AchievementEvaluator(db_path=db_path, bus=self.bus)bio_store = BioStore(db_path=db_path)@@ -971,6 +980,7 @@ class WebServer:self._bio_generator = bio_generatorapp.state.board_aggregator = aggregatorapp.state.board_store = store+ app.state.board_insights = insightsapp.state.achievement_evaluator = evaluatorapp.state.bio_generator = bio_generatorapp.state.bio_store = bio_store@@ -989,6 +999,7 @@ class WebServer:self._bio_generator = Noneapp.state.board_aggregator = Noneapp.state.board_store = None+ app.state.board_insights = Noneapp.state.achievement_evaluator = Noneapp.state.bio_generator = Noneapp.state.bio_store = Nonediff --git a/tests/board/test_insights.py b/tests/board/test_insights.pynew file mode 100644index 0000000000..d69ab2d337--- /dev/null+++ b/tests/board/test_insights.py@@ -0,0 +1,186 @@+"""Board insights: one picture built from the stores the app already keeps.++Every source is a real (temporary) store written the way its owner writes it;+the tests check the counts, the local-day bucketing, the streak across+sources and that a missing store degrades to ``available: false``.+"""+from __future__ import annotations++import sqlite3+from datetime import datetime, timedelta+from pathlib import Path++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.board.aggregator import BoardAggregator+from jarvis.board.insights import (+ SERIES_DAYS,+ BoardInsights,+ InsightSources,+ current_streak,+ longest_streak,+)+from jarvis.board.store import BoardStore+from jarvis.dictation.stats import DictationStats+from jarvis.ui.web.board_routes import board_router+++def _noon(days_ago: int) -> datetime:+ now = datetime.now().astimezone().replace(hour=12, minute=0, second=0, microsecond=0)+ return now - timedelta(days=days_ago)+++def _ms(moment: datetime) -> int:+ return int(moment.timestamp() * 1000)+++def _write_dictation(path: Path) -> None:+ stats = DictationStats(path)+ stats.record(created_at=_noon(0).isoformat(), word_count=120, duration_s=60.0)+ stats.record(created_at=_noon(1).isoformat(), word_count=80, duration_s=40.0)+++def _write_agent_chat(path: Path) -> None:+ conn = sqlite3.connect(path)+ conn.executescript(+ """+ CREATE TABLE agent_chat_sessions (+ session_id TEXT PRIMARY KEY, provider TEXT, surface TEXT+ );+ CREATE TABLE agent_chat_events (+ session_id TEXT, seq INTEGER, ts_ms INTEGER, kind TEXT, payload TEXT+ );+ """+ )+ conn.execute("INSERT INTO agent_chat_sessions VALUES ('s1', 'claude-api', 'jarvis')")+ conn.execute("INSERT INTO agent_chat_sessions VALUES ('s2', 'gemini', 'society')")+ rows = [+ ("s1", 1, _ms(_noon(2)), "user_message", "{}"),+ ("s1", 2, _ms(_noon(2)), "assistant_text", "{}"),+ ("s2", 1, _ms(_noon(2)), "user_message", "{}"),+ ]+ conn.executemany("INSERT INTO agent_chat_events VALUES (?, ?, ?, ?, ?)", rows)+ conn.commit()+ conn.close()+++def _write_cli_index(path: Path) -> None:+ conn = sqlite3.connect(path)+ conn.execute(+ "CREATE TABLE cli_turns (agent TEXT, session_id TEXT, ts_ms INTEGER, "+ "tokens_in INTEGER, tokens_out INTEGER)"+ )+ rows = [+ ("claude-cli", "a", _ms(_noon(3)), 10, 5),+ ("claude-cli", "a", _ms(_noon(3)) + 60_000, 10, 5),+ ("claude-cli", "b", _ms(_noon(40)), 1, 1),+ ("codex-cli", "c", _ms(_noon(3)), 100, 50),+ ]+ conn.executemany("INSERT INTO cli_turns VALUES (?, ?, ?, ?, ?)", rows)+ conn.commit()+ conn.close()+++def _sources(tmp_path: Path) -> InsightSources:+ dictation = tmp_path / "dictation_stats.json"+ chat = tmp_path / "agent_chat.db"+ cli = tmp_path / "cli_usage_index.db"+ _write_dictation(dictation)+ _write_agent_chat(chat)+ _write_cli_index(cli)+ board = tmp_path / "board" / "personal.db"+ BoardAggregator(jsonl_dir=tmp_path / "fr", db_path=board).run()+ return InsightSources(+ dictation_stats=dictation, board_db=board, agent_chat_db=chat, cli_index_db=cli,+ )+++def test_build_counts_every_source(tmp_path: Path) -> None:+ picture = BoardInsights(_sources(tmp_path)).build()++ assert picture["dictation"] == {+ "available": True, "words": 200, "dictations": 2, "seconds": 100.0,+ }+ assert picture["chats"]["messages"] == 2+ assert picture["chats"]["sessions"] == 2+ assert picture["chats"]["providers"][0]["provider"] == "claude-api"+ assert picture["chats"]["providers"][0]["jarvis_sessions"] == 1++ agents = {item["agent"]: item for item in picture["agents"]["items"]}+ assert agents["claude-cli"]["sessions"] == 2+ assert agents["claude-cli"]["sessions_30d"] == 1+ assert agents["claude-cli"]["turns"] == 3+ assert agents["claude-cli"]["tokens"] == 32+ assert picture["agents"]["sessions"] == 3+ assert picture["agents"]["turns"] == 4++ assert picture["reference"] == {"typing_wpm": 40, "novel_words": 90_000}+ assert picture["trend"]["words_30d"] == 200+++def test_daily_series_and_streak_span_all_sources(tmp_path: Path) -> None:+ picture = BoardInsights(_sources(tmp_path)).build()++ days = picture["days"]+ assert len(days) == SERIES_DAYS+ by_date = {d["date"]: d for d in days}+ assert by_date[_noon(0).date().isoformat()]["dictation_words"] == 120+ assert by_date[_noon(2).date().isoformat()]["chat_messages"] == 2+ assert by_date[_noon(3).date().isoformat()]["agent_sessions"] == 2+ # Dictation today + yesterday, chat two days ago, agents three days ago:+ # four consecutive days, each from a different store.+ assert picture["streak"]["current_days"] == 4+ assert picture["records"]["best_agent_day"]["value"] == 2++ punch = picture["punch_card"]+ assert len(punch) == 7 and all(len(row) == 24 for row in punch)+ assert sum(map(sum, punch)) == 2 + 4 # chat messages + agent turns+++def test_missing_stores_read_as_unavailable(tmp_path: Path) -> None:+ picture = BoardInsights(+ InsightSources(+ dictation_stats=tmp_path / "missing.json",+ board_db=tmp_path / "missing.db",+ sessions_db=None,+ agent_chat_db=tmp_path / "missing_chat.db",+ cli_index_db=None,+ )+ ).build()+ assert picture["dictation"]["available"] is False+ assert picture["voice"]["available"] is False+ assert picture["chats"]["available"] is False+ assert picture["agents"]["available"] is False+ assert picture["streak"] == {+ "current_days": 0, "longest_days": 0, "active_days": 0, "first_day": None,+ }+ assert picture["records"] == {"best_words_day": None, "best_agent_day": None}+++def test_streak_grace_for_a_quiet_today() -> None:+ today = _noon(0).date()+ days = {(today - timedelta(days=n)).isoformat() for n in (1, 2, 3, 7, 8)}+ assert current_streak(days, today) == 3+ assert longest_streak(days) == 3+++def test_route_returns_the_picture_with_categories(tmp_path: Path) -> None:+ sources = _sources(tmp_path)+ app = FastAPI()+ app.include_router(board_router)+ app.state.board_store = BoardStore(db_path=sources.board_db)+ app.state.board_insights = BoardInsights(sources)+ with TestClient(app) as client:+ resp = client.get("/api/board/insights")+ assert resp.status_code == 200+ body = resp.json()+ assert body["dictation"]["words"] == 200+ assert [c["category"] for c in body["categories"]["categories"]][:1] == ["agents"]+++def test_route_is_503_without_insights() -> None:+ app = FastAPI()+ app.include_router(board_router)+ with TestClient(app) as client:+ assert client.get("/api/board/insights").status_code == 503