Frontend addresses flows and dashboards by id: routes /flows/$flowId, /dashboards/$id and /view/$id, query keys, saves, lists, device pickers, search, brain and endpoint links and generated results dashboards go by id, while live values, issues, pauses and message names keep the key; tabs take the title from the document; creating uses POST and opens the issued id; the flow and dashboard panels show key and id with a copy button and a served HTTP or WebSocket node shows its hook URL under the flow id; specs create by POST and ids.spec.ts exercises issued ids

This commit is contained in:
2026-11-02 19:57:43 +01:00
parent fd637e0f1e
commit fa15522cb0
65 changed files with 1380 additions and 784 deletions
+7 -1
View File
@@ -256,6 +256,12 @@ when no usable message value is available.
To change one on a schedule, have a scheduled node publish its bound message. To change one on a schedule, have a scheduled node publish its bound message.
The top of the panel shows the dashboard's key and its id, with a copy button
for the id. The id never changes: the editor, `/view/{id}` and the devices
showing the dashboard all use it. A dashboard from before ids were introduced
kept its key as its id, while one created now gets an opaque id such as
`d_k3q7m2xa`. The tab shows the title.
### Look and theme ### Look and theme
**Fluksio** is the default look. **Material** uses flat tonal cards; **Glass** **Fluksio** is the default look. **Material** uses flat tonal cards; **Glass**
@@ -448,7 +454,7 @@ under the finger, as a tile view moves.
## Showing one ## Showing one
Open `/view/{name}` for a dashboard-only view with your normal session. Open `/view/{id}` for a dashboard-only view with your normal session.
For a dedicated screen, pair a device. For a dedicated screen, pair a device.
## Devices: hanging a screen on a wall ## Devices: hanging a screen on a wall
+12
View File
@@ -82,6 +82,12 @@ limit, the default.
memory and GPU requirements. Placement by `worker` and `worker_policy` is memory and GPU requirements. Placement by `worker` and `worker_policy` is
configured through the API or flow JSON; see [Remote workers](../code/workers.md). configured through the API or flow JSON; see [Remote workers](../code/workers.md).
An HTTP or WebSocket node whose URL is a path, such as `/tick`, is served by
the engine. The panel then shows the full **Webhook URL** (or **Socket URL**)
with a copy button. It sits under the flow's id, `/hooks/<flow id>/tick`, so it
keeps working whatever the flow is called. A stored secret is not shown. The
URL names it as the last segment for you to fill in.
### Code and reuse ### Code and reuse
Define `process(...)` in **Code**. If the file instead contains exactly one Define `process(...)` in **Code**. If the file instead contains exactly one
@@ -105,12 +111,18 @@ Open **Flow settings** from the pencil button in the dock.
| Setting | Purpose | | Setting | Purpose |
|---|---| |---|---|
| **Identity** | shows the flow's key, the namespace of its messages, and its id with a copy button |
| **Running** | starts or stops the published live flow's subscriptions, schedules and webhooks | | **Running** | starts or stops the published live flow's subscriptions, schedules and webhooks |
| **Mode** | chooses continuous `live` operation or requested `batch` runs | | **Mode** | chooses continuous `live` operation or requested `batch` runs |
| **Inputs** | declares external messages, their starting values and whether a run or a panel writes them; run inputs become run parameters | | **Inputs** | declares external messages, their starting values and whether a run or a panel writes them; run inputs become run parameters |
| **Result** | selects batch output messages | | **Result** | selects batch output messages |
| **Contents** | shows the node count and message namespace | | **Contents** | shows the node count and message namespace |
The id never changes. The editor's address, hook URLs and the API use it. A
flow that existed before ids were introduced kept its key as its id, while a
flow created now gets an opaque one such as `f_k3q7m2xa`. The tab and the
canvas show the title, or the key when there is no title.
For live inputs, **Publish this value now** sends the starting value immediately. For live inputs, **Publish this value now** sends the starting value immediately.
Changing a stored starting value alone does not replace an existing message. Changing a stored starting value alone does not replace an existing message.
+15 -6
View File
@@ -133,9 +133,19 @@ async function captureRuns(page, dir) {
}).catch(() => null) }).catch(() => null)
if (!answer?.ok) return null if (!answer?.ok) return null
const body = await answer.json() const body = await answer.json()
return (body.data || []) const board = (body.data || []).find((one) => one.name.endsWith("_results"))
.map((one) => one.name) if (!board) return null
.find((n) => n.endsWith("_results")) // Named after its flow's key; the runs screen filters by the flow's id.
const flows = await fetch(
`/api/v1/flows/?name=${board.name.replace(/_results$/, "")}`,
{
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token")}`,
},
},
).then((reply) => (reply.ok ? reply.json() : { data: [] }))
const flow = flows.data?.[0]?.id
return flow ? { id: board.id, flow } : null
}) })
// A dashboard read against two runs: the same page a live run is watched // A dashboard read against two runs: the same page a live run is watched
@@ -144,8 +154,7 @@ async function captureRuns(page, dir) {
// the table is filtered to its flow rather than read from the top. Another // the table is filtered to its flow rather than read from the top. Another
// flow's run finishing later would otherwise photograph an empty grid. // flow's run finishing later would otherwise photograph an empty grid.
if (results) { if (results) {
const flow = results.replace(/_results$/, "") await page.goto(`${APP_URL}/runs?flow=${results.flow}`, {
await page.goto(`${APP_URL}/runs?flow=${flow}`, {
waitUntil: "networkidle", waitUntil: "networkidle",
}) })
const ids = await page.getByTestId("run-link").evaluateAll((links) => const ids = await page.getByTestId("run-link").evaluateAll((links) =>
@@ -155,7 +164,7 @@ async function captureRuns(page, dir) {
.filter(Boolean), .filter(Boolean),
) )
if (ids.length) { if (ids.length) {
await page.goto(`${APP_URL}/view/${results}?runs=${ids.join(",")}`, { await page.goto(`${APP_URL}/view/${results.id}?runs=${ids.join(",")}`, {
waitUntil: "networkidle", waitUntil: "networkidle",
}) })
await page.waitForTimeout(2000) await page.waitForTimeout(2000)
+8 -2
View File
@@ -4,7 +4,7 @@ import { Bird, Bot, MessageCircle, Send, Square, Trash2 } from "lucide-react"
import { lazy, Suspense, useEffect, useRef, useState } from "react" import { lazy, Suspense, useEffect, useRef, useState } from "react"
import { AiService, type ChatItem } from "@/client" import { AiService, type ChatItem } from "@/client"
import { flowKeys } from "@/components/Flow/queries" import { flowKeys, flowsQueryOptions } from "@/components/Flow/queries"
import { SidePanel } from "@/components/Flow/SidePanel" import { SidePanel } from "@/components/Flow/SidePanel"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { FluksioLoader } from "@/components/ui/fluksio-loader" import { FluksioLoader } from "@/components/ui/fluksio-loader"
@@ -182,7 +182,13 @@ export function ChatPanel() {
const node = nodes.find((n) => n.id === nodeId) ?? nodes[0] const node = nodes.find((n) => n.id === nodeId) ?? nodes[0]
const control = useControl(node) const control = useControl(node)
const pathname = useRouterState({ select: (s) => s.location.pathname }) const pathname = useRouterState({ select: (s) => s.location.pathname })
const flow = FLOW_PATH.exec(pathname)?.[1] // The address holds the flow's id; the assistant is told its key.
const flowId = FLOW_PATH.exec(pathname)?.[1]
const { data: flowList } = useQuery({
...flowsQueryOptions(),
enabled: Boolean(flowId),
})
const flow = flowList?.data.find((one) => one.id === flowId)?.name
const [items, setItems] = useState<Item[]>([]) const [items, setItems] = useState<Item[]>([])
const [loaded, setLoaded] = useState(false) const [loaded, setLoaded] = useState(false)
@@ -156,8 +156,8 @@ function Tile({
}) { }) {
return ( return (
<Link <Link
to="/dashboards/$name" to="/dashboards/$id"
params={{ name: dashboard.name }} params={{ id: dashboard.id! }}
data-testid="home-dashboard-tile" data-testid="home-dashboard-tile"
className={cn( className={cn(
"grid content-start gap-2 rounded-lg border border-border p-2 transition-colors hover:bg-accent/50", "grid content-start gap-2 rounded-lg border border-border p-2 transition-colors hover:bg-accent/50",
@@ -251,7 +251,7 @@ export function DashboardMosaic({
return ( return (
<div className={container}> <div className={container}>
{dashboards.map((dashboard) => ( {dashboards.map((dashboard) => (
<Tile key={dashboard.name} dashboard={dashboard} className={tile} /> <Tile key={dashboard.id} dashboard={dashboard} className={tile} />
))} ))}
</div> </div>
) )
+11 -18
View File
@@ -159,46 +159,39 @@ export function GlobalSearch({
else into.set(entry.category, [entry]) else into.set(entry.category, [entry])
} }
// `id` is the flow or dashboard to open, the entry's own or its parent's;
// `parent` is only the key, for reading.
const go = (entry: SearchEntry) => { const go = (entry: SearchEntry) => {
onOpenChange(false) onOpenChange(false)
setQuery("") setQuery("")
const id = entry.id ?? ""
switch (entry.category) { switch (entry.category) {
case "flow": case "flow":
return navigate({ return navigate({ to: "/flows/$flowId", params: { flowId: id } })
to: "/flows/$flowName",
params: { flowName: entry.name },
})
case "node": case "node":
return navigate({ return navigate({
to: "/flows/$flowName", to: "/flows/$flowId",
params: { flowName: entry.parent ?? "" }, params: { flowId: id },
search: { node: entry.name }, search: { node: entry.name },
}) })
// A setting is `<node>.<setting>`, and a node id has no dot. // A setting is `<node>.<setting>`, and a node id has no dot.
case "setting": case "setting":
return navigate({ return navigate({
to: "/flows/$flowName", to: "/flows/$flowId",
params: { flowName: entry.parent ?? "" }, params: { flowId: id },
search: { node: entry.name.split(".")[0] }, search: { node: entry.name.split(".")[0] },
}) })
// Arriving on the label's id does what clicking the label does. // Arriving on the label's id does what clicking the label does.
case "input": case "input":
case "output": case "output":
return navigate({ return navigate({
to: "/flows/$flowName", to: "/flows/$flowId",
params: { flowName: entry.parent ?? "" }, params: { flowId: id },
search: { node: `${entry.category}:${entry.name}` }, search: { node: `${entry.category}:${entry.name}` },
}) })
case "dashboard": case "dashboard":
return navigate({
to: "/dashboards/$name",
params: { name: entry.name },
})
case "widget": case "widget":
return navigate({ return navigate({ to: "/dashboards/$id", params: { id } })
to: "/dashboards/$name",
params: { name: entry.parent ?? "" },
})
case "device": case "device":
return navigate({ to: "/devices/$id", params: { id: entry.name } }) return navigate({ to: "/devices/$id", params: { id: entry.name } })
case "secret": case "secret":
@@ -220,6 +220,8 @@ export function OverviewToolbar({
* *
* @param done what the toast says happened to them, "Published" * @param done what the toast says happened to them, "Published"
* @param missed what the ones that failed still are, "Still unpublished" * @param missed what the ones that failed still are, "Still unpublished"
* @param labelOf what a failed one is called in the toast, when what is
* acted on is an id nobody would recognise
*/ */
function useBatch( function useBatch(
act: (name: string) => Promise<unknown>, act: (name: string) => Promise<unknown>,
@@ -227,6 +229,7 @@ function useBatch(
done: string, done: string,
missed: string, missed: string,
onDone: () => void, onDone: () => void,
labelOf: (name: string) => string = (name) => name,
) { ) {
const { showSuccessToast, showErrorToast } = useCustomToast() const { showSuccessToast, showErrorToast } = useCustomToast()
return useMutation({ return useMutation({
@@ -236,7 +239,9 @@ function useBatch(
try { try {
await act(name) await act(name)
} catch (err) { } catch (err) {
failed.push(`${name} (${extractErrorMessage(err as ApiError)})`) failed.push(
`${labelOf(name)} (${extractErrorMessage(err as ApiError)})`,
)
} }
} }
return failed return failed
@@ -261,8 +266,16 @@ export function usePublishAll(
publish: (name: string) => Promise<unknown>, publish: (name: string) => Promise<unknown>,
noun: string, noun: string,
onDone: () => void, onDone: () => void,
labelOf?: (name: string) => string,
) { ) {
return useBatch(publish, noun, "Published", "Still unpublished", onDone) return useBatch(
publish,
noun,
"Published",
"Still unpublished",
onDone,
labelOf,
)
} }
/** /**
@@ -273,8 +286,9 @@ export function useDeleteSelected(
remove: (name: string) => Promise<unknown>, remove: (name: string) => Promise<unknown>,
noun: string, noun: string,
onDone: () => void, onDone: () => void,
labelOf?: (name: string) => string,
) { ) {
return useBatch(remove, noun, "Deleted", "Still there", onDone) return useBatch(remove, noun, "Deleted", "Still there", onDone, labelOf)
} }
/** /**
@@ -285,8 +299,16 @@ export function useDuplicateSelected(
duplicate: (name: string) => Promise<unknown>, duplicate: (name: string) => Promise<unknown>,
noun: string, noun: string,
onDone: () => void, onDone: () => void,
labelOf?: (name: string) => string,
) { ) {
return useBatch(duplicate, noun, "Duplicated", "Not duplicated", onDone) return useBatch(
duplicate,
noun,
"Duplicated",
"Not duplicated",
onDone,
labelOf,
)
} }
/** /**
@@ -385,6 +385,8 @@ export function DashboardEditor({
edit: boolean edit: boolean
}) { }) {
const [draft, setDraft] = useState<Dashboard>(dashboard) const [draft, setDraft] = useState<Dashboard>(dashboard)
// What the API, the routes and the devices know it by; never edited.
const id = dashboard.id!
const [selected, setSelected] = useState<string | null>(null) const [selected, setSelected] = useState<string | null>(null)
// The face a round dashboard shows: the widget picked, or the one last // The face a round dashboard shows: the widget picked, or the one last
// picked or paged to once its settings are put away. // picked or paged to once its settings are put away.
@@ -403,9 +405,9 @@ export function DashboardEditor({
const root = useCanvasRoot(draft) const root = useCanvasRoot(draft)
const navigate = useNavigate() const navigate = useNavigate()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const save = useSaveDashboard(dashboard.name) const save = useSaveDashboard(id)
const publish = usePublishDashboard(dashboard.name) const publish = usePublishDashboard(id)
const discard = useDiscardDashboardDraft(dashboard.name) const discard = useDiscardDashboardDraft(id)
const [discardOpen, setDiscardOpen] = useState(false) const [discardOpen, setDiscardOpen] = useState(false)
const { showSuccessToast, showErrorToast } = useCustomToast() const { showSuccessToast, showErrorToast } = useCustomToast()
const copied = useCopiedWidget() const copied = useCopiedWidget()
@@ -484,8 +486,7 @@ export function DashboardEditor({
} }
const remove = useMutation({ const remove = useMutation({
mutationFn: () => mutationFn: () => DashboardsService.deleteDashboard({ dashboardId: id }),
DashboardsService.deleteDashboard({ dashboardId: draft.name }),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: dashboardKeys.all }) queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
navigate({ to: "/dashboards" }) navigate({ to: "/dashboards" })
@@ -590,7 +591,7 @@ export function DashboardEditor({
(devices?.data ?? []).find( (devices?.data ?? []).find(
(device) => (device) =>
(device.dashboards ?? []).length > 1 && (device.dashboards ?? []).length > 1 &&
(device.dashboards ?? []).includes(draft.name), (device.dashboards ?? []).includes(id),
)?.dashboards ?? null )?.dashboards ?? null
// A round face has no room for one: a panel swipes between those instead. // A round face has no room for one: a panel swipes between those instead.
const hasRail = Boolean(railDashboards) && !stacked && !round const hasRail = Boolean(railDashboards) && !stacked && !round
@@ -598,13 +599,13 @@ export function DashboardEditor({
railDashboards && !round ? ( railDashboards && !round ? (
<PanelRail <PanelRail
dashboards={railDashboards} dashboards={railDashboards}
current={draft.name} current={id}
horizontal={stacked} horizontal={stacked}
// Editing one dashboard of a panel and editing its neighbour are the // Editing one dashboard of a panel and editing its neighbour are the
// same job, so the rail keeps whichever mode this one is in. // same job, so the rail keeps whichever mode this one is in.
linkFor={(name) => ({ linkFor={(other) => ({
to: "/dashboards/$name", to: "/dashboards/$id",
params: { name }, params: { id: other },
search: edit ? { edit: true } : {}, search: edit ? { edit: true } : {},
})} })}
/> />
@@ -675,8 +676,8 @@ export function DashboardEditor({
setSelected(null) setSelected(null)
setSettingsOpen(false) setSettingsOpen(false)
navigate({ navigate({
to: "/dashboards/$name", to: "/dashboards/$id",
params: { name: draft.name }, params: { id },
search: next ? { edit: true } : {}, search: next ? { edit: true } : {},
}) })
} }
@@ -685,7 +686,7 @@ export function DashboardEditor({
const pickable = (widget: WidgetDef, grip = false) => ( const pickable = (widget: WidgetDef, grip = false) => (
<Pickable <Pickable
widget={widget} widget={widget}
dashboard={draft.name} dashboard={id}
grip={grip} grip={grip}
selected={widget.id === selected} selected={widget.id === selected}
onPick={() => { onPick={() => {
@@ -985,7 +986,7 @@ export function DashboardEditor({
asChild asChild
> >
<a <a
href={appPath(`/view/${draft.name}`)} href={appPath(`/view/${id}`)}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >
@@ -97,14 +97,14 @@ export function DashboardPalette({
<CommandGroup heading="Dashboards"> <CommandGroup heading="Dashboards">
{dashboards.map((dashboard) => ( {dashboards.map((dashboard) => (
<CommandItem <CommandItem
key={dashboard.name} key={dashboard.id}
value={`dashboard ${dashboard.name} ${dashboard.title}`} value={`dashboard ${dashboard.name} ${dashboard.title}`}
onSelect={() => onSelect={() =>
close(() => close(() =>
// Editing a neighbour is the same job, as on the rail. // Editing a neighbour is the same job, as on the rail.
navigate({ navigate({
to: "/dashboards/$name", to: "/dashboards/$id",
params: { name: dashboard.name }, params: { id: dashboard.id! },
search: { edit: true }, search: { edit: true },
}), }),
) )
@@ -536,7 +536,7 @@ function WidgetGrid({
issue={widgetIssue(widget)} issue={widgetIssue(widget)}
scroll={scrolls(widget)} scroll={scrolls(widget)}
> >
<WidgetBody widget={widget} dashboard={dashboard.name} /> <WidgetBody widget={widget} dashboard={dashboard.id!} />
</Frame> </Frame>
)} )}
</motion.div> </motion.div>
@@ -28,20 +28,21 @@ export function PanelRail({
linkFor, linkFor,
horizontal, horizontal,
}: { }: {
/** Dashboard ids, in the order the device carries them. */
dashboards: string[] dashboards: string[]
current: string current: string
linkFor: (name: string) => LinkProps linkFor: (id: string) => LinkProps
horizontal?: boolean horizontal?: boolean
}) { }) {
const { Rail } = useUi() const { Rail } = useUi()
const box = useRef<HTMLDivElement>(null) const box = useRef<HTMLDivElement>(null)
const still = useReducedMotion() const still = useReducedMotion()
const entries = useQueries({ const entries = useQueries({
queries: dashboards.map((name) => dashboardQueryOptions(name)), queries: dashboards.map((id) => dashboardQueryOptions(id)),
combine: (results) => combine: (results) =>
results.map((result, index) => ({ results.map((result, index) => ({
name: dashboards[index], name: dashboards[index],
label: result.data?.title || dashboards[index], label: result.data?.title || result.data?.name || dashboards[index],
icon: result.data?.icon ?? "", icon: result.data?.icon ?? "",
active: dashboards[index] === current, active: dashboards[index] === current,
link: linkFor(dashboards[index]), link: linkFor(dashboards[index]),
@@ -16,7 +16,7 @@ import { cn } from "@/lib/utils"
* One dashboard filling whatever screen it landed on. * One dashboard filling whatever screen it landed on.
* *
* The whole of what a wall panel draws, shared by the single-dashboard route * The whole of what a wall panel draws, shared by the single-dashboard route
* (`/view/{name}`) and the paired-panel one (`/panel/{id}`) so a device shows * (`/view/{id}`) and the paired-panel one (`/panel/{id}`) so a device shows
* the same thing either way — the second merely has a rail beside it. * the same thing either way — the second merely has a rail beside it.
* *
* The dashboard's theme is stated by the route rather than here: on these two * The dashboard's theme is stated by the route rather than here: on these two
@@ -601,7 +601,7 @@ export function RoundView({
> >
<Face <Face
widget={one} widget={one}
dashboard={dashboard.name} dashboard={dashboard.id!}
size={size} size={size}
editing={editing} editing={editing}
onPick={onPick && (() => onPick(one.id))} onPick={onPick && (() => onPick(one.id))}
@@ -80,8 +80,10 @@ export function RunsContextProvider({
const finals = new Map<string, LiveValue>() const finals = new Map<string, LiveValue>()
if (primary) { if (primary) {
const at = primary.finished_at ? Date.parse(String(primary.finished_at)) : 0 const at = primary.finished_at ? Date.parse(String(primary.finished_at)) : 0
// Results are named under the flow's key, which `flow` (its id) is not.
const namespace = primary.flow_name || primary.flow
for (const [key, value] of Object.entries(primary.result ?? {})) { for (const [key, value] of Object.entries(primary.result ?? {})) {
finals.set(key.includes(".") ? key : `${primary.flow}.${key}`, { finals.set(key.includes(".") ? key : `${namespace}.${key}`, {
value, value,
ts: at ? at / 1000 : null, ts: at ? at / 1000 : null,
}) })
@@ -105,7 +107,7 @@ export function RunsContextProvider({
) )
}) })
const flow = primary?.flow ?? "" const flow = primary?.flow_name || primary?.flow || ""
const context: DataContext = { const context: DataContext = {
kind: "runs", kind: "runs",
label: label:
+11 -2
View File
@@ -8,6 +8,7 @@ import { screensOf } from "@/components/Devices/ports"
import { devicesQueryOptions } from "@/components/Devices/queries" import { devicesQueryOptions } from "@/components/Devices/queries"
import { import {
FieldLabel, FieldLabel,
IdentitySection,
InfoTip, InfoTip,
PANEL_SECTION, PANEL_SECTION,
PanelSection, PanelSection,
@@ -241,6 +242,8 @@ function RunsSourceFields({
}) { }) {
const { data: flows } = useQuery(runOverviewQueryOptions()) const { data: flows } = useQuery(runOverviewQueryOptions())
const mode = runs.ids?.length ? "ids" : runs.group ? "group" : "latest" const mode = runs.ids?.length ? "ids" : runs.group ? "group" : "latest"
// The pick holds the flow's id; its metrics are named under its key.
const key = flows?.find((row) => row.flow === runs.flow)?.flow_name
return ( return (
<div className="grid gap-2"> <div className="grid gap-2">
@@ -256,7 +259,7 @@ function RunsSourceFields({
<SelectContent> <SelectContent>
{(flows ?? []).map((row) => ( {(flows ?? []).map((row) => (
<SelectItem key={row.flow} value={row.flow}> <SelectItem key={row.flow} value={row.flow}>
{row.flow} {row.flow_name || row.flow}
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>
@@ -271,7 +274,7 @@ function RunsSourceFields({
placeholder="Pick a metric" placeholder="Pick a metric"
filter={(message) => filter={(message) =>
(message.dtype === "float" || message.dtype === "int") && (message.dtype === "float" || message.dtype === "int") &&
(!runs.flow || message.name.startsWith(`${runs.flow}.`)) (!runs.flow || !key || message.name.startsWith(`${key}.`))
} }
onPick={(metric) => onChange({ ...runs, metric })} onPick={(metric) => onChange({ ...runs, metric })}
/> />
@@ -1980,6 +1983,12 @@ export function DashboardPanel({
} }
> >
<div className="grid gap-5 p-4"> <div className="grid gap-5 p-4">
<IdentitySection
name={dashboard.name}
id={dashboard.id!}
help="The key is the dashboard's name. The id never changes: this page's address, the view link, devices and the API use it."
/>
<PanelSection <PanelSection
title="Rail icon" title="Rail icon"
help="Drawn on the rail when a panel carries more than one dashboard." help="Drawn on the rail when a panel carries more than one dashboard."
+19 -18
View File
@@ -8,9 +8,9 @@ import {
export const dashboardKeys = { export const dashboardKeys = {
all: ["dashboards"] as const, all: ["dashboards"] as const,
/** The working copy and the published document are two different reads. */ /** By id. The working copy and the published document are two reads. */
detail: (name: string, draft = false) => detail: (id: string, draft = false) =>
["dashboards", name, draft ? "draft" : "published"] as const, ["dashboards", id, draft ? "draft" : "published"] as const,
messages: ["messages"] as const, messages: ["messages"] as const,
history: (message: string) => ["messages", message, "history"] as const, history: (message: string) => ["messages", message, "history"] as const,
} }
@@ -26,9 +26,9 @@ export const dashboardsQueryOptions = () => ({
* A wall panel asks for the published one, which is the whole point of the * A wall panel asks for the published one, which is the whole point of the
* split: nothing half-arranged reaches the wall until someone publishes. * split: nothing half-arranged reaches the wall until someone publishes.
*/ */
export const dashboardQueryOptions = (name: string, draft = false) => ({ export const dashboardQueryOptions = (id: string, draft = false) => ({
queryKey: dashboardKeys.detail(name, draft), queryKey: dashboardKeys.detail(id, draft),
queryFn: () => DashboardsService.readDashboard({ dashboardId: name, draft }), queryFn: () => DashboardsService.readDashboard({ dashboardId: id, draft }),
}) })
/** Every message any flow declares — what a widget can be pointed at. */ /** Every message any flow declares — what a widget can be pointed at. */
@@ -46,44 +46,44 @@ export const messageHistoryQueryOptions = (message: string) => ({
* *
* This writes the draft; panels keep showing the published document. * This writes the draft; panels keep showing the published document.
*/ */
export function useSaveDashboard(name: string) { export function useSaveDashboard(id: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: (body: DashboardDef_Input) => mutationFn: (body: DashboardDef_Input) =>
DashboardsService.saveDashboard({ dashboardId: name, requestBody: body }), DashboardsService.saveDashboard({ dashboardId: id, requestBody: body }),
onSuccess: (saved) => { onSuccess: (saved) => {
queryClient.setQueryData(dashboardKeys.detail(name, true), saved) queryClient.setQueryData(dashboardKeys.detail(id, true), saved)
queryClient.invalidateQueries({ queryKey: dashboardKeys.all }) queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
}, },
}) })
} }
/** Publish the unpublished changes, which is what puts them on the panels. */ /** Publish the unpublished changes, which is what puts them on the panels. */
export function usePublishDashboard(name: string) { export function usePublishDashboard(id: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: (version: number) => mutationFn: (version: number) =>
DashboardsService.publishDashboard({ DashboardsService.publishDashboard({
dashboardId: name, dashboardId: id,
requestBody: { version }, requestBody: { version },
}), }),
onSuccess: (published) => { onSuccess: (published) => {
queryClient.setQueryData(dashboardKeys.detail(name, true), published) queryClient.setQueryData(dashboardKeys.detail(id, true), published)
queryClient.setQueryData(dashboardKeys.detail(name), published) queryClient.setQueryData(dashboardKeys.detail(id), published)
queryClient.invalidateQueries({ queryKey: dashboardKeys.all }) queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
}, },
}) })
} }
/** Throw the unpublished edit away; the panels keep showing what they had. */ /** Throw the unpublished edit away; the panels keep showing what they had. */
export function useDiscardDashboardDraft(name: string) { export function useDiscardDashboardDraft(id: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: () => mutationFn: () =>
DashboardsService.discardDashboardDraft({ dashboardId: name }), DashboardsService.discardDashboardDraft({ dashboardId: id }),
onSuccess: (published) => { onSuccess: (published) => {
queryClient.setQueryData(dashboardKeys.detail(name, true), published) queryClient.setQueryData(dashboardKeys.detail(id, true), published)
queryClient.setQueryData(dashboardKeys.detail(name), published) queryClient.setQueryData(dashboardKeys.detail(id), published)
queryClient.invalidateQueries({ queryKey: dashboardKeys.all }) queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
}, },
}) })
@@ -116,7 +116,8 @@ export function usePublishMessage() {
requestBody: { requestBody: {
value, value,
source_kind: "dashboard", source_kind: "dashboard",
// Matches the endpoint id the canvas builds for this widget. // Matches the endpoint id the canvas builds for this widget,
// `dashboard:<dashboard id>:<widget>`.
source_id: source_id:
dashboard && widget ? `dashboard:${dashboard}:${widget}` : "", dashboard && widget ? `dashboard:${dashboard}:${widget}` : "",
source_label: label ?? widget ?? "Dashboard", source_label: label ?? widget ?? "Dashboard",
@@ -867,6 +867,7 @@ function DropdownWidget({ widget, dashboard }: WidgetProps) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/** `dashboard` is the dashboard's id, which a control credits what it sends to. */
export type WidgetProps = { widget: WidgetDef; dashboard: string } export type WidgetProps = { widget: WidgetDef; dashboard: string }
const RENDERERS: Partial< const RENDERERS: Partial<
@@ -312,14 +312,15 @@ function Dashboards({
}) { }) {
const { data } = useQuery(dashboardsQueryOptions()) const { data } = useQuery(dashboardsQueryOptions())
const known = data?.data ?? [] const known = data?.data ?? []
// Dashboard ids: a device keeps showing a dashboard whatever it is called.
const assigned = device.dashboards ?? [] const assigned = device.dashboards ?? []
const byName = new Map(known.map((dashboard) => [dashboard.name, dashboard])) const byId = new Map(known.map((dashboard) => [dashboard.id, dashboard]))
const free = known.filter((dashboard) => !assigned.includes(dashboard.name)) const free = known.filter((dashboard) => !assigned.includes(dashboard.id!))
const set = (dashboards: string[]) => onChange({ dashboards }) const set = (dashboards: string[]) => onChange({ dashboards })
const move = (from: number, by: number) => { const move = (from: number, by: number) => {
const next = [...assigned] const next = [...assigned]
const [name] = next.splice(from, 1) const [id] = next.splice(from, 1)
next.splice(from + by, 0, name) next.splice(from + by, 0, id)
set(next) set(next)
} }
@@ -334,13 +335,13 @@ function Dashboards({
</p> </p>
) : ( ) : (
<ol className="grid gap-1" data-testid="device-dashboards"> <ol className="grid gap-1" data-testid="device-dashboards">
{assigned.map((name, index) => { {assigned.map((id, index) => {
const dashboard = byName.get(name) const dashboard = byId.get(id)
const title = dashboard?.title || name const title = dashboard?.title || dashboard?.name || id
// What this dashboard draws on the rail. // What this dashboard draws on the rail.
const Glyph = resolveIcon(dashboard?.icon ?? "") const Glyph = resolveIcon(dashboard?.icon ?? "")
return ( return (
<li key={name} className="flex items-center gap-2 text-sm"> <li key={id} className="flex items-center gap-2 text-sm">
<span className="w-4 shrink-0 text-xs text-muted-foreground"> <span className="w-4 shrink-0 text-xs text-muted-foreground">
{index + 1} {index + 1}
</span> </span>
@@ -352,8 +353,8 @@ function Dashboards({
</span> </span>
{dashboard ? ( {dashboard ? (
<Link <Link
to="/dashboards/$name" to="/dashboards/$id"
params={{ name }} params={{ id }}
className="min-w-0 flex-1 truncate hover:underline" className="min-w-0 flex-1 truncate hover:underline"
> >
{title} {title}
@@ -361,7 +362,7 @@ function Dashboards({
) : ( ) : (
// Deleted since: the device skips it. // Deleted since: the device skips it.
<span className="min-w-0 flex-1 truncate text-muted-foreground line-through"> <span className="min-w-0 flex-1 truncate text-muted-foreground line-through">
{name} {id}
</span> </span>
)} )}
{canEdit ? ( {canEdit ? (
@@ -391,7 +392,7 @@ function Dashboards({
size="icon-touch" size="icon-touch"
className="text-muted-foreground" className="text-muted-foreground"
aria-label={`Remove ${title}`} aria-label={`Remove ${title}`}
onClick={() => set(assigned.filter((n) => n !== name))} onClick={() => set(assigned.filter((n) => n !== id))}
> >
<X /> <X />
</Button> </Button>
@@ -403,7 +404,7 @@ function Dashboards({
</ol> </ol>
)} )}
{canEdit && free.length > 0 ? ( {canEdit && free.length > 0 ? (
<Select value="" onValueChange={(name) => set([...assigned, name])}> <Select value="" onValueChange={(id) => set([...assigned, id])}>
<SelectTrigger <SelectTrigger
className="justify-self-start" className="justify-self-start"
aria-label="Add a dashboard" aria-label="Add a dashboard"
@@ -413,7 +414,7 @@ function Dashboards({
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{free.map((dashboard) => ( {free.map((dashboard) => (
<SelectItem key={dashboard.name} value={dashboard.name}> <SelectItem key={dashboard.id} value={dashboard.id!}>
{dashboard.title || dashboard.name} {dashboard.title || dashboard.name}
</SelectItem> </SelectItem>
))} ))}
@@ -778,8 +779,8 @@ function Capabilities({
{wired.map((binding) => ( {wired.map((binding) => (
<Link <Link
key={`${binding.flow}.${binding.node}.${binding.message}`} key={`${binding.flow}.${binding.node}.${binding.message}`}
to="/flows/$flowName" to="/flows/$flowId"
params={{ flowName: binding.flow }} params={{ flowId: binding.flow_id! }}
search={{ node: binding.node }} search={{ node: binding.node }}
className="min-w-0 truncate font-mono hover:underline" className="min-w-0 truncate font-mono hover:underline"
> >
@@ -839,8 +840,8 @@ export function UseInFlow({
const { data } = useQuery(flowsQueryOptions()) const { data } = useQuery(flowsQueryOptions())
const flows = data?.data ?? [] const flows = data?.data ?? []
const place = useMutation({ const place = useMutation({
mutationFn: async (flowName: string) => { mutationFn: async (flowId: string) => {
const { definition } = await FlowsService.readFlow({ flowId: flowName }) const { definition } = await FlowsService.readFlow({ flowId })
const nodes = definition.nodes ?? [] const nodes = definition.nodes ?? []
const existing = deviceNodeOf(nodes, device.id) const existing = deviceNodeOf(nodes, device.id)
const node = existing ?? { const node = existing ?? {
@@ -854,7 +855,7 @@ export function UseInFlow({
const placed = port ? withPort(node, port) : node const placed = port ? withPort(node, port) : node
if (placed !== existing) { if (placed !== existing) {
await FlowsService.saveFlow({ await FlowsService.saveFlow({
flowId: flowName, flowId,
requestBody: { requestBody: {
...definition, ...definition,
nodes: existing nodes: existing
@@ -863,12 +864,12 @@ export function UseInFlow({
}, },
}) })
} }
return { flowName, node: placed.id } return { flowId, node: placed.id }
}, },
onSuccess: ({ flowName, node }) => onSuccess: ({ flowId, node }) =>
navigate({ navigate({
to: "/flows/$flowName", to: "/flows/$flowId",
params: { flowName }, params: { flowId },
search: { node }, search: { node },
}), }),
onError: (error) => handleError.call(showErrorToast, error as ApiError), onError: (error) => handleError.call(showErrorToast, error as ApiError),
@@ -876,7 +877,7 @@ export function UseInFlow({
if (flows.length === 0) return null if (flows.length === 0) return null
return ( return (
<Select value="" onValueChange={(flowName) => place.mutate(flowName)}> <Select value="" onValueChange={(flowId) => place.mutate(flowId)}>
<SelectTrigger <SelectTrigger
size={size} size={size}
className="shrink-0 justify-self-start" className="shrink-0 justify-self-start"
@@ -892,7 +893,7 @@ export function UseInFlow({
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{flows.map((flow) => ( {flows.map((flow) => (
<SelectItem key={flow.name} value={flow.name}> <SelectItem key={flow.id} value={flow.id!}>
{flow.title || flow.name} {flow.title || flow.name}
</SelectItem> </SelectItem>
))} ))}
@@ -10,7 +10,9 @@ export type BrainNodeData = {
kind: string kind: string
/** The `flow.node_id` names behind this neuron; live events key by these. */ /** The `flow.node_id` names behind this neuron; live events key by these. */
members: string[] members: string[]
/** The keys of the flows it sits in, and their ids in the same order. */
flows: string[] flows: string[]
flowIds: string[]
/** Circle diameter in pixels, from how many neurons this one is wired to. */ /** Circle diameter in pixels, from how many neurons this one is wired to. */
size: number size: number
/** Why this neuron cannot run, if validation found something. */ /** Why this neuron cannot run, if validation found something. */
+10 -5
View File
@@ -113,6 +113,7 @@ function assemble(graph: BrainGraph, placed: Placed[]): Layout {
kind: source.kind, kind: source.kind,
members: source.members ?? [], members: source.members ?? [],
flows: source.flows ?? [], flows: source.flows ?? [],
flowIds: source.flow_ids ?? [],
size: node.size, size: node.size,
issue: source.issue, issue: source.issue,
} satisfies BrainNodeData, } satisfies BrainNodeData,
@@ -233,18 +234,22 @@ function BrainCanvas() {
// flows are in the order they contributed one — which is rarely the // flows are in the order they contributed one — which is rarely the
// one that failed. So the failing member picks the flow, and takes // one that failed. So the failing member picks the flow, and takes
// its node with it; `flow.node_id`, and neither half can hold a dot. // its node with it; `flow.node_id`, and neither half can hold a dot.
const { members, flows } = node.data as BrainNodeData // The member names the flow by key; `flowIds` beside `flows` says
// which flow that is, so the address never comes from a key.
const { members, flows, flowIds } = node.data as BrainNodeData
const failing = members.find( const failing = members.find(
(member) => (member) =>
liveStore.getFailure(member) || liveStore.getFailure(member) ||
liveStore.getStatus(member)?.status === "error", liveStore.getStatus(member)?.status === "error",
) )
const [memberFlow, nodeId] = (failing ?? "").split(".") const [memberFlow, nodeId] = (failing ?? "").split(".")
const flowName = memberFlow || flows[0] const flowId = memberFlow
if (flowName) ? flowIds[flows.indexOf(memberFlow)]
: flowIds[0]
if (flowId)
navigate({ navigate({
to: "/flows/$flowName", to: "/flows/$flowId",
params: { flowName }, params: { flowId },
search: nodeId ? { node: nodeId } : {}, search: nodeId ? { node: nodeId } : {},
}) })
}} }}
@@ -149,13 +149,13 @@ export function CommandPalette({
<CommandGroup heading="Flows"> <CommandGroup heading="Flows">
{flows.map((flow) => ( {flows.map((flow) => (
<CommandItem <CommandItem
key={flow.name} key={flow.id}
value={`flow ${flow.name} ${flow.title}`} value={`flow ${flow.name} ${flow.title}`}
onSelect={() => onSelect={() =>
close(() => close(() =>
navigate({ navigate({
to: "/flows/$flowName", to: "/flows/$flowId",
params: { flowName: flow.name }, params: { flowId: flow.id! },
}), }),
) )
} }
@@ -49,11 +49,14 @@ export type InspectedEdge = {
export function EdgeInspector({ export function EdgeInspector({
edge, edge,
flow, flow,
flowId,
onClose, onClose,
onUnbind, onUnbind,
}: { }: {
edge: InspectedEdge | null edge: InspectedEdge | null
/** The flow's key, which its messages are named under. */
flow: string flow: string
flowId: string
onClose: () => void onClose: () => void
onUnbind: (message: string) => void onUnbind: (message: string) => void
}) { }) {
@@ -64,7 +67,7 @@ export function EdgeInspector({
const replay = useMutation({ const replay = useMutation({
mutationFn: (value: unknown) => mutationFn: (value: unknown) =>
FlowsService.triggerNode({ FlowsService.triggerNode({
flowId: flow, flowId,
nodeId: edge?.sourceId ?? "", nodeId: edge?.sourceId ?? "",
requestBody: { values: { [edge?.message ?? ""]: value } }, requestBody: { values: { [edge?.message ?? ""]: value } },
}), }),
@@ -145,6 +148,7 @@ export function EdgeInspector({
<div className="mt-2"> <div className="mt-2">
<MessageSparkline <MessageSparkline
flow={flow} flow={flow}
flowId={flowId}
name={displayName(flow, edge.message)} name={displayName(flow, edge.message)}
/> />
</div> </div>
+51 -36
View File
@@ -258,11 +258,12 @@ function uniqueNodeId(existing: NodeDef_Input[], type: string): string {
} }
function FlowEditorInner({ function FlowEditorInner({
flowName, flowId,
focus, focus,
onReload, onReload,
}: { }: {
flowName: string /** What the route and every API call address it by. */
flowId: string
/** A node or endpoint to arrive on, from the address bar. */ /** A node or endpoint to arrive on, from the address bar. */
focus?: string focus?: string
onReload: () => void onReload: () => void
@@ -275,8 +276,11 @@ function FlowEditorInner({
const { resolvedTheme } = useTheme() const { resolvedTheme } = useTheme()
const { data: flows } = useSuspenseQuery(flowsQueryOptions()) const { data: flows } = useSuspenseQuery(flowsQueryOptions())
const { data: detail } = useSuspenseQuery(flowQueryOptions(flowName)) const { data: detail } = useSuspenseQuery(flowQueryOptions(flowId))
const { data: nodeTypeInfo } = useQuery(nodeTypesQueryOptions()) const { data: nodeTypeInfo } = useQuery(nodeTypesQueryOptions())
// The key: the namespace of the flow's messages, which live values, issues,
// pauses and node ids are all named under.
const flowName = detail.definition.name
const { const {
save, save,
@@ -285,9 +289,9 @@ function FlowEditorInner({
resolveConflict, resolveConflict,
adopt, adopt,
mutation: saving, mutation: saving,
} = useAutosave(flowName) } = useAutosave(flowId)
const publish = usePublish(flowName) const publish = usePublish(flowId)
const discard = useDiscardDraft(flowName) const discard = useDiscardDraft(flowId)
// The whole working document, so a flow-level edit is an edit like any // The whole working document, so a flow-level edit is an edit like any
// other — undoable, and on screen before the server has seen it. // other — undoable, and on screen before the server has seen it.
@@ -464,6 +468,7 @@ function FlowEditorInner({
data: { data: {
definition: definition ?? { id: node.id }, definition: definition ?? { id: node.id },
flow: flowName, flow: flowName,
flowId,
typeLabel: typeLabel:
typeLabels.get(definition?.type ?? "") ?? definition?.type ?? "", typeLabels.get(definition?.type ?? "") ?? definition?.type ?? "",
isPlugin: pluginTypes.has(definition?.type ?? ""), isPlugin: pluginTypes.has(definition?.type ?? ""),
@@ -477,6 +482,7 @@ function FlowEditorInner({
canvasNodes, canvasNodes,
definitions, definitions,
flowName, flowName,
flowId,
issuesByNode, issuesByNode,
warningsByNode, warningsByNode,
pluginTypes, pluginTypes,
@@ -532,25 +538,28 @@ function FlowEditorInner({
*/ */
const openEndpoint = useCallback( const openEndpoint = useCallback(
(id: string, via?: string) => { (id: string, via?: string) => {
const [kind, rest] = id.split(":", 2) const kind = id.split(":", 1)[0]
// Where it lives comes with it: a key in the endpoint's id names
// messages, never an address. Read at the click, so a refetched detail
// does not make this a new callback and re-run the arrival below.
const owner = queryClient
.getQueryData<FlowDetail>(flowKeys.detail(flowId))
?.endpoints?.find((one) => one.id === id)?.owner_id
if (kind === "input" || kind === "output") { if (kind === "input" || kind === "output") {
// This flow's own boundary, declared in its settings. // This flow's own boundary, declared in its settings.
setSelectedId(null) setSelectedId(null)
setFlowPanelOpen(true) setFlowPanelOpen(true)
} else if (kind === "dashboard") { } else if (kind === "dashboard" && owner) {
navigate({ to: "/dashboards/$id", params: { id: owner } })
} else if (kind === "flow" && owner) {
navigate({ navigate({
to: "/dashboards/$name", to: "/flows/$flowId",
params: { name: (rest ?? "").split(":")[0] }, params: { flowId: owner },
})
} else if (kind === "flow") {
navigate({
to: "/flows/$flowName",
params: { flowName: (rest ?? "").split(".")[0] },
search: { node: `flow:${via ? `${flowName}.${via}` : flowName}` }, search: { node: `flow:${via ? `${flowName}.${via}` : flowName}` },
}) })
} }
}, },
[navigate, flowName], [navigate, flowName, flowId, queryClient],
) )
/** /**
@@ -861,7 +870,7 @@ function FlowEditorInner({
const runMutation = useMutation({ const runMutation = useMutation({
mutationFn: (inputs: Record<string, unknown> = {}) => mutationFn: (inputs: Record<string, unknown> = {}) =>
FlowsService.runFlow({ flowId: flowName, requestBody: { inputs } }), FlowsService.runFlow({ flowId, requestBody: { inputs } }),
onSuccess: (state) => { onSuccess: (state) => {
liveStore.setValues( liveStore.setValues(
Object.fromEntries( Object.fromEntries(
@@ -892,10 +901,10 @@ function FlowEditorInner({
const enableMutation = useMutation({ const enableMutation = useMutation({
mutationFn: (next: boolean) => mutationFn: (next: boolean) =>
next next
? FlowsService.startFlow({ flowId: flowName }) ? FlowsService.startFlow({ flowId })
: FlowsService.stopFlow({ flowId: flowName }), : FlowsService.stopFlow({ flowId }),
onSuccess: (detail) => { onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(flowName), detail) queryClient.setQueryData(flowKeys.detail(flowId), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true }) queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
}, },
onError: () => showErrorToast("The flow could not be started or stopped."), onError: () => showErrorToast("The flow could not be started or stopped."),
@@ -904,14 +913,14 @@ function FlowEditorInner({
const pauseMutation = useMutation({ const pauseMutation = useMutation({
mutationFn: (next: boolean) => mutationFn: (next: boolean) =>
next next
? FlowsService.pauseFlow({ flowId: flowName }) ? FlowsService.pauseFlow({ flowId })
: FlowsService.resumeFlow({ flowId: flowName }), : FlowsService.resumeFlow({ flowId }),
// The engine answers with a flow_paused event, which is what the dock reads. // The engine answers with a flow_paused event, which is what the dock reads.
onError: () => showErrorToast("The flow could not be paused."), onError: () => showErrorToast("The flow could not be paused."),
}) })
const stepMutation = useMutation({ const stepMutation = useMutation({
mutationFn: () => FlowsService.stepFlow({ flowId: flowName }), mutationFn: () => FlowsService.stepFlow({ flowId }),
// Says which node ran, or that nothing was held back — both are answers. // Says which node ran, or that nothing was held back — both are answers.
onSuccess: (result) => showSuccessToast(result.message), onSuccess: (result) => showSuccessToast(result.message),
onError: () => showErrorToast("The flow could not be stepped."), onError: () => showErrorToast("The flow could not be stepped."),
@@ -919,11 +928,11 @@ function FlowEditorInner({
const deleteMutation = useMutation({ const deleteMutation = useMutation({
mutationFn: async (withRuns: boolean) => { mutationFn: async (withRuns: boolean) => {
await FlowsService.deleteFlow({ flowId: flowName }) await FlowsService.deleteFlow({ flowId })
// After the flow, which is refused while a run is live, so a refusal // After the flow, which is refused while a run is live, so a refusal
// leaves both standing. // leaves both standing.
if (withRuns) if (withRuns)
await RunsService.deleteRuns({ flow: flowName, history: true }) await RunsService.deleteRuns({ flow: flowId, history: true })
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: flowKeys.all }) queryClient.invalidateQueries({ queryKey: flowKeys.all })
@@ -947,7 +956,7 @@ function FlowEditorInner({
// draft, so the ports on the canvas have to be there first. // draft, so the ports on the canvas have to be there first.
await flush() await flush()
return FlowsService.saveNodeSource({ return FlowsService.saveNodeSource({
flowId: flowName, flowId,
nodeId, nodeId,
requestBody: { code }, requestBody: { code },
drop, drop,
@@ -955,7 +964,7 @@ function FlowEditorInner({
}, },
// One at a time: the save that drops a port must not land before the // One at a time: the save that drops a port must not land before the
// autosave that kept it. // autosave that kept it.
scope: { id: `source:${flowName}` }, scope: { id: `source:${flowId}` },
onSuccess: (saved) => { onSuccess: (saved) => {
const followed = saved.node const followed = saved.node
if (followed && saved.version) { if (followed && saved.version) {
@@ -974,7 +983,7 @@ function FlowEditorInner({
), ),
) )
} }
queryClient.invalidateQueries({ queryKey: ["flows", flowName] }) queryClient.invalidateQueries({ queryKey: flowKeys.detail(flowId) })
}, },
}) })
@@ -1205,10 +1214,10 @@ function FlowEditorInner({
// Publish what was actually stored: the version only advances once the // Publish what was actually stored: the version only advances once the
// queued save has landed. // queued save has landed.
const current = queryClient.getQueryData<FlowDetail>( const current = queryClient.getQueryData<FlowDetail>(
flowKeys.detail(flowName), flowKeys.detail(flowId),
) )
publish.mutate(current?.definition.version ?? 1) publish.mutate(current?.definition.version ?? 1)
}, [flowName, flush, publish.mutate, queryClient]) }, [flowId, flush, publish.mutate, queryClient])
/** Copy the selected nodes, with the code of the ones carrying their own. */ /** Copy the selected nodes, with the code of the ones carrying their own. */
const copyNodes = useCallback(async () => { const copyNodes = useCallback(async () => {
@@ -1227,7 +1236,7 @@ function FlowEditorInner({
.filter((node) => !node.source_ref && sourceTypes.has(node.type ?? "")) .filter((node) => !node.source_ref && sourceTypes.has(node.type ?? ""))
.map(async (node) => { .map(async (node) => {
const { code } = await FlowsService.readNodeSource({ const { code } = await FlowsService.readNodeSource({
flowId: flowName, flowId,
nodeId: node.id, nodeId: node.id,
}) })
sources[node.id] = code sources[node.id] = code
@@ -1244,7 +1253,7 @@ function FlowEditorInner({
if (!stored) { if (!stored) {
notify("That is too much to copy. The browser store is full.", "error") notify("That is too much to copy. The browser store is full.", "error")
} }
}, [canvasNodes, definitions, flowName, selectedId, sourceTypes]) }, [canvasNodes, definitions, flowId, selectedId, sourceTypes])
/** /**
* Paste them here, renamed around whatever this flow already holds. The * Paste them here, renamed around whatever this flow already holds. The
@@ -1341,6 +1350,8 @@ function FlowEditorInner({
return ( return (
<> <>
{/* From the document: the id in the address is opaque for a new flow. */}
<title>{`${flowDoc.title || flowName} - Fluksio`}</title>
{/* {/*
* Grows in from the centre rather than arriving mid-pan, the same * Grows in from the centre rather than arriving mid-pan, the same
* entrance the brain view uses. React Flow reads a node's handle bounds * entrance the brain view uses. React Flow reads a node's handle bounds
@@ -1531,6 +1542,7 @@ function FlowEditorInner({
<FlowPanel <FlowPanel
open={flowPanelOpen && !selected} open={flowPanelOpen && !selected}
flowId={flowId}
definition={flowDoc} definition={flowDoc}
nodeCount={definitions.length} nodeCount={definitions.length}
// Confirmed, so it is a finished edit rather than a run of keystrokes. // Confirmed, so it is a finished edit rather than a run of keystrokes.
@@ -1546,6 +1558,7 @@ function FlowEditorInner({
<NodePanel <NodePanel
node={selected} node={selected}
flow={flowName} flow={flowName}
flowId={flowId}
nodeTypes={nodeTypeInfo ?? []} nodeTypes={nodeTypeInfo ?? []}
origin={flowDoc.origin} origin={flowDoc.origin}
suggestions={suggestions} suggestions={suggestions}
@@ -1572,6 +1585,7 @@ function FlowEditorInner({
<EdgeInspector <EdgeInspector
edge={inspected} edge={inspected}
flow={flowName} flow={flowName}
flowId={flowId}
onClose={() => setInspected(null)} onClose={() => setInspected(null)}
onUnbind={unbind} onUnbind={unbind}
/> />
@@ -1579,6 +1593,7 @@ function FlowEditorInner({
<InputInspector <InputInspector
input={inspectedInput} input={inspectedInput}
flow={flowName} flow={flowName}
flowId={flowId}
onClose={() => setInspectedInput(null)} onClose={() => setInspectedInput(null)}
onEdit={() => { onEdit={() => {
setInspectedInput(null) setInspectedInput(null)
@@ -1753,10 +1768,10 @@ function useUnpositionedNodes(definitions: NodeDef_Input[]) {
} }
export function FlowEditor({ export function FlowEditor({
flowName, flowId,
focus, focus,
}: { }: {
flowName: string flowId: string
/** A node or endpoint to arrive on — see `FlowEditorInner`. */ /** A node or endpoint to arrive on — see `FlowEditorInner`. */
focus?: string focus?: string
}) { }) {
@@ -1782,8 +1797,8 @@ export function FlowEditor({
* would throw an unsaved edit away with it. * would throw an unsaved edit away with it.
*/} */}
<FlowEditorInner <FlowEditorInner
key={`${flowName}:${epoch}`} key={`${flowId}:${epoch}`}
flowName={flowName} flowId={flowId}
focus={focus} focus={focus}
onReload={reload} onReload={reload}
/> />
+6 -2
View File
@@ -92,7 +92,10 @@ const STATUS_STYLES = {
export type FlowNodeData = { export type FlowNodeData = {
definition: NodeDef_Input definition: NodeDef_Input
/** The flow's key, which its node ids and live values are named under. */
flow: string flow: string
/** The flow's id, which the API takes. */
flowId: string
typeLabel: string typeLabel: string
isPlugin?: boolean isPlugin?: boolean
issueText: string issueText: string
@@ -141,6 +144,7 @@ function FlowNodeComponent({ data, selected }: NodeProps) {
const { const {
definition, definition,
flow, flow,
flowId,
typeLabel, typeLabel,
isPlugin, isPlugin,
issueText, issueText,
@@ -278,7 +282,7 @@ function FlowNodeComponent({ data, selected }: NodeProps) {
// Best effort by nature: it may well have finished between // Best effort by nature: it may well have finished between
// the render and the click, which is the outcome asked for. // the render and the click, which is the outcome asked for.
FlowsService.cancelNode({ FlowsService.cancelNode({
flowId: flow, flowId,
nodeId: definition.id, nodeId: definition.id,
}).catch(() => {}) }).catch(() => {})
}} }}
@@ -318,7 +322,7 @@ function FlowNodeComponent({ data, selected }: NodeProps) {
onShowLogs(definition.id) onShowLogs(definition.id)
// Reading it is what dismisses it: nothing else does, and a // Reading it is what dismisses it: nothing else does, and a
// marker that never goes away stops meaning anything. // marker that never goes away stops meaning anything.
liveStore.acknowledgeFailure(nodeId) liveStore.acknowledgeFailure(nodeId, flowId)
}} }}
> >
<Bug /> <Bug />
+14 -1
View File
@@ -13,7 +13,12 @@ import {
} from "@/components/ui/dialog" } from "@/components/ui/dialog"
import { Switch } from "@/components/ui/switch" import { Switch } from "@/components/ui/switch"
import { BoundarySections } from "./FlowBoundary" import { BoundarySections } from "./FlowBoundary"
import { PanelSection, PanelTitle, SidePanel } from "./SidePanel" import {
IdentitySection,
PanelSection,
PanelTitle,
SidePanel,
} from "./SidePanel"
/** /**
* The flow's own settings, in the same panel its nodes use — down to where the * The flow's own settings, in the same panel its nodes use — down to where the
@@ -21,6 +26,7 @@ import { PanelSection, PanelTitle, SidePanel } from "./SidePanel"
*/ */
export function FlowPanel({ export function FlowPanel({
open, open,
flowId,
definition, definition,
nodeCount, nodeCount,
onChange, onChange,
@@ -32,6 +38,7 @@ export function FlowPanel({
onClose, onClose,
}: { }: {
open: boolean open: boolean
flowId: string
definition: FlowDef_Input definition: FlowDef_Input
nodeCount: number nodeCount: number
onChange: (next: FlowDef_Input) => void onChange: (next: FlowDef_Input) => void
@@ -77,6 +84,12 @@ export function FlowPanel({
} }
> >
<div className="grid gap-6 p-4"> <div className="grid gap-6 p-4">
<IdentitySection
name={definition.name}
id={flowId}
help="The key names the flow's messages. The id never changes: the address of this page, its hook URLs and the API use it."
/>
<PanelSection <PanelSection
title="Running" title="Running"
className="gap-3" className="gap-3"
@@ -24,11 +24,14 @@ export type InspectedInput = {
export function InputInspector({ export function InputInspector({
input, input,
flow, flow,
flowId,
onClose, onClose,
onEdit, onEdit,
}: { }: {
input: InspectedInput | null input: InspectedInput | null
/** The flow's key, which its messages are named under. */
flow: string flow: string
flowId: string
onClose: () => void onClose: () => void
onEdit: () => void onEdit: () => void
}) { }) {
@@ -111,6 +114,7 @@ export function InputInspector({
<div className="mt-2"> <div className="mt-2">
<MessageSparkline <MessageSparkline
flow={flow} flow={flow}
flowId={flowId}
name={displayName(flow, qualify(flow, name))} name={displayName(flow, qualify(flow, name))}
dtype={spec.dtype} dtype={spec.dtype}
/> />
@@ -59,17 +59,20 @@ function useSettled(value: string): string {
*/ */
export function MessageSparkline({ export function MessageSparkline({
flow, flow,
flowId,
name, name,
dtype, dtype,
}: { }: {
/** The flow's key, which a bare `name` is read under. */
flow: string flow: string
flowId: string
name: string name: string
/** What the port declares, so a value that never arrived still says what it would be. */ /** What the port declares, so a value that never arrived still says what it would be. */
dtype?: DType dtype?: DType
}) { }) {
const message = useSettled(name) const message = useSettled(name)
const live = useLiveValue(qualify(flow, message)) const live = useLiveValue(qualify(flow, message))
const { data } = useQuery(messageHistoryQueryOptions(flow, message)) const { data } = useQuery(messageHistoryQueryOptions(flowId, message))
const [tail, setTail] = useState<HistoryPoint[]>([]) const [tail, setTail] = useState<HistoryPoint[]>([])
// Pointing the field at another message makes the collected tail meaningless. // Pointing the field at another message makes the collected tail meaningless.
+80 -14
View File
@@ -26,6 +26,7 @@ import {
type MessageSpec, type MessageSpec,
type NodeDef_Input, type NodeDef_Input,
type NodeTypeInfo, type NodeTypeInfo,
OpenAPI,
} from "@/client" } from "@/client"
import { import {
DEVICE_TYPE, DEVICE_TYPE,
@@ -81,6 +82,7 @@ import {
useParamSuggestions, useParamSuggestions,
} from "./queries" } from "./queries"
import { import {
CopyValue,
FieldLabel, FieldLabel,
InfoTip, InfoTip,
PANEL_SECTION, PANEL_SECTION,
@@ -307,6 +309,7 @@ function PortList({
side, side,
specs, specs,
flow, flow,
flowId,
emptyHint, emptyHint,
suggestions, suggestions,
onChange, onChange,
@@ -318,7 +321,9 @@ function PortList({
/** An input reads a message into the code, an output writes one out of it. */ /** An input reads a message into the code, an output writes one out of it. */
side: "requires" | "provides" side: "requires" | "provides"
specs: MessageSpec[] specs: MessageSpec[]
/** The flow's key, which a bare message name is read under. */
flow: string flow: string
flowId: string
emptyHint: string emptyHint: string
suggestions: string[] suggestions: string[]
onChange: (next: MessageSpec[]) => void onChange: (next: MessageSpec[]) => void
@@ -579,6 +584,7 @@ function PortList({
{spec.name ? ( {spec.name ? (
<MessageSparkline <MessageSparkline
flow={flow} flow={flow}
flowId={flowId}
name={spec.name} name={spec.name}
dtype={spec.dtype ?? undefined} dtype={spec.dtype ?? undefined}
/> />
@@ -1616,17 +1622,69 @@ function ResourcesSection({
) )
} }
/**
* Where a webhook or a socket this node serves is reached: a path in its `url`
* is served under the flow's id, so a URL handed out survives a new key.
*
* A stored secret stays in the secrets store, so the URL names it instead of
* carrying it, and that last segment is for whoever uses it to fill in.
*/
function HookSection({
flowId,
node,
}: {
flowId: string
node: NodeDef_Input
}) {
const path = String(node.params?.url ?? "")
if (!["http", "websocket"].includes(node.type ?? "") || !path.startsWith("/"))
return null
const secret = node.params?.secret
const plain = typeof secret === "string" ? secret : ""
const stored =
secret && typeof secret === "object"
? (secret as { $secret?: string }).$secret
: undefined
// Concatenated, as for the socket: under a portal the base has a path.
const base = String(OpenAPI.BASE || window.location.origin).replace(/\/$/, "")
const http = `${base}/hooks/${flowId}/${path.replace(/^\/+/, "")}${
plain ? `/${plain}` : ""
}`
const url = node.type === "websocket" ? http.replace(/^http/, "ws") : http
const what = node.type === "websocket" ? "socket URL" : "webhook URL"
const title = what[0].toUpperCase() + what.slice(1)
return (
<div className="grid gap-1.5">
<div className="flex items-center gap-1">
<span className={SECTION}>{title}</span>
<InfoTip label={title}>
{stored
? `Served while the flow runs. Append the value of the secret ${stored} as the last segment.`
: "Served while the flow runs. It stays the same if the flow's key changes."}
</InfoTip>
</div>
<CopyValue value={url} label={what} testId="hook-url">
{url}
{stored ? (
<span className="text-muted-foreground">/{`<${stored}>`}</span>
) : null}
</CopyValue>
</div>
)
}
/** /**
* Sharing a node moves its code to the library, where other flows can point at * Sharing a node moves its code to the library, where other flows can point at
* it. Each flow keeps its own ports and settings; only the code is common, so * it. Each flow keeps its own ports and settings; only the code is common, so
* one fix reaches all of them. * one fix reaches all of them.
*/ */
function SharingSection({ function SharingSection({
flow, flowId,
node, node,
onShared, onShared,
}: { }: {
flow: string flowId: string
node: NodeDef_Input node: NodeDef_Input
onShared: () => void onShared: () => void
}) { }) {
@@ -1640,14 +1698,14 @@ function SharingSection({
const done = () => { const done = () => {
queryClient.invalidateQueries({ queryKey: flowKeys.library }) queryClient.invalidateQueries({ queryKey: flowKeys.library })
queryClient.invalidateQueries({ queryKey: flowKeys.detail(flow) }) queryClient.invalidateQueries({ queryKey: flowKeys.detail(flowId) })
onShared() onShared()
} }
const share = useMutation({ const share = useMutation({
mutationFn: (libName: string) => mutationFn: (libName: string) =>
FlowsService.shareNode({ FlowsService.shareNode({
flowId: flow, flowId,
nodeId: node.id, nodeId: node.id,
requestBody: { lib_name: libName }, requestBody: { lib_name: libName },
}), }),
@@ -1657,8 +1715,7 @@ function SharingSection({
}) })
const unshare = useMutation({ const unshare = useMutation({
mutationFn: () => mutationFn: () => FlowsService.unshareNode({ flowId, nodeId: node.id }),
FlowsService.unshareNode({ flowId: flow, nodeId: node.id }),
onSuccess: done, onSuccess: done,
onError: () => showErrorToast("The node could not be unshared."), onError: () => showErrorToast("The node could not be unshared."),
}) })
@@ -1736,27 +1793,27 @@ const percent = (value: unknown) =>
* it is an edit like any other, so it waits in the draft until publishing. * it is an edit like any other, so it waits in the draft until publishing.
*/ */
function TrainingSection({ function TrainingSection({
flow, flowId,
node, node,
onUse, onUse,
}: { }: {
flow: string flowId: string
node: NodeDef_Input node: NodeDef_Input
onUse: (model: string) => void onUse: (model: string) => void
}) { }) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
// Why it would not start, such as wren's training flow not being registered. // Why it would not start, such as wren's training flow not being registered.
const [problem, setProblem] = useState<string | null>(null) const [problem, setProblem] = useState<string | null>(null)
const queryKey = ["wren-training", flow, node.id] const queryKey = ["wren-training", flowId, node.id]
const { data: training } = useQuery({ const { data: training } = useQuery({
queryKey, queryKey,
queryFn: () => FlowsService.readTraining({ flowId: flow, nodeId: node.id }), queryFn: () => FlowsService.readTraining({ flowId, nodeId: node.id }),
// Training takes minutes, so only a run still going is read again. // Training takes minutes, so only a run still going is read again.
refetchInterval: (query) => refetchInterval: (query) =>
query.state.data && isLive(query.state.data.status) ? 5_000 : false, query.state.data && isLive(query.state.data.status) ? 5_000 : false,
}) })
const train = useMutation({ const train = useMutation({
mutationFn: () => FlowsService.trainNode({ flowId: flow, nodeId: node.id }), mutationFn: () => FlowsService.trainNode({ flowId, nodeId: node.id }),
onMutate: () => setProblem(null), onMutate: () => setProblem(null),
onSuccess: () => queryClient.invalidateQueries({ queryKey }), onSuccess: () => queryClient.invalidateQueries({ queryKey }),
onError: handleError.bind(setProblem), onError: handleError.bind(setProblem),
@@ -2030,6 +2087,7 @@ function scaffoldFor(node: NodeDef_Input): string {
function PanelBody({ function PanelBody({
node, node,
flow, flow,
flowId,
nodeType, nodeType,
origin, origin,
suggestions, suggestions,
@@ -2043,6 +2101,7 @@ function PanelBody({
}: { }: {
node: NodeDef_Input node: NodeDef_Input
flow: string flow: string
flowId: string
nodeType: NodeTypeInfo | undefined nodeType: NodeTypeInfo | undefined
origin: FlowOrigin | null | undefined origin: FlowOrigin | null | undefined
suggestions: PortSuggestions suggestions: PortSuggestions
@@ -2057,7 +2116,7 @@ function PanelBody({
}) { }) {
const hasSource = nodeType?.has_source ?? node.type === "python" const hasSource = nodeType?.has_source ?? node.type === "python"
const { data: source } = useQuery({ const { data: source } = useQuery({
...nodeSourceQueryOptions(flow, node.id), ...nodeSourceQueryOptions(flowId, node.id),
enabled: hasSource, enabled: hasSource,
}) })
// Code the engine runs is a superuser's to change; the server refuses // Code the engine runs is a superuser's to change; the server refuses
@@ -2228,6 +2287,7 @@ function PanelBody({
side="requires" side="requires"
specs={node.requires ?? []} specs={node.requires ?? []}
flow={flow} flow={flow}
flowId={flowId}
emptyHint="Nothing yet. Add a message this node reads." emptyHint="Nothing yet. Add a message this node reads."
suggestions={suggestions.consumes} suggestions={suggestions.consumes}
onChange={(requires) => editNode({ ...node, requires })} onChange={(requires) => editNode({ ...node, requires })}
@@ -2237,6 +2297,7 @@ function PanelBody({
side="provides" side="provides"
specs={node.provides ?? []} specs={node.provides ?? []}
flow={flow} flow={flow}
flowId={flowId}
emptyHint="Nothing yet. Add a message this node publishes." emptyHint="Nothing yet. Add a message this node publishes."
suggestions={suggestions.provides} suggestions={suggestions.provides}
onChange={(provides) => { onChange={(provides) => {
@@ -2270,6 +2331,7 @@ function PanelBody({
) : ( ) : (
paramsForm paramsForm
)} )}
<HookSection flowId={flowId} node={node} />
{nodeType?.free_params ? ( {nodeType?.free_params ? (
<FreeParamsForm <FreeParamsForm
params={node.params ?? {}} params={node.params ?? {}}
@@ -2282,7 +2344,7 @@ function PanelBody({
) : null} ) : null}
{node.type === "wren" ? ( {node.type === "wren" ? (
<TrainingSection <TrainingSection
flow={flow} flowId={flowId}
node={node} node={node}
onUse={(model) => onUse={(model) =>
editNode({ ...node, params: { ...node.params, model } }) editNode({ ...node, params: { ...node.params, model } })
@@ -2325,7 +2387,7 @@ function PanelBody({
<ResourcesSection node={node} onChange={editNode} /> <ResourcesSection node={node} onChange={editNode} />
) : null} ) : null}
{hasSource ? ( {hasSource ? (
<SharingSection flow={flow} node={node} onShared={onShared} /> <SharingSection flowId={flowId} node={node} onShared={onShared} />
) : null} ) : null}
</div> </div>
@@ -2405,6 +2467,7 @@ export type PortSuggestions = { consumes: string[]; provides: string[] }
export function NodePanel({ export function NodePanel({
node, node,
flow, flow,
flowId,
nodeTypes, nodeTypes,
origin, origin,
suggestions, suggestions,
@@ -2419,7 +2482,9 @@ export function NodePanel({
onDelete, onDelete,
}: { }: {
node: NodeDef_Input | null node: NodeDef_Input | null
/** The flow's key, the namespace its messages are named under. */
flow: string flow: string
flowId: string
nodeTypes: NodeTypeInfo[] nodeTypes: NodeTypeInfo[]
/** Set when the flow was declared in code elsewhere; its bodies are generated. */ /** Set when the flow was declared in code elsewhere; its bodies are generated. */
origin: FlowOrigin | null | undefined origin: FlowOrigin | null | undefined
@@ -2476,6 +2541,7 @@ export function NodePanel({
<PanelBody <PanelBody
node={node} node={node}
flow={flow} flow={flow}
flowId={flowId}
nodeType={nodeType} nodeType={nodeType}
origin={origin} origin={origin}
suggestions={suggestions} suggestions={suggestions}
+77 -1
View File
@@ -1,4 +1,4 @@
import { Info, X } from "lucide-react" import { Check, Copy, Info, X } from "lucide-react"
import { AnimatePresence, motion } from "motion/react" import { AnimatePresence, motion } from "motion/react"
import type { ReactNode } from "react" import type { ReactNode } from "react"
import { useEffect, useState } from "react" import { useEffect, useState } from "react"
@@ -12,6 +12,7 @@ import {
TooltipContent, TooltipContent,
TooltipTrigger, TooltipTrigger,
} from "@/components/ui/tooltip" } from "@/components/ui/tooltip"
import { useCopyToClipboard } from "@/hooks/useCopyToClipboard"
import { useIsMobile } from "@/hooks/useMobile" import { useIsMobile } from "@/hooks/useMobile"
import { duration, easeEmphasized, easeStandard } from "@/lib/motion" import { duration, easeEmphasized, easeStandard } from "@/lib/motion"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
@@ -122,6 +123,81 @@ export function PanelSection({
) )
} }
/**
* Something to paste elsewhere, an id or a URL: selectable as text, with a
* button that copies all of it. No button where the browser has no clipboard
* (a page served over plain http), since one that does nothing is worse.
*/
export function CopyValue({
value,
label,
testId,
children,
}: {
value: string
/** What is copied, for the button's label: "id", "webhook URL". */
label: string
testId?: string
/** What is drawn, when that is more than the value itself. */
children?: ReactNode
}) {
const [copied, copy] = useCopyToClipboard()
return (
<div className="flex min-w-0 items-center gap-1">
<span
className="min-w-0 flex-1 select-all break-all font-mono text-sm"
data-testid={testId}
>
{children ?? value}
</span>
{navigator.clipboard ? (
<Button
variant="ghost"
size="icon-touch"
className="shrink-0 text-muted-foreground"
aria-label={`Copy the ${label}`}
onClick={() => copy(value)}
>
{copied === value ? <Check /> : <Copy />}
</Button>
) : null}
</div>
)
}
/**
* The key a flow or dashboard goes by and the id it is addressed by. The id
* never changes, so it is the one worth copying into a script or a link.
*/
export function IdentitySection({
name,
id,
help,
}: {
name: string
id: string
help: ReactNode
}) {
return (
<PanelSection title="Identity" help={help}>
<dl className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-4 text-sm">
<div className="contents">
<dt className="text-muted-foreground">Key</dt>
<dd className="truncate font-mono" data-testid="identity-key">
{name}
</dd>
</div>
<div className="contents">
<dt className="text-muted-foreground">Id</dt>
<dd className="min-w-0">
<CopyValue value={id} label="id" testId="identity-id" />
</dd>
</div>
</dl>
</PanelSection>
)
}
/** /**
* What the thing in this panel is called, and the one place to rename it. * What the thing in this panel is called, and the one place to rename it.
* *
+6 -5
View File
@@ -201,18 +201,19 @@ export const liveStore = {
* not, which is what makes a failure between two glances at the canvas * not, which is what makes a failure between two glances at the canvas
* findable at all. * findable at all.
*/ */
acknowledgeFailure(nodeId: string) { acknowledgeFailure(nodeId: string, flowId: string) {
if (!failures.delete(nodeId)) return if (!failures.delete(nodeId)) return
notify(`failure:${nodeId}`) notify(`failure:${nodeId}`)
const [flow, node] = nodeId.split(".") // `key.node`: the key names the node, the id addresses the flow.
if (!flow || !node) return const node = nodeId.split(".")[1]
if (!node) return
// Hand-written rather than generated: nothing hangs off the response, and // Hand-written rather than generated: nothing hangs off the response, and
// a call that does not arrive only means the marker is back after a // a call that does not arrive only means the marker is back after a
// reload — which is the safer way round for a failure. // reload — which is the safer way round for a failure.
request(OpenAPI, { request(OpenAPI, {
method: "POST", method: "POST",
url: "/api/v1/flows/{name}/nodes/{node_id}/acknowledge", url: "/api/v1/flows/{flow_id}/nodes/{node_id}/acknowledge",
path: { name: flow, node_id: node }, path: { flow_id: flowId, node_id: node },
}).catch(() => {}) }).catch(() => {})
}, },
recordEngineEvent(event: EngineEvent) { recordEngineEvent(event: EngineEvent) {
+28 -27
View File
@@ -15,13 +15,14 @@ import {
SecretsService, SecretsService,
} from "@/client" } from "@/client"
/** Keyed by flow id, which every flow route takes. */
export const flowKeys = { export const flowKeys = {
all: ["flows"] as const, all: ["flows"] as const,
detail: (name: string) => ["flows", name] as const, detail: (id: string) => ["flows", id] as const,
source: (name: string, nodeId: string) => source: (id: string, nodeId: string) =>
["flows", name, "source", nodeId] as const, ["flows", id, "source", nodeId] as const,
history: (name: string, message: string) => history: (id: string, message: string) =>
["flows", name, "history", message] as const, ["flows", id, "history", message] as const,
nodeTypes: ["flows", "node-types"] as const, nodeTypes: ["flows", "node-types"] as const,
library: ["flows", "library"] as const, library: ["flows", "library"] as const,
// Under `all` on purpose: the socket invalidates that prefix on every // Under `all` on purpose: the socket invalidates that prefix on every
@@ -34,9 +35,9 @@ export const flowsQueryOptions = () => ({
queryFn: () => FlowsService.readFlows(), queryFn: () => FlowsService.readFlows(),
}) })
export const flowQueryOptions = (name: string) => ({ export const flowQueryOptions = (id: string) => ({
queryKey: flowKeys.detail(name), queryKey: flowKeys.detail(id),
queryFn: () => FlowsService.readFlow({ flowId: name }), queryFn: () => FlowsService.readFlow({ flowId: id }),
}) })
/** Names of the stored secrets, for pointing a credential parameter at one. */ /** Names of the stored secrets, for pointing a credential parameter at one. */
@@ -69,15 +70,15 @@ export const nodeTypesQueryOptions = () => ({
staleTime: Number.POSITIVE_INFINITY, staleTime: Number.POSITIVE_INFINITY,
}) })
export const nodeSourceQueryOptions = (name: string, nodeId: string) => ({ export const nodeSourceQueryOptions = (id: string, nodeId: string) => ({
queryKey: flowKeys.source(name, nodeId), queryKey: flowKeys.source(id, nodeId),
queryFn: () => FlowsService.readNodeSource({ flowId: name, nodeId }), queryFn: () => FlowsService.readNodeSource({ flowId: id, nodeId }),
}) })
/** The recent values of one message, for the panel's sparkline. */ /** The recent values of one message, for the panel's sparkline. */
export const messageHistoryQueryOptions = (name: string, message: string) => ({ export const messageHistoryQueryOptions = (id: string, message: string) => ({
queryKey: flowKeys.history(name, message), queryKey: flowKeys.history(id, message),
queryFn: () => FlowsService.readMessageHistory({ flowId: name, message }), queryFn: () => FlowsService.readMessageHistory({ flowId: id, message }),
}) })
/** Other flows change rarely; suggestions do not need them fresh to the second. */ /** Other flows change rarely; suggestions do not need them fresh to the second. */
@@ -103,7 +104,7 @@ export function useParamSuggestions(
// entries; an aggregate endpoint if a big instance makes that hurt. // entries; an aggregate endpoint if a big instance makes that hurt.
const details = useQueries({ const details = useQueries({
queries: (type ? (flows?.data ?? []) : []).map((flow) => ({ queries: (type ? (flows?.data ?? []) : []).map((flow) => ({
...flowQueryOptions(flow.name), ...flowQueryOptions(flow.id!),
staleTime: SUGGEST_STALE, staleTime: SUGGEST_STALE,
})), })),
}) })
@@ -130,25 +131,25 @@ const AUTOSAVE_DELAY = 800
const RETRY_DELAY = 100 const RETRY_DELAY = 100
/** Publish the unpublished changes, which is what puts them on the engine. */ /** Publish the unpublished changes, which is what puts them on the engine. */
export function usePublish(name: string) { export function usePublish(id: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: (version: number) => mutationFn: (version: number) =>
FlowsService.publishFlow({ flowId: name, requestBody: { version } }), FlowsService.publishFlow({ flowId: id, requestBody: { version } }),
onSuccess: (detail) => { onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(name), detail) queryClient.setQueryData(flowKeys.detail(id), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true }) queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
}, },
}) })
} }
/** Throw the unpublished changes away and go back to what is running. */ /** Throw the unpublished changes away and go back to what is running. */
export function useDiscardDraft(name: string) { export function useDiscardDraft(id: string) {
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: () => FlowsService.discardDraft({ flowId: name }), mutationFn: () => FlowsService.discardDraft({ flowId: id }),
onSuccess: (detail) => { onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(name), detail) queryClient.setQueryData(flowKeys.detail(id), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true }) queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
}, },
}) })
@@ -166,7 +167,7 @@ export function useDiscardDraft(name: string) {
* between, the server refuses rather than discarding their work, and `conflict` * between, the server refuses rather than discarding their work, and `conflict`
* turns true for the editor to ask which version wins. * turns true for the editor to ask which version wins.
*/ */
export function useAutosave(name: string): { export function useAutosave(id: string): {
save: (definition: FlowDef_Input) => void save: (definition: FlowDef_Input) => void
/** Send what is queued and resolve once the server has it. */ /** Send what is queued and resolve once the server has it. */
flush: () => Promise<void> flush: () => Promise<void>
@@ -189,7 +190,7 @@ export function useAutosave(name: string): {
const mutation = useMutation({ const mutation = useMutation({
mutationFn: (definition: FlowDef_Input) => mutationFn: (definition: FlowDef_Input) =>
FlowsService.saveFlow({ FlowsService.saveFlow({
flowId: name, flowId: id,
// The ref holds the freshest version this client has seen; before the // The ref holds the freshest version this client has seen; before the
// first save that is the one the document was loaded with. Sending // first save that is the one the document was loaded with. Sending
// `undefined` would drop the field and let the server read the default, // `undefined` would drop the field and let the server read the default,
@@ -210,7 +211,7 @@ export function useAutosave(name: string): {
version.current = detail.definition.version ?? null version.current = detail.definition.version ?? null
// Write the server's answer straight into the cache: invalidating would // Write the server's answer straight into the cache: invalidating would
// pull the document back out from under edits still in flight. // pull the document back out from under edits still in flight.
queryClient.setQueryData(flowKeys.detail(name), detail) queryClient.setQueryData(flowKeys.detail(id), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true }) queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
}, },
onError: (error) => { onError: (error) => {
@@ -250,17 +251,17 @@ export function useAutosave(name: string): {
sent.current = null sent.current = null
version.current = null version.current = null
await queryClient.invalidateQueries({ await queryClient.invalidateQueries({
queryKey: flowKeys.detail(name), queryKey: flowKeys.detail(id),
}) })
return return
} }
const current = await FlowsService.readFlow({ flowId: name }) const current = await FlowsService.readFlow({ flowId: id })
version.current = current.definition.version ?? null version.current = current.definition.version ?? null
const definition = pending.current ?? sent.current const definition = pending.current ?? sent.current
pending.current = null pending.current = null
if (definition) mutate(definition) if (definition) mutate(definition)
}, },
[mutate, name, queryClient], [mutate, id, queryClient],
) )
const save = useCallback( const save = useCallback(
+26 -6
View File
@@ -35,6 +35,11 @@ const AUTH_ATTEMPTS = 3
*/ */
const HEALTH_FLOOR = 60_000 const HEALTH_FLOOR = 60_000
/**
* An engine event names its flow by key (`flow`), which node ids and live
* values are qualified with, and by id (`flow_id`), which a query or a route
* takes. Snapshot lists stay keyed by key.
*/
type FlowEvent = type FlowEvent =
| { | {
type: "snapshot" type: "snapshot"
@@ -58,6 +63,7 @@ type FlowEvent =
| { | {
type: "node_queued" type: "node_queued"
flow?: string flow?: string
flow_id?: string
node: string node: string
run?: string run?: string
detail?: string detail?: string
@@ -66,6 +72,7 @@ type FlowEvent =
| { | {
type: "node_executed" type: "node_executed"
flow?: string flow?: string
flow_id?: string
node: string node: string
outputs: number outputs: number
duration_ms?: number duration_ms?: number
@@ -73,6 +80,7 @@ type FlowEvent =
| { | {
type: "node_error" type: "node_error"
flow?: string flow?: string
flow_id?: string
node: string node: string
error: string error: string
ts?: number ts?: number
@@ -80,21 +88,29 @@ type FlowEvent =
| { type: "node_status"; node: string; status: string; error?: string | null } | { type: "node_status"; node: string; status: string; error?: string | null }
| { type: "node_error_acknowledged"; node: string; ts?: number } | { type: "node_error_acknowledged"; node: string; ts?: number }
| ({ type: "node_log" } & LogLine) | ({ type: "node_log" } & LogLine)
| { type: "flow_paused"; flow: string; paused: boolean } | { type: "flow_paused"; flow: string; flow_id?: string; paused: boolean }
| { | {
type: "node_health" type: "node_health"
flow?: string flow?: string
flow_id?: string
node: string node: string
health: "ok" | "degraded" | "down" | "unknown" health: "ok" | "degraded" | "down" | "unknown"
detail?: string | null detail?: string | null
ts?: number ts?: number
} }
| { type: "flow_quarantined"; flow: string; error?: string; ts?: number } | {
type: "flow_quarantined"
flow: string
flow_id?: string
error?: string
ts?: number
}
| { type: "engine_degraded"; reason?: string; ts?: number } | { type: "engine_degraded"; reason?: string; ts?: number }
| { type: "engine_fatal"; reason?: string; ts?: number } | { type: "engine_fatal"; reason?: string; ts?: number }
| { | {
type: "cascade_dropped" type: "cascade_dropped"
flow?: string flow?: string
flow_id?: string
node?: string node?: string
deliveries?: number deliveries?: number
ts?: number ts?: number
@@ -102,6 +118,7 @@ type FlowEvent =
| { | {
type: "queue_unavailable" type: "queue_unavailable"
flow?: string flow?: string
flow_id?: string
node?: string node?: string
error?: string error?: string
ts?: number ts?: number
@@ -111,6 +128,7 @@ type FlowEvent =
nodes: { id: string; status: string; error?: string | null }[] nodes: { id: string; status: string; error?: string | null }[]
paused?: string[] paused?: string[]
} }
/** `dashboard` is an id, or empty when only device assignments changed. */
| { type: "dashboard_changed"; dashboard?: string; ts?: number } | { type: "dashboard_changed"; dashboard?: string; ts?: number }
| { | {
type: "device_status" type: "device_status"
@@ -122,6 +140,7 @@ type FlowEvent =
| { | {
type: "run_started" | "run_finished" type: "run_started" | "run_finished"
flow: string flow: string
flow_id?: string
run: string run: string
status?: string status?: string
group?: string group?: string
@@ -130,6 +149,7 @@ type FlowEvent =
| { | {
type: "run_metric" type: "run_metric"
flow: string flow: string
flow_id?: string
run: string run: string
names: string[] names: string[]
ts?: number ts?: number
@@ -231,11 +251,11 @@ function endLive() {
} }
/** Everything a node's health shows up in, which is two unrelated keys. */ /** Everything a node's health shows up in, which is two unrelated keys. */
function invalidateHealth(flow: string | undefined) { function invalidateHealth(flowId: string | undefined) {
// `graph` is a sibling of the flow's own key rather than a child, so the // `graph` is a sibling of the flow's own key rather than a child, so the
// detail invalidation alone never reaches Home's fault rings. // detail invalidation alone never reaches Home's fault rings.
for (const queryKey of [ for (const queryKey of [
flow ? flowKeys.detail(flow) : flowKeys.all, flowId ? flowKeys.detail(flowId) : flowKeys.all,
flowKeys.graph, flowKeys.graph,
]) { ]) {
client?.invalidateQueries({ queryKey }) client?.invalidateQueries({ queryKey })
@@ -387,7 +407,7 @@ function open(url: string) {
// the server derives — so the screen only moved on mount, navigation // the server derives — so the screen only moved on mount, navigation
// or a rebuild, never when health actually flipped. The store had a // or a rebuild, never when health actually flipped. The store had a
// health map of its own and nothing ever read it. // health map of its own and nothing ever read it.
invalidateHealth(message.flow) invalidateHealth(message.flow_id)
// Degraded is held back by the same floor, as a warning rather than // Degraded is held back by the same floor, as a warning rather than
// a fault. // a fault.
if (message.health === "down" || message.health === "degraded") { if (message.health === "down" || message.health === "degraded") {
@@ -402,7 +422,7 @@ function open(url: string) {
message.node, message.node,
setTimeout(() => { setTimeout(() => {
healthTimers.delete(message.node) healthTimers.delete(message.node)
invalidateHealth(message.flow) invalidateHealth(message.flow_id)
}, HEALTH_FLOOR), }, HEALTH_FLOOR),
) )
} }
+8 -7
View File
@@ -37,6 +37,7 @@ export function FlowTable({ range }: { range: Range }) {
const { data: rollups } = useQuery(flowRollupsQueryOptions(range)) const { data: rollups } = useQuery(flowRollupsQueryOptions(range))
const flows = [...(data?.data ?? [])].sort(byRecency) const flows = [...(data?.data ?? [])].sort(byRecency)
// Rollups name the flow by id, as every list here is keyed.
const activity = new Map<string, FlowRollup>( const activity = new Map<string, FlowRollup>(
(rollups ?? []).map((row: FlowRollup) => [row.flow, row]), (rollups ?? []).map((row: FlowRollup) => [row.flow, row]),
) )
@@ -104,9 +105,9 @@ export function FlowTable({ range }: { range: Range }) {
<tbody> <tbody>
{flows.map((flow) => ( {flows.map((flow) => (
<Row <Row
key={flow.name} key={flow.id}
flow={flow} flow={flow}
activity={activity.get(flow.name)} activity={activity.get(flow.id!)}
/> />
))} ))}
</tbody> </tbody>
@@ -132,11 +133,11 @@ function Row({
const toggle = useMutation({ const toggle = useMutation({
mutationFn: (next: boolean) => mutationFn: (next: boolean) =>
next next
? FlowsService.startFlow({ flowId: flow.name }) ? FlowsService.startFlow({ flowId: flow.id! })
: FlowsService.stopFlow({ flowId: flow.name }), : FlowsService.stopFlow({ flowId: flow.id! }),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: flowKeys.all }) queryClient.invalidateQueries({ queryKey: flowKeys.all })
queryClient.invalidateQueries({ queryKey: flowKeys.detail(flow.name) }) queryClient.invalidateQueries({ queryKey: flowKeys.detail(flow.id!) })
}, },
onError: () => showErrorToast("The flow could not be started or stopped."), onError: () => showErrorToast("The flow could not be started or stopped."),
}) })
@@ -151,8 +152,8 @@ function Row({
sizes to the longest name and pushes the page sideways. */} sizes to the longest name and pushes the page sideways. */}
<td className="max-w-0 px-4 py-2 sm:min-w-40"> <td className="max-w-0 px-4 py-2 sm:min-w-40">
<Link <Link
to="/flows/$flowName" to="/flows/$flowId"
params={{ flowName: flow.name }} params={{ flowId: flow.id! }}
className="block min-w-0" className="block min-w-0"
> >
<p className="truncate font-medium">{flow.title || flow.name}</p> <p className="truncate font-medium">{flow.title || flow.name}</p>
@@ -190,7 +190,7 @@ function Failure({ event }: { event: EventRow }) {
the card, and the rest is behind the chevron anyway. */} the card, and the rest is behind the chevron anyway. */}
<span className="min-w-0 flex-1 break-words"> <span className="min-w-0 flex-1 break-words">
<span className="font-mono text-sm"> <span className="font-mono text-sm">
{event.node || event.flow || "engine"} {event.node || event.flow_name || event.flow || "engine"}
</span> </span>
<span className="ml-2 text-sm text-muted-foreground">{first}</span> <span className="ml-2 text-sm text-muted-foreground">{first}</span>
</span> </span>
@@ -334,7 +334,7 @@ export function HealthActivity({ range }: { range: Range }) {
className="flex items-baseline gap-3 border-b border-border py-2 text-sm last:border-0" className="flex items-baseline gap-3 border-b border-border py-2 text-sm last:border-0"
> >
<span className="min-w-0 flex-1 truncate font-mono"> <span className="min-w-0 flex-1 truncate font-mono">
{run.flow} {run.flow_name || run.flow}
</span> </span>
{/* Five fixed columns do not fit a phone. What caused a run {/* Five fixed columns do not fit a phone. What caused a run
is the one a narrow row can do without — the status, the is the one a narrow row can do without — the status, the
@@ -439,7 +439,7 @@ export function HealthActivity({ range }: { range: Range }) {
{event.actor} {event.detail} {event.actor} {event.detail}
{event.flow ? ( {event.flow ? (
<span className="ml-1 font-mono text-muted-foreground"> <span className="ml-1 font-mono text-muted-foreground">
{event.flow} {event.flow_name || event.flow}
</span> </span>
) : null} ) : null}
</span> </span>
+4 -3
View File
@@ -70,13 +70,14 @@ export function NewRun({
const counts = new Map((overview ?? []).map((row) => [row.flow, row])) const counts = new Map((overview ?? []).map((row) => [row.flow, row]))
const rows = (flows?.data ?? []).map((one) => { const rows = (flows?.data ?? []).map((one) => {
const seen = counts.get(one.name) const seen = counts.get(one.id!)
const notes = [ const notes = [
one.mode === "batch" ? "batch" : "", one.mode === "batch" ? "batch" : "",
one.has_draft ? "draft" : "", one.has_draft ? "draft" : "",
].filter(Boolean) ].filter(Boolean)
return { return {
flow: one.name, flow: one.id!,
flow_name: one.name,
runs: seen?.runs ?? 0, runs: seen?.runs ?? 0,
running: seen?.running ?? 0, running: seen?.running ?? 0,
queued: seen?.queued ?? 0, queued: seen?.queued ?? 0,
@@ -106,7 +107,7 @@ export function NewRun({
</div> </div>
{flow && ( {flow && (
<Button variant="outline" size="sm" className="h-8" asChild> <Button variant="outline" size="sm" className="h-8" asChild>
<Link to="/flows/$flowName" params={{ flowName: flow }}> <Link to="/flows/$flowId" params={{ flowId: flow }}>
<SquarePen className="size-3.5" /> <SquarePen className="size-3.5" />
Open in editor Open in editor
</Link> </Link>
@@ -34,12 +34,17 @@ const resultsName = (flow: string) => `${flow}_results`
* A flow with no results dashboard yet is offered one built from its own * A flow with no results dashboard yet is offered one built from its own
* declared ports, which is the shortest path from "I ran something" to "I can * declared ports, which is the shortest path from "I ran something" to "I can
* see it" — and an ordinary dashboard afterwards. * see it" — and an ordinary dashboard afterwards.
*
* `flow` is the flow's id, which the generator takes; `flowName` its key,
* which the results dashboard is named after.
*/ */
export function OpenInDashboard({ export function OpenInDashboard({
flow, flow,
flowName,
ids, ids,
}: { }: {
flow?: string flow?: string
flowName?: string
ids: string[] ids: string[]
}) { }) {
const navigate = useNavigate() const navigate = useNavigate()
@@ -48,32 +53,38 @@ export function OpenInDashboard({
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const { data } = useQuery(dashboardsQueryOptions()) const { data } = useQuery(dashboardsQueryOptions())
const show = (name: string) => { const show = (id: string) => {
setOpen(false) setOpen(false)
navigate({ navigate({
to: "/view/$name", to: "/view/$id",
params: { name }, params: { id },
search: { runs: ids.join(",") }, search: { runs: ids.join(",") },
}) })
} }
const dashboards = data?.data ?? []
const label = flowName || flow
const results = flowName ? resultsName(flowName) : ""
const generate = useMutation({ const generate = useMutation({
mutationFn: (name: string) => mutationFn: (flowId: string) =>
DashboardsService.generateResultsDashboard({ flowId: name }), DashboardsService.generateResultsDashboard({ flowId }),
onSuccess: (made) => { onSuccess: (made) => {
client.invalidateQueries({ queryKey: dashboardKeys.all }) client.invalidateQueries({ queryKey: dashboardKeys.all })
show(made.name) show(made.id!)
}, },
onError: (error: { status?: number }) => { onError: async (error: { status?: number }) => {
// Someone else made it between the listing and the click; it is the one // Someone else made it between the listing and the click; it is the one
// that was wanted either way. // that was wanted either way. The refusal does not say its id.
if (error.status === 409 && flow) return show(resultsName(flow)) if (error.status === 409 && results) {
const found = await DashboardsService.readDashboards({ name: results })
const made = found.data[0]?.id
if (made) return show(made)
}
showErrorToast("Could not build a results dashboard for this flow") showErrorToast("Could not build a results dashboard for this flow")
}, },
}) })
const dashboards = data?.data ?? []
const results = flow ? resultsName(flow) : ""
const hasResults = dashboards.some((one) => one.name === results) const hasResults = dashboards.some((one) => one.name === results)
if (ids.length === 0) return null if (ids.length === 0) return null
@@ -98,22 +109,22 @@ export function OpenInDashboard({
{flow && !hasResults ? ( {flow && !hasResults ? (
<CommandGroup> <CommandGroup>
<CommandItem <CommandItem
value={`build results ${flow}`} value={`build results ${label}`}
onSelect={() => generate.mutate(flow)} onSelect={() => generate.mutate(flow)}
disabled={generate.isPending} disabled={generate.isPending}
> >
{generate.isPending {generate.isPending
? "Building…" ? "Building…"
: `Build a results dashboard for ${flow}`} : `Build a results dashboard for ${label}`}
</CommandItem> </CommandItem>
</CommandGroup> </CommandGroup>
) : null} ) : null}
<CommandGroup> <CommandGroup>
{dashboards.map((one) => ( {dashboards.map((one) => (
<CommandItem <CommandItem
key={one.name} key={one.id}
value={`${one.name} ${one.title}`} value={`${one.name} ${one.title}`}
onSelect={() => show(one.name)} onSelect={() => show(one.id!)}
> >
{one.title || one.name} {one.title || one.name}
{one.name === results ? ( {one.name === results ? (
+6 -2
View File
@@ -87,7 +87,7 @@ export function RunDetail({ id }: { id: string }) {
search={{ flow: run.flow }} search={{ flow: run.flow }}
className="text-muted-foreground text-sm hover:underline" className="text-muted-foreground text-sm hover:underline"
> >
{run.flow} {run.flow_name || run.flow}
</Link> </Link>
<h1 className="font-mono font-semibold text-xl">{shortId(run.id)}</h1> <h1 className="font-mono font-semibold text-xl">{shortId(run.id)}</h1>
<RunStatusBadge run={run} /> <RunStatusBadge run={run} />
@@ -115,7 +115,11 @@ export function RunDetail({ id }: { id: string }) {
)} )}
<div className="ml-auto flex items-center gap-2"> <div className="ml-auto flex items-center gap-2">
<OpenInDashboard flow={run.flow} ids={[run.id]} /> <OpenInDashboard
flow={run.flow}
flowName={run.flow_name}
ids={[run.id]}
/>
{isLive(run.status) ? ( {isLive(run.status) ? (
<Button <Button
variant="outline" variant="outline"
+15 -9
View File
@@ -166,7 +166,10 @@ export function RunsScreen({
<section className="flex min-w-0 flex-1 flex-col gap-4"> <section className="flex min-w-0 flex-1 flex-col gap-4">
<header className="flex flex-wrap items-center gap-3"> <header className="flex flex-wrap items-center gap-3">
<h1 className="mr-auto font-semibold text-2xl"> <h1 className="mr-auto font-semibold text-2xl">
{search.flow ?? "Runs"} {search.flow
? overview?.find((row) => row.flow === search.flow)?.flow_name ||
search.flow
: "Runs"}
</h1> </h1>
<Button variant="brand" size="sm" className="h-8" asChild> <Button variant="brand" size="sm" className="h-8" asChild>
@@ -301,7 +304,7 @@ export function RunsScreen({
ids={selected} ids={selected}
search={search} search={search}
update={update} update={update}
flow={runs.find((run) => run.id === selected[0])?.flow} run={runs.find((run) => run.id === selected[0])}
/> />
)} )}
@@ -315,7 +318,9 @@ export function RunsScreen({
} }
export type RailRow = { export type RailRow = {
/** The flow's id; `flow_name`, its key, is what the rail shows. */
flow: string flow: string
flow_name?: string
runs: number runs: number
running: number running: number
queued: number queued: number
@@ -387,7 +392,7 @@ export function FlowRail({
{rows.map((row) => {rows.map((row) =>
entry( entry(
row.flow, row.flow,
row.flow, row.flow_name || row.flow,
row.runs, row.runs,
row.running + row.queued, row.running + row.queued,
active === row.flow, active === row.flow,
@@ -548,11 +553,11 @@ function RunsTable({
{showFlow && ( {showFlow && (
<TableCell className="text-sm"> <TableCell className="text-sm">
<Link <Link
to="/flows/$flowName" to="/flows/$flowId"
params={{ flowName: run.flow }} params={{ flowId: run.flow }}
className="text-muted-foreground hover:underline" className="text-muted-foreground hover:underline"
> >
{run.flow} {run.flow_name || run.flow}
</Link> </Link>
</TableCell> </TableCell>
)} )}
@@ -623,12 +628,13 @@ function Compare({
ids, ids,
search, search,
update, update,
flow, run,
}: { }: {
ids: string[] ids: string[]
search: RunsSearch search: RunsSearch
update: (next: Partial<RunsSearch>) => void update: (next: Partial<RunsSearch>) => void
flow?: string /** The first one picked, whose flow a results dashboard would be for. */
run?: RunRow
}) { }) {
const names = useMetricNames(ids[0]) const names = useMetricNames(ids[0])
const metric = const metric =
@@ -666,7 +672,7 @@ function Compare({
} }
/> />
)} )}
<OpenInDashboard flow={flow} ids={ids} /> <OpenInDashboard flow={run?.flow} flowName={run?.flow_name} ids={ids} />
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
+51 -51
View File
@@ -25,9 +25,9 @@ import { Route as LayoutWorkersRouteImport } from './routes/_layout/workers'
import { Route as OauthAuthorizeRouteImport } from './routes/oauth.authorize' import { Route as OauthAuthorizeRouteImport } from './routes/oauth.authorize'
import { Route as PanelIndexRouteImport } from './routes/panel.index' import { Route as PanelIndexRouteImport } from './routes/panel.index'
import { Route as PanelIdRouteImport } from './routes/panel.$id' import { Route as PanelIdRouteImport } from './routes/panel.$id'
import { Route as ViewNameRouteImport } from './routes/view.$name' import { Route as ViewIdRouteImport } from './routes/view.$id'
import { Route as CanvasDashboardsNameRouteImport } from './routes/_canvas/dashboards/$name' import { Route as CanvasDashboardsIdRouteImport } from './routes/_canvas/dashboards/$id'
import { Route as CanvasFlowsFlowNameRouteImport } from './routes/_canvas/flows/$flowName' import { Route as CanvasFlowsFlowIdRouteImport } from './routes/_canvas/flows/$flowId'
import { Route as LayoutDashboardsIndexRouteImport } from './routes/_layout/dashboards/index' import { Route as LayoutDashboardsIndexRouteImport } from './routes/_layout/dashboards/index'
import { Route as LayoutDevicesIndexRouteImport } from './routes/_layout/devices/index' import { Route as LayoutDevicesIndexRouteImport } from './routes/_layout/devices/index'
import { Route as LayoutDevicesIdRouteImport } from './routes/_layout/devices/$id' import { Route as LayoutDevicesIdRouteImport } from './routes/_layout/devices/$id'
@@ -114,19 +114,19 @@ const PanelIdRoute = PanelIdRouteImport.update({
path: '/panel/$id', path: '/panel/$id',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const ViewNameRoute = ViewNameRouteImport.update({ const ViewIdRoute = ViewIdRouteImport.update({
id: '/view/$name', id: '/view/$id',
path: '/view/$name', path: '/view/$id',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const CanvasDashboardsNameRoute = CanvasDashboardsNameRouteImport.update({ const CanvasDashboardsIdRoute = CanvasDashboardsIdRouteImport.update({
id: '/dashboards/$name', id: '/dashboards/$id',
path: '/dashboards/$name', path: '/dashboards/$id',
getParentRoute: () => CanvasRoute, getParentRoute: () => CanvasRoute,
} as any) } as any)
const CanvasFlowsFlowNameRoute = CanvasFlowsFlowNameRouteImport.update({ const CanvasFlowsFlowIdRoute = CanvasFlowsFlowIdRouteImport.update({
id: '/flows/$flowName', id: '/flows/$flowId',
path: '/flows/$flowName', path: '/flows/$flowId',
getParentRoute: () => CanvasRoute, getParentRoute: () => CanvasRoute,
} as any) } as any)
const LayoutDashboardsIndexRoute = LayoutDashboardsIndexRouteImport.update({ const LayoutDashboardsIndexRoute = LayoutDashboardsIndexRouteImport.update({
@@ -179,10 +179,10 @@ export interface FileRoutesByFullPath {
'/workers': typeof LayoutWorkersRoute '/workers': typeof LayoutWorkersRoute
'/oauth/authorize': typeof OauthAuthorizeRoute '/oauth/authorize': typeof OauthAuthorizeRoute
'/panel/$id': typeof PanelIdRoute '/panel/$id': typeof PanelIdRoute
'/view/$name': typeof ViewNameRoute '/view/$id': typeof ViewIdRoute
'/panel/': typeof PanelIndexRoute '/panel/': typeof PanelIndexRoute
'/dashboards/$name': typeof CanvasDashboardsNameRoute '/dashboards/$id': typeof CanvasDashboardsIdRoute
'/flows/$flowName': typeof CanvasFlowsFlowNameRoute '/flows/$flowId': typeof CanvasFlowsFlowIdRoute
'/devices/$id': typeof LayoutDevicesIdRoute '/devices/$id': typeof LayoutDevicesIdRoute
'/runs/$id': typeof LayoutRunsIdRoute '/runs/$id': typeof LayoutRunsIdRoute
'/runs/new': typeof LayoutRunsNewRoute '/runs/new': typeof LayoutRunsNewRoute
@@ -205,10 +205,10 @@ export interface FileRoutesByTo {
'/workers': typeof LayoutWorkersRoute '/workers': typeof LayoutWorkersRoute
'/oauth/authorize': typeof OauthAuthorizeRoute '/oauth/authorize': typeof OauthAuthorizeRoute
'/panel/$id': typeof PanelIdRoute '/panel/$id': typeof PanelIdRoute
'/view/$name': typeof ViewNameRoute '/view/$id': typeof ViewIdRoute
'/panel': typeof PanelIndexRoute '/panel': typeof PanelIndexRoute
'/dashboards/$name': typeof CanvasDashboardsNameRoute '/dashboards/$id': typeof CanvasDashboardsIdRoute
'/flows/$flowName': typeof CanvasFlowsFlowNameRoute '/flows/$flowId': typeof CanvasFlowsFlowIdRoute
'/devices/$id': typeof LayoutDevicesIdRoute '/devices/$id': typeof LayoutDevicesIdRoute
'/runs/$id': typeof LayoutRunsIdRoute '/runs/$id': typeof LayoutRunsIdRoute
'/runs/new': typeof LayoutRunsNewRoute '/runs/new': typeof LayoutRunsNewRoute
@@ -233,11 +233,11 @@ export interface FileRoutesById {
'/_layout/workers': typeof LayoutWorkersRoute '/_layout/workers': typeof LayoutWorkersRoute
'/oauth/authorize': typeof OauthAuthorizeRoute '/oauth/authorize': typeof OauthAuthorizeRoute
'/panel/$id': typeof PanelIdRoute '/panel/$id': typeof PanelIdRoute
'/view/$name': typeof ViewNameRoute '/view/$id': typeof ViewIdRoute
'/_layout/': typeof LayoutIndexRoute '/_layout/': typeof LayoutIndexRoute
'/panel/': typeof PanelIndexRoute '/panel/': typeof PanelIndexRoute
'/_canvas/dashboards/$name': typeof CanvasDashboardsNameRoute '/_canvas/dashboards/$id': typeof CanvasDashboardsIdRoute
'/_canvas/flows/$flowName': typeof CanvasFlowsFlowNameRoute '/_canvas/flows/$flowId': typeof CanvasFlowsFlowIdRoute
'/_layout/devices/$id': typeof LayoutDevicesIdRoute '/_layout/devices/$id': typeof LayoutDevicesIdRoute
'/_layout/runs/$id': typeof LayoutRunsIdRoute '/_layout/runs/$id': typeof LayoutRunsIdRoute
'/_layout/runs/new': typeof LayoutRunsNewRoute '/_layout/runs/new': typeof LayoutRunsNewRoute
@@ -262,10 +262,10 @@ export interface FileRouteTypes {
| '/workers' | '/workers'
| '/oauth/authorize' | '/oauth/authorize'
| '/panel/$id' | '/panel/$id'
| '/view/$name' | '/view/$id'
| '/panel/' | '/panel/'
| '/dashboards/$name' | '/dashboards/$id'
| '/flows/$flowName' | '/flows/$flowId'
| '/devices/$id' | '/devices/$id'
| '/runs/$id' | '/runs/$id'
| '/runs/new' | '/runs/new'
@@ -288,10 +288,10 @@ export interface FileRouteTypes {
| '/workers' | '/workers'
| '/oauth/authorize' | '/oauth/authorize'
| '/panel/$id' | '/panel/$id'
| '/view/$name' | '/view/$id'
| '/panel' | '/panel'
| '/dashboards/$name' | '/dashboards/$id'
| '/flows/$flowName' | '/flows/$flowId'
| '/devices/$id' | '/devices/$id'
| '/runs/$id' | '/runs/$id'
| '/runs/new' | '/runs/new'
@@ -315,11 +315,11 @@ export interface FileRouteTypes {
| '/_layout/workers' | '/_layout/workers'
| '/oauth/authorize' | '/oauth/authorize'
| '/panel/$id' | '/panel/$id'
| '/view/$name' | '/view/$id'
| '/_layout/' | '/_layout/'
| '/panel/' | '/panel/'
| '/_canvas/dashboards/$name' | '/_canvas/dashboards/$id'
| '/_canvas/flows/$flowName' | '/_canvas/flows/$flowId'
| '/_layout/devices/$id' | '/_layout/devices/$id'
| '/_layout/runs/$id' | '/_layout/runs/$id'
| '/_layout/runs/new' | '/_layout/runs/new'
@@ -338,7 +338,7 @@ export interface RootRouteChildren {
SignupRoute: typeof SignupRoute SignupRoute: typeof SignupRoute
OauthAuthorizeRoute: typeof OauthAuthorizeRoute OauthAuthorizeRoute: typeof OauthAuthorizeRoute
PanelIdRoute: typeof PanelIdRoute PanelIdRoute: typeof PanelIdRoute
ViewNameRoute: typeof ViewNameRoute ViewIdRoute: typeof ViewIdRoute
PanelIndexRoute: typeof PanelIndexRoute PanelIndexRoute: typeof PanelIndexRoute
} }
@@ -456,25 +456,25 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof PanelIdRouteImport preLoaderRoute: typeof PanelIdRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/view/$name': { '/view/$id': {
id: '/view/$name' id: '/view/$id'
path: '/view/$name' path: '/view/$id'
fullPath: '/view/$name' fullPath: '/view/$id'
preLoaderRoute: typeof ViewNameRouteImport preLoaderRoute: typeof ViewIdRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/_canvas/dashboards/$name': { '/_canvas/dashboards/$id': {
id: '/_canvas/dashboards/$name' id: '/_canvas/dashboards/$id'
path: '/dashboards/$name' path: '/dashboards/$id'
fullPath: '/dashboards/$name' fullPath: '/dashboards/$id'
preLoaderRoute: typeof CanvasDashboardsNameRouteImport preLoaderRoute: typeof CanvasDashboardsIdRouteImport
parentRoute: typeof CanvasRoute parentRoute: typeof CanvasRoute
} }
'/_canvas/flows/$flowName': { '/_canvas/flows/$flowId': {
id: '/_canvas/flows/$flowName' id: '/_canvas/flows/$flowId'
path: '/flows/$flowName' path: '/flows/$flowId'
fullPath: '/flows/$flowName' fullPath: '/flows/$flowId'
preLoaderRoute: typeof CanvasFlowsFlowNameRouteImport preLoaderRoute: typeof CanvasFlowsFlowIdRouteImport
parentRoute: typeof CanvasRoute parentRoute: typeof CanvasRoute
} }
'/_layout/dashboards/': { '/_layout/dashboards/': {
@@ -530,13 +530,13 @@ declare module '@tanstack/react-router' {
} }
interface CanvasRouteChildren { interface CanvasRouteChildren {
CanvasDashboardsNameRoute: typeof CanvasDashboardsNameRoute CanvasDashboardsIdRoute: typeof CanvasDashboardsIdRoute
CanvasFlowsFlowNameRoute: typeof CanvasFlowsFlowNameRoute CanvasFlowsFlowIdRoute: typeof CanvasFlowsFlowIdRoute
} }
const CanvasRouteChildren: CanvasRouteChildren = { const CanvasRouteChildren: CanvasRouteChildren = {
CanvasDashboardsNameRoute: CanvasDashboardsNameRoute, CanvasDashboardsIdRoute: CanvasDashboardsIdRoute,
CanvasFlowsFlowNameRoute: CanvasFlowsFlowNameRoute, CanvasFlowsFlowIdRoute: CanvasFlowsFlowIdRoute,
} }
const CanvasRouteWithChildren = const CanvasRouteWithChildren =
@@ -588,7 +588,7 @@ const rootRouteChildren: RootRouteChildren = {
SignupRoute: SignupRoute, SignupRoute: SignupRoute,
OauthAuthorizeRoute: OauthAuthorizeRoute, OauthAuthorizeRoute: OauthAuthorizeRoute,
PanelIdRoute: PanelIdRoute, PanelIdRoute: PanelIdRoute,
ViewNameRoute: ViewNameRoute, ViewIdRoute: ViewIdRoute,
PanelIndexRoute: PanelIndexRoute, PanelIndexRoute: PanelIndexRoute,
} }
export const routeTree = rootRouteImport export const routeTree = rootRouteImport
@@ -8,33 +8,36 @@ import { useFlowSocket } from "@/components/Flow/useFlowSocket"
type Search = { edit?: boolean } type Search = { edit?: boolean }
export const Route = createFileRoute("/_canvas/dashboards/$name")({ export const Route = createFileRoute("/_canvas/dashboards/$id")({
component: DashboardRoute, component: DashboardRoute,
// Edit mode is a search param so viewing stays the default a panel opens // Edit mode is a search param so viewing stays the default a panel opens
// into, and an editing session is a link someone can send. // into, and an editing session is a link someone can send.
validateSearch: (search: Record<string, unknown>): Search => ({ validateSearch: (search: Record<string, unknown>): Search => ({
edit: search.edit === true || search.edit === "true" || undefined, edit: search.edit === true || search.edit === "true" || undefined,
}), }),
head: ({ params }) => ({ meta: [{ title: `${params.name} - Fluksio` }] }),
}) })
function DashboardRoute() { function DashboardRoute() {
const { name } = Route.useParams() const { id } = Route.useParams()
const { edit } = Route.useSearch() const { edit } = Route.useSearch()
// Widgets read live values; the canvas shell has no socket of its own. // Widgets read live values; the canvas shell has no socket of its own.
useFlowSocket() useFlowSocket()
// The working copy: an edit is the editor's until it is published, so what // The working copy: an edit is the editor's until it is published, so what
// a wall panel is showing right now stays untouched by this session. // a wall panel is showing right now stays untouched by this session.
const { data: dashboard } = useQuery(dashboardQueryOptions(name, true)) const { data: dashboard } = useQuery(dashboardQueryOptions(id, true))
if (!dashboard) return null if (!dashboard) return null
return ( return (
<>
{/* From the document, since the id in the address can be opaque. */}
<title>{`${dashboard.title || dashboard.name} - Fluksio`}</title>
<DashboardEditor <DashboardEditor
// Leaving edit mode drops the draft, so the session starts clean. // Leaving edit mode drops the draft, so the session starts clean.
key={`${name}:${edit ? "edit" : "view"}`} key={`${id}:${edit ? "edit" : "view"}`}
dashboard={dashboard as Dashboard} dashboard={dashboard as Dashboard}
edit={Boolean(edit)} edit={Boolean(edit)}
/> />
</>
) )
} }
@@ -6,7 +6,9 @@ import { Skeleton } from "@/components/ui/skeleton"
type Search = { node?: string } type Search = { node?: string }
export const Route = createFileRoute("/_canvas/flows/$flowName")({ // The tab title comes from the loaded document (`FlowEditor`): the id in the
// address is opaque for a flow made here.
export const Route = createFileRoute("/_canvas/flows/$flowId")({
component: FlowRoute, component: FlowRoute,
// Which node, or input or output label, to arrive on. A search param rather // Which node, or input or output label, to arrive on. A search param rather
// than a hash so the brain graph's click-through — and any link out of an // than a hash so the brain graph's click-through — and any link out of an
@@ -14,9 +16,6 @@ export const Route = createFileRoute("/_canvas/flows/$flowName")({
validateSearch: (search: Record<string, unknown>): Search => ({ validateSearch: (search: Record<string, unknown>): Search => ({
node: typeof search.node === "string" ? search.node : undefined, node: typeof search.node === "string" ? search.node : undefined,
}), }),
head: ({ params }) => ({
meta: [{ title: `${params.flowName} - Fluksio` }],
}),
}) })
function Loading() { function Loading() {
@@ -28,12 +27,12 @@ function Loading() {
} }
function FlowRoute() { function FlowRoute() {
const { flowName } = Route.useParams() const { flowId } = Route.useParams()
const { node } = Route.useSearch() const { node } = Route.useSearch()
return ( return (
<Suspense fallback={<Loading />}> <Suspense fallback={<Loading />}>
<FlowEditor flowName={flowName} focus={node} /> <FlowEditor flowId={flowId} focus={node} />
</Suspense> </Suspense>
) )
} }
@@ -51,14 +51,20 @@ function Dashboards() {
queryClient.invalidateQueries({ queryKey: dashboardKeys.all }) queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
setDialogOpen(false) setDialogOpen(false)
navigate({ navigate({
to: "/dashboards/$name", to: "/dashboards/$id",
params: { name: created.name }, params: { id: created.id! },
search: { edit: true }, search: { edit: true },
}) })
}, },
onError: handleError.bind(showErrorToast), onError: handleError.bind(showErrorToast),
}) })
// Selections and requests go by id; a person reads the title or the key.
const labelOf = (id: string) => {
const dashboard = data?.data.find((d) => d.id === id)
return dashboard ? dashboard.title || dashboard.name : id
}
// The summary carries the working copy's version, which is the one publishing // The summary carries the working copy's version, which is the one publishing
// is based on — so the list already holds everything this needs. // is based on — so the list already holds everything this needs.
const publishAll = usePublishAll( const publishAll = usePublishAll(
@@ -66,11 +72,12 @@ function Dashboards() {
DashboardsService.publishDashboard({ DashboardsService.publishDashboard({
dashboardId: dashboard, dashboardId: dashboard,
requestBody: { requestBody: {
version: data?.data.find((d) => d.name === dashboard)?.version ?? 1, version: data?.data.find((d) => d.id === dashboard)?.version ?? 1,
}, },
}), }),
"dashboard", "dashboard",
() => queryClient.invalidateQueries({ queryKey: dashboardKeys.all }), () => queryClient.invalidateQueries({ queryKey: dashboardKeys.all }),
labelOf,
) )
// The store only accepts this shape, so say so before the request does. // The store only accepts this shape, so say so before the request does.
@@ -84,14 +91,15 @@ function Dashboards() {
) )
const drafts = (data?.data ?? []) const drafts = (data?.data ?? [])
.filter((dashboard) => dashboard.has_draft) .filter((dashboard) => dashboard.has_draft)
.map((dashboard) => dashboard.name) .map((dashboard) => dashboard.id!)
const selection = useSelection(dashboards.map((dashboard) => dashboard.name)) const selection = useSelection(dashboards.map((dashboard) => dashboard.id!))
const remove = useDeleteSelected( const remove = useDeleteSelected(
(dashboard) => (dashboard) =>
DashboardsService.deleteDashboard({ dashboardId: dashboard }), DashboardsService.deleteDashboard({ dashboardId: dashboard }),
"dashboard", "dashboard",
() => queryClient.invalidateQueries({ queryKey: dashboardKeys.all }), () => queryClient.invalidateQueries({ queryKey: dashboardKeys.all }),
labelOf,
) )
const duplicate = useDuplicateSelected( const duplicate = useDuplicateSelected(
@@ -102,6 +110,7 @@ function Dashboards() {
selection.clear() selection.clear()
queryClient.invalidateQueries({ queryKey: dashboardKeys.all }) queryClient.invalidateQueries({ queryKey: dashboardKeys.all })
}, },
labelOf,
) )
return ( return (
@@ -167,7 +176,7 @@ function Dashboards() {
<ConfirmDelete <ConfirmDelete
open={deleteOpen} open={deleteOpen}
onOpenChange={setDeleteOpen} onOpenChange={setDeleteOpen}
names={selection.selected} names={selection.selected.map(labelOf)}
noun="dashboard" noun="dashboard"
pending={remove.isPending} pending={remove.isPending}
onConfirm={() => { onConfirm={() => {
@@ -192,10 +201,10 @@ function Dashboards() {
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3"> <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{dashboards.map((dashboard) => ( {dashboards.map((dashboard) => (
<OverviewCard <OverviewCard
key={dashboard.name} key={dashboard.id}
link={{ link={{
to: "/dashboards/$name", to: "/dashboards/$id",
params: { name: dashboard.name }, params: { id: dashboard.id! },
}} }}
icon={LayoutDashboard} icon={LayoutDashboard}
title={dashboard.title || dashboard.name} title={dashboard.title || dashboard.name}
@@ -204,8 +213,8 @@ function Dashboards() {
dashboard.widget_count === 1 ? "" : "s" dashboard.widget_count === 1 ? "" : "s"
}`} }`}
selecting={selection.selecting} selecting={selection.selecting}
selected={selection.selected.includes(dashboard.name)} selected={selection.selected.includes(dashboard.id!)}
onToggle={() => selection.toggle(dashboard.name)} onToggle={() => selection.toggle(dashboard.id!)}
testId="dashboard-card" testId="dashboard-card"
/> />
))} ))}
+24 -12
View File
@@ -47,20 +47,29 @@ function Flows() {
const [deleteOpen, setDeleteOpen] = useState(false) const [deleteOpen, setDeleteOpen] = useState(false)
const [withRuns, setWithRuns] = useState(false) const [withRuns, setWithRuns] = useState(false)
// The server issues the id, so the new flow is opened by what it answers.
const create = useMutation({ const create = useMutation({
mutationFn: (flow: string) => mutationFn: (flow: string) =>
FlowsService.saveFlow({ FlowsService.createFlow({
flowId: flow,
requestBody: { name: flow, nodes: [], inputs: [] }, requestBody: { name: flow, nodes: [], inputs: [] },
}), }),
onSuccess: (_saved, flow) => { onSuccess: (created) => {
queryClient.invalidateQueries({ queryKey: flowKeys.all }) queryClient.invalidateQueries({ queryKey: flowKeys.all })
setDialogOpen(false) setDialogOpen(false)
navigate({ to: "/flows/$flowName", params: { flowName: flow } }) navigate({
to: "/flows/$flowId",
params: { flowId: created.definition.id! },
})
}, },
onError: handleError.bind(showErrorToast), onError: handleError.bind(showErrorToast),
}) })
// Selections and requests go by id; a person reads the title or the key.
const labelOf = (id: string) => {
const flow = data?.data.find((f) => f.id === id)
return flow ? flow.title || flow.name : id
}
// The summary carries the working copy's version, which is the one publishing // The summary carries the working copy's version, which is the one publishing
// is based on — so the list already holds everything this needs. // is based on — so the list already holds everything this needs.
const publishAll = usePublishAll( const publishAll = usePublishAll(
@@ -68,11 +77,12 @@ function Flows() {
FlowsService.publishFlow({ FlowsService.publishFlow({
flowId: flow, flowId: flow,
requestBody: { requestBody: {
version: data?.data.find((f) => f.name === flow)?.version ?? 1, version: data?.data.find((f) => f.id === flow)?.version ?? 1,
}, },
}), }),
"flow", "flow",
() => queryClient.invalidateQueries({ queryKey: flowKeys.all }), () => queryClient.invalidateQueries({ queryKey: flowKeys.all }),
labelOf,
) )
const slug = name const slug = name
@@ -85,9 +95,9 @@ function Flows() {
) )
const drafts = (data?.data ?? []) const drafts = (data?.data ?? [])
.filter((flow) => flow.has_draft) .filter((flow) => flow.has_draft)
.map((flow) => flow.name) .map((flow) => flow.id!)
const selection = useSelection(flows.map((flow) => flow.name)) const selection = useSelection(flows.map((flow) => flow.id!))
const remove = useDeleteSelected( const remove = useDeleteSelected(
async (flow) => { async (flow) => {
await FlowsService.deleteFlow({ flowId: flow }) await FlowsService.deleteFlow({ flowId: flow })
@@ -95,6 +105,7 @@ function Flows() {
}, },
"flow", "flow",
() => queryClient.invalidateQueries({ queryKey: flowKeys.all }), () => queryClient.invalidateQueries({ queryKey: flowKeys.all }),
labelOf,
) )
const duplicate = useDuplicateSelected( const duplicate = useDuplicateSelected(
@@ -104,6 +115,7 @@ function Flows() {
selection.clear() selection.clear()
queryClient.invalidateQueries({ queryKey: flowKeys.all }) queryClient.invalidateQueries({ queryKey: flowKeys.all })
}, },
labelOf,
) )
return ( return (
@@ -173,7 +185,7 @@ function Flows() {
<ConfirmDelete <ConfirmDelete
open={deleteOpen} open={deleteOpen}
onOpenChange={setDeleteOpen} onOpenChange={setDeleteOpen}
names={selection.selected} names={selection.selected.map(labelOf)}
noun="flow" noun="flow"
pending={remove.isPending} pending={remove.isPending}
onConfirm={() => { onConfirm={() => {
@@ -204,8 +216,8 @@ function Flows() {
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3"> <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{flows.map((flow) => ( {flows.map((flow) => (
<OverviewCard <OverviewCard
key={flow.name} key={flow.id}
link={{ to: "/flows/$flowName", params: { flowName: flow.name } }} link={{ to: "/flows/$flowId", params: { flowId: flow.id! } }}
icon={Workflow} icon={Workflow}
title={flow.title || flow.name} title={flow.title || flow.name}
draft={flow.has_draft} draft={flow.has_draft}
@@ -215,8 +227,8 @@ function Flows() {
flow.error_count ? ` · ${flow.error_count} to fix` : "" flow.error_count ? ` · ${flow.error_count} to fix` : ""
}`} }`}
selecting={selection.selecting} selecting={selection.selecting}
selected={selection.selected.includes(flow.name)} selected={selection.selected.includes(flow.id!)}
onToggle={() => selection.toggle(flow.name)} onToggle={() => selection.toggle(flow.id!)}
testId="flow-card" testId="flow-card"
/> />
))} ))}
+9 -9
View File
@@ -20,7 +20,7 @@ import { cn } from "@/lib/utils"
* What a paired device shows: the dashboards it was assigned. The address * What a paired device shows: the dashboards it was assigned. The address
* stays `/panel/{id}`, which is what screens already hanging were pointed at. * stays `/panel/{id}`, which is what screens already hanging were pointed at.
* *
* The same full-bleed surface as `/view/{name}`, with a rail down the left * The same full-bleed surface as `/view/{id}`, with a rail down the left
* (along the bottom on a phone) when there is more than one to switch between — so a hallway tablet and a * (along the bottom on a phone) when there is more than one to switch between — so a hallway tablet and a
* workshop tablet can carry different sets without either dashboard knowing * workshop tablet can carry different sets without either dashboard knowing
* anything about the other. * anything about the other.
@@ -51,7 +51,7 @@ function PanelRoute() {
const { data: panel } = useQuery(deviceQueryOptions(id)) const { data: panel } = useQuery(deviceQueryOptions(id))
const dashboards = panel?.dashboards ?? [] const dashboards = panel?.dashboards ?? []
// A name in the URL that this panel no longer carries falls back to the // A dashboard in the URL that this panel no longer carries falls back to the
// first, which is what a dashboard removed from under a running panel does. // first, which is what a dashboard removed from under a running panel does.
const current = d && dashboards.includes(d) ? d : dashboards[0] const current = d && dashboards.includes(d) ? d : dashboards[0]
@@ -86,12 +86,12 @@ function PanelRoute() {
// Which way along the rail the dashboard shown was reached, so its tiles // Which way along the rail the dashboard shown was reached, so its tiles
// come in from that side: further down it (1) from below, as a round // come in from that side: further down it (1) from below, as a round
// panel's next dashboard rises, and further up (-1) from above. // panel's next dashboard rises, and further up (-1) from above.
const shown = dashboard?.name const shown = dashboard?.id
const [turned, setTurned] = useState({ name: shown, by: 1 }) const [turned, setTurned] = useState({ id: shown, by: 1 })
if (shown !== turned.name) { if (shown !== turned.id) {
const by = const by =
dashboards.indexOf(shown ?? "") - dashboards.indexOf(turned.name ?? "") dashboards.indexOf(shown ?? "") - dashboards.indexOf(turned.id ?? "")
setTurned({ name: shown, by: by < 0 ? -1 : 1 }) setTurned({ id: shown, by: by < 0 ? -1 : 1 })
} }
// Said by the panel rather than by the dashboard: this is the screen, and // Said by the panel rather than by the dashboard: this is the screen, and
// whether it is touched or pointed at is a fact about the screen. A document // whether it is touched or pointed at is a fact about the screen. A document
@@ -151,10 +151,10 @@ function PanelRoute() {
dashboards={dashboards} dashboards={dashboards}
current={current} current={current}
horizontal={stacked} horizontal={stacked}
linkFor={(name) => ({ linkFor={(dashboardId) => ({
to: "/panel/$id", to: "/panel/$id",
params: { id }, params: { id },
search: { d: name }, search: { d: dashboardId },
})} })}
/> />
) : null ) : null
+1 -1
View File
@@ -50,7 +50,7 @@ function pairedPanel(): string {
* the panel it names, so a reboot comes back to the dashboard rather than * the panel it names, so a reboot comes back to the dashboard rather than
* asking the household for another code. * asking the household for another code.
* *
* Outside both shells like `/view/{name}`: until it is paired, this device has * Outside both shells like `/view/{id}`: until it is paired, this device has
* no session and there is nothing to put around it. * no session and there is nothing to put around it.
* *
* Reached through the portal as well, for a screen hanging where this * Reached through the portal as well, for a screen hanging where this
@@ -26,7 +26,7 @@ import { cn } from "@/lib/utils"
* same surface with a rail for switching between the dashboards it was * same surface with a rail for switching between the dashboards it was
* assigned. This route stays for a browser tab pointed straight at one. * assigned. This route stays for a browser tab pointed straight at one.
*/ */
export const Route = createFileRoute("/view/$name")({ export const Route = createFileRoute("/view/$id")({
component: PanelView, component: PanelView,
beforeLoad: async () => { beforeLoad: async () => {
if (!isLoggedIn()) { if (!isLoggedIn()) {
@@ -40,15 +40,14 @@ export const Route = createFileRoute("/view/$name")({
runs: runs:
typeof search.runs === "string" && search.runs ? search.runs : undefined, typeof search.runs === "string" && search.runs ? search.runs : undefined,
}), }),
head: ({ params }) => ({ meta: [{ title: `${params.name} - Fluksio` }] }),
}) })
function PanelView() { function PanelView() {
const { name } = Route.useParams() const { id } = Route.useParams()
const { runs } = Route.useSearch() const { runs } = Route.useSearch()
const navigate = useNavigate() const navigate = useNavigate()
useFlowSocket() useFlowSocket()
const { data: dashboard } = useQuery(dashboardQueryOptions(name)) const { data: dashboard } = useQuery(dashboardQueryOptions(id))
const stacked = useIsMobile() const stacked = useIsMobile()
const runIds = runIdsOf(runs) const runIds = runIdsOf(runs)
// A tab pointed at one dashboard is that dashboard, so its appearance // A tab pointed at one dashboard is that dashboard, so its appearance
@@ -73,14 +72,16 @@ function PanelView() {
)} )}
style={root.style} style={root.style}
> >
{/* From the document, since the id in the address can be opaque. */}
<title>{`${dashboard.title || dashboard.name} - Fluksio`}</title>
{runIds.length > 0 ? ( {runIds.length > 0 ? (
<RunsContextProvider runIds={runIds} dashboard={dashboard as Dashboard}> <RunsContextProvider runIds={runIds} dashboard={dashboard as Dashboard}>
<ContextBarFor <ContextBarFor
members={runIds} members={runIds}
onChange={(next) => onChange={(next) =>
navigate({ navigate({
to: "/view/$name", to: "/view/$id",
params: { name }, params: { id },
search: next.length ? { runs: next.join(",") } : {}, search: next.length ? { runs: next.join(",") } : {},
}) })
} }
+5 -3
View File
@@ -1,7 +1,9 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { deleteAll } from "./utils/api" import { deleteAll, openedFlowId } from "./utils/api"
const flowName = `test_clip_${Date.now().toString(36)}` const flowName = `test_clip_${Date.now().toString(36)}`
/** Issued by the server when the first test creates it in the app. */
let flowId = ""
const KEY = "fluksio.nodeClipboard" const KEY = "fluksio.nodeClipboard"
declare global { declare global {
@@ -17,7 +19,7 @@ test.use({
}) })
test.afterAll(async ({ browser }) => { test.afterAll(async ({ browser }) => {
await deleteAll(browser, [`/flows/${flowName}`]) await deleteAll(browser, [`/flows/${flowId}`])
}) })
test("the canvas clipboard yields to the native one", async ({ page }) => { test("the canvas clipboard yields to the native one", async ({ page }) => {
@@ -25,7 +27,7 @@ test("the canvas clipboard yields to the native one", async ({ page }) => {
await page.getByTestId("new-flow").click() await page.getByTestId("new-flow").click()
await page.getByTestId("new-flow-name").fill(flowName) await page.getByTestId("new-flow-name").fill(flowName)
await page.getByTestId("create-flow").click() await page.getByTestId("create-flow").click()
await page.waitForURL(`/flows/${flowName}`) flowId = await openedFlowId(page)
await page.getByTestId("add-node").click() await page.getByTestId("add-node").click()
await page await page
+11 -11
View File
@@ -1,6 +1,12 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* A colour disc sends once, at the end of the gesture. * A colour disc sends once, at the end of the gesture.
@@ -27,9 +33,7 @@ test.beforeAll(async ({ browser }) => {
// A node that only declares: nothing consumes the message, so a publish // A node that only declares: nothing consumes the message, so a publish
// reaches the graph without waking an engine run. The widget is what is // reaches the graph without waking an engine run. The widget is what is
// under test, not a flow. // under test, not a flow.
const madeFlow = await api(page, `/flows/${flowName}`, { const madeFlow = await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Colour drag", title: "Colour drag",
version: 1, version: 1,
@@ -44,10 +48,9 @@ test.beforeAll(async ({ browser }) => {
], ],
}, },
], ],
},
}) })
if (!madeFlow.ok()) if (!madeFlow.ok())
throw new Error(`flow PUT ${madeFlow.status()}: ${await madeFlow.text()}`) throw new Error(`flow POST ${madeFlow.status()}: ${await madeFlow.text()}`)
const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json() const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json()
await api(page, `/flows/${flowName}/publish`, { await api(page, `/flows/${flowName}/publish`, {
method: "POST", method: "POST",
@@ -65,11 +68,9 @@ test.beforeAll(async ({ browser }) => {
} }
// A leftover from a run that failed before its teardown would answer the // A leftover from a run that failed before its teardown would answer the
// create with a version conflict. // create with a conflict.
await api(page, `/dashboards/${dashboard}`, { method: "DELETE" }) await api(page, `/dashboards/${dashboard}`, { method: "DELETE" })
const madeBoard = await api(page, `/dashboards/${dashboard}`, { const madeBoard = await createDashboard(page, {
method: "PUT",
data: {
name: dashboard, name: dashboard,
title: "Colour drag", title: "Colour drag",
version: 0, version: 0,
@@ -96,7 +97,6 @@ test.beforeAll(async ({ browser }) => {
config: { target: `${flowName}.hex`, dtype: "str", format: "hex" }, config: { target: `${flowName}.hex`, dtype: "str", format: "hex" },
}, },
], ],
},
}) })
if (!madeBoard.ok()) if (!madeBoard.ok())
throw new Error( throw new Error(
+13 -11
View File
@@ -1,5 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, deleteAll } from "./utils/api" import { api, deleteAll, openedFlowId } from "./utils/api"
/** /**
* Editing writes a draft; only publishing hands it to the engine. The two * Editing writes a draft; only publishing hands it to the engine. The two
@@ -8,13 +8,15 @@ import { api, deleteAll } from "./utils/api"
*/ */
const flowName = `test_draft_${Date.now().toString(36)}` const flowName = `test_draft_${Date.now().toString(36)}`
/** Issued by the server when the first test creates it in the app. */
let flowId = ""
test.use({ storageState: "playwright/.auth/user.json" }) test.use({ storageState: "playwright/.auth/user.json" })
test.describe.configure({ mode: "serial" }) test.describe.configure({ mode: "serial" })
test.afterAll(async ({ browser }) => { test.afterAll(async ({ browser }) => {
await deleteAll(browser, [`/flows/${flowName}`]) await deleteAll(browser, [`/flows/${flowId}`])
}) })
test("a draft stays off the engine until it is published", async ({ page }) => { test("a draft stays off the engine until it is published", async ({ page }) => {
@@ -22,7 +24,7 @@ test("a draft stays off the engine until it is published", async ({ page }) => {
await page.getByTestId("new-flow").click() await page.getByTestId("new-flow").click()
await page.getByTestId("new-flow-name").fill(flowName) await page.getByTestId("new-flow-name").fill(flowName)
await page.getByTestId("create-flow").click() await page.getByTestId("create-flow").click()
await page.waitForURL(`/flows/${flowName}`) flowId = await openedFlowId(page)
await page.getByTestId("add-node").click() await page.getByTestId("add-node").click()
await page await page
@@ -39,7 +41,7 @@ test("a draft stays off the engine until it is published", async ({ page }) => {
// Nothing of this flow is loaded while it is only a draft. // Nothing of this flow is loaded while it is only a draft.
await page.waitForTimeout(1500) await page.waitForTimeout(1500)
const before = await (await api(page, `/flows/${flowName}/state`)).json() const before = await (await api(page, `/flows/${flowId}/state`)).json()
expect(before.nodes).toHaveLength(0) expect(before.nodes).toHaveLength(0)
await page.getByTestId("publish-flow").click() await page.getByTestId("publish-flow").click()
@@ -49,26 +51,26 @@ test("a draft stays off the engine until it is published", async ({ page }) => {
await expect(page.getByTestId("discard-draft")).toBeHidden() await expect(page.getByTestId("discard-draft")).toBeHidden()
await expect(page.getByTestId("publish-flow")).toBeDisabled() await expect(page.getByTestId("publish-flow")).toBeDisabled()
const after = await (await api(page, `/flows/${flowName}/state`)).json() const after = await (await api(page, `/flows/${flowId}/state`)).json()
expect(after.nodes.length).toBeGreaterThan(0) expect(after.nodes.length).toBeGreaterThan(0)
}) })
test("a save against a version someone else moved on from is refused", async ({ test("a save against a version someone else moved on from is refused", async ({
page, page,
}) => { }) => {
await page.goto(`/flows/${flowName}`) await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node") await page.waitForSelector(".react-flow__node")
const detail = await (await api(page, `/flows/${flowName}`)).json() const detail = await (await api(page, `/flows/${flowId}`)).json()
// Stand in for a second client that saved first. // Stand in for a second client that saved first.
const first = await api(page, `/flows/${flowName}`, { const first = await api(page, `/flows/${flowId}`, {
method: "PUT", method: "PUT",
data: { ...detail.definition, title: "Theirs" }, data: { ...detail.definition, title: "Theirs" },
}) })
expect(first.ok()).toBeTruthy() expect(first.ok()).toBeTruthy()
const stale = await api(page, `/flows/${flowName}`, { const stale = await api(page, `/flows/${flowId}`, {
method: "PUT", method: "PUT",
data: { ...detail.definition, title: "Mine" }, data: { ...detail.definition, title: "Mine" },
}) })
@@ -79,7 +81,7 @@ test("a save against a version someone else moved on from is refused", async ({
}) })
test("discarding a draft goes back to the published flow", async ({ page }) => { test("discarding a draft goes back to the published flow", async ({ page }) => {
await page.goto(`/flows/${flowName}`) await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node") await page.waitForSelector(".react-flow__node")
await page.getByTestId("discard-draft").click() await page.getByTestId("discard-draft").click()
@@ -87,7 +89,7 @@ test("discarding a draft goes back to the published flow", async ({ page }) => {
await expect(page.getByTestId("discard-draft")).toBeHidden() await expect(page.getByTestId("discard-draft")).toBeHidden()
await expect(page.getByTestId("publish-flow")).toBeDisabled() await expect(page.getByTestId("publish-flow")).toBeDisabled()
const detail = await (await api(page, `/flows/${flowName}`)).json() const detail = await (await api(page, `/flows/${flowId}`)).json()
expect(detail.has_draft).toBe(false) expect(detail.has_draft).toBe(false)
expect(detail.definition.title).not.toBe("Theirs") expect(detail.definition.title).not.toBe("Theirs")
}) })
+2 -2
View File
@@ -1,5 +1,5 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { api, apiPage, createDashboard, deleteAll } from "./utils/api"
/** /**
* The dashboard editor's quiet failures. * The dashboard editor's quiet failures.
@@ -41,7 +41,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/dashboards/${dashboardName}`, { method: "POST" }) await createDashboard(page, { name: dashboardName })
// The working copy, which is what a new dashboard may be: the editor reads // The working copy, which is what a new dashboard may be: the editor reads
// the draft, so the setup writes one rather than publishing. // the draft, so the setup writes one rather than publishing.
const dashboard = await ( const dashboard = await (
+9 -6
View File
@@ -1,5 +1,11 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* Dashboards and other flows appear on the canvas but are not part of the flow. * Dashboards and other flows appear on the canvas but are not part of the flow.
@@ -21,9 +27,7 @@ test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
// A flow reading a message, and a dashboard control that sets it. // A flow reading a message, and a dashboard control that sets it.
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
nodes: [ nodes: [
{ {
@@ -44,7 +48,6 @@ test.beforeAll(async ({ browser }) => {
}, },
], ],
version: 1, version: 1,
},
}) })
const saved = await (await api(page, `/flows/${flowName}`)).json() const saved = await (await api(page, `/flows/${flowName}`)).json()
await api(page, `/flows/${flowName}/publish`, { await api(page, `/flows/${flowName}/publish`, {
@@ -53,7 +56,7 @@ test.beforeAll(async ({ browser }) => {
}) })
const dashboard = await ( const dashboard = await (
await api(page, `/dashboards/${dashboardName}`, { method: "POST" }) await createDashboard(page, { name: dashboardName })
).json() ).json()
dashboard.widgets = [ dashboard.widgets = [
{ {
+15 -18
View File
@@ -1,6 +1,6 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { apiUrl } from "./config.ts" import { apiUrl } from "./config.ts"
import { api, deleteAll } from "./utils/api" import { api, createFlow, deleteAll, openedFlowId } from "./utils/api"
/** /**
* The flow editor's load-bearing behaviour: nodes are placed, connections come * The flow editor's load-bearing behaviour: nodes are placed, connections come
@@ -9,20 +9,22 @@ import { api, deleteAll } from "./utils/api"
*/ */
const flowName = `test_flow_${Date.now().toString(36)}` const flowName = `test_flow_${Date.now().toString(36)}`
/** Issued by the server when the first test creates it in the app. */
let flowId = ""
test.use({ storageState: "playwright/.auth/user.json" }) test.use({ storageState: "playwright/.auth/user.json" })
test.describe.configure({ mode: "serial" }) test.describe.configure({ mode: "serial" })
test.afterAll(async ({ browser }) => { test.afterAll(async ({ browser }) => {
await deleteAll(browser, [`/flows/${flowName}`]) await deleteAll(browser, [`/flows/${flowId}`])
}) })
/** Write a node's source through the API; typing code is not what we test. */ /** Write a node's source through the API; typing code is not what we test. */
async function setNodeSource(page: Page, nodeId: string, code: string) { async function setNodeSource(page: Page, nodeId: string, code: string) {
const token = await page.evaluate(() => localStorage.getItem("access_token")) const token = await page.evaluate(() => localStorage.getItem("access_token"))
const response = await page.request.put( const response = await page.request.put(
`${apiUrl}/api/v1/flows/${flowName}/nodes/${nodeId}/source`, `${apiUrl}/api/v1/flows/${flowId}/nodes/${nodeId}/source`,
{ headers: { Authorization: `Bearer ${token}` }, data: { code } }, { headers: { Authorization: `Bearer ${token}` }, data: { code } },
) )
expect(response.ok()).toBeTruthy() expect(response.ok()).toBeTruthy()
@@ -32,7 +34,7 @@ async function setNodeSource(page: Page, nodeId: string, code: string) {
async function nodeSource(page: Page, nodeId: string) { async function nodeSource(page: Page, nodeId: string) {
const token = await page.evaluate(() => localStorage.getItem("access_token")) const token = await page.evaluate(() => localStorage.getItem("access_token"))
const response = await page.request.get( const response = await page.request.get(
`${apiUrl}/api/v1/flows/${flowName}/nodes/${nodeId}/source`, `${apiUrl}/api/v1/flows/${flowId}/nodes/${nodeId}/source`,
{ headers: { Authorization: `Bearer ${token}` } }, { headers: { Authorization: `Bearer ${token}` } },
) )
expect(response.ok()).toBeTruthy() expect(response.ok()).toBeTruthy()
@@ -75,7 +77,7 @@ test("a flow can be created, wired up, and comes back after a reload", async ({
await page.getByTestId("new-flow").click() await page.getByTestId("new-flow").click()
await page.getByTestId("new-flow-name").fill(flowName) await page.getByTestId("new-flow-name").fill(flowName)
await page.getByTestId("create-flow").click() await page.getByTestId("create-flow").click()
await page.waitForURL(`/flows/${flowName}`) flowId = await openedFlowId(page)
await addFunctionNode(page, 1) await addFunctionNode(page, 1)
await addFunctionNode(page, 2) await addFunctionNode(page, 2)
@@ -94,7 +96,7 @@ test("a flow can be created, wired up, and comes back after a reload", async ({
}) })
test("running a flow puts values on its edges", async ({ page }) => { test("running a flow puts values on its edges", async ({ page }) => {
await page.goto(`/flows/${flowName}`) await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node") await page.waitForSelector(".react-flow__node")
await setNodeSource( await setNodeSource(
@@ -126,7 +128,7 @@ test("running a flow puts values on its edges", async ({ page }) => {
* a delete has to bring the code back with the node, not just the box. * a delete has to bring the code back with the node, not just the box.
*/ */
test("undo brings a deleted node back with its source", async ({ page }) => { test("undo brings a deleted node back with its source", async ({ page }) => {
await page.goto(`/flows/${flowName}`) await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node") await page.waitForSelector(".react-flow__node")
await page.locator(".react-flow__node").first().click() await page.locator(".react-flow__node").first().click()
@@ -156,9 +158,7 @@ test("a port's code name is a field only when it differs from its message", asyn
}) => { }) => {
const name = `test_ports_${Date.now().toString(36)}` const name = `test_ports_${Date.now().toString(36)}`
await page.goto("/") await page.goto("/")
const saved = await api(page, `/flows/${name}`, { const saved = await createFlow(page, {
method: "PUT",
data: {
name, name,
nodes: [ nodes: [
{ {
@@ -177,7 +177,6 @@ test("a port's code name is a field only when it differs from its message", asyn
}, },
], ],
inputs: [], inputs: [],
},
}) })
expect(saved.ok()).toBeTruthy() expect(saved.ok()).toBeTruthy()
try { try {
@@ -231,9 +230,10 @@ test("code typed into a node's editor is saved", async ({ page }) => {
const name = `test_code_${Date.now().toString(36)}` const name = `test_code_${Date.now().toString(36)}`
const text = "# level, other = 1, 2" const text = "# level, other = 1, 2"
await page.goto("/") await page.goto("/")
const saved = await api(page, `/flows/${name}`, { const saved = await createFlow(page, {
method: "PUT", name,
data: { name, nodes: [{ id: "writer", type: "python" }], inputs: [] }, nodes: [{ id: "writer", type: "python" }],
inputs: [],
}) })
expect(saved.ok()).toBeTruthy() expect(saved.ok()).toBeTruthy()
try { try {
@@ -262,9 +262,7 @@ test("code typed into a node's editor is saved", async ({ page }) => {
test("a JSON setting saves only text that parses", async ({ page }) => { test("a JSON setting saves only text that parses", async ({ page }) => {
const name = `test_json_${Date.now().toString(36)}` const name = `test_json_${Date.now().toString(36)}`
await page.goto("/") await page.goto("/")
const saved = await api(page, `/flows/${name}`, { const saved = await createFlow(page, {
method: "PUT",
data: {
name, name,
nodes: [ nodes: [
{ {
@@ -276,7 +274,6 @@ test("a JSON setting saves only text that parses", async ({ page }) => {
}, },
], ],
inputs: [], inputs: [],
},
}) })
expect(saved.ok()).toBeTruthy() expect(saved.ok()).toBeTruthy()
try { try {
+235
View File
@@ -0,0 +1,235 @@
import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api"
/**
* Objects made the ordinary way, with an id the server issues.
*
* Every other spec pins its id to its key, and with the two equal a key
* passed where an id belongs still works. Here they differ, so each place the
* app has to tell them apart is exercised: routes and API calls by id, live
* values, hooks and message names by key.
*/
const stamp = Date.now().toString(36)
const key = `test_ids_${stamp}`
const boardKey = `${key}_board`
const batchKey = `${key}_batch`
const FLOW_ID = /^f_[a-z2-7]{8}$/
const BOARD_ID = /^d_[a-z2-7]{8}$/
let flowId = ""
let boardId = ""
let batchId = ""
let runId = ""
let resultsId = ""
test.use({
storageState: "playwright/.auth/user.json",
permissions: ["clipboard-read", "clipboard-write"],
})
test.describe.configure({ mode: "serial" })
/** Publish a flow's working copy, whatever version it has reached. */
async function publishFlow(page: Page, id: string) {
const detail = await (await api(page, `/flows/${id}`)).json()
await api(page, `/flows/${id}/publish`, {
method: "POST",
data: { version: detail.definition.version },
})
}
test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser)
// A webhook feeding `level`, created without an id.
const flow = await api(page, "/flows/", {
method: "POST",
data: {
name: key,
nodes: [
{
id: "hook",
type: "http",
params: { url: "/ping", method: "POST" },
requires: [],
provides: [{ name: "level", dtype: "float" }],
},
],
},
})
expect(flow.status()).toBe(201)
flowId = (await flow.json()).definition.id
expect(flowId).toMatch(FLOW_ID)
// A dashboard reading it, bound by the flow's key.
const board = await api(page, "/dashboards/", {
method: "POST",
data: { name: boardKey, title: "Issued board" },
})
expect(board.status()).toBe(201)
const made = await board.json()
boardId = made.id
expect(boardId).toMatch(BOARD_ID)
const saved = await (
await api(page, `/dashboards/${boardId}`, {
method: "PUT",
data: {
...made,
widgets: [
{
id: "level",
type: "stat",
title: "Issued level",
layout: { lg: { x: 0, y: 0, w: 3, h: 2 } },
config: { message: `${key}.level`, dtype: "float" },
},
],
},
})
).json()
await api(page, `/dashboards/${boardId}/publish`, {
method: "POST",
data: { version: saved.version },
})
// A batch flow with one finished run, for its results dashboard.
const batch = await api(page, "/flows/", {
method: "POST",
data: {
name: batchKey,
mode: "batch",
outputs: ["score"],
nodes: [
{
id: "score",
type: "python",
provides: [{ name: "score", dtype: "float" }],
},
],
},
})
batchId = (await batch.json()).definition.id
expect(batchId).toMatch(FLOW_ID)
await api(page, `/flows/${batchId}/nodes/score/source`, {
method: "PUT",
data: { code: 'def process():\n return {"score": 1.5}\n' },
})
await publishFlow(page, batchId)
const run = await api(page, `/runs/flows/${batchId}`, {
method: "POST",
data: { params: {} },
})
expect(run.ok()).toBeTruthy()
runId = (await run.json()).id
await page.close()
})
test.afterAll(async ({ browser }) => {
await deleteAll(
browser,
[
resultsId && `/dashboards/${resultsId}`,
boardId && `/dashboards/${boardId}`,
flowId && `/flows/${flowId}`,
batchId && `/flows/${batchId}`,
// After the flow, as the editor does it, and only by its id.
batchId && `/runs?flow=${batchId}&history=true`,
].filter(Boolean),
)
})
test("a flow opens, saves and publishes by its issued id", async ({ page }) => {
await page.goto(`/flows/${flowId}`)
await page.waitForSelector(".react-flow__node")
// The tab is named from the document, never from the opaque address.
await expect(page).toHaveTitle(`${key} - Fluksio`)
await page.getByTestId("edit-flow").click()
const panel = page.getByTestId("flow-panel")
await expect(panel.getByTestId("identity-key")).toHaveText(key)
await expect(panel.getByTestId("identity-id")).toHaveText(flowId)
await panel.getByLabel("Flow title").fill("Issued id")
await panel.getByTestId("confirm-rename").click()
await expect
.poll(
async () =>
(await (await api(page, `/flows/${flowId}`)).json()).definition.title,
)
.toBe("Issued id")
await expect(page).toHaveTitle("Issued id - Fluksio")
await page.getByTestId("publish-flow").click()
await expect(page.getByTestId("discard-draft")).toBeHidden()
const detail = await (await api(page, `/flows/${flowId}`)).json()
expect(detail.has_draft).toBe(false)
expect(detail.definition.name).toBe(key)
})
test("its hook URL carries the id, and a call through it shows up live", async ({
page,
}) => {
await page.goto(`/flows/${flowId}?node=hook`)
const url = page.getByTestId("hook-url")
await expect(url).toHaveText(new RegExp(`/hooks/${flowId}/ping$`))
const hook = (await url.textContent()) ?? ""
await page.getByRole("button", { name: "Copy the webhook URL" }).click()
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(hook)
// The route is mounted once the published flow is rebuilt.
await expect
.poll(async () =>
(await page.request.post(hook, { data: { level: 7 } })).status(),
)
.toBe(200)
// The value is named by the key, which is what the canvas matches on.
await expect(page.locator(".react-flow__edgelabel-renderer")).toContainText(
"7",
{ timeout: 15000 },
)
// The dashboard drawn on the canvas opens by its own id.
await page.getByText("Issued level").first().click()
await page.waitForURL(`**/dashboards/${boardId}`)
await expect(page).toHaveTitle("Issued board - Fluksio")
await expect(page.getByTestId("canvas-surface")).toContainText("7")
})
test("a dashboard shows its key and id, and its view opens by the id", async ({
page,
}) => {
await page.goto(`/dashboards/${boardId}?edit=true`)
await page.getByTestId("edit-dashboard").click()
const panel = page.getByTestId("dashboard-panel")
await expect(panel.getByTestId("identity-key")).toHaveText(boardKey)
await expect(panel.getByTestId("identity-id")).toHaveText(boardId)
await page.goto(`/view/${boardId}`)
await expect(page).toHaveTitle("Issued board - Fluksio")
await expect(page.getByText("Issued level")).toBeVisible()
})
test("a run's results dashboard is built and opened by its issued id", async ({
page,
}) => {
await page.goto("/")
await expect
.poll(
async () => (await (await api(page, `/runs/${runId}`)).json()).status,
{ timeout: 30_000 },
)
.toBe("ok")
await page.goto(`/runs/${runId}`)
// Labelled by the flow's key, linked by its id.
await expect(page.getByRole("link", { name: batchKey })).toBeVisible()
await page.getByRole("button", { name: "Open in dashboard" }).click()
await page.getByText(`Build a results dashboard for ${batchKey}`).click()
await page.waitForURL(/\/view\/d_[a-z2-7]{8}\?runs=/)
resultsId = new URL(page.url()).pathname.split("/").pop() ?? ""
const results = await (await api(page, `/dashboards/${resultsId}`)).json()
expect(results.name).toBe(`${batchKey}_results`)
})
+2 -5
View File
@@ -1,5 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { api, apiPage, createFlow, deleteAll } from "./utils/api"
/** /**
* One socket serves the whole shell, and it has to survive the routes under it * One socket serves the whole shell, and it has to survive the routes under it
@@ -18,9 +18,7 @@ test.use({ storageState: "playwright/.auth/user.json" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Live", title: "Live",
nodes: [ nodes: [
@@ -35,7 +33,6 @@ test.beforeAll(async ({ browser }) => {
requires: [{ name: "reading", dtype: "float" }], requires: [{ name: "reading", dtype: "float" }],
}, },
], ],
},
}) })
const detail = await (await api(page, `/flows/${flowName}`)).json() const detail = await (await api(page, `/flows/${flowName}`)).json()
await api(page, `/flows/${flowName}/publish`, { await api(page, `/flows/${flowName}/publish`, {
+11 -11
View File
@@ -1,5 +1,11 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* Every screen at a phone's width, checking the one thing that is easy to * Every screen at a phone's width, checking the one thing that is easy to
@@ -81,9 +87,7 @@ test.beforeAll(async ({ browser }) => {
// A chain and a four-way fan: enough of a graph to lay out, and wider than // A chain and a four-way fan: enough of a graph to lay out, and wider than
// a phone can take abreast, so the wrapping is exercised. // a phone can take abreast, so the wrapping is exercised.
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Mobile", title: "Mobile",
nodes: [ nodes: [
@@ -105,7 +109,6 @@ test.beforeAll(async ({ browser }) => {
})), })),
], ],
version: 1, version: 1,
},
}) })
const saved = await (await api(page, `/flows/${flowName}`)).json() const saved = await (await api(page, `/flows/${flowName}`)).json()
await api(page, `/flows/${flowName}/publish`, { await api(page, `/flows/${flowName}/publish`, {
@@ -113,9 +116,7 @@ test.beforeAll(async ({ browser }) => {
data: { version: saved.definition.version }, data: { version: saved.definition.version },
}) })
await api(page, `/flows/${feedName}`, { await createFlow(page, {
method: "PUT",
data: {
name: feedName, name: feedName,
title: "Feed", title: "Feed",
version: 1, version: 1,
@@ -135,7 +136,6 @@ test.beforeAll(async ({ browser }) => {
], ],
}, },
], ],
},
}) })
const feed = await (await api(page, `/flows/${feedName}?draft=true`)).json() const feed = await (await api(page, `/flows/${feedName}?draft=true`)).json()
await api(page, `/flows/${feedName}/publish`, { await api(page, `/flows/${feedName}/publish`, {
@@ -175,7 +175,7 @@ test.beforeAll(async ({ browser }) => {
}) })
const dashboard = await ( const dashboard = await (
await api(page, `/dashboards/${dashboardName}`, { method: "POST" }) await createDashboard(page, { name: dashboardName })
).json() ).json()
dashboard.widgets = [ dashboard.widgets = [
{ {
@@ -274,7 +274,7 @@ test.beforeAll(async ({ browser }) => {
}) })
const locked = await ( const locked = await (
await api(page, `/dashboards/${lockedName}`, { method: "POST" }) await createDashboard(page, { name: lockedName })
).json() ).json()
locked.settings = { ...(locked.settings ?? {}), locked: { value: true } } locked.settings = { ...(locked.settings ?? {}), locked: { value: true } }
locked.widgets = [ locked.widgets = [
+9 -6
View File
@@ -1,5 +1,11 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* A panel carrying more than one dashboard draws the way between them. * A panel carrying more than one dashboard draws the way between them.
@@ -22,9 +28,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Panel", title: "Panel",
version: 1, version: 1,
@@ -38,7 +42,6 @@ test.beforeAll(async ({ browser }) => {
], ],
}, },
], ],
},
}) })
const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json() const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json()
await api(page, `/flows/${flowName}/publish`, { await api(page, `/flows/${flowName}/publish`, {
@@ -51,7 +54,7 @@ test.beforeAll(async ({ browser }) => {
}) })
for (const name of [first, second]) { for (const name of [first, second]) {
await api(page, `/dashboards/${name}`, { method: "POST" }) await createDashboard(page, { name: name })
const doc = await (await api(page, `/dashboards/${name}?draft=true`)).json() const doc = await (await api(page, `/dashboards/${name}?draft=true`)).json()
doc.settings = { look: { value: "glass" } } doc.settings = { look: { value: "glass" } }
doc.widgets = [ doc.widgets = [
+3 -7
View File
@@ -1,5 +1,5 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { api, apiPage, createDashboard, deleteAll } from "./utils/api"
/** /**
* An editor save is a rewrite of the whole document, not a patch of what moved. * An editor save is a rewrite of the whole document, not a patch of what moved.
@@ -48,11 +48,8 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
// Version 0 creates: a first draft is what a save of a name nobody has used // Created as a draft, which is what the editor reads.
// yet means, and the editor reads the draft. const made = await createDashboard(page, {
const made = await api(page, `/dashboards/${dashboardName}`, {
method: "PUT",
data: {
name: dashboardName, name: dashboardName,
title: "Persistence", title: "Persistence",
icon: "layout-dashboard", icon: "layout-dashboard",
@@ -62,7 +59,6 @@ test.beforeAll(async ({ browser }) => {
version: 0, version: 0,
widgets: [MOVED, KEPT], widgets: [MOVED, KEPT],
settings: SETTINGS, settings: SETTINGS,
},
}) })
if (!made.ok()) if (!made.ok())
throw new Error(`dashboard PUT ${made.status()}: ${await made.text()}`) throw new Error(`dashboard PUT ${made.status()}: ${await made.text()}`)
+9 -9
View File
@@ -1,6 +1,12 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* A round dashboard's ring publishes once a turn settles, not per notch. * A round dashboard's ring publishes once a turn settles, not per notch.
@@ -21,9 +27,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
// One node that only declares: a publish lands without waking a run. // One node that only declares: a publish lands without waking a run.
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Ring", title: "Ring",
version: 1, version: 1,
@@ -34,7 +38,6 @@ test.beforeAll(async ({ browser }) => {
provides: [{ name: "level", dtype: "float" }], provides: [{ name: "level", dtype: "float" }],
}, },
], ],
},
}) })
const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json() const flow = await (await api(page, `/flows/${flowName}?draft=true`)).json()
await api(page, `/flows/${flowName}/publish`, { await api(page, `/flows/${flowName}/publish`, {
@@ -43,9 +46,7 @@ test.beforeAll(async ({ browser }) => {
}) })
await api(page, `/dashboards/${dashboard}`, { method: "DELETE" }) await api(page, `/dashboards/${dashboard}`, { method: "DELETE" })
const made = await api(page, `/dashboards/${dashboard}`, { const made = await createDashboard(page, {
method: "PUT",
data: {
name: dashboard, name: dashboard,
title: "Ring", title: "Ring",
version: 0, version: 0,
@@ -66,7 +67,6 @@ test.beforeAll(async ({ browser }) => {
config: { content: "The second face" }, config: { content: "The second face" },
}, },
], ],
},
}) })
if (!made.ok()) if (!made.ok())
throw new Error(`dashboard PUT ${made.status()}: ${await made.text()}`) throw new Error(`dashboard PUT ${made.status()}: ${await made.text()}`)
+2 -5
View File
@@ -1,5 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { api, apiPage, createFlow, deleteAll } from "./utils/api"
/** /**
* What the runs screen can do to a run, rather than what it can show about one. * What the runs screen can do to a run, rather than what it can show about one.
@@ -28,9 +28,7 @@ test.afterAll(async ({ browser }) => {
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Runs under test", title: "Runs under test",
// `rate` is declared and never passed, which is what puts its declared // `rate` is declared and never passed, which is what puts its declared
@@ -50,7 +48,6 @@ test.beforeAll(async ({ browser }) => {
], ],
}, },
], ],
},
}) })
await api(page, `/flows/${flowName}/nodes/train/source`, { await api(page, `/flows/${flowName}/nodes/train/source`, {
method: "PUT", method: "PUT",
+2 -5
View File
@@ -1,5 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { api, apiPage, createFlow, deleteAll } from "./utils/api"
/** /**
* Flows can be taken off the engine and put back, and what a node prints — or * Flows can be taken off the engine and put back, and what a node prints — or
@@ -29,9 +29,7 @@ test.afterAll(async ({ browser }) => {
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Runtime", title: "Runtime",
nodes: [ nodes: [
@@ -46,7 +44,6 @@ test.beforeAll(async ({ browser }) => {
requires: [{ name: "reading", dtype: "float" }], requires: [{ name: "reading", dtype: "float" }],
}, },
], ],
},
}) })
await api(page, `/flows/${flowName}/nodes/sensor/source`, { await api(page, `/flows/${flowName}/nodes/sensor/source`, {
method: "PUT", method: "PUT",
+2 -5
View File
@@ -1,5 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { apiPage, createFlow, deleteAll } from "./utils/api"
/** /**
* The global search: the only way to reach a node without knowing its flow. * The global search: the only way to reach a node without knowing its flow.
@@ -16,9 +16,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Searchable flow", title: "Searchable flow",
nodes: [ nodes: [
@@ -30,7 +28,6 @@ test.beforeAll(async ({ browser }) => {
}, },
], ],
inputs: [{ spec: { name: "findme_input", dtype: "float" } }], inputs: [{ spec: { name: "findme_input", dtype: "float" } }],
},
}) })
await page.close() await page.close()
}) })
+11 -11
View File
@@ -1,6 +1,12 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* A slider publishes what a *drag* leaves it on, not only what a tap picks. * A slider publishes what a *drag* leaves it on, not only what a tap picks.
@@ -20,9 +26,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
const madeFlow = await api(page, `/flows/${flowName}`, { const madeFlow = await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Slider drag", title: "Slider drag",
version: 1, version: 1,
@@ -36,21 +40,18 @@ test.beforeAll(async ({ browser }) => {
}, },
], ],
inputs: [{ spec: { name: "level", dtype: "float" }, initial: 0 }], inputs: [{ spec: { name: "level", dtype: "float" }, initial: 0 }],
},
}) })
if (!madeFlow.ok()) if (!madeFlow.ok())
throw new Error(`flow PUT ${madeFlow.status()}: ${await madeFlow.text()}`) throw new Error(`flow POST ${madeFlow.status()}: ${await madeFlow.text()}`)
await api(page, `/flows/${flowName}/nodes/level/source`, { await api(page, `/flows/${flowName}/nodes/level/source`, {
method: "PUT", method: "PUT",
data: { code: "def process(level=0.0):\n return {'echo': level}\n" }, data: { code: "def process(level=0.0):\n return {'echo': level}\n" },
}) })
// A leftover from a run that failed before its teardown would answer the // A leftover from a run that failed before its teardown would answer the
// create with a version conflict. // create with a conflict.
await api(page, `/dashboards/${dashboard}`, { method: "DELETE" }) await api(page, `/dashboards/${dashboard}`, { method: "DELETE" })
const madeBoard = await api(page, `/dashboards/${dashboard}`, { const madeBoard = await createDashboard(page, {
method: "PUT",
data: {
name: dashboard, name: dashboard,
title: "Slider drag", title: "Slider drag",
version: 0, version: 0,
@@ -69,7 +70,6 @@ test.beforeAll(async ({ browser }) => {
}, },
}, },
], ],
},
}) })
if (!madeBoard.ok()) if (!madeBoard.ok())
throw new Error( throw new Error(
+47
View File
@@ -32,6 +32,53 @@ export async function apiPage(browser: Browser) {
return page return page
} }
/**
* Create a flow the way the app does, with a POST, under its key as a pinned
* id, so a spec keeps addressing it by the name it chose. The suite signs in
* as a superuser, who may pin. The answer is the request's own.
*/
export function createFlow(
page: Page,
doc: { name: string; [field: string]: unknown },
) {
return api(page, "/flows/", {
method: "POST",
data: { id: doc.name, ...doc },
})
}
/**
* The same for a dashboard. Creating one takes only its key and title, so the
* rest of `doc` is saved over the new draft, and the answer is that save's.
*/
export async function createDashboard(
page: Page,
doc: { name: string; title?: string; [field: string]: unknown },
) {
const made = await api(page, "/dashboards/", {
method: "POST",
data: { id: doc.name, name: doc.name, title: doc.title },
})
const rest = Object.keys(doc).filter(
(key) => key !== "name" && key !== "title",
)
if (!made.ok() || rest.length === 0) return made
const { version } = await made.json()
return api(page, `/dashboards/${doc.name}`, {
method: "PUT",
data: { ...doc, version },
})
}
/**
* The id the server issued a flow just created in the app, read off the
* editor it opened: an opaque `f_` and eight characters, never the key.
*/
export async function openedFlowId(page: Page) {
await page.waitForURL(/\/flows\/f_[a-z2-7]{8}$/)
return new URL(page.url()).pathname.split("/").pop() ?? ""
}
/** Delete the given API paths, whether or not they are still there. */ /** Delete the given API paths, whether or not they are still there. */
export async function deleteAll(browser: Browser, paths: string[]) { export async function deleteAll(browser: Browser, paths: string[]) {
const page = await apiPage(browser) const page = await apiPage(browser)
+2 -5
View File
@@ -1,5 +1,5 @@
import { expect, test } from "@playwright/test" import { expect, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import { api, apiPage, createFlow, deleteAll } from "./utils/api"
/** /**
* What a message carrying a dictionary looks like in a panel four hundred * What a message carrying a dictionary looks like in a panel four hundred
@@ -21,9 +21,7 @@ test.describe.configure({ mode: "serial" })
test.beforeAll(async ({ browser }) => { test.beforeAll(async ({ browser }) => {
const page = await apiPage(browser) const page = await apiPage(browser)
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Values", title: "Values",
version: 1, version: 1,
@@ -37,7 +35,6 @@ test.beforeAll(async ({ browser }) => {
], ],
}, },
], ],
},
}) })
// Saving writes a draft and moves the version on, so publish what is // Saving writes a draft and moves the version on, so publish what is
// actually there rather than what it was a moment ago. // actually there rather than what it was a moment ago.
+11 -10
View File
@@ -1,5 +1,11 @@
import { expect, type Page, test } from "@playwright/test" import { expect, type Page, test } from "@playwright/test"
import { api, apiPage, deleteAll } from "./utils/api" import {
api,
apiPage,
createDashboard,
createFlow,
deleteAll,
} from "./utils/api"
/** /**
* The wall-panel widgets, on the page a panel actually opens. * The wall-panel widgets, on the page a panel actually opens.
@@ -39,9 +45,7 @@ test.beforeAll(async ({ browser }) => {
// One node that only declares: nothing consumes these, so publishing a value // One node that only declares: nothing consumes these, so publishing a value
// fills the panel without waking an engine run. // fills the panel without waking an engine run.
await api(page, `/flows/${flowName}`, { await createFlow(page, {
method: "PUT",
data: {
name: flowName, name: flowName,
title: "Widgets", title: "Widgets",
version: 1, version: 1,
@@ -63,7 +67,6 @@ test.beforeAll(async ({ browser }) => {
], ],
}, },
], ],
},
}) })
// Saving writes a draft and moves the version on, so publish what is // Saving writes a draft and moves the version on, so publish what is
// actually there rather than what it was a moment ago. // actually there rather than what it was a moment ago.
@@ -92,7 +95,7 @@ test.beforeAll(async ({ browser }) => {
]) ])
const dashboard = await ( const dashboard = await (
await api(page, `/dashboards/${dashboardName}`, { method: "POST" }) await createDashboard(page, { name: dashboardName })
).json() ).json()
// Two rows taller than the default panel: the tiles below already fill it, // Two rows taller than the default panel: the tiles below already fill it,
// and a widget past the last row is clipped rather than drawn. // and a widget past the last row is clipped rather than drawn.
@@ -236,9 +239,7 @@ test.beforeAll(async ({ browser }) => {
data: { version: draft.version }, data: { version: draft.version },
}) })
const stack = await ( const stack = await (await createDashboard(page, { name: stackName })).json()
await api(page, `/dashboards/${stackName}`, { method: "POST" })
).json()
stack.widgets = [ stack.widgets = [
{ {
id: "split", id: "split",
@@ -284,7 +285,7 @@ test.beforeAll(async ({ browser }) => {
}) })
const locked = await ( const locked = await (
await api(page, `/dashboards/${lockedName}`, { method: "POST" }) await createDashboard(page, { name: lockedName })
).json() ).json()
locked.settings = { ...(locked.settings ?? {}), locked: { value: true } } locked.settings = { ...(locked.settings ?? {}), locked: { value: true } }
locked.widgets = [ locked.widgets = [