From ecac7273871eb51312b888b39964d1df29a173b1 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 07:01:54 +0000 Subject: [PATCH 1/4] feat(automations): a list and a builder for automations, with a test panel Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01AjJqXgjj1cNdKGRQbX5frb --- .../__tests__/automations-model.test.ts | 236 ++++++++ .../__tests__/automations-ui.test.tsx | 300 ++++++++++ .../app/(app)/automations/[id]/page.tsx | 14 + .../app/(app)/automations/new/page.tsx | 10 + .../app/(app)/automations/page.tsx | 10 + .../components/app-shell/nav-config.ts | 2 + .../automations/automation-builder.tsx | 460 +++++++++++++++ .../automations/automation-page.tsx | 153 +++++ .../automations/automations-page.tsx | 234 ++++++++ .../components/automations/data.ts | 35 ++ .../components/automations/model.ts | 423 ++++++++++++++ .../components/automations/parts.tsx | 526 ++++++++++++++++++ .../components/automations/test-panel.tsx | 132 +++++ 13 files changed, 2535 insertions(+) create mode 100644 nextjs-frontend/__tests__/automations-model.test.ts create mode 100644 nextjs-frontend/__tests__/automations-ui.test.tsx create mode 100644 nextjs-frontend/app/(app)/automations/[id]/page.tsx create mode 100644 nextjs-frontend/app/(app)/automations/new/page.tsx create mode 100644 nextjs-frontend/app/(app)/automations/page.tsx create mode 100644 nextjs-frontend/components/automations/automation-builder.tsx create mode 100644 nextjs-frontend/components/automations/automation-page.tsx create mode 100644 nextjs-frontend/components/automations/automations-page.tsx create mode 100644 nextjs-frontend/components/automations/data.ts create mode 100644 nextjs-frontend/components/automations/model.ts create mode 100644 nextjs-frontend/components/automations/parts.tsx create mode 100644 nextjs-frontend/components/automations/test-panel.tsx diff --git a/nextjs-frontend/__tests__/automations-model.test.ts b/nextjs-frontend/__tests__/automations-model.test.ts new file mode 100644 index 00000000..258834e0 --- /dev/null +++ b/nextjs-frontend/__tests__/automations-model.test.ts @@ -0,0 +1,236 @@ +import { + aliasFor, + draftProblems, + fromApi, + graphOf, + joinFor, + joinText, + kindFields, + newTrigger, + opsFor, + rowsOf, + stepBadge, + stepsOf, + suggestedName, + toApi, + treeOf, + valueFrom, + valueText, + type Draft, + type Step, +} from "@/components/automations/model"; +import type { ActionDef } from "@/components/workflows/workflow-model"; + +// as GET /api/v1/automations/actions lists them +const actions: ActionDef[] = [ + { name: "log_line", label: "Write to the run log", group: "Run", params: {}, required: ["text"], effect: "read" }, + { + name: "ask_model", + label: "Ask the model", + group: "AI", + params: { type: "object", properties: { prompt: { type: "string", title: "Prompt" } } }, + required: ["prompt"], + effect: "read", + }, + { name: "notify", label: "Send a message", group: "Messages", params: {}, required: ["text"], effect: "depends" }, + { name: "http_request", label: "Call a web address", group: "Web", params: {}, required: ["url"], effect: "out" }, +]; +const step = (id: string, action: string, extra: Partial = {}): Step => ({ id, action, params: {}, ...extra }); + +describe("the builder's rows", () => { + it("reads a flat tree as rows and writes them back", () => { + const tree = { + any: [ + { path: "object.from.0", op: "ends_with", value: "@stmarys.org" }, + { path: "summary", op: "exists" }, + ], + }; + const r = rowsOf(tree)!; + expect(r).toEqual({ mode: "any", rows: tree.any }); + expect(treeOf(r)).toEqual(tree); + expect(rowsOf(undefined)).toEqual({ mode: "all", rows: [] }); + expect(rowsOf({ path: "summary", op: "exists" })).toEqual({ + mode: "all", + rows: [{ path: "summary", op: "exists" }], + }); + expect(treeOf({ mode: "all", rows: [{ path: " ", op: "contains", value: "x" }] })).toBeUndefined(); + expect(treeOf({ mode: "all", rows: [{ path: "summary", op: "exists", value: "left over" }] })).toEqual({ + all: [{ path: "summary", op: "exists" }], + }); + }); + + it("leaves a nested tree to be shown in words", () => { + expect(rowsOf({ all: [{ any: [{ path: "a", op: "exists" }] }] })).toBeNull(); + expect(rowsOf({ not: { path: "a", op: "exists" } })).toBeNull(); + expect(rowsOf({ all: [{ seen: { kinds: ["email.received"], within: "2d" } }] })).toBeNull(); + }); + + it("offers the tests that suit a field, and reads typed values by test", () => { + expect(opsFor("text")[0]).toBe("contains"); + expect(opsFor("number")[0]).toBe("gt"); + expect(opsFor("time")).toContain("weekday"); + expect(valueFrom("in", "a@x.io, b@x.io")).toEqual(["a@x.io", "b@x.io"]); + expect(valueFrom("between", "1, 5")).toEqual([1, 5]); + expect(valueFrom("gt", "3")).toBe(3); + expect(valueFrom("equals", "3", "number")).toBe(3); + expect(valueFrom("equals", "3")).toBe("3"); + expect(valueFrom("exists", "x")).toBeUndefined(); + expect(valueText({ path: "a", op: "in", value: ["x", "y"] })).toBe("x, y"); + }); + + it("lists a kind's fields from its schema, nested one level, with their types", () => { + const schema = { + type: "object", + properties: { + id: { type: "string" }, + summary: { type: "string", title: "Summary" }, + published: { type: "string", format: "date-time", title: "When" }, + object: { + type: "object", + title: "What", + properties: { + from: { type: "array", title: "Sender" }, + attachments: { type: "integer", title: "Attachments" }, + }, + }, + }, + }; + expect(kindFields(schema)).toEqual([ + { path: "summary", label: "Summary", type: "text" }, + { path: "published", label: "When", type: "time" }, + { path: "object.from", label: "What · Sender", type: "list" }, + { path: "object.attachments", label: "What · Attachments", type: "number" }, + ]); + }); +}); + +describe("triggers and the join line", () => { + it("names new triggers after what they are, once each", () => { + expect(aliasFor("email.received", [])).toBe("email"); + expect(aliasFor("email.received", ["email"])).toBe("email2"); + expect(newTrigger("schedule", [], "Europe/London")).toEqual({ + as: "clock", + on: "schedule", + cron: "0 7 * * *", + timezone: "Europe/London", + }); + expect(newTrigger("sensor.alert", [])).toEqual({ as: "sensor", on: "event", kinds: ["sensor.alert"] }); + expect(newTrigger("webhook", [])).toEqual({ as: "hook", on: "webhook" }); + }); + + it("reads each join as its line says it", () => { + const ts = [newTrigger("email.received", []), newTrigger("calendar_event.added", ["email"])]; + expect(joinText(joinFor("any", ts))).toBe("Any of these"); + expect(joinText({ ...joinFor("all", ts), key: "object.from.0" })).toBe( + "All of these within 10m for the same object.from.0", + ); + expect(joinText(joinFor("count", ts))).toBe("3 times email within 5m"); + expect(joinText(joinFor("absent", ts))).toBe("email and then no calendar_event within 2d"); + expect(joinText(joinFor("batch", ts))).toBe("Collect for 1h, then once"); + expect(joinFor("count", ts, { mode: "all", within: "1h" })).toEqual({ + mode: "count", + of: "email", + at_least: 3, + within: "1h", + }); + }); +}); + +describe("the Then as a list", () => { + it("hangs what passes nothing on off the step before it, and reads the graph back as the list", () => { + const steps = [ + step("ask", "ask_model"), + step("web", "http_request"), + step("tell", "notify"), + step("log", "log_line", { delay: "30m" }), + step("note", "log_line"), + ]; + const g = graphOf(steps, actions); + expect(g.edges).toEqual([ + { source: "in", target: "ask" }, + { source: "ask", target: "web" }, + { source: "ask", target: "tell" }, + { source: "ask", target: "log" }, + { source: "ask", target: "note" }, + ]); + expect(g.nodes[4].config).toEqual({ action: "log_line", params: {}, delay: "30m" }); + expect(stepsOf(g, actions)).toEqual(steps); + }); + + it("says a graph branches when a list can't draw it", () => { + const decide = graphOf([step("a", "log_line")], actions); + decide.nodes.push({ id: "d", type: "decide", config: {} }); + expect(stepsOf(decide, actions)).toBeNull(); + const side = { + nodes: [ + { id: "in", type: "input", config: {} }, + { id: "a", type: "action", config: { action: "log_line" } }, + { id: "b", type: "action", config: { action: "log_line" } }, + ], + edges: [ + { source: "in", target: "a" }, + { source: "in", target: "b" }, + ], + }; + expect(stepsOf(side, actions)).toBeNull(); + expect(stepsOf(null)).toEqual([]); + }); + + it("goes to the API's shape and back", () => { + const api = { + name: "School emails", + triggers: [{ as: "mail", on: "event", kinds: ["email.received"] }], + join: { mode: "any" }, + if: { all: [{ path: "event.object.subject", op: "contains", value: "trip" }] }, + graph: graphOf([step("a", "log_line", { params: { text: "{{ event.summary }}" } })], actions), + spaces: [3], + }; + const d = fromApi(api, actions); + expect(d.steps).toEqual([{ id: "a", action: "log_line", params: { text: "{{ event.summary }}" } }]); + expect(toApi(d, actions)).toEqual({ + name: "School emails", + triggers: api.triggers, + join: { mode: "any" }, + if: api.if, + graph: api.graph, + }); + // a join only goes with several triggers; a branching graph goes as it is + const two: Draft = { + ...d, + triggers: [...d.triggers, { as: "cal", on: "event", kinds: ["calendar_event.added"] }], + join: { mode: "all", within: "1d" }, + steps: null, + graph: { nodes: [], edges: [] }, + }; + expect(toApi(two, actions)).toMatchObject({ join: { mode: "all", within: "1d" }, graph: { nodes: [], edges: [] } }); + expect(toApi({ ...d, name: " ", triggers: [] }, actions).name).toBe("log_line"); + }); + + it("names an unnamed automation, says what is missing, and badges each step's risk", () => { + const d: Draft = { + name: "", + triggers: [{ as: "mail", on: "event", kinds: [] }], + join: { mode: "any" }, + if: null, + steps: [step("a", "ask_model"), step("b", "")], + graph: { nodes: [], edges: [] }, + }; + expect(draftProblems(d, actions)).toEqual({ + "trigger.0": "Choose what happens.", + "step.a": "Fill in Prompt.", + "step.b": "Choose an action.", + }); + expect(draftProblems({ ...d, triggers: [], steps: [] }, actions)).toEqual({ + triggers: "Add a trigger: what sets it off.", + steps: "Add an action: what it does.", + }); + expect( + suggestedName( + { ...d, triggers: [{ as: "m", on: "event", kinds: ["email.received"] }] }, + { kind: () => "Email received", action: () => "Ask the model" }, + ), + ).toBe("Ask the model on email received"); + expect(stepBadge(step("w", "http_request"), actions).label).toBe("Asks you first"); + expect(stepBadge(step("w", "http_request"), actions, { w: "auto" }).label).toBe("Runs on its own"); + }); +}); diff --git a/nextjs-frontend/__tests__/automations-ui.test.tsx b/nextjs-frontend/__tests__/automations-ui.test.tsx new file mode 100644 index 00000000..b3c8512c --- /dev/null +++ b/nextjs-frontend/__tests__/automations-ui.test.tsx @@ -0,0 +1,300 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import "@testing-library/jest-dom"; +import type { ReactNode } from "react"; + +import { Activities, Automations } from "@/app/openapi-client"; +import type { Automation } from "@/app/openapi-client/types.gen"; +import { AutomationBuilder, problemAt } from "@/components/automations/automation-builder"; +import { AutomationsPage } from "@/components/automations/automations-page"; +import { ToastProvider } from "@/components/ui/toast"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Automations: { + listAutomations: jest.fn(), + listActions: jest.fn(), + createAutomation: jest.fn(), + updateAutomation: jest.fn(), + enableAutomation: jest.fn(), + deleteAutomation: jest.fn(), + restoreAutomation: jest.fn(), + runAutomation: jest.fn(), + variableCatalog: jest.fn(), + testDraft: jest.fn(), + draftAutomation: jest.fn(), + setPolicy: jest.fn(), + }, + Activities: { listActivityKinds: jest.fn(), listActivities: jest.fn() }, + Activity: { resourceCosts: jest.fn(() => Promise.resolve({ data: { costs: {} }, response: { ok: true } })) }, + Budgets: { listBudgets: jest.fn(() => Promise.resolve({ data: [], response: { ok: true } })) }, + Routines: { previewSchedule: jest.fn() }, + Pipelines: {}, + Workflows: {}, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +const push = jest.fn(); +jest.mock("next/navigation", () => ({ useRouter: () => ({ push, replace: jest.fn() }) })); +jest.mock("@/lib/hooks/session", () => ({ + useArchive: () => ({ + admin: true, + me: { user: { admin: true } }, + namespaces: [{ id: 3, name: "home" }], + can: () => true, + }), +})); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const m = (f: unknown) => f as jest.Mock; + +const ACTIONS = [ + { + name: "notify", + label: "Send a message", + group: "Messages", + description: "Tells you in your own chat app", + params: { + type: "object", + properties: { to: { type: "string", title: "To", default: "me" }, text: { type: "string", title: "Message" } }, + }, + required: ["text"], + effect: "depends", + }, + { + name: "http_request", + label: "Call a web address", + group: "Web", + params: { type: "object", properties: { url: { type: "string", title: "Address" } } }, + required: ["url"], + effect: "out", + }, +]; +const KINDS = [ + { + name: "email.received", + label: "Email received", + source: "Email", + type: "Create", + object_type: "Note", + schema: { + type: "object", + properties: { + summary: { type: "string", title: "Summary" }, + object: { type: "object", title: "What", properties: { subject: { type: "string", title: "Subject" } } }, + }, + }, + }, +]; +const ROW = { + id: 7, + name: "School emails", + enabled: true, + run_as: 1, + triggers: [{ as: "email", on: "event", kinds: ["email.received"] }], + join: { mode: "any" }, + workflow: 12, + graph: { + nodes: [ + { id: "in", type: "input", config: {} }, + { id: "notify", type: "action", config: { action: "notify", params: { text: "{{ event.summary }}" } } }, + ], + edges: [{ source: "in", target: "notify" }], + }, + policy: {}, + limits: {}, + counters: {}, + last_status: "done", + last_run_at: "2026-10-18T06:00:00Z", + waiting: 2, + runs_today: 3, + reads: "“Email received”, where the subject contains “trip”", + next_at: null, +} as unknown as Automation; + +function wrap(ui: ReactNode) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + {ui} + + , + ); +} + +beforeEach(() => { + m(Automations.listActions).mockReturnValue(ok(ACTIONS)); + m(Activities.listActivityKinds).mockReturnValue(ok(KINDS)); + m(Automations.variableCatalog).mockReturnValue( + ok({ + variables: [ + { path: "event.summary", type: "string", label: "Summary", group: "The activity" }, + { path: "events.email.object.subject", type: "string", label: "Subject", group: "email" }, + ], + }), + ); + m(Activities.listActivities).mockReturnValue( + ok({ + items: [{ id: "act-1", kind: "email.received", summary: "Trip on Friday", published: "2026-10-18T05:00:00Z" }], + }), + ); +}); + +test("the list reads each automation, and Delete is undone from its toast", async () => { + m(Automations.listAutomations).mockReturnValue(ok({ automations: [ROW] })); + m(Automations.deleteAutomation).mockReturnValue(ok({ ok: true })); + m(Automations.restoreAutomation).mockReturnValue(ok({ ok: true })); + wrap(); + const row = (await screen.findByRole("link", { name: "School emails" })).closest("tr")!; + expect(within(row).getByText("“Email received”, where the subject contains “trip”")).toBeInTheDocument(); + expect(within(row).getByText("Done")).toBeInTheDocument(); + expect(within(row).getByText("3")).toBeInTheDocument(); + expect(within(row).getByRole("link", { name: "2" })).toHaveAttribute("href", "/approvals"); + expect(within(row).getByRole("switch", { name: "School emails on" })).toBeChecked(); + fireEvent.keyDown(within(row).getByRole("button", { name: "More for School emails" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Delete" })); + await waitFor(() => expect(Automations.deleteAutomation).toHaveBeenCalled()); + fireEvent.click(await screen.findByRole("button", { name: "Undo" })); + await waitFor(() => expect(Automations.restoreAutomation).toHaveBeenCalled()); +}); + +test("an empty list says what automations are for", async () => { + m(Automations.listAutomations).mockReturnValue(ok({ automations: [] })); + wrap(); + expect(await screen.findByText("No automations yet")).toBeInTheDocument(); +}); + +test("the builder adds a trigger with a condition and an action, then saves it switched off", async () => { + m(Automations.createAutomation).mockReturnValue(ok({ id: 9, hooks: [] })); + const saved = jest.fn(); + wrap(); + expect(screen.getByLabelText("Describe it in words")).toHaveFocus(); + // When: an email arrives, only when the subject contains trip + fireEvent.keyDown(screen.getByRole("button", { name: "Add a trigger" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Email received" })); + expect(await screen.findByRole("heading", { name: "Email received" })).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Add an only-when condition" })); + fireEvent.change(screen.getByLabelText("Field 1"), { target: { value: "object.subject" } }); + fireEvent.change(screen.getByLabelText("Value 1"), { target: { value: "trip" } }); + // Then: send a message, its text from the variable picker + fireEvent.keyDown(screen.getByRole("button", { name: "Add an action" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Send a message" })); + expect(await screen.findByText("Asks you first when it reaches other people")).toBeInTheDocument(); + const text = screen.getByLabelText(/^Message/); + await waitFor(() => expect(Automations.variableCatalog).toHaveBeenCalled()); + fireEvent.change(text, { target: { value: "School: {{ eve", selectionStart: 14 } }); + fireEvent.keyDown(text, { key: "Enter" }); + expect(text).toHaveValue("School: {{ event.summary }}"); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(Automations.createAutomation).toHaveBeenCalled()); + const body = m(Automations.createAutomation).mock.calls[0][0].body; + expect(body).toMatchObject({ + name: "Send a message on email received", + enabled: false, + triggers: [ + { + as: "email", + on: "event", + kinds: ["email.received"], + where: { all: [{ path: "object.subject", op: "contains", value: "trip" }] }, + }, + ], + if: null, + }); + expect(body.graph.nodes[1]).toMatchObject({ + type: "action", + config: { action: "notify", params: { text: "School: {{ event.summary }}" } }, + }); + expect(saved).toHaveBeenCalledWith(9, []); +}); + +test("Describe it in words fills the builder and says what it left out", async () => { + m(Automations.draftAutomation).mockReturnValue( + ok({ + draft: { + name: "Tell me about school emails", + triggers: [{ as: "mail", on: "event", kinds: ["email.received"] }], + graph: ROW.graph, + }, + dropped: [], + unmapped: ["when both arrive"], + }), + ); + wrap(); + const box = screen.getByLabelText("Describe it in words"); + fireEvent.change(box, { target: { value: "When the school emails, tell me" } }); + fireEvent.keyDown(box, { key: "Enter" }); + expect(await screen.findByDisplayValue("Tell me about school emails")).toBeInTheDocument(); + expect(screen.getByText("Not done: when both arrive")).toBeInTheDocument(); + expect(Automations.createAutomation).not.toHaveBeenCalled(); +}); + +test("the test panel runs the draft on a recent activity and says what it would do", async () => { + m(Automations.testDraft).mockReturnValue( + ok({ + status: "done", + trace: { notify: { status: "done" } }, + log: ["would tell you"], + intents: [{ node: "notify", action: "notify", status: "done", risk: "routine" }], + steps: 1, + }), + ); + wrap(); + fireEvent.click(await screen.findByRole("button", { name: "Test" })); + const panel = screen.getByRole("complementary", { name: "Test" }); + await within(panel).findByRole("option", { name: /Trip on Friday/ }); + fireEvent.click(within(panel).getByRole("button", { name: "Test" })); + expect(await within(panel).findByText("notify · Send a message: would run at once")).toBeInTheDocument(); + expect(m(Automations.testDraft).mock.calls[0][0].body).toMatchObject({ + activity: "act-1", + draft: { name: "School emails" }, + }); +}); + +test("a saved automation lets an outside action run on its own, and a branching one opens in the canvas", async () => { + const web = { + ...ROW, + graph: { + nodes: [ + { id: "in", type: "input", config: {} }, + { id: "http", type: "action", config: { action: "http_request", params: { url: "https://example.org" } } }, + ], + edges: [{ source: "in", target: "http" }], + }, + } as unknown as Automation; + m(Automations.setPolicy).mockReturnValue(ok({ http: "auto" })); + const { unmount } = wrap(); + fireEvent.click(await screen.findByRole("switch", { name: "Let Call a web address run on its own" })); + await waitFor(() => + expect(m(Automations.setPolicy).mock.calls[0][0]).toMatchObject({ + path: { aid: 7 }, + body: { node: "http", value: "auto" }, + }), + ); + expect(await screen.findByText("Runs on its own")).toBeInTheDocument(); + unmount(); + const branching = { + ...ROW, + graph: { + ...ROW.graph, + nodes: [...(ROW.graph as { nodes: unknown[] }).nodes, { id: "d", type: "decide", config: {} }], + }, + } as unknown as Automation; + wrap(); + expect(await screen.findByText("This automation branches; edit it in the canvas.")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Open in canvas" })).toHaveAttribute("href", "/workflows/12"); +}); + +test("API problems go next to what they are about", () => { + const d = { + name: "", + triggers: [{ as: "mail", on: "event" }], + join: { mode: "any" as const }, + if: null, + steps: [{ id: "a", action: "notify", params: {} }], + graph: { nodes: [], edges: [] }, + }; + expect(problemAt("trigger mail: choose kinds", d)).toBe("trigger.0"); + expect(problemAt("action node a reaches outside Lens", d)).toBe("step.a"); + expect(problemAt("limits: cooldown is a duration", d)).toBe(""); +}); diff --git a/nextjs-frontend/app/(app)/automations/[id]/page.tsx b/nextjs-frontend/app/(app)/automations/[id]/page.tsx new file mode 100644 index 00000000..362810a6 --- /dev/null +++ b/nextjs-frontend/app/(app)/automations/[id]/page.tsx @@ -0,0 +1,14 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; + +import { AutomationPage } from "@/components/automations/automation-page"; + +export const metadata: Metadata = { title: "Automation" }; + +/** One automation: the builder, and what it has done. */ +export default async function Page({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const n = Number(id); + if (!Number.isInteger(n) || n < 1) notFound(); + return ; +} diff --git a/nextjs-frontend/app/(app)/automations/new/page.tsx b/nextjs-frontend/app/(app)/automations/new/page.tsx new file mode 100644 index 00000000..4abd1eac --- /dev/null +++ b/nextjs-frontend/app/(app)/automations/new/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; + +import { NewAutomationPage } from "@/components/automations/automation-page"; + +export const metadata: Metadata = { title: "New automation" }; + +/** A new automation, from the builder or a sentence. */ +export default function Page() { + return ; +} diff --git a/nextjs-frontend/app/(app)/automations/page.tsx b/nextjs-frontend/app/(app)/automations/page.tsx new file mode 100644 index 00000000..bb21de28 --- /dev/null +++ b/nextjs-frontend/app/(app)/automations/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; + +import { AutomationsPage } from "@/components/automations/automations-page"; + +export const metadata: Metadata = { title: "Automations" }; + +/** Automations: when something happens, if a test passes, do something. */ +export default function Page() { + return ; +} diff --git a/nextjs-frontend/components/app-shell/nav-config.ts b/nextjs-frontend/components/app-shell/nav-config.ts index 598ea5f8..38fef4d7 100644 --- a/nextjs-frontend/components/app-shell/nav-config.ts +++ b/nextjs-frontend/components/app-shell/nav-config.ts @@ -22,6 +22,7 @@ import { Wallet, Waypoints, Workflow, + Zap, } from "lucide-react"; export type NavItem = { @@ -74,6 +75,7 @@ export const NAV: NavItem[] = [ whileCounted: true, group: "Automate", }, + { label: "Automations", href: "/automations", icon: Zap, group: "Automate" }, { label: "Pipelines", href: "/pipelines", icon: Workflow, group: "Automate" }, // Everything that runs on a clock in one list: everyone has it, for the schedules of their own automations. It // takes the row Routines had (the Routines page opens from it), so the nav fits a phone screen as before. diff --git a/nextjs-frontend/components/automations/automation-builder.tsx b/nextjs-frontend/components/automations/automation-builder.tsx new file mode 100644 index 00000000..165d245a --- /dev/null +++ b/nextjs-frontend/components/automations/automation-builder.tsx @@ -0,0 +1,460 @@ +"use client"; + +/** + * The builder: When (triggers and the join line), If (conditions on the run) and Then (actions in order), read top to + * bottom, with "Describe it in words" on a new one, a test panel, and Save and turn on. Ctrl/Cmd+Enter saves; Enter + * on the last row adds the next. + */ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { FlaskConical, Plus, Sparkles, Workflow as WorkflowIcon } from "lucide-react"; +import Link from "next/link"; +import { useEffect, useMemo, useState, type KeyboardEvent } from "react"; + +import { Automations } from "@/app/openapi-client"; +import type { Automation } from "@/app/openapi-client/types.gen"; +import { useActions, useKinds } from "@/components/automations/data"; +import { + CLOCK, + draftProblems, + fromApi, + joinFor, + newTrigger, + stepId, + suggestedName, + toApi, + type Draft, + type FieldType, + type Step, +} from "@/components/automations/model"; +import { JoinLine, RowsEditor, StepCard, TriggerCard, type FieldInfo } from "@/components/automations/parts"; +import { TestPanel } from "@/components/automations/test-panel"; +import type { Variable } from "@/components/forms/schema-form"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/field"; +import { Menu, MenuContent, MenuItem, MenuLabel, MenuTrigger } from "@/components/ui/menu"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; + +const BLANK: Draft = { + name: "", + triggers: [], + join: { mode: "any" }, + if: null, + steps: [], + graph: { nodes: [], edges: [] }, +}; + +/** Where an API problem belongs: a trigger (by index), an action (by id), or the automation. */ +export function problemAt(msg: string, d: Draft): string { + const t = /^trigger (\w+)/.exec(msg)?.[1]; + const k = d.triggers.findIndex((x) => x.as === t); + if (k >= 0) return `trigger.${k}`; + const n = /(?:action node|decide) (\w+)/.exec(msg)?.[1]; + if (n && d.steps?.some((s) => s.id === n)) return `step.${n}`; + return ""; +} + +const TYPES: Record = { + string: "text", + number: "number", + integer: "number", + array: "list", + boolean: "bool", + time: "time", + datetime: "time", +}; + +export type Hook = { as: string; url: string; secret: string }; + +export function AutomationBuilder({ + automation, + onSaved, +}: { + automation?: Automation; + /** After a save: its id, and any new webhook addresses with their secrets (shown once). */ + onSaved?: (id: number, hooks: Hook[]) => void; +}) { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const actions = useActions(); + const kinds = useKinds(); + const acts = actions.data; + const [draft, setDraft] = useState(() => (automation ? fromApi(automation as never, acts) : BLANK)); + const [policy, setPolicy] = useState>(() => ({ ...(automation?.policy ?? {}) })); + const [testing, setTesting] = useState(false); + const [error, setError] = useState<{ at: string; message: string } | null>(null); + const [notes, setNotes] = useState([]); + const [words, setWords] = useState(""); + const saved = automation?.id; + + // once the catalog is in, a saved graph is read as steps against it (what passes nothing on hangs as a leaf) + useEffect(() => { + if (automation && acts) + setDraft((d) => (d.steps === null || !d.steps.length ? fromApi(automation as never, acts) : d)); + }, [automation, acts]); + + const kindLabel = (k: string) => kinds.data?.find((x) => x.name === k)?.label ?? k; + const actionLabel = (a: string) => acts?.find((x) => x.name === a)?.label ?? a; + const guess = suggestedName(draft, { kind: kindLabel, action: actionLabel }); + const problems = { ...draftProblems(draft, acts), ...(error ? { [error.at]: error.message } : {}) }; + + // what templates and conditions can read, from the draft's triggers + const catalogKey = JSON.stringify(draft.triggers.map((t) => [t.as, t.on, t.kinds])); + const vars = useQuery({ + queryKey: ["automation-variables", saved ?? null, catalogKey], + queryFn: () => + data( + Automations.variableCatalog({ + client, + body: { draft: { triggers: draft.triggers, ...(saved ? { id: saved } : {}) } as never }, + }), + ), + enabled: draft.triggers.length > 0, + retry: false, + staleTime: 60_000, + }); + const variables: Variable[] = useMemo( + () => (vars.data?.variables ?? []).map((v) => ({ path: v.path, label: v.label, group: v.group })), + [vars.data], + ); + const ifFields: FieldInfo[] = (vars.data?.variables ?? []).map((v) => ({ + path: v.path, + label: v.label, + type: TYPES[v.type] ?? "any", + })); + const stepVariables = (k: number): Variable[] => [ + ...variables, + ...(draft.steps ?? []).slice(0, k).map((s) => ({ + path: `steps.${s.id}`, + label: `What ${actionLabel(s.action)} gave back`, + group: "Steps", + })), + ]; + + const set = (patch: Partial) => { + setError(null); + setDraft((d) => ({ ...d, ...patch })); + }; + const setSteps = (steps: Step[]) => set({ steps }); + + const describe = useMutation({ + mutationFn: (text: string) => data(Automations.draftAutomation({ client, body: { text } })), + onSuccess: (r) => { + const d = fromApi(r.draft as never, acts); + setDraft({ ...d, steps: d.steps ?? [] }); + setNotes([...(r.dropped ?? []), ...(r.unmapped ?? []).map((u) => `Not done: ${u}`)]); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t draft it", body: e.message }), + }); + + const save = useMutation({ + mutationFn: async (turnOn: boolean) => { + const body = toApi({ ...draft, name: draft.name.trim() || guess }, acts); + if (!saved) { + const r = await data(Automations.createAutomation({ client, body: { ...body, enabled: turnOn } as never })); + return { id: r.id, hooks: r.hooks ?? [] }; + } + const r = await data(Automations.updateAutomation({ client, path: { aid: saved }, body: body as never })); + if (turnOn && !automation?.enabled) + await data(Automations.enableAutomation({ client, path: { aid: saved }, body: { on: true } })); + return { id: saved, hooks: r.hooks ?? [] }; + }, + onSuccess: (r, turnOn) => { + void qc.invalidateQueries({ queryKey: ["automations"] }); + void qc.invalidateQueries({ queryKey: ["automation", r.id] }); + toast({ + tone: "green", + title: turnOn ? "Saved and on" : "Saved", + body: turnOn ? "It acts on what happens from now on." : saved ? undefined : "It’s off until you turn it on.", + }); + onSaved?.(r.id, r.hooks as Hook[]); + }, + onError: (e: Error) => setError({ at: problemAt(e.message, draft), message: e.message }), + }); + + const policyFor = useMutation({ + mutationFn: ({ node, auto }: { node: string; auto: boolean }) => + data(Automations.setPolicy({ client, path: { aid: saved! }, body: { node, value: auto ? "auto" : "ask" } })), + onSuccess: (r) => { + setPolicy(r as Record); + void qc.invalidateQueries({ queryKey: ["automation", saved] }); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t change it", body: e.message }), + }); + + const blocked = Object.entries(draftProblems(draft, acts))[0]; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !blocked && !save.isPending) { + e.preventDefault(); + save.mutate(false); + } + }; + const savedNodes = new Set( + ((automation?.graph as { nodes?: { id: string }[] } | null)?.nodes ?? []).map((n) => n.id), + ); + const groups = [...new Set((kinds.data ?? []).filter((k) => !k.noisy).map((k) => k.source))]; + const actionGroups = [...new Set((acts ?? []).map((a) => a.group))]; + + return ( +
+
+ {!saved && ( +
+ +
+ setWords(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && !e.metaKey && !e.ctrlKey && words.trim()) { + e.preventDefault(); + describe.mutate(words.trim()); + } + }} + /> + +
+

+ The model fills the builder in; nothing is saved until you save. +

+ {notes.length > 0 && ( +
    + {notes.map((n) => ( +
  • {n}
  • + ))} +
+ )} +
+ )} + + set({ name: e.target.value })} + /> + +
+

+ When +

+ {problems.triggers &&

{problems.triggers}

} + {draft.triggers.map((t, k) => ( + set({ triggers: draft.triggers.map((y, i) => (i === k ? x : y)) })} + onRemove={() => { + const triggers = draft.triggers.filter((_, i) => i !== k); + set({ + triggers, + join: triggers.length > 1 ? joinFor(draft.join.mode, triggers, draft.join) : { mode: "any" }, + }); + }} + /> + ))} + {draft.triggers.length > 1 && ( + set({ join })} /> + )} + + + + + + {groups.map((g) => ( +
+ {g} + {(kinds.data ?? []) + .filter((k) => k.source === g && !k.noisy) + .map((k) => ( + + set({ + triggers: [ + ...draft.triggers, + newTrigger( + k.name, + draft.triggers.map((x) => x.as), + ), + ], + }) + } + > + {k.label} + + ))} +
+ ))} + Time and calls + {CLOCK.map((c) => ( + + set({ + triggers: [ + ...draft.triggers, + newTrigger( + c.on, + draft.triggers.map((x) => x.as), + Intl.DateTimeFormat().resolvedOptions().timeZone, + ), + ], + }) + } + > + {c.label} + + ))} +
+
+
+ +
+

+ If optional +

+ set({ if: tree ?? null })} + fields={ifFields} + empty="It always goes on to Then." + /> +
+ +
+

+ Then +

+ {draft.steps === null ? ( +
+

This automation branches; edit it in the canvas.

+ {automation?.workflow != null && ( + + )} +
+ ) : ( + <> + {problems.steps &&

{problems.steps}

} + {draft.steps.map((s, k) => ( + setSteps(draft.steps!.map((y) => (y.id === s.id ? x : y)))} + onRemove={() => setSteps(draft.steps!.filter((y) => y.id !== s.id))} + onMove={(by) => { + const list = [...draft.steps!]; + const [x] = list.splice(k, 1); + list.splice(k + by, 0, x); + setSteps(list); + }} + onPolicy={(auto) => policyFor.mutate({ node: s.id, auto })} + /> + ))} + + + + + + {actionGroups.map((g) => ( +
+ {g} + {(acts ?? []) + .filter((a) => a.group === g) + .map((a) => ( + + setSteps([ + ...(draft.steps ?? []), + { id: stepId(draft.steps ?? [], a.name), action: a.name, params: {} }, + ]) + } + > + {a.label} + + ))} +
+ ))} +
+
+ {automation?.workflow != null && draft.steps.length > 0 && ( + + Open in canvas, to branch on a condition or the model’s pick + + )} + + )} +
+ + {problems[""] && ( +

+ {problems[""]} +

+ )} +
+ {!automation?.enabled && ( + + )} + + + Ctrl or ⌘ + Enter saves. +
+
+ {testing && setTesting(false)} />} +
+ ); +} diff --git a/nextjs-frontend/components/automations/automation-page.tsx b/nextjs-frontend/components/automations/automation-page.tsx new file mode 100644 index 00000000..7df246a5 --- /dev/null +++ b/nextjs-frontend/components/automations/automation-page.tsx @@ -0,0 +1,153 @@ +"use client"; + +/** One automation: its name, on or off, Run now, and the builder; a new one starts from the builder alone. */ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Play, Zap } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useEffect, useState } from "react"; + +import { Automations } from "@/app/openapi-client"; +import { AutomationBuilder, type Hook } from "@/components/automations/automation-builder"; +import { runStatus } from "@/components/automations/model"; +import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/field"; +import { EmptyState, Skeleton } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; + +const HOOKS = (id: number) => `automation-hooks-${id}`; + +function Crumbs({ name }: { name: string }) { + return ( + + ); +} + +export function NewAutomationPage() { + const router = useRouter(); + return ( +
+ +

New automation

+ { + // a webhook's secret shows once: carry it to the automation's page + if (hooks.length) + try { + sessionStorage.setItem(HOOKS(id), JSON.stringify(hooks)); + } catch { + // no storage: the page says to look at the trigger again + } + router.push(`/automations/${id}`); + }} + /> +
+ ); +} + +export function AutomationPage({ id }: { id: number }) { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const q = useQuery({ + queryKey: ["automation", id], + queryFn: () => data(Automations.getAutomation({ client, path: { aid: id } })), + }); + const [hooks, setHooks] = useState([]); + useEffect(() => { + try { + const got = sessionStorage.getItem(HOOKS(id)); + if (got) { + setHooks(JSON.parse(got) as Hook[]); + sessionStorage.removeItem(HOOKS(id)); + } + } catch { + // nothing carried over + } + }, [id]); + const a = q.data; + const toggle = useMutation({ + mutationFn: (on: boolean) => data(Automations.enableAutomation({ client, path: { aid: id }, body: { on } })), + onSuccess: () => { + void qc.invalidateQueries({ queryKey: ["automation", id] }); + void qc.invalidateQueries({ queryKey: ["automations"] }); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t switch it", body: e.message }), + }); + const run = useMutation({ + mutationFn: () => data(Automations.runAutomation({ client, path: { aid: id }, body: {} })), + onSuccess: (r) => { + void qc.invalidateQueries({ queryKey: ["automation-runs", id] }); + toast( + r.run + ? { tone: "green", title: "It ran", body: runStatus(r.status).label } + : { tone: "gate", title: "It didn’t run", body: r.why ?? undefined }, + ); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t run it", body: e.message }), + }); + + if (q.isLoading) + return ( +
+ + +
+ ); + if (q.error || !a) { + const e = q.error as ApiError | null; + return ( + } + title={e?.status === 404 ? "This automation doesn’t exist" : "Couldn’t load the automation"} + actions={ + + } + > + {e?.message} + + ); + } + return ( +
+ +
+

{a.name}

+ toggle.mutate(on)} + label={a.enabled ? "On" : "Off"} + aria-label={`${a.name} on`} + /> + +
+ {hooks.length > 0 && ( +
+

Its webhook addresses, shown this once: keep the secret to sign calls.

+ {hooks.map((h) => ( +

+ {h.as}: {h.url} · secret {h.secret} +

+ ))} +
+ )} + got.length && setHooks(got)} + /> +
+ ); +} diff --git a/nextjs-frontend/components/automations/automations-page.tsx b/nextjs-frontend/components/automations/automations-page.tsx new file mode 100644 index 00000000..998738f3 --- /dev/null +++ b/nextjs-frontend/components/automations/automations-page.tsx @@ -0,0 +1,234 @@ +"use client"; + +/** Automations: each one's name, what sets it off, whether it is on, its last run, runs today, what waits for you, + * what it cost this month and when it runs next; Run now, Duplicate and Delete (with Undo) on each. */ +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { Ellipsis, Plus, Zap } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; + +import { Automations } from "@/app/openapi-client"; +import type { Automation } from "@/app/openapi-client/types.gen"; +import { runStatus } from "@/components/automations/model"; +import { useAutomations } from "@/components/automations/data"; +import { CostCell, useBudgets, useCosts } from "@/components/costs/costs"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/field"; +import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from "@/components/ui/menu"; +import { DateTime, EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; +import { Table, Td, Th, THead, Tr } from "@/components/ui/table"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; + +export function AutomationsPage() { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const list = useAutomations(); + const rows = list.data?.automations ?? []; + const costs = useCosts(rows.map((a) => `automation:${a.id}`)); + const budgets = useBudgets(); + const refresh = () => qc.invalidateQueries({ queryKey: ["automations"] }); + + const toggle = useMutation({ + mutationFn: ({ a, on }: { a: Automation; on: boolean }) => + data(Automations.enableAutomation({ client, path: { aid: a.id }, body: { on } })), + onSuccess: () => void refresh(), + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t switch it", body: e.message }), + }); + const run = useMutation({ + mutationFn: (a: Automation) => data(Automations.runAutomation({ client, path: { aid: a.id }, body: {} })), + onSuccess: (r, a) => { + void refresh(); + toast( + r.run + ? { + tone: "green", + title: `${a.name} ran`, + body: runStatus(r.status).label, + action: { label: "Open", onClick: () => router.push(`/automations/${a.id}?tab=runs`) }, + } + : { tone: "gate", title: `${a.name} didn’t run`, body: r.why ?? undefined }, + ); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t run it", body: e.message }), + }); + const duplicate = useMutation({ + mutationFn: async (a: Automation) => { + const body = { + name: `${a.name} (copy)`, + // a copy's webhook gets an address of its own when it is saved + triggers: a.triggers.map((t) => (t.on === "webhook" ? { as: t.as, on: t.on } : t)), + join: a.join, + if: a.if ?? null, + graph: a.graph ?? undefined, + workflow: a.graph ? undefined : a.workflow, + spaces: a.spaces, + limits: a.limits, + enabled: false, + }; + return data(Automations.createAutomation({ client, body: body as never })); + }, + onSuccess: (r) => { + void refresh(); + router.push(`/automations/${r.id}`); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t duplicate it", body: e.message }), + }); + const restore = useMutation({ + mutationFn: (a: Automation) => data(Automations.restoreAutomation({ client, path: { aid: a.id } })), + onSuccess: () => void refresh(), + }); + const remove = useMutation({ + mutationFn: (a: Automation) => data(Automations.deleteAutomation({ client, path: { aid: a.id } })), + onSuccess: (_, a) => { + void refresh(); + toast({ + title: `Deleted ${a.name}`, + body: "Undo brings it back, switched off.", + action: { label: "Undo", onClick: () => restore.mutate(a) }, + }); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t delete it", body: e.message }), + }); + + return ( +
+ a.enabled).length} on` : undefined} + actions={ + + } + > +

+ When something happens, if a test passes, Lens does something for you. What reaches outside Lens asks you + first, on the Approvals page. +

+
+ {list.isLoading ? ( + + ) : list.error ? ( + } + title="Couldn’t load automations" + actions={} + > + {(list.error as Error).message} + + ) : !rows.length ? ( + } + title="No automations yet" + actions={ + + } + > + Tell Lens what to do when something happens: an email from the school arrives, a sensor raises an alert, or + every weekday at seven. Describe it in words and Lens drafts it. + + ) : ( +
+ + + + + + + + + + + + + + + {rows.map((a) => { + const st = a.last_status ? runStatus(a.last_status) : null; + return ( + + + + + + + + + + + ); + })} + +
AutomationLast runTodayWaitingThis monthNextOn + Actions +
+
+ + {a.name} + + {a.reads && {a.reads}} +
+
+
+ {st ? {st.label} : Not yet} + {a.last_run_at && } +
+
{a.runs_today ?? 0} + {a.waiting ? ( + + {a.waiting} + + ) : ( + 0 + )} + + + + {a.enabled && a.next_at ? : "—"} + + toggle.mutate({ a, on })} + /> + + + + + + + run.mutate(a)}>Run now + duplicate.mutate(a)}>Duplicate + + remove.mutate(a)}> + Delete + + + +
+
+ )} +
+ ); +} diff --git a/nextjs-frontend/components/automations/data.ts b/nextjs-frontend/components/automations/data.ts new file mode 100644 index 00000000..980cf8e0 --- /dev/null +++ b/nextjs-frontend/components/automations/data.ts @@ -0,0 +1,35 @@ +"use client"; + +/** What the studio reads from the API: automations, the actions catalog and the kinds of activity. */ +import { useQuery } from "@tanstack/react-query"; + +import { Activities, Automations } from "@/app/openapi-client"; +import type { ActivityKind } from "@/app/openapi-client/types.gen"; +import type { ActionDef } from "@/components/workflows/workflow-model"; +import { data, useApiClient } from "@/lib/api/browser"; + +export function useAutomations() { + const client = useApiClient(); + return useQuery({ + queryKey: ["automations"], + queryFn: () => data(Automations.listAutomations({ client })), + }); +} + +export function useActions() { + const client = useApiClient(); + return useQuery({ + queryKey: ["automation-actions"], + queryFn: async () => (await data(Automations.listActions({ client }))) as ActionDef[], + staleTime: 300_000, + }); +} + +export function useKinds() { + const client = useApiClient(); + return useQuery({ + queryKey: ["activity-kinds"], + queryFn: async () => (await data(Activities.listActivityKinds({ client }))) as ActivityKind[], + staleTime: 300_000, + }); +} diff --git a/nextjs-frontend/components/automations/model.ts b/nextjs-frontend/components/automations/model.ts new file mode 100644 index 00000000..ee8cb62f --- /dev/null +++ b/nextjs-frontend/components/automations/model.ts @@ -0,0 +1,423 @@ +/** + * An automation as the studio's builder edits it: When (triggers, each with "only when" rows, and a join line), If + * (rows over the run context) and Then (an ordered list of action steps), read from and written back to the API's + * shape (docs/automations.md, Saving automations). A Then that isn't a straight list is kept as its graph and edited + * on the canvas. + */ +import type { Tone } from "@/components/ui/badge"; +import { effectBadge, type ActionDef, type WfEdge, type WfGraph } from "@/components/workflows/workflow-model"; + +/** One test of a match tree: {path, op, value}. */ +export type Test = { path: string; op: string; value?: unknown }; +/** A flat match tree, as rows: all (or any) of the tests. */ +export type Rows = { mode: "all" | "any"; rows: Test[] }; +export type Trigger = { + as: string; + on: string; + kinds?: string[]; + where?: unknown; + cron?: string; + timezone?: string; + at?: string; + field?: string; + offset?: string; + [key: string]: unknown; +}; +export type Join = { + mode: "any" | "all" | "count" | "absent" | "batch"; + within?: string; + key?: string; + of?: string; + at_least?: number; + after?: string; + missing?: string; +}; +/** One action of the Then, in order: an action node. */ +export type Step = { id: string; action: string; params: Record; delay?: string; when?: string }; +export type Draft = { + name: string; + triggers: Trigger[]; + join: Join; + /** The If as a match tree, or null for none. */ + if: unknown; + /** The Then as steps, or null when it branches (then `graph` is what it is). */ + steps: Step[] | null; + graph: WfGraph; + spaces?: number[] | null; +}; + +// ---------- match trees as rows ---------- +const isTest = (m: unknown): m is Test => + Boolean(m) && typeof m === "object" && typeof (m as Test).op === "string" && !("seen" in (m as object)); + +/** A tree as rows, or null when it nests (it is shown in words and edited as a whole, not as rows). */ +export function rowsOf(tree: unknown): Rows | null { + if (tree == null) return { mode: "all", rows: [] }; + if (isTest(tree)) return { mode: "all", rows: [{ ...tree, path: tree.path ?? "" }] }; + const t = tree as { all?: unknown[]; any?: unknown[] }; + const list = t.all ?? t.any; + if (!Array.isArray(list) || Object.keys(t).length !== 1 || !list.every(isTest)) return null; + return { mode: t.all ? "all" : "any", rows: list.map((x) => ({ ...(x as Test), path: (x as Test).path ?? "" })) }; +} + +/** Rows as a tree: rows without a path or a test are left out; none gives no tree. */ +export function treeOf(r: Rows): unknown { + const rows = r.rows + .filter((x) => x.path.trim() && x.op) + .map((x) => (NO_VALUE.includes(x.op) ? { path: x.path.trim(), op: x.op } : { ...x, path: x.path.trim() })); + return rows.length ? { [r.mode]: rows } : undefined; +} + +export const OP_LABEL: Record = { + contains: "contains", + equals: "is", + not_equals: "isn’t", + starts_with: "starts with", + ends_with: "ends with", + matches: "matches", + in: "is one of", + not_in: "isn’t one of", + gt: "is more than", + lt: "is less than", + between: "is between", + before: "is before", + after: "is after", + within: "is within", + weekday: "is on", + time_between: "is between the times", + exists: "is there", + empty: "is empty", + changed: "changed", +}; +export const NO_VALUE = ["exists", "empty", "changed"]; +/** Tests that take a list of values, written with commas. */ +const LISTS = ["in", "not_in", "between", "weekday", "time_between"]; + +export type FieldType = "text" | "number" | "time" | "list" | "bool" | "any"; + +/** The tests that suit a field of this type, the likeliest first. */ +export function opsFor(type: FieldType): string[] { + switch (type) { + case "text": + return [ + "contains", + "equals", + "not_equals", + "starts_with", + "ends_with", + "matches", + "in", + "not_in", + "exists", + "empty", + "changed", + ]; + case "number": + return ["gt", "lt", "equals", "not_equals", "between", "in", "exists", "changed"]; + case "time": + return ["within", "before", "after", "between", "weekday", "time_between", "exists"]; + case "list": + return ["contains", "empty", "exists", "in", "not_in"]; + case "bool": + return ["equals", "exists", "changed"]; + default: + return Object.keys(OP_LABEL); + } +} + +/** A test's value as its box shows it. */ +export function valueText(t: Test): string { + if (t.value == null) return ""; + if (Array.isArray(t.value)) return t.value.map(String).join(", "); + return String(t.value); +} + +/** What's typed in a test's box as its value: lists with commas, numbers for number tests, true/false for toggles. */ +export function valueFrom(op: string, text: string, type: FieldType = "any"): unknown { + if (NO_VALUE.includes(op)) return undefined; + const num = (s: string) => (/^-?\d+(\.\d+)?$/.test(s.trim()) ? Number(s.trim()) : s.trim()); + if (LISTS.includes(op)) + return text + .split(",") + .map((x) => x.trim()) + .filter(Boolean) + .map((x) => (type === "number" || op === "between" ? num(x) : x)); + if (op === "gt" || op === "lt" || type === "number") return num(text); + if (type === "bool" && (text === "true" || text === "false")) return text === "true"; + return text; +} + +/** A kind's fields a trigger's "only when" can test, from its schema: {path, label, type}, nested one level. */ +export function kindFields(schema: unknown): { path: string; label: string; type: FieldType }[] { + const out: { path: string; label: string; type: FieldType }[] = []; + const walk = (props: Record | undefined, prefix: string, above: string) => { + for (const [k, p] of Object.entries(props ?? {})) { + const path = prefix ? `${prefix}.${k}` : k; + const label = above ? `${above} · ${p.title ?? k}` : (p.title ?? k); + const type = typeOf(p); + if (type === "object") { + if (!prefix) walk(p.properties, path, p.title ?? k); + } else if (!["id", "kind", "space", "tag"].includes(path)) out.push({ path, label, type }); + } + }; + walk((schema as { properties?: Record })?.properties, "", ""); + return out; +} +type Prop = { type?: string | string[]; title?: string; format?: string; properties?: Record }; +function typeOf(p: Prop): FieldType | "object" { + const t = Array.isArray(p.type) ? p.type.find((x) => x !== "null") : p.type; + if (t === "object") return "object"; + if (t === "array") return "list"; + if (t === "integer" || t === "number") return "number"; + if (t === "boolean") return "bool"; + if (t === "string") return p.format === "date-time" || p.format === "date" ? "time" : "text"; + return "any"; +} + +// ---------- triggers and the join ---------- +/** Trigger cards that aren't a kind of activity, as "Add a trigger" offers them. */ +export const CLOCK: { on: string; label: string; hint: string }[] = [ + { on: "schedule", label: "Every day at…", hint: "On a schedule, like every weekday at 07:00" }, + { on: "at", label: "At a time", hint: "Once, at a date and time" }, + { on: "webhook", label: "A webhook is called", hint: "Its own address, given when it is saved" }, + { on: "manual", label: "When I run it", hint: "Only when you press Run now" }, +]; + +/** A name for a new trigger, from its kind (email.received → email) or what it is, not taken yet. */ +export function aliasFor(what: string, taken: string[]): string { + const base = + (what.includes(".") ? what.split(".")[0] : ({ schedule: "clock", at: "time", webhook: "hook" }[what] ?? what)) + .toLowerCase() + .replace(/[^a-z0-9_]/g, "_") + .replace(/^[^a-z]+/, "") || "trigger"; + let name = base; + for (let k = 2; taken.includes(name); k++) name = `${base}${k}`; + return name; +} + +/** A new trigger: on a kind of activity, or a clock, webhook or manual one. */ +export function newTrigger(what: string, taken: string[], timezone = "UTC"): Trigger { + const as = aliasFor(what, taken); + if (what === "schedule") return { as, on: "schedule", cron: "0 7 * * *", timezone }; + if (what === "at") return { as, on: "at", at: "", timezone }; + if (what === "webhook" || what === "manual") return { as, on: what }; + return { as, on: "event", kinds: [what] }; +} + +/** The join line in words, as the builder's choice reads it. */ +export function joinText(j: Join): string { + const within = j.within ?? "10m"; + const same = j.key ? ` for the same ${j.key}` : ""; + switch (j.mode) { + case "all": + return `All of these within ${within}${same}`; + case "count": + return `${j.at_least ?? 3} times ${j.of ?? "the first"} within ${within}${same}`; + case "absent": + return `${j.after ?? "the first"} and then no ${j.missing ?? "the second"} within ${within}${same}`; + case "batch": + return `Collect for ${within}, then once`; + default: + return "Any of these"; + } +} + +/** A join of this mode with the triggers' names filled in. */ +export function joinFor(mode: Join["mode"], triggers: Trigger[], was?: Join): Join { + const [a, b] = triggers.map((t) => t.as); + const within = was?.within ?? (mode === "absent" ? "2d" : mode === "batch" ? "1h" : mode === "count" ? "5m" : "10m"); + if (mode === "any") return { mode }; + if (mode === "all") return { mode, within, ...(was?.key ? { key: was.key } : {}) }; + if (mode === "count") return { mode, of: was?.of ?? a, at_least: was?.at_least ?? 3, within }; + if (mode === "absent") return { mode, after: was?.after ?? a, missing: was?.missing ?? b ?? a, within }; + return { mode, within }; +} + +// ---------- the Then: steps and the graph ---------- +const params = (c: Record) => (c.params as Record | undefined) ?? {}; + +/** An action that passes nothing on: it reaches outside Lens or other people (or may: depends), or it waits. Such a + * step hangs off the one before it, as the leaf rule has it. */ +export function passesNothing(s: Step, actions?: ActionDef[]): boolean { + if (s.delay || s.when) return true; + const e = actions?.find((a) => a.name === s.action)?.effect; + return e === undefined || e === "out" || e === "depends"; +} + +/** Steps as an event workflow: What happened, then each action after the last one that passes something on. */ +export function graphOf(steps: Step[], actions?: ActionDef[]): WfGraph { + const nodes: WfGraph["nodes"] = [{ id: "in", type: "input", config: {}, x: 0, y: 120 }]; + const edges: WfEdge[] = []; + let from = "in"; + steps.forEach((s, k) => { + const config: Record = { action: s.action, params: s.params }; + if (s.delay) config.delay = s.delay; + if (s.when) config.when = s.when; + nodes.push({ id: s.id, type: "action", config, x: 280 * (k + 1), y: 120 }); + edges.push({ source: from, target: s.id }); + if (!passesNothing(s, actions)) from = s.id; + }); + return { nodes, edges }; +} + +/** A graph as steps, or null when it branches (a decide, condition or loop node, or actions side by side that a list + * wouldn't draw the same way). */ +export function stepsOf(g: WfGraph | null | undefined, actions?: ActionDef[]): Step[] | null { + if (!g) return []; + const input = g.nodes.filter((n) => n.type === "input"); + if (input.length !== 1 || g.nodes.some((n) => n.type !== "input" && n.type !== "action")) return null; + if (g.edges.some((e) => (e.port && e.port !== "out") || (e.input && e.input !== "in") || e.branch)) return null; + const by = new Map(g.nodes.map((n) => [n.id, n])); + const kids = (id: string) => + g.edges + .filter((e) => e.source === id) + .map((e) => by.get(e.target)) + .filter((n) => n != null); + const out: Step[] = []; + let cur = input[0].id; + for (let guard = 0; guard <= g.nodes.length; guard++) { + const next = kids(cur); + const ends = next + .filter((n) => !kids(n.id).length) + .sort((a, b) => (a.x ?? 0) - (b.x ?? 0) || a.id.localeCompare(b.id)); + const on = next.filter((n) => kids(n.id).length); + if (on.length > 1) return null; + for (const n of ends) out.push(stepFrom(n)); + if (!on.length) break; + out.push(stepFrom(on[0])); + cur = on[0].id; + } + if (out.length !== g.nodes.length - 1) return null; + // a list draws it this way only if it is the graph itself + const again = graphOf(out, actions) + .edges.map((e) => `${e.source}>${e.target}`) + .sort(); + const was = g.edges.map((e) => `${e.source}>${e.target}`).sort(); + return again.join() === was.join() ? out : null; +} + +function stepFrom(n: WfGraph["nodes"][number]): Step { + const c = n.config; + return { + id: n.id, + action: String(c.action ?? ""), + params: params(c), + ...(c.delay != null ? { delay: String(c.delay) } : {}), + ...(c.when != null ? { when: String(c.when) } : {}), + }; +} + +/** An id for a new step, not taken yet. */ +export function stepId(steps: Step[], action: string): string { + const base = action.split("_")[0] || "a"; + const taken = new Set(steps.map((s) => s.id)); + let id = base; + for (let k = 2; taken.has(id); k++) id = `${base}${k}`; + return id; +} + +// ---------- the API's shape ---------- +type ApiAutomation = { + name: string; + triggers: Record[]; + join?: Record | null; + if?: unknown; + graph?: Record | null; + spaces?: number[] | null; +}; + +/** An automation from the API as a draft for the builder. */ +export function fromApi(a: ApiAutomation, actions?: ActionDef[]): Draft { + const graph = (a.graph as WfGraph | null | undefined) ?? { nodes: [], edges: [] }; + return { + name: a.name, + triggers: (a.triggers ?? []) as Trigger[], + join: ((a.join as Join | null | undefined) ?? { mode: "any" }) as Join, + if: a.if ?? null, + steps: stepsOf(graph, actions), + graph, + spaces: a.spaces, + }; +} + +/** A draft as POST /automations (and PATCH) take it. */ +export function toApi(d: Draft, actions?: ActionDef[]) { + const triggers = d.triggers.map((t) => { + const out: Record = { ...t }; + if (out.where === undefined || out.where === null) delete out.where; + return out; + }); + return { + name: d.name.trim() || suggestedName(d), + triggers, + join: triggers.length > 1 ? d.join : { mode: "any" }, + if: d.if ?? null, + graph: d.steps ? graphOf(d.steps, actions) : d.graph, + }; +} + +/** A name for an automation nobody named: its first action and trigger. */ +export function suggestedName( + d: Draft, + labels?: { kind?: (k: string) => string; action?: (a: string) => string }, +): string { + const t = d.triggers[0]; + const when = !t + ? "" + : t.on === "event" + ? (labels?.kind?.(t.kinds?.[0] ?? "") ?? t.kinds?.[0] ?? "") + : (CLOCK.find((c) => c.on === t.on)?.label ?? t.on); + const first = d.steps?.[0]; + const what = first ? (labels?.action?.(first.action) ?? first.action) : ""; + return [what, when && `on ${when.toLowerCase()}`].filter(Boolean).join(" ") || "New automation"; +} + +/** What a step's badge says: whether it runs on its own or asks first, with the person's pick for it. */ +export function stepBadge(s: Step, actions: ActionDef[] | undefined, policy?: Record) { + if (policy?.[s.id] === "auto") return { label: "Runs on its own", tone: "green" as const }; + return effectBadge(actions?.find((a) => a.name === s.action)?.effect); +} + +/** Whether a step's action can be let run on its own: one that asks first because it reaches outside Lens or other + * people (a change inside Lens asks unless it is to what set it off, whatever the pick). */ +export const canRunOnItsOwn = (s: Step, actions?: ActionDef[]) => + ["out", "depends"].includes(actions?.find((a) => a.name === s.action)?.effect ?? ""); + +/** What's missing before saving, by where it is ("" for the automation): the API names the rest. */ +export function draftProblems(d: Draft, actions?: ActionDef[]): Record { + const out: Record = {}; + if (!d.triggers.length) out.triggers = "Add a trigger: what sets it off."; + d.triggers.forEach((t, k) => { + if (t.on === "event" && !t.kinds?.length) out[`trigger.${k}`] = "Choose what happens."; + if (t.on === "schedule" && !String(t.cron ?? "").trim()) out[`trigger.${k}`] = "Give the schedule."; + if (t.on === "at" && !String(t.at ?? "").trim()) out[`trigger.${k}`] = "Give the date and time."; + }); + if (d.steps) { + if (!d.steps.length) out.steps = "Add an action: what it does."; + d.steps.forEach((s) => { + const a = actions?.find((x) => x.name === s.action); + const missing = a?.required?.find((r) => s.params[r] == null || s.params[r] === ""); + if (!a) out[`step.${s.id}`] = "Choose an action."; + else if (missing) { + const title = ((a.params.properties ?? {}) as Record)[missing]?.title ?? missing; + out[`step.${s.id}`] = `Fill in ${title}.`; + } + }); + } + return out; +} + +/** A run's status, as its badge says it. */ +export function runStatus(s: string | null | undefined): { label: string; tone: Tone } { + const known: Record = { + done: { label: "Done", tone: "green" }, + partly: { label: "Partly done", tone: "gate" }, + failed: { label: "Failed", tone: "red" }, + running: { label: "Running", tone: "intent" }, + waiting: { label: "Waiting", tone: "gate" }, + held: { label: "Held: over a budget", tone: "gate" }, + released: { label: "Let through", tone: "neutral" }, + skipped: { label: "Skipped", tone: "neutral" }, + }; + return known[s ?? ""] ?? { label: s ?? "—", tone: "neutral" }; +} diff --git a/nextjs-frontend/components/automations/parts.tsx b/nextjs-frontend/components/automations/parts.tsx new file mode 100644 index 00000000..07a1ae70 --- /dev/null +++ b/nextjs-frontend/components/automations/parts.tsx @@ -0,0 +1,526 @@ +"use client"; + +/** The builder's pieces: "only when" and If rows, a trigger card, the join line and an action card. */ +import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react"; +import { useRef, type KeyboardEvent } from "react"; + +import type { ActivityKind } from "@/app/openapi-client/types.gen"; +import { + CLOCK, + NO_VALUE, + OP_LABEL, + canRunOnItsOwn, + joinFor, + joinText, + kindFields, + opsFor, + rowsOf, + stepBadge, + treeOf, + valueFrom, + valueText, + type FieldType, + type Join, + type Rows, + type Step, + type Trigger, +} from "@/components/automations/model"; +import { SchemaForm, type Variable } from "@/components/forms/schema-form"; +import type { JsonSchema } from "@/components/forms/schema-model"; +import { PRESETS, presetOf } from "@/components/routines/routine-model"; +import { SchedulePreview } from "@/components/routines/schedule-fields"; +import { Badge } from "@/components/ui/badge"; +import { Button, IconButton } from "@/components/ui/button"; +import { Field, Input, Select, Switch } from "@/components/ui/field"; +import { Panel } from "@/components/ui/panel"; +import { Segmented } from "@/components/ui/tabs"; +import type { ActionDef } from "@/components/workflows/workflow-model"; + +export type FieldInfo = { path: string; label: string; type: FieldType }; + +/** Rows of tests, all or any of them: a field, a test that suits it and a value. Enter in the last value adds a row. */ +export function RowsEditor({ + value, + onChange, + fields, + idPrefix, + empty, + addLabel = "Add a condition", +}: { + value: unknown; + onChange: (tree: unknown) => void; + fields: FieldInfo[]; + idPrefix: string; + empty?: string; + addLabel?: string; +}) { + const box = useRef(null); + const rows = rowsOf(value); + if (!rows) + return ( +
+ These conditions nest, so they are edited through the API or by an agent. + +
+ ); + const set = (r: Rows) => onChange(treeOf(r) ?? (r.rows.length ? { [r.mode]: r.rows } : undefined)); + const add = () => { + const first = fields[0]; + set({ ...rows, rows: [...rows.rows, { path: first?.path ?? "", op: opsFor(first?.type ?? "any")[0] }] }); + // the new row's field takes the focus + requestAnimationFrame(() => box.current?.querySelector(`[data-row="${rows.rows.length}"]`)?.focus()); + }; + const typeOf = (path: string) => fields.find((f) => f.path === path)?.type ?? "any"; + const listId = `${idPrefix}-fields`; + return ( +
+ {rows.rows.length > 1 && ( + set({ ...rows, mode: v as Rows["mode"] })} + items={[ + { value: "all", label: "All of these" }, + { value: "any", label: "Any of these" }, + ]} + /> + )} + + {fields.map((f) => ( + + ))} + + {rows.rows.map((r, k) => { + const type = typeOf(r.path); + const ops = opsFor(type); + const setRow = (patch: Partial) => + set({ ...rows, rows: rows.rows.map((x, i) => (i === k ? { ...x, ...patch } : x)) }); + const onKey = (e: KeyboardEvent) => { + if (e.key === "Enter" && !e.metaKey && !e.ctrlKey && k === rows.rows.length - 1) { + e.preventDefault(); + add(); + } + }; + return ( +
+ setRow({ path: e.target.value })} + /> + setRow({ value: valueFrom(r.op, e.target.value, type) })} + /> + )} + set({ ...rows, rows: rows.rows.filter((_, i) => i !== k) })} + > + + +
+ ); + })} + {!rows.rows.length && empty &&

{empty}

} + +
+ ); +} + +/** One trigger: what happens (a kind, a schedule, a time, its webhook, by hand) and its "only when" rows. */ +export function TriggerCard({ + trigger: t, + index, + kinds, + onChange, + onRemove, + problem, +}: { + trigger: Trigger; + index: number; + kinds: ActivityKind[]; + onChange: (t: Trigger) => void; + onRemove: () => void; + problem?: string; +}) { + const kind = kinds.find((k) => k.name === t.kinds?.[0]); + const title = + t.on === "event" + ? (kind?.label ?? t.kinds?.[0] ?? "Something happens") + : t.on === "relative" + ? "A time in an activity" + : (CLOCK.find((c) => c.on === t.on)?.label ?? t.on); + const id = `trigger-${index}`; + return ( + as {t.as}} + actions={ + + + + } + > +
+ {problem && ( +

+ {problem} +

+ )} + {(t.on === "event" || t.on === "relative") && ( + <> + + {({ id: fid }) => ( + onChange({ ...t, at: e.target.value })} + /> + )} + + +
+ )} + {t.on === "webhook" && ( +

+ It gets its own address and signing secret when the automation is saved; they show once. +

+ )} + {t.on === "manual" &&

It runs when you press Run now.

} + +
+ ); +} + +function TimezoneField({ trigger: t, onChange, id }: { trigger: Trigger; onChange: (t: Trigger) => void; id: string }) { + return ( + + {({ id: fid }) => ( + onChange({ ...t, timezone: e.target.value })} + /> + )} + + ); +} + +/** A schedule: the routine editor's presets, a cron line, the time zone and the next times. */ +function ScheduleFields({ + trigger: t, + onChange, + id, +}: { + trigger: Trigger; + onChange: (t: Trigger) => void; + id: string; +}) { + const preset = presetOf(t.cron); + return ( +
+
+ + {({ id: fid }) => ( + onChange({ ...t, cron: e.target.value })} + /> + )} + + +
+ +
+ ); +} + +const JOINS: { value: Join["mode"]; label: string }[] = [ + { value: "any", label: "Any of these" }, + { value: "all", label: "All of these within a time" }, + { value: "count", label: "Several times within a time" }, + { value: "absent", label: "One, and then not the other" }, + { value: "batch", label: "Collect for a while, then once" }, +]; + +/** With two or more triggers: how they make one run, as a line that reads like the sentence it means. */ +export function JoinLine({ + join, + triggers, + onChange, +}: { + join: Join; + triggers: Trigger[]; + onChange: (j: Join) => void; +}) { + const names = triggers.map((t) => ({ value: t.as, label: t.as })); + const small = (label: string, el: React.ReactNode) => ( + + ); + return ( +
+
+ onChange({ ...join, at_least: Number(e.target.value) || 1 })} + /> + times + onChange({ ...join, after: e.target.value })} + options={names} + /> + and then no + onChange({ ...join, within: e.target.value })} + />, + )} + {join.mode !== "any" && + join.mode !== "batch" && + small( + "for the same", + onChange({ ...join, key: e.target.value || undefined })} + />, + )} +
+

{joinText(join)}

+
+ ); +} + +/** One action of the Then: which action, its settings from its params, a wait, and whether it asks first. */ +export function StepCard({ + step: s, + index, + count, + actions, + variables, + policy, + saved, + onChange, + onRemove, + onMove, + onPolicy, + problem, +}: { + step: Step; + index: number; + count: number; + actions: ActionDef[]; + variables?: Variable[]; + policy: Record; + /** Saved: only then can a step be let run on its own. */ + saved: boolean; + onChange: (s: Step) => void; + onRemove: () => void; + onMove: (by: number) => void; + onPolicy: (auto: boolean) => void; + problem?: string; +}) { + const a = actions.find((x) => x.name === s.action); + const badge = stepBadge(s, actions, policy); + const auto = policy[s.id] === "auto"; + return ( + + {badge.label} + onMove(-1)}> + + + onMove(1)}> + + + + + + + } + > +
+ {problem && ( +

+ {problem} +

+ )} + {a && ( + onChange({ ...s, params })} + variables={variables} + /> + )} + + {({ id, describedBy }) => ( + onChange({ ...s, delay: e.target.value.trim() || undefined })} + /> + )} + + {canRunOnItsOwn(s, actions) && ( +
+ +

+ {!saved + ? "Save it first; then you can let this action run without asking you." + : auto + ? "It runs without asking you first. Switch it off to be asked again." + : "It asks you first each time, on the Approvals page or with a yes in your chat app."} +

+
+ )} +
+
+ ); +} diff --git a/nextjs-frontend/components/automations/test-panel.tsx b/nextjs-frontend/components/automations/test-panel.tsx new file mode 100644 index 00000000..d93017f0 --- /dev/null +++ b/nextjs-frontend/components/automations/test-panel.tsx @@ -0,0 +1,132 @@ +"use client"; + +/** Try the automation as it is in the builder, saved or not, on a recent activity its triggers would take or on a + * kind's sample: whether its If passed, what each node did and what each action would do. Nothing is kept or sent. */ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { FlaskConical, X } from "lucide-react"; +import { useState } from "react"; + +import { Activities, Automations } from "@/app/openapi-client"; +import type { ActivityKind } from "@/app/openapi-client/types.gen"; +import { runStatus, toApi, type Draft } from "@/components/automations/model"; +import { Badge } from "@/components/ui/badge"; +import { Button, IconButton } from "@/components/ui/button"; +import { Select } from "@/components/ui/field"; +import { wouldDo, type ActionDef } from "@/components/workflows/workflow-model"; +import { data, useApiClient } from "@/lib/api/browser"; +import { relative } from "@/lib/format"; + +export function TestPanel({ + draft, + actions, + kinds, + onClose, +}: { + draft: Draft; + actions?: ActionDef[]; + kinds: ActivityKind[]; + onClose: () => void; +}) { + const client = useApiClient(); + const listening = [...new Set(draft.triggers.flatMap((t) => (t.on === "event" ? (t.kinds ?? []) : [])))]; + const recent = useQuery({ + queryKey: ["activities", "for-test", listening], + queryFn: () => data(Activities.listActivities({ client, query: { kinds: listening, limit: 8 } })), + enabled: listening.length > 0, + }); + const items = recent.data?.items ?? []; + const samples = listening.length + ? listening + : draft.triggers.some((t) => t.on === "schedule" || t.on === "at") + ? ["clock.tick"] + : ["webhook.received"]; + const [pick, setPick] = useState(""); + const chosen = pick || (items[0] ? `a:${items[0].id}` : `k:${samples[0]}`); + const tryIt = useMutation({ + mutationFn: () => + data( + Automations.testDraft({ + client, + body: { + draft: { ...toApi(draft, actions), enabled: false } as never, + ...(chosen.startsWith("a:") ? { activity: chosen.slice(2) } : { kind: chosen.slice(2) }), + }, + }), + ), + }); + const r = tryIt.data; + const label = (k: string) => kinds.find((x) => x.name === k)?.label ?? k; + return ( +