AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(ui): add a vitals panel to the Pulse heartbeat card (#203)
Rufus4101207b487c
diff --git a/packages/ui/scripts/heartbeat-vitals.test.mjs b/packages/ui/scripts/heartbeat-vitals.test.mjsnew file mode 100644index 00000000..3101a1d0--- /dev/null+++ b/packages/ui/scripts/heartbeat-vitals.test.mjs@@ -0,0 +1,131 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ deriveVitals,+ formatTrend,+ formatVitalDate,+} from "../src/lib/heartbeatVitals.ts";++// Build a dense oldest → newest window from a list of counts; the last entry+// is "today". Dates are consecutive UTC days ending 2026-09-24.+function window(counts) {+ const end = Date.UTC(2026, 8, 24);+ return counts.map((count, i) => ({+ date: new Date(end - (counts.length - 1 - i) * 86_400_000).toISOString().slice(0, 10),+ count,+ }));+}++const zeros = (n) => Array.from({ length: n }, () => 0);++// --- empty / idle ------------------------------------------------------------++test("all-zero window degrades to zeros and nulls", () => {+ const v = deriveVitals(window(zeros(90)));+ assert.deepEqual(v.currentStreak, { days: 0, throughToday: false });+ assert.equal(v.longestStreak, 0);+ assert.equal(v.total, 0);+ assert.equal(v.activeDays, 0);+ assert.equal(v.avgPerActiveDay, null);+ assert.equal(v.busiestDay, null);+ assert.equal(v.trend.pct, null);+ assert.equal(v.trend.direction, "none");+ assert.equal(formatTrend(v.trend), "—");+});++test("an empty list does not throw", () => {+ const v = deriveVitals([]);+ assert.deepEqual(v.currentStreak, { days: 0, throughToday: false });+ assert.equal(v.trend.windowDays, 0);+ assert.equal(v.busiestDay, null);+});++// --- streaks -----------------------------------------------------------------++test("current streak counts through today when today is active", () => {+ const v = deriveVitals(window([0, 1, 2, 3]));+ assert.deepEqual(v.currentStreak, { days: 3, throughToday: true });+});++test("current streak counts back from yesterday when today is still idle", () => {+ const v = deriveVitals(window([0, 2, 1, 4, 0]));+ assert.deepEqual(v.currentStreak, { days: 3, throughToday: false });+});++test("current streak is 0 when both today and yesterday are idle", () => {+ const v = deriveVitals(window([3, 3, 0, 0]));+ assert.equal(v.currentStreak.days, 0);+});++test("longest streak is found mid-window, distinct from the current one", () => {+ const v = deriveVitals(window([1, 0, 1, 1, 1, 1, 0, 2, 2]));+ assert.equal(v.longestStreak, 4);+ assert.deepEqual(v.currentStreak, { days: 2, throughToday: true });+});++// --- totals / averages / busiest ---------------------------------------------++test("total, active days, and average per active day", () => {+ const v = deriveVitals(window([0, 3, 0, 4, 0]));+ assert.equal(v.total, 7);+ assert.equal(v.activeDays, 2);+ assert.equal(v.avgPerActiveDay, 3.5);+});++test("average rounds to one decimal", () => {+ const v = deriveVitals(window([1, 1, 2]));+ assert.equal(v.avgPerActiveDay, 1.3);+});++test("busiest-day tie goes to the most recent day", () => {+ const days = window([5, 1, 5, 2]);+ const v = deriveVitals(days);+ assert.deepEqual(v.busiestDay, days[2]);+});++// --- trend -------------------------------------------------------------------++test("trend compares the last 30 days to the 30 before", () => {+ // 90 days: first 30 ignored, prior 30 sum to 30, last 30 sum to 36.+ const counts = [...Array(30).fill(9), ...Array(30).fill(1), ...Array(24).fill(1), ...Array(6).fill(2)];+ const v = deriveVitals(window(counts));+ assert.equal(v.trend.windowDays, 30);+ assert.equal(v.trend.prior, 30);+ assert.equal(v.trend.current, 36);+ assert.equal(v.trend.pct, 20);+ assert.equal(v.trend.direction, "up");+ assert.equal(formatTrend(v.trend), "▲ 20%");+});++test("a drop reads as down with an absolute percentage", () => {+ const v = deriveVitals(window([...Array(30).fill(2), ...Array(30).fill(1)]));+ assert.equal(v.trend.pct, -50);+ assert.equal(formatTrend(v.trend), "▼ 50%");+});++test("equal halves read as flat", () => {+ const v = deriveVitals(window(Array(60).fill(1)));+ assert.equal(v.trend.direction, "flat");+ assert.equal(formatTrend(v.trend), "flat");+});++test("no prior activity: pct is null and direction is new", () => {+ const v = deriveVitals(window([...zeros(30), ...Array(30).fill(1)]));+ assert.equal(v.trend.pct, null);+ assert.equal(v.trend.direction, "new");+ assert.equal(formatTrend(v.trend), "new");+});++test("a window shorter than 60 days compares the halves that exist", () => {+ const v = deriveVitals(window([1, 1, 1, 1, 2, 2, 2, 2, 5]));+ // 9 days → 4-day halves: prior = days[1..4] = 1+1+1+2, current = days[5..8] = 2+2+2+5.+ assert.equal(v.trend.windowDays, 4);+ assert.equal(v.trend.prior, 5);+ assert.equal(v.trend.current, 11);+});++// --- formatting --------------------------------------------------------------++test("formatVitalDate formats in UTC", () => {+ assert.equal(formatVitalDate("2026-09-08"), "Tue, Sep 8");+});diff --git a/packages/ui/src/components/memories/PulseHeader.tsx b/packages/ui/src/components/memories/PulseHeader.tsxindex a85ece9f..bf411edb 100644--- a/packages/ui/src/components/memories/PulseHeader.tsx+++ b/packages/ui/src/components/memories/PulseHeader.tsx@@ -11,18 +11,27 @@ import {type DailyActivityCount,type ScheduledAction,} from "@/lib/api";+import {+ deriveVitals,+ formatTrend,+ formatVitalDate,+ type TrendDirection,+} from "@/lib/heartbeatVitals";import {LivePulse,+ STAT_VALUE_TONE,Skeleton,StatTile,formatRunAt,groupByRhythm,metaFor,+ type StatTone,} from "./shared";// The Pulse header is the page's at-a-glance band: a strip of headline metrics// plus the "heartbeat" — a GitHub-contributions-style heatmap of the-// Executive's self-initiated activity over the last 90 days. Every metric is+// Executive's self-initiated activity over the last 90 days, with a vitals+// panel (streaks, totals, trend) derived from the same counts. Every metric is// derived from data the page already needs (pending scheduled actions + the// three memory lists); only the per-day heatmap requires its own endpoint,// since /today/activity returns the last-N items, not a daily timeline. Peer@@ -133,11 +142,20 @@ export default function PulseHeader() {</div><LivePulse /></div>- {loading || !data ? (- <Skeleton className="h-24 w-full" />- ) : (- <Heatmap days={data.heatmap} />- )}+ {/* The heatmap is fixed-width (~14 week columns), so the vitals panel+ takes the rest of the row on md+ and stacks beneath it below. */}+ <div className="flex flex-col md:flex-row gap-6">+ <div className="shrink-0 min-w-0">+ {loading || !data ? (+ <Skeleton className="h-32 w-56" />+ ) : (+ <Heatmap days={data.heatmap} />+ )}+ </div>+ <div className="flex-1 min-w-0 md:border-l md:border-line md:pl-6">+ {loading || !data ? <VitalsSkeleton /> : <Vitals days={data.heatmap} />}+ </div>+ </div></section></header>);@@ -195,6 +213,106 @@ function deriveStats(];}+// --------------------------------------------------------------------------- #+// Vitals — summary numbers beside the heatmap, derived from the same counts+// --------------------------------------------------------------------------- #++const VITALS_COUNT = 6;++const TREND_TONE: Record<TrendDirection, StatTone> = {+ up: "emerald",+ down: "amber",+ flat: "default",+ new: "emerald",+ none: "default",+};++function plural(n: number, one: string, many: string = `${one}s`): string {+ return `${n} ${n === 1 ? one : many}`;+}++function Vital({+ label,+ value,+ hint,+ tone = "default",+}: {+ label: string;+ value: string;+ hint?: string;+ tone?: StatTone;+}) {+ return (+ <div className="min-w-0">+ <div className="text-[11px] font-medium uppercase tracking-wide text-fg-subtle truncate">+ {label}+ </div>+ <div className={`mt-1 text-xl font-semibold tabular-nums truncate ${STAT_VALUE_TONE[tone]}`}>+ {value}+ </div>+ {hint && <div className="text-[11px] text-fg-muted mt-0.5 truncate">{hint}</div>}+ </div>+ );+}++const VITALS_GRID = "grid grid-cols-2 sm:grid-cols-3 gap-x-6 gap-y-5";++function Vitals({ days }: { days: DailyActivityCount[] }) {+ const v = useMemo(() => deriveVitals(days), [days]);+ const { trend } = v;++ return (+ <div className={VITALS_GRID}>+ <Vital+ label="Current streak"+ value={plural(v.currentStreak.days, "day")}+ hint={+ v.currentStreak.days === 0+ ? "no active days lately"+ : v.currentStreak.throughToday+ ? "through today"+ : "through yesterday"+ }+ tone="emerald"+ />+ <Vital label="Longest streak" value={plural(v.longestStreak, "day")} />+ <Vital+ label={`${days.length}-day total`}+ value={plural(v.total, "beat")}+ hint={`on ${v.activeDays} of ${days.length} days`}+ />+ <Vital+ label="Avg per active day"+ value={v.avgPerActiveDay === null ? "—" : v.avgPerActiveDay.toFixed(1)}+ />+ <Vital+ label="Busiest day"+ value={v.busiestDay ? formatVitalDate(v.busiestDay.date) : "—"}+ hint={v.busiestDay ? plural(v.busiestDay.count, "action") : undefined}+ />+ <Vital+ label={`Last ${trend.windowDays} vs prior`}+ value={formatTrend(trend)}+ hint={trend.windowDays > 0 ? `${trend.current} vs ${trend.prior}` : undefined}+ tone={TREND_TONE[trend.direction]}+ />+ </div>+ );+}++function VitalsSkeleton() {+ return (+ <div className={VITALS_GRID}>+ {Array.from({ length: VITALS_COUNT }).map((_, i) => (+ <div key={i}>+ <Skeleton className="h-3 w-20" />+ <Skeleton className="h-6 w-14 mt-2" />+ </div>+ ))}+ </div>+ );+}+// --------------------------------------------------------------------------- #// Heatmap — GitHub-contributions-style grid (weeks as columns, weekdays as rows)// --------------------------------------------------------------------------- #diff --git a/packages/ui/src/components/memories/shared.tsx b/packages/ui/src/components/memories/shared.tsxindex 11f92dc0..856903b8 100644--- a/packages/ui/src/components/memories/shared.tsx+++ b/packages/ui/src/components/memories/shared.tsx@@ -146,9 +146,9 @@ export function groupByRhythm(// they render correctly in both light and dark mode.// ----------------------------------------------------------------------------type StatTone = "default" | "accent" | "emerald" | "amber";+export type StatTone = "default" | "accent" | "emerald" | "amber";-const STAT_VALUE_TONE: Record<StatTone, string> = {+export const STAT_VALUE_TONE: Record<StatTone, string> = {default: "text-fg",accent: "text-indigo-300",emerald: "text-emerald-300",diff --git a/packages/ui/src/lib/heartbeatVitals.ts b/packages/ui/src/lib/heartbeatVitals.tsnew file mode 100644index 00000000..0dac0ce5--- /dev/null+++ b/packages/ui/src/lib/heartbeatVitals.ts@@ -0,0 +1,123 @@+// Vitals for the Pulse "Heartbeat" card: summary numbers derived from the same+// dense per-day counts the heatmap draws (GET /today/activity/daily — every+// calendar day present, oldest → newest, the last entry is today, UTC).+// Kept dependency-free so `node --test` can import it directly.++/** One day of activity; structurally the same as `DailyActivityCount` in api.ts. */+export interface ActivityDay {+ date: string; // YYYY-MM-DD (UTC)+ count: number;+}++/** Days per side of the "recent vs prior" comparison when the window allows. */+export const TREND_WINDOW_DAYS = 30;++export type TrendDirection = "up" | "down" | "flat" | "new" | "none";++export interface HeartbeatTrend {+ /** Days in each half of the comparison (≤ TREND_WINDOW_DAYS). */+ windowDays: number;+ current: number;+ prior: number;+ /** Rounded % change vs prior; null when prior is 0 (no baseline). */+ pct: number | null;+ direction: TrendDirection;+}++export interface HeartbeatVitals {+ /**+ * Consecutive active days ending today — or ending yesterday when nothing has+ * fired yet today, so the streak doesn't read as broken first thing.+ */+ currentStreak: { days: number; throughToday: boolean };+ longestStreak: number;+ total: number;+ activeDays: number;+ /** Mean count over active days, 1 decimal; null when there were none. */+ avgPerActiveDay: number | null;+ /** Highest-count day (most recent wins a tie); null when every day is 0. */+ busiestDay: ActivityDay | null;+ trend: HeartbeatTrend;+}++function sum(days: ActivityDay[]): number {+ return days.reduce((n, d) => n + d.count, 0);+}++function currentStreak(days: ActivityDay[]): HeartbeatVitals["currentStreak"] {+ let end = days.length - 1;+ const throughToday = end >= 0 && days[end].count > 0;+ if (!throughToday) end -= 1; // today idle so far: count back from yesterday+ let n = 0;+ for (let i = end; i >= 0 && days[i].count > 0; i--) n++;+ return { days: n, throughToday };+}++function trend(days: ActivityDay[]): HeartbeatTrend {+ const windowDays = Math.min(TREND_WINDOW_DAYS, Math.floor(days.length / 2));+ const current = windowDays > 0 ? sum(days.slice(-windowDays)) : 0;+ const prior = windowDays > 0 ? sum(days.slice(-2 * windowDays, -windowDays)) : 0;+ if (prior === 0) {+ return { windowDays, current, prior, pct: null, direction: current > 0 ? "new" : "none" };+ }+ const pct = Math.round(((current - prior) / prior) * 100);+ const direction: TrendDirection = pct > 0 ? "up" : pct < 0 ? "down" : "flat";+ return { windowDays, current, prior, pct, direction };+}++export function deriveVitals(days: ActivityDay[]): HeartbeatVitals {+ let total = 0;+ let activeDays = 0;+ let longest = 0;+ let run = 0;+ let busiest: ActivityDay | null = null;++ for (const day of days) {+ total += day.count;+ if (day.count > 0) {+ activeDays++;+ run++;+ longest = Math.max(longest, run);+ // `>=` so a later day with the same count wins the tie.+ if (busiest === null || day.count >= busiest.count) busiest = day;+ } else {+ run = 0;+ }+ }++ return {+ currentStreak: currentStreak(days),+ longestStreak: longest,+ total,+ activeDays,+ avgPerActiveDay: activeDays > 0 ? Math.round((total / activeDays) * 10) / 10 : null,+ busiestDay: busiest,+ trend: trend(days),+ };+}++/** "Tue, Sep 9" for a YYYY-MM-DD date, formatted in UTC to match the buckets. */+export function formatVitalDate(date: string): string {+ return new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", {+ weekday: "short",+ month: "short",+ day: "numeric",+ timeZone: "UTC",+ });+}++/** Display text for a trend: "▲ 18%", "▼ 12%", "flat", "new", or "—". */+export function formatTrend(t: HeartbeatTrend): string {+ switch (t.direction) {+ case "up":+ return `▲ ${t.pct}%`;+ case "down":+ return `▼ ${Math.abs(t.pct ?? 0)}%`;+ case "flat":+ return "flat";+ case "new":+ return "new";+ case "none":+ return "—";+ }+}