Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions docs/automations.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,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, the studio | planned |

## Contract
Expand Down Expand Up @@ -653,6 +653,16 @@ 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`, or ⌘K (Ctrl+K) → Approvals) 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. While anything waits, a badge in the top bar counts it, the nav
has an Approvals item under Automate with the same count, and Home's Needs attention has a row for them; with nothing
waiting, none of them shows, so the nav stays as short as it was.

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).
Expand Down Expand Up @@ -944,4 +954,5 @@ and agents with the `automation_vars` and `set_automation_vars` MCP tools.
- 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.
108 changes: 108 additions & 0 deletions nextjs-frontend/__tests__/approvals-model.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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", whileCounted: true, 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");
});
});
216 changes: 216 additions & 0 deletions nextjs-frontend/__tests__/approvals-page.test.tsx
Original file line number Diff line number Diff line change
@@ -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> = {}): 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(
<QueryClientProvider client={qc}>
<TooltipProvider>
<ToastProvider>{ui}</ToastProvider>
</TooltipProvider>
</QueryClientProvider>,
);
}

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(<ApprovalsPage />);
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(<ApprovalsPage />);
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(<ApprovalsPage />);
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(<ApprovalsPage />);
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(<ApprovalsPage />);
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(<ApprovalsPage />);
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(<ApprovalsPage />);
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(<ApprovalsBadge />);
const link = await screen.findByRole("link", { name: "3 waiting for your approval" });
expect(link).toHaveAttribute("href", "/approvals");
expect(link).toHaveTextContent("3");
unmount();
waiting = [];
wrap(<ApprovalsBadge />);
await waitFor(() => expect(Chats.countApprovals).toHaveBeenCalledTimes(2));
await act(async () => undefined);
expect(screen.queryByRole("link")).not.toBeInTheDocument();
});
});
16 changes: 14 additions & 2 deletions nextjs-frontend/__tests__/nav-groups.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import { TooltipProvider } from "@/components/ui/tooltip";
jest.mock("next/navigation", () => ({ usePathname: () => "/settings/llm" }));
jest.mock("@/components/notes/notes-tree", () => ({ NotesTree: () => null }));

const nav = (collapsed: boolean) =>
const nav = (collapsed: boolean, counts = {}) =>
render(
<TooltipProvider>
<Nav admin collapsed={collapsed} counts={{}} />
<Nav admin collapsed={collapsed} counts={counts} />
</TooltipProvider>,
);

Expand Down Expand Up @@ -39,3 +39,15 @@ test("the timeline is under Explore for everyone", () => {
}
expect(isActive("/timeline", "/timeline")).toBe(true);
});

test("Approvals is in the nav only while something waits, and Automate keeps its name either way", () => {
const { unmount } = nav(false);
expect(screen.queryByRole("link", { name: /Approvals/ })).not.toBeInTheDocument();
expect(screen.getByText("Automate")).toBeInTheDocument();
unmount();
nav(false, { approvals: 2 });
expect(screen.getByRole("link", { name: "Approvals 2" })).toHaveAttribute("href", "/approvals");
const text = screen.getByRole("navigation", { name: "Primary" }).textContent ?? "";
expect(text.indexOf("Automate")).toBeLessThan(text.indexOf("Approvals"));
expect(text.indexOf("Approvals")).toBeLessThan(text.indexOf("Pipelines"));
});
Loading
Loading