Open-source SEO, GEO, and marketing skills for AI agents.
feat(goals): "Needs you" escalation surface — rail card + sidebar mark
Yuting Zhong2a923ef9c37c
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsxindex 6ddf2c49..dc0c7864 100644--- a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx+++ b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx@@ -7,13 +7,16 @@ import {getLatestGoalForAgent,listGoalActions,listOpenGoalActions,+ listUserActionRequests,loggedSpendTotal,listGoalLearnings,listGoalTicks,listMetricSnapshots,isTargetMet,+ USER_ACTION_PREFIX,type Goal,} from "@/server/db/goals";+import { GoalNeedsYou, type NeedsYouItem } from "@/components/goal-needs-you";import { listCheckRows } from "@/server/goals/checks";import {listSessionsForAgent,@@ -242,6 +245,15 @@ function GoalRail({}) {const snapshots = listMetricSnapshots(goal.id, 400);const ticks = listGoalTicks(goal.id, 60);+ // Open escalations only the user can resolve — pinned above everything.+ const needsYou: NeedsYouItem[] = listUserActionRequests(goal.id).map((a) => ({+ action_id: a.id,+ ask: a.description+ .slice(USER_ACTION_PREFIX.length)+ .replace(/^[\s:—–-]+/, ""),+ tick_number: a.tick_number,+ raised_at: a.created_at,+ }));const allActions = listGoalActions(goal.id, 100);const targetMet = isTargetMet(goal);const tickRunning = ticks.some((t) => t.status === "running");@@ -293,6 +305,8 @@ function GoalRail({return (<div className="flex flex-col gap-5">+ <GoalNeedsYou items={needsYou} />+{/* Statement */}<p className="m-0 text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-3))]">“{goal.statement}”diff --git a/notfair/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsxindex 540ed75b..81b6e850 100644--- a/notfair/src/components/app-sidebar.tsx+++ b/notfair/src/components/app-sidebar.tsx@@ -19,6 +19,7 @@ import { listProjects } from "@/server/db/projects";import { getActiveProject } from "@/server/active-project";import { listProjectAgents } from "@/server/agent-meta";import {+ countUserActionRequests,getPinnedGoalIds,listGoals,listLiveGoals,@@ -80,6 +81,8 @@ export async function AppSidebar() {const agentBySlug = new Map(agentEntries.map((a) => [a.agent_id, a]));// Move-to-group menu targets on every goal row.const groupTargets = goalGroups.map((group) => ({ id: group.id, name: group.name }));+ // Open "Needs you" escalations per goal — amber mark on the rail rows.+ const attentionByGoal = active ? countUserActionRequests(active.slug) : new Map<string, number>();// Full goal list for the create-group dialog behind the + header action.const groupNameById = new Map(goalGroups.map((group) => [group.id, group.name]));const editorGoals: GoalGroupEditorGoal[] = allGoals.map((goal) => {@@ -165,6 +168,7 @@ export async function AppSidebar() {projectSlug={active.slug}groups={groupTargets}groupId={null}+ needsAttention={(attentionByGoal.get(goal.id) ?? 0) > 0}/>);})}@@ -196,6 +200,7 @@ export async function AppSidebar() {projectSlug={active.slug}groups={groupTargets}groupId={group.id}+ needsAttention={(attentionByGoal.get(goal.id) ?? 0) > 0}/>);})}diff --git a/notfair/src/components/goal-needs-you.test.tsx b/notfair/src/components/goal-needs-you.test.tsxnew file mode 100644index 00000000..03e296da--- /dev/null+++ b/notfair/src/components/goal-needs-you.test.tsx@@ -0,0 +1,59 @@+// @vitest-environment jsdom+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { GoalNeedsYou } from "@/components/goal-needs-you";++// Mock at the server-action boundary, per repo test conventions.+const markHandled = vi.hoisted(() => vi.fn());+vi.mock("@/server/actions/goals", () => ({+ markUserActionHandledAction: markHandled,+}));++const refresh = vi.hoisted(() => vi.fn());+vi.mock("next/navigation", () => ({+ useRouter: () => ({ refresh, push: vi.fn() }),+}));++const ITEMS = [+ {+ action_id: "a1",+ ask: "Replace the production OPENAI_API_KEY with one from an active project.",+ tick_number: 43,+ raised_at: new Date(Date.now() - 3_600_000).toISOString(),+ },+ {+ action_id: "a2",+ ask: "Grant the Meta app image-upload access and re-authorize.",+ tick_number: null,+ raised_at: new Date().toISOString(),+ },+];++beforeEach(() => {+ markHandled.mockReset();+ refresh.mockReset();+});++describe("GoalNeedsYou", () => {+ it("renders nothing when there are no open asks", () => {+ const { container } = render(<GoalNeedsYou items={[]} />);+ expect(container).toBeEmptyDOMElement();+ });++ it("lists every ask with its raised context", () => {+ render(<GoalNeedsYou items={ITEMS} />);+ expect(screen.getByRole("region", { name: /needs you: 2 actions/i })).toBeInTheDocument();+ expect(screen.getByText(/OPENAI_API_KEY/)).toBeInTheDocument();+ expect(screen.getByText(/raised 1h ago · check #43/)).toBeInTheDocument();+ expect(screen.getByText(/Meta app image-upload access/)).toBeInTheDocument();+ });++ it("marks an ask handled and refreshes", async () => {+ markHandled.mockResolvedValue({ ok: true });+ render(<GoalNeedsYou items={ITEMS} />);+ fireEvent.click(screen.getAllByRole("button", { name: /mark handled/i })[0]!);+ await waitFor(() => expect(markHandled).toHaveBeenCalledWith("a1"));+ await waitFor(() => expect(refresh).toHaveBeenCalled());+ });+});diff --git a/notfair/src/components/goal-needs-you.tsx b/notfair/src/components/goal-needs-you.tsxnew file mode 100644index 00000000..af0c39d3--- /dev/null+++ b/notfair/src/components/goal-needs-you.tsx@@ -0,0 +1,86 @@+"use client";++import { useRouter } from "next/navigation";+import { useTransition } from "react";+import { toast } from "sonner";+import { Check, TriangleAlert } from "lucide-react";+import { markUserActionHandledAction } from "@/server/actions/goals";+import { timeAgo } from "@/lib/time-ago";++export type NeedsYouItem = {+ action_id: string;+ /** Full escalation text, "USER ACTION REQUIRED" prefix already stripped. */+ ask: string;+ tick_number: number | null;+ raised_at: string;+};++/**+ * The escalation surface: open asks only the USER can resolve, pinned at+ * the top of the goal rail. Everything else in the loop is the agent's+ * job — this card is the one place that is explicitly yours. It renders+ * nothing when there is nothing to do; when it shows, the agent repeats+ * the same asks in every check summary until telemetry proves the fix+ * (or you mark one handled here, which the agent later verifies).+ */+export function GoalNeedsYou({ items }: { items: NeedsYouItem[] }) {+ const router = useRouter();+ const [pending, startTransition] = useTransition();++ if (items.length === 0) return null;++ function markHandled(item: NeedsYouItem) {+ startTransition(async () => {+ const r = await markUserActionHandledAction(item.action_id);+ if (!r.ok) {+ toast.error(r.error ?? "Could not mark it handled.");+ return;+ }+ toast.success("Marked handled — the agent verifies it on a later check.");+ router.refresh();+ });+ }++ return (+ <section+ aria-label={`Needs you: ${items.length} action${items.length === 1 ? "" : "s"}`}+ className="ns-card bg-[hsl(var(--notfair-warn)/0.09)] p-3.5"+ >+ <div className="mb-2 flex items-center gap-1.5">+ <TriangleAlert aria-hidden className="size-3.5 text-[hsl(var(--notfair-warn))]" />+ <h2 className="m-0 text-[11px] font-semibold tracking-wide text-[hsl(var(--notfair-warn))] uppercase">+ Needs you+ </h2>+ <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-warn))]">+ {items.length}+ </span>+ </div>+ <ul className="m-0 flex list-none flex-col gap-3 p-0">+ {items.map((item) => (+ <li key={item.action_id}>+ <p className="m-0 text-[12.5px] leading-relaxed">{item.ask}</p>+ <div className="mt-1 flex items-center justify-between gap-2">+ <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">+ raised {timeAgo(item.raised_at)}+ {item.tick_number !== null && ` · check #${item.tick_number}`}+ </span>+ <button+ type="button"+ className="ns-btn ns-btn-ghost shrink-0 !px-2 !py-0.5 text-[11.5px]"+ disabled={pending}+ onClick={() => markHandled(item)}+ >+ <Check className="size-3" />+ Mark handled+ </button>+ </div>+ </li>+ ))}+ </ul>+ <p className="mt-2.5 mb-0 text-[11px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">+ The agent repeats these in every check until telemetry proves the fix.+ Marking one handled closes the ask — it re-escalates if still broken.+ </p>+ </section>+ );+}diff --git a/notfair/src/components/sidebar-goal-item.tsx b/notfair/src/components/sidebar-goal-item.tsxindex a2bba43e..230a6a3f 100644--- a/notfair/src/components/sidebar-goal-item.tsx+++ b/notfair/src/components/sidebar-goal-item.tsx@@ -16,6 +16,7 @@ import {PinOff,Play,Trash2,+ TriangleAlert,} from "lucide-react";import {SidebarMenuAction,@@ -77,6 +78,7 @@ export function SidebarGoalItem({projectSlug,groups,groupId,+ needsAttention = false,}: {href: string;/** Project home — where the user lands after deleting the open goal. */@@ -92,6 +94,8 @@ export function SidebarGoalItem({groups: { id: string; name: string }[];/** The group this goal currently belongs to, if any. */groupId: string | null;+ /** Open "Needs you" escalations — renders the amber attention mark. */+ needsAttention?: boolean;}) {const router = useRouter();const pathname = usePathname();@@ -147,6 +151,12 @@ export function SidebarGoalItem({><span className={cn("ns-dot", dotClass)} aria-hidden /><span className={cn("truncate", labelClass)}>{label}</span>+ {needsAttention && (+ <TriangleAlert+ aria-label="Needs your action"+ className="!size-3 shrink-0 text-[hsl(var(--notfair-warn))]"+ />+ )}{pinned && (<Pinaria-label="Pinned"diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.tsindex dc241d73..82696189 100644--- a/notfair/src/server/actions/goals.ts+++ b/notfair/src/server/actions/goals.ts@@ -6,11 +6,14 @@ import {deleteGoalsForAgent,endActionObservation,getGoal,+ getGoalAction,getGoalForAgent,renameGoal,+ reviewGoalAction,setGoalPinned,setGoalStatus,startGoalLoop,+ USER_ACTION_PREFIX,} from "@/server/db/goals";import { cascadeDeleteAgentArtifacts } from "@/server/agents/cascade-delete";import { getProject } from "@/server/db/projects";@@ -213,6 +216,32 @@ export async function releaseLockAction(action_id: string): Promise<GoalActionRereturn { ok: true };}+/**+ * "Mark handled" on a Needs-you escalation. The user says they made the+ * fix; the action closes so the card stops nagging. If telemetry later+ * proves otherwise, the agent's blocked-on-user rule re-escalates with a+ * fresh decision action — acknowledgment is cheap, lying to the loop isn't.+ */+export async function markUserActionHandledAction(+ action_id: string,+): Promise<GoalActionResult> {+ const action = getGoalAction(action_id);+ if (+ !action ||+ action.kind !== "decision" ||+ !action.description.startsWith(USER_ACTION_PREFIX)+ ) {+ return { ok: false, error: "Not an open user-action escalation." };+ }+ const reviewed = reviewGoalAction(+ action_id,+ "User marked this handled from the goal screen. Verify against telemetry on a later check; re-escalate if it is still broken.",+ );+ if (!reviewed) return { ok: false, error: "Already closed." };+ revalidatePath("/", "layout");+ return { ok: true };+}+/*** Manual "Run tick now". Fire-and-forget for the turn itself, but the* check row is claimed synchronously inside runGoalTick's pre-awaitdiff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.tsindex d51fb51b..3908f9bc 100644--- a/notfair/src/server/db/goals.ts+++ b/notfair/src/server/db/goals.ts@@ -659,6 +659,33 @@ export function listOpenGoalActions(goal_id: string): GoalAction[] {.all(goal_id) as GoalAction[];}+/** Escalation contract: the agent identity requires decision actions that+ * need the USER to act to start with this prefix. The "Needs you" UI keys+ * off it — prose elsewhere never surfaces there. */+export const USER_ACTION_PREFIX = "USER ACTION REQUIRED";++/** Open escalations awaiting the user, oldest first. */+export function listUserActionRequests(goal_id: string): GoalAction[] {+ return listOpenGoalActions(goal_id).filter(+ (a) => a.kind === "decision" && a.description.startsWith(USER_ACTION_PREFIX),+ );+}++/** goal_id → open user-escalation count, for rail badges across a project. */+export function countUserActionRequests(project_slug: string): Map<string, number> {+ const rows = getDb()+ .prepare(+ `SELECT a.goal_id AS goal_id, COUNT(*) AS n+ FROM goal_actions a+ JOIN goals g ON g.id = a.goal_id+ WHERE g.project_slug = ? AND a.status = 'open'+ AND a.kind = 'decision' AND a.description LIKE ? || '%'+ GROUP BY a.goal_id`,+ )+ .all(project_slug, USER_ACTION_PREFIX) as Array<{ goal_id: string; n: number }>;+ return new Map(rows.map((r) => [r.goal_id, r.n]));+}+export function listGoalActions(goal_id: string, limit = 50): GoalAction[] {return getDb().prepare(diff --git a/notfair/src/server/goals/identity.ts b/notfair/src/server/goals/identity.tsindex 928dede6..f2b3fd52 100644--- a/notfair/src/server/goals/identity.ts+++ b/notfair/src/server/goals/identity.ts@@ -184,7 +184,10 @@ at all (log it as a \`research\` or \`decision\` action).Some root causes are provably outside your reach: productioncredentials, platform/app permissions, account settings, a dependencyonly the user can change. When you identify one, log it as a-\`decision\` action naming the exact fix the user must make, and+\`decision\` action whose description STARTS WITH+\`USER ACTION REQUIRED:\` followed by the exact fix the user must+make — that prefix is a UI contract: it pins the ask in the goal+screen's "Needs you" panel and marks the goal in the sidebar. Thenrepeat the ask in EVERY tick summary until the state provablychanges — a finding mentioned once is a finding lost; the diary isyour only channel to the user, and they read it in five-second