Open-source SEO, GEO, and marketing skills for AI agents.
feat(ui): redesign goals and tool activity
Yuting Zhong26ddc1c0dd64
diff --git a/notfair/src/app/(app)/[project]/goals/page.tsx b/notfair/src/app/(app)/[project]/goals/page.tsxindex 99c0a521..9cb8a8e4 100644--- a/notfair/src/app/(app)/[project]/goals/page.tsx+++ b/notfair/src/app/(app)/[project]/goals/page.tsx@@ -3,26 +3,26 @@ import { notFound } from "next/navigation";import { Plus } from "lucide-react";import { getProject } from "@/server/db/projects";import { listProjectAgents } from "@/server/agent-meta";-import { getPinnedGoalIds, listGoals } from "@/server/db/goals";+import { getPinnedGoalIds, listGoals, listMetricSnapshots } from "@/server/db/goals";import { projectHref } from "@/lib/project-href";import { goalLabel } from "@/lib/goal-label";-import { GoalsBoard, type BoardGoal } from "@/components/goals-board";+import {+ GoalsBoard,+ type BoardGoal,+ type GoalDashboardSection,+} from "@/components/goals-board";import {listGoalGroupMemberships,listGoalGroups,- listGoalsInGroup,} from "@/server/db/goal-groups";-import { countGoalGroupHealth } from "@/lib/goal-group-health";-import { GoalGroupsOverview, type GoalGroupOverviewRow } from "@/components/goal-groups-overview";import { GoalGroupEditor, type GoalGroupEditorGoal } from "@/components/goal-group-editor";+import { GoalAutoRefresh } from "@/components/goal-auto-refresh";export const dynamic = "force-dynamic";/**- * The All-goals board: every goal in the workspace across its whole- * lifecycle, one column per state. The sidebar rail only carries live- * goals — this page is where closed goals (achieved, failed, or closed by- * hand) remain browsable.+ * The workspace goal dashboard: every main metric and its history, arranged+ * into the same goal groups users manage in the sidebar.*/export default async function AllGoalsPage({params,@@ -43,8 +43,8 @@ export default async function AllGoalsPage({);const groupById = new Map(groups.map((group) => [group.id, group.name]));- // Plain-JSON card props for the client board. Goals whose agent sidecar- // is missing (half-deleted workspace) have no page to link to — skip.+ // Plain-JSON card props for the dashboard. Goals whose agent sidecar is+ // missing (half-deleted workspace) have no page to link to, so skip them.const goals = projectGoals.flatMap<BoardGoal>((g) => {const agent = agentById.get(g.agent_id);if (!agent) return [];@@ -57,33 +57,44 @@ export default async function AllGoalsPage({status: g.status,status_reason: g.status_reason,metric_name: g.metric_name,- baseline_value: g.baseline_value,current_value: g.current_value,target_value: g.target_value,metric_direction: g.metric_direction,mode: g.mode,tick_count: g.tick_count,pinned: pinnedIds.has(g.id),- created_at: g.created_at,updated_at: g.updated_at,+ snapshots: listMetricSnapshots(g.id, 120).map((snapshot) => snapshot.value),},];});- const groupRows: GoalGroupOverviewRow[] = groups.map((group) => {- const members = listGoalsInGroup(group.id);- const counts = countGoalGroupHealth(members);- return {- id: group.id,- href: projectHref(slug, `/groups/${group.id}`),- name: group.name,- description: group.description,- goal_count: members.length,- healthy_count: counts.healthy,- attention_count: counts.attention,- waiting_count: counts.waiting + counts.paused,- };- });+ const goalById = new Map(goals.map((goal) => [goal.id, goal]));+ const goalsByGroup = new Map<string, BoardGoal[]>();+ for (const [goalId, groupId] of membershipByGoal) {+ const goal = goalById.get(goalId);+ if (!goal) continue;+ const groupGoals = goalsByGroup.get(groupId) ?? [];+ groupGoals.push(goal);+ goalsByGroup.set(groupId, groupGoals);+ }+ const sections: GoalDashboardSection[] = groups.map((group) => ({+ id: group.id,+ href: projectHref(slug, `/groups/${group.id}`),+ name: group.name,+ description: group.description || "A shared dashboard for related goals.",+ goals: goalsByGroup.get(group.id) ?? [],+ }));+ const ungroupedGoals = goals.filter((goal) => !membershipByGoal.has(goal.id));+ if (ungroupedGoals.length > 0) {+ sections.push({+ id: "ungrouped",+ href: null,+ name: "Ungrouped",+ description: "Independent goals that are not part of a shared dashboard.",+ goals: ungroupedGoals,+ });+ }const editorGoals: GoalGroupEditorGoal[] = projectGoals.map((goal) => {const groupId = membershipByGoal.get(goal.id) ?? null;return {@@ -95,53 +106,48 @@ export default async function AllGoalsPage({};});- // Anchored to the viewport region (like the goal screen) so the column- // strip scrolls inside the page instead of stretching SidebarInset — a- // flex item with no min-width — and dragging the whole body sideways.return (- <div className="absolute inset-0 flex flex-col overflow-y-auto px-7 pt-8 pb-4">- <header className="ns-page-head shrink-0">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">All goals</h1>- <p className="ns-page-sub">- Every goal in {project.display_name}, across its whole life —- filter by status, click through for the full story.- </p>- </div>- <div className="ns-page-actions">- <GoalGroupEditor projectSlug={slug} goals={editorGoals} />- <Link href={projectHref(slug, "")} className="ns-btn ns-btn-ghost shrink-0">- <Plus className="size-3.5" />- New goal- </Link>- </div>- </header>-- <section className="mb-7" aria-labelledby="goal-groups-heading">- <h2 id="goal-groups-heading" className="ns-h2 mt-0">- <span>Groups</span>- <span className="ns-h2-meta">Dashboards for related goals</span>- </h2>- <GoalGroupsOverview groups={groupRows} />- </section>-- {goals.length === 0 ? (- <div className="ns-card p-8 text-center">- <p className="m-0 text-[13.5px] text-[hsl(var(--notfair-ink-3))]">- No goals yet. State an ambition and NotFair will figure out how to- measure and chase it.- </p>- <Link- href={projectHref(slug, "")}- className="ns-btn ns-btn-primary mt-4 inline-flex"- >- <Plus className="size-3.5" />- Create your first goal- </Link>- </div>- ) : (- <GoalsBoard goals={goals} />+ <>+ {goals.some((goal) => goal.status === "active") && (+ <GoalAutoRefresh intervalMs={60_000} />)}- </div>+ <div className="absolute inset-0 overflow-y-auto">+ <main className="mx-auto w-full max-w-[1320px] px-4 pt-8 pb-20 sm:px-7">+ <header className="mb-8 flex flex-col gap-5 lg:flex-row lg:items-start lg:justify-between">+ <div className="ns-page-head-stack">+ <h1 className="ns-page-title">Goals dashboard</h1>+ <p className="ns-page-sub">+ Every main metric in {project.display_name}, grouped by the work it belongs to.+ </p>+ </div>+ <div className="ns-page-actions">+ <GoalGroupEditor projectSlug={slug} goals={editorGoals} />+ <Link href={projectHref(slug, "")} className="ns-btn ns-btn-ghost shrink-0">+ <Plus className="size-3.5" />+ New goal+ </Link>+ </div>+ </header>++ {goals.length === 0 ? (+ <div className="ns-card p-8 text-center">+ <p className="m-0 text-[13.5px] text-[hsl(var(--notfair-ink-3))]">+ No goals yet. State an ambition and NotFair will figure out how to+ measure and chase it.+ </p>+ <Link+ href={projectHref(slug, "")}+ className="ns-btn ns-btn-primary mt-4 inline-flex"+ >+ <Plus className="size-3.5" />+ Create your first goal+ </Link>+ </div>+ ) : (+ <GoalsBoard sections={sections} />+ )}+ </main>+ </div>+ </>);}diff --git a/notfair/src/components/chat/messages.test.tsx b/notfair/src/components/chat/messages.test.tsxindex 54656773..6ea67534 100644--- a/notfair/src/components/chat/messages.test.tsx+++ b/notfair/src/components/chat/messages.test.tsx@@ -41,4 +41,45 @@ describe("ToolGroup", () => {expect(container.querySelector("details")).toBe(details);expect(details).toHaveAttribute("open");});++ it("puts the disclosure control after the activity text and expands a flat scrollable list", () => {+ const { container } = render(+ <ToolGroup+ tools={[+ {+ ...runningTool,+ toolCallId: "edit-1",+ name: "Edit",+ label: "src/page.tsx",+ done: true,+ },+ {+ ...runningTool,+ toolCallId: "read-1",+ name: "Read",+ label: "DESIGN.md",+ done: true,+ },+ {+ ...runningTool,+ toolCallId: "shell-1",+ label: "rg -n ToolGroup src",+ done: true,+ },+ ]}+ />,+ );++ const summary = container.querySelector("summary")!;+ const label = summary.querySelector("[data-tool-summary]")!;+ const toggle = summary.querySelector("[data-tool-toggle]")!;+ const list = container.querySelector("[data-tool-list]")!;++ expect(label).toHaveTextContent("Edited file, read file, ran command");+ expect(label.nextElementSibling).toBe(toggle);+ expect(toggle).toHaveClass("opacity-0");+ expect(list).toHaveClass("max-h-64", "overflow-y-auto");+ expect(list.querySelectorAll("[data-tool-row]")).toHaveLength(3);+ expect(list.querySelector("[data-tool-row] .ml-5")).toBeNull();+ });});diff --git a/notfair/src/components/chat/messages.tsx b/notfair/src/components/chat/messages.tsxindex 7b8c7ec7..a5a897d7 100644--- a/notfair/src/components/chat/messages.tsx+++ b/notfair/src/components/chat/messages.tsx@@ -3,12 +3,12 @@import { useState } from "react";import {AlertCircle,- CheckCircle2,+ BookOpen,ChevronRight,- Loader2,MessageCircle,+ Search,+ Terminal,Wrench,- XCircle,} from "lucide-react";import { Markdown } from "@/components/markdown";@@ -17,8 +17,8 @@ import { cn } from "@/lib/utils";import {humanizeTool,iconForTool,+ looksLikeShellInvocation,matchMcpServerKey,- formatToolName,type McpCatalogEntryLite,} from "./tool-intent";import type { RenderedItem, ToolEntry } from "./transcript-model";@@ -111,79 +111,57 @@ export function ToolGroup({}) {const inFlightCount = tools.filter((t) => !t.done).length;const isLive = inFlightCount > 0;- const headline = tools.find((t) => !t.done) ?? tools[tools.length - 1] ?? null;- // Group status reflects the FINAL outcome, not "any error ever". When the- // agent retried a failed call and the retry succeeded, the user sees- // green — only expanding the card reveals the intermediate stumble.- // Matches Claude.ai's pattern of grading by "did this turn ultimately- // work" rather than punishing every recoverable hiccup.const lastDone = [...tools].reverse().find((t) => t.done);const hasError = !!(lastDone && !lastDone.ok);- const intent = headline- ? humanizeTool(headline.name, headline.label)- : { verb: "Tool call" };- const headMcp = headline ? matchMcpServerKey(headline.name, mcpCatalog) : null;- const HeadIcon = headline ? iconForTool(headline.name) : Wrench;- const mcpCount = tools.filter((tool) =>- matchMcpServerKey(tool.name, mcpCatalog),- ).length;- const StatusIcon = isLive ? Loader2 : hasError ? XCircle : CheckCircle2;- const statusClass = isLive- ? "text-[hsl(var(--notfair-accent))] motion-safe:animate-spin"- : hasError- ? "text-destructive"- : "text-emerald-500";- const summaryLabel =- tools.length === 1- ? intent.verb- : `${isLive ? "Using" : "Used"} ${tools.length} tools`;+ const headline = representativeTool(tools);+ const headMcp = headline+ ? matchMcpServerKey(headline.name, mcpCatalog)+ : null;+ const HeadIcon = headline ? iconForSummary(headline) : Wrench;+ const summaryLabel = summarizeTools(tools);+ const statusLabel = isLive ? "Running" : hasError ? "Failed" : "Complete";return (<detailsdata-activity-kind={headMcp ? "mcp" : "tool"}- className="group"+ className="group/details"><summaryclassName={cn(- "-mx-2 flex min-h-8 cursor-pointer select-none items-center gap-2 rounded-lg px-2 py-1 text-xs",- "transition-colors hover:bg-[hsl(var(--notfair-hover))] [&::-webkit-details-marker]:hidden",+ "group/summary flex min-h-8 cursor-pointer list-none select-none items-center gap-2 py-0.5 text-[15px] leading-6",+ "text-[hsl(var(--notfair-ink-3))] focus-visible:outline-none [&::-webkit-details-marker]:hidden",)}>- <ChevronRight className="size-3.5 shrink-0 text-muted-foreground/60 transition-transform group-open:rotate-90" />- {headMcp ? (- <ToolBrandFavicon- resourceUrl={headMcp.resource_url}- alt={headMcp.display_name}- />- ) : (- <HeadIcon className="size-3.5 shrink-0 text-muted-foreground" />- )}+ <span className="flex size-4 shrink-0 items-center justify-center">+ {headMcp ? (+ <ToolBrandFavicon+ resourceUrl={headMcp.resource_url}+ alt={headMcp.display_name}+ />+ ) : (+ <HeadIcon className="size-4" aria-hidden />+ )}+ </span><span+ data-tool-summaryclassName={cn(- "font-medium",- isLive ? "ns-shimmer-text" : "text-foreground/80",+ "min-w-0 truncate",+ isLive && "ns-shimmer-text",)}>{summaryLabel}</span>- {tools.length === 1 && intent.target && (- <span className="min-w-0 flex-1 truncate font-mono text-[10.5px] text-muted-foreground/80">- {intent.target}- </span>- )}- {tools.length === 1 && headMcp && (- <span className="truncate text-[10.5px] text-muted-foreground/80">- {headMcp.display_name} MCP- </span>- )}- {tools.length > 1 && mcpCount > 0 && (- <span className="text-[10.5px] text-muted-foreground/80">- {mcpCount} MCP {mcpCount === 1 ? "call" : "calls"}- </span>- )}- <StatusIcon className={cn("ml-auto size-3.5 shrink-0", statusClass)} />+ <ChevronRight+ data-tool-toggle+ className="size-4 shrink-0 opacity-0 transition-[transform,opacity] group-hover/summary:opacity-100 group-focus-visible/summary:opacity-100 group-open/details:rotate-90 group-open/details:opacity-100"+ aria-hidden+ />+ <span className="sr-only">{statusLabel}</span></summary>- <div className="mt-1.5 divide-y divide-border/30 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)] px-3.5 py-1">+ <div+ data-tool-list+ className="mt-1 max-h-64 overflow-y-auto overscroll-contain text-[15px] leading-6 text-[hsl(var(--notfair-ink-3))]"+ >{tools.map((t, index) => (<ToolRowkey={`${t.toolCallId}:${index}`}@@ -205,61 +183,124 @@ function ToolRow({}) {const intent = humanizeTool(entry.name, entry.label);const mcp = matchMcpServerKey(entry.name, mcpCatalog);- const Icon = iconForTool(entry.name);- const StatusIcon = entry.done- ? entry.ok- ? CheckCircle2- : XCircle- : Loader2;- const statusClass = entry.done- ? entry.ok- ? "text-emerald-500"- : "text-destructive"- : "text-[hsl(var(--notfair-accent))] motion-safe:animate-spin";- // Show the raw command/label only when it actually adds information —- // i.e. it's not redundant with the intent target the header already- // surfaces (path/url/etc.). Keeps simple tool rows tight while still- // exposing shell command lines and other raw invocations in full.- const showRawLabel =- !!entry.label &&- entry.label.trim() !== "" &&- entry.label.trim() !== intent.target?.trim();+ const Icon = iconForActivity(entry);+ const rowLabel = formatActivityLabel(intent.verb, intent.target);+ const statusLabel = !entry.done+ ? "Running"+ : entry.ok+ ? "Complete"+ : "Failed";+return (- <div className="space-y-1.5 py-2.5">- <div className="flex items-center gap-2 text-xs">- <StatusIcon className={cn("size-3.5 shrink-0", statusClass)} />- <span className="font-medium text-foreground/90">{intent.verb}</span>- {intent.target && (- <span className="min-w-0 flex-1 truncate font-mono text-[10.5px] text-muted-foreground">- {intent.target}- </span>- )}- <span className="ml-auto shrink-0 text-[10px] text-muted-foreground/70">- {mcp ? `${mcp.display_name} MCP` : "Local tool"}- </span>- </div>- <div className="ml-5 flex items-center gap-1.5 font-mono text-[10px] text-muted-foreground/60">+ <div+ data-tool-row+ data-tool-status={statusLabel.toLowerCase()}+ className="flex min-h-7 items-center gap-2 py-0.5"+ title={entry.label ?? rowLabel}+ >+ <span className="flex size-4 shrink-0 items-center justify-center">{mcp ? (- <ToolBrandFavicon resourceUrl={mcp.resource_url} alt={mcp.display_name} />+ <ToolBrandFavicon+ resourceUrl={mcp.resource_url}+ alt={mcp.display_name}+ />) : (- <Icon className="size-3 shrink-0" />+ <Icon className="size-4" aria-hidden />)}- <span>{formatToolName(entry.name)}</span>- </div>- {showRawLabel && (- <pre className="ml-5 max-h-40 overflow-auto rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 py-2 font-mono text-[10.5px] leading-relaxed text-foreground/75 whitespace-pre-wrap break-all">- {entry.label}- </pre>- )}- {entry.done && entry.result && (- <div className="ml-5 text-[11px] leading-relaxed text-muted-foreground/90">- <span className="break-words">{entry.result}</span>- </div>- )}+ </span>+ <span className="min-w-0 truncate">{rowLabel}</span>+ <span className="sr-only">{statusLabel}</span></div>);}+type ActivityCategory = "edit" | "read" | "command" | "other";++function activityCategory(entry: ToolEntry): ActivityCategory {+ const name = entry.name.toLowerCase();+ if (name === "write" || name === "edit" || name === "patch") return "edit";+ if (name === "read" || name === "cat" || name === "open") return "read";+ if (+ name === "shell" ||+ name === "bash" ||+ name === "exec" ||+ looksLikeShellInvocation(entry.name) ||+ looksLikeShellInvocation(entry.label ?? "")+ ) {+ return "command";+ }+ return "other";+}++/**+ * Use the same quiet, category-level summary as the reference transcript:+ * "Edited files, read files, ran commands" rather than a tool count.+ */+function summarizeTools(tools: ToolEntry[]): string {+ if (tools.length === 0) return "Tool activity";+ const phrases: string[] = [];+ const editCount = tools.filter(+ (tool) => activityCategory(tool) === "edit",+ ).length;+ const readCount = tools.filter(+ (tool) => activityCategory(tool) === "read",+ ).length;+ const commandCount = tools.filter(+ (tool) => activityCategory(tool) === "command",+ ).length;++ if (editCount > 0)+ phrases.push(editCount === 1 ? "Edited file" : "Edited files");+ if (readCount > 0)+ phrases.push(readCount === 1 ? "Read file" : "Read files");+ if (commandCount > 0)+ phrases.push(commandCount === 1 ? "Ran command" : "Ran commands");++ for (const tool of tools) {+ if (activityCategory(tool) !== "other") continue;+ const verb = humanizeTool(tool.name, tool.label).verb;+ if (!phrases.some((phrase) => phrase.toLowerCase() === verb.toLowerCase())) {+ phrases.push(verb);+ }+ }++ return phrases+ .map((phrase, index) =>+ index === 0 ? phrase : phrase.charAt(0).toLowerCase() + phrase.slice(1),+ )+ .join(", ");+}++function representativeTool(tools: ToolEntry[]): ToolEntry | null {+ for (const category of ["edit", "read", "command", "other"] as const) {+ const match = tools.find((tool) => activityCategory(tool) === category);+ if (match) return match;+ }+ return null;+}++function iconForActivity(entry: ToolEntry) {+ const verb = humanizeTool(entry.name, entry.label).verb.toLowerCase();+ if (verb.startsWith("searched")) return Search;+ if (verb.startsWith("read")) return BookOpen;+ return iconForTool(entry.name);+}++function iconForSummary(entry: ToolEntry) {+ const category = activityCategory(entry);+ if (category === "read") return BookOpen;+ if (category === "command") return Terminal;+ return iconForActivity(entry);+}++function formatActivityLabel(verb: string, target?: string): string {+ if (!target) return verb;+ // The intent already supplies the noun through the target, so avoid+ // stilted rows such as "Read file DESIGN.md".+ const compactVerb = verb.replace(/\s+(?:file|url)$/i, "");+ return `${compactVerb} ${target}`;+}+/*** Tiny inline favicon for an MCP tool row — sized to fit the same 3.5* grid slot as the lucide icons next to it, so MCP and built-in toolsdiff --git a/notfair/src/components/goal-groups-overview.tsx b/notfair/src/components/goal-groups-overview.tsxdeleted file mode 100644index 56c12f70..00000000--- a/notfair/src/components/goal-groups-overview.tsx+++ /dev/null@@ -1,57 +0,0 @@-import Link from "next/link";-import { FolderKanban } from "lucide-react";--export type GoalGroupOverviewRow = {- id: string;- href: string;- name: string;- description: string;- goal_count: number;- healthy_count: number;- attention_count: number;- waiting_count: number;-};--export function GoalGroupsOverview({ groups }: { groups: GoalGroupOverviewRow[] }) {- if (groups.length === 0) {- return (- <div className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.45)] px-4 py-5 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">- Group related goals to see their metrics and recent checks together.- </div>- );- }- return (- <ol className="ns-group">- {groups.map((group) => (- <li key={group.id}>- <Link href={group.href} className="ns-row-button">- <span className="ns-glyph" aria-hidden>- <FolderKanban className="size-4" />- </span>- <span className="ns-row-body min-w-0">- <span className="ns-row-title-row">- <span className="ns-row-title">{group.name}</span>- <span className="ns-tag-mono">{group.goal_count} goal{group.goal_count === 1 ? "" : "s"}</span>- </span>- <span className="ns-row-desc block truncate">- {group.description || "A shared dashboard for related goals."}- </span>- </span>- <span className="ml-auto flex shrink-0 items-center gap-3 text-[11.5px]">- {group.healthy_count > 0 && (- <span className="text-[hsl(var(--notfair-accent))]">{group.healthy_count} healthy</span>- )}- {group.attention_count > 0 && (- <span className="text-[hsl(var(--destructive))]">{group.attention_count} attention</span>- )}- {group.waiting_count > 0 && (- <span className="text-[hsl(var(--notfair-ink-4))]">{group.waiting_count} waiting</span>- )}- <span className="chev" aria-hidden>›</span>- </span>- </Link>- </li>- ))}- </ol>- );-}diff --git a/notfair/src/components/goal-sparkline.tsx b/notfair/src/components/goal-sparkline.tsxindex 9cef76bb..f722cef6 100644--- a/notfair/src/components/goal-sparkline.tsx+++ b/notfair/src/components/goal-sparkline.tsx@@ -18,7 +18,10 @@ export function GoalSparkline({}) {if (values.length < 2) {return (- <div className="flex h-24 items-center justify-center text-[12.5px] text-[hsl(var(--notfair-ink-4))]">+ <div+ className="flex items-center justify-center text-[12.5px] text-[hsl(var(--notfair-ink-4))]"+ style={{ height }}+ >Not enough readings yet — the sparkline appears after a couple of ticks.</div>);@@ -43,7 +46,7 @@ export function GoalSparkline({return (<svgviewBox={`0 0 ${width} ${height}`}- style={{ height: `${height <= 40 ? height : 96}px` }}+ style={{ height }}className="w-full"role="img"aria-label={`Metric trend: ${first} → ${last}${target !== null ? `, target ${target}` : ""}`}diff --git a/notfair/src/components/goals-board.test.tsx b/notfair/src/components/goals-board.test.tsxindex 649008b7..c981ffa7 100644--- a/notfair/src/components/goals-board.test.tsx+++ b/notfair/src/components/goals-board.test.tsx@@ -1,7 +1,11 @@// @vitest-environment jsdomimport { describe, expect, it } from "vitest";-import { fireEvent, render, screen, within } from "@testing-library/react";-import { GoalsBoard, type BoardGoal } from "./goals-board";+import { render, screen, within } from "@testing-library/react";+import {+ GoalsBoard,+ type BoardGoal,+ type GoalDashboardSection,+} from "./goals-board";function goal(overrides: Partial<BoardGoal>): BoardGoal {return {@@ -12,74 +16,135 @@ function goal(overrides: Partial<BoardGoal>): BoardGoal {status: "active",status_reason: null,metric_name: "Clicks",- baseline_value: 0,current_value: 5,target_value: 10,metric_direction: "increase",mode: "achieve",tick_count: 3,pinned: false,- created_at: "2026-07-01T00:00:00.000Z",updated_at: "2026-07-10T00:00:00.000Z",+ snapshots: [1, 3, 5],+ ...overrides,+ };+}++function section(overrides: Partial<GoalDashboardSection>): GoalDashboardSection {+ return {+ id: "group-1",+ name: "Acquisition",+ description: "Goals that grow qualified demand.",+ href: "/proj/groups/group-1",+ goals: [],...overrides,};}describe("GoalsBoard", () => {- it("groups goals into lifecycle columns", () => {+ it("renders group sections with every goal's metric history and destination", () => {render(<GoalsBoard- goals={[- goal({ id: "a", label: "Running goal", status: "active" }),- goal({ id: "b", label: "Won goal", status: "achieved", status_reason: "target hit" }),- goal({ id: "c", label: "Draft goal", status: "intake" }),+ sections={[+ section({+ goals: [+ goal({+ id: "clicks",+ href: "/proj/goals/clicks",+ label: "Organic clicks +30%",+ current_value: 76,+ target_value: 77,+ snapshots: [61, 69, 76],+ }),+ goal({+ id: "errors",+ href: "/proj/goals/errors",+ label: "Errors under 2%",+ metric_direction: "decrease",+ mode: "maintain",+ current_value: 1.82,+ target_value: 2,+ snapshots: [3.4, 2.5, 1.82],+ }),+ ],+ }),]}/>,);- expect(- within(screen.getByRole("region", { name: "Running" })).getByText("Running goal"),- ).toBeTruthy();- const achieved = screen.getByRole("region", { name: "Achieved" });- expect(within(achieved).getByText("Won goal")).toBeTruthy();- expect(within(achieved).getByText("target hit")).toBeTruthy();- expect(- within(screen.getByRole("region", { name: "Setting up" })).getByText("Draft goal"),- ).toBeTruthy();- });- it("toggling a status chip hides and restores its column", () => {- render(<GoalsBoard goals={[goal({ status: "active" })]} />);- const chip = screen.getByRole("button", { name: /Running/ });- expect(screen.getByRole("region", { name: "Running" })).toBeTruthy();+ const group = screen.getByRole("region", { name: "Acquisition" });+ expect(within(group).getByRole("link", { name: "Open group" })).toHaveAttribute(+ "href",+ "/proj/groups/group-1",+ );- fireEvent.click(chip);- expect(screen.queryByRole("region", { name: "Running" })).toBeNull();+ const clicks = within(group).getByRole("link", { name: /^Open Organic clicks \+30%/ });+ expect(clicks).toHaveAttribute("href", "/proj/goals/clicks");+ expect(within(clicks).getByText("76")).toBeTruthy();+ expect(within(clicks).getByText("target ≥ 77")).toBeTruthy();+ expect(+ within(clicks).getByRole("img", { name: /Metric trend: 61 → 76/ }),+ ).toHaveStyle({ height: "76px" });- fireEvent.click(chip);- expect(screen.getByRole("region", { name: "Running" })).toBeTruthy();+ const errors = within(group).getByRole("link", { name: /^Open Errors under 2%/ });+ expect(within(errors).getByText("hold ≤ 2")).toBeTruthy();+ expect(within(errors).getByText("on target")).toBeTruthy();});- it("sorts pinned goals to the top of their column", () => {+ it("keeps pinned goals first and closed goals behind live goals", () => {render(<GoalsBoard- goals={[- goal({ id: "old", label: "Older unpinned", created_at: "2026-07-02T00:00:00.000Z" }),- goal({- id: "new",- label: "Newest unpinned",- created_at: "2026-07-05T00:00:00.000Z",+ sections={[+ section({+ href: null,+ goals: [+ goal({ id: "closed", label: "Closed", status: "killed" }),+ goal({ id: "live", label: "Live", updated_at: "2026-07-20T00:00:00.000Z" }),+ goal({ id: "pinned", label: "Pinned", pinned: true }),+ ],}),- goal({- id: "pinned",- label: "Pinned goal",- pinned: true,- created_at: "2026-07-01T00:00:00.000Z",+ ]}+ />,+ );++ const links = within(screen.getByRole("region", { name: "Acquisition" }))+ .getAllByRole("link")+ .map((link) => link.getAttribute("aria-label")?.split(",")[0]);+ expect(links).toEqual(["Open Pinned", "Open Live", "Open Closed"]);+ });++ it("shows measured and unmeasured history empty states", () => {+ render(+ <GoalsBoard+ sections={[+ section({+ goals: [+ goal({ id: "one-reading", snapshots: [5] }),+ goal({+ id: "intake",+ label: "New goal",+ metric_name: null,+ current_value: null,+ target_value: null,+ snapshots: [],+ statement: "Measure signups from the new landing page.",+ status: "intake",+ }),+ ],}),]}/>,);- const cards = within(screen.getByRole("region", { name: "Running" })).getAllByRole("link");- expect(cards[0]!.textContent).toContain("Pinned goal");- expect(cards[1]!.textContent).toContain("Newest unpinned");++ expect(screen.getByText("Trend appears after the next reading")).toBeTruthy();+ expect(screen.getByText("Measure signups from the new landing page.")).toBeTruthy();+ expect(screen.getByText("Main metric is being defined")).toBeTruthy();+ });++ it("keeps empty groups visible and actionable", () => {+ render(<GoalsBoard sections={[section({ goals: [] })]} />);+ expect(screen.getByText("No goals in this group yet.", { exact: false })).toBeTruthy();+ expect(screen.getByRole("link", { name: "Open group" })).toHaveAttribute(+ "href",+ "/proj/groups/group-1",+ );});});diff --git a/notfair/src/components/goals-board.tsx b/notfair/src/components/goals-board.tsxindex 6d9d2fd7..764a8258 100644--- a/notfair/src/components/goals-board.tsx+++ b/notfair/src/components/goals-board.tsx@@ -1,14 +1,13 @@-"use client";-import Link from "next/link";-import { useState } from "react";-import { Pin } from "lucide-react";-import { cn } from "@/lib/utils";+import { ArrowUpRight, Pin } from "lucide-react";+import { GoalSparkline } from "@/components/goal-sparkline";import { formatMetric } from "@/lib/format-metric";+import { goalGroupHealth, type GoalGroupHealth } from "@/lib/goal-group-health";import { timeAgo } from "@/lib/time-ago";+import { cn } from "@/lib/utils";-// Local copy of the status union — this component is client-side and takes-// plain JSON props; importing from the server db module would be noise.+// Plain JSON is passed from the server route so this dashboard stays cheap to+// render and every card can be a normal link, with no client hydration needed.type GoalStatus =| "intake"| "proposed"@@ -26,215 +25,242 @@ export type BoardGoal = {status: GoalStatus;status_reason: string | null;metric_name: string | null;- baseline_value: number | null;current_value: number | null;target_value: number | null;metric_direction: "increase" | "decrease" | null;mode: "achieve" | "maintain";tick_count: number;pinned: boolean;- created_at: string;updated_at: string;+ snapshots: number[];};-type GroupKey = "setup" | "running" | "paused" | "achieved" | "failed" | "closed";--/**- * Board columns. Intake and proposed share a column — both are "the goal- * isn't running yet"; the card chip tells them apart (and flags the one- * waiting on the user's confirm in chat). The three terminal states each get- * their own column so an achieved goal reads as a win, not just "gone".- */-const GROUPS: Array<{- key: GroupKey;- title: string;- statuses: GoalStatus[];- dot: string;-}> = [- { key: "setup", title: "Setting up", statuses: ["intake", "proposed"], dot: "ns-dot-warn" },- { key: "running", title: "Running", statuses: ["active"], dot: "ns-dot-live" },- { key: "paused", title: "Paused", statuses: ["paused"], dot: "ns-dot-mute" },- { key: "achieved", title: "Achieved", statuses: ["achieved"], dot: "ns-dot-on" },- { key: "failed", title: "Failed", statuses: ["failed"], dot: "ns-dot-err" },- { key: "closed", title: "Closed", statuses: ["killed"], dot: "ns-dot-mute" },-];+export type GoalDashboardSection = {+ id: string;+ name: string;+ description: string;+ href: string | null;+ goals: BoardGoal[];+};const TERMINAL: GoalStatus[] = ["achieved", "failed", "killed"];+const HEALTH_COPY: Record<+ GoalGroupHealth,+ { label: string; dot: string; text: string }+> = {+ healthy: {+ label: "on target",+ dot: "ns-dot-live",+ text: "text-[hsl(var(--notfair-accent))]",+ },+ attention: {+ label: "needs attention",+ dot: "ns-dot-err",+ text: "text-[hsl(var(--destructive))]",+ },+ waiting: {+ label: "waiting for data",+ dot: "ns-dot-warn",+ text: "text-[hsl(var(--notfair-warn))]",+ },+ paused: {+ label: "paused",+ dot: "ns-dot-mute",+ text: "text-[hsl(var(--notfair-ink-4))]",+ },+ closed: {+ label: "closed",+ dot: "ns-dot-mute",+ text: "text-[hsl(var(--notfair-ink-4))]",+ },+};+/**- * Jira-style board of every goal in the project, one column per lifecycle- * group, with toggleable status filters. Read-only: cards link to the goal- * screen where the real controls live.+ * Workspace-level metric dashboard. Groups provide the page structure and+ * every raised surface is a real navigation target: clicking any metric card+ * opens that goal's full history and chat.*/-export function GoalsBoard({ goals }: { goals: BoardGoal[] }) {- const [visible, setVisible] = useState<Set<GroupKey>>(- () => new Set(GROUPS.map((g) => g.key)),- );-- function toggle(key: GroupKey) {- setVisible((prev) => {- const next = new Set(prev);- if (next.has(key)) next.delete(key);- else next.add(key);- return next;- });- }-- const columns = GROUPS.map((group) => {- const items = goals- .filter((g) => group.statuses.includes(g.status))- .sort((a, b) => {- if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;- // Closed columns: most recently closed first. Live columns: newest first.- const key = TERMINAL.includes(a.status) ? "updated_at" : "created_at";- return b[key].localeCompare(a[key]);- });- return { ...group, items };- });-- const shown = columns.filter((c) => visible.has(c.key));+export function GoalsBoard({ sections }: { sections: GoalDashboardSection[] }) {+ const allGoals = sections.flatMap((section) => section.goals);+ const running = allGoals.filter((goal) => goal.status === "active").length;+ const paused = allGoals.filter((goal) => goal.status === "paused").length;+ const closed = allGoals.filter((goal) => TERMINAL.includes(goal.status)).length;return (- <div className="flex min-h-0 flex-1 flex-col gap-4">- <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label="Filter goals by status">- {columns.map((c) => (- <button- key={c.key}- type="button"- onClick={() => toggle(c.key)}- aria-pressed={visible.has(c.key)}- className={cn(- "flex items-center gap-1.5 rounded-full px-3 py-1 text-[12.5px] font-medium transition-colors",- visible.has(c.key)- ? "bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-accent))] shadow-[var(--notfair-shadow-sm)]"- : "bg-[hsl(var(--notfair-surface-2)/0.6)] text-[hsl(var(--notfair-ink-3))] hover:bg-[hsl(var(--notfair-surface-2))]",- )}- >- <span className={cn("ns-dot", c.dot)} aria-hidden />- {c.title}- <span className="tabular-nums opacity-70">{c.items.length}</span>- </button>- ))}+ <div>+ <div+ className="mb-9 flex flex-wrap items-center gap-x-5 gap-y-2 text-[12px] text-[hsl(var(--notfair-ink-4))]"+ aria-label="Goals summary"+ >+ <span className="font-mono tabular-nums">+ {allGoals.length} goal{allGoals.length === 1 ? "" : "s"}+ </span>+ {running > 0 && (+ <span className="flex items-center gap-1.5 text-[hsl(var(--notfair-accent))]">+ <span className="ns-dot ns-dot-live" aria-hidden />+ {running} running+ </span>+ )}+ {paused > 0 && (+ <span className="flex items-center gap-1.5">+ <span className="ns-dot ns-dot-mute" aria-hidden />+ {paused} paused+ </span>+ )}+ {closed > 0 && (+ <span className="flex items-center gap-1.5">+ <span className="ns-dot ns-dot-mute" aria-hidden />+ {closed} closed+ </span>+ )}</div>- {shown.length === 0 ? (- <p className="m-0 py-10 text-center text-[13px] text-[hsl(var(--notfair-ink-4))]">- Every status is filtered out — turn one back on above.- </p>- ) : (- <div className="flex min-h-0 flex-1 items-start gap-3 overflow-x-auto pb-4">- {shown.map((c) => (- <section- key={c.key}- aria-label={c.title}- className="flex max-h-full w-[280px] shrink-0 flex-col rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)]"- >- <header className="flex items-center gap-2 px-3 pt-3 pb-2">- <span className={cn("ns-dot", c.dot)} aria-hidden />- <h2 className="m-0 text-[11px] font-semibold uppercase tracking-[0.08em] text-[hsl(var(--notfair-ink-3))]">- {c.title}- </h2>- <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {c.items.length}- </span>- </header>- <div className="flex min-h-0 flex-col gap-2 overflow-y-auto px-2 pb-2">- {c.items.length === 0 ? (- <p className="m-0 px-1.5 py-6 text-center text-[12px] text-[hsl(var(--notfair-ink-4))]">- No goals here+ <div className="flex flex-col gap-12">+ {sections.map((section) => {+ const goals = [...section.goals].sort((a, b) => {+ if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;+ if (TERMINAL.includes(a.status) !== TERMINAL.includes(b.status)) {+ return TERMINAL.includes(a.status) ? 1 : -1;+ }+ return b.updated_at.localeCompare(a.updated_at);+ });+ const headingId = `goal-section-${section.id}`;++ return (+ <section key={section.id} aria-labelledby={headingId}>+ <header className="mb-4 flex items-end justify-between gap-4">+ <div className="min-w-0">+ <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <h2+ id={headingId}+ className="m-0 text-[16px] font-semibold tracking-[-0.018em] text-[hsl(var(--notfair-ink-2))]"+ >+ {section.name}+ </h2>+ <span className="font-mono text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">+ {goals.length} goal{goals.length === 1 ? "" : "s"}+ </span>+ </div>+ <p className="m-0 mt-1 max-w-[70ch] text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">+ {section.description}</p>- ) : (- c.items.map((g) => <GoalCard key={g.id} goal={g} />)+ </div>+ {section.href && (+ <Link+ href={section.href}+ className="group/link flex shrink-0 items-center gap-1 text-[11.5px] text-[hsl(var(--notfair-ink-4))] transition-colors hover:text-[hsl(var(--notfair-ink-2))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ Open group+ <ArrowUpRight className="size-3 transition-transform group-hover/link:-translate-y-0.5 group-hover/link:translate-x-0.5" />+ </Link>)}- </div>+ </header>++ {goals.length === 0 ? (+ <div className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.42)] px-5 py-8 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">+ No goals in this group yet. Use <span className="text-[hsl(var(--notfair-ink-3))]">Manage group</span> to add one.+ </div>+ ) : (+ <div className="grid grid-cols-1 gap-3 lg:grid-cols-2 2xl:grid-cols-3">+ {goals.map((goal) => (+ <GoalMetricCard key={goal.id} goal={goal} />+ ))}+ </div>+ )}</section>- ))}- </div>- )}+ );+ })}+ </div></div>);}-/** Direction-agnostic progress toward target, 0..1, or null when unknowable. */-function progressFraction(g: BoardGoal): number | null {- if (- g.baseline_value === null ||- g.current_value === null ||- g.target_value === null ||- g.target_value === g.baseline_value- ) {- return null;- }- const f = (g.current_value - g.baseline_value) / (g.target_value - g.baseline_value);- return Math.min(1, Math.max(0, f));-}--function GoalCard({ goal }: { goal: BoardGoal }) {- const closed = TERMINAL.includes(goal.status);- const progress =- goal.status === "active" || goal.status === "paused" ? progressFraction(goal) : null;+function GoalMetricCard({ goal }: { goal: BoardGoal }) {+ const health = goalGroupHealth(goal);+ const healthCopy = HEALTH_COPY[health];+ const comparator = goal.metric_direction === "decrease" ? "≤" : "≥";+ const metricReady = goal.metric_name !== null;+ const hasChart = goal.snapshots.length >= 2;+ const accessibleTarget =+ goal.target_value === null+ ? ""+ : `, ${goal.mode === "maintain" ? "hold" : "target"} ${comparator} ${formatMetric(goal.target_value)}`;return (<Linkhref={goal.href}- className="ns-card block p-3 no-underline transition-shadow hover:shadow-[var(--notfair-shadow)]"+ aria-label={`Open ${goal.label}, current ${formatMetric(goal.current_value)}${accessibleTarget}`}+ className="group ns-card flex min-h-[250px] flex-col overflow-hidden p-5 no-underline transition-[transform,box-shadow,background-color] duration-150 hover:-translate-y-0.5 hover:shadow-[var(--notfair-shadow-lg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <div className="flex items-start justify-between gap-2">- <span className="min-w-0 flex-1 text-[13px] leading-snug font-semibold text-foreground">- {goal.label}+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span className={cn("ns-dot", healthCopy.dot)} aria-hidden />+ <h3 className="m-0 truncate text-[14px] font-semibold tracking-[-0.012em] text-foreground">+ {goal.label}+ </h3>+ {goal.pinned && (+ <Pin+ aria-label="Pinned"+ className="size-3 shrink-0 text-[hsl(var(--notfair-ink-4))]"+ />+ )}+ </div>+ <p className="m-0 mt-1 truncate text-[11.5px] text-[hsl(var(--notfair-ink-4))]">+ {goal.metric_name ?? "Main metric is being defined"}+ </p>+ </div>+ <span+ className={cn(+ "shrink-0 text-[10.5px] font-medium lowercase",+ healthCopy.text,+ )}+ >+ {healthCopy.label}</span>- {goal.pinned && (- <Pin- aria-label="Pinned"- className="mt-0.5 size-3 shrink-0 text-[hsl(var(--notfair-ink-4))]"- />- )}</div>- {goal.status === "proposed" && (- <span className="ns-tag-accent mt-1.5 inline-block">confirm the plan in chat</span>- )}- {goal.status === "intake" && (- <span className="ns-tag mt-1.5 inline-block">defining metric</span>- )}-- <p className="m-0 mt-1.5 line-clamp-2 text-[12px] leading-snug text-[hsl(var(--notfair-ink-3))]">- {goal.statement}- </p>-- {goal.metric_name && goal.target_value !== null && (- <p className="m-0 mt-2 text-[11.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- <span className="text-[hsl(var(--notfair-ink-3))]">{goal.metric_name}</span>{" "}- {formatMetric(goal.current_value)} / {formatMetric(goal.target_value)}- {goal.mode === "maintain" ? " (hold)" : ""}- </p>- )}+ <div className="mt-5 flex items-end gap-2">+ <span className="text-[28px] leading-none font-semibold tabular-nums tracking-[-0.035em] text-foreground">+ {formatMetric(goal.current_value)}+ </span>+ {goal.target_value !== null && (+ <span className="pb-0.5 font-mono text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">+ {goal.mode === "maintain" ? "hold " : "target "}+ {comparator} {formatMetric(goal.target_value)}+ </span>+ )}+ </div>- {progress !== null && (- <div- className="mt-1.5 h-[3px] w-full overflow-hidden rounded-full bg-[hsl(var(--notfair-ink-4)/0.12)]"- role="progressbar"- aria-valuenow={Math.round(progress * 100)}- aria-valuemin={0}- aria-valuemax={100}- >- <div- className="h-full rounded-full bg-[hsl(var(--notfair-accent))]"- style={{ width: `${Math.round(progress * 100)}%` }}+ <div className="mt-4 flex min-h-[92px] flex-1 items-center rounded-[10px] bg-[hsl(var(--notfair-surface-2)/0.46)] px-2.5 py-2">+ {hasChart ? (+ <GoalSparkline+ values={goal.snapshots}+ target={goal.target_value}+ direction={goal.metric_direction}+ width={520}+ height={76}/>- </div>- )}+ ) : (+ <div className="flex h-[76px] w-full items-center justify-center text-center text-[11.5px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">+ {metricReady+ ? "Trend appears after the next reading"+ : goal.statement}+ </div>+ )}+ </div>- {closed && goal.status_reason && (- <p className="m-0 mt-1.5 line-clamp-2 text-[11.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">- {goal.status_reason}- </p>- )}+ <div className="mt-4 flex items-center justify-between gap-3 font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">+ <span>+ {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"} · {timeAgo(goal.updated_at)}+ </span>+ <ArrowUpRight className="size-3.5 shrink-0 transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5" />+ </div>- <p className="m-0 mt-2 text-[11px] text-[hsl(var(--notfair-ink-4))]">- {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"} ·{" "}- {closed ? `closed ${timeAgo(goal.updated_at)}` : `updated ${timeAgo(goal.updated_at)}`}- </p>+ {TERMINAL.includes(goal.status) && goal.status_reason && (+ <span className="sr-only">{goal.status_reason}</span>+ )}</Link>);}