Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(notfair-cmo): Codex usage bars, pixel-art avatars, polished home

Yuting Zhong6bcd4f4037ec
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
index b966c0ad..5df7bcf4 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/page.tsx
@@ -1,31 +1,15 @@
import Link from "next/link";
-import {
- Bot,
- Briefcase,
- Check,
- Clock,
- Megaphone,
- MessageCircle,
- MessageSquare,
- Search,
- type LucideIcon,
-} from "lucide-react";
+import { Bot, Check, Clock, MessageSquare } from "lucide-react";
import { notFound } from "next/navigation";
import { getProject } from "@/server/db/projects";
-import { TEMPLATES, type AgentTemplateKey } from "@/server/agent-templates";
+import { TEMPLATES } from "@/server/agent-templates";
import { listProjectAgents } from "@/server/agent-meta";
import { listCronsForProject } from "@/server/scheduler/display";
import { reprovisionAgentsAction } from "@/server/actions/projects";
import { ReprovisionButton } from "@/components/reprovision-button";
+import { AgentAvatar } from "@/components/agent-avatar";
import { projectHref } from "@/lib/project-href";
-const ROLE_ICON: Record<AgentTemplateKey, LucideIcon> = {
- cmo: Briefcase,
- google_ads: Megaphone,
- meta_ads: MessageCircle,
- seo: Search,
-};
-
export default async function AgentsPage({
params,
}: {
@@ -67,16 +51,17 @@ export default async function AgentsPage({
const role = agent.template_key
? TEMPLATES.find((t) => t.key === agent.template_key)
: undefined;
- const Icon = agent.template_key
- ? ROLE_ICON[agent.template_key] ?? Bot
- : Bot;
const crons = cronByAgent.get(agent.agent_id) ?? 0;
return (
<div key={agent.agent_id} className="ns-card">
<div className="flex items-start gap-4 p-[18px]">
- <span className="ns-glyph" aria-hidden>
- <Icon className="size-[18px] text-[hsl(var(--notfair-ink-2))]" />
- </span>
+ {agent.template_key ? (
+ <AgentAvatar role={agent.template_key} size={44} />
+ ) : (
+ <span className="ns-glyph" aria-hidden>
+ <Bot className="size-[18px] text-[hsl(var(--notfair-ink-2))]" />
+ </span>
+ )}
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
<h2 className="m-0 text-[15.5px] font-semibold tracking-tight text-[hsl(var(--notfair-ink))]">
diff --git a/notfair-cmo/src/app/(app)/[project]/page.tsx b/notfair-cmo/src/app/(app)/[project]/page.tsx
index 04ae1e0f..70f1b63c 100644
--- a/notfair-cmo/src/app/(app)/[project]/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/page.tsx
@@ -1,26 +1,16 @@
import Link from "next/link";
import { notFound } from "next/navigation";
-import {
- Bot,
- Briefcase,
- Megaphone,
- MessageCircle,
- MessageSquare,
- Search,
- type LucideIcon,
-} from "lucide-react";
+import { Bot, MessageSquare } from "lucide-react";
import { getProject } from "@/server/db/projects";
-import { costToday } from "@/server/db/cost";
import { listPendingApprovals } from "@/server/db/approvals";
import { listTasks } from "@/server/db/tasks";
import { listAgentActions } from "@/server/db/agent-actions";
-import { TEMPLATES, type AgentTemplateKey } from "@/server/agent-templates";
+import { TEMPLATES } from "@/server/agent-templates";
import { listProjectAgents } from "@/server/agent-meta";
+import { colorForRole } from "@/lib/agent-colors";
+import { cn } from "@/lib/utils";
import { projectHref } from "@/lib/project-href";
-
-function formatUsd(n: number) {
- return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
-}
+import { AgentAvatar } from "@/components/agent-avatar";
function timeAgo(iso: string) {
const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
@@ -30,13 +20,6 @@ function timeAgo(iso: string) {
return `${Math.floor(seconds / 86400)}d ago`;
}
-const ROLE_ICON: Record<AgentTemplateKey, LucideIcon> = {
- cmo: Briefcase,
- google_ads: Megaphone,
- meta_ads: MessageCircle,
- seo: Search,
-};
-
export default async function ProjectHomePage({
params,
}: {
@@ -46,7 +29,6 @@ export default async function ProjectHomePage({
const project = getProject(slug);
if (!project || project.archived_at) notFound();
- const cost = costToday(project.slug);
const pending = listPendingApprovals(project.slug);
const tasks = listTasks(project.slug);
const recent = listAgentActions(project.slug, 8);
@@ -77,15 +59,9 @@ export default async function ProjectHomePage({
</div>
</header>
- {/* KPI strip — four quiet metric tiles. */}
- <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
- <KpiTile
- label="Spend today"
- value={formatUsd(cost.total_usd)}
- hint={`LLM ${formatUsd(cost.by_source.llm)} · Ads ${formatUsd(
- cost.by_source.google_ads + cost.by_source.gsc,
- )}`}
- />
+ {/* KPI strip. Spend tracking lives elsewhere now; the home tiles
+ surface only the counters the user has a direct action on. */}
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
<KpiTile
label="Active tasks"
value={String(running)}
@@ -121,23 +97,34 @@ export default async function ProjectHomePage({
const role = agent.template_key
? TEMPLATES.find((t) => t.key === agent.template_key)
: undefined;
- const Icon = agent.template_key
- ? ROLE_ICON[agent.template_key] ?? Bot
- : Bot;
+ const rolePalette = agent.template_key
+ ? colorForRole(agent.template_key)
+ : null;
return (
<li key={agent.agent_id}>
<Link
href={projectHref(slug, `/agents/${agent.slug}/chat`)}
className="ns-row-button"
>
- <span className="ns-glyph" aria-hidden>
- <Icon className="size-[18px] text-[hsl(var(--notfair-ink-2))]" />
- </span>
+ {agent.template_key ? (
+ <AgentAvatar role={agent.template_key} size={40} />
+ ) : (
+ <span className="ns-glyph" aria-hidden>
+ <Bot className="size-[18px] text-[hsl(var(--notfair-ink-2))]" />
+ </span>
+ )}
<span className="ns-row-body">
<span className="ns-row-title-row">
<span className="ns-row-title">{agent.name}</span>
{role && (
- <span className="ns-tag">{role.display_name}</span>
+ <span
+ className={cn(
+ "inline-flex items-center rounded-[5px] border px-1.5 py-[2px] text-[10.5px] font-medium uppercase tracking-wide leading-none",
+ rolePalette?.chip ?? "ns-tag",
+ )}
+ >
+ {role.display_name}
+ </span>
)}
</span>
<span className="ns-row-desc block">
diff --git a/notfair-cmo/src/components/agent-avatar.tsx b/notfair-cmo/src/components/agent-avatar.tsx
new file mode 100644
index 00000000..beeba212
--- /dev/null
+++ b/notfair-cmo/src/components/agent-avatar.tsx
@@ -0,0 +1,263 @@
+import type { AgentTemplateKey } from "@/server/agent-templates";
+
+/**
+ * Cute pixel-art avatars for each specialist role. Hand-designed on a
+ * 16×16 grid so the faces stay crisp at any render size (the SVG uses
+ * shape-rendering="crispEdges"). Each character has:
+ *
+ * - a role-tinted soft background circle, matching the colored chip
+ * used elsewhere in the system (CMO blue, Google Ads amber, Meta
+ * pink, SEO emerald)
+ * - a per-character palette (hair colour, accent) so the four faces
+ * are visually distinct at small sizes
+ * - one signature accessory (glasses, headset, hair clip, magnifying
+ * glass) so the role reads in one glance
+ *
+ * The grids are intentionally schematic — at 38px (the glyph slot) the
+ * eye is roughly 2×2 pixels, so we lean on the silhouette + hair +
+ * accessory rather than fine facial detail.
+ */
+
+type Avatar = {
+ grid: readonly string[];
+ palette: Record<string, string>;
+ /** Background wash behind the face — subtle role colour. */
+ bg: string;
+};
+
+const SKIN = "#F2C8A0";
+const SKIN_SHADOW = "#E0AE85";
+const EYE = "#1E1E22";
+const MOUTH = "#C36A6A";
+const CHEEK = "#F9B7A6";
+
+/**
+ * Greg — CMO. Neat side part, glasses, navy collar peeking. The
+ * executive of the four. Blue background to match the sidebar CMO chip.
+ */
+const CMO: Avatar = {
+ bg: "#DBE7FB",
+ palette: {
+ h: "#5B3A1F", // hair (warm brown)
+ H: "#3F2916", // hair shadow
+ s: SKIN,
+ S: SKIN_SHADOW,
+ e: EYE,
+ g: "#6B7280", // glasses frame
+ m: MOUTH,
+ c: CHEEK,
+ t: "#1F3A8A", // tie/jacket navy
+ w: "#FFFFFF", // shirt collar
+ },
+ grid: [
+ "................",
+ "................",
+ ".....HHHHHH.....",
+ "....HhhhhhhH....",
+ "...HhhhhhhhhH...",
+ "...Hhssssshhh...",
+ "...hsSssssShh...",
+ "...gsegssges....", // glasses
+ "...hsesssesh....",
+ "....hssssssh....",
+ "....cssmsscs....",
+ ".....ssssss.....",
+ "....wsssssw.....",
+ "...twwwwwwwt....", // collar + tie
+ "..tttttttttt....",
+ "..tttttttttt....",
+ ],
+};
+
+/**
+ * Ana — Google Ads specialist. Auburn ponytail, headset (the call-rep
+ * vibe of running campaigns), warm amber background. Energetic.
+ */
+const GOOGLE_ADS: Avatar = {
+ bg: "#FCE7C7",
+ palette: {
+ h: "#B85820", // auburn hair
+ H: "#8A3F12",
+ s: SKIN,
+ S: SKIN_SHADOW,
+ e: EYE,
+ m: MOUTH,
+ c: CHEEK,
+ y: "#F59E0B", // headset accent
+ Y: "#92400E",
+ p: "#FFD9C2", // earring highlight
+ },
+ grid: [
+ "................",
+ "................",
+ "....HHHHHHH.....",
+ "...HhhhhhhhH....",
+ "..yHhhhhhhhHy...", // headset over hair
+ "..ysshhhhhssy...",
+ "..ysSsssssSsy...",
+ "..yseSsssSesy...",
+ "..ssssesessss...",
+ "...ssssssssp....", // earring dot
+ "...cssmmsscs....",
+ "....ssssssss....",
+ "....ssssssss....",
+ "...HhhhhhhhH....", // hair flows behind shoulders
+ "..HhhhhhhhhhH...",
+ "..hhhhhhhhhhhh..",
+ ],
+};
+
+/**
+ * Mia — Meta Ads specialist. Pink bob, side bangs, a sparkle decoration
+ * (creative/social vibe). Pink background to match the chip.
+ */
+const META_ADS: Avatar = {
+ bg: "#FCD5E2",
+ palette: {
+ h: "#E45A8A", // pink hair
+ H: "#B83465",
+ s: SKIN,
+ S: SKIN_SHADOW,
+ e: EYE,
+ m: MOUTH,
+ c: CHEEK,
+ p: "#FCE7F0", // hair highlight
+ "*": "#F472B6", // sparkle
+ },
+ grid: [
+ "................",
+ "................",
+ "...HHHHHHHHH....",
+ "..HhhhhhhhhhH...",
+ ".Hhhhhhhhhhhh*..", // sparkle
+ ".HhpssssspphhH..",
+ ".Hhsssssssshh...",
+ ".Hheseeesssh....",
+ ".Hssseessshh....",
+ "..hssSsssShh....",
+ "..cssmmmssc.....",
+ "...ssssssss.....",
+ "...ssssssss.....",
+ "..HhsssssshH....",
+ ".HhhhhhhhhhhH...",
+ "..hhhhhhhhhh....",
+ ],
+};
+
+/**
+ * Sam — SEO specialist. Green hair, round glasses with a magnifying-
+ * glass handle peeking off one side (the search motif). Emerald
+ * background.
+ */
+const SEO: Avatar = {
+ bg: "#D4EEDD",
+ palette: {
+ h: "#3F8A4F", // green hair
+ H: "#2A5E36",
+ s: SKIN,
+ S: SKIN_SHADOW,
+ e: EYE,
+ m: MOUTH,
+ c: CHEEK,
+ g: "#374151", // glasses + handle
+ G: "#9CA3AF", // glasses inside highlight
+ },
+ grid: [
+ "................",
+ "................",
+ "....HHHHHHH.....",
+ "...HhhhhhhhH....",
+ "..HhhhhhhhhhH...",
+ "..Hhssssssshh...",
+ "..hssSsssssSh...",
+ "..gggssssgggh...", // glasses arms
+ "..gGgeggeGgg....", // glasses lenses + eyes
+ "...gggssgggg....",
+ "...hsmmmsshg....", // handle of magnifier
+ "....ssssssg.....",
+ "....csscssg.....",
+ "...hssssshg.....",
+ "..hhhhhhhhh.....",
+ "..hhhhhhhhh.....",
+ ],
+};
+
+const AVATARS: Record<AgentTemplateKey, Avatar> = {
+ cmo: CMO,
+ google_ads: GOOGLE_ADS,
+ meta_ads: META_ADS,
+ seo: SEO,
+};
+
+/**
+ * Render the pixel-art avatar for a template-backed agent. Pass the
+ * pixel size (defaults to 38, matching `.ns-glyph`). The component
+ * collapses to a `null` if no avatar exists for the role — callers
+ * should fall back to a generic icon in that case.
+ */
+export function AgentAvatar({
+ role,
+ size = 38,
+ className,
+}: {
+ role: AgentTemplateKey | null | undefined;
+ size?: number;
+ className?: string;
+}) {
+ const avatar = role ? AVATARS[role] : undefined;
+ if (!avatar) return null;
+ const grid = avatar.grid;
+ const cols = grid[0]!.length;
+ const rows = grid.length;
+ const cellPx = size / Math.max(cols, rows);
+
+ // One <rect> per non-transparent pixel. We also draw a background
+ // circle (a 16-wide rounded rect that fills the viewBox) so the
+ // avatar reads as a single chip the way our other ns-glyph slots do.
+ const rects: React.ReactNode[] = [];
+ rects.push(
+ <rect
+ key="bg"
+ x={0}
+ y={0}
+ width={cols}
+ height={rows}
+ rx={cols * 0.22}
+ ry={rows * 0.22}
+ fill={avatar.bg}
+ />,
+ );
+ for (let y = 0; y < rows; y++) {
+ const row = grid[y]!;
+ for (let x = 0; x < cols; x++) {
+ const ch = row[x]!;
+ const color = avatar.palette[ch];
+ if (!color) continue;
+ rects.push(
+ <rect
+ key={`${x}-${y}`}
+ x={x}
+ y={y}
+ width={1.01} // tiny overlap kills sub-pixel seams when zoomed
+ height={1.01}
+ fill={color}
+ />,
+ );
+ }
+ }
+
+ return (
+ <svg
+ role="img"
+ aria-hidden
+ width={size}
+ height={size}
+ viewBox={`0 0 ${cols} ${rows}`}
+ shapeRendering="crispEdges"
+ style={{ width: size, height: size, display: "block" }}
+ className={className}
+ >
+ {rects}
+ </svg>
+ );
+}
diff --git a/notfair-cmo/src/components/agent-nav.tsx b/notfair-cmo/src/components/agent-nav.tsx
index a3ca97d9..74c2e783 100644
--- a/notfair-cmo/src/components/agent-nav.tsx
+++ b/notfair-cmo/src/components/agent-nav.tsx
@@ -2,14 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import {
- Bot,
- Briefcase,
- Megaphone,
- MessageCircle,
- Search,
- type LucideIcon,
-} from "lucide-react";
+import { Bot } from "lucide-react";
import {
SidebarMenu,
SidebarMenuButton,
@@ -19,6 +12,7 @@ import type { AgentTemplateKey } from "@/server/agent-templates";
import { colorForRole } from "@/lib/agent-colors";
import { cn } from "@/lib/utils";
import { projectHref } from "@/lib/project-href";
+import { AgentAvatar } from "./agent-avatar";
import { useLiveCounts } from "./live-counts-context";
type AgentNavEntry = {
@@ -47,13 +41,6 @@ type Props = {
inFlightCounts?: Record<string, number>;
};
-const TEMPLATE_ICONS: Record<AgentTemplateKey, LucideIcon> = {
- cmo: Briefcase,
- google_ads: Megaphone,
- meta_ads: MessageCircle,
- seo: Search,
-};
-
export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
const pathname = usePathname();
const live = useLiveCounts();
@@ -68,14 +55,17 @@ export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
const agentBase = `/${projectSlug}/agents/${a.slug}`;
const isActive =
pathname === agentBase || pathname?.startsWith(`${agentBase}/`);
- const Icon = a.template_key ? TEMPLATE_ICONS[a.template_key] ?? Bot : Bot;
const liveCount = counts[a.key] ?? 0;
const rolePalette = a.template_key ? colorForRole(a.template_key) : null;
return (
<SidebarMenuItem key={a.key}>
<SidebarMenuButton asChild isActive={isActive}>
<Link href={href}>
- <Icon />
+ {a.template_key ? (
+ <AgentAvatar role={a.template_key} size={20} />
+ ) : (
+ <Bot />
+ )}
<span className="truncate">{a.name}</span>
{a.role_label && rolePalette && (
<span
@@ -93,10 +83,7 @@ export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
role="status"
aria-label={`${liveCount} running`}
>
- <span
- aria-hidden
- className="ns-dot ns-dot-live"
- />
+ <span aria-hidden className="ns-dot ns-dot-live" />
<span className="text-[10px] font-semibold tabular-nums text-[hsl(var(--notfair-accent))]">
{liveCount}
</span>
diff --git a/notfair-cmo/src/components/app-sidebar.tsx b/notfair-cmo/src/components/app-sidebar.tsx
index 38bfeec6..071ef733 100644
--- a/notfair-cmo/src/components/app-sidebar.tsx
+++ b/notfair-cmo/src/components/app-sidebar.tsx
@@ -27,10 +27,12 @@ import { listProjects } from "@/server/db/projects";
import { getActiveProject } from "@/server/active-project";
import { listProjectAgents } from "@/server/agent-meta";
import { TEMPLATES } from "@/server/agent-templates";
+import { readHarnessUsage } from "@/server/harness-usage";
import { projectHref } from "@/lib/project-href";
import { ProjectSwitcher } from "./project-switcher";
import { AgentNav } from "./agent-nav";
import { ApprovalsLiveBadge } from "./live-badge";
+import { HarnessFooter } from "./harness-footer";
type NavItem = {
href: string;
@@ -53,6 +55,13 @@ export async function AppSidebar() {
const projects = listProjects();
const active = await getActiveProject();
const agentEntries = active ? await listProjectAgents(active.slug) : [];
+ // Best-effort fetch of harness usage. For Codex this hits the
+ // chatgpt.com wham/usage endpoint (cached 60s in-process); for
+ // Claude Code it just reads the local stats-cache. Either failure
+ // mode collapses to a quieter chip.
+ const harnessUsage = active
+ ? await readHarnessUsage(active.harness_adapter)
+ : null;
return (
<Sidebar collapsible="icon">
@@ -121,14 +130,12 @@ export async function AppSidebar() {
)}
</SidebarContent>
- {active && (
+ {active && harnessUsage && (
<SidebarFooter className="border-t border-border/60 px-3 py-2 group-data-[collapsible=icon]:hidden">
- <p className="text-[11px] leading-tight text-muted-foreground">
- Local agents · running on{" "}
- <span className="font-medium text-foreground">
- {active.harness_adapter === "codex-local" ? "Codex" : "Claude Code"}
- </span>
- </p>
+ <HarnessFooter
+ adapter={active.harness_adapter}
+ usage={harnessUsage}
+ />
</SidebarFooter>
)}
</Sidebar>
diff --git a/notfair-cmo/src/components/harness-footer.tsx b/notfair-cmo/src/components/harness-footer.tsx
new file mode 100644
index 00000000..3e3547af
--- /dev/null
+++ b/notfair-cmo/src/components/harness-footer.tsx
@@ -0,0 +1,291 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { ChevronDown } from "lucide-react";
+import type { HarnessUsage, RateLimitWindow } from "@/server/harness-usage";
+
+type Props = {
+ adapter: "claude-code-local" | "codex-local";
+ usage: HarnessUsage;
+};
+
+const HARNESS_LABEL: Record<Props["adapter"], string> = {
+ "codex-local": "Codex",
+ "claude-code-local": "Claude Code",
+};
+
+// localStorage key — single bool. Default = expanded (we want users to
+// see their usage at a glance on first install; collapsing is a
+// per-user preference for once they've internalised the pattern).
+const COLLAPSE_KEY = "notfair-cmo:harness-footer:collapsed";
+
+/**
+ * Sidebar footer summary of the active harness. The header row (dot,
+ * harness name, plan chip, chevron) is always visible and acts as the
+ * collapse toggle; the detail section below — usage bars for Codex,
+ * activity counts for Claude Code — hides when the user collapses.
+ *
+ * State is persisted in localStorage so the choice survives page
+ * reloads. Default is expanded.
+ */
+export function HarnessFooter({ adapter, usage }: Props) {
+ const harnessName = HARNESS_LABEL[adapter];
+ // Default to expanded; hydrate from localStorage after mount so SSR
+ // and first paint stay deterministic.
+ const [collapsed, setCollapsed] = useState(false);
+ const [hydrated, setHydrated] = useState(false);
+
+ useEffect(() => {
+ try {
+ const raw = window.localStorage.getItem(COLLAPSE_KEY);
+ if (raw === "1") setCollapsed(true);
+ } catch {
+ // localStorage unavailable — keep the default.
+ }
+ setHydrated(true);
+ }, []);
+
+ useEffect(() => {
+ if (!hydrated) return;
+ try {
+ if (collapsed) window.localStorage.setItem(COLLAPSE_KEY, "1");
+ else window.localStorage.removeItem(COLLAPSE_KEY);
+ } catch {
+ // Storage write failure is non-fatal.
+ }
+ }, [collapsed, hydrated]);
+
+ if (usage.kind === "codex") {
+ const planLabel = formatPlan(usage.plan);
+ return (
+ <FooterShell>
+ <FooterHeader
+ harness={harnessName}
+ chip={planLabel ? `ChatGPT ${planLabel}` : null}
+ chipTone="accent"
+ collapsed={collapsed}
+ onToggle={() => setCollapsed((v) => !v)}
+ />
+ {!collapsed &&
+ (usage.rateLimit ? (
+ <div className="mt-2 space-y-2">
+ <UsageBar label="5-hour" window={usage.rateLimit.primary} />
+ <UsageBar label="Weekly" window={usage.rateLimit.secondary} />
+ </div>
+ ) : (
+ <FooterDetail>Sign in to Codex to see usage limits</FooterDetail>
+ ))}
+ </FooterShell>
+ );
+ }
+
+ if (usage.kind === "claude-code") {
+ const detail = usage.stale
+ ? lastSeenLabel(usage.lastComputedDate)
+ : `${formatCount(usage.messagesToday)} msg · ${formatTokens(
+ usage.tokensToday,
+ )} today`;
+ return (
+ <FooterShell>
+ <FooterHeader
+ harness={harnessName}
+ chip={usage.stale ? "Idle" : "Active today"}
+ chipTone={usage.stale ? "neutral" : "accent"}
+ collapsed={collapsed}
+ onToggle={() => setCollapsed((v) => !v)}
+ />
+ {!collapsed && detail && <FooterDetail>{detail}</FooterDetail>}
+ </FooterShell>
+ );
+ }
+
+ // Unknown harness — nothing collapsible, just a tiny chip.
+ return (
+ <FooterShell>
+ <FooterHeader
+ harness={harnessName}
+ chip={null}
+ collapsed={false}
+ onToggle={null}
+ />
+ </FooterShell>
+ );
+}
+
+function FooterShell({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="flex flex-col px-1 py-1.5 leading-tight">{children}</div>
+ );
+}
+
+function FooterHeader({
+ harness,
+ chip,
+ chipTone = "neutral",
+ collapsed,
+ onToggle,
+}: {
+ harness: string;
+ chip: string | null;
+ chipTone?: "accent" | "neutral";
+ collapsed: boolean;
+ onToggle: (() => void) | null;
+}) {
+ const body = (
+ <>
+ <span
+ aria-hidden
+ className={`ns-dot ${chipTone === "accent" ? "ns-dot-on" : "ns-dot-mute"}`}
+ />
+ <span className="text-[12px] font-medium tracking-tight text-[hsl(var(--notfair-ink-2))]">
+ {harness}
+ </span>
+ {chip && (
+ <span className="ml-auto truncate text-[11px] font-medium text-[hsl(var(--notfair-ink-4))]">
+ {chip}
+ </span>
+ )}
+ {onToggle && (
+ <ChevronDown
+ aria-hidden
+ className={`size-3 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform duration-150 ${
+ collapsed ? "-rotate-90" : ""
+ } ${chip ? "ml-1" : "ml-auto"}`}
+ />
+ )}
+ </>
+ );
+
+ if (!onToggle) {
+ return <div className="flex items-center gap-1.5">{body}</div>;
+ }
+
+ return (
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={!collapsed}
+ aria-label={collapsed ? "Show harness usage" : "Hide harness usage"}
+ className="-mx-1 flex w-[calc(100%+0.5rem)] items-center gap-1.5 rounded-md px-1 py-0.5 transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"
+ >
+ {body}
+ </button>
+ );
+}
+
+function FooterDetail({ children }: { children: React.ReactNode }) {
+ return (
+ <p className="m-0 mt-1 truncate text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {children}
+ </p>
+ );
+}
+
+/**
+ * Usage bar — label + remaining percent + thin progress track + reset
+ * timestamp. Mirrors the ChatGPT settings page bars but compact enough
+ * to fit a 240px sidebar.
+ */
+function UsageBar({
+ label,
+ window,
+}: {
+ label: string;
+ window: RateLimitWindow;
+}) {
+ const used = clamp(window.used_percent, 0, 100);
+ const remaining = 100 - used;
+ // Bar color signals headroom. Brand green when comfortable, amber
+ // approaching the limit, red when about to hit it.
+ const tone =
+ remaining < 5
+ ? "bg-[hsl(0_72%_51%)]"
+ : remaining < 20
+ ? "bg-[hsl(38_92%_50%)]"
+ : "bg-[hsl(var(--notfair-accent))]";
+ return (
+ <div>
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="text-[11px] font-medium text-[hsl(var(--notfair-ink-3))]">
+ {label}
+ </span>
+ <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {Math.round(remaining)}% left
+ </span>
+ </div>
+ <div
+ className="mt-1 h-[3px] w-full overflow-hidden rounded-full bg-[hsl(var(--notfair-surface-2))]"
+ role="progressbar"
+ aria-label={`${label} usage`}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(used)}
+ >
+ <div
+ className={`h-full rounded-full transition-[width] ${tone}`}
+ style={{ width: `${remaining}%` }}
+ />
+ </div>
+ <p className="m-0 mt-0.5 text-[10.5px] text-[hsl(var(--notfair-ink-4))]">
+ Resets {formatReset(window.reset_at)}
+ </p>
+ </div>
+ );
+}
+
+function formatPlan(slug: string | null): string | null {
+ if (!slug) return null;
+ // wham/usage returns lowercase plan slugs like "prolite", "pro",
+ // "free", "plus". Title-case and tidy a couple of multi-word ones.
+ const map: Record<string, string> = {
+ prolite: "Plus",
+ pro: "Pro",
+ free: "Free",
+ plus: "Plus",
+ business: "Business",
+ enterprise: "Enterprise",
+ edu: "Edu",
+ };
+ return map[slug] ?? slug.charAt(0).toUpperCase() + slug.slice(1);
+}
+
+function formatReset(unixSeconds: number): string {
+ const now = Date.now();
+ const target = unixSeconds * 1000;
+ const deltaMs = target - now;
+ if (deltaMs <= 0) return "now";
+ const minutes = Math.round(deltaMs / 60_000);
+ if (minutes < 60) return `in ${minutes}m`;
+ const hours = Math.round(deltaMs / 3_600_000);
+ if (hours < 24) return `in ${hours}h`;
+ const date = new Date(target);
+ return date.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ });
+}
+
+function formatCount(n: number): string {
+ if (n >= 1000) return `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}K`;
+ return String(n);
+}
+
+function formatTokens(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1000) return `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}K`;
+ return `${n}`;
+}
+
+function lastSeenLabel(iso: string | null): string {
+ if (!iso) return "No usage logged";
+ const d = new Date(`${iso}T00:00:00`);
+ if (Number.isNaN(d.getTime())) return "No usage logged";
+ return `Last seen ${d.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ })}`;
+}
+
+function clamp(n: number, min: number, max: number): number {
+ return Math.max(min, Math.min(max, n));
+}
diff --git a/notfair-cmo/src/server/harness-usage.ts b/notfair-cmo/src/server/harness-usage.ts
new file mode 100644
index 00000000..b4f5b901
--- /dev/null
+++ b/notfair-cmo/src/server/harness-usage.ts
@@ -0,0 +1,216 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+/**
+ * Read what each local AI-agent harness exposes about the user's account
+ * so the sidebar footer can surface real account state instead of just
+ * the harness name.
+ *
+ * - **codex-local** → hits `https://chatgpt.com/backend-api/wham/usage`
+ * using the access token from `~/.codex/auth.json`. That's the same
+ * endpoint the ChatGPT settings page reads to render the 5-hour and
+ * weekly usage bars. Returns `used_percent`, the rolling window
+ * duration, and the unix-epoch `reset_at` for both windows.
+ * Cached in-process so navigating between pages doesn't beat on
+ * chatgpt.com once per render.
+ *
+ * - **claude-code-local** → `~/.claude/stats-cache.json`. Updated by
+ * the `claude` CLI on each run; contains per-day message/session/
+ * token rollups. Goes stale when `claude` hasn't run today, which
+ * we surface so the UI doesn't pretend a stale snapshot is "today".
+ *
+ * Failure modes (network error, missing/expired token, missing file,
+ * malformed JSON) all fall through to the harness-specific `unknown`
+ * shape — the sidebar footer must never break because chatgpt.com is
+ * unreachable or `auth.json` was rotated.
+ */
+
+export type RateLimitWindow = {
+ /** Fractional percent already consumed in the rolling window. */
+ used_percent: number;
+ /** Length of the rolling window (e.g. 18000 = 5h, 604800 = 7d). */
+ limit_window_seconds: number;
+ /** Unix epoch (seconds) when this window's usage tally resets. */
+ reset_at: number;
+};
+
+export type CodexUsage = {
+ kind: "codex";
+ /** Codex plan name from wham/usage (e.g. "prolite", "pro", "free"). */
+ plan: string | null;
+ /** Account email from the JWT — used as a tooltip / accessibility hint. */
+ email: string | null;
+ /** Two-window rate limits, or null when the API call failed.
+ * primary = short rolling window (~5h); secondary = ~7d window. */
+ rateLimit: { primary: RateLimitWindow; secondary: RateLimitWindow } | null;
+};
+
+export type ClaudeUsage = {
+ kind: "claude-code";
+ messagesToday: number;
+ sessionsToday: number;
+ /** Sum across every model that ran today. */
+ tokensToday: number;
+ /** True when stats-cache.json hasn't been recomputed today. The UI
+ * shows a quieter message in this state so the row doesn't read as
+ * "0 messages today" (true but misleading). */
+ stale: boolean;
+ /** YYYY-MM-DD of the latest day stats were rolled up. */
+ lastComputedDate: string | null;
+};
+
+export type HarnessUsage =
+ | CodexUsage
+ | ClaudeUsage
+ | { kind: "unknown" };
+
+// In-process cache keyed by adapter. The chatgpt.com usage endpoint
+// updates whenever the user runs codex, so a 60s TTL keeps the bars
+// responsive without hammering the backend on every sidebar render.
+type CacheEntry = { until: number; value: HarnessUsage };
+const cache = new Map<string, CacheEntry>();
+const CACHE_TTL_MS = 60_000;
+
+export async function readHarnessUsage(
+ adapter: "claude-code-local" | "codex-local",
+): Promise<HarnessUsage> {
+ const hit = cache.get(adapter);
+ if (hit && hit.until > Date.now()) return hit.value;
+ let value: HarnessUsage;
+ try {
+ if (adapter === "codex-local") value = await readCodexUsage();
+ else if (adapter === "claude-code-local") value = readClaudeUsage();
+ else value = { kind: "unknown" };
+ } catch {
+ value = { kind: "unknown" };
+ }
+ cache.set(adapter, { until: Date.now() + CACHE_TTL_MS, value });
+ return value;
+}
+
+async function readCodexUsage(): Promise<HarnessUsage> {
+ const authFile = path.join(os.homedir(), ".codex", "auth.json");
+ if (!fs.existsSync(authFile)) {
+ return { kind: "codex", plan: null, email: null, rateLimit: null };
+ }
+ const auth = JSON.parse(fs.readFileSync(authFile, "utf-8")) as {
+ tokens?: { access_token?: string; id_token?: string };
+ };
+ const accessToken = auth.tokens?.access_token;
+ if (!accessToken) {
+ return { kind: "codex", plan: null, email: null, rateLimit: null };
+ }
+
+ // Decode just to pull the email + chatgpt account id (needed as the
+ // ChatGPT-Account-Id header so the backend scopes the response to
+ // the right workspace).
+ const { email, accountId } = decodeIdToken(auth.tokens?.id_token);
+
+ let plan: string | null = null;
+ let rateLimit: CodexUsage["rateLimit"] = null;
+ try {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), 4000);
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${accessToken}`,
+ Accept: "application/json",
+ };
+ if (accountId) headers["ChatGPT-Account-Id"] = accountId;
+ const res = await fetch("https://chatgpt.com/backend-api/wham/usage", {
+ headers,
+ signal: ctrl.signal,
+ });
+ clearTimeout(t);
+ if (res.ok) {
+ const body = (await res.json()) as {
+ plan_type?: string;
+ rate_limit?: {
+ primary_window?: RateLimitWindow;
+ secondary_window?: RateLimitWindow;
+ };
+ };
+ if (typeof body.plan_type === "string") plan = body.plan_type;
+ const p = body.rate_limit?.primary_window;
+ const s = body.rate_limit?.secondary_window;
+ if (p && s) {
+ rateLimit = { primary: p, secondary: s };
+ }
+ }
+ } catch {
+ // Network error / abort — leave rateLimit null; the footer falls
+ // back to the plan chip only.
+ }
+
+ return { kind: "codex", plan, email, rateLimit };
+}
+
+function decodeIdToken(idToken: string | undefined): {
+ email: string | null;
+ accountId: string | null;
+} {
+ if (!idToken) return { email: null, accountId: null };
+ const parts = idToken.split(".");
+ if (parts.length < 2) return { email: null, accountId: null };
+ try {
+ const claims = JSON.parse(
+ Buffer.from(parts[1]!, "base64url").toString("utf-8"),
+ ) as Record<string, unknown>;
+ const authClaims =
+ (claims["https://api.openai.com/auth"] as
+ | Record<string, unknown>
+ | undefined) ?? {};
+ return {
+ email: typeof claims.email === "string" ? claims.email : null,
+ accountId:
+ typeof authClaims.chatgpt_account_id === "string"
+ ? authClaims.chatgpt_account_id
+ : null,
+ };
+ } catch {
+ return { email: null, accountId: null };
+ }
+}
+
+function readClaudeUsage(): HarnessUsage {
+ const file = path.join(os.homedir(), ".claude", "stats-cache.json");
+ if (!fs.existsSync(file)) {
+ return {
+ kind: "claude-code",
+ messagesToday: 0,
+ sessionsToday: 0,
+ tokensToday: 0,
+ stale: true,
+ lastComputedDate: null,
+ };
+ }
+ const stats = JSON.parse(fs.readFileSync(file, "utf-8")) as {
+ dailyActivity?: Array<{
+ date: string;
+ messageCount?: number;
+ sessionCount?: number;
+ }>;
+ dailyModelTokens?: Array<{
+ date: string;
+ tokensByModel?: Record<string, number>;
+ }>;
+ lastComputedDate?: string;
+ };
+ const today = new Date().toISOString().slice(0, 10);
+ const todayActivity = stats.dailyActivity?.find((d) => d.date === today);
+ const todayTokens = stats.dailyModelTokens?.find((d) => d.date === today);
+ const tokensSum = todayTokens
+ ? Object.values(todayTokens.tokensByModel ?? {}).reduce(
+ (sum, v) => sum + (typeof v === "number" ? v : 0),
+ 0,
+ )
+ : 0;
+ return {
+ kind: "claude-code",
+ messagesToday: todayActivity?.messageCount ?? 0,
+ sessionsToday: todayActivity?.sessionCount ?? 0,
+ tokensToday: tokensSum,
+ stale: stats.lastComputedDate !== today,
+ lastComputedDate: stats.lastComputedDate ?? null,
+ };
+}