Skip to content

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

feat(notfair-cmo): Slack-style needs-you badges + task rail simplification

Yuting Zhong8092f037f9b2
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
index dfd31f44..c16f6301 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
@@ -106,7 +106,7 @@ export default async function AgentChatThreadPage({
<GoogleAdsMcpBanner status={googleAdsMcpStatus} projectSlug={projectSlug} />
)}
- <div className="flex items-center justify-between border-b bg-background/80 px-6 py-2 backdrop-blur">
+ <div className="flex items-center justify-between bg-background/80 px-6 py-2 backdrop-blur">
<div className="text-xs text-muted-foreground">
{sessionsForDropdown.length === 0
? "No threads yet"
diff --git a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
index 8186c303..02592ea1 100644
--- a/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
+++ b/notfair-cmo/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
@@ -5,6 +5,7 @@ import { getProject } from "@/server/db/projects";
import { getMcpCatalog } from "@/server/mcp-catalog";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { listApprovalsForTask } from "@/server/db/approvals";
+import { attentionByTaskForAgent } from "@/server/db/attention";
import { listQuestionsForTask } from "@/server/db/questions";
import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";
import { buildPendingSessionKey, findSessionBySessionId } from "@/server/sessions/view";
@@ -81,6 +82,7 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {
const tasks = listTasksByAgent(agentFullId);
const proposedCount = tasks.filter((t) => t.status === "proposed").length;
+ const attentionByTask = attentionByTaskForAgent(project.slug, agentFullId);
// Brand-favicon lookup table for MCP tool calls in the transcript.
const mcpCatalog = getMcpCatalog(project.slug).map((m) => ({
key: m.key,
@@ -97,6 +99,7 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {
tasks={tasks}
selected={selected}
proposedCount={proposedCount}
+ attentionByTask={attentionByTask}
mcpCatalog={mcpCatalog}
/>
);
diff --git a/notfair-cmo/src/app/(app)/layout.tsx b/notfair-cmo/src/app/(app)/layout.tsx
index 2afd5de8..d5cefe10 100644
--- a/notfair-cmo/src/app/(app)/layout.tsx
+++ b/notfair-cmo/src/app/(app)/layout.tsx
@@ -4,6 +4,7 @@ import { ClientMountGate } from "@/components/client-mount-gate";
import { LiveCountsProvider } from "@/components/live-counts-context";
import { getActiveProject } from "@/server/active-project";
import { actionableApprovalCount } from "@/server/db/approvals";
+import { attentionByAgent } from "@/server/db/attention";
import { inFlightCountsByAgent } from "@/server/db/tasks";
export default async function AppLayout({ children }: { children: React.ReactNode }) {
@@ -18,6 +19,7 @@ export default async function AppLayout({ children }: { children: React.ReactNod
}
}
const initialApprovals = active ? actionableApprovalCount(active.slug) : 0;
+ const initialAttention = active ? attentionByAgent(active.slug) : {};
return (
<ClientMountGate
@@ -32,6 +34,7 @@ export default async function AppLayout({ children }: { children: React.ReactNod
project: active?.slug ?? null,
agents: initialAgents,
approvals: initialApprovals,
+ attention: initialAttention,
}}
>
<SidebarProvider>
diff --git a/notfair-cmo/src/app/api/in-flight-counts/route.ts b/notfair-cmo/src/app/api/in-flight-counts/route.ts
index d35fc048..1cc3fe80 100644
--- a/notfair-cmo/src/app/api/in-flight-counts/route.ts
+++ b/notfair-cmo/src/app/api/in-flight-counts/route.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { getActiveProject } from "@/server/active-project";
import { actionableApprovalCount } from "@/server/db/approvals";
+import { attentionByAgent } from "@/server/db/attention";
import { inFlightCountsByAgent } from "@/server/db/tasks";
export const dynamic = "force-dynamic";
@@ -16,11 +17,17 @@ export const runtime = "nodejs";
export async function GET() {
const project = await getActiveProject();
if (!project) {
- return NextResponse.json({ project: null, agents: {}, approvals: 0 });
+ return NextResponse.json({
+ project: null,
+ agents: {},
+ approvals: 0,
+ attention: {},
+ });
}
const countsMap = inFlightCountsByAgent(project.slug);
const agents: Record<string, number> = {};
for (const [agentId, count] of countsMap) agents[agentId] = count;
const approvals = actionableApprovalCount(project.slug);
- return NextResponse.json({ project: project.slug, agents, approvals });
+ const attention = attentionByAgent(project.slug);
+ return NextResponse.json({ project: project.slug, agents, approvals, attention });
}
diff --git a/notfair-cmo/src/components/agent-nav.test.tsx b/notfair-cmo/src/components/agent-nav.test.tsx
index 176869c3..4ddd8d61 100644
--- a/notfair-cmo/src/components/agent-nav.test.tsx
+++ b/notfair-cmo/src/components/agent-nav.test.tsx
@@ -94,26 +94,47 @@ describe("AgentNav", () => {
expect(target?.getAttribute("data-active")).toBe("true");
});
- it("renders the in-flight count badge when count > 0", () => {
+ it("renders the red attention badge and deep-links to the blocked task", () => {
render(
<AgentNav
projectSlug="proj"
agents={agents}
- inFlightCounts={{ "proj-cmo": 3 }}
+ attention={{ "proj-cmo": { count: 1, task_id: "demo1-1" } }}
/>,
);
- expect(screen.getByText("3")).toBeInTheDocument();
- expect(screen.getByLabelText("3 running")).toBeInTheDocument();
+ expect(
+ screen.getByLabelText("1 waiting on your answer"),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /Greg/i })).toHaveAttribute(
+ "href",
+ "/proj/agents/cmo-greg/tasks?task=demo1-1",
+ );
+ // Other agents keep the default chat link.
+ expect(screen.getByRole("link", { name: /Ana/i })).toHaveAttribute(
+ "href",
+ "/proj/agents/google-ads-ana/chat",
+ );
});
- it("does not render a count when in-flight is 0", () => {
+ it("falls back to the Tasks tab when no waiting item is task-anchored", () => {
render(
<AgentNav
projectSlug="proj"
agents={agents}
- inFlightCounts={{ "proj-cmo": 0 }}
+ attention={{ "proj-cmo": { count: 2, task_id: null } }}
/>,
);
- expect(screen.queryByLabelText(/running/i)).not.toBeInTheDocument();
+ expect(
+ screen.getByLabelText("2 waiting on your answer"),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /Greg/i })).toHaveAttribute(
+ "href",
+ "/proj/agents/cmo-greg/tasks",
+ );
+ });
+
+ it("renders no indicator at all when nothing needs the user", () => {
+ render(<AgentNav projectSlug="proj" agents={agents} />);
+ expect(screen.queryByRole("status")).not.toBeInTheDocument();
});
});
diff --git a/notfair-cmo/src/components/agent-nav.tsx b/notfair-cmo/src/components/agent-nav.tsx
index feb41396..b0aee040 100644
--- a/notfair-cmo/src/components/agent-nav.tsx
+++ b/notfair-cmo/src/components/agent-nav.tsx
@@ -33,30 +33,43 @@ type Props = {
projectSlug: string;
agents: AgentNavEntry[];
/**
- * Optional server-side initial map (agent_id → in-flight count) used
+ * Optional server-side initial map (agent_id → attention entry) used
* for the first paint only. After mount, live values come from
* LiveCountsContext so we don't re-render the parent server component
* just to flip a number.
*/
- inFlightCounts?: Record<string, number>;
+ attention?: Record<string, { count: number; task_id: string | null }>;
};
-export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
+export function AgentNav({ projectSlug, agents, attention = {} }: Props) {
const pathname = usePathname();
const live = useLiveCounts();
- const counts: Record<string, number> = { ...inFlightCounts, ...live.agents };
+ const attentionByAgent = { ...attention, ...live.attention };
return (
<SidebarMenu>
{agents.map((a) => {
+ // Slack model: when the agent is blocked on the user, the row IS
+ // the notification — red badge, and the click lands directly in
+ // the decision space (the blocked task's page) instead of Chat.
+ const agentAttention = attentionByAgent[a.key];
+ const needsYou = (agentAttention?.count ?? 0) > 0;
// Every agent lands on Chat by default — users start by talking to
// the agent. Tasks tab (the audit/history view of filed work) is one
// click away.
- const href = projectHref(projectSlug, `/agents/${a.slug}/chat`);
+ const href = needsYou
+ ? projectHref(
+ projectSlug,
+ `/agents/${a.slug}/tasks${
+ agentAttention?.task_id
+ ? `?task=${encodeURIComponent(agentAttention.task_id)}`
+ : ""
+ }`,
+ )
+ : projectHref(projectSlug, `/agents/${a.slug}/chat`);
const agentBase = `/${projectSlug}/agents/${a.slug}`;
const isActive =
pathname === agentBase || pathname?.startsWith(`${agentBase}/`);
- const liveCount = counts[a.key] ?? 0;
const rolePalette = a.template_key ? colorForRole(a.template_key) : null;
return (
<SidebarMenuItem key={a.key}>
@@ -78,16 +91,13 @@ export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
{a.role_label}
</span>
)}
- {liveCount > 0 && (
+ {needsYou && (
<span
- className="ml-auto inline-flex items-center gap-1.5"
role="status"
- aria-label={`${liveCount} running`}
+ aria-label={`${agentAttention!.count} waiting on your answer`}
+ className="ml-auto inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-[hsl(var(--destructive))] px-1 text-[10px] font-semibold tabular-nums leading-none text-white"
>
- <span aria-hidden className="ns-dot ns-dot-live" />
- <span className="text-[10px] font-semibold tabular-nums text-[hsl(var(--notfair-accent))]">
- {liveCount}
- </span>
+ {agentAttention!.count}
</span>
)}
</Link>
diff --git a/notfair-cmo/src/components/agent-task-workspace.test.tsx b/notfair-cmo/src/components/agent-task-workspace.test.tsx
index ff0a9146..79b8acce 100644
--- a/notfair-cmo/src/components/agent-task-workspace.test.tsx
+++ b/notfair-cmo/src/components/agent-task-workspace.test.tsx
@@ -112,9 +112,8 @@ beforeEach(() => {
});
describe("AgentTaskWorkspace empty state", () => {
- it("shows 'Nothing assigned yet.' subtitle and zero count when tasks is empty", () => {
+ it("shows the empty rail message when tasks is empty", () => {
render(<AgentTaskWorkspace {...baseProps()} />);
- expect(screen.getByText("Nothing assigned yet.")).toBeInTheDocument();
expect(screen.getByText("The CMO will delegate tasks here.")).toBeInTheDocument();
// Right pane empty state for hasTasks=false.
expect(screen.getByText(/Google Ads has no tasks yet/)).toBeInTheDocument();
@@ -133,24 +132,19 @@ describe("AgentTaskWorkspace empty state", () => {
});
});
-describe("AgentTaskWorkspace in-flight summary + StartAllTasksButton", () => {
- it("counts running + proposed + approved as 'in flight' and hides the start-all button when proposedCount=0", () => {
+describe("AgentTaskWorkspace StartAllTasksButton", () => {
+ it("hides the start-all button when proposedCount=0", () => {
render(
<AgentTaskWorkspace
{...baseProps({
tasks: [
makeTask({ id: "a", display_id: "demo-1", status: "working" }),
- makeTask({ id: "b", display_id: "demo-2", status: "approved" }),
makeTask({ id: "c", display_id: "demo-3", status: "done" }),
],
proposedCount: 0,
})}
/>,
);
- expect(screen.getByText(/in flight/)).toBeInTheDocument();
- // The summary "2 in flight" text is split across nodes; just look for "2".
- const inFlightPara = screen.getByText(/in flight/).closest("p");
- expect(inFlightPara?.textContent).toContain("2");
expect(screen.queryByRole("button", { name: /Start all/ })).not.toBeInTheDocument();
});
@@ -165,42 +159,51 @@ describe("AgentTaskWorkspace in-flight summary + StartAllTasksButton", () => {
);
expect(screen.getByRole("button", { name: /Start all 1 task/ })).toBeInTheDocument();
});
+});
- it("falls back to 'All quiet.' when there are tasks but none in flight", () => {
+describe("AgentTaskWorkspace task list", () => {
+ it("renders one flat list — no status group headers", () => {
render(
<AgentTaskWorkspace
{...baseProps({
- tasks: [makeTask({ status: "done" })],
+ tasks: [
+ makeTask({ id: "1", display_id: "demo-1", status: "working", title: "one" }),
+ makeTask({ id: "2", display_id: "demo-2", status: "proposed", title: "two" }),
+ makeTask({ id: "3", display_id: "demo-3", status: "done", title: "three" }),
+ makeTask({ id: "4", display_id: "demo-4", status: "failed", title: "four", error_message: "boom" }),
+ ],
})}
/>,
);
- expect(screen.getByText("All quiet.")).toBeInTheDocument();
+ // All four rows render in a single list without section labels.
+ expect(screen.getAllByRole("listitem")).toHaveLength(4);
+ for (const label of ["Working", "Proposed", "Done", "Failed"]) {
+ expect(screen.queryByText(label)).not.toBeInTheDocument();
+ }
+ // Failed task still surfaces the error message in the row.
+ expect(screen.getByText("boom")).toBeInTheDocument();
});
-});
-describe("AgentTaskWorkspace task list grouping", () => {
- it("groups tasks by status and labels each group", () => {
+ it("shows the red attention badge on rows whose task waits on the user", () => {
render(
<AgentTaskWorkspace
{...baseProps({
tasks: [
- makeTask({ id: "1", display_id: "demo-1", status: "working" }),
- makeTask({ id: "2", display_id: "demo-2", status: "proposed" }),
- makeTask({ id: "3", display_id: "demo-3", status: "done" }),
- makeTask({ id: "4", display_id: "demo-4", status: "failed", error_message: "boom" }),
+ makeTask({ id: "b1", display_id: "demo-1", status: "blocked", title: "needs me" }),
+ makeTask({ id: "ok", display_id: "demo-2", status: "working", title: "fine" }),
],
+ attentionByTask: { b1: 2 },
})}
/>,
);
- expect(screen.getByText("Working")).toBeInTheDocument();
- expect(screen.getByText("Proposed")).toBeInTheDocument();
- expect(screen.getByText("Done")).toBeInTheDocument();
- expect(screen.getByText("Failed")).toBeInTheDocument();
- // Failed task surfaces the error message in the row.
- expect(screen.getByText("boom")).toBeInTheDocument();
+ expect(screen.getByLabelText("2 waiting on your answer")).toBeInTheDocument();
+ // The badge sits inside the row of the blocked task, not the other one.
+ expect(
+ screen.getByText("needs me").closest("button"),
+ ).toContainElement(screen.getByLabelText("2 waiting on your answer"));
});
- it("falls back to brief.slice(0,80) when task.title is null", () => {
+ it("falls back to a brief excerpt when task.title is null", () => {
const brief = "This is a fallback brief shown when the task has no title field at all and we need text.";
render(
<AgentTaskWorkspace
@@ -209,7 +212,7 @@ describe("AgentTaskWorkspace task list grouping", () => {
})}
/>,
);
- expect(screen.getByText(brief.slice(0, 80))).toBeInTheDocument();
+ expect(screen.getByText(brief.slice(0, 160))).toBeInTheDocument();
});
it("clicking a task row calls router.replace with the display_id as ?task=", () => {
diff --git a/notfair-cmo/src/components/agent-task-workspace.tsx b/notfair-cmo/src/components/agent-task-workspace.tsx
index 6e9fd48e..fedf14c5 100644
--- a/notfair-cmo/src/components/agent-task-workspace.tsx
+++ b/notfair-cmo/src/components/agent-task-workspace.tsx
@@ -40,21 +40,6 @@ const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "working", "blocke
// composer is a parallel channel for free-form direction.
const COMPOSER_LOCKED: TaskStatus[] = ["proposed", "approved", "working"];
-// `blocked` covers two distinct reasons: waiting on an approval, or
-// waiting on another task to finish. The section header stays generic
-// ("Blocked") and each row's subline spells out the actual reason —
-// avoids the previous "Waiting on approval" label being a lie when the
-// real blocker is an upstream task.
-const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [
- { status: "working", label: "Working" },
- { status: "blocked", label: "Blocked" },
- { status: "proposed", label: "Proposed" },
- { status: "approved", label: "Approved" },
- { status: "done", label: "Done" },
- { status: "failed", label: "Failed" },
- { status: "cancelled", label: "Cancelled" },
-];
-
const STATUS_VARIANT: Record<
TaskStatus,
"default" | "secondary" | "outline" | "destructive"
@@ -96,6 +81,9 @@ type Props = {
tasks: Task[];
selected: SelectedTaskBundle | null;
proposedCount: number;
+ /** task_id → count of pending questions/approvals waiting on the user.
+ * Rows in the rail show the Slack-style red badge when > 0. */
+ attentionByTask?: Record<string, number>;
/** MCP catalog forwarded to the per-task LiveTranscript so tool calls
* that resolve to an MCP server render the server's brand favicon. */
mcpCatalog?: McpCatalogEntryLite[];
@@ -109,22 +97,13 @@ export function AgentTaskWorkspace({
tasks,
selected,
proposedCount,
+ attentionByTask = {},
mcpCatalog,
}: Props) {
const router = useRouter();
const search = useSearchParams();
const selectedId = search.get("task");
- const grouped = useMemo(() => {
- const map = new Map<TaskStatus, Task[]>();
- for (const t of tasks) {
- const list = map.get(t.status) ?? [];
- list.push(t);
- map.set(t.status, list);
- }
- return map;
- }, [tasks]);
-
// Resolve blocker → blocker task. Used by TaskRow to show a
// "Waiting on <display_id>" subline on tasks blocked by an upstream
// task (vs. tasks blocked by an approval). Internal-only — only the
@@ -137,10 +116,6 @@ export function AgentTaskWorkspace({
}, [tasks]);
const totalCount = tasks.length;
- const inFlightCount =
- (grouped.get("working")?.length ?? 0) +
- (grouped.get("proposed")?.length ?? 0) +
- (grouped.get("approved")?.length ?? 0);
function selectTask(displayId: string) {
const params = new URLSearchParams(search?.toString() ?? "");
@@ -156,28 +131,14 @@ export function AgentTaskWorkspace({
the open transcript. */}
{/* ── Left pane: task list ─────────────────────────────────────── */}
<aside className="flex w-80 shrink-0 flex-col bg-[hsl(var(--notfair-sidebar))]">
- <div className="px-4 py-3">
- <p className="text-[11px] text-muted-foreground">
- {inFlightCount > 0 ? (
- <span className="inline-flex items-center gap-1.5">
- <RunningDot size="sm" aria-label="" />
- <span className="tabular-nums">{inFlightCount}</span> in flight
- </span>
- ) : totalCount === 0 ? (
- "Nothing assigned yet."
- ) : (
- "All quiet."
- )}
- </p>
- {proposedCount > 0 && (
- <div className="mt-2">
- <StartAllTasksButton
- agentId={agentFullId}
- proposedCount={proposedCount}
- />
- </div>
- )}
- </div>
+ {proposedCount > 0 && (
+ <div className="px-4 py-3">
+ <StartAllTasksButton
+ agentId={agentFullId}
+ proposedCount={proposedCount}
+ />
+ </div>
+ )}
<div className="min-h-0 flex-1 overflow-y-auto py-1">
{totalCount === 0 ? (
@@ -185,40 +146,27 @@ export function AgentTaskWorkspace({
The CMO will delegate tasks here.
</div>
) : (
- STATUS_GROUPS.map((group) => {
- const items = grouped.get(group.status);
- if (!items || items.length === 0) return null;
- return (
- <div key={group.status} className="py-1">
- <div className="flex items-center justify-between px-4 py-1.5">
- <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
- {group.label}
- </span>
- <span className="text-[10px] tabular-nums text-muted-foreground">
- {items.length}
- </span>
- </div>
- <ul>
- {items.map((t) => (
- <li key={t.id}>
- <TaskRow
- task={t}
- blocker={
- t.blocked_by_task_id
- ? taskById.get(t.blocked_by_task_id)
- : undefined
- }
- selected={
- t.display_id === selectedId || t.id === selectedId
- }
- onSelect={() => selectTask(t.display_id)}
- />
- </li>
- ))}
- </ul>
- </div>
- );
- })
+ /* gap-1 matches SidebarMenu's item spacing so the task rail
+ reads like the agent list. */
+ <ul className="flex flex-col gap-1">
+ {tasks.map((t) => (
+ <li key={t.id}>
+ <TaskRow
+ task={t}
+ blocker={
+ t.blocked_by_task_id
+ ? taskById.get(t.blocked_by_task_id)
+ : undefined
+ }
+ attentionCount={attentionByTask[t.id] ?? 0}
+ selected={
+ t.display_id === selectedId || t.id === selectedId
+ }
+ onSelect={() => selectTask(t.display_id)}
+ />
+ </li>
+ ))}
+ </ul>
)}
</div>
</aside>
@@ -490,6 +438,7 @@ function CancelTaskButton({ taskDisplayId }: { taskDisplayId: string }) {
function TaskRow({
task,
blocker,
+ attentionCount = 0,
selected,
onSelect,
}: {
@@ -497,6 +446,9 @@ function TaskRow({
/** When this task is blocked by another task, the blocker (for the
* "Waiting on <id>" subline). Undefined for approval-blocked tasks. */
blocker?: Task;
+ /** Pending questions/approvals on this task waiting on the user —
+ * renders the Slack-style red badge when > 0. */
+ attentionCount?: number;
selected: boolean;
onSelect: () => void;
}) {
@@ -511,11 +463,16 @@ function TaskRow({
onClick={onSelect}
aria-current={selected ? "true" : undefined}
className={cn(
- "group block w-full px-4 py-2.5 text-left transition-colors",
- "hover:bg-accent/40 focus-visible:outline-none focus-visible:bg-accent/40",
- selected && "bg-accent/80 hover:bg-accent/80",
+ // Mirror the sidebar's SidebarMenuButton look (rounded-md, inset,
+ // sidebar-accent fill on hover/selected) so picking a task reads
+ // the same as picking an agent.
+ "group mx-2 block w-[calc(100%-1rem)] rounded-md px-2.5 py-2 text-left transition-colors",
+ "hover:bg-sidebar-accent focus-visible:outline-none focus-visible:bg-sidebar-accent",
+ selected && "bg-sidebar-accent",
)}
>
+ {/* Line 1: glyph + task id (+ red badge). Line 2: title, clamped to
+ two rows with an ellipsis so long briefs never overflow the rail. */}
<div className="flex items-center gap-2.5">
<span className="flex size-3.5 shrink-0 items-center justify-center">
{isRunning ? (
@@ -524,22 +481,29 @@ function TaskRow({
<StatusGlyph status={task.status} />
)}
</span>
- <span className="min-w-0 flex-1 truncate text-xs">
- <span className="mr-1.5 font-mono text-[10px] text-muted-foreground tabular-nums">
- {task.display_id.toUpperCase()}
- </span>
+ <span className="min-w-0 flex-1 truncate font-mono text-[10px] font-medium text-muted-foreground tabular-nums">
+ {task.display_id.toUpperCase()}
+ </span>
+ {attentionCount > 0 && (
<span
- className={cn(
- selected ? "font-medium text-foreground" : "text-foreground/90",
- !isInFlight && task.status !== "working" && "text-muted-foreground",
- )}
+ role="status"
+ aria-label={`${attentionCount} waiting on your answer`}
+ className="inline-flex h-[18px] min-w-[18px] shrink-0 items-center justify-center rounded-full bg-[hsl(var(--destructive))] px-1 text-[10px] font-semibold tabular-nums leading-none text-white"
>
- {task.title ?? task.brief.slice(0, 80)}
+ {attentionCount}
</span>
- </span>
- <span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
- {formatRelative(task.updated_at)}
- </span>
+ )}
+ </div>
+ <div
+ className={cn(
+ // leading-4 (1rem) × 2 lines = min-h-8: one-line titles reserve
+ // the second line's space so every row is the same height.
+ "ml-6 mt-0.5 line-clamp-2 min-h-8 text-xs leading-4",
+ selected ? "font-medium text-foreground" : "text-foreground/90",
+ !isInFlight && task.status !== "working" && "text-muted-foreground",
+ )}
+ >
+ {task.title ?? task.brief.slice(0, 160)}
</div>
{task.status === "failed" && task.error_message && (
<div className="ml-6 mt-1 line-clamp-1 text-[10px] text-destructive/80">
@@ -622,20 +586,6 @@ function parseOptionsJson(json: string): string[] {
return [];
}
-function formatRelative(iso: string): string {
- const t = Date.parse(iso);
- if (!Number.isFinite(t)) return "";
- const delta = Date.now() - t;
- const sec = Math.round(delta / 1000);
- if (sec < 60) return `${sec}s`;
- const min = Math.round(sec / 60);
- if (min < 60) return `${min}m`;
- const hr = Math.round(min / 60);
- if (hr < 24) return `${hr}h`;
- const day = Math.round(hr / 24);
- return `${day}d`;
-}
-
/**
* Recovery card for the specific blocked sub-state where the agent's
* turn ended without it calling submit_task_status. Surfaces three
diff --git a/notfair-cmo/src/components/live-counts-context.test.tsx b/notfair-cmo/src/components/live-counts-context.test.tsx
index 8c355673..7d9169db 100644
--- a/notfair-cmo/src/components/live-counts-context.test.tsx
+++ b/notfair-cmo/src/components/live-counts-context.test.tsx
@@ -25,6 +25,7 @@ const initial: LiveCounts = {
project: "demo1",
agents: { "demo1-cmo": 0, "demo1-google-ads": 1 },
approvals: 0,
+ attention: {},
};
afterEach(() => {
diff --git a/notfair-cmo/src/components/live-counts-context.tsx b/notfair-cmo/src/components/live-counts-context.tsx
index f9bf0a18..a9028298 100644
--- a/notfair-cmo/src/components/live-counts-context.tsx
+++ b/notfair-cmo/src/components/live-counts-context.tsx
@@ -20,6 +20,15 @@ import {
* re-renders. When the response differs, only the badge nodes that
* read the new value actually update.
*/
+export interface AgentAttentionEntry {
+ /** Pending questions + actionable approvals waiting on the user. */
+ count: number;
+ /** Oldest waiting item's task id — deep-link target so the badge
+ * lands directly in the decision space. Null when none of the
+ * waiting items is anchored to a task. */
+ task_id: string | null;
+}
+
export interface LiveCounts {
/** Project slug the counts belong to. null when no active project. */
project: string | null;
@@ -27,12 +36,15 @@ export interface LiveCounts {
agents: Record<string, number>;
/** Project-level actionable approvals count. */
approvals: number;
+ /** Map of agent_id → blocked-on-you signal (Slack-style red badge). */
+ attention: Record<string, AgentAttentionEntry>;
}
const LiveCountsContext = createContext<LiveCounts>({
project: null,
agents: {},
approvals: 0,
+ attention: {},
});
export function useLiveCounts(): LiveCounts {
@@ -86,10 +98,13 @@ export function LiveCountsProvider({
.sort(([a], [b]) => a.localeCompare(b))
.map(([k, v]) => [k, v]),
v: body.approvals,
+ n: Object.entries(body.attention ?? {})
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([k, v]) => [k, v.count, v.task_id]),
});
if (sigRef.current === sig) return;
sigRef.current = sig;
- setCounts(body);
+ setCounts({ ...body, attention: body.attention ?? {} });
} catch {
// Network hiccup — skip this tick.
}
diff --git a/notfair-cmo/src/server/db/attention.test.ts b/notfair-cmo/src/server/db/attention.test.ts
new file mode 100644
index 00000000..efec92fb
--- /dev/null
+++ b/notfair-cmo/src/server/db/attention.test.ts
@@ -0,0 +1,207 @@
+import Database from "better-sqlite3";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { MIGRATIONS } from "./migrations";
+
+let testDb: Database.Database;
+
+vi.mock("./db", () => ({
+ getDb: () => testDb,
+ getDbPath: () => ":memory:",
+}));
+
+import { attentionByAgent, attentionByTaskForAgent } from "./attention";
+import { createQuestion, answerQuestion } from "./questions";
+
+function applyMigrations(db: Database.Database): void {
+ for (const m of MIGRATIONS) db.exec(m.sql);
+}
+
+function createDb(): Database.Database {
+ const db = new Database(":memory:");
+ db.pragma("foreign_keys = ON");
+ applyMigrations(db);
+ return db;
+}
+
+function seedProject(slug = "acme"): void {
+ testDb
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
+ )
+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
+}
+
+/** questions.task_id carries a FK to tasks(id) — seed a real row. */
+function seedTask(id: string, agent_id = "acme-cmo-greg"): void {
+ testDb
+ .prepare(
+ `INSERT INTO tasks (id, project_slug, agent_id, brief, status, created_at, updated_at)
+ VALUES (?, 'acme', ?, 'brief', 'blocked', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z')`,
+ )
+ .run(id, agent_id);
+}
+
+function insertApproval(input: {
+ id: string;
+ agent_id: string;
+ task_id?: string | null;
+ status?: string;
+ created_at?: string;
+}): void {
+ testDb
+ .prepare(
+ `INSERT INTO approvals
+ (id, project_slug, agent_id, task_id, action_summary, action_type,
+ cost_estimate_usd, payload_json, status, created_at)
+ VALUES (?, 'acme', ?, ?, 'Raise budget', 'spend', 10, '{}', ?, ?)`,
+ )
+ .run(
+ input.id,
+ input.agent_id,
+ input.task_id ?? null,
+ input.status ?? "pending",
+ input.created_at ?? "2026-01-02T00:00:00.000Z",
+ );
+}
+
+beforeEach(() => {
+ testDb = createDb();
+ seedProject();
+});
+
+afterEach(() => {
+ testDb.close();
+});
+
+describe("attentionByAgent", () => {
+ it("returns an empty map when nothing waits on the user", () => {
+ expect(attentionByAgent("acme")).toEqual({});
+ });
+
+ it("counts pending questions and actionable approvals per agent", () => {
+ seedTask("t-1");
+ createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-1",
+ prompt: "What does Demo1 sell?",
+ options: [],
+ });
+ insertApproval({ id: "a-1", agent_id: "acme-cmo-greg", task_id: "t-1" });
+ insertApproval({
+ id: "a-2",
+ agent_id: "acme-google-ads-ana",
+ task_id: "t-9",
+ status: "revision_requested",
+ });
+
+ const out = attentionByAgent("acme");
+ expect(out["acme-cmo-greg"]?.count).toBe(2);
+ expect(out["acme-google-ads-ana"]?.count).toBe(1);
+ expect(out["acme-google-ads-ana"]?.task_id).toBe("t-9");
+ });
+
+ it("deep-links to the OLDEST task-anchored item", () => {
+ insertApproval({
+ id: "a-new",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-new",
+ created_at: "2026-01-05T00:00:00.000Z",
+ });
+ insertApproval({
+ id: "a-old",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-old",
+ created_at: "2026-01-03T00:00:00.000Z",
+ });
+
+ expect(attentionByAgent("acme")["acme-cmo-greg"]?.task_id).toBe("t-old");
+ });
+
+ it("falls back past unanchored items to the first task-anchored one", () => {
+ seedTask("t-2");
+ createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo-greg",
+ task_id: null,
+ prompt: "Free-standing question",
+ options: [],
+ });
+ insertApproval({
+ id: "a-1",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-2",
+ created_at: "2099-01-01T00:00:00.000Z",
+ });
+
+ const entry = attentionByAgent("acme")["acme-cmo-greg"];
+ expect(entry?.count).toBe(2);
+ expect(entry?.task_id).toBe("t-2");
+ });
+
+ it("excludes resolved questions and decided approvals", () => {
+ seedTask("t-1");
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-1",
+ prompt: "Answered already",
+ options: ["Yes"],
+ });
+ answerQuestion({ id: q.id, answer_option_index: 0, answer_text: null });
+ insertApproval({
+ id: "a-done",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-1",
+ status: "approved",
+ });
+
+ expect(attentionByAgent("acme")).toEqual({});
+ });
+
+ it("attentionByTaskForAgent maps task ids to their pending-item counts", () => {
+ seedTask("t-1");
+ seedTask("t-2");
+ createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo-greg",
+ task_id: "t-1",
+ prompt: "One",
+ options: [],
+ });
+ insertApproval({ id: "a-1", agent_id: "acme-cmo-greg", task_id: "t-1" });
+ insertApproval({ id: "a-2", agent_id: "acme-cmo-greg", task_id: "t-2" });
+ // Unanchored + other-agent rows don't leak in.
+ createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo-greg",
+ task_id: null,
+ prompt: "Free-standing",
+ options: [],
+ });
+ insertApproval({ id: "a-3", agent_id: "acme-google-ads-ana", task_id: "t-9" });
+
+ expect(attentionByTaskForAgent("acme", "acme-cmo-greg")).toEqual({
+ "t-1": 2,
+ "t-2": 1,
+ });
+ });
+
+ it("scopes to the requested project", () => {
+ seedProject("other");
+ testDb
+ .prepare(
+ `INSERT INTO questions
+ (id, project_slug, agent_id, task_id, prompt, options_json,
+ status, answer_option_index, answer_text, resolved_by_kind,
+ created_at, resolved_at)
+ VALUES ('q-x', 'other', 'other-cmo', NULL, 'p', '[]',
+ 'pending', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', NULL)`,
+ )
+ .run();
+
+ expect(attentionByAgent("acme")).toEqual({});
+ expect(attentionByAgent("other")["other-cmo"]?.count).toBe(1);
+ });
+});
diff --git a/notfair-cmo/src/server/db/attention.ts b/notfair-cmo/src/server/db/attention.ts
new file mode 100644
index 00000000..2dd6f001
--- /dev/null
+++ b/notfair-cmo/src/server/db/attention.ts
@@ -0,0 +1,80 @@
+import { getDb } from "./db";
+
+/**
+ * "Needs you" signal for the sidebar — the Slack-unread-badge model.
+ * An agent demands attention when it has a pending question
+ * (`ask_user_question`) or an actionable approval (`request_approval`)
+ * waiting on the user. Both park the task in `blocked`, where it is
+ * invisible unless the user happens to open that agent's Tasks tab —
+ * this module powers the red badge that makes it visible everywhere.
+ */
+export type AgentAttention = {
+ /** Pending questions + actionable approvals waiting on the user. */
+ count: number;
+ /**
+ * Task id of the OLDEST waiting item that is anchored to a task — the
+ * deep-link target so clicking the badge lands directly in the
+ * decision space (`/agents/<slug>/tasks?task=<id>`). Null when no
+ * waiting item names a task (free-standing questions).
+ */
+ task_id: string | null;
+};
+
+/**
+ * Per-task variant for the task rail: task_id → count of pending
+ * questions + actionable approvals on that task. Rows without a task
+ * anchor are skipped — the rail can only badge rows it renders.
+ */
+export function attentionByTaskForAgent(
+ project_slug: string,
+ agent_id: string,
+): Record<string, number> {
+ const db = getDb();
+ const rows = db
+ .prepare(
+ `SELECT task_id FROM questions
+ WHERE project_slug = ? AND agent_id = ? AND status = 'pending'
+ AND task_id IS NOT NULL
+ UNION ALL
+ SELECT task_id FROM approvals
+ WHERE project_slug = ? AND agent_id = ? AND status IN ('pending','revision_requested')
+ AND task_id IS NOT NULL`,
+ )
+ .all(project_slug, agent_id, project_slug, agent_id) as Array<{
+ task_id: string;
+ }>;
+
+ const out: Record<string, number> = {};
+ for (const r of rows) out[r.task_id] = (out[r.task_id] ?? 0) + 1;
+ return out;
+}
+
+export function attentionByAgent(
+ project_slug: string,
+): Record<string, AgentAttention> {
+ const db = getDb();
+ const rows = db
+ .prepare(
+ `SELECT agent_id, task_id, created_at FROM questions
+ WHERE project_slug = ? AND status = 'pending'
+ UNION ALL
+ SELECT agent_id, task_id, created_at FROM approvals
+ WHERE project_slug = ? AND status IN ('pending','revision_requested')
+ ORDER BY created_at ASC`,
+ )
+ .all(project_slug, project_slug) as Array<{
+ agent_id: string;
+ task_id: string | null;
+ created_at: string;
+ }>;
+
+ const out: Record<string, AgentAttention> = {};
+ for (const r of rows) {
+ const entry = (out[r.agent_id] ??= { count: 0, task_id: null });
+ entry.count += 1;
+ // Rows arrive oldest-first, so the first anchored one wins — answer
+ // the item the agent has been waiting on longest.
+ if (entry.task_id === null && r.task_id) entry.task_id = r.task_id;
+ }
+ return out;
+}