diff --git a/README.md b/README.md index 4dff8b72..59998748 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,8 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p Lens, with a yes in the chat it told you in; agents can decline an approval but never give one. Each automation has limits and budgets, and agents make, try and run them over MCP and in the assistant, or draft one from a sentence. An automation's workflow is drawn and tried on the workflow canvas, with its actions in the palette, and the studio - lists your automations and builds one in When, If and Then, tested on a recent activity before you save it. + lists your automations, builds one in When, If and Then (tested on a recent activity before you save it), and shows + its runs, what's coming up, its variables and its costs. ([Processing](docs/processing.md#workflows-and-the-canvas), [converting assets](docs/processing.md#converting-assets), [notifications](docs/notifications.md), [automations](docs/automations.md), [approvals](docs/automations.md#approvals), [schedules](docs/schedules.md), @@ -275,8 +276,6 @@ These are open pull requests, not yet part of Lens: Next, and not in a pull request yet; each links to where it is tracked: -- **The automations studio:** each automation's runs, what's coming up, its variables and its costs, in tabs - ([automations](docs/automations.md)). - **Timeline:** what each item caused, and Approve and Decline on waiting approvals ([timeline](docs/timeline.md)). - **Notes:** nesting a note under its project or area without a click, pages in the graph, and wiki addresses for topics, recordings and the other things that have pages ([notes](docs/notes.md)). diff --git a/docs/automations.md b/docs/automations.md index 04285902..a74d39e4 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -52,7 +52,7 @@ merged is called built. | Automations for agents: the MCP tools and the assistant's, switching on and running now by approval | built | | Describing an automation in words: a draft from a sentence (`POST /api/v1/automations/draft`) | built | | The studio: the list at `/automations` and the When, If and Then builder, with a test panel ([The studio](#the-studio)) | built | -| The studio's tabs for an automation's runs, what's coming up, its variables and its costs | planned | +| An automation's page: its runs, what's coming up, its variables and its costs, in tabs ([An automation's page](#an-automations-page)) | built | ## The studio @@ -86,6 +86,19 @@ row or action they are about. An automation whose workflow branches (a Decide node, or an action after a condition) can't be read as a list: the builder says so and opens it in the [canvas](#on-the-canvas), where When and If still edit. +### An automation's page + +An automation's page has its switch, Run now and five tabs (`?tab=` in the address opens one): + +- **Edit**: the builder. +- **Runs**: newest first, 20 at a time with Older runs for the next page. Each reads how it went, what started it, + what its actions did and what it cost; opening one shows each action's outcome and the run's log. A run held over a + budget offers Run it once or Skip. Run now opens this tab. +- **Coming up**: its next schedule times, `at` times and actions that wait, soonest first. +- **Variables**: what it keeps between runs ([Saved variables](#saved-variables)). Edit a value as text or JSON and + press Enter; Clear is undone from its toast; a new name and value are added with Enter. +- **Costs**: its budget and its activity: the calls it made and what they cost. + ## Contract Every part of the studio builds on the shapes below. A change to one of them comes in a small pull request of its @@ -1305,8 +1318,7 @@ held run until you pick. message the person's template wrote, so they stay when the run read outside text. - Variables and templates: secrets as variables (sealed, never rendered into prompts); typed variable declarations with defaults per automation; a time zone of each person's own, rather than the triggers'; wrapping outside text - the same way in `tool_nodes.ask_model` (pipeline workflows) and extensions' prompt tools; variables in the - Settings page of an automation (the studio, M11); an activity when a person changes a variable; marking a variable + the same way in `tool_nodes.ask_model` (pipeline workflows) and extensions' prompt tools; an activity when a person changes a variable; marking a variable from outside text only when the value itself came from it, not whenever the run read some; removing an automation's variables when it is deleted (M6); a preview that runs the nodes before the template's (dry) rather than standing in for their outputs; the picker listing a saved prompt template's output schema for the node that diff --git a/docs/requirements.md b/docs/requirements.md index 56a71735..56882040 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -225,6 +225,7 @@ request, to another check that proves the same thing; loosening a requirement or | Agents make, try and run automations over MCP and in the assistant, or draft one from a sentence | [test_automation_tools.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_automation_tools.py) `test_agents_save_try_and_run_automations_over_mcp`, `test_the_assistant_saves_at_once_and_asks_to_switch_on_or_run`; [test_automations.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_automations.py) `test_an_automation_is_drafted_from_a_sentence` | | An automation's workflow is drawn and tried on the canvas: its actions in the palette, their settings drawn from each action's params, Decide's ports and the leaf rule | [workflow-canvas.test.ts](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/workflow-canvas.test.ts) `give a decide node a port per option, then unsure`, `keep the leaf rule: nothing after an action that reaches outside Lens or waits`, `say what the backend would reject in their settings`; [automation-nodes-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/automation-nodes-ui.test.tsx) `sets an action up from the catalog, its params drawn from its schema`; [schema-form.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/schema-form.test.tsx) `opens the variable picker on {{ and puts the pick in with Enter` | | In the web app, automations are listed with what sets each off in words, and built in When, If and Then with a test on a recent activity, problems next to their fields | [automations-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/automations-ui.test.tsx) `the list reads each automation, and Delete is undone from its toast`, `the builder adds a trigger with a condition and an action, then saves it switched off`, `the test panel runs the draft on a recent activity and says what it would do`, `API problems go next to what they are about`; [test_automations.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_automations.py) `test_lists_read_the_triggers_in_words_and_say_when_it_runs_next` | +| An automation's page shows its runs a page at a time with each one's log, what's coming up, its variables to edit and its costs | [automation-detail.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/automation-detail.test.tsx) `Runs pages back with before, and a run opens to what it did and its log`, `a run held over a budget can run once or be skipped`, `Coming up lists its times, and says why when there are none`, `Variables set from the keyboard, and Clear is undone from its toast` | ## See what it costs diff --git a/nextjs-frontend/__tests__/automation-detail.test.tsx b/nextjs-frontend/__tests__/automation-detail.test.tsx new file mode 100644 index 00000000..6034ddde --- /dev/null +++ b/nextjs-frontend/__tests__/automation-detail.test.tsx @@ -0,0 +1,169 @@ +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 { Automations } from "@/app/openapi-client"; +import { AutomationPage } from "@/components/automations/automation-page"; +import { RunsTab, UpcomingTab, VariablesTab, runCounts, varFrom, varText } from "@/components/automations/detail-tabs"; +import { ToastProvider } from "@/components/ui/toast"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Automations: { + listActions: jest.fn(), + listRuns: jest.fn(), + getRun: jest.fn(), + decideHeldRun: jest.fn(), + upcoming: jest.fn(), + getAutomationVars: jest.fn(), + putAutomationVars: jest.fn(), + getAutomation: jest.fn(), + runAutomation: jest.fn(), + enableAutomation: jest.fn(), + }, +})); +jest.mock("next/navigation", () => ({ useRouter: () => ({ push: jest.fn() }) })); +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; + +function wrap(ui: ReactNode) { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + + {ui} + + , + ); +} + +const run = (id: number, more: Record = {}) => ({ + id, + automation: 7, + status: "done", + trigger: "email", + started_at: "2026-10-18T06:00:00Z", + counts: { done: 1 }, + ...more, +}); + +beforeEach(() => { + m(Automations.listActions).mockReturnValue( + ok([{ name: "notify", label: "Send a message", group: "Messages", params: {}, effect: "depends" }]), + ); +}); + +test("a run reads what it did in a few words, and a variable edits as one line of JSON", () => { + expect(runCounts({ counts: { done: 3, waiting: 1, failed: 0 } })).toBe("3 done, 1 waiting"); + expect(runCounts({ counts: {}, why: "over its budget" })).toBe("over its budget"); + expect(runCounts({ counts: { done: 1 }, error: "boom" })).toBe("boom"); + expect(varText({ seen: 2 })).toBe('{"seen":2}'); + expect(varText("plain")).toBe("plain"); + expect(varFrom("[1, 2]")).toEqual([1, 2]); + expect(varFrom("not json")).toBe("not json"); +}); + +test("Runs pages back with before, and a run opens to what it did and its log", async () => { + m(Automations.listRuns) + .mockReturnValueOnce( + ok({ runs: [run(9), run(8, { status: "failed", error: "The address didn’t answer" })], next: 8 }), + ) + .mockReturnValueOnce(ok({ runs: [run(5)], next: null })); + m(Automations.getRun).mockReturnValue( + ok({ + ...run(9), + log: ["notify: sent"], + intents: [{ action: "notify", status: "done" }], + trace: {}, + }), + ); + wrap(); + const list = await screen.findByRole("list", { name: "Runs" }); + expect(within(list).getByText("The address didn’t answer")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Older runs" })); + await waitFor(() => expect(within(list).getAllByRole("listitem")).toHaveLength(3)); + expect(m(Automations.listRuns).mock.calls[1][0].query).toEqual({ before: 8, limit: 20 }); + expect(screen.queryByRole("button", { name: "Older runs" })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Run 9" })); + expect(await screen.findByText("notify: sent")).toBeInTheDocument(); + expect( + within(screen.getByRole("list", { name: "What it did" })).getByText("Send a message: done"), + ).toBeInTheDocument(); +}); + +test("a run held over a budget can run once or be skipped", async () => { + m(Automations.listRuns).mockReturnValue(ok({ runs: [run(4, { status: "held", counts: {} })], next: null })); + m(Automations.decideHeldRun).mockReturnValue(ok({ ok: true })); + wrap(); + fireEvent.click(await screen.findByRole("button", { name: "Run it once" })); + await waitFor(() => + expect(m(Automations.decideHeldRun).mock.calls[0][0]).toMatchObject({ path: { run: 4 }, body: { run: true } }), + ); +}); + +test("Coming up lists its times, and says why when there are none", async () => { + m(Automations.upcoming).mockReturnValueOnce( + ok({ + times: [ + { key: "sched-7-daily", at: "2026-10-19T07:00:00Z", description: "every day at 07:00", trigger: "daily" }, + ], + }), + ); + const { unmount } = wrap(); + expect(await screen.findByText("every day at 07:00")).toBeInTheDocument(); + unmount(); + m(Automations.upcoming).mockReturnValueOnce(ok({ times: [] })); + wrap(); + expect(await screen.findByText(/It’s off/)).toBeInTheDocument(); +}); + +test("Variables set from the keyboard, and Clear is undone from its toast", async () => { + const vars = { vars: [{ name: "seen", value: 2, updated_at: "2026-10-18T06:00:00Z" }] }; + m(Automations.getAutomationVars).mockReturnValue(ok(vars)); + m(Automations.putAutomationVars).mockReturnValue(ok(vars)); + wrap(); + const box = await screen.findByLabelText("Value of seen"); + fireEvent.change(box, { target: { value: "3" } }); + fireEvent.keyDown(box, { key: "Enter" }); + await waitFor(() => + expect(m(Automations.putAutomationVars).mock.calls[0][0]).toMatchObject({ + path: { aid: 7 }, + body: { vars: { seen: 3 } }, + }), + ); + fireEvent.click(screen.getByRole("button", { name: "Clear" })); + await waitFor(() => expect(m(Automations.putAutomationVars).mock.calls[1][0].body).toEqual({ vars: { seen: null } })); + fireEvent.click(await screen.findByRole("button", { name: "Undo" })); + await waitFor(() => expect(m(Automations.putAutomationVars).mock.calls[2][0].body).toEqual({ vars: { seen: 2 } })); + fireEvent.change(screen.getByLabelText("New variable name"), { target: { value: "trips" } }); + fireEvent.change(screen.getByLabelText("New variable value"), { target: { value: '["Rome"]' } }); + fireEvent.keyDown(screen.getByLabelText("New variable value"), { key: "Enter" }); + await waitFor(() => + expect(m(Automations.putAutomationVars).mock.calls[3][0].body).toEqual({ vars: { trips: ["Rome"] } }), + ); +}); + +test("the page opens the tab its address names, and Run now shows the runs", async () => { + m(Automations.getAutomation).mockReturnValue( + ok({ + id: 7, + name: "School emails", + enabled: true, + triggers: [], + join: { mode: "any" }, + graph: { nodes: [], edges: [] }, + }), + ); + m(Automations.upcoming).mockReturnValue(ok({ times: [] })); + m(Automations.listRuns).mockReturnValue(ok({ runs: [run(9)], next: null })); + m(Automations.runAutomation).mockReturnValue(ok({ run: 10, status: "done" })); + wrap(); + expect(await screen.findByRole("tab", { name: "Coming up" })).toHaveAttribute("aria-selected", "true"); + expect(await screen.findByText("Nothing coming up")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Run now" })); + expect(await screen.findByRole("list", { name: "Runs" })).toBeInTheDocument(); + expect(screen.getByRole("tab", { name: "Runs" })).toHaveAttribute("aria-selected", "true"); +}); diff --git a/nextjs-frontend/app/(app)/automations/[id]/page.tsx b/nextjs-frontend/app/(app)/automations/[id]/page.tsx index 362810a6..eb3c0d47 100644 --- a/nextjs-frontend/app/(app)/automations/[id]/page.tsx +++ b/nextjs-frontend/app/(app)/automations/[id]/page.tsx @@ -5,10 +5,17 @@ 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 }> }) { +/** One automation: the builder, and what it has done (`?tab=runs|upcoming|variables|costs` opens a tab). */ +export default async function Page({ + params, + searchParams, +}: { + params: Promise<{ id: string }>; + searchParams: Promise<{ tab?: string }>; +}) { const { id } = await params; + const { tab } = await searchParams; const n = Number(id); if (!Number.isInteger(n) || n < 1) notFound(); - return ; + return ; } diff --git a/nextjs-frontend/components/automations/automation-page.tsx b/nextjs-frontend/components/automations/automation-page.tsx index 7df246a5..8bf8645d 100644 --- a/nextjs-frontend/components/automations/automation-page.tsx +++ b/nextjs-frontend/components/automations/automation-page.tsx @@ -1,6 +1,7 @@ "use client"; -/** One automation: its name, on or off, Run now, and the builder; a new one starts from the builder alone. */ +/** One automation: its name, on or off, Run now, and tabs for the builder, its runs, what's coming up, its variables + * and its costs; 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"; @@ -9,10 +10,12 @@ import { useEffect, useState } from "react"; import { Automations } from "@/app/openapi-client"; import { AutomationBuilder, type Hook } from "@/components/automations/automation-builder"; +import { CostsTab, RunsTab, UpcomingTab, VariablesTab } from "@/components/automations/detail-tabs"; 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 { Tabs } from "@/components/ui/tabs"; import { useToast } from "@/components/ui/toast"; import { ApiError, data, useApiClient } from "@/lib/api/browser"; @@ -51,7 +54,11 @@ export function NewAutomationPage() { ); } -export function AutomationPage({ id }: { id: number }) { +export const TABS = ["edit", "runs", "upcoming", "variables", "costs"] as const; +export type Tab = (typeof TABS)[number]; + +export function AutomationPage({ id, tab: first }: { id: number; tab?: string }) { + const [tab, setTab] = useState(TABS.includes(first as Tab) ? (first as Tab) : "edit"); const client = useApiClient(); const qc = useQueryClient(); const toast = useToast(); @@ -84,6 +91,7 @@ export function AutomationPage({ id }: { id: number }) { mutationFn: () => data(Automations.runAutomation({ client, path: { aid: id }, body: {} })), onSuccess: (r) => { void qc.invalidateQueries({ queryKey: ["automation-runs", id] }); + setTab("runs"); toast( r.run ? { tone: "green", title: "It ran", body: runStatus(r.status).label } @@ -143,11 +151,33 @@ export function AutomationPage({ id }: { id: number }) { ))} )} - got.length && setHooks(got)} + setTab(v as Tab)} + items={[ + { value: "edit", label: "Edit" }, + { value: "runs", label: "Runs" }, + { value: "upcoming", label: "Coming up" }, + { value: "variables", label: "Variables" }, + { value: "costs", label: "Costs" }, + ]} /> + {tab === "runs" ? ( + + ) : tab === "upcoming" ? ( + + ) : tab === "variables" ? ( + + ) : tab === "costs" ? ( + + ) : ( + got.length && setHooks(got)} + /> + )} ); } diff --git a/nextjs-frontend/components/automations/detail-tabs.tsx b/nextjs-frontend/components/automations/detail-tabs.tsx new file mode 100644 index 00000000..44c796e2 --- /dev/null +++ b/nextjs-frontend/components/automations/detail-tabs.tsx @@ -0,0 +1,338 @@ +"use client"; + +/** What an automation has done and will do: its runs (newest first, a page at a time, each opening to its log and what + * it did), the times it runs next, the variables it keeps between runs, and what it costs. */ +import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { CalendarClock, ChevronDown, ChevronRight, History, Variable } from "lucide-react"; +import { useState } from "react"; + +import { Automations } from "@/app/openapi-client"; +import type { AutomationRun, AutomationVar } from "@/app/openapi-client/types.gen"; +import { useActions } from "@/components/automations/data"; +import { runStatus } from "@/components/automations/model"; +import { ActivityPanel, BudgetPanel, Cost } from "@/components/costs/costs"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/field"; +import { DateTime, EmptyState, Skeleton, SkeletonRows } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { didDo, type ActionDef } from "@/components/workflows/workflow-model"; +import { data, useApiClient } from "@/lib/api/browser"; +import { plural } from "@/lib/format"; + +export const PAGE = 20; + +/** What a run did, in a few words: "3 done, 1 waiting", or why it didn't run. */ +export function runCounts(r: Pick): string { + const parts = Object.entries(r.counts ?? {}) + .filter(([, n]) => n > 0) + .map(([k, n]) => `${n} ${k}`); + return r.error ?? (parts.length ? parts.join(", ") : (r.why ?? "Nothing to do")); +} + +/** A variable's value as one line of JSON to edit, and back: text that isn't JSON is kept as a string. */ +export function varText(v: unknown): string { + return typeof v === "string" ? v : JSON.stringify(v ?? null); +} +export function varFrom(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return text; + } +} + +function RunDetail({ id, actions }: { id: number; actions?: ActionDef[] }) { + const client = useApiClient(); + const q = useQuery({ + queryKey: ["automation-run", id], + queryFn: () => data(Automations.getRun({ client, path: { run: id } })), + }); + if (q.isLoading) return ; + if (q.error) return

{(q.error as Error).message}

; + const intents = q.data?.intents ?? []; + const log = q.data?.log ?? []; + return ( +
+ {intents.length > 0 && ( +
    + {intents.map((i, n) => ( +
  • {didDo(i, actions)}
  • + ))} +
+ )} + {log.length ? ( +
+          {log.join("\n")}
+        
+ ) : ( +

Nothing in the log.

+ )} +
+ ); +} + +function RunRow({ run, actions, aid }: { run: AutomationRun; actions?: ActionDef[]; aid: number }) { + const [open, setOpen] = useState(false); + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const st = runStatus(run.status); + const decide = useMutation({ + mutationFn: (go: boolean) => data(Automations.decideHeldRun({ client, path: { run: run.id }, body: { run: go } })), + onSuccess: (_, go) => { + void qc.invalidateQueries({ queryKey: ["automation-runs", aid] }); + toast({ tone: "green", title: go ? "Let through: it runs now" : "Skipped" }); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t decide", body: e.message }), + }); + return ( +
  • +
    + + {st.label} + {run.dry && Test} + {run.trigger && by {run.trigger}} + {runCounts(run)} + {(run.cost_usd || run.tokens) && ( + + )} + {run.status === "held" && ( + + + + + )} +
    + {open && ( +
    + +
    + )} +
  • + ); +} + +export function RunsTab({ aid }: { aid: number }) { + const client = useApiClient(); + const actions = useActions().data; + const q = useInfiniteQuery({ + queryKey: ["automation-runs", aid], + initialPageParam: null as number | null, + queryFn: ({ pageParam }) => + data(Automations.listRuns({ client, path: { aid }, query: { before: pageParam, limit: PAGE } })), + getNextPageParam: (last) => last.next ?? null, + }); + if (q.isLoading) return ; + if (q.error) + return ( + } + title="Couldn’t load the runs" + actions={} + > + {(q.error as Error).message} + + ); + const runs = q.data?.pages.flatMap((p) => p.runs) ?? []; + if (!runs.length) + return ( + } title="No runs yet"> + It runs when its trigger fires, or when you press Run now. + + ); + return ( +
    +
      + {runs.map((r) => ( + + ))} +
    + {q.hasNextPage && ( + + )} +
    + ); +} + +type Upcoming = { key?: string; at?: string; description?: string; trigger?: string | null; untrusted?: boolean }; + +export function UpcomingTab({ aid, enabled }: { aid: number; enabled: boolean }) { + const client = useApiClient(); + const q = useQuery({ + queryKey: ["automation-upcoming", aid], + queryFn: () => data(Automations.upcoming({ client, path: { aid }, query: { n: 20 } })), + }); + if (q.isLoading) return ; + if (q.error) return

    {(q.error as Error).message}

    ; + const times = (q.data?.times ?? []) as Upcoming[]; + if (!times.length) + return ( + } title="Nothing coming up"> + {enabled + ? "It has no schedule, time or wait coming up. It still runs when its events arrive." + : "It’s off, so nothing is coming up. Switch it on to set its times."} + + ); + return ( +
      + {times.map((t, n) => ( +
    • + + {t.description} + {t.trigger && · {t.trigger}} + {t.untrusted && Quotes outside text} +
    • + ))} +
    + ); +} + +function VarRow({ v, aid }: { v: AutomationVar; aid: number }) { + const [text, setText] = useState(varText(v.value)); + const set = useSetVars(aid); + const changed = text !== varText(v.value); + return ( +
  • + {v.name} + setText(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter" && changed) set.mutate({ vars: { [v.name]: varFrom(text) } }); + if (e.key === "Escape") setText(varText(v.value)); + }} + /> + {v.untrusted && From outside text} + {v.updated_at && } + + +
  • + ); +} + +function useSetVars(aid: number) { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const m = useMutation({ + mutationFn: ({ vars }: { vars: Record; undo?: Record }) => + data(Automations.putAutomationVars({ client, path: { aid }, body: { vars } })), + onSuccess: (got, { undo }) => { + qc.setQueryData(["automation-vars", aid], got); + if (undo) + toast({ + tone: "intent", + title: `Cleared ${Object.keys(undo).join(", ")}`, + action: { label: "Undo", onClick: () => m.mutate({ vars: undo }) }, + }); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldn’t set it", body: e.message }), + }); + return m; +} + +export function VariablesTab({ aid }: { aid: number }) { + const client = useApiClient(); + const q = useQuery({ + queryKey: ["automation-vars", aid], + queryFn: () => data(Automations.getAutomationVars({ client, path: { aid } })), + }); + const set = useSetVars(aid); + const [name, setName] = useState(""); + const [value, setValue] = useState(""); + if (q.isLoading) return ; + if (q.error) return

    {(q.error as Error).message}

    ; + const vars = q.data?.vars ?? []; + const add = () => { + if (!name.trim()) return; + set.mutate({ vars: { [name.trim()]: varFrom(value) } }, { onSuccess: () => (setName(""), setValue("")) }); + }; + return ( +
    +

    + What it remembers between runs: its actions set these, and its conditions and templates read them as{" "} + {"{{ vars.name }}"}. +

    + {vars.length ? ( +
      + {vars.map((v) => ( + + ))} +
    + ) : ( + } title="No variables yet"> + It has nothing kept between runs. + + )} +
    + setName(e.target.value)} + /> + setValue(e.target.value)} + onKeyDown={(e) => e.key === "Enter" && add()} + /> + +
    + {vars.length > 0 &&

    {plural(vars.length, "variable")}

    } +
    + ); +} + +export function CostsTab({ aid }: { aid: number }) { + return ( +
    + + +
    + ); +} diff --git a/nextjs-frontend/components/workflows/workflow-model.ts b/nextjs-frontend/components/workflows/workflow-model.ts index ae47e6ec..60b17ae4 100644 --- a/nextjs-frontend/components/workflows/workflow-model.ts +++ b/nextjs-frontend/components/workflows/workflow-model.ts @@ -577,6 +577,22 @@ export function wouldDo(i: Record, actions?: ActionDef[]): stri return `${String(i.node)} · ${what}: ${how}${i.untrusted ? " (reads outside text)" : ""}`; } +/** One action a run carried out, as a line: what, and whether it ran, waits for your pick or its time, or failed. */ +export function didDo(i: Record, actions?: ActionDef[]): string { + const what = actions?.find((a) => a.name === i.action)?.label ?? String(i.action); + const how = + i.status === "done" + ? "done" + : i.status === "scheduled" + ? "waiting for its time" + : i.status === "failed" + ? `failed${i.error ? `: ${String(i.error)}` : ""}` + : i.status === "waiting" + ? "waiting for your pick" + : String(i.status ?? "—"); + return `${what}: ${how}${i.untrusted ? " (reads outside text)" : ""}`; +} + /** An action node waits before it acts: for a delay, or until a time. */ export const waits = (n: WfNode) => n.config.delay != null || n.config.when != null; /** Nodes that keep something: a workflow needs one (or a node that keeps something as set up, see savesAsSet). */