From 05553f442581e8efe5b19f2c8399711c6f1841fe Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Fri, 16 Oct 2026 00:40:39 +0000 Subject: [PATCH 1/2] feat(automations): the Approvals page, its badge, and Home's row /approvals lists what waits for the person's pick, each automation's together and the assistant's by conversation: what it would do, why, its effect and expiry, with the first in focus so Enter approves it, Edit in place, Always allow where it can be, and Decline with Undo instead of a question. A badge in the top bar and the nav count what waits, and Home's Needs attention has a row for them. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01VF3LK1DBx3dXX2b8c5T3cQ --- docs/automations.md | 14 +- .../__tests__/approvals-model.test.ts | 108 +++++++++ .../__tests__/approvals-page.test.tsx | 216 ++++++++++++++++++ nextjs-frontend/app/(app)/approvals/page.tsx | 16 ++ .../components/app-shell/app-shell.tsx | 10 +- .../components/app-shell/nav-config.ts | 6 +- nextjs-frontend/components/app-shell/nav.tsx | 2 +- .../components/approvals/approvals-badge.tsx | 31 +++ .../components/approvals/approvals-page.tsx | 198 ++++++++++++++++ .../components/approvals/inbox-card.tsx | 198 ++++++++++++++++ nextjs-frontend/components/approvals/model.ts | 146 ++++++++++++ .../components/approvals/use-approvals.ts | 28 +++ nextjs-frontend/components/chat/approval.tsx | 8 +- nextjs-frontend/components/home/attention.ts | 24 +- .../components/home/home-screen.tsx | 4 + 15 files changed, 998 insertions(+), 11 deletions(-) create mode 100644 nextjs-frontend/__tests__/approvals-model.test.ts create mode 100644 nextjs-frontend/__tests__/approvals-page.test.tsx create mode 100644 nextjs-frontend/app/(app)/approvals/page.tsx create mode 100644 nextjs-frontend/components/approvals/approvals-badge.tsx create mode 100644 nextjs-frontend/components/approvals/approvals-page.tsx create mode 100644 nextjs-frontend/components/approvals/inbox-card.tsx create mode 100644 nextjs-frontend/components/approvals/model.ts create mode 100644 nextjs-frontend/components/approvals/use-approvals.ts diff --git a/docs/automations.md b/docs/automations.md index 1b74c46ad..56221a197 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -39,7 +39,7 @@ merged is called built. | Deciding an automation's action with a yes in the chat it told you in | built | | Approvals as activities (`approval.waiting`, `approval.decided`) and the `approval.waiting` notification | built | | Agents' approval tools: `approvals` and `decline_approval` over MCP and in the assistant, and no way for an agent to approve | built | -| The Approvals page and its badge | planned | +| The Approvals page (`/approvals`), its badge in the top bar and nav, and Home's Needs attention row | built | | Storing and running automations, joins, variables, the studio | planned | ## Contract @@ -649,6 +649,15 @@ expires, seen by its person alone ([Approvals as activities](#approvals-as-activ target can send `approval.waiting` to a team chat or webhook ([Notifications](notifications.md#events)); it is off until a target asks for it. +**The Approvals page** (`/approvals`, in the nav under Automate) lists what waits for your pick, each automation's +together and the assistant's by conversation: what it would do, why (a link to the activity that caused it), whether +it reaches outside Lens, when it expires, and its params. The first is in focus, so Enter approves it and focus moves +to the next; Tab moves between them. **Edit** changes the params in place (Enter approves with the changes), +**Always allow** shows where the node can be allowed, and **Decline** takes it out at once with Undo on the notice +for a few seconds instead of a question. The link you were told (`/approvals?id=12`) brings that one first, or says +what became of it. Below, what was decided lately. A badge in the top bar counts what waits (nothing shows while +none do), the nav item carries the same count, and Home's Needs attention has a row for them. + The inbox reads `GET /api/v1/approvals` (newest first; `status`, `origin=automation|chat`, `automation`, `chat_id`, and `before` with `limit` to page), `GET /api/v1/approvals/{aid}` and `GET /api/v1/approvals/count` (`{waiting, automations}`, for a badge). @@ -810,4 +819,5 @@ the timer was cancelled, or Lens was off past the catch-up window. - Approvals: a cost estimate on actions that ask (a run on another asset could say what it would cost); approve buttons in Telegram and Slack (today a yes decides only actions inside Lens); approvals that need two people; one card for many alike ("approve all 12"); trying a failed one again; expiring an automation's approvals when it is - removed. + removed; on the page, keys for decline and edit, live updates instead of reading again each minute, and the + assistant's proposals shown with their estimates. diff --git a/nextjs-frontend/__tests__/approvals-model.test.ts b/nextjs-frontend/__tests__/approvals-model.test.ts new file mode 100644 index 000000000..8151e8257 --- /dev/null +++ b/nextjs-frontend/__tests__/approvals-model.test.ts @@ -0,0 +1,108 @@ +import type { Approval } from "@/app/openapi-client/types.gen"; +import { navFor } from "@/components/app-shell/nav-config"; +import { + badgeCount, + changedParams, + DAY, + draftOf, + effectLabel, + expiresLine, + groupApprovals, + outcomeLine, + paramLines, +} from "@/components/approvals/model"; +import { buildAttention } from "@/components/home/attention"; + +const NOW = Date.parse("2026-10-16T09:00:00Z"); + +function approval(id: number, over: Partial = {}): Approval { + return { + id, + tool: "action", + status: "pending", + summary: `Post number ${id}`, + origin: { automation: 4, run: 51, node: `n${id}` }, + automation: "School emails", + intent: { action: "notify", params: { text: "Trip on Friday", times: 2 }, effect: "out" }, + ...over, + }; +} + +describe("the approvals inbox's model", () => { + it("groups each automation's together, and the assistant's by conversation, newest group first", () => { + const chat = approval(9, { origin: null, intent: null, tool: "run_template", chat: 3, automation: null }); + const groups = groupApprovals([ + approval(12), + chat, + approval(8, { origin: { automation: 5 }, automation: null }), + approval(7), + ]); + expect(groups.map((g) => [g.title, g.items.map((a) => a.id)])).toEqual([ + ["School emails", [12, 7]], + ["The assistant, in a conversation", [9]], + ["Automation 5", [8]], + ]); + expect(groups[1].chat).toBe(3); + expect(groups[0].automation).toBe(4); + }); + + it("says what an effect means and when it expires", () => { + expect(effectLabel("out")).toBe("Reaches outside Lens"); + expect(effectLabel("lens")).toBe("Changes something in Lens"); + expect(effectLabel(undefined)).toBeNull(); + expect(expiresLine(new Date(NOW + 6 * DAY).toISOString(), NOW)).toBe("Expires in 6 days"); + expect(expiresLine(new Date(NOW + DAY + 1000).toISOString(), NOW)).toBe("Expires in 1 day"); + expect(expiresLine(new Date(NOW + 3600_000).toISOString(), NOW)).toBe("Expires within a day"); + expect(expiresLine(new Date(NOW - 1).toISOString(), NOW)).toBe("Expired"); + expect(expiresLine(null, NOW)).toBeNull(); + }); + + it("shows params in a line each, and an edit keeps their types and leaves out what's emptied", () => { + const params = { text: "Trip on Friday", times: 2, rooms: ["family"], note: "" }; + expect(paramLines(params)).toEqual([ + { key: "text", value: "Trip on Friday" }, + { key: "times", value: "2" }, + { key: "rooms", value: '["family"]' }, + ]); + const draft = draftOf(params); + expect(draft).toEqual({ text: "Trip on Friday", times: "2", rooms: '["family"]', note: "" }); + expect(changedParams({ ...draft, times: "3", text: "" }, params)).toEqual({ times: 3, text: null }); + expect(changedParams(draft, params)).toEqual({}); // nothing changed, nothing sent + expect(() => changedParams({ ...draft, rooms: "[family" }, params)).toThrow("rooms isn’t valid"); + }); + + it("says what became of a decided one", () => { + expect(outcomeLine({ status: "done", summary: "Post it", decided_by: "sam@x.io" })).toBe( + "Approved by sam@x.io: Post it", + ); + expect(outcomeLine({ status: "failed", summary: "Post it", error: "the room is gone" })).toBe( + "Approved, but it failed: Post it (the room is gone)", + ); + expect(outcomeLine({ status: "declined", summary: "Post it" })).toBe("Declined: Post it"); + expect(outcomeLine({ status: "expired", summary: "Post it" })).toBe("Expired with no pick: Post it"); + }); + + it("counts in the badge and the nav, and Home says what waits", () => { + expect(badgeCount(0)).toBeNull(); + expect(badgeCount(3)).toBe("3"); + expect(badgeCount(140)).toBe("99+"); + for (const admin of [true, false]) { + const item = navFor(admin).find((i) => i.href === "/approvals"); + expect(item).toMatchObject({ label: "Approvals", countKey: "approvals", group: "Automate" }); + } + const home = (waiting: number, automations: number) => + buildAttention({ latestJobs: new Map(), recent: [], nsById: new Map(), approvals: { waiting, automations } }); + expect(home(0, 0)).toEqual([]); + expect(home(2, 2)).toEqual([ + expect.objectContaining({ + key: "approvals", + kind: "gate", + title: "2 actions wait for your approval", + meta: "from automations", + action: { label: "Review", do: { type: "link", href: "/approvals" } }, + }), + ]); + expect(home(1, 0)[0]).toMatchObject({ title: "1 action waits for your approval", meta: "from the assistant" }); + expect(home(3, 1)[0].meta).toBe("1 from automations, 2 from the assistant"); + }); +}); diff --git a/nextjs-frontend/__tests__/approvals-page.test.tsx b/nextjs-frontend/__tests__/approvals-page.test.tsx new file mode 100644 index 000000000..a4839743b --- /dev/null +++ b/nextjs-frontend/__tests__/approvals-page.test.tsx @@ -0,0 +1,216 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import "@testing-library/jest-dom"; +import type { ReactNode } from "react"; + +import { Chats } from "@/app/openapi-client"; +import type { Approval } from "@/app/openapi-client/types.gen"; +import { ApprovalsBadge } from "@/components/approvals/approvals-badge"; +import { ApprovalsPage, UNDO_MS } from "@/components/approvals/approvals-page"; +import { ToastProvider } from "@/components/ui/toast"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Chats: { + listApprovals: jest.fn(), + getApproval: jest.fn(), + decideApproval: jest.fn(), + countApprovals: jest.fn(), + }, +})); +let search = ""; +jest.mock("next/navigation", () => ({ + useRouter: () => ({ push: jest.fn(), replace: jest.fn() }), + usePathname: () => "/approvals", + useSearchParams: () => new URLSearchParams(search), +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const m = (f: unknown) => f as jest.Mock; +const CAN = { approve: true, decline: true, edit: true, always: true }; + +function approval(id: number, over: Partial = {}): Approval { + return { + id, + tool: "action", + status: "pending", + summary: `Post “Trip ${id}” to the family room`, + origin: { automation: 4, run: 51, node: `n${id}` }, + automation: "School emails", + intent: { action: "test_post", params: { text: `Trip ${id}`, times: 1 }, effect: "out" }, + why: { activity: "create-recording-7", summary: "Work Gmail received “School trip”", url: "/resources/7" }, + expires_at: new Date(Date.now() + 6.5 * 86_400_000).toISOString(), + created_at: new Date().toISOString(), + can: CAN, + ...over, + }; +} + +let waiting: Approval[] = []; +function serve(recent: Approval[] = []) { + m(Chats.listApprovals).mockImplementation(({ query }: { query: { status?: string } }) => + ok(query.status === "pending" ? waiting : [...waiting, ...recent]), + ); + m(Chats.decideApproval).mockImplementation( + ({ path, body }: { path: { aid: number }; body: { decision: string } }) => { + waiting = waiting.filter((a) => a.id !== path.aid); + return ok( + body.decision === "decline" ? { status: "declined" } : { status: "done", always: body.decision === "always" }, + ); + }, + ); + m(Chats.countApprovals).mockImplementation(() => ok({ waiting: waiting.length, automations: waiting.length })); +} + +function wrap(ui: ReactNode) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + {ui} + + , + ); +} + +beforeEach(() => { + search = ""; + waiting = [ + approval(12), + approval(11), + approval(9, { + origin: null, + intent: null, + tool: "run_template", + chat: 3, + automation: null, + summary: "Run notes", + can: { approve: true, decline: true }, + }), + ]; +}); + +describe("the approvals inbox", () => { + it("groups what waits, puts the first in focus, and Enter approves it", async () => { + serve(); + wrap(); + const first = await screen.findByRole("group", { name: "Approval: Post “Trip 12” to the family room" }); + expect(screen.getByRole("region", { name: "School emails" })).toBeInTheDocument(); + expect(screen.getByRole("region", { name: "The assistant, in a conversation" })).toBeInTheDocument(); + expect(screen.getByText("3 wait for your pick")).toBeInTheDocument(); + await waitFor(() => expect(first).toHaveFocus()); + expect(within(first).getByText(/Reaches outside Lens · Expires in 6 days/)).toBeInTheDocument(); + expect(within(first).getByRole("link", { name: "Work Gmail received “School trip”" })).toHaveAttribute( + "href", + "/resources/7", + ); + fireEvent.keyDown(first, { key: "Enter" }); + await waitFor(() => + expect(Chats.decideApproval).toHaveBeenCalledWith( + expect.objectContaining({ path: { aid: 12 }, body: { decision: "approve" } }), + ), + ); + const next = await screen.findByRole("group", { name: "Approval: Post “Trip 11” to the family room" }); + await waitFor(() => expect(next).toHaveFocus()); // focus moves on to the next one + expect(screen.queryByRole("group", { name: /Trip 12/ })).not.toBeInTheDocument(); + }); + + it("declines with Undo instead of a question, and sends it once the notice is gone", async () => { + jest.useFakeTimers(); + try { + serve(); + wrap(); + const card = await screen.findByRole("group", { name: /Trip 12/ }); + fireEvent.click(within(card).getByRole("button", { name: "Decline" })); + expect(screen.queryByRole("group", { name: /Trip 12/ })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Undo" })); + expect(await screen.findByRole("group", { name: /Trip 12/ })).toBeInTheDocument(); + act(() => jest.advanceTimersByTime(UNDO_MS + 100)); + expect(Chats.decideApproval).not.toHaveBeenCalled(); // taken back: nothing sent + fireEvent.click(within(screen.getByRole("group", { name: /Trip 12/ })).getByRole("button", { name: "Decline" })); + act(() => jest.advanceTimersByTime(UNDO_MS + 100)); + await waitFor(() => + expect(Chats.decideApproval).toHaveBeenCalledWith( + expect.objectContaining({ path: { aid: 12 }, body: { decision: "decline" } }), + ), + ); + } finally { + jest.useRealTimers(); + } + }); + + it("edits the params, typed as they were, and Always allow is there only when it can be", async () => { + waiting = [approval(12), approval(11, { can: { ...CAN, always: false } })]; + serve(); + wrap(); + const card = await screen.findByRole("group", { name: /Trip 12/ }); + expect(within(card).getByRole("button", { name: "Always allow" })).toBeInTheDocument(); + expect( + within(screen.getByRole("group", { name: /Trip 11/ })).queryByRole("button", { name: "Always allow" }), + ).not.toBeInTheDocument(); + fireEvent.click(within(card).getByRole("button", { name: "Edit" })); + const text = within(card).getByLabelText("text"); + expect(text).toHaveFocus(); + fireEvent.change(text, { target: { value: "Trip on Friday" } }); + fireEvent.change(within(card).getByLabelText("times"), { target: { value: "2" } }); + fireEvent.submit(within(card).getByRole("form", { name: "Change what it does" })); + await waitFor(() => + expect(Chats.decideApproval).toHaveBeenCalledWith( + expect.objectContaining({ + path: { aid: 12 }, + body: { decision: "edit", params: { text: "Trip on Friday", times: 2 } }, + }), + ), + ); + }); + + it("brings the one you were sent first, and says what became of one already decided", async () => { + search = "id=11"; + serve(); + const { unmount } = wrap(); + const cards = await screen.findAllByRole("group", { name: /^Approval: Post/ }); + expect(cards[0]).toHaveAccessibleName("Approval: Post “Trip 11” to the family room"); + unmount(); + search = "id=5"; + m(Chats.getApproval).mockImplementation(() => + ok(approval(5, { status: "declined", decided_by: "sam@x.io", summary: "Post “Old”" })), + ); + wrap(); + expect(await screen.findByText("Declined by sam@x.io: Post “Old”")).toBeInTheDocument(); + }); + + it("an approval you can't approve from here says why", async () => { + waiting = [approval(12, { can: { approve: false, decline: true, edit: false, always: false } })]; + serve(); + wrap(); + const card = await screen.findByRole("group", { name: /Trip 12/ }); + expect(within(card).getByRole("button", { name: "Approve" })).toHaveAttribute("aria-disabled", "true"); + fireEvent.keyDown(card, { key: "Enter" }); + expect(Chats.decideApproval).not.toHaveBeenCalled(); + expect(within(card).queryByRole("button", { name: "Edit" })).not.toBeInTheDocument(); + }); + + it("says when nothing waits", async () => { + waiting = []; + serve(); + wrap(); + expect(await screen.findByText("Nothing waits for your pick")).toBeInTheDocument(); + }); +}); + +describe("the top bar's approvals badge", () => { + it("shows how many wait and opens the inbox, and nothing when none do", async () => { + serve(); + const { unmount } = wrap(); + const link = await screen.findByRole("link", { name: "3 waiting for your approval" }); + expect(link).toHaveAttribute("href", "/approvals"); + expect(link).toHaveTextContent("3"); + unmount(); + waiting = []; + wrap(); + await waitFor(() => expect(Chats.countApprovals).toHaveBeenCalledTimes(2)); + await act(async () => undefined); + expect(screen.queryByRole("link")).not.toBeInTheDocument(); + }); +}); diff --git a/nextjs-frontend/app/(app)/approvals/page.tsx b/nextjs-frontend/app/(app)/approvals/page.tsx new file mode 100644 index 000000000..580c4f4cc --- /dev/null +++ b/nextjs-frontend/app/(app)/approvals/page.tsx @@ -0,0 +1,16 @@ +import type { Metadata } from "next"; +import { Suspense } from "react"; + +import { ApprovalsPage } from "@/components/approvals/approvals-page"; + +export const metadata: Metadata = { title: "Approvals" }; + +/** What waits for your pick: automations' actions that ask first and the assistant's proposals (backend: + * GET /api/v1/approvals, docs/automations.md "Approvals"). */ +export default function Page() { + return ( + + + + ); +} diff --git a/nextjs-frontend/components/app-shell/app-shell.tsx b/nextjs-frontend/components/app-shell/app-shell.tsx index 0dc0cd3c2..46e8bfee5 100644 --- a/nextjs-frontend/components/app-shell/app-shell.tsx +++ b/nextjs-frontend/components/app-shell/app-shell.tsx @@ -14,6 +14,8 @@ import { NamespaceSwitcher } from "@/components/app-shell/namespace-switcher"; import { Nav } from "@/components/app-shell/nav"; import { Shortcuts } from "@/components/app-shell/shortcuts"; import { UpdateBanner } from "@/components/app-shell/update-banner"; +import { ApprovalsBadge } from "@/components/approvals/approvals-badge"; +import { useApprovalCount } from "@/components/approvals/use-approvals"; import { BudgetMeter } from "@/components/costs/budget-meter"; import { WelcomeTour } from "@/components/home/welcome-tour"; import { PageChat } from "@/components/page-chat/page-chat"; @@ -52,8 +54,8 @@ function PartialNamespace({ ns, onAll }: { ns: string; onAll: () => void }) { ); } -/** The signed-in frame: nav rail, top bar (namespace, ⌘K, budget, activity, import, alerts, account), the page and the page - * chat beside it. */ +/** The signed-in frame: nav rail, top bar (namespace, ⌘K, budget, activity, import, approvals, alerts, account), the + * page and the page chat beside it. */ export function AppShell({ user, children }: { user: SessionUser; children: ReactNode }) { const [collapsed, setCollapsed] = useState(false); const [mobileOpen, setMobileOpen] = useState(false); @@ -114,7 +116,8 @@ export function AppShell({ user, children }: { user: SessionUser; children: Reac enabled: Boolean(namespace) && can("viewer", namespace), // speakers are the namespace's members' only staleTime: 60_000, }); - const counts = { recordings, reviews: reviews.data }; + const approvals = useApprovalCount(); + const counts = { recordings, reviews: reviews.data, approvals: approvals.data?.waiting || undefined }; const canImport = can("editor", namespace); return ( @@ -191,6 +194,7 @@ export function AppShell({ user, children }: { user: SessionUser; children: Reac )} + (window.location.href = "/#attention")}> diff --git a/nextjs-frontend/components/app-shell/nav-config.ts b/nextjs-frontend/components/app-shell/nav-config.ts index ff49b052d..fb02035c6 100644 --- a/nextjs-frontend/components/app-shell/nav-config.ts +++ b/nextjs-frontend/components/app-shell/nav-config.ts @@ -6,6 +6,7 @@ import { HardDriveDownload, History, House, + Inbox, LibraryBig, MessagesSquare, NotebookPen, @@ -30,8 +31,8 @@ export type NavItem = { adminOnly?: boolean; /** Only shown to people who aren't administrators (admins have it under another item). */ membersOnly?: boolean; - /** A count shown next to the label (library size, speakers to review in Settings). */ - countKey?: "recordings" | "reviews"; + /** A count shown next to the label (library size, speakers to review in Settings, approvals waiting). */ + countKey?: "recordings" | "reviews" | "approvals"; /** The group it's in, named above its first item; the first group (what people use every day) has no name. */ group: NavGroup; }; @@ -58,6 +59,7 @@ export const NAV: NavItem[] = [ { label: "Graph", href: "/graph", icon: Waypoints, group: "Explore" }, { label: "Podcasts", href: "/podcasts", icon: Podcast, group: "Explore" }, { label: "Reports", href: "/reports", icon: ChartNoAxesColumn, group: "Explore" }, + { label: "Approvals", href: "/approvals", icon: Inbox, countKey: "approvals", group: "Automate" }, { label: "Pipelines", href: "/pipelines", icon: Workflow, group: "Automate" }, { label: "Routines", href: "/routines", icon: CalendarClock, adminOnly: true, group: "Automate" }, { label: "Extensions", href: "/extensions", icon: Blocks, group: "Automate" }, diff --git a/nextjs-frontend/components/app-shell/nav.tsx b/nextjs-frontend/components/app-shell/nav.tsx index f77f93bbc..d161d7a5a 100644 --- a/nextjs-frontend/components/app-shell/nav.tsx +++ b/nextjs-frontend/components/app-shell/nav.tsx @@ -26,7 +26,7 @@ export function Nav({ admin: boolean; collapsed: boolean; onToggle?: () => void; - counts: { recordings?: number; reviews?: number }; + counts: { recordings?: number; reviews?: number; approvals?: number }; onNavigate?: () => void; className?: string; top?: ReactNode; diff --git a/nextjs-frontend/components/approvals/approvals-badge.tsx b/nextjs-frontend/components/approvals/approvals-badge.tsx new file mode 100644 index 000000000..faf8f8e2a --- /dev/null +++ b/nextjs-frontend/components/approvals/approvals-badge.tsx @@ -0,0 +1,31 @@ +"use client"; + +import { Inbox } from "lucide-react"; +import Link from "next/link"; + +import { badgeCount } from "@/components/approvals/model"; +import { useApprovalCount } from "@/components/approvals/use-approvals"; + +/** The top bar's badge: how many approvals wait for your pick, opening the inbox. Nothing shows while none wait. */ +export function ApprovalsBadge() { + const count = useApprovalCount(); + const n = count.data?.waiting ?? 0; + const label = badgeCount(n); + if (!label) return null; + return ( + + + + {label} + + + ); +} diff --git a/nextjs-frontend/components/approvals/approvals-page.tsx b/nextjs-frontend/components/approvals/approvals-page.tsx new file mode 100644 index 000000000..c9cb1ff66 --- /dev/null +++ b/nextjs-frontend/components/approvals/approvals-page.tsx @@ -0,0 +1,198 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { Inbox } from "lucide-react"; +import Link from "next/link"; +import { useSearchParams } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +import { Chats } from "@/app/openapi-client"; +import type { Approval, Estimate } from "@/app/openapi-client/types.gen"; +import { InboxCard } from "@/components/approvals/inbox-card"; +import { groupApprovals, outcomeLine, shortValue } from "@/components/approvals/model"; +import { INBOX_KEY, useApprovalsChanged } from "@/components/approvals/use-approvals"; +import { ApprovalCard } from "@/components/chat/approval"; +import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; +import { plural } from "@/lib/format"; + +/** How long a decline can be taken back before it is sent. */ +export const UNDO_MS = 6000; + +function without(s: Set, id: number): Set { + const out = new Set(s); + out.delete(id); + return out; +} + +/** The approvals inbox (docs/automations.md, Approvals): what waits for your pick, grouped by the automation or + * conversation that asked, the first in focus so Enter approves it; Decline offers Undo instead of a question; what + * was decided lately below. `?id=` (the link you were told) brings that one first. */ +export function ApprovalsPage() { + const client = useApiClient(); + const toast = useToast(); + const changed = useApprovalsChanged(); + const asked = Number(useSearchParams().get("id")) || null; + + const waiting = useQuery({ + queryKey: [...INBOX_KEY, "pending"], + queryFn: () => data(Chats.listApprovals({ client, query: { status: "pending", limit: 200 } })), + }); + const recent = useQuery({ + queryKey: [...INBOX_KEY, "recent"], + queryFn: () => data(Chats.listApprovals({ client, query: { limit: 30 } })), + }); + const inList = Boolean(asked && waiting.data?.some((a) => a.id === asked)); + const one = useQuery({ + queryKey: [...INBOX_KEY, "one", asked], + enabled: asked != null && waiting.isSuccess && !inList, + queryFn: () => data(Chats.getApproval({ client, path: { aid: asked as number } })), + retry: false, + }); + + // declined (Undo still open) or decided here: out of the list at once, before the list is read again + const [hidden, setHidden] = useState>(() => new Set()); + const timers = useRef(new Map>()); + const send = useCallback( + (id: number) => { + timers.current.delete(id); + void data(Chats.decideApproval({ client, path: { aid: id }, body: { decision: "decline" } })) + .then(changed) + .catch((e: Error) => { + setHidden((h) => without(h, id)); + toast({ tone: "red", title: "Couldn’t decline it", body: e.message }); + }); + }, + [client, changed, toast], + ); + const sendRef = useRef(send); + sendRef.current = send; + useEffect(() => { + const pending = timers.current; + return () => { + // leaving the page sends what was declined: Undo was only open while the notice was + for (const [id, t] of pending) { + clearTimeout(t); + sendRef.current(id); + } + }; + }, []); + const decline = useCallback( + (a: Approval) => { + setHidden((h) => new Set(h).add(a.id)); + timers.current.set( + a.id, + setTimeout(() => sendRef.current(a.id), UNDO_MS), + ); + toast({ + title: `Declined “${shortValue(a.summary ?? "it", 60)}”`, + body: "Nothing runs.", + duration: UNDO_MS, + action: { + label: "Undo", + onClick: () => { + clearTimeout(timers.current.get(a.id)); + timers.current.delete(a.id); + setHidden((h) => without(h, a.id)); + }, + }, + }); + }, + [toast], + ); + const done = useCallback((id: number) => setHidden((h) => new Set(h).add(id)), []); + + const items = useMemo(() => { + const left = (waiting.data ?? []).filter((a) => !hidden.has(a.id)); + return asked ? [...left.filter((a) => a.id === asked), ...left.filter((a) => a.id !== asked)] : left; + }, [waiting.data, hidden, asked]); + const groups = useMemo(() => groupApprovals(items), [items]); + const first = items[0]?.id; + const decided = (recent.data ?? []).filter((a) => a.status !== "pending" && !hidden.has(a.id)); + const shown = one.data && one.data.status !== "pending" ? one.data : null; + + return ( +
+ +

+ Enter approves the one in focus, Tab moves to the next. Declining can be undone for a few seconds. +

+
+ {shown && ( +
+

{outcomeLine(shown)}

+
+ )} + {waiting.isPending ? ( + + ) : waiting.isError ? ( + + {waiting.error.message} + + ) : groups.length === 0 ? ( + } title="Nothing waits for your pick"> + When an automation's action asks first, it waits here, and you're told in your chat app. + + ) : ( + groups.map((g) => ( +
+

+ {g.title} + {g.items.length} + {g.chat != null && ( + + Open the conversation + + )} +

+ {g.items.map((a) => + a.intent ? ( + + ) : ( + + ), + )} +
+ )) + )} + {decided.length > 0 && ( +
+

Decided lately

+
    + {decided.map((a) => ( +
  • + {outcomeLine(a)} +
  • + ))} +
+
+ )} +
+ ); +} diff --git a/nextjs-frontend/components/approvals/inbox-card.tsx b/nextjs-frontend/components/approvals/inbox-card.tsx new file mode 100644 index 000000000..c8a5aef89 --- /dev/null +++ b/nextjs-frontend/components/approvals/inbox-card.tsx @@ -0,0 +1,198 @@ +"use client"; + +import { useMutation } from "@tanstack/react-query"; +import Link from "next/link"; +import { useEffect, useRef, useState, type FormEvent } from "react"; + +import { Chats } from "@/app/openapi-client"; +import type { Approval, ApprovalDecision } from "@/app/openapi-client/types.gen"; +import { changedParams, draftOf, effectLabel, expiresLine, paramLines, shortValue } from "@/components/approvals/model"; +import { useApprovalsChanged } from "@/components/approvals/use-approvals"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Textarea } from "@/components/ui/field"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; +import { relative } from "@/lib/format"; + +const LONG = 80; // a param longer than this is edited in a text box + +/** An automation's action waiting for the person's pick: what it would do, why, when it expires, and Approve (Enter + * while the card has focus), Edit, Always allow and Decline. Decline is the page's, so it can offer Undo. */ +export function InboxCard({ + a, + autoFocus, + onDone, + onDecline, +}: { + a: Approval; + autoFocus?: boolean; + onDone: (id: number) => void; + onDecline: (a: Approval) => void; +}) { + const client = useApiClient(); + const changed = useApprovalsChanged(); + const toast = useToast(); + const ref = useRef(null); + const [editing, setEditing] = useState(false); + const [draft, setDraft] = useState>(() => draftOf(a.intent?.params)); + const [problem, setProblem] = useState(null); + useEffect(() => { + if (autoFocus) ref.current?.focus(); + }, [autoFocus]); + + const decide = useMutation({ + mutationFn: (body: ApprovalDecision) => data(Chats.decideApproval({ client, path: { aid: a.id }, body })), + onSuccess: (out, body) => { + changed(); + onDone(a.id); + if (out.status === "failed") + toast({ tone: "red", title: "Approved, but it failed", body: out.error ?? a.summary }); + else if (body.decision === "always") + toast({ + tone: "green", + title: out.always ? "Done, and allowed from now on" : "Done this once", + body: out.always ? `${a.automation ?? "The automation"} does this without asking from now on.` : out.error, + }); + else toast({ tone: "green", title: "Done", body: a.summary }); + }, + onError: (e: Error) => setProblem(e.message), + }); + + const can = a.can ?? {}; + const busy = decide.isPending; + const approve = () => { + if (can.approve && !busy) decide.mutate({ decision: "approve" }); + }; + const saveEdit = (e: FormEvent) => { + e.preventDefault(); + try { + decide.mutate({ decision: "edit", params: changedParams(draft, a.intent?.params) }); + } catch (err) { + setProblem(err instanceof Error ? err.message : String(err)); + } + }; + const effect = effectLabel(a.intent?.effect); + const expires = expiresLine(a.expires_at); + const lines = paramLines(a.intent?.params); + const why = a.why; + const whyHref = why?.url || (why?.activity ? `/timeline?q=${encodeURIComponent(why.summary ?? "")}` : null); + + return ( +
{ + if (e.key === "Enter" && e.target === e.currentTarget) { + e.preventDefault(); + approve(); + } + }} + className="flex flex-col gap-2.5 rounded-[14px] border-2 border-gold bg-gold-surface p-4 outline-none focus-visible:ring-2 focus-visible:ring-blue" + > + {a.summary ?? "An action"} +

+ {[effect, expires, a.created_at ? `asked ${relative(a.created_at)}` : null].filter(Boolean).join(" · ")} +

+ {why?.summary && ( +

+ Because:{" "} + {whyHref ? ( + + {shortValue(why.summary, 200)} + + ) : ( + shortValue(why.summary, 200) + )} +

+ )} + {!editing && lines.length > 0 && ( +
+ {lines.map((l) => ( +
+
{l.key}
+
{l.value}
+
+ ))} +
+ )} + {editing ? ( +
+ {Object.keys(draft).map((k, i) => ( + + {({ id }) => + draft[k].length > LONG || draft[k].includes("\n") ? ( +